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
//! Background test-runner worker. Mirrors [`crate::app::git_worker`]: a thread
//! owns the channels, runs `cargo test` off the render loop, streams parsed
//! cases plus raw output, and the app drains the results into the panel each
//! tick. Requests: `RunAll` (execute) and `Discover` (`cargo test -- --list`,
//! populate the tree without running); per-test granularity and other
//! ecosystems come in later milestones.

use std::cell::RefCell;
use std::collections::BTreeMap;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc::{Receiver, Sender};
use std::sync::{Arc, Mutex};

use super::model::{Activity, TestCase, TestStatus};
use super::parse::{
    parse_jest_json, parse_list_line, parse_pytest_collect_line, parse_pytest_line,
    parse_test_line, parse_vitest_list_json, parse_vitest_list_line, parse_vitest_tap_line,
};
use super::regex_escape;
use crate::output::{self, OutputLevel};
use crate::widgets::testing::TestingPanel;

/// Which built-in run mechanism a workspace's tests use. Which one a given
/// root resolves to is manifest data ([`super::registry`]), not code.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Runner {
    Cargo,
    Pytest,
    Vitest,
    Jest,
    Go,
    Codeql,
}

/// Detect the workspace's test runner from the enabled extensions'
/// `[[test_runners]]` declarations. `None` means no recognised test project,
/// so the Testing view stays empty instead of shelling a tool that would error.
pub fn runner_for(extensions_dir: &Path, root: &Path) -> Option<Runner> {
    super::registry::runner_for(extensions_dir, root)
}

/// Every runner that claims `root` (#1408): a folder with two languages'
/// tests has a runner for each, and the Testing view lists both.
pub fn runners_for(extensions_dir: &Path, root: &Path) -> Vec<Runner> {
    super::registry::runners_for(extensions_dir, root)
}

/// The runners whose tests a file of this kind holds, by its extension.
fn runners_of_file(file: &Path) -> &'static [Runner] {
    let ext = file.extension().and_then(|e| e.to_str()).unwrap_or("");
    match ext {
        "rs" => &[Runner::Cargo],
        "py" => &[Runner::Pytest],
        "go" => &[Runner::Go],
        "js" | "jsx" | "mjs" | "cjs" | "ts" | "tsx" | "mts" | "cts" => {
            &[Runner::Vitest, Runner::Jest]
        }
        "ql" | "qlref" | "expected" => &[Runner::Codeql],
        _ => &[],
    }
}

/// The runner of `runners` that runs the tests in `file` (#1408): the one
/// for the file's language, else the folder's first. A pytest file in a
/// maturin crate is pytest's, not Cargo's.
pub fn runner_for_file(runners: &[Runner], file: Option<&Path>) -> Option<Runner> {
    file.map(runners_of_file)
        .unwrap_or(&[])
        .iter()
        .copied()
        .find(|r| runners.contains(r))
        .or_else(|| runners.first().copied())
}

/// The runner a run of `name` goes to (#1408): the file's language when the
/// run came from a file, else the runner that listed `name` (or, for a
/// suite, a test under it), else the folder's first. Where the file's
/// language has two runners (Vitest and Jest), the one that listed `name`
/// or the file's tests decides.
fn choose_runner(
    runners: &[Runner],
    owners: &BTreeMap<String, Runner>,
    name: &str,
    file: Option<&Path>,
) -> Option<Runner> {
    let of_file: Vec<Runner> = file
        .map(runners_of_file)
        .unwrap_or(&[])
        .iter()
        .copied()
        .filter(|r| runners.contains(r))
        .collect();
    // A suite owns what sits under it at the `::` separator, not every
    // name that starts with its text: Rust's `tests` is not pytest's
    // `tests/test_x.py`.
    let suite = super::suite_pattern(name);
    let by_name = owners
        .get(name)
        .or_else(|| {
            owners
                .iter()
                .find(|(listed, _)| listed.starts_with(&suite))
                .map(|(_, r)| r)
        })
        .copied()
        .filter(|r| runners.contains(r));
    let by_file = match of_file.as_slice() {
        [] => None,
        [only] => Some(*only),
        several => by_name
            .filter(|r| several.contains(r))
            .or_else(|| file.and_then(|f| file_owner(owners, f, several)))
            .or_else(|| several.first().copied()),
    };
    by_file.or(by_name).or_else(|| runners.first().copied())
}

/// The runner among `candidates` that listed a test of `file`: JS test
/// names start with the file's path relative to the root.
fn file_owner(
    owners: &BTreeMap<String, Runner>,
    file: &Path,
    candidates: &[Runner],
) -> Option<Runner> {
    owners
        .iter()
        .find(|(listed, r)| {
            candidates.contains(r)
                && listed
                    .split_once("::")
                    .is_some_and(|(path, _)| !path.is_empty() && file.ends_with(path))
        })
        .map(|(_, r)| *r)
}

pub enum TestRequest {
    RunAll,
    /// Run a single test by its exact name (click-to-run from the tree).
    RunOne(String),
    /// Run every test whose name contains the string (run-at-cursor by
    /// function name). cargo's name filter is a substring match. The file
    /// the run came from, if any, picks the runner (#1408).
    RunFilter(String, Option<PathBuf>),
    /// Run each of these tests by its exact name, one after another, as one
    /// run (#1535: Rerun Failed Tests). Ends once, failed if any failed.
    RunMany(Vec<String>),
    /// Run a whole suite by its unanchored name (a header click). The cargo
    /// arm anchors it with [`super::suite_pattern`] so `parse` cannot sweep
    /// `parse_utils::b`; pytest gets it positionally as a node-ID prefix.
    RunSuite(String),
    /// Run with the runner's coverage tool on (#263): everything, or only
    /// the tests `scope` names.
    RunCoverage(Option<CoverageScope>),
    /// List the tests without running them. `quiet` is the Testing view's
    /// own discover (#1841): the worker, not the UI thread, finds the
    /// runner, which can mean walking the tree for CodeQL test packs. It
    /// answers [`TestResponse::QuietDiscovery`] first, and a root no runner
    /// claims ends there, without a refusal the status bar reports.
    Discover {
        quiet: bool,
    },
    /// Rebind the worker's working directory (Explorer re-root). Without it the
    /// worker keeps shelling cargo in the launch dir captured at spawn, so after
    /// a Make Root into a child repo `cargo test -- --list` errors with "could
    /// not find Cargo.toml" and the tree never populates.
    SetRoot(PathBuf),
    /// Rebind the `codeql` program CodeQL test runs shell: the app's own, so
    /// the Testing view and the CodeQL side bar run the same CLI (and a test
    /// can stand a script in for it).
    SetCodeqlProgram(PathBuf),
    /// Rebind the folder of the user's added extensions the runners are read
    /// from: the app's own, so a test can add CodeQL, whose runner comes with
    /// the CodeQL extension (#1842), without touching the real one.
    SetExtensionsDir(PathBuf),
}

pub enum TestResponse {
    Started(Activity),
    Case(TestCase),
    /// A cargo build-status line (e.g. "Compiling ratatui v0.29") to show as
    /// live progress while the test binary compiles, so a multi-minute
    /// discovery doesn't look frozen behind a static "Discovering tests".
    Progress(String),
    /// `ok` is the runner's exit success, for a discovery as for a run: a
    /// listing that errors (a collection error, a build failure) is a failed
    /// discovery, not an empty project (#845). `None` when nothing ran (a
    /// coverage run refused for want of its tool).
    Finished {
        ok: Option<bool>,
    },
    /// The queued request found no enabled runner claiming the root (it was
    /// disabled between the app's entry-point check and the worker draining
    /// the queue). Distinct from `Finished` so the panel can roll back the
    /// Running marks the `start_*` call painted instead of stranding them,
    /// and the app can say why nothing ran.
    Refused,
    /// The worker reached a quiet discovery (#1841). Sent before anything
    /// else it does, so the drain can tell the request the Testing view
    /// queued from any other's answers; when no runner claims the root,
    /// nothing follows it.
    QuietDiscovery,
    /// A coverage run's report, or why there is none. Sent before its
    /// `Finished`.
    Coverage(Result<super::coverage::Coverage, CoverageError>),
}

/// Why a coverage run produced no report.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CoverageError {
    /// The runner's coverage tool is not installed: its name and the
    /// command that installs it.
    Missing { tool: &'static str, install: String },
    /// The run ended without writing a report (it failed to build, or
    /// the tool errored).
    NoReport,
    /// The runner has no coverage tool croft can drive: its name.
    Unsupported { runner: &'static str },
}

/// What a cancel (#1534) needs to reach the runner the worker thread is
/// blocked on: the process group of the child it is streaming, and how
/// many requests the app has cancelled. Requests are counted on both sides
/// in channel order, so a cancel covers the request in flight and any the
/// worker has not picked up yet, and never a later one.
#[derive(Clone, Default)]
pub struct RunControl {
    /// The streaming child's pid, which is its process group (it is
    /// spawned as a group leader).
    running: Arc<Mutex<Option<i32>>>,
    /// Requests numbered up to this one are cancelled.
    cancelled_upto: Arc<AtomicU64>,
}

impl RunControl {
    /// Cancel every request numbered up to `upto`: kill the running child's
    /// whole process group (the runner, pytest-xdist workers, a `cargo
    /// test` binary), and keep any further child of those requests from
    /// starting.
    fn cancel(&self, upto: u64) {
        self.cancelled_upto.fetch_max(upto, Ordering::SeqCst);
        if let Some(pgid) = *self.running.lock().unwrap() {
            // SAFETY: `pgid` is the group of a child this worker spawned as
            // its own group leader, so only the test run is signalled.
            unsafe {
                libc::killpg(pgid, libc::SIGKILL);
            }
        }
    }

    fn is_cancelled(&self, request: u64) -> bool {
        request <= self.cancelled_upto.load(Ordering::SeqCst)
    }

    /// Spawn `cmd` as the leader of a new process group and record it, or
    /// refuse with `None` when `request` was cancelled. Checked and
    /// recorded under the lock, so a cancel either sees the pid or the
    /// spawn sees the cancel. A runner that is "Text file busy" for a
    /// moment, just installed or a test's freshly written stand-in, is
    /// waited out rather than reported as a failed run. The lock is let go
    /// between tries, so a cancel from the UI never waits on that, and the
    /// next try sees it.
    fn spawn(&self, request: u64, cmd: &mut Command) -> Option<std::io::Result<Child>> {
        use std::os::unix::process::CommandExt;
        cmd.process_group(0);
        crate::review_ops::retry_while_busy(
            || {
                let mut running = self.running.lock().unwrap();
                if self.is_cancelled(request) {
                    return None;
                }
                let child = cmd.spawn();
                if let Ok(c) = &child {
                    *running = i32::try_from(c.id()).ok();
                }
                Some(child)
            },
            |r| matches!(r, Some(Err(e)) if crate::review_ops::text_file_busy(e)),
        )
    }

    fn finished(&self) {
        *self.running.lock().unwrap() = None;
    }
}

pub struct TestWorker {
    request_tx: Sender<TestRequest>,
    /// Reaches the runner the worker thread is blocked on (#1534).
    control: RunControl,
    /// Requests sent so far: the worker numbers them in the same order.
    sent: u64,
    /// A cancel is waiting for its run's end, which the drain reports as
    /// cancelled rather than as a verdict.
    cancel_pending: bool,
    /// Responses arrive tagged with the epoch of the root they ran under; the
    /// drain drops tags older than [`Self::expected_epoch`] so a run still
    /// streaming when the Explorer re-roots can't pollute the new project's
    /// tree (same idea as the commit graph's root-tagged drain).
    response_rx: Receiver<(u64, TestResponse)>,
    /// A quiet discovery is queued and has not started yet (#1841). Until
    /// the worker reaches it the panel is not busy, so without this every
    /// reopen of the Testing view would queue another.
    discover_queued: bool,
    /// Bumped on every [`Self::set_root`], in lockstep with the loop's own
    /// counter: the request channel is FIFO, so both sides count the same
    /// `SetRoot`s in the same order.
    expected_epoch: u64,
    // Mirror of the root the loop last saw, for tests that assert the re-root
    // wiring. The loop owns its own copy via `SetRoot`; prod never reads this.
    #[cfg(test)]
    root: PathBuf,
}

impl TestWorker {
    pub fn spawn(workspace_root: PathBuf) -> Self {
        let (request_tx, request_rx) = std::sync::mpsc::channel::<TestRequest>();
        let (response_tx, response_rx) = std::sync::mpsc::channel::<(u64, TestResponse)>();
        #[cfg(test)]
        let root = workspace_root.clone();
        let control = RunControl::default();
        let worker_control = control.clone();
        std::thread::spawn(move || {
            crate::startup_gate::wait();
            worker_loop(workspace_root, request_rx, response_tx, &worker_control)
        });
        Self {
            request_tx,
            control,
            sent: 0,
            cancel_pending: false,
            response_rx,
            discover_queued: false,
            expected_epoch: 0,
            #[cfg(test)]
            root,
        }
    }

    /// Build a worker around hand-made channels (no thread) so tests can
    /// inject tagged responses straight into the drain.
    #[cfg(test)]
    fn for_test() -> (Self, Sender<(u64, TestResponse)>) {
        let (request_tx, _request_rx) = std::sync::mpsc::channel::<TestRequest>();
        let (response_tx, response_rx) = std::sync::mpsc::channel::<(u64, TestResponse)>();
        (
            Self {
                request_tx,
                control: RunControl::default(),
                sent: 0,
                cancel_pending: false,
                response_rx,
                discover_queued: false,
                expected_epoch: 0,
                root: PathBuf::new(),
            },
            response_tx,
        )
    }

    /// Queue `req`, numbered as the worker will number it.
    fn send(&mut self, req: TestRequest) {
        self.sent += 1;
        let _ = self.request_tx.send(req);
    }

    pub fn run_coverage(&mut self) {
        self.send(TestRequest::RunCoverage(None));
    }

    /// Run only the tests `scope` names with coverage on (#263).
    pub fn run_coverage_scoped(&mut self, scope: CoverageScope) {
        self.send(TestRequest::RunCoverage(Some(scope)));
    }

    pub fn run_all(&mut self) {
        self.send(TestRequest::RunAll);
    }

    pub fn run_one(&mut self, name: String) {
        self.send(TestRequest::RunOne(name));
    }

    pub fn run_many(&self, names: Vec<String>) {
        let _ = self.request_tx.send(TestRequest::RunMany(names));
    }

    /// Run the tests matching `pattern`, with the runner for `file`'s
    /// language when the run came from one (#1408).
    pub fn run_filter(&mut self, pattern: String, file: Option<PathBuf>) {
        self.send(TestRequest::RunFilter(pattern, file));
    }

    pub fn run_suite(&mut self, suite: String) {
        self.send(TestRequest::RunSuite(suite));
    }

    pub fn discover(&mut self) {
        self.send(TestRequest::Discover { quiet: false });
    }

    /// Discover from the Testing view (#1841): queued without looking for a
    /// runner first, so opening the view never waits on that search. The
    /// worker finds the runner and stays silent when there is none.
    pub fn discover_quietly(&mut self) {
        self.discover_queued = true;
        self.send(TestRequest::Discover { quiet: true });
    }

    /// A quiet discovery is queued and has not started yet.
    pub fn discover_queued(&self) -> bool {
        self.discover_queued
    }

    /// How many requests have been queued, for tests that count them.
    #[cfg(test)]
    pub fn requests_sent(&self) -> u64 {
        self.sent
    }

    pub fn set_codeql_program(&mut self, program: PathBuf) {
        self.send(TestRequest::SetCodeqlProgram(program));
    }

    pub fn set_extensions_dir(&mut self, dir: PathBuf) {
        self.send(TestRequest::SetExtensionsDir(dir));
    }

    /// Stop the run or discovery in flight (#1534): its runner's process
    /// group is killed, and its end reaches the panel as cancelled. Also
    /// called on quit, so no runner outlives croft.
    pub fn cancel(&mut self) {
        self.control.cancel(self.sent);
        self.cancel_pending = true;
    }

    /// Rebind the worker to a new workspace root after an Explorer re-root.
    /// Everything still streaming for the old root carries the old epoch and
    /// is dropped by [`Self::drain`].
    pub fn set_root(&mut self, root: PathBuf) {
        #[cfg(test)]
        {
            self.root = root.clone();
        }
        self.expected_epoch += 1;
        // A discovery queued for the old root reports under the old epoch,
        // which the drain drops: nothing would ever clear it.
        self.discover_queued = false;
        // Every request a pending cancel covers was sent before this
        // re-root, so its end carries the old epoch and is dropped below:
        // the cancel must not outlive it and swallow the new root's next
        // verdict.
        self.cancel_pending = false;
        self.send(TestRequest::SetRoot(root));
    }

    #[cfg(test)]
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Drain streamed results into the panel. Returns true iff anything was
    /// applied, so the main loop only redraws on a real update. Responses
    /// tagged with an epoch older than the last `set_root` belong to the
    /// previous project and are dropped.
    pub fn drain(&mut self, panel: &mut TestingPanel) -> bool {
        let mut changed = false;
        while let Ok((epoch, resp)) = self.response_rx.try_recv() {
            if epoch != self.expected_epoch {
                continue;
            }
            match resp {
                TestResponse::QuietDiscovery => {
                    self.discover_queued = false;
                    continue;
                }
                TestResponse::Started(activity) => panel.on_busy_started(activity),
                TestResponse::Case(case) => panel.apply_case(case),
                TestResponse::Progress(line) => panel.set_progress(line),
                TestResponse::Finished { .. } | TestResponse::Refused
                    if std::mem::take(&mut self.cancel_pending) =>
                {
                    panel.on_cancelled()
                }
                TestResponse::Finished { ok } => panel.on_finished(ok),
                TestResponse::Refused => panel.on_refused(),
                // A cancelled coverage run's killed child wrote no report:
                // that error is not news, and would overwrite the cancel.
                TestResponse::Coverage(_) if self.cancel_pending => continue,
                TestResponse::Coverage(result) => panel.on_coverage(result),
            }
            changed = true;
        }
        changed
    }
}

/// A response sender bound to the epoch of the request it serves, so every
/// line a handler streams is tagged without threading the counter through.
struct EpochTx<'a> {
    tx: &'a Sender<(u64, TestResponse)>,
    epoch: u64,
    /// The `codeql` program a CodeQL test run shells (see
    /// [`TestRequest::SetCodeqlProgram`]); carried here because every
    /// handler already takes the sender.
    codeql: &'a Path,
    /// The user's added extensions, whose runners count alongside the
    /// bundled ones (see [`TestRequest::SetExtensionsDir`]).
    extensions: &'a Path,
    /// Where the streaming child is recorded for a cancel (#1534), and the
    /// number of the request being served.
    control: &'a RunControl,
    request: u64,
    /// Which runner listed or ran each test (#1408), so a later run of one
    /// goes back to it; `tag` is the runner whose cases this sender
    /// carries.
    owners: Option<&'a RefCell<BTreeMap<String, Runner>>>,
    tag: Option<Runner>,
}

impl<'a> EpochTx<'a> {
    fn send(&self, resp: TestResponse) {
        if let (Some(owners), Some(runner), TestResponse::Case(case)) =
            (self.owners, self.tag, &resp)
        {
            owners.borrow_mut().insert(case.name.clone(), runner);
        }
        let _ = self.tx.send((self.epoch, resp));
    }

    /// This sender, recording what it carries as `runner`'s.
    fn tagged(&self, runner: Runner) -> EpochTx<'a> {
        EpochTx {
            tag: Some(runner),
            ..*self
        }
    }

    /// The runner a run of `name` goes to, among `runners`.
    fn choose(&self, runners: &[Runner], name: &str, file: Option<&Path>) -> Option<Runner> {
        let empty = BTreeMap::new();
        match self.owners {
            Some(owners) => choose_runner(runners, &owners.borrow(), name, file),
            None => choose_runner(runners, &empty, name, file),
        }
    }

    /// An owned clone for the stderr tee thread.
    fn to_owned(&self) -> (Sender<(u64, TestResponse)>, u64) {
        (self.tx.clone(), self.epoch)
    }
}

fn worker_loop(
    mut root: PathBuf,
    rx: Receiver<TestRequest>,
    tx: Sender<(u64, TestResponse)>,
    control: &RunControl,
) {
    let mut epoch = 0u64;
    // Found on PATH, as the CodeQL side bar finds it, until the app says
    // otherwise.
    let mut codeql = PathBuf::from("codeql");
    let mut extensions = crate::lsp::manifest::user_extensions_dir();
    let mut request = 0u64;
    let owners = RefCell::new(BTreeMap::new());
    while let Ok(req) = rx.recv() {
        request += 1;
        let etx = EpochTx {
            tx: &tx,
            epoch,
            codeql: &codeql,
            extensions: &extensions,
            control,
            request,
            owners: Some(&owners),
            tag: None,
        };
        match req {
            TestRequest::RunAll => run_all(&root, &etx),
            TestRequest::RunCoverage(scope) => run_coverage(&root, &etx, scope.as_ref()),
            TestRequest::RunOne(name) => run_one(&root, &etx, &name),
            TestRequest::RunMany(names) => run_many(&root, &etx, &names),
            TestRequest::RunFilter(pattern, file) => {
                run_filter_in(&root, &etx, &pattern, false, file.as_deref())
            }
            TestRequest::RunSuite(suite) => run_filter(&root, &etx, &suite, true),
            TestRequest::Discover { quiet } => discover(&root, &etx, quiet),
            TestRequest::SetRoot(p) => {
                root = p;
                epoch += 1;
                owners.borrow_mut().clear();
            }
            TestRequest::SetCodeqlProgram(p) => codeql = p,
            TestRequest::SetExtensionsDir(p) => extensions = p,
        }
    }
}

/// `args` for a cargo test or coverage run at `root`, with `--workspace`
/// after the subcommand when the root manifest has a `[workspace]` table
/// (#1508). At the root of a workspace that is also a package, plain `cargo
/// test` builds and runs only that package, so the members' tests were
/// never listed or run; for a virtual manifest the flag changes nothing.
fn workspace_args<'a>(root: &Path, args: &[&'a str]) -> Vec<&'a str> {
    let mut out = args.to_vec();
    let subcommand = matches!(args.first(), Some(&"test" | &"llvm-cov"));
    if subcommand && !args.contains(&"--version") && declares_workspace(root) {
        out.insert(1, "--workspace");
    }
    out
}

/// Whether `root/Cargo.toml` has a `[workspace]` table.
fn declares_workspace(root: &Path) -> bool {
    std::fs::read_to_string(root.join("Cargo.toml"))
        .ok()
        .and_then(|text| text.parse::<toml::Table>().ok())
        .is_some_and(|manifest| manifest.contains_key("workspace"))
}

/// `cargo <args>` rooted at the workspace, with piped stdio. cargo is resolved
/// by absolute path (GUI-launched croft inherits a stripped PATH) and its own
/// dir is prepended to the child PATH so the rustup shim finds its sibling
/// `rustc` (same fix as the dependencies fetcher).
fn cargo_cmd(root: &Path, args: &[&str]) -> Command {
    let cargo = crate::widgets::dependencies::cargo_binary();
    let mut cmd = Command::new(&cargo);
    cmd.args(workspace_args(root, args))
        .current_dir(root)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    if let Some(dir) = cargo.parent()
        && let Some(path_var) = std::env::var_os("PATH")
    {
        let mut paths = vec![dir.to_path_buf()];
        paths.extend(std::env::split_paths(&path_var));
        if let Ok(joined) = std::env::join_paths(paths) {
            cmd.env("PATH", joined);
        }
    }
    cmd
}

/// How to launch pytest for a workspace: a program, and the arguments that
/// come before pytest's own. A project venv (`.venv/`, then `venv/`) with
/// pytest installed (its `pytest` script, or a python that imports it) wins, run as `<venv>/bin/python -m pytest` the way VS
/// Code runs it: `-m` puts the root on `sys.path`, so tests import the
/// project's own top-level modules, which the `pytest` script alone does
/// not (#845). Without one, `python3 -m pytest` when that `python3` can
/// import pytest: a `pytest` script on `PATH` may belong to another
/// interpreter (a uv tool's), which cannot import the project's
/// dependencies. Then the `pytest` script; with no script anywhere,
/// `python3 -m pytest`, which at least fails with a reason instead of a
/// spawn error.
fn pytest_launch(root: &Path) -> (PathBuf, &'static [&'static str]) {
    pytest_launch_on(root, std::env::var_os("PATH").as_deref())
}

/// [`pytest_launch`] against the given `PATH` value.
fn pytest_launch_on(
    root: &Path,
    path_var: Option<&std::ffi::OsStr>,
) -> (PathBuf, &'static [&'static str]) {
    const MODULE: &[&str] = &["-m", "pytest"];
    for venv in [".venv", "venv"] {
        let bin = root.join(venv).join("bin");
        let python = bin.join("python");
        // `-m pytest` needs the module: the console script says it is
        // installed without a process, and without the script the venv's
        // python is asked.
        if python.is_file() && (bin.join("pytest").is_file() || python_has_pytest(root, &python)) {
            return (python, MODULE);
        }
    }
    let python3 = python3_program(path_var);
    if python_has_pytest(root, &python3) {
        return (python3, MODULE);
    }
    match pytest_script(path_var) {
        Some(script) => (script, &[]),
        None => (python3, MODULE),
    }
}

/// Absolute path to `python3`: `PATH`, then Homebrew's and the usual
/// local prefix, for the GUI-stripped-PATH reason [`pytest_script`]
/// gives. Bare `python3` when none is found.
fn python3_program(path_var: Option<&std::ffi::OsStr>) -> PathBuf {
    let path_dirs = path_var.map(std::env::split_paths).into_iter().flatten();
    let fallback = ["/opt/homebrew/bin", "/usr/local/bin"].map(PathBuf::from);
    path_dirs
        .chain(fallback)
        .map(|dir| dir.join("python3"))
        .find(|candidate| candidate.is_file())
        .unwrap_or_else(|| PathBuf::from("python3"))
}

/// Whether `python` can import pytest when run in `root`, asked once per
/// root and interpreter for the life of the process: discovery and every
/// run launch pytest, and the answer only changes when pytest is
/// installed or removed.
fn python_has_pytest(root: &Path, python: &Path) -> bool {
    use std::collections::HashMap;
    use std::sync::{Mutex, OnceLock};
    static ANSWERS: OnceLock<Mutex<HashMap<(PathBuf, PathBuf), bool>>> = OnceLock::new();
    let key = (root.to_path_buf(), python.to_path_buf());
    let answers = ANSWERS.get_or_init(Default::default);
    if let Some(&known) = answers.lock().unwrap_or_else(|e| e.into_inner()).get(&key) {
        return known;
    }
    let has = Command::new(python)
        .args(["-c", "import pytest"])
        .current_dir(root)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .is_ok_and(|s| s.success());
    answers
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .insert(key, has);
    has
}

/// Absolute path to a `pytest` script outside any project venv: `PATH`,
/// then the usual user/tool install dirs — resolved absolutely like
/// [`cargo_cmd`] because a GUI-launched croft inherits the stripped
/// launchd PATH.
fn pytest_script(path_var: Option<&std::ffi::OsStr>) -> Option<PathBuf> {
    if let Some(path_var) = path_var {
        for dir in std::env::split_paths(path_var) {
            let candidate = dir.join("pytest");
            if candidate.is_file() {
                return Some(candidate);
            }
        }
    }
    if let Some(home) = std::env::var_os("HOME") {
        let candidate = PathBuf::from(home)
            .join(".local")
            .join("bin")
            .join("pytest");
        if candidate.is_file() {
            return Some(candidate);
        }
    }
    for dir in ["/opt/homebrew/bin", "/usr/local/bin"] {
        let candidate = PathBuf::from(dir).join("pytest");
        if candidate.is_file() {
            return Some(candidate);
        }
    }
    None
}

/// pytest's verbosity for a run: `<id> PASSED` lines are printed from 1
/// up. Set outright, not with `-v`, which counts on from the project's
/// `addopts`: with the common `-q` there, `-v` lands on 0 and the run
/// prints only dots, so no result is read (#1502).
const PYTEST_RUN_VERBOSITY: &str = "--verbosity=1";

/// pytest's verbosity for `--collect-only`: one node id per line is level
/// -1 exactly. `-q` would stack on an `addopts` `-q` to -2, which prints a
/// count per file instead (#1502).
const PYTEST_COLLECT_VERBOSITY: &str = "--verbosity=-1";

/// `pytest <args>` rooted at the workspace, launched as [`pytest_launch`]
/// says, with piped stdio. Discovery, runs and coverage all come through
/// here, so they always agree on the interpreter.
fn pytest_cmd(root: &Path, args: &[&str]) -> Command {
    let (program, lead) = pytest_launch(root);
    let mut cmd = Command::new(program);
    cmd.args(lead)
        .args(args)
        .current_dir(root)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    cmd
}

/// Absolute path to `go`: `PATH`, then where the official installer and
/// Homebrew put it — absolute for the same GUI-stripped-PATH reason as
/// [`cargo_cmd`].
fn go_binary() -> PathBuf {
    let path_dirs = std::env::var_os("PATH")
        .map(|p| std::env::split_paths(&p).collect::<Vec<_>>())
        .unwrap_or_default();
    path_dirs
        .into_iter()
        .chain(["/usr/local/go/bin", "/opt/homebrew/bin", "/usr/local/bin"].map(PathBuf::from))
        .map(|d| d.join("go"))
        .find(|p| p.is_file())
        .unwrap_or_else(|| PathBuf::from("go"))
}

/// `go test -json <args>` in `root` (#264).
fn go_cmd<S: AsRef<std::ffi::OsStr>>(root: &Path, args: &[S]) -> Command {
    let mut cmd = Command::new(go_binary());
    cmd.args(["test", "-json"])
        .args(args)
        .current_dir(root)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    cmd
}

/// Run `go test -json` and stream its finished tests, showing the text the
/// tests printed (not the JSON events) in the OUTPUT channel. `./...` is
/// spelled for the root's modules (see [`super::gotest::Modules::expand`]).
fn run_go<S: AsRef<str>>(tx: &EpochTx, root: &Path, args: &[S]) -> Option<bool> {
    let modules = super::gotest::Modules::of(root);
    let cmd = go_cmd(root, &modules.expand(args));
    run_streaming_shown(tx, cmd, super::gotest::shown, |line| {
        super::gotest::parse_event(&modules, line)
            .into_iter()
            .collect()
    })
}

/// Run `codeql <args>` in `root` and stream each test's result (#578). A
/// result is complete once the diff or errors after its line have arrived,
/// so it lands when the next test's line (or the end of output) does; each
/// failure also gets a one-line summary in OUTPUT, above the CLI's own
/// diff-heavy text.
fn run_codeql(tx: &EpochTx, root: &Path, args: &[String]) -> Option<bool> {
    let mut cmd = Command::new(tx.codeql);
    cmd.args(args)
        .current_dir(root)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    let stream = std::cell::RefCell::new(super::codeqltest::RunStream::new(root));
    let report = |o: super::codeqltest::Outcome| {
        if let Some(summary) = o.failure_summary() {
            output::push(output::CHANNEL_TESTS, OutputLevel::Error, &summary);
        }
        o.case()
    };
    let ok = run_streaming(tx, cmd, |line| {
        stream
            .borrow_mut()
            .feed(line)
            .map(report)
            .into_iter()
            .collect()
    });
    if let Some(o) = stream.borrow_mut().finish() {
        tx.send(TestResponse::Case(report(o)));
    }
    ok
}

/// Absolute path to a JS test runner binary for a workspace: the project's own
/// `node_modules/.bin/<name>` first (the installed version, with the project's
/// config resolvable), then `PATH`, then the usual global dirs — absolute for
/// the same GUI-stripped-PATH reason as [`cargo_cmd`].
fn js_binary(root: &Path, name: &str) -> PathBuf {
    let local = root.join("node_modules").join(".bin").join(name);
    if local.is_file() {
        return local;
    }
    if let Some(path_var) = std::env::var_os("PATH") {
        for dir in std::env::split_paths(&path_var) {
            let candidate = dir.join(name);
            if candidate.is_file() {
                return candidate;
            }
        }
    }
    for dir in ["/opt/homebrew/bin", "/usr/local/bin"] {
        let candidate = PathBuf::from(dir).join(name);
        if candidate.is_file() {
            return candidate;
        }
    }
    PathBuf::from(name)
}

/// `<vitest|jest> <args>` rooted at the workspace, with piped stdio.
/// `NO_COLOR` strips ANSI from the parsed stream and `CI` keeps vitest out of
/// watch/interactive mode.
fn js_cmd<S: AsRef<std::ffi::OsStr>>(root: &Path, runner: &str, args: &[S]) -> Command {
    let mut cmd = Command::new(js_binary(root, runner));
    cmd.args(args)
        .current_dir(root)
        .env("NO_COLOR", "1")
        .env("CI", "1")
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    cmd
}

/// Split a croft JS node ID (`file::describe...::test`) into its file and an
/// optional title: the first segment is always the test file, the last (when
/// present) the name filter to hand `-t`.
fn js_id_parts(id: &str) -> (&str, Option<&str>) {
    match id.split_once("::") {
        Some((file, rest)) => (file, rest.rsplit("::").next()),
        None => (id, None),
    }
}

/// Whether a run-filter pattern is a node-ID (prefix) rooted at a test file,
/// as opposed to a bare title from run-at-cursor.
fn is_js_file(pattern: &str) -> bool {
    super::parse::is_js_test_file(js_id_parts(pattern).0)
}

/// One test-harness executable out of `cargo test --no-run`'s JSON: its
/// path, the target that built it, the target's root source file, and
/// whether that target is an integration test (kind `test`, one harness per
/// `tests/*.rs` — or per explicit `[[test]]` entry, which can rename the
/// target and point it anywhere; `src_path` is the only reliable link back
/// to the file).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TestBinary {
    pub path: PathBuf,
    pub target: String,
    pub src_path: PathBuf,
    pub integration: bool,
}

/// The test-profile executables from `cargo test --no-run
/// --message-format=json` output: compiler-artifact lines whose profile is
/// `test` and whose `executable` is set. Ranked lib first (unit tests
/// overwhelmingly live in the lib), then bin, then integration `test`
/// targets, preserving cargo's order within a rank. A src/lib.rs +
/// src/main.rs crate emits both a lib and a bin harness; the old last-wins
/// pick handed a lib test to the bin harness, which filters everything out
/// and exits before a breakpoint can bind.
pub fn test_binary_candidates(output: &str) -> Vec<TestBinary> {
    let mut ranked: Vec<(u8, TestBinary)> = Vec::new();
    for line in output.lines() {
        let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else {
            continue;
        };
        if v.get("reason").and_then(|r| r.as_str()) != Some("compiler-artifact")
            || v.get("profile")
                .and_then(|p| p.get("test"))
                .and_then(|t| t.as_bool())
                != Some(true)
        {
            continue;
        }
        let Some(exe) = v.get("executable").and_then(|e| e.as_str()) else {
            continue;
        };
        let target = v.get("target");
        let has_kind = |want: &str| {
            target
                .and_then(|t| t.get("kind"))
                .and_then(|k| k.as_array())
                .is_some_and(|kinds| kinds.iter().filter_map(|k| k.as_str()).any(|k| k == want))
        };
        let kind_rank = if has_kind("lib") {
            0
        } else if has_kind("bin") {
            1
        } else {
            2
        };
        ranked.push((
            kind_rank,
            TestBinary {
                path: PathBuf::from(exe),
                target: target
                    .and_then(|t| t.get("name"))
                    .and_then(|n| n.as_str())
                    .unwrap_or("")
                    .to_string(),
                src_path: PathBuf::from(
                    target
                        .and_then(|t| t.get("src_path"))
                        .and_then(|s| s.as_str())
                        .unwrap_or(""),
                ),
                integration: has_kind("test"),
            },
        ));
    }
    ranked.sort_by_key(|(r, _)| *r); // stable: cargo order kept within a rank
    ranked.into_iter().map(|(_, c)| c).collect()
}

/// Which candidate harness actually contains `name`: each is asked to
/// `--list` with the name as libtest's filter (fast — nothing runs), and the
/// first listing a test whose final `::` segment IS the name wins. The
/// filter alone is a substring match, so `lib_side_test` would otherwise
/// claim a harness that only knows `lib_side_test_extra`. cargo's JSON does
/// not say which target defines a test.
pub fn binary_containing_test(candidates: &[PathBuf], name: &str) -> Option<PathBuf> {
    let qualified = format!("::{name}");
    for exe in candidates {
        let Ok(out) = Command::new(exe)
            .args([name, "--list"])
            .stdin(Stdio::null())
            .output()
        else {
            continue;
        };
        let stdout = String::from_utf8_lossy(&out.stdout);
        let listed = stdout.lines().any(|l| {
            l.trim_end()
                .strip_suffix(": test")
                .is_some_and(|t| t == name || t.ends_with(&qualified))
        });
        if listed {
            return Some(exe.clone());
        }
    }
    None
}

/// Build (or reuse) the workspace's test binaries and pick the harness that
/// contains `name`: `cargo test --no-run --message-format=json`, then a
/// `--list` probe when more than one harness could own the test. A nonzero
/// cargo exit is a build failure even if some targets' executables were
/// already emitted — launching a partial build would debug stale code
/// instead of surfacing the compile error. `source` (the file the debug
/// gesture happened in) narrows the harnesses first: a file that IS a
/// target's `src_path` owns that target outright (exact even for a renamed
/// `[[test]] path = ...` target the file stem cannot predict); a module
/// file narrows to its side of the build (`tests/` → integration harnesses,
/// anything else → lib/bin) and never widens further — a lib-first probe
/// over every harness is how a unit test used to steal an integration
/// test's bare name. Blocking — the app runs this on a background thread
/// and launches from the drain.
pub fn build_test_binary(
    root: &Path,
    name: &str,
    source: Option<&Path>,
) -> std::io::Result<PathBuf> {
    let out = cargo_cmd(root, &["test", "--no-run", "--message-format=json"]).output()?;
    let stderr = String::from_utf8_lossy(&out.stderr);
    if !out.status.success() {
        return Err(std::io::Error::other(format!(
            "cargo test --no-run failed: {}",
            stderr
                .lines()
                .rev()
                .find(|l| l.starts_with("error"))
                .or_else(|| stderr.lines().last())
                .unwrap_or("")
                .trim()
        )));
    }
    let stdout = String::from_utf8_lossy(&out.stdout);
    let all = test_binary_candidates(&stdout);
    if all.is_empty() {
        return Err(std::io::Error::other(format!(
            "no test binary in cargo's build output: {}",
            stderr.lines().last().unwrap_or("")
        )));
    }
    let pool: Vec<&TestBinary> = match source {
        Some(src) => {
            // Canonicalize both sides: cargo reports resolved paths
            // (/private/var/... on macOS) while the editor may hold the
            // symlinked spelling of the same file.
            let canon = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
            let src = canon(src);
            let exact: Vec<&TestBinary> =
                all.iter().filter(|c| canon(&c.src_path) == src).collect();
            if exact.is_empty() {
                let is_integration_src = src.strip_prefix(canon(root)).is_ok_and(|rel| {
                    rel.components()
                        .next()
                        .is_some_and(|c| c.as_os_str() == "tests")
                });
                let side: Vec<&TestBinary> = all
                    .iter()
                    .filter(|c| c.integration == is_integration_src)
                    .collect();
                if side.is_empty() {
                    return Err(std::io::Error::other(format!(
                        "no {} harness in the build owns {}",
                        if is_integration_src {
                            "integration-test"
                        } else {
                            "unit-test"
                        },
                        src.display()
                    )));
                }
                side
            } else {
                exact
            }
        }
        None => all.iter().collect(),
    };
    match pool.as_slice() {
        [only] => Ok(only.path.clone()),
        _ => {
            let paths: Vec<PathBuf> = pool.iter().map(|c| c.path.clone()).collect();
            binary_containing_test(&paths, name).ok_or_else(|| {
                std::io::Error::other(format!(
                    "none of the {} test harnesses lists a test named {name}",
                    paths.len()
                ))
            })
        }
    }
}

/// The config file stems and extensions vitest reads its `projects` from.
const VITEST_CONFIG_STEMS: [&str; 2] = ["vitest.config", "vite.config"];
const VITEST_CONFIG_EXTS: [&str; 6] = ["ts", "mts", "cts", "js", "mjs", "cjs"];

/// Whether `root` runs vitest projects (#1504), formerly workspaces: a
/// `vitest.workspace.*` or `vitest.projects.*` file, or a config declaring
/// `projects` (or the older `workspace`). There tap-flat names a test by its file relative to its
/// PROJECT, without the project, so two packages' `x.test.ts` collapse into
/// one suite and same-named tests overwrite each other. A false positive
/// costs only the live tree updates: the run is read from its JSON report.
fn vitest_has_projects(root: &Path) -> bool {
    let ws_file = ["vitest.workspace", "vitest.projects"].iter().any(|stem| {
        VITEST_CONFIG_EXTS
            .iter()
            .chain(&["json"])
            .any(|ext| root.join(format!("{stem}.{ext}")).is_file())
    });
    ws_file
        || VITEST_CONFIG_STEMS.iter().any(|stem| {
            VITEST_CONFIG_EXTS.iter().any(|ext| {
                std::fs::read_to_string(root.join(format!("{stem}.{ext}")))
                    .is_ok_and(|config| declares_vitest_projects(&config))
            })
        })
}

/// Whether config source declares a `projects:` or `workspace:` key, quoted
/// or not. Not a parser: a key-shaped word is enough.
fn declares_vitest_projects(config: &str) -> bool {
    ["projects", "workspace"].iter().any(|key| {
        config.match_indices(key).any(|(i, _)| {
            let word_start = config[..i]
                .chars()
                .next_back()
                .is_none_or(|c| !(c.is_alphanumeric() || c == '_' || c == '$'));
            let after = &config[i + key.len()..];
            let after = after.strip_prefix(['"', '\'']).unwrap_or(after);
            word_start && after.trim_start().starts_with(':')
        })
    })
}

/// Run vitest with `args`, a `run` reporting through tap-flat. Outside a
/// projects setup the tap-flat lines stream into the tree as they come. In
/// one (#1504) they only reach OUTPUT: the json reporter's report, whose
/// files are absolute, names the cases once the run ends, rooted at the
/// workspace-relative file so each package keeps its own tests.
fn run_vitest(tx: &EpochTx, root: &Path, args: &[String]) -> Option<bool> {
    if !vitest_has_projects(root) {
        return run_streaming(tx, js_cmd(root, "vitest", args), one(parse_vitest_tap_line));
    }
    static RUN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let n = RUN.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let report = std::env::temp_dir().join(format!("croft-vitest-{}-{n}.json", std::process::id()));
    let _ = std::fs::remove_file(&report);
    let mut args = args.to_vec();
    args.push(String::from("--reporter=json"));
    args.push(format!("--outputFile.json={}", report.display()));
    let ok = run_streaming(tx, js_cmd(root, "vitest", &args), |_| Vec::new());
    let text = std::fs::read_to_string(&report).unwrap_or_default();
    let _ = std::fs::remove_file(&report);
    for case in parse_jest_json(root, &text) {
        tx.send(TestResponse::Case(case));
    }
    ok
}

/// vitest argv for one exact test: the file scopes the run and `-t` narrows
/// to the test. vitest's `-t/--testNamePattern` is jest-compatible — a
/// REGEX over the full name — so the name is escaped like jest's, and
/// anchored (see [`exact_title_anchor`]).
fn vitest_one_args(name: &str) -> Vec<String> {
    let mut args = vec![String::from("run"), js_id_parts(name).0.to_string()];
    if let Some(anchor) = exact_title_anchor(name) {
        args.push(String::from("-t"));
        args.push(anchor);
    }
    args.push(String::from("--reporter=tap-flat"));
    args
}

/// `-t` regex for one test (#1506): its describe chain and title, escaped,
/// joined with [`JS_NAME_JOIN`] the way vitest and jest build the full name
/// they search `-t` in, and anchored at both ends. The bare title is a
/// search too, so `works` also ran `works with negatives` and a `works` in
/// another describe. `None` for an ID that is only a file.
fn exact_title_anchor(id: &str) -> Option<String> {
    full_name_regex(id).map(|name| format!("^{name}$"))
}

/// What joins a describe and the next title in the full name `-t` is
/// matched against: a space for jest and vitest before 5, ` > ` from vitest
/// 5 on. A title can itself hold `::` (`connects to ::1`), which the node
/// ID cannot tell from a boundary, so `::` matches at a boundary too.
const JS_NAME_JOIN: &str = "(?: | > |::)";

/// The describe and title separator alone, closing a suite's chain.
const JS_SUITE_JOIN: &str = "(?: | > )";

/// The describe chain and title of a JS node ID as the escaped full name
/// the runners match `-t` against; `None` for a bare file.
fn full_name_regex(id: &str) -> Option<String> {
    let (_, rest) = id.split_once("::")?;
    Some(
        rest.split("::")
            .map(regex_escape)
            .collect::<Vec<_>>()
            .join(JS_NAME_JOIN),
    )
}

/// `-t` regex for a suite click's describe chain: every segment after the
/// file, escaped and joined the way vitest and jest build the full name they
/// match `-t` against (describes + title joined by a space, or ` > ` from
/// vitest 5 — vitest's `getTaskFullName`, jest's `getTestID`), anchored at
/// the start and closed with the separator so describe `auth` cannot sweep
/// an `auth-helper` sibling. `None` when the suite is the whole file (no describe segments),
/// where the file argument alone scopes the run.
fn suite_title_anchor(pattern: &str) -> Option<String> {
    full_name_regex(pattern).map(|joined| format!("^{joined}{JS_SUITE_JOIN}"))
}

/// vitest argv for a filter run: a suite click passes a node-ID prefix
/// (`file` or `file::describe`), run-at-cursor a bare title. The file scopes
/// the run when present; a describe chain (anchored, see
/// [`suite_title_anchor`]) or the bare title narrows via `-t`.
fn vitest_filter_args(pattern: &str, suite: bool) -> Vec<String> {
    let mut args = vec![String::from("run")];
    let (file, title) = js_id_parts(pattern);
    if is_js_file(pattern) {
        args.push(file.to_string());
        if suite {
            if let Some(anchor) = suite_title_anchor(pattern) {
                args.push(String::from("-t"));
                args.push(anchor);
            }
        } else if let Some(t) = title {
            args.push(String::from("-t"));
            args.push(regex_escape(t));
        }
    } else {
        args.push(String::from("-t"));
        args.push(regex_escape(pattern));
    }
    args.push(String::from("--reporter=tap-flat"));
    args
}

/// jest's own way to name one test file (#1506). A bare positional file is
/// a `testPathPattern`, a regex searched in each absolute path, so
/// `src/a.test.js` also ran `legacy/src/a.test.js`; `--runTestsByPath`
/// takes it as that exact path.
fn jest_file_args(file: &str) -> [String; 2] {
    [String::from("--runTestsByPath"), file.to_string()]
}

/// jest argv for one exact test, mirroring [`vitest_one_args`]: the exact
/// file and an anchored `-t` (a regex over the full name) for the test.
fn jest_one_args(name: &str) -> Vec<String> {
    let mut args = jest_file_args(js_id_parts(name).0).to_vec();
    if let Some(anchor) = exact_title_anchor(name) {
        args.push(String::from("-t"));
        args.push(anchor);
    }
    args.push(String::from("--json"));
    args
}

/// jest argv for a filter run, mirroring [`vitest_filter_args`]: a node-ID
/// prefix scopes by file (plus an anchored `-t` for a suite's describe
/// chain), a bare title goes through `-t` alone.
fn jest_filter_args(pattern: &str, suite: bool) -> Vec<String> {
    let mut args = Vec::new();
    if is_js_file(pattern) {
        let (file, title) = js_id_parts(pattern);
        args.extend(jest_file_args(file));
        if suite {
            if let Some(anchor) = suite_title_anchor(pattern) {
                args.push(String::from("-t"));
                args.push(anchor);
            }
        } else if let Some(t) = title {
            args.push(String::from("-t"));
            args.push(regex_escape(t));
        }
    } else {
        args.push(String::from("-t"));
        args.push(regex_escape(pattern));
    }
    args.push(String::from("--json"));
    args
}

/// Adapt a one-line-one-case parser to [`run_streaming`]'s many-cases shape
/// (jest's `--json` yields every case from a single stdout line, so the
/// streaming contract is a `Vec` per line).
fn one(parse: fn(&str) -> Option<TestCase>) -> impl Fn(&str) -> Vec<TestCase> {
    move |line| parse(line).into_iter().collect()
}

/// Spawn `cmd`, tee stderr (compile diagnostics) to the OUTPUT channel, and run
/// each stdout line through `parse` — every matched [`TestCase`] is streamed as
/// it arrives. Returns the child's exit success, or `None` if it never spawned.
fn run_streaming(
    tx: &EpochTx,
    cmd: Command,
    parse: impl Fn(&str) -> Vec<TestCase>,
) -> Option<bool> {
    run_streaming_shown(tx, cmd, |line| Some(line.to_string()), parse)
}

/// [`run_streaming`], with `show` choosing what of each stdout line the
/// OUTPUT channel gets (`None` hides it): `go test -json` wraps the tests'
/// own text in events.
fn run_streaming_shown(
    tx: &EpochTx,
    cmd: Command,
    show: impl Fn(&str) -> Option<String>,
    parse: impl Fn(&str) -> Vec<TestCase>,
) -> Option<bool> {
    run_streaming_exit(tx, cmd, show, parse).map(|code| code == Some(0))
}

/// [`run_streaming_shown`], answering the child's exit code rather than
/// its success, for a caller that reads a nonzero code as something other
/// than failure. `Some(None)` when it died to a signal or could not be
/// waited on, `None` if it never spawned.
fn run_streaming_exit(
    tx: &EpochTx,
    mut cmd: Command,
    show: impl Fn(&str) -> Option<String>,
    parse: impl Fn(&str) -> Vec<TestCase>,
) -> Option<Option<i32>> {
    let mut child = match tx.control.spawn(tx.request, &mut cmd) {
        // Cancelled before it started: it ended without a verdict.
        None => return Some(None),
        Some(Ok(c)) => c,
        Some(Err(e)) => {
            output::push(
                output::CHANNEL_TESTS,
                OutputLevel::Error,
                &format!("failed to spawn the test runner: {e}"),
            );
            return None;
        }
    };
    let stderr_handle = child.stderr.take().map(|err| {
        let (tx, epoch) = tx.to_owned();
        std::thread::spawn(move || {
            for line in BufReader::new(err).lines().map_while(Result::ok) {
                output::push(output::CHANNEL_TESTS, OutputLevel::Info, &line);
                if let Some(p) = cargo_progress(&line) {
                    let _ = tx.send((epoch, TestResponse::Progress(p)));
                }
            }
        })
    });
    if let Some(out) = child.stdout.take() {
        for line in BufReader::new(out).lines().map_while(Result::ok) {
            if let Some(text) = show(&line) {
                output::push(output::CHANNEL_TESTS, OutputLevel::Info, &text);
            }
            for case in parse(&line) {
                tx.send(TestResponse::Case(case));
            }
        }
    }
    if let Some(h) = stderr_handle {
        let _ = h.join();
    }
    let code = child.wait().ok().and_then(|s| s.code());
    tx.control.finished();
    Some(code)
}

/// The cargo build-status verbs printed to stderr (whitespace-indented on a
/// non-TTY). We surface these as live progress; everything else (diagnostics,
/// the `--list` chrome) stays in the OUTPUT channel only.
const CARGO_PROGRESS_VERBS: [&str; 6] = [
    "Compiling",
    "Building",
    "Downloading",
    "Updating",
    "Finished",
    "Running",
];

/// Turn a cargo stderr line into a short progress string (trimmed), or `None`
/// if it is not a build-status line.
pub(crate) fn cargo_progress(line: &str) -> Option<String> {
    let trimmed = line.trim();
    let verb = trimmed.split_whitespace().next()?;
    CARGO_PROGRESS_VERBS
        .contains(&verb)
        .then(|| trimmed.to_string())
}

fn run_all(root: &Path, tx: &EpochTx) {
    // `None` (no enabled runner claims the root) must never fall through to
    // cargo: the app's entry points refuse first, and this second gate keeps
    // a disabled runner from shelling anything even if a new call site
    // forgets the check. It must also run BEFORE `Started`, which clears the
    // discovered tree — a refusal keeps the panel exactly as it was.
    // Exhaustive matches below, no `_` arm, so a future Runner variant is a
    // compile error here instead of silently cargo.
    let runners = runners_for(tx.extensions, root);
    if runners.is_empty() {
        tx.send(TestResponse::Refused);
        return;
    }
    tx.send(TestResponse::Started(Activity::Running));
    // Every runner runs, even after one fails (#1408).
    let mut ok = true;
    for runner in runners {
        ok &= run_all_with(runner, root, &tx.tagged(runner));
    }
    tx.send(TestResponse::Finished { ok: Some(ok) });
}

/// Run everything `runner` runs; whether it all passed.
fn run_all_with(runner: Runner, root: &Path, tx: &EpochTx) -> bool {
    match runner {
        Runner::Pytest => {
            let cmd = pytest_cmd(root, &[PYTEST_RUN_VERBOSITY, "--color=no"]);
            run_streaming(tx, cmd, one(parse_pytest_line))
        }
        Runner::Vitest => run_vitest(
            tx,
            root,
            &[String::from("run"), String::from("--reporter=tap-flat")],
        ),
        Runner::Jest => {
            let cmd = js_cmd(root, "jest", &["--json"]);
            run_streaming(tx, cmd, |line| parse_jest_json(root, line))
        }
        Runner::Cargo => {
            let cmd = cargo_cmd(root, &["test", "--no-fail-fast", "--color=never"]);
            run_streaming(tx, cmd, one(parse_test_line))
        }
        Runner::Go => run_go(tx, root, &[String::from("./...")]),
        Runner::Codeql => {
            let packs = super::codeqltest::test_packs(root, &codeql_markers());
            match super::codeqltest::all_args(root, &packs) {
                Some(args) => run_codeql(tx, root, &args),
                // No test pack: nothing to run, and nothing failed.
                None => Some(true),
            }
        }
    }
    .unwrap_or(false)
}

/// The pack files the bundled CodeQL runner looks for. A run needs the test
/// packs again, not just the verdict that there is one.
fn codeql_markers() -> Vec<String> {
    vec![String::from("qlpack.yml"), String::from("codeql-pack.yml")]
}

/// The report every runner is asked to write: LCOV, into `dir`.
fn coverage_report(dir: &Path) -> PathBuf {
    dir.join("lcov.info")
}

/// Which tests a coverage run covers, when not all of them (#263): `name`
/// as run-at-cursor resolved it, `exact` when it is a full test name
/// rather than a substring filter, `suite` when it is a suite from the
/// Testing tree, selected as a plain run of that suite selects it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CoverageScope {
    pub name: String,
    pub exact: bool,
    pub suite: bool,
}

/// The filter arguments that narrow a coverage run to `scope`: the same
/// selection a plain run of that test makes, less what [`coverage_args`]
/// already says (vitest's `run` and reporter, jest's `--json`).
fn coverage_scope_args(runner: Runner, scope: &CoverageScope) -> Vec<String> {
    let name = scope.name.as_str();
    let drop = |args: Vec<String>, skip: &[&str]| {
        args.into_iter()
            .filter(|a| !skip.contains(&a.as_str()) && !a.starts_with("--reporter="))
            .collect::<Vec<_>>()
    };
    match runner {
        Runner::Pytest => {
            if scope.exact || scope.suite || name.contains(".py") {
                vec![name.to_string()]
            } else {
                vec![String::from("-k"), name.to_string()]
            }
        }
        Runner::Vitest => drop(
            if scope.exact {
                vitest_one_args(name)
            } else {
                vitest_filter_args(name, scope.suite)
            },
            &["run"],
        ),
        Runner::Jest => drop(
            if scope.exact {
                jest_one_args(name)
            } else {
                jest_filter_args(name, scope.suite)
            },
            &["--json"],
        ),
        // `cargo llvm-cov [TESTNAME] [-- <libtest args>]`, as `cargo test`,
        // a suite anchored as its plain run anchors it.
        Runner::Cargo => {
            let name = if scope.suite {
                super::suite_pattern(name)
            } else {
                name.to_string()
            };
            let mut a = vec![name];
            if scope.exact {
                a.push(String::from("--"));
                a.push(String::from("--exact"));
            }
            a
        }
        Runner::Go => {
            if scope.exact {
                super::gotest::one_args(name)
            } else {
                super::gotest::filter_args(name, scope.suite)
            }
        }
        // Refused before any argv is built (see run_coverage).
        Runner::Codeql => Vec::new(),
    }
}

/// The run-everything argv with coverage on, writing LCOV into `dir`. Each
/// keeps the output format the normal run parses, so results stream into
/// the tree as usual.
fn coverage_args(runner: Runner, dir: &Path) -> Vec<String> {
    let dir_s = dir.display().to_string();
    let report = coverage_report(dir).display().to_string();
    let v = |args: &[&str]| args.iter().map(|a| a.to_string()).collect::<Vec<_>>();
    match runner {
        Runner::Pytest => {
            let mut a = v(&[
                PYTEST_RUN_VERBOSITY,
                "--color=no",
                "--cov=.",
                "--cov-branch",
            ]);
            a.push(format!("--cov-report=lcov:{report}"));
            a
        }
        Runner::Vitest => {
            let mut a = v(&[
                "run",
                "--reporter=tap-flat",
                "--coverage.enabled",
                "--coverage.reporter=lcov",
            ]);
            a.push(format!("--coverage.reportsDirectory={dir_s}"));
            a
        }
        Runner::Jest => {
            let mut a = v(&["--json", "--coverage", "--coverageReporters=lcov"]);
            a.push(format!("--coverageDirectory={dir_s}"));
            a
        }
        Runner::Cargo => {
            let mut a = v(&[
                "llvm-cov",
                "--no-fail-fast",
                "--color=never",
                "--lcov",
                "--output-path",
            ]);
            a.push(report);
            a
        }
        // A Go cover profile, turned into `report` once the run ends.
        Runner::Go => vec![format!("-coverprofile={}", go_cover_profile(dir).display())],
        Runner::Codeql => Vec::new(),
    }
}

/// Where a Go coverage run writes its native profile.
fn go_cover_profile(dir: &Path) -> PathBuf {
    dir.join("cover.out")
}

/// What installs a runner's coverage tool, picked from the project's own
/// package manager. `None` for jest, whose coverage is built in.
fn coverage_install(runner: Runner, root: &Path) -> Option<(&'static str, String)> {
    let has = |f: &str| root.join(f).exists();
    match runner {
        Runner::Cargo => Some((
            "cargo-llvm-cov",
            String::from("cargo install cargo-llvm-cov"),
        )),
        Runner::Pytest => Some((
            "pytest-cov",
            if has("uv.lock") {
                String::from("uv add --dev pytest-cov")
            } else if has(".venv") {
                String::from(".venv/bin/python -m pip install pytest-cov")
            } else {
                String::from("python3 -m pip install pytest-cov")
            },
        )),
        Runner::Vitest => Some((
            "@vitest/coverage-v8",
            if has("pnpm-lock.yaml") {
                String::from("pnpm add -D @vitest/coverage-v8")
            } else if has("yarn.lock") {
                String::from("yarn add -D @vitest/coverage-v8")
            } else {
                String::from("npm install -D @vitest/coverage-v8")
            },
        )),
        // Coverage is built into `go test`; CodeQL has none to install.
        Runner::Jest | Runner::Go | Runner::Codeql => None,
    }
}

/// Whether the runner's coverage tool can run here.
fn coverage_tool_present(runner: Runner, root: &Path) -> bool {
    match runner {
        Runner::Cargo => cargo_cmd(root, &["llvm-cov", "--version"])
            .status()
            .is_ok_and(|s| s.success()),
        Runner::Pytest => pytest_cmd(root, &["--help"])
            .output()
            .is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains("--cov")),
        // Node resolves a package from the nearest `node_modules` up the
        // tree, so a monorepo's hoisted install at the repository root counts.
        Runner::Vitest => root.ancestors().any(|dir| {
            ["coverage-v8", "coverage-istanbul"]
                .iter()
                .any(|p| dir.join("node_modules/@vitest").join(p).is_dir())
        }),
        Runner::Jest | Runner::Go | Runner::Codeql => true,
    }
}

/// Run everything with coverage (#263). A missing tool is reported before
/// anything runs, with the command that installs it; the tree is left as
/// it was.
fn run_coverage(root: &Path, tx: &EpochTx, scope: Option<&CoverageScope>) {
    // A scoped run goes to the runner that owns its test, as a plain run
    // of it does (#1408): a pytest case in a maturin crate is pytest-cov's.
    let runner = match scope {
        Some(scope) => tx.choose(&runners_for(tx.extensions, root), &scope.name, None),
        None => runner_for(tx.extensions, root),
    };
    let Some(runner) = runner else {
        tx.send(TestResponse::Refused);
        return;
    };
    // A query test has no source lines of its own to cover.
    if runner == Runner::Codeql {
        tx.send(TestResponse::Coverage(Err(CoverageError::Unsupported {
            runner: "CodeQL tests",
        })));
        tx.send(TestResponse::Finished { ok: None });
        return;
    }
    if !coverage_tool_present(runner, root)
        && let Some((tool, install)) = coverage_install(runner, root)
    {
        {
            tx.send(TestResponse::Coverage(Err(CoverageError::Missing {
                tool,
                install,
            })));
            tx.send(TestResponse::Finished { ok: None });
            return;
        }
    }
    let dir = std::env::temp_dir().join(format!("croft-coverage-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let _ = std::fs::create_dir_all(&dir);
    // A scoped run, like `run_one`, leaves the rest of the tree as it is:
    // the app has already marked what it runs.
    if scope.is_none() {
        tx.send(TestResponse::Started(Activity::Running));
    }
    let mut args = coverage_args(runner, &dir);
    match scope {
        Some(scope) => args.extend(coverage_scope_args(runner, scope)),
        // The other runners run everything by default; `go test` only the
        // package in the current directory.
        None if runner == Runner::Go => args.push(String::from("./...")),
        None => {}
    }

    let args: Vec<&str> = args.iter().map(String::as_str).collect();
    let ok = match runner {
        Runner::Pytest => run_streaming(tx, pytest_cmd(root, &args), one(parse_pytest_line)),
        Runner::Vitest => {
            let args: Vec<String> = args.iter().map(|a| a.to_string()).collect();
            run_vitest(tx, root, &args)
        }
        Runner::Jest => run_streaming(tx, js_cmd(root, "jest", &args), |line| {
            parse_jest_json(root, line)
        }),
        Runner::Cargo => run_streaming(tx, cargo_cmd(root, &args), one(parse_test_line)),
        Runner::Go => run_go(tx, root, &args),
        Runner::Codeql => None,
    }
    .unwrap_or(false);
    let lcov = if runner == Runner::Go {
        std::fs::read_to_string(go_cover_profile(&dir)).map(|profile| {
            let modules = super::gotest::Modules::of(root);
            super::gotest::cover_profile_to_lcov(&profile, &modules)
        })
    } else {
        std::fs::read_to_string(coverage_report(&dir))
    };
    let report = lcov
        .map(|text| super::coverage::Coverage::from_lcov(&text, root))
        .map_err(|_| CoverageError::NoReport);
    tx.send(TestResponse::Coverage(report));
    tx.send(TestResponse::Finished { ok: Some(ok) });
}

/// Run a single test by exact name: `cargo test <name> --color=never -- --exact`
/// (`--exact` stops the name being treated as a substring filter), or for
/// pytest the node ID itself, which is already exact. No `Started` is sent: the
/// app marks just this case Running and keeps the rest of the tree, so a
/// single-test run doesn't wipe the discovered list.
fn run_one(root: &Path, tx: &EpochTx, name: &str) {
    // See run_all: `None` refuses instead of falling through to cargo, and
    // `Refused` (not a bare Finished) rolls back this case's Running mark.
    let Some(runner) = tx.choose(&runners_for(tx.extensions, root), name, None) else {
        tx.send(TestResponse::Refused);
        return;
    };
    let ok = run_one_case(root, tx, runner, name);
    tx.send(TestResponse::Finished { ok: Some(ok) });
}

/// Run each of `names` exactly, one after another, as a single run (#1535):
/// every runner can run one test by name, which no shared multi-name filter
/// spans. All are run whatever an earlier one did, and the run fails if any
/// of them did.
fn run_many(root: &Path, tx: &EpochTx, names: &[String]) {
    let runners = runners_for(tx.extensions, root);
    if runners.is_empty() {
        tx.send(TestResponse::Refused);
        return;
    }
    let mut ok = true;
    for name in names {
        // Each test goes back to the runner that listed it (#1408).
        ok &= tx
            .choose(&runners, name, None)
            .is_some_and(|runner| run_one_case_seen(root, tx, runner, name));
    }
    tx.send(TestResponse::Finished { ok: Some(ok) });
}

/// [`run_one_case`], passed only when the runner also reported a result
/// for `name`: a test renamed since discovery matches nothing, and a
/// name-filtered runner exits cleanly having run zero tests.
fn run_one_case_seen(root: &Path, tx: &EpochTx, runner: Runner, name: &str) -> bool {
    let (case_tx, case_rx) = std::sync::mpsc::channel::<(u64, TestResponse)>();
    std::thread::scope(|s| {
        let forward = s.spawn(|| {
            let mut seen = false;
            for (epoch, resp) in case_rx {
                if let TestResponse::Case(case) = &resp {
                    seen |= case.name == name;
                }
                let _ = tx.tx.send((epoch, resp));
            }
            seen
        });
        let passed = {
            let etx = EpochTx {
                tx: &case_tx,
                epoch: tx.epoch,
                codeql: tx.codeql,
                extensions: tx.extensions,
                control: tx.control,
                request: tx.request,
                owners: tx.owners,
                tag: tx.tag,
            };
            run_one_case(root, &etx, runner, name)
        };
        drop(case_tx);
        let seen = forward.join().unwrap_or(false);
        passed && seen
    })
}

/// One test by its exact name under `runner`, its result streamed; true
/// when the runner exited cleanly.
fn run_one_case(root: &Path, tx: &EpochTx, runner: Runner, name: &str) -> bool {
    match runner {
        Runner::Pytest => {
            let cmd = pytest_cmd(root, &[PYTEST_RUN_VERBOSITY, "--color=no", name]);
            run_streaming(tx, cmd, one(parse_pytest_line))
        }
        Runner::Vitest => run_vitest(tx, root, &vitest_one_args(name)),
        Runner::Jest => {
            let cmd = js_cmd(root, "jest", &jest_one_args(name));
            run_streaming(tx, cmd, |line| parse_jest_json(root, line))
        }
        Runner::Cargo => {
            let cmd = cargo_cmd(root, &["test", name, "--color=never", "--", "--exact"]);
            run_streaming(tx, cmd, one(parse_test_line))
        }
        Runner::Go => run_go(tx, root, &super::gotest::one_args(name)),
        Runner::Codeql => run_codeql(tx, root, &super::codeqltest::select_args(name)),
    }
    .unwrap_or(false)
}

/// Run every test matching a name filter. `suite` marks a header click: the
/// cargo arm then anchors the pattern with [`super::suite_pattern`], since a
/// bare substring like `parse` would also sweep `parse_utils::b`. pytest
/// splits the two shapes: a suite is a node-ID prefix (`tests/test_x.py`,
/// `tests/test_x.py::TestGroup`) passed positionally, a bare function name
/// (run-at-cursor) goes through `-k`, pytest's substring matcher. vitest and
/// jest anchor a suite's describe chain (see [`suite_title_anchor`]), since
/// their `-t` is an unanchored regex over the full name. Like [`run_one`],
/// the app has already marked the affected cases and shown the busy state,
/// so no `Started` is sent.
fn run_filter(root: &Path, tx: &EpochTx, pattern: &str, suite: bool) {
    run_filter_in(root, tx, pattern, suite, None);
}

/// [`run_filter`] for a run that came from `file`, whose language picks
/// the runner (#1408).
fn run_filter_in(root: &Path, tx: &EpochTx, pattern: &str, suite: bool, file: Option<&Path>) {
    // See run_all: `None` refuses instead of falling through to cargo, and
    // `Refused` (not a bare Finished) rolls back the filtered Running marks.
    let Some(runner) = tx.choose(&runners_for(tx.extensions, root), pattern, file) else {
        tx.send(TestResponse::Refused);
        return;
    };
    let ok = match runner {
        Runner::Pytest => {
            // A suite is always a node-ID prefix; the `.py` sniff keeps a
            // node-ID handed to a plain filter run positional too.
            let cmd = if suite || pattern.contains(".py") {
                pytest_cmd(root, &[PYTEST_RUN_VERBOSITY, "--color=no", pattern])
            } else {
                pytest_cmd(root, &[PYTEST_RUN_VERBOSITY, "--color=no", "-k", pattern])
            };
            run_streaming(tx, cmd, one(parse_pytest_line))
        }
        Runner::Vitest => run_vitest(tx, root, &vitest_filter_args(pattern, suite)),
        Runner::Jest => {
            let cmd = js_cmd(root, "jest", &jest_filter_args(pattern, suite));
            run_streaming(tx, cmd, |line| parse_jest_json(root, line))
        }
        Runner::Cargo => {
            let anchored;
            let pattern = if suite {
                anchored = super::suite_pattern(pattern);
                &anchored
            } else {
                pattern
            };
            let cmd = cargo_cmd(root, &["test", pattern, "--no-fail-fast", "--color=never"]);
            run_streaming(tx, cmd, one(parse_test_line))
        }
        Runner::Go => run_go(tx, root, &super::gotest::filter_args(pattern, suite)),
        // A suite is its folder; any other filter is taken as the path (or
        // id) of what to run.
        Runner::Codeql => run_codeql(tx, root, &super::codeqltest::select_args(pattern)),
    }
    .unwrap_or(false);
    tx.send(TestResponse::Finished { ok: Some(ok) });
}

/// List tests without running them (`cargo test -- --list`, or pytest's
/// `--collect-only -q`), streaming each as a `NotRun` case. The cargo path
/// still compiles the test binary, hence the Discovering state. The lister's
/// exit status goes back with `Finished`, so a listing that errors (pytest's
/// exit 2 on a collection error, a build failure) reads as a failed
/// discovery rather than a project with no tests (#845).
fn discover(root: &Path, tx: &EpochTx, quiet: bool) {
    if quiet {
        tx.send(TestResponse::QuietDiscovery);
    }
    // See run_all: refuse before `Started` so the panel keeps its tree.
    let runners = runners_for(tx.extensions, root);
    if runners.is_empty() {
        if !quiet {
            tx.send(TestResponse::Refused);
        }
        return;
    }
    tx.send(TestResponse::Started(Activity::Discovering));
    // Each runner lists its own tests into the one tree (#1408).
    let mut ok = true;
    for runner in runners {
        ok &= discover_with(runner, root, &tx.tagged(runner));
    }
    tx.send(TestResponse::Finished { ok: Some(ok) });
}

/// List `runner`'s tests; whether its lister succeeded.
fn discover_with(runner: Runner, root: &Path, tx: &EpochTx) -> bool {
    let not_run = |name: String| TestCase {
        name,
        status: TestStatus::NotRun,
    };
    match runner {
        Runner::Pytest => {
            let cmd = pytest_cmd(root, &["--collect-only", PYTEST_COLLECT_VERBOSITY, "--color=no"]);
            let show = |line: &str| Some(line.to_string());
            run_streaming_exit(tx, cmd, show, |line| {
                parse_pytest_collect_line(line)
                    .map(not_run)
                    .into_iter()
                    .collect()
            })
            // Exit 5 is pytest's "no tests were collected": a project with
            // no tests yet, which lists fine.
            .map(|code| matches!(code, Some(0 | 5)))
        }
        // `--passWithNoTests`: vitest 1 has no `list` command, reads the
        // word as a file filter and, finding no file, exits 1 without it.
        // vitest 2 and later exit 0 with no tests either way, and 1 still
        // on a file that fails to load. jest's `--listTests` exits 0 with
        // nothing to list.
        // A projects setup (#1504) lists as JSON, whose absolute files keep
        // each package's tests apart; the text listing names a test by its
        // project and a file relative to that project.
        Runner::Vitest if vitest_has_projects(root) => {
            let listed = std::cell::RefCell::new(String::new());
            let cmd = js_cmd(root, "vitest", &["list", "--json", "--passWithNoTests"]);
            let ok = run_streaming(tx, cmd, |line| {
                let mut listed = listed.borrow_mut();
                listed.push_str(line);
                listed.push('\n');
                Vec::new()
            });
            for name in parse_vitest_list_json(root, &listed.borrow()) {
                tx.send(TestResponse::Case(not_run(name)));
            }
            ok
        }
        Runner::Vitest => {
            let cmd = js_cmd(root, "vitest", &["list", "--passWithNoTests"]);
            run_streaming(tx, cmd, |line| {
                parse_vitest_list_line(line)
                    .map(not_run)
                    .into_iter()
                    .collect()
            })
        }
        // jest can only cheaply list FILES (`--listTests`, absolute paths);
        // per-test names come from the first run's `--json` document.
        Runner::Jest => {
            let cmd = js_cmd(root, "jest", &["--listTests"]);
            run_streaming(tx, cmd, |line| {
                let rel = Path::new(line.trim())
                    .strip_prefix(root)
                    .map(|p| p.display().to_string());
                match rel {
                    Ok(r) if !r.is_empty() => vec![not_run(r)],
                    _ => Vec::new(),
                }
            })
        }
        Runner::Cargo => {
            let cmd = cargo_cmd(root, &["test", "--color=never", "--", "--list"]);
            run_streaming(tx, cmd, |line| {
                parse_list_line(line).map(not_run).into_iter().collect()
            })
        }
        // `go test -list` compiles each package's tests but runs none.
        Runner::Go => {
            let modules = super::gotest::Modules::of(root);
            let cmd = go_cmd(root, &modules.expand(&["-list", ".", "./..."]));
            run_streaming_shown(tx, cmd, super::gotest::shown, |line| {
                super::gotest::parse_list_event(&modules, line)
                    .map(not_run)
                    .into_iter()
                    .collect()
            })
        }
        // Tests are files; listing them needs no CLI, and cannot fail.
        Runner::Codeql => {
            let packs = super::codeqltest::test_packs(root, &codeql_markers());
            for id in super::codeqltest::discover(root, &packs) {
                tx.send(TestResponse::Case(not_run(id)));
            }
            Some(true)
        }
    }
    // A lister that never spawned (pytest not installed) failed too.
    .unwrap_or(false)
}

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

    /// A user extensions folder with nothing added: the bundled runners only.
    const NO_EXTENSIONS: &str = "";

    /// A user extensions folder with CodeQL added, whose runner comes with
    /// it (#1842).
    fn codeql_added() -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join("codeql")).unwrap();
        std::fs::write(
            dir.path().join("codeql/extension.toml"),
            crate::mcp::registry_index::CODEQL_MANIFEST,
        )
        .unwrap();
        dir
    }

    /// A runner disabled between the app's entry-point check and the worker
    /// picking the queued request up must refuse WITHOUT wiping panel state:
    /// `Started(Running)` clears the discovered tree, and a bare
    /// `Finished{ok: None}` after `start_single`/`start_filter` leaves those
    /// cases stranded as Running forever (T-Rex reproduced both).
    #[test]
    fn refusing_a_run_with_no_runner_never_wipes_or_strands_the_panel() {
        let tmp = tempfile::tempdir().unwrap();
        let (tx, rx) = std::sync::mpsc::channel();
        let etx = EpochTx {
            tx: &tx,
            epoch: 0,
            codeql: Path::new("codeql"),
            extensions: Path::new(NO_EXTENSIONS),
            control: &RunControl::default(),
            request: 1,
            owners: None,
            tag: None,
        };
        run_all(tmp.path(), &etx);
        run_one(tmp.path(), &etx, "a::b");
        run_filter(tmp.path(), &etx, "a", false);
        run_filter(tmp.path(), &etx, "a", true);
        discover(tmp.path(), &etx, false);
        let msgs: Vec<TestResponse> = rx.try_iter().map(|(_, r)| r).collect();
        assert!(
            !msgs.iter().any(|m| matches!(m, TestResponse::Started(_))),
            "a refused run must not send Started: it wipes the discovered tree"
        );
        assert_eq!(
            msgs.iter()
                .filter(|m| matches!(m, TestResponse::Refused))
                .count(),
            5,
            "each refused request must answer with Refused, not a bare Finished"
        );
        assert!(
            !msgs
                .iter()
                .any(|m| matches!(m, TestResponse::Finished { .. })),
            "a bare Finished after start_single/start_filter strands cases Running"
        );
    }

    /// Running and not a zombie: a killed runner's background child is
    /// reparented and may wait to be reaped.
    #[cfg(unix)]
    fn running(pid: i32) -> bool {
        // SAFETY: signal 0 only checks that the pid exists.
        if unsafe { libc::kill(pid, 0) } != 0 {
            return false;
        }
        std::fs::read_to_string(format!("/proc/{pid}/stat")).map_or(true, |stat| {
            !stat
                .rsplit_once(')')
                .is_some_and(|(_, rest)| rest.trim_start().starts_with('Z'))
        })
    }

    #[cfg(unix)]
    fn wait_until(what: &str, mut done: impl FnMut() -> bool) {
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
        while !done() {
            assert!(std::time::Instant::now() < deadline, "timed out: {what}");
            std::thread::sleep(std::time::Duration::from_millis(20));
        }
    }

    /// #1534: a run whose test hangs (here a `codeql` that never returns,
    /// with a child of its own) is cancelled: the whole process group dies,
    /// the panel goes idle with the run marked cancelled, and the next run
    /// goes ahead and reports its own verdict.
    #[cfg(unix)]
    #[test]
    fn cancelling_a_hung_run_kills_its_processes_and_frees_the_worker() {
        use std::os::unix::fs::PermissionsExt;
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join("test/Find")).unwrap();
        std::fs::write(
            root.join("test/qlpack.yml"),
            "name: acme/tests\nextractor: javascript\ntests: .\n",
        )
        .unwrap();
        std::fs::write(root.join("test/Find/Find.qlref"), "Find.ql\n").unwrap();
        let bin = tempfile::tempdir().unwrap();
        let hang = bin.path().join("hang");
        std::fs::write(
            &hang,
            format!(
                "#!/bin/sh\necho $$ > '{d}/runner.pid'\nsleep 1000 &\necho $! > '{d}/child.pid'\nwait\n",
                d = bin.path().display()
            ),
        )
        .unwrap();
        std::fs::set_permissions(&hang, std::fs::Permissions::from_mode(0o755)).unwrap();
        let pid = |name: &str| -> Option<i32> {
            std::fs::read_to_string(bin.path().join(name))
                .ok()?
                .trim()
                .parse()
                .ok()
        };

        let mut worker = TestWorker::spawn(root.to_path_buf());
        let mut panel = TestingPanel::new();
        let added = codeql_added();
        worker.set_extensions_dir(added.path().to_path_buf());
        worker.set_codeql_program(hang);
        worker.run_all();
        wait_until("the hung run starts", || {
            worker.drain(&mut panel);
            panel.is_busy() && pid("child.pid").is_some()
        });
        let (runner, child) = (pid("runner.pid").unwrap(), pid("child.pid").unwrap());
        worker.cancel();
        wait_until("the run ends", || {
            worker.drain(&mut panel);
            !panel.is_busy()
        });
        assert!(panel.take_cancelled(), "the end reads as cancelled");
        wait_until("the runner dies", || !running(runner));
        wait_until("the runner's child dies", || !running(child));

        // The next run is not cancelled: it reports its own verdict.
        let codeql = fake_codeql(
            bin.path(),
            root,
            "[1/1 comp 1.1s eval 20ms] PASSED @ROOT@/test/Find/Find.qlref\n",
        );
        worker.set_codeql_program(codeql);
        worker.run_all();
        panel.take_finished();
        let mut verdict = None;
        wait_until("the second run ends", || {
            worker.drain(&mut panel);
            verdict = panel.take_finished();
            verdict.is_some()
        });
        assert!(!panel.take_cancelled());
        assert_eq!(verdict, Some(Some(true)));
    }

    /// #1534 negative: a cancel covers the requests sent before it, never a
    /// later one, and refuses to start their further children.
    #[cfg(unix)]
    #[test]
    fn a_cancel_covers_only_the_requests_sent_before_it() {
        let control = RunControl::default();
        control.cancel(2);
        assert!(control.is_cancelled(1));
        assert!(control.is_cancelled(2));
        assert!(!control.is_cancelled(3));
        let mut cmd = Command::new("true");
        assert!(
            control.spawn(2, &mut cmd).is_none(),
            "a cancelled run starts nothing"
        );
        let mut child = control.spawn(3, &mut cmd).unwrap().unwrap();
        child.wait().unwrap();
        control.finished();
        assert!(control.running.lock().unwrap().is_none());
    }

    /// CI on `main` failed `a_single_vitest_project_still_streams_tap_flat`
    /// with no tests run: another test forked while its stand-in vitest was
    /// still open for writing, so exec said "Text file busy". A runner busy
    /// for a moment, held open here, still starts.
    #[cfg(unix)]
    #[test]
    fn a_runner_busy_for_a_moment_after_writing_still_starts() {
        let tmp = tempfile::tempdir().unwrap();
        let (bin, f) = busy_runner(tmp.path());
        let writer = std::thread::spawn(move || {
            std::thread::sleep(std::time::Duration::from_millis(100));
            drop(f);
        });
        let control = RunControl::default();
        let mut cmd = Command::new(&bin);
        let mut child = control
            .spawn(1, &mut cmd)
            .expect("not cancelled")
            .expect("the busy runner starts once its writer lets go");
        assert!(child.wait().unwrap().success());
        writer.join().unwrap();
    }

    /// A stand-in runner in `dir` and the handle that keeps it open for
    /// writing, so exec says "Text file busy" until the handle is dropped.
    #[cfg(unix)]
    fn busy_runner(dir: &Path) -> (PathBuf, std::fs::File) {
        use std::io::Write as _;
        use std::os::unix::fs::OpenOptionsExt;
        let bin = dir.join("runner");
        let mut f = std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .mode(0o755)
            .open(&bin)
            .unwrap();
        f.write_all(b"#!/bin/sh\nexit 0\n").unwrap();
        f.flush().unwrap();
        (bin, f)
    }

    /// A cancel while a busy runner is being waited out lands at once
    /// rather than after the wait, and the run starts nothing.
    #[cfg(unix)]
    #[test]
    fn a_cancel_stops_the_wait_for_a_busy_runner() {
        let tmp = tempfile::tempdir().unwrap();
        let (bin, writer) = busy_runner(tmp.path());
        let control = RunControl::default();
        let spawner = {
            let control = control.clone();
            std::thread::spawn(move || control.spawn(1, &mut Command::new(&bin)))
        };
        std::thread::sleep(std::time::Duration::from_millis(100));
        control.cancel(1);
        let spawned = spawner.join().unwrap();
        assert!(spawned.is_none(), "the cancel ends the wait: {spawned:?}");
        drop(writer);
    }

    /// A stand-in `codeql` in `dir` that logs its arguments and prints
    /// `out` (`@ROOT@` replaced by `root`), exiting nonzero when it reports
    /// a failure, as `codeql test run` does.
    #[cfg(unix)]
    fn fake_codeql(dir: &Path, root: &Path, out: &str) -> PathBuf {
        use std::os::unix::fs::PermissionsExt;
        let code = i32::from(out.contains("FAILED"));
        let script = format!(
            "#!/bin/sh\necho \"$*\" >> '{log}'\ncat <<'EOF'\n{out}EOF\nexit {code}\n",
            log = dir.join("calls.log").display(),
            out = out.replace("@ROOT@", &root.display().to_string()),
        );
        let bin = dir.join("codeql");
        std::fs::write(&bin, script).unwrap();
        std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
        bin
    }

    /// CodeQL tests (#578) end to end against a fake CLI: discovery lists
    /// each test file without running anything, a run of the test pack
    /// reports the pass and the diff failure, one test runs by its file,
    /// a suite by its folder, and coverage is refused as unavailable.
    #[cfg(unix)]
    #[test]
    fn codeql_tests_discover_run_and_refuse_coverage_with_a_fake_cli() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let write = |rel: &str, text: &str| {
            let p = root.join(rel);
            std::fs::create_dir_all(p.parent().unwrap()).unwrap();
            std::fs::write(p, text).unwrap();
        };
        write(
            "test/qlpack.yml",
            "name: acme/tests\nextractor: javascript\ntests: .\n",
        );
        write("test/Find/Find.qlref", "Find.ql\n");
        write("test/Find/Find.expected", "");
        write("test/Bad/Bad.ql", "select 1");
        write("test/Bad/Bad.expected", "");
        let bin = tempfile::tempdir().unwrap();
        let codeql = fake_codeql(
            bin.path(),
            root,
            "Executing 2 tests in 2 directories.\n\
             [1/2 comp 1.1s eval 20ms] PASSED @ROOT@/test/Find/Find.qlref\n\
             [2/2 comp 1.0s eval 18ms] FAILED(RESULT) @ROOT@/test/Bad/Bad.ql\n\
             --- expected\n+++ actual\n@@ -0,0 +1 @@\n+| 1 |\n\
             1 tests passed; 1 tests failed:\n  FAILED: @ROOT@/test/Bad/Bad.ql\n",
        );
        let added = codeql_added();
        assert_eq!(
            runner_for(Path::new(NO_EXTENSIONS), root),
            None,
            "not built in"
        );
        assert_eq!(runner_for(added.path(), root), Some(Runner::Codeql));
        let (tx, rx) = std::sync::mpsc::channel();
        let etx = EpochTx {
            tx: &tx,
            epoch: 0,
            codeql: &codeql,
            extensions: added.path(),
            control: &RunControl::default(),
            request: 1,
            owners: None,
            tag: None,
        };
        let drain = |rx: &Receiver<(u64, TestResponse)>| {
            let mut cases = Vec::new();
            let mut finished = None;
            for (_, r) in rx.try_iter() {
                match r {
                    TestResponse::Case(c) => cases.push((c.name, c.status)),
                    TestResponse::Finished { ok } => finished = Some(ok),
                    _ => {}
                }
            }
            (cases, finished)
        };
        let log = || std::fs::read_to_string(bin.path().join("calls.log")).unwrap_or_default();

        discover(root, &etx, false);
        let (cases, finished) = drain(&rx);
        assert_eq!(
            cases,
            vec![
                (String::from("test/Bad::Bad.ql"), TestStatus::NotRun),
                (String::from("test/Find::Find.qlref"), TestStatus::NotRun),
            ]
        );
        assert_eq!(finished, Some(Some(true)), "listing files cannot fail");
        assert_eq!(log(), "", "discovery never shells the CLI");

        run_all(root, &etx);
        let (cases, finished) = drain(&rx);
        assert_eq!(
            cases,
            vec![
                (String::from("test/Find::Find.qlref"), TestStatus::Passed),
                (String::from("test/Bad::Bad.ql"), TestStatus::Failed),
            ]
        );
        assert_eq!(finished, Some(Some(false)), "a failing test fails the run");
        assert_eq!(log(), "test run test\n", "run all runs the test pack");

        run_one(root, &etx, "test/Find::Find.qlref");
        run_filter(root, &etx, "test/Bad", true);
        let _ = drain(&rx);
        assert!(
            log().ends_with("test run test/Find/Find.qlref\ntest run test/Bad\n"),
            "{}",
            log()
        );

        run_coverage(root, &etx, None);
        let msgs: Vec<TestResponse> = rx.try_iter().map(|(_, r)| r).collect();
        assert!(matches!(
            msgs.as_slice(),
            [
                TestResponse::Coverage(Err(CoverageError::Unsupported { .. })),
                TestResponse::Finished { ok: None }
            ]
        ));
    }

    /// End to end against a real `go` (#264): discovery lists each
    /// package's tests, a run reports pass/fail/skip and subtests, one test
    /// runs alone, and coverage paints the package's source. Needs Go, so it
    /// is ignored by default; run it with `--ignored`.
    #[test]
    #[ignore]
    fn go_test_discovers_runs_and_covers_a_real_module() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        std::fs::write(root.join("go.mod"), "module example.com/m\n\ngo 1.21\n").unwrap();
        std::fs::create_dir(root.join("foo")).unwrap();
        std::fs::write(
            root.join("foo/foo.go"),
            "package foo\n\nfunc Add(a, b int) int {\n\tif a > 100 {\n\t\treturn 0\n\t}\n\treturn a + b\n}\n",
        )
        .unwrap();
        std::fs::write(
            root.join("foo/foo_test.go"),
            "package foo\n\nimport \"testing\"\n\n\
             func TestAdd(t *testing.T) {\n\tt.Run(\"small one\", func(t *testing.T) {\n\t\tif Add(1, 2) != 3 {\n\t\t\tt.Fatal(\"bad\")\n\t\t}\n\t})\n}\n\n\
             func TestBad(t *testing.T) { t.Fatal(\"nope\") }\n\n\
             func TestSkip(t *testing.T) { t.Skip(\"later\") }\n",
        )
        .unwrap();
        std::fs::write(
            root.join("root_test.go"),
            "package m\n\nimport \"testing\"\n\nfunc TestRoot(t *testing.T) {}\n",
        )
        .unwrap();
        let (tx, rx) = std::sync::mpsc::channel();
        let etx = EpochTx {
            tx: &tx,
            epoch: 0,
            codeql: Path::new("codeql"),
            extensions: Path::new(NO_EXTENSIONS),
            control: &RunControl::default(),
            request: 1,
            owners: None,
            tag: None,
        };
        let cases = |rx: &Receiver<(u64, TestResponse)>| {
            let mut v: Vec<(String, TestStatus)> = rx
                .try_iter()
                .filter_map(|(_, r)| match r {
                    TestResponse::Case(c) => Some((c.name, c.status)),
                    _ => None,
                })
                .collect();
            v.sort_by(|a, b| a.0.cmp(&b.0));
            v
        };
        use TestStatus::*;
        let s = String::from;

        discover(root, &etx, false);
        assert_eq!(
            cases(&rx),
            [
                (s("./foo::TestAdd"), NotRun),
                (s("./foo::TestBad"), NotRun),
                (s("./foo::TestSkip"), NotRun),
                (s(".::TestRoot"), NotRun),
            ]
        );
        run_all(root, &etx);
        assert_eq!(
            cases(&rx),
            [
                (s("./foo::TestAdd"), Passed),
                (s("./foo::TestAdd/small_one"), Passed),
                (s("./foo::TestBad"), Failed),
                (s("./foo::TestSkip"), Skipped),
                (s(".::TestRoot"), Passed),
            ]
        );
        run_one(root, &etx, "./foo::TestAdd/small_one");
        assert_eq!(
            cases(&rx),
            [
                (s("./foo::TestAdd"), Passed),
                (s("./foo::TestAdd/small_one"), Passed),
            ]
        );
        run_filter(root, &etx, "./foo", true);
        assert_eq!(cases(&rx).len(), 4, "the whole package");

        run_coverage(root, &etx, None);
        let report = rx
            .try_iter()
            .find_map(|(_, r)| match r {
                TestResponse::Coverage(c) => Some(c),
                _ => None,
            })
            .expect("a coverage report")
            .expect("go writes a profile");
        let file = report
            .files
            .get(&root.join("foo/foo.go"))
            .expect("foo.go is covered");
        assert_eq!(file.hits.get(&7), Some(&1), "return a + b ran");
        assert_eq!(file.hits.get(&5), Some(&0), "return 0 never ran");
    }

    #[test]
    fn vitest_titles_are_regex_escaped_like_jests() {
        // vitest's `-t/--testNamePattern` is jest-compatible: a REGEX over
        // the full name. Passing a title raw turns `adds (1 + 1)` into a
        // capture group (0 tests match) and an unbalanced `[` into an
        // invalid-pattern error. The jest paths already escape; vitest must
        // treat the same flag the same way.
        let args = vitest_one_args("tests/math.test.js::math::adds (1 + 1)");
        assert_eq!(
            args,
            vec![
                "run",
                "tests/math.test.js",
                "-t",
                r"^math(?: | > |::)adds \(1 \+ 1\)$",
                "--reporter=tap-flat"
            ]
        );
        let args = vitest_filter_args("parses [ tokens", false);
        assert_eq!(
            args,
            vec!["run", "-t", r"parses \[ tokens", "--reporter=tap-flat"]
        );
        let args = vitest_filter_args("tests/a.test.js::group (x)", false);
        assert_eq!(
            args,
            vec![
                "run",
                "tests/a.test.js",
                "-t",
                r"group \(x\)",
                "--reporter=tap-flat"
            ]
        );
    }

    #[test]
    fn drain_drops_responses_from_before_the_last_set_root() {
        let (mut w, tx) = TestWorker::for_test();
        let mut panel = TestingPanel::new();
        // A run for the OLD root is still streaming when the Explorer re-roots.
        w.set_root(PathBuf::from("/new"));
        tx.send((
            0,
            TestResponse::Case(TestCase {
                name: String::from("old_project::stale"),
                status: TestStatus::Failed,
            }),
        ))
        .unwrap();
        tx.send((0, TestResponse::Finished { ok: Some(false) }))
            .unwrap();
        assert!(
            !w.drain(&mut panel),
            "stale-epoch responses must be dropped, not applied"
        );
        assert!(panel.is_empty(), "the old project's case never lands");

        // Responses for the new root (epoch 1) still flow.
        tx.send((
            1,
            TestResponse::Case(TestCase {
                name: String::from("new_project::fresh"),
                status: TestStatus::Passed,
            }),
        ))
        .unwrap();
        assert!(w.drain(&mut panel));
        assert!(!panel.is_empty());
    }

    /// #1841: the Testing view's own discover leaves finding the runner to
    /// the worker, so a root no runner claims must end it without the
    /// refusal a run gesture reports, and without a Started that would
    /// wipe the panel.
    #[test]
    fn a_quiet_discovery_with_no_runner_ends_silently() {
        let tmp = tempfile::tempdir().unwrap();
        let (tx, rx) = std::sync::mpsc::channel();
        let etx = EpochTx {
            tx: &tx,
            epoch: 0,
            codeql: Path::new("codeql"),
            extensions: Path::new(NO_EXTENSIONS),
            control: &RunControl::default(),
            request: 1,
            owners: None,
            tag: None,
        };
        discover(tmp.path(), &etx, true);
        let msgs: Vec<TestResponse> = rx.try_iter().map(|(_, r)| r).collect();
        assert!(
            matches!(msgs.as_slice(), [TestResponse::QuietDiscovery]),
            "a quiet discovery with no runner says it was reached and nothing else"
        );

        let (mut w, tx) = TestWorker::for_test();
        let mut panel = TestingPanel::new();
        w.discover_quietly();
        assert!(w.discover_queued());
        tx.send((0, TestResponse::QuietDiscovery)).unwrap();
        assert!(
            !w.drain(&mut panel),
            "the marker changes nothing on screen, so nothing needs redrawing"
        );
        assert!(!w.discover_queued(), "the marker ends the queued discovery");
        assert!(!panel.take_refusal(), "a quiet discovery never says why");
        assert!(!panel.is_busy());
    }

    /// #1841: only the quiet discovery's own marker clears the queued flag:
    /// a regular discovery queued ahead of it answering first must not, or
    /// a reopen of the Testing view would queue another. A re-root clears
    /// it too, since its drain drops the old root's answers.
    #[test]
    fn only_the_quiet_discovery_itself_clears_the_queued_flag() {
        let (mut w, tx) = TestWorker::for_test();
        let mut panel = TestingPanel::new();
        w.discover();
        w.discover_quietly();
        tx.send((0, TestResponse::Started(Activity::Discovering)))
            .unwrap();
        tx.send((0, TestResponse::Finished { ok: Some(true) }))
            .unwrap();
        tx.send((0, TestResponse::Refused)).unwrap();
        assert!(w.drain(&mut panel));
        assert!(
            w.discover_queued(),
            "the earlier discovery's answers are not the quiet one starting"
        );
        tx.send((0, TestResponse::QuietDiscovery)).unwrap();
        tx.send((0, TestResponse::Started(Activity::Discovering)))
            .unwrap();
        assert!(w.drain(&mut panel));
        assert!(!w.discover_queued());
        assert!(panel.is_busy(), "the panel now shows the discovery");

        let (mut w, _tx) = TestWorker::for_test();
        w.discover_quietly();
        w.set_root(PathBuf::from("/new"));
        assert!(
            !w.discover_queued(),
            "the old root's discovery can never report under the new epoch"
        );
    }

    /// A root that is a package with `members` beside it (#1508).
    fn package_and_workspace() -> tempfile::TempDir {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            "[package]\nname = \"app\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n[workspace]\nmembers = [\"util\"]\n",
        )
        .unwrap();
        tmp
    }

    fn args_of(cmd: &Command) -> Vec<String> {
        cmd.get_args()
            .map(|a| a.to_string_lossy().into_owned())
            .collect()
    }

    /// #1508: at the root of a workspace that is also a package, every test
    /// and coverage run covers the members too: listing, Run All, one test,
    /// a filter, the debug build and llvm-cov.
    #[test]
    fn cargo_runs_at_a_workspace_root_cover_every_member() {
        let tmp = package_and_workspace();
        let root = tmp.path();
        for (args, want) in [
            (
                &["test", "--color=never", "--", "--list"][..],
                &["test", "--workspace", "--color=never", "--", "--list"][..],
            ),
            (
                &["test", "--no-fail-fast", "--color=never"][..],
                &["test", "--workspace", "--no-fail-fast", "--color=never"][..],
            ),
            (
                &[
                    "test",
                    "tests::util_works",
                    "--color=never",
                    "--",
                    "--exact",
                ][..],
                &[
                    "test",
                    "--workspace",
                    "tests::util_works",
                    "--color=never",
                    "--",
                    "--exact",
                ][..],
            ),
            (
                &["test", "--no-run", "--message-format=json"][..],
                &["test", "--workspace", "--no-run", "--message-format=json"][..],
            ),
            (
                &["llvm-cov", "--no-fail-fast", "--lcov"][..],
                &["llvm-cov", "--workspace", "--no-fail-fast", "--lcov"][..],
            ),
        ] {
            assert_eq!(args_of(&cargo_cmd(root, args)), want);
        }
        // A virtual manifest takes the flag too; it changes nothing there.
        std::fs::write(
            root.join("Cargo.toml"),
            "[workspace]\nmembers = [\"a\", \"b\"]\n",
        )
        .unwrap();
        assert_eq!(workspace_args(root, &["test"]), ["test", "--workspace"]);
    }

    /// #1508, negative: a single package, a probe for llvm-cov and a
    /// manifest croft cannot read run as they always did.
    #[test]
    fn cargo_runs_without_a_workspace_table_are_left_alone() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        std::fs::write(
            root.join("Cargo.toml"),
            "[package]\nname = \"solo\"\nversion = \"0.1.0\"\n# [workspace] in a comment\n",
        )
        .unwrap();
        assert_eq!(
            workspace_args(root, &["test", "--no-fail-fast"]),
            ["test", "--no-fail-fast"]
        );
        let ws = package_and_workspace();
        assert_eq!(
            workspace_args(ws.path(), &["llvm-cov", "--version"]),
            ["llvm-cov", "--version"]
        );
        std::fs::write(root.join("Cargo.toml"), "[workspace\nbroken").unwrap();
        assert_eq!(workspace_args(root, &["test"]), ["test"]);
        let none = tempfile::tempdir().unwrap();
        assert_eq!(workspace_args(none.path(), &["test"]), ["test"]);
    }

    /// #1534: a cancel whose run's end is dropped as stale by a re-root
    /// does not carry over to the new root's next run.
    #[test]
    fn a_cancel_dropped_by_a_re_root_does_not_cancel_the_next_run() {
        let (mut w, tx) = TestWorker::for_test();
        let mut panel = TestingPanel::new();
        w.cancel();
        w.set_root(PathBuf::from("/new"));
        tx.send((0, TestResponse::Finished { ok: None })).unwrap();
        tx.send((1, TestResponse::Started(Activity::Running)))
            .unwrap();
        tx.send((1, TestResponse::Finished { ok: Some(true) }))
            .unwrap();
        w.drain(&mut panel);
        assert!(!panel.take_cancelled(), "the new run is not cancelled");
        assert_eq!(panel.take_finished(), Some(Some(true)));
    }

    /// #1534: a cancelled coverage run's missing report does not replace
    /// the cancel with a coverage error.
    #[test]
    fn a_cancelled_coverage_run_reports_no_coverage_error() {
        let (mut w, tx) = TestWorker::for_test();
        let mut panel = TestingPanel::new();
        tx.send((0, TestResponse::Started(Activity::Running)))
            .unwrap();
        w.drain(&mut panel);
        w.cancel();
        tx.send((0, TestResponse::Coverage(Err(CoverageError::NoReport))))
            .unwrap();
        tx.send((0, TestResponse::Finished { ok: Some(false) }))
            .unwrap();
        w.drain(&mut panel);
        assert!(panel.take_cancelled());
        assert!(panel.take_coverage_error().is_none());
    }

    #[test]
    fn cargo_json_artifact_lines_yield_the_unit_test_binary() {
        // Shapes captured from a real `cargo test --no-run --message-format=json`
        // run: one compiler-artifact line per target, `executable` set only on
        // test binaries. A src/lib.rs + src/main.rs crate emits BOTH a lib and
        // a bin harness; last-wins used to hand a lib test to the bin harness,
        // which filters everything out and exits before a breakpoint binds.
        // Candidates rank lib first (unit tests overwhelmingly live there),
        // then bin, then integration, preserving cargo order within a rank.
        let lines = [
            r#"{"reason":"compiler-artifact","target":{"kind":["test"],"name":"cli","src_path":"/p/tests/cli.rs"},"profile":{"test":true},"executable":"/p/target/debug/deps/cli-2a2d806b06669aa7"}"#,
            r#"{"reason":"compiler-artifact","target":{"kind":["lib"],"name":"croft"},"profile":{"test":true},"executable":"/p/target/debug/deps/croft-lib00"}"#,
            r#"{"reason":"compiler-artifact","target":{"kind":["bin"],"name":"croft"},"profile":{"test":true},"executable":"/p/target/debug/deps/croft-bin00"}"#,
            r#"{"reason":"build-finished","success":true}"#,
        ];
        let joined = lines.join("\n");
        let got = test_binary_candidates(&joined);
        assert_eq!(
            got.iter().map(|c| c.path.clone()).collect::<Vec<_>>(),
            vec![
                PathBuf::from("/p/target/debug/deps/croft-lib00"),
                PathBuf::from("/p/target/debug/deps/croft-bin00"),
                PathBuf::from("/p/target/debug/deps/cli-2a2d806b06669aa7"),
            ],
            "lib outranks bin outranks integration; nothing is dropped"
        );
        // Target identity survives the ranking: the integration harness knows
        // its target name so a source file under tests/ can select it.
        assert_eq!(got[2].target, "cli");
        assert_eq!(got[2].src_path, PathBuf::from("/p/tests/cli.rs"));
        assert!(got[2].integration);
        assert!(!got[0].integration && !got[1].integration);
        // Only an integration target: it is still returned.
        assert_eq!(
            test_binary_candidates(lines[0])
                .iter()
                .map(|c| c.path.clone())
                .collect::<Vec<_>>(),
            vec![PathBuf::from("/p/target/debug/deps/cli-2a2d806b06669aa7")]
        );
        assert!(test_binary_candidates(lines[3]).is_empty());
        assert!(test_binary_candidates("").is_empty());
    }

    /// cargo's JSON does not say which target defines a test; with several
    /// harnesses each is asked to `--list` the name (fast, runs nothing) and
    /// the first that knows it wins.
    #[test]
    fn probe_picks_the_harness_that_actually_lists_the_test() {
        use std::os::unix::fs::PermissionsExt;
        let tmp = tempfile::tempdir().unwrap();
        let script = |name: &str, body: &str| {
            let p = tmp.path().join(name);
            std::fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
            std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
            p
        };
        let empty = script("bin_harness", r#"echo "0 tests, 0 benchmarks""#);
        let has = script("lib_harness", r#"echo "module::lib_side_test: test""#);
        assert_eq!(
            binary_containing_test(&[empty.clone(), has.clone()], "lib_side_test"),
            Some(has),
            "the harness listing the test wins even when probed second"
        );
        assert_eq!(
            binary_containing_test(&[empty], "lib_side_test"),
            None,
            "no harness knows the test -> no pick"
        );
        // libtest's filter arg is a SUBSTRING match, so a harness whose only
        // hit is a longer name (`lib_side_test_extra`) still prints a
        // `…: test` line; the probe must compare the listed name's final
        // segment exactly, not just spot any listing.
        let superstring = script(
            "super_harness",
            r#"echo "module::lib_side_test_extra: test""#,
        );
        assert_eq!(
            binary_containing_test(&[superstring], "lib_side_test"),
            None,
            "a superstring name is not the test"
        );
    }

    #[test]
    fn a_failed_workspace_build_is_an_error_not_a_partial_binary() {
        // cargo can emit one member's test executable before another member
        // fails to compile. Debugging must surface the build error, never
        // launch the partial artifact as if the build succeeded.
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            "[workspace]\nmembers = [\"good\", \"bad\"]\nresolver = \"2\"\n",
        )
        .unwrap();
        for (pkg, body) in [
            ("good", "#[test]\nfn probed_test() {}\n"),
            ("bad", "fn broken() { missing_symbol }\n"),
        ] {
            let dir = tmp.path().join(pkg);
            std::fs::create_dir_all(dir.join("src")).unwrap();
            std::fs::write(
                dir.join("Cargo.toml"),
                format!("[package]\nname = \"{pkg}\"\nversion = \"0.0.0\"\nedition = \"2021\"\n"),
            )
            .unwrap();
            std::fs::write(dir.join("src").join("lib.rs"), body).unwrap();
        }
        let err = build_test_binary(tmp.path(), "probed_test", None)
            .expect_err("a failed build must not yield a binary");
        assert!(
            err.to_string().contains("cargo"),
            "the error names the failed build, got: {err}"
        );
    }

    #[test]
    fn the_source_file_picks_the_harness_for_a_duplicate_test_name() {
        // A lib test and an integration test sharing a bare fn name: the
        // lib-first ranking used to run the lib's test when the gesture was
        // in tests/integ.rs. The gesture's file owns exactly one harness.
        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
        std::fs::create_dir_all(tmp.path().join("tests")).unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            "[package]\nname = \"dup\"\nversion = \"0.0.0\"\nedition = \"2021\"\n",
        )
        .unwrap();
        std::fs::write(
            tmp.path().join("src").join("lib.rs"),
            "#[cfg(test)]\nmod tests {\n    #[test]\n    fn same_name() {}\n}\n",
        )
        .unwrap();
        std::fs::write(
            tmp.path().join("tests").join("integ.rs"),
            "#[test]\nfn same_name() {}\n",
        )
        .unwrap();
        let stem_of = |p: &PathBuf| p.file_name().unwrap().to_string_lossy().to_string();
        let from_integration = build_test_binary(
            tmp.path(),
            "same_name",
            Some(&tmp.path().join("tests").join("integ.rs")),
        )
        .unwrap();
        assert!(
            stem_of(&from_integration).starts_with("integ"),
            "a tests/ file selects its integration harness, got {from_integration:?}"
        );
        let from_lib = build_test_binary(
            tmp.path(),
            "same_name",
            Some(&tmp.path().join("src").join("lib.rs")),
        )
        .unwrap();
        assert!(
            stem_of(&from_lib).starts_with("dup"),
            "a src/ file selects the lib harness, got {from_lib:?}"
        );
    }

    #[test]
    fn a_renamed_integration_target_still_owns_its_source_file() {
        // Explicit `[[test]]` entries can point a target at any path:
        // tests/custom_source.rs building target renamed_harness. Guessing
        // the target from the file stem found nothing, fell back to every
        // harness, and the lib-first probe handed the gesture to the unit
        // harness — whose exact filter then ran zero tests. cargo's JSON
        // knows each target's src_path; the gesture's file matches it
        // exactly, whatever the target is called.
        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
        std::fs::create_dir_all(tmp.path().join("tests")).unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            concat!(
                "[package]\nname = \"renamed\"\nversion = \"0.0.0\"\nedition = \"2021\"\n",
                "[[test]]\nname = \"renamed_harness\"\npath = \"tests/custom_source.rs\"\n",
            ),
        )
        .unwrap();
        std::fs::write(
            tmp.path().join("src").join("lib.rs"),
            "#[cfg(test)]\nmod tests {\n    #[test]\n    fn same_name() {}\n}\n",
        )
        .unwrap();
        std::fs::write(
            tmp.path().join("tests").join("custom_source.rs"),
            "#[test]\nfn same_name() {}\n",
        )
        .unwrap();
        let picked = build_test_binary(
            tmp.path(),
            "same_name",
            Some(&tmp.path().join("tests").join("custom_source.rs")),
        )
        .unwrap();
        assert!(
            picked
                .file_name()
                .unwrap()
                .to_string_lossy()
                .starts_with("renamed_harness"),
            "the [[test]] target owning the source wins, got {picked:?}"
        );
    }

    #[test]
    fn jest_args_mirror_the_vitest_builders() {
        // The jest argv used to be assembled inline at each call site; the
        // vitest escaping bug came exactly from that kind of divergence.
        assert_eq!(
            jest_one_args("tests/math.test.js::math::adds (1 + 1)"),
            vec![
                "--runTestsByPath",
                "tests/math.test.js",
                "-t",
                r"^math(?: | > |::)adds \(1 \+ 1\)$",
                "--json"
            ]
        );
        assert_eq!(
            jest_filter_args("parses [ tokens", false),
            vec!["-t", r"parses \[ tokens", "--json"]
        );
        assert_eq!(
            jest_filter_args("tests/a.test.js::group (x)", false),
            vec![
                "--runTestsByPath",
                "tests/a.test.js",
                "-t",
                r"group \(x\)",
                "--json"
            ]
        );
    }

    /// #1506: Run on one jest or vitest test names it by its whole describe
    /// chain, anchored at both ends, so `works` no longer also runs `works
    /// with negatives` or a `works` under another describe.
    #[test]
    fn one_js_test_is_named_by_its_whole_chain_anchored() {
        let id = "src/math.test.js::add::works";
        let jest = jest_one_args(id);
        assert_eq!(
            jest,
            vec![
                "--runTestsByPath",
                "src/math.test.js",
                "-t",
                "^add(?: | > |::)works$",
                "--json"
            ]
        );
        let vitest = vitest_one_args(id);
        assert_eq!(vitest[3], "^add(?: | > |::)works$", "{vitest:?}");
        let filter = regex::Regex::new(&jest[3]).unwrap();
        assert!(filter.is_match("add works"));
        assert!(filter.is_match("add > works"), "vitest 5's separator");
        for other in ["add works with negatives", "sub add works", "add  works"] {
            assert!(!filter.is_match(other), "{other} must not run");
        }
        // A test outside any describe is its title alone.
        assert_eq!(
            exact_title_anchor("src/a.test.js::works").as_deref(),
            Some("^works$")
        );
        // Regex syntax in a title is still literal.
        let odd =
            regex::Regex::new(&exact_title_anchor("a.test.js::x.y::[1] $ok").unwrap()).unwrap();
        assert!(odd.is_match("x.y [1] $ok") && !odd.is_match("xzy [1] $ok"));
    }

    /// #1506: jest reads a bare file argument as a path regex, so
    /// `src/math.test.js` also ran `legacy/src/math.test.js`. Every run
    /// that names a file names it with `--runTestsByPath`.
    #[test]
    fn every_jest_run_names_its_file_as_an_exact_path() {
        assert_eq!(
            jest_filter_args("src/math.test.js", true),
            vec!["--runTestsByPath", "src/math.test.js", "--json"]
        );
        assert_eq!(
            jest_filter_args("src/math.test.js::add", true),
            vec![
                "--runTestsByPath",
                "src/math.test.js",
                "-t",
                "^add(?: | > )",
                "--json"
            ]
        );
        let coverage = coverage_scope_args(
            Runner::Jest,
            &CoverageScope {
                name: String::from("src/math.test.js::add::works"),
                exact: true,
                suite: false,
            },
        );
        assert_eq!(
            coverage,
            vec![
                "--runTestsByPath",
                "src/math.test.js",
                "-t",
                "^add(?: | > |::)works$"
            ]
        );
    }

    /// #1506, negative: run-at-cursor's bare title names no file, so it
    /// gets neither `--runTestsByPath` nor an anchor.
    #[test]
    fn a_bare_title_run_stays_an_unanchored_search() {
        assert_eq!(
            jest_filter_args("works", false),
            vec!["-t", "works", "--json"]
        );
        assert_eq!(
            vitest_filter_args("works", false),
            vec!["run", "-t", "works", "--reporter=tap-flat"]
        );
        assert_eq!(exact_title_anchor("src/math.test.js"), None);
    }

    /// A suite click's `-t` must not be a bare substring: describe `auth`
    /// would sweep `auth-helper handles retries` in the same file while the
    /// panel marks only the suite's own cases as Running. vitest and jest
    /// both match `-t` against the space-joined describe chain + title
    /// (vitest `getTaskFullName`, jest `getTestID`), so the anchor is
    /// `^segments… ` with the closing join space.
    #[test]
    fn a_js_suite_click_anchors_the_name_filter_to_the_describe_chain() {
        assert_eq!(
            vitest_filter_args("tests/a.test.js::auth", true),
            vec![
                "run",
                "tests/a.test.js",
                "-t",
                "^auth(?: | > )",
                "--reporter=tap-flat"
            ]
        );
        assert_eq!(
            jest_filter_args("tests/a.test.js::group (x)::inner", true),
            vec![
                "--runTestsByPath",
                "tests/a.test.js",
                "-t",
                r"^group \(x\)(?: | > |::)inner(?: | > )",
                "--json"
            ]
        );
        // A suite that is the whole file needs no `-t`: the positional file
        // argument already scopes the run exactly.
        assert_eq!(
            vitest_filter_args("tests/a.test.js", true),
            vec!["run", "tests/a.test.js", "--reporter=tap-flat"]
        );
    }

    #[test]
    fn coverage_runs_keep_each_runners_output_and_write_lcov_into_the_dir() {
        let dir = Path::new("/t/cov");
        let py = coverage_args(Runner::Pytest, dir);
        assert!(
            py.contains(&"--cov-report=lcov:/t/cov/lcov.info".to_string()),
            "{py:?}"
        );
        assert!(
            py.contains(&"--cov-branch".to_string())
                && py.contains(&PYTEST_RUN_VERBOSITY.to_string())
        );
        let vi = coverage_args(Runner::Vitest, dir);
        assert!(vi.contains(&"--reporter=tap-flat".to_string()));
        assert!(
            vi.contains(&"--coverage.reportsDirectory=/t/cov".to_string()),
            "{vi:?}"
        );
        let je = coverage_args(Runner::Jest, dir);
        assert!(je.contains(&"--json".to_string()));
        assert!(je.contains(&"--coverageDirectory=/t/cov".to_string()));
        let ca = coverage_args(Runner::Cargo, dir);
        assert_eq!(ca[0], "llvm-cov");
        assert_eq!(ca.last().unwrap(), "/t/cov/lcov.info");
        assert_eq!(coverage_report(dir), Path::new("/t/cov/lcov.info"));
    }

    #[test]
    fn a_scoped_coverage_run_narrows_to_the_test_as_a_plain_run_would() {
        let exact = |n: &str| CoverageScope {
            name: n.into(),
            exact: true,
            suite: false,
        };
        let loose = |n: &str| CoverageScope {
            name: n.into(),
            exact: false,
            suite: false,
        };
        let suite = |n: &str| CoverageScope {
            name: n.into(),
            exact: false,
            suite: true,
        };
        // A suite selects what its plain run selects (#263): cargo anchored
        // at `suite::`, pytest by node-ID prefix, JS by file.
        assert_eq!(
            coverage_scope_args(Runner::Cargo, &suite("parse")),
            vec!["parse::"]
        );
        assert_eq!(
            coverage_scope_args(Runner::Pytest, &suite("test_x")),
            vec!["test_x"]
        );
        assert_eq!(
            coverage_scope_args(Runner::Vitest, &suite("tests/a.test.js")),
            vitest_filter_args("tests/a.test.js", true)
                .into_iter()
                .filter(|a| a != "run" && !a.starts_with("--reporter="))
                .collect::<Vec<_>>()
        );
        assert_eq!(
            coverage_scope_args(Runner::Cargo, &exact("parse::a")),
            vec!["parse::a", "--", "--exact"]
        );
        assert_eq!(
            coverage_scope_args(Runner::Cargo, &loose("parse")),
            vec!["parse"]
        );
        assert_eq!(
            coverage_scope_args(Runner::Pytest, &exact("tests/test_x.py::test_a")),
            vec!["tests/test_x.py::test_a"]
        );
        assert_eq!(
            coverage_scope_args(Runner::Pytest, &loose("test_a")),
            vec!["-k", "test_a"]
        );
        // The coverage args already say `run`, the reporter and `--json`:
        // the scope adds only the selection, so none appears twice.
        let vi = coverage_scope_args(Runner::Vitest, &exact("tests/a.test.js::adds"));
        assert!(
            !vi.iter()
                .any(|a| a == "run" || a.starts_with("--reporter=")),
            "{vi:?}"
        );
        assert!(vi.contains(&String::from("tests/a.test.js")) && vi.contains(&String::from("-t")));
        let je = coverage_scope_args(Runner::Jest, &exact("tests/a.test.js::adds"));
        assert!(!je.contains(&String::from("--json")), "{je:?}");
        assert!(je.contains(&String::from("tests/a.test.js")));
    }

    #[test]
    fn the_install_offer_follows_the_projects_package_manager() {
        let d = tempfile::tempdir().unwrap();
        assert_eq!(
            coverage_install(Runner::Jest, d.path()),
            None,
            "jest has coverage built in"
        );
        assert_eq!(
            coverage_install(Runner::Pytest, d.path()).unwrap().1,
            "python3 -m pip install pytest-cov"
        );
        std::fs::write(d.path().join("uv.lock"), "").unwrap();
        assert_eq!(
            coverage_install(Runner::Pytest, d.path()).unwrap().1,
            "uv add --dev pytest-cov"
        );
        assert_eq!(
            coverage_install(Runner::Vitest, d.path()).unwrap().1,
            "npm install -D @vitest/coverage-v8"
        );
        std::fs::write(d.path().join("pnpm-lock.yaml"), "").unwrap();
        assert_eq!(
            coverage_install(Runner::Vitest, d.path()).unwrap().1,
            "pnpm add -D @vitest/coverage-v8"
        );
        assert_eq!(
            coverage_install(Runner::Cargo, d.path()).unwrap().0,
            "cargo-llvm-cov"
        );
    }

    /// #263: a monorepo hoists `@vitest/coverage-v8` to the repository's
    /// `node_modules`, where Node resolves it from a package below.
    #[test]
    fn vitest_coverage_is_found_in_a_hoisted_node_modules() {
        let tmp = tempfile::tempdir().unwrap();
        let pkg = tmp.path().join("packages/app");
        std::fs::create_dir_all(&pkg).unwrap();
        assert!(!coverage_tool_present(Runner::Vitest, &pkg));
        std::fs::create_dir_all(tmp.path().join("node_modules/@vitest/coverage-v8")).unwrap();
        assert!(coverage_tool_present(Runner::Vitest, &pkg));
    }

    /// A stand-in project venv under `root/venv`: `bin/pytest` marks pytest
    /// installed, and `bin/python` is a script that saves its arguments
    /// beside itself (`bin/python.args`) and then runs `body`.
    #[cfg(unix)]
    fn fake_venv(root: &Path, venv: &str, body: &str) {
        use std::os::unix::fs::PermissionsExt;
        let bin = root.join(venv).join("bin");
        std::fs::create_dir_all(&bin).unwrap();
        let python = format!("echo \"$*\" > \"$0.args\"\n{body}");
        for (name, text) in [("python", python.as_str()), ("pytest", "exit 0")] {
            let p = bin.join(name);
            std::fs::write(&p, format!("#!/bin/sh\n{text}\n")).unwrap();
            std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
        }
    }

    /// #1535: Rerun Failed Tests runs each name exactly, all of them even
    /// after one fails, and the run ends once: failed if any failed, passed
    /// only when every one did.
    #[cfg(unix)]
    #[test]
    fn run_many_runs_every_name_and_fails_if_any_did() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        std::fs::write(root.join("pyproject.toml"), "[project]\nname = \"g\"\n").unwrap();
        let (tx, rx) = std::sync::mpsc::channel();
        let etx = EpochTx {
            tx: &tx,
            epoch: 0,
            codeql: Path::new("codeql"),
            extensions: Path::new(NO_EXTENSIONS),
            control: &RunControl::default(),
            request: 1,
            owners: None,
            tag: None,
        };
        let log = root.join(".venv/bin/python.log");
        let ran = |names: &[&str]| {
            let _ = std::fs::remove_file(&log);
            let names: Vec<String> = names.iter().map(|n| n.to_string()).collect();
            run_many(root, &etx, &names);
            let finished: Vec<Option<bool>> = rx
                .try_iter()
                .filter_map(|(_, r)| match r {
                    TestResponse::Finished { ok } => Some(ok),
                    _ => None,
                })
                .collect();
            let calls = std::fs::read_to_string(&log).unwrap_or_default();
            (calls.lines().count(), finished)
        };

        fake_venv(
            root,
            ".venv",
            "echo \"$*\" >> \"$0.log\"\ncase \"$*\" in *test_b*) exit 1;; *test_gone*) exit 0;; esac\nfor a; do last=$a; done\necho \"$last PASSED\"\nexit 0",
        );
        assert_eq!(
            ran(&["t.py::test_a", "t.py::test_b", "t.py::test_c"]),
            (3, vec![Some(false)]),
            "test_c still runs after test_b fails, and the run ends once, failed"
        );
        let calls = std::fs::read_to_string(&log).unwrap();
        assert!(calls.contains("t.py::test_a") && calls.contains("t.py::test_c"));
        assert_eq!(
            ran(&["t.py::test_a", "t.py::test_c"]),
            (2, vec![Some(true)]),
            "every one passing is a passed run"
        );
        assert_eq!(
            ran(&["t.py::test_a", "t.py::test_gone"]),
            (2, vec![Some(false)]),
            "a name the runner reported no result for, though it exited 0, fails the run"
        );
    }

    /// A project whose pytest `addopts` is `addopts`, with a venv python
    /// that answers the way pytest does for the verbosity it ends up at:
    /// `addopts` comes first, `-v` / `-q` (and `-qq`) count up and down
    /// from there, and `--verbosity=N` sets the level outright. Collection
    /// prints node ids only at -1; a run prints `<id> PASSED` lines only
    /// from 1 up, and dots below that.
    #[cfg(unix)]
    fn pytest_project_with_addopts(root: &Path, addopts: &str) {
        std::fs::write(
            root.join("pyproject.toml"),
            format!("[tool.pytest.ini_options]\naddopts = \"{addopts}\"\n"),
        )
        .unwrap();
        let body = format!(
            r#"shift 2
v=0
collect=0
for a in {addopts} "$@"; do
  case "$a" in
    -v) v=$((v+1)) ;;
    -vv) v=$((v+2)) ;;
    -q) v=$((v-1)) ;;
    -qq) v=$((v-2)) ;;
    --verbosity=*) v="${{a#--verbosity=}}" ;;
    --collect-only) collect=1 ;;
  esac
done
if [ "$collect" = 1 ]; then
  if [ "$v" -le -2 ]; then echo "tests/test_x.py: 2"
  elif [ "$v" -eq -1 ]; then echo "tests/test_x.py::test_a"; echo "tests/test_x.py::test_b"
  else echo "<Module tests/test_x.py>"; echo "  <Function test_a>"; echo "  <Function test_b>"
  fi
  echo "2 tests collected in 0.01s"
  exit 0
fi
if [ "$v" -ge 1 ]; then
  echo "tests/test_x.py::test_a PASSED"
  echo "tests/test_x.py::test_b FAILED"
else
  echo "tests/test_x.py .F"
fi
echo "1 failed, 1 passed in 0.01s"
exit 1"#
        );
        fake_venv(root, ".venv", &body);
    }

    /// What `f` sends: the cases by name and status, and the run's verdict.
    fn collect_responses(
        root: &Path,
        f: impl Fn(&Path, &EpochTx),
    ) -> (Vec<(String, TestStatus)>, Option<Option<bool>>) {
        let (tx, rx) = std::sync::mpsc::channel();
        let etx = EpochTx {
            tx: &tx,
            epoch: 0,
            codeql: Path::new("codeql"),
            extensions: Path::new(NO_EXTENSIONS),
            control: &RunControl::default(),
            request: 1,
            owners: None,
            tag: None,
        };
        f(root, &etx);
        let mut cases = Vec::new();
        let mut finished = None;
        for (_, r) in rx.try_iter() {
            match r {
                TestResponse::Case(c) => cases.push((c.name, c.status)),
                TestResponse::Finished { ok } => finished = Some(ok),
                _ => {}
            }
        }
        (cases, finished)
    }

    /// The issue's maturin layout (#1408): a crate with one Rust test, and a
    /// pytest project beside it whose venv python answers as pytest does.
    #[cfg(unix)]
    fn maturin_project(root: &Path) {
        pytest_project_with_addopts(root, "");
        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::write(
            root.join("Cargo.toml"),
            "[package]\nname = \"fastmath\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
        )
        .unwrap();
        std::fs::write(
            root.join("src/lib.rs"),
            "#[cfg(test)]\nmod tests {\n    #[test]\n    fn adds() {}\n}\n",
        )
        .unwrap();
    }

    /// What `f` sends through a sender that records which runner listed
    /// each test, as the worker loop's does.
    fn collect_with_owners(
        root: &Path,
        owners: &RefCell<BTreeMap<String, Runner>>,
        f: impl Fn(&Path, &EpochTx),
    ) -> (Vec<(String, TestStatus)>, Option<Option<bool>>) {
        let (tx, rx) = std::sync::mpsc::channel();
        let etx = EpochTx {
            tx: &tx,
            epoch: 0,
            codeql: Path::new("codeql"),
            extensions: Path::new(NO_EXTENSIONS),
            control: &RunControl::default(),
            request: 1,
            owners: Some(owners),
            tag: None,
        };
        f(root, &etx);
        let mut cases = Vec::new();
        let mut finished = None;
        for (_, r) in rx.try_iter() {
            match r {
                TestResponse::Case(c) => cases.push((c.name, c.status)),
                TestResponse::Finished { ok } => finished = Some(ok),
                _ => {}
            }
        }
        (cases, finished)
    }

    /// #1408: a maturin crate's Testing view lists its Rust test and its
    /// pytest tests together, and Run All runs both runners.
    #[cfg(unix)]
    #[test]
    fn a_maturin_crate_lists_and_runs_its_rust_and_python_tests() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        maturin_project(root);
        let owners = RefCell::new(BTreeMap::new());
        let (cases, finished) = collect_with_owners(root, &owners, |r, t| discover(r, t, false));
        let names: Vec<&str> = cases.iter().map(|(n, _)| n.as_str()).collect();
        assert_eq!(
            names,
            [
                "tests::adds",
                "tests/test_x.py::test_a",
                "tests/test_x.py::test_b"
            ],
        );
        assert_eq!(finished, Some(Some(true)));
        assert_eq!(owners.borrow()["tests::adds"], Runner::Cargo);
        assert_eq!(owners.borrow()["tests/test_x.py::test_a"], Runner::Pytest);

        let (cases, finished) = collect_with_owners(root, &owners, run_all);
        assert!(
            cases.contains(&(String::from("tests::adds"), TestStatus::Passed)),
            "{cases:?}"
        );
        assert!(
            cases.contains(&(String::from("tests/test_x.py::test_b"), TestStatus::Failed)),
            "{cases:?}"
        );
        assert_eq!(
            finished,
            Some(Some(false)),
            "pytest's failure fails the run"
        );
    }

    /// #1408: a run from a `.py` file, or of a test pytest listed, goes to
    /// pytest in a maturin crate; it used to run `cargo test` and report
    /// that no test ran.
    #[cfg(unix)]
    #[test]
    fn a_python_test_in_a_maturin_crate_runs_under_pytest() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        maturin_project(root);
        let py = root.join("tests/test_x.py");
        let owners = RefCell::new(BTreeMap::new());
        let (cases, _) = collect_with_owners(root, &owners, |r, t| {
            run_filter_in(r, t, "test_a", false, Some(&py))
        });
        assert!(
            cases.contains(&(String::from("tests/test_x.py::test_a"), TestStatus::Passed)),
            "{cases:?}"
        );
        collect_with_owners(root, &owners, |r, t| discover(r, t, false));
        let (cases, _) = collect_with_owners(root, &owners, |r, t| {
            run_one(r, t, "tests/test_x.py::test_a")
        });
        assert!(
            cases.contains(&(String::from("tests/test_x.py::test_a"), TestStatus::Passed)),
            "{cases:?}"
        );
    }

    /// #1408: the runner for a run is the file's language, then whichever
    /// runner listed the test (or a test in the suite), then the folder's
    /// first.
    #[test]
    fn a_run_goes_to_its_files_runner_then_the_one_that_listed_it() {
        let both = [Runner::Cargo, Runner::Pytest];
        let owners = BTreeMap::from([
            (String::from("tests/test_api.py::test_py"), Runner::Pytest),
            (String::from("tests::adds"), Runner::Cargo),
        ]);
        let py = Path::new("/w/tests/test_api.py");
        let rs = Path::new("/w/src/lib.rs");
        assert_eq!(
            choose_runner(&both, &owners, "test_py", Some(py)),
            Some(Runner::Pytest)
        );
        assert_eq!(
            choose_runner(&both, &owners, "adds", Some(rs)),
            Some(Runner::Cargo)
        );
        assert_eq!(
            choose_runner(&both, &owners, "tests/test_api.py::test_py", None),
            Some(Runner::Pytest)
        );
        assert_eq!(
            choose_runner(&both, &owners, "tests/test_api.py", None),
            Some(Runner::Pytest),
            "a suite goes to the runner of a test under it"
        );
        assert_eq!(runner_for_file(&both, Some(py)), Some(Runner::Pytest));
        let web = [Runner::Pytest, Runner::Jest];
        assert_eq!(
            runner_for_file(&web, Some(Path::new("/w/ui/a.test.tsx"))),
            Some(Runner::Jest)
        );
    }

    /// #1408: a suite owns only what sits under it at the `::` separator.
    /// Rust's `tests` suite beside pytest's `tests/...` nodes (which sort
    /// first) is Cargo's, not pytest's.
    #[test]
    fn a_suite_goes_to_the_runner_of_a_test_under_its_separator() {
        let both = [Runner::Pytest, Runner::Cargo];
        let owners = BTreeMap::from([
            (String::from("tests/test_x.py::test_a"), Runner::Pytest),
            (String::from("tests::adds"), Runner::Cargo),
        ]);
        assert_eq!(
            choose_runner(&both, &owners, "tests", None),
            Some(Runner::Cargo)
        );
    }

    /// #1408: where Vitest and Jest both claim the folder, a JS file goes to
    /// the runner that listed it, not to whichever comes first; with no
    /// listing yet it falls back to the extension order.
    #[test]
    fn a_js_file_goes_to_the_runner_that_listed_its_tests() {
        let both = [Runner::Vitest, Runner::Jest];
        let owners = BTreeMap::from([
            (String::from("ui/a.test.ts::adds"), Runner::Jest),
            (String::from("web/b.test.ts::subs"), Runner::Vitest),
        ]);
        let jest_file = Path::new("/w/ui/a.test.ts");
        let vitest_file = Path::new("/w/web/b.test.ts");
        assert_eq!(
            choose_runner(&both, &owners, "adds", Some(jest_file)),
            Some(Runner::Jest)
        );
        assert_eq!(
            choose_runner(&both, &owners, "subs", Some(vitest_file)),
            Some(Runner::Vitest)
        );
        assert_eq!(
            choose_runner(&both, &owners, "ui/a.test.ts::adds", Some(jest_file)),
            Some(Runner::Jest)
        );
        assert_eq!(
            choose_runner(&both, &BTreeMap::new(), "adds", Some(jest_file)),
            Some(Runner::Vitest)
        );
    }

    /// #1408, negative: a file in a language the folder has no runner for,
    /// a name no runner listed, or a listing by a runner no longer there
    /// falls back to the folder's first runner; no runner at all is none.
    #[test]
    fn a_run_nothing_claims_goes_to_the_folders_first_runner() {
        let both = [Runner::Cargo, Runner::Pytest];
        let stale = BTreeMap::from([(String::from("x"), Runner::Go)]);
        let md = Path::new("/w/README.md");
        let go = Path::new("/w/main_test.go");
        assert_eq!(
            choose_runner(&both, &stale, "y", Some(md)),
            Some(Runner::Cargo)
        );
        assert_eq!(
            choose_runner(&both, &stale, "x", Some(go)),
            Some(Runner::Cargo)
        );
        assert_eq!(runner_for_file(&both, None), Some(Runner::Cargo));
        assert_eq!(runner_for_file(&[], Some(md)), None);
        assert_eq!(choose_runner(&[], &stale, "x", None), None);
    }

    /// #1502: a project with `-q` in its pytest `addopts` (the pytest docs'
    /// own `-ra -q` example) listed no tests: croft's `-q` stacked on it and
    /// collection printed per-file counts instead of node ids. Discovery now
    /// sets the verbosity outright.
    #[cfg(unix)]
    #[test]
    fn discovery_lists_pytest_tests_under_a_quiet_addopts() {
        for addopts in ["-ra -q", "-qq", "", "-v"] {
            let tmp = tempfile::tempdir().unwrap();
            let root = tmp.path();
            pytest_project_with_addopts(root, addopts);
            let (cases, finished) = collect_responses(root, |r, t| discover(r, t, false));
            assert_eq!(
                cases,
                vec![
                    (String::from("tests/test_x.py::test_a"), TestStatus::NotRun),
                    (String::from("tests/test_x.py::test_b"), TestStatus::NotRun),
                ],
                "addopts {addopts:?}"
            );
            assert_eq!(finished, Some(Some(true)), "addopts {addopts:?}");
        }
    }

    /// #1502: with `-q` in `addopts`, croft's `-v` cancelled out, the run
    /// printed dots, no result was parsed and the view said "Run failed".
    /// Runs now ask for verbosity 1 outright, whatever `addopts` holds.
    #[cfg(unix)]
    #[test]
    fn a_pytest_run_reports_results_under_a_quiet_addopts() {
        for addopts in ["-ra -q", "-qq", "", "-v"] {
            let tmp = tempfile::tempdir().unwrap();
            let root = tmp.path();
            pytest_project_with_addopts(root, addopts);
            let expected = vec![
                (String::from("tests/test_x.py::test_a"), TestStatus::Passed),
                (String::from("tests/test_x.py::test_b"), TestStatus::Failed),
            ];
            let (cases, _) = collect_responses(root, run_all);
            assert_eq!(cases, expected, "run all, addopts {addopts:?}");
            let (cases, _) = collect_responses(root, |r, t| run_one(r, t, "tests/test_x.py"));
            assert_eq!(cases, expected, "run one, addopts {addopts:?}");
        }
    }

    /// #845: `pytest --collect-only` exits 2 on a collection error, having
    /// listed nothing. Discovery used to drop that status and finish exactly
    /// as an empty project does, so the view offered a run that would fail
    /// the same way. The status now goes back with `Finished`, a listing
    /// that works included.
    #[cfg(unix)]
    #[test]
    fn a_listing_that_errors_is_a_failed_discovery() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        std::fs::write(root.join("pyproject.toml"), "[project]\nname = \"g\"\n").unwrap();
        assert_eq!(
            runner_for(Path::new(NO_EXTENSIONS), root),
            Some(Runner::Pytest)
        );
        let (tx, rx) = std::sync::mpsc::channel();
        let etx = EpochTx {
            tx: &tx,
            epoch: 0,
            codeql: Path::new("codeql"),
            extensions: Path::new(NO_EXTENSIONS),
            control: &RunControl::default(),
            request: 1,
            owners: None,
            tag: None,
        };
        let discovered = || {
            discover(root, &etx, false);
            let mut cases = Vec::new();
            let mut finished = None;
            for (_, r) in rx.try_iter() {
                match r {
                    TestResponse::Case(c) => cases.push(c.name),
                    TestResponse::Finished { ok } => finished = Some(ok),
                    _ => {}
                }
            }
            (cases, finished)
        };

        fake_venv(root, ".venv", "echo tests/test_g.py::test_total\nexit 0");
        assert_eq!(
            discovered(),
            (
                vec![String::from("tests/test_g.py::test_total")],
                Some(Some(true))
            )
        );
        fake_venv(
            root,
            ".venv",
            "echo \"E   ModuleNotFoundError: No module named 'groceries'\" >&2\nexit 2",
        );
        assert_eq!(
            discovered(),
            (Vec::new(), Some(Some(false))),
            "a collection error is a failed discovery, not an empty project"
        );
        // pytest's exit 5 ("no tests were collected") is an empty project.
        fake_venv(root, ".venv", "echo 'no tests ran in 0.01s'\nexit 5");
        assert_eq!(discovered(), (Vec::new(), Some(Some(true))));
    }

    /// #1503: with `-n auto` in a project's addopts, pytest-xdist prints each
    /// result outcome first. Run All read none of them and, the run exiting 1
    /// for its failed test, the view showed "Run failed" over an empty list.
    #[cfg(unix)]
    #[test]
    fn run_all_reads_results_under_pytest_xdist() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        std::fs::write(root.join("pyproject.toml"), "[project]\nname = \"x\"\n").unwrap();
        fake_venv(
            root,
            ".venv",
            "cat <<'EOF'\n\
             ============================= test session starts ==============================\n\
             created: 2/2 workers\n\
             2 workers [2 items]\n\
             \n\
             scheduling tests via LoadScheduling\n\
             \n\
             [gw0] [ 50%] PASSED tests/test_x.py::test_a \n\
             [gw1] [100%] FAILED tests/test_x.py::test_b \n\
             =========================== short test summary info ============================\n\
             FAILED tests/test_x.py::test_b - assert False\n\
             ========================= 1 failed, 1 passed in 0.61s ==========================\n\
             EOF\nexit 1",
        );
        let (tx, rx) = std::sync::mpsc::channel();
        let etx = EpochTx {
            tx: &tx,
            epoch: 0,
            codeql: Path::new("codeql"),
            extensions: Path::new(NO_EXTENSIONS),
            control: &RunControl::default(),
            request: 1,
            owners: None,
            tag: None,
        };
        run_all(root, &etx);
        let cases: Vec<(String, TestStatus)> = rx
            .try_iter()
            .filter_map(|(_, r)| match r {
                TestResponse::Case(c) => Some((c.name, c.status)),
                _ => None,
            })
            .collect();
        assert_eq!(
            cases,
            vec![
                (String::from("tests/test_x.py::test_a"), TestStatus::Passed),
                (String::from("tests/test_x.py::test_b"), TestStatus::Failed),
            ]
        );
    }

    /// #845: a project venv with pytest in it runs pytest as a module of the
    /// venv's own python, which puts the project root on `sys.path` (the
    /// bare `pytest` script does not, and a flat project's tests then fail
    /// to import its modules). Discovery and runs launch it the same way.
    #[cfg(unix)]
    #[test]
    fn pytest_runs_as_a_module_of_the_project_venvs_python() {
        for venv in [".venv", "venv"] {
            let tmp = tempfile::tempdir().unwrap();
            let root = tmp.path();
            fake_venv(root, venv, "exit 0");
            let python = root.join(venv).join("bin").join("python");
            assert_eq!(
                pytest_launch(root),
                (python.clone(), &["-m", "pytest"][..]),
                "{venv}"
            );
            let args = |cmd: Command| {
                cmd.get_args()
                    .map(|a| a.to_string_lossy().into_owned())
                    .collect::<Vec<_>>()
            };
            let collect = pytest_cmd(root, &["--collect-only", "-q", "--color=no"]);
            assert_eq!(collect.get_program(), python.as_os_str());
            assert_eq!(
                args(collect),
                ["-m", "pytest", "--collect-only", "-q", "--color=no"]
            );
            assert_eq!(
                args(pytest_cmd(root, &["-v", "--color=no", "t.py::a"])),
                ["-m", "pytest", "-v", "--color=no", "t.py::a"]
            );
        }
        // A venv without pytest in it is not where pytest lives.
        let tmp = tempfile::tempdir().unwrap();
        let bin = tmp.path().join(".venv").join("bin");
        std::fs::create_dir_all(&bin).unwrap();
        std::fs::write(bin.join("python"), "").unwrap();
        assert_ne!(pytest_launch(tmp.path()).0, bin.join("python"));
    }

    /// #845 guard: only exit 0 and pytest's 5 ("no tests were collected")
    /// read as a listing that worked. A lister that exits 1, or dies to a
    /// signal with no exit code at all, is a failed discovery, never an
    /// empty project, even when it printed a test id before dying.
    #[cfg(unix)]
    #[test]
    fn a_listing_that_exits_one_or_dies_to_a_signal_is_a_failed_discovery() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        std::fs::write(root.join("pyproject.toml"), "[project]\nname = \"g\"\n").unwrap();
        let (tx, rx) = std::sync::mpsc::channel();
        let etx = EpochTx {
            tx: &tx,
            epoch: 0,
            codeql: Path::new("codeql"),
            extensions: Path::new(NO_EXTENSIONS),
            control: &RunControl::default(),
            request: 1,
            owners: None,
            tag: None,
        };
        let finished = || {
            discover(root, &etx, false);
            rx.try_iter().find_map(|(_, r)| match r {
                TestResponse::Finished { ok } => Some(ok),
                _ => None,
            })
        };
        fake_venv(root, ".venv", "exit 1");
        assert_eq!(finished(), Some(Some(false)), "exit 1");
        fake_venv(
            root,
            ".venv",
            "echo tests/test_g.py::test_total\nkill -9 $$",
        );
        assert_eq!(finished(), Some(Some(false)), "killed by a signal");
    }

    /// A `bin` dir to stand for `PATH`: a `pytest` script, and a `python3`
    /// that appends each command line it gets to `python3.log` beside
    /// itself and answers `-c "import pytest"` with `probe_exit`.
    #[cfg(unix)]
    fn fake_path_bin(dir: &Path, probe_exit: i32) -> PathBuf {
        use std::os::unix::fs::PermissionsExt;
        let bin = dir.join("bin");
        std::fs::create_dir_all(&bin).unwrap();
        let python =
            format!("echo \"$*\" >> \"$0.log\"\n[ \"$1\" = -c ] && exit {probe_exit}\nexit 0");
        for (name, text) in [("python3", python.as_str()), ("pytest", "exit 0")] {
            let p = bin.join(name);
            std::fs::write(&p, format!("#!/bin/sh\n{text}\n")).unwrap();
            std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
        }
        bin
    }

    /// #845: with no project venv, a `python3` that can import pytest runs
    /// it as `python3 -m pytest`, ahead of a `pytest` script on PATH that
    /// may belong to another interpreter (a uv tool's, which cannot import
    /// the project's dependencies). The probe runs once per root.
    #[cfg(unix)]
    #[test]
    fn without_a_venv_a_python3_that_has_pytest_runs_it_as_a_module() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("proj");
        std::fs::create_dir_all(&root).unwrap();
        let bin = fake_path_bin(tmp.path(), 0);
        let path = bin.clone().into_os_string();
        let want = (bin.join("python3"), &["-m", "pytest"][..]);
        assert_eq!(pytest_launch_on(&root, Some(&path)), want);
        assert_eq!(pytest_launch_on(&root, Some(&path)), want);
        let log = std::fs::read_to_string(bin.join("python3.log")).unwrap_or_default();
        assert_eq!(log, "-c import pytest\n", "probed once");
    }

    /// #845 guard: a `python3` that cannot import pytest is not used for
    /// it; the `pytest` script on PATH runs as before.
    #[cfg(unix)]
    #[test]
    fn without_a_venv_a_python3_lacking_pytest_leaves_the_pytest_script() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("proj");
        std::fs::create_dir_all(&root).unwrap();
        let bin = fake_path_bin(tmp.path(), 1);
        let path = bin.clone().into_os_string();
        assert_eq!(
            pytest_launch_on(&root, Some(&path)),
            (bin.join("pytest"), &[][..])
        );
    }

    /// A stand-in project venv with no `pytest` script: `bin/python` logs
    /// each command line to `bin/python.log` and answers `-c "import
    /// pytest"` with `probe_exit`.
    #[cfg(unix)]
    fn scriptless_venv(root: &Path, probe_exit: i32) -> PathBuf {
        use std::os::unix::fs::PermissionsExt;
        let bin = root.join(".venv").join("bin");
        std::fs::create_dir_all(&bin).unwrap();
        let python = bin.join("python");
        std::fs::write(
            &python,
            format!(
                "#!/bin/sh\necho \"$*\" >> \"$0.log\"\n[ \"$1\" = -c ] && exit {probe_exit}\nexit 0\n"
            ),
        )
        .unwrap();
        std::fs::set_permissions(&python, std::fs::Permissions::from_mode(0o755)).unwrap();
        python
    }

    /// #845 review: `python -m pytest` needs the module, not the console
    /// script, so a venv whose python imports pytest is where pytest lives
    /// even with no `bin/pytest` beside it.
    #[cfg(unix)]
    #[test]
    fn a_venv_whose_python_imports_pytest_runs_it_without_the_script() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("proj");
        let python = scriptless_venv(&root, 0);
        let bin = fake_path_bin(tmp.path(), 0);
        let path = bin.clone().into_os_string();
        assert_eq!(
            pytest_launch_on(&root, Some(&path)),
            (python, &["-m", "pytest"][..])
        );
        assert!(!bin.join("python3.log").exists(), "python3 was not probed");
    }

    /// #845 review guard: the probe is the fallback, not the rule. A venv
    /// with the script is used without asking its python, and a venv whose
    /// python cannot import pytest (and has no script) is passed over.
    #[cfg(unix)]
    #[test]
    fn a_venv_is_probed_only_without_the_script_and_skipped_when_it_lacks_pytest() {
        let tmp = tempfile::tempdir().unwrap();
        let with_script = tmp.path().join("a");
        let python = scriptless_venv(&with_script, 0);
        let script = python.with_file_name("pytest");
        std::fs::write(&script, "#!/bin/sh\nexit 0\n").unwrap();
        assert_eq!(pytest_launch_on(&with_script, None).0, python);
        assert!(
            !python.with_file_name("python.log").exists(),
            "a venv with the script is not probed"
        );

        let lacking = tmp.path().join("b");
        let python = scriptless_venv(&lacking, 1);
        let bin = fake_path_bin(tmp.path(), 0);
        let path = bin.clone().into_os_string();
        assert_eq!(
            pytest_launch_on(&lacking, Some(&path)),
            (bin.join("python3"), &["-m", "pytest"][..]),
            "a venv without pytest is not where it lives"
        );
        assert_eq!(
            std::fs::read_to_string(python.with_file_name("python.log")).unwrap(),
            "-c import pytest\n",
            "its python was asked once"
        );
    }

    /// #845 guard: a project venv with pytest still wins over a `python3`
    /// that has pytest too, and that `python3` is not even asked.
    #[cfg(unix)]
    #[test]
    fn a_venv_with_pytest_wins_without_probing_python3() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("proj");
        fake_venv(&root, ".venv", "exit 0");
        let bin = fake_path_bin(tmp.path(), 0);
        let path = bin.clone().into_os_string();
        assert_eq!(
            pytest_launch_on(&root, Some(&path)),
            (root.join(".venv/bin/python"), &["-m", "pytest"][..])
        );
        assert!(!bin.join("python3.log").exists(), "python3 was not probed");
    }

    /// Discover `root` on this thread: the names listed, and what
    /// `Finished` said.
    fn discovery_of(root: &Path) -> (Vec<String>, Option<Option<bool>>) {
        let (tx, rx) = std::sync::mpsc::channel();
        let etx = EpochTx {
            tx: &tx,
            epoch: 0,
            codeql: Path::new("codeql"),
            extensions: Path::new(NO_EXTENSIONS),
            control: &RunControl::default(),
            request: 1,
            owners: None,
            tag: None,
        };
        discover(root, &etx, false);
        let mut cases = Vec::new();
        let mut finished = None;
        for (_, r) in rx.try_iter() {
            match r {
                TestResponse::Case(c) => cases.push(c.name),
                TestResponse::Finished { ok } => finished = Some(ok),
                _ => {}
            }
        }
        (cases, finished)
    }

    /// #1505, end to end with the real `go` when it is installed: a
    /// `go.work` root lists every module's tests and Run All runs them.
    #[test]
    fn a_go_work_workspace_lists_and_runs_every_module() {
        if Command::new(go_binary()).arg("version").output().is_err() {
            return;
        }
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let write = |rel: &str, text: &str| {
            let p = root.join(rel);
            std::fs::create_dir_all(p.parent().unwrap()).unwrap();
            std::fs::write(p, text).unwrap();
        };
        write("lib/go.mod", "module example.com/lib\n\ngo 1.21\n");
        write(
            "lib/lib_test.go",
            "package lib\n\nimport \"testing\"\n\nfunc TestAdd(t *testing.T) {}\n",
        );
        write("svc/go.mod", "module example.com/svc\n\ngo 1.21\n");
        write(
            "svc/svc_test.go",
            "package svc\n\nimport \"testing\"\n\nfunc TestSvc(t *testing.T) { t.Fatal(\"svc broken\") }\n",
        );
        write("go.work", "go 1.21\n\nuse (\n\t./lib\n\t./svc\n)\n");
        let (mut listed, finished) = discovery_of(root);
        listed.sort();
        assert_eq!(listed, ["./lib::TestAdd", "./svc::TestSvc"], "{finished:?}");

        let (tx, rx) = std::sync::mpsc::channel();
        let etx = EpochTx {
            tx: &tx,
            epoch: 0,
            codeql: Path::new("codeql"),
            extensions: Path::new(NO_EXTENSIONS),
            control: &RunControl::default(),
            request: 1,
            owners: None,
            tag: None,
        };
        run_all(root, &etx);
        let mut ran: Vec<(String, TestStatus)> = rx
            .try_iter()
            .filter_map(|(_, r)| match r {
                TestResponse::Case(c) => Some((c.name, c.status)),
                _ => None,
            })
            .collect();
        ran.sort_by(|a, b| a.0.cmp(&b.0));
        assert_eq!(
            ran,
            [
                (String::from("./lib::TestAdd"), TestStatus::Passed),
                (String::from("./svc::TestSvc"), TestStatus::Failed),
            ]
        );
    }

    /// A JS project whose `runner` (`vitest` or `jest`) is the stand-in
    /// script `body` in its `node_modules/.bin`.
    #[cfg(unix)]
    fn fake_js_runner(root: &Path, runner: &str, body: &str) {
        use std::os::unix::fs::PermissionsExt;
        let bin = root.join("node_modules").join(".bin");
        std::fs::create_dir_all(&bin).unwrap();
        std::fs::write(
            root.join("package.json"),
            format!("{{\"devDependencies\":{{\"{runner}\":\"*\"}}}}"),
        )
        .unwrap();
        let p = bin.join(runner);
        std::fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
        std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
    }

    /// #845: a JS project with no test files lists as an empty project, not
    /// a failed discovery. vitest 2 and later exit 0 from `vitest list`
    /// then, but vitest 1 has no `list` command: it reads the word as a
    /// file filter, says "No test files found" and exits 1 unless told
    /// `--passWithNoTests`. The stand-in behaves as vitest 1.6 does. jest's
    /// `--listTests` exits 0 with nothing to list (29 and 30 alike).
    #[cfg(unix)]
    #[test]
    fn a_js_project_with_no_test_files_lists_as_empty_not_failed() {
        let tmp = tempfile::tempdir().unwrap();
        fake_js_runner(
            tmp.path(),
            "vitest",
            "case \" $* \" in *\" --passWithNoTests \"*) exit 0 ;; esac\n\
             echo 'No test files found, exiting with code 1' >&2\nexit 1",
        );
        assert_eq!(
            runner_for(Path::new(NO_EXTENSIONS), tmp.path()),
            Some(Runner::Vitest)
        );
        assert_eq!(discovery_of(tmp.path()), (Vec::new(), Some(Some(true))));

        let tmp = tempfile::tempdir().unwrap();
        fake_js_runner(tmp.path(), "jest", "exit 0");
        assert_eq!(
            runner_for(Path::new(NO_EXTENSIONS), tmp.path()),
            Some(Runner::Jest)
        );
        assert_eq!(discovery_of(tmp.path()), (Vec::new(), Some(Some(true))));
    }

    /// Run everything in `root` on this thread: the cases reported, in order.
    fn run_all_of(root: &Path) -> Vec<(String, TestStatus)> {
        let (tx, rx) = std::sync::mpsc::channel();
        let etx = EpochTx {
            tx: &tx,
            epoch: 0,
            codeql: Path::new("codeql"),
            extensions: Path::new(NO_EXTENSIONS),
            control: &RunControl::default(),
            request: 1,
            owners: None,
            tag: None,
        };
        run_all(root, &etx);
        rx.try_iter()
            .filter_map(|(_, r)| match r {
                TestResponse::Case(c) => Some((c.name, c.status)),
                _ => None,
            })
            .collect()
    }

    /// A stand-in vitest 3 for the #1504 monorepo: packages `a` and `b`
    /// each hold an `x.test.ts` with the same two tests, and `b`'s second
    /// fails. tap-flat names each test by its file relative to its project,
    /// so all four print as `x.test.ts > ...`; `list --json` and the json
    /// reporter carry absolute files.
    #[cfg(unix)]
    fn fake_vitest_monorepo(root: &Path) {
        let r = root.display();
        let list = format!(
            r#"[{{"name":"parses input","file":"{r}/packages/a/x.test.ts","projectName":"a"}},{{"name":"rejects bad input","file":"{r}/packages/a/x.test.ts","projectName":"a"}},{{"name":"parses input","file":"{r}/packages/b/x.test.ts","projectName":"b"}},{{"name":"rejects bad input","file":"{r}/packages/b/x.test.ts","projectName":"b"}}]"#
        );
        let pass = |t: &str| {
            format!(
                r#"{{"ancestorTitles":[],"status":"passed","title":"{t}","failureMessages":[]}}"#
            )
        };
        let report = format!(
            r#"{{"testResults":[{{"name":"{r}/packages/a/x.test.ts","assertionResults":[{},{}]}},{{"name":"{r}/packages/b/x.test.ts","assertionResults":[{},{{"ancestorTitles":[],"status":"failed","title":"rejects bad input","failureMessages":["no"]}}]}}]}}"#,
            pass("parses input"),
            pass("rejects bad input"),
            pass("parses input"),
        );
        std::fs::write(root.join("list.json"), list).unwrap();
        std::fs::write(root.join("report.json"), report).unwrap();
        fake_js_runner(
            root,
            "vitest",
            "case \"$1\" in list)\n\
               case \" $* \" in *\" --json \"*) cat list.json ;;\n\
               *) echo '[a] x.test.ts > parses input'; echo '[b] x.test.ts > parses input' ;; esac\n\
               exit 0 ;; esac\n\
             echo 'ok 1 - x.test.ts > parses input # time=1ms'\n\
             echo 'ok 2 - x.test.ts > rejects bad input # time=1ms'\n\
             echo 'ok 3 - x.test.ts > parses input # time=1ms'\n\
             echo 'not ok 4 - x.test.ts > rejects bad input # time=1ms'\n\
             for a in \"$@\"; do case \"$a\" in --outputFile.json=*) cp report.json \"${a#*=}\" ;; esac; done\n\
             exit 1",
        );
    }

    /// #1504: with vitest `projects`, a run reports four tests in two
    /// packages, not two in one merged `x.test.ts`, and on the same IDs the
    /// discovery listed.
    #[cfg(unix)]
    #[test]
    fn a_vitest_projects_run_keeps_each_packages_tests_apart() {
        let tmp = tempfile::tempdir().unwrap();
        fake_vitest_monorepo(tmp.path());
        std::fs::write(
            tmp.path().join("vitest.config.ts"),
            "import { defineConfig } from 'vitest/config'\n\
             export default defineConfig({ test: { projects: ['packages/*'] } })\n",
        )
        .unwrap();
        let ran = run_all_of(tmp.path());
        assert_eq!(
            ran,
            vec![
                (
                    "packages/a/x.test.ts::parses input".into(),
                    TestStatus::Passed
                ),
                (
                    "packages/a/x.test.ts::rejects bad input".into(),
                    TestStatus::Passed
                ),
                (
                    "packages/b/x.test.ts::parses input".into(),
                    TestStatus::Passed
                ),
                (
                    "packages/b/x.test.ts::rejects bad input".into(),
                    TestStatus::Failed
                ),
            ]
        );
        let (listed, finished) = discovery_of(tmp.path());
        assert_eq!(finished, Some(Some(true)));
        assert_eq!(listed, ran.into_iter().map(|c| c.0).collect::<Vec<_>>());
    }

    /// #1504 negative: a single-project vitest root keeps streaming
    /// tap-flat as before, and is never asked for a JSON report.
    #[cfg(unix)]
    #[test]
    fn a_single_vitest_project_still_streams_tap_flat() {
        let tmp = tempfile::tempdir().unwrap();
        fake_vitest_monorepo(tmp.path());
        std::fs::write(
            tmp.path().join("vitest.config.ts"),
            "export default { test: { include: ['projects/**/*.test.ts'] } }\n",
        )
        .unwrap();
        let ran = run_all_of(tmp.path());
        assert_eq!(ran.len(), 4, "{ran:?}");
        assert!(
            ran.iter().all(|c| c.0.starts_with("x.test.ts::")),
            "{ran:?}"
        );
        let (listed, _) = discovery_of(tmp.path());
        assert_eq!(
            listed,
            vec!["[a] x.test.ts::parses input", "[b] x.test.ts::parses input"]
        );
    }

    #[test]
    fn vitest_projects_are_found_in_the_config_or_a_workspace_file() {
        for config in [
            "defineConfig({ test: { projects: ['packages/*'] } })",
            "export default { test: { \"projects\" : [] } }",
            "export default { test: { 'projects': [] } }",
            "defineWorkspace; export default { test: { workspace: ['a'] } }",
        ] {
            assert!(declares_vitest_projects(config), "{config}");
        }
        for config in [
            "export default { test: { include: ['projects/**'] } }",
            "const projects = ['a']",
            "export default { test: { myprojects: 1, workspaceRoot: 'x' } }",
            "",
        ] {
            assert!(!declares_vitest_projects(config), "{config}");
        }
        let tmp = tempfile::tempdir().unwrap();
        assert!(!vitest_has_projects(tmp.path()));
        std::fs::write(
            tmp.path().join("vitest.workspace.ts"),
            "export default []\n",
        )
        .unwrap();
        assert!(vitest_has_projects(tmp.path()));
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("vitest.projects.json"), "[]\n").unwrap();
        assert!(vitest_has_projects(tmp.path()));
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("vite.config.mts"), "test: { projects: [] }").unwrap();
        assert!(vitest_has_projects(tmp.path()));
    }

    /// #845 guard: `--passWithNoTests` only forgives an empty project. A
    /// vitest listing that errors (a test file that fails to transform)
    /// still exits 1 with the flag, and stays a failed discovery.
    #[cfg(unix)]
    #[test]
    fn a_vitest_listing_that_errors_is_still_a_failed_discovery() {
        let tmp = tempfile::tempdir().unwrap();
        fake_js_runner(
            tmp.path(),
            "vitest",
            "echo 'Error: Transform failed with 1 error' >&2\nexit 1",
        );
        assert_eq!(discovery_of(tmp.path()), (Vec::new(), Some(Some(false))));
    }

    /// A title holding `::` (`connects to ::1`) is not split into a chain
    /// that matches nothing: the anchored name still selects it, under
    /// jest's and vitest 5's separators alike.
    #[test]
    fn a_js_title_with_a_double_colon_still_runs_exactly() {
        let id = "src/net.test.js::server::connects to ::1";
        let anchor = vitest_one_args(id)[3].clone();
        let filter = regex::Regex::new(&anchor).unwrap();
        for full in ["server connects to ::1", "server > connects to ::1"] {
            assert!(filter.is_match(full), "{full} must run: {anchor}");
        }
        for other in ["server connects to ::12", "server connects to"] {
            assert!(!filter.is_match(other), "{other} must not run");
        }
    }
}