paperboy 0.5.5

A Rust TUI API tester
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
//! The `Collection` container: a loaded `.hurl` file plus app-level state
//! (selected entry, environment, captured values, cached preview). The Hurl
//! request model, parser, serializer and `[Captures]`/`[Asserts]` evaluation
//! live in the [`crate::hurl`] module.

use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};

use crate::git_remote::GitOrigin;
use crate::hurl::{HurlEntry, RunStatus, collection_to_hurl};
use crate::tree::{self, Row};

/// The cached headline of one request in a collection that isn't loaded: its
/// **full** title (folder segments included, so the workspace tree can nest it
/// — see [`WsRow::RequestFolder`]) and what it does.
///
/// The method is cached with the name because a list of bare names makes the
/// reader open a file to find out which row is the POST — the one thing the
/// badge exists to save them.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WsTitle {
    /// The request's whole title, e.g. `"Auth/Tokens/Refresh"`. Empty for an
    /// untitled request, which is displayed as its `url` instead.
    pub name: String,
    /// What to show when the request has no title. Kept apart from `name`
    /// rather than substituted into it because a URL is full of `/` and the
    /// tree reads `/` as folder nesting — an untitled `GET https://x/a/b` must
    /// be one row, not an `https:` folder holding an `x` folder.
    pub url: String,
    pub method: String,
}

/// What a run left behind on one request: its pass/fail marker and the
/// response it came back with.
///
/// A Workspace tab holds one file's requests at a time, and a file with no
/// unsaved edits is re-read from disk when it is opened again — so a run's
/// result lived exactly as long as the tab stayed on that collection. Running
/// a request, looking at another folder and coming back lost both the tick and
/// the response, which is precisely the moment someone wants to compare them.
/// Results are parked here instead, per file, and handed back when the file
/// returns; the tree also reads them so a file that isn't loaded still shows
/// what happened to its requests this session.
///
/// Runtime-only, like [`Collection::workspace_pending`]: a response is a
/// point-in-time answer from a server, not a fact about the collection, and
/// has no business surviving a restart (or being written to disk, where the
/// headers it carries would outlive the session that earned them).
#[derive(Debug, Clone, Default)]
pub struct RunRecord {
    /// Identifies the request the result belongs to, so a file edited outside
    /// PaperBoy between the run and the reopen can't hand a stale response to
    /// whatever request now sits at that position.
    key: String,
    last_run: RunStatus,
    last_response: Option<crate::http::ApiResponse>,
}

/// How a request is recognised across a reload: what it is and where it goes.
fn run_key(entry: &HurlEntry) -> String {
    format!("{}\u{1}{}\u{1}{}", entry.title, entry.method, entry.url)
}

fn ws_request_title(entry: &HurlEntry) -> WsTitle {
    WsTitle {
        name: entry.title.clone(),
        url: entry.url.clone(),
        method: entry.method.clone(),
    }
}

/// The name shown on a request's row: the last segment of its title, since the
/// segments before it are drawn as the folder rows above it. An untitled
/// request shows `url` instead — it still has to be findable in the tree.
fn ws_leaf_label(title: &str, url: &str) -> String {
    let leaf = crate::tree::entry_path(title).pop().unwrap_or_default();
    if leaf.is_empty() {
        url.to_string()
    } else {
        leaf
    }
}

/// Parse a collection file into the display labels of its requests, for listing
/// a not-currently-loaded collection's requests in the workspace tree. Returns
/// an empty vec when the file can't be read or parsed — the collection then
/// simply shows no requests until it is opened.
fn read_collection_labels(path: &Path) -> Vec<WsTitle> {
    std::fs::read_to_string(path)
        .map(|content| {
            crate::postman::parse_collection(&content)
                .iter()
                .map(ws_request_title)
                .collect()
        })
        .unwrap_or_default()
}

/// One row in the Workspace tab's file-tree request list (see
/// [`Collection::ws_rows`]). This navigates the real filesystem under the
/// workspace root and inlines expanded collections' requests directly beneath
/// their file rows (an accordion) — and, within a file, the *virtual* folders
/// encoded in request titles (see [`crate::tree`]), so an imported Postman
/// collection keeps the folder structure it was written with instead of
/// collapsing into one long list of leaf names.
///
/// The tree is a real expand/collapse tree: `workspace_expanded` (on
/// [`Collection`]) holds the set of open folders *and* open collection files
/// *and* open virtual request folders; visibility is derived depth-first from
/// that set. Unlike [`Row`], which shows one virtual folder at a time with an
/// `Up` row, this shows the whole nesting inline.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WsRow {
    /// A folder in the workspace tree.  `expanded` is true when the folder is
    /// in the tab's `workspace_expanded` set (its children are visible).
    Folder {
        path: PathBuf,
        name: String,
        depth: usize,
        expanded: bool,
    },
    /// A collection file in the workspace tree.  `open` is true when the file's
    /// path is in the tab's `workspace_expanded` set, i.e. its inline request
    /// names are shown beneath it (whether or not it is the loaded file).
    Collection {
        path: PathBuf,
        name: String,
        depth: usize,
        open: bool,
    },
    /// A PaperTrail report file (`.trail`).  Selecting it opens the
    /// workspace-aware report view embedded in the right pane.
    Report {
        path: PathBuf,
        name: String,
        depth: usize,
    },
    /// An environment file (`.vars`).  Selecting it loads the file as a global
    /// environment (the same path as File → Load → Environment) rather than
    /// trying to parse it as a collection.
    Environment {
        path: PathBuf,
        name: String,
        depth: usize,
    },
    /// A *virtual* folder inside a collection file: the leading path segments
    /// of its requests' titles (`"Auth/Login"` → an `Auth` folder holding
    /// `Login`). It has no file of its own, so `path` is a synthetic key —
    /// the collection file's path with the folder's segments pushed onto it
    /// (see [`request_folder_path`]). That key can't collide with a real
    /// entry, because the collection is a *file* and so has no children on
    /// disk, which lets these rows share `workspace_expanded` (and its
    /// persistence, and the move/rename repointing) with real folders.
    RequestFolder {
        /// The collection file whose requests this folder groups.
        collection: PathBuf,
        /// Synthetic expand/collapse key; see above.
        path: PathBuf,
        /// The folder's own name — the one title segment, not the whole path.
        name: String,
        depth: usize,
        expanded: bool,
    },
    /// A request shown indented under its [`WsRow::Collection`] row, or under
    /// the [`WsRow::RequestFolder`] rows its title nests it in; `depth` is the
    /// containing row's depth + 1. `collection` is the owning file's path and
    /// `idx` the request's position within it. When `loaded` is true the file
    /// is the tab's currently-loaded collection, so `idx` indexes `entries` and
    /// the row renders in full detail; when false the row is drawn from the
    /// cached name and method (see `workspace_titles`) and selecting it previews
    /// the name — opening it (Enter/Right) loads that collection first.
    Request {
        collection: PathBuf,
        idx: usize,
        /// The request's *leaf* name: any folder segments of its title are
        /// shown as the [`WsRow::RequestFolder`] rows above it, not repeated
        /// here.
        name: String,
        /// The request's HTTP method, known for every listed request whether or
        /// not its file is the loaded one.
        method: String,
        depth: usize,
        loaded: bool,
    },
}

impl WsRow {
    /// The filesystem path a row stands for — the file itself for a file row,
    /// the owning collection for a request (which has no file of its own).
    ///
    /// Lets callers that only care *where* a row is (revealing a just-created
    /// file, deciding which folder a new one goes in) avoid re-matching all
    /// six variants each time. A [`WsRow::RequestFolder`] answers with its
    /// synthetic key rather than its collection, because the callers that ask
    /// are the ones toggling `workspace_expanded`.
    pub fn path(&self) -> &Path {
        match self {
            WsRow::Folder { path, .. }
            | WsRow::Collection { path, .. }
            | WsRow::Report { path, .. }
            | WsRow::Environment { path, .. }
            | WsRow::RequestFolder { path, .. } => path,
            WsRow::Request { collection, .. } => collection,
        }
    }

    /// How far the row is indented in the tree.
    pub fn depth(&self) -> usize {
        match self {
            WsRow::Folder { depth, .. }
            | WsRow::Collection { depth, .. }
            | WsRow::Report { depth, .. }
            | WsRow::Environment { depth, .. }
            | WsRow::RequestFolder { depth, .. }
            | WsRow::Request { depth, .. } => *depth,
        }
    }

    /// The text shown for the row — what a typed filter matches against.
    pub fn name(&self) -> &str {
        match self {
            WsRow::Folder { name, .. }
            | WsRow::Collection { name, .. }
            | WsRow::Report { name, .. }
            | WsRow::Environment { name, .. }
            | WsRow::RequestFolder { name, .. }
            | WsRow::Request { name, .. } => name,
        }
    }
}

/// Narrow an already-built Workspace tree to the rows matching `query`, keeping
/// every ancestor of a match so the survivors still read as a tree rather than
/// as a flat list of names with no indication of which file they came from.
///
/// A plain collection's filter flattens instead ([`crate::tree::rows_matching`])
/// because there the only context a match has is its title, which the row
/// already spells out in full. A workspace row's context is the *file* it lives
/// in, which the row does not repeat — so dropping the ancestors would leave a
/// screen of request names with no way to tell two identically-named requests
/// in different collections apart.
///
/// Matching is case-insensitive and on the substring, matching the Requests and
/// Environments filters; a folder that matches keeps its whole subtree, since
/// naming a folder is the obvious way to ask for what is in it.
fn filter_ws_rows(rows: Vec<WsRow>, query: &str) -> Vec<WsRow> {
    let needle = query.trim().to_lowercase();
    if needle.is_empty() {
        return rows;
    }
    let mut keep = vec![false; rows.len()];
    // The indices of the rows containing the one being looked at, innermost
    // last — a match marks all of them, which is what keeps the tree readable.
    let mut ancestors: Vec<usize> = Vec::new();
    // Set while inside a matched folder's subtree, holding that folder's depth,
    // so everything under it is kept without having to match on its own.
    let mut inside: Option<usize> = None;
    for (i, row) in rows.iter().enumerate() {
        let d = row.depth();
        while ancestors.last().is_some_and(|&a| rows[a].depth() >= d) {
            ancestors.pop();
        }
        if inside.is_some_and(|kept| d <= kept) {
            inside = None;
        }
        if inside.is_some() || row.name().to_lowercase().contains(&needle) {
            keep[i] = true;
            for &a in &ancestors {
                keep[a] = true;
            }
            if inside.is_none() && matches!(row, WsRow::Folder { .. } | WsRow::RequestFolder { .. })
            {
                inside = Some(d);
            }
        }
        ancestors.push(i);
    }
    rows.into_iter()
        .zip(keep)
        .filter_map(|(r, k)| k.then_some(r))
        .collect()
}

/// A title for a copy of `title` that no entry in `entries` already carries.
///
/// A request's title is its *identifier*: reports address requests by name
/// (see `report::run::resolve_qualified`), and two entries sharing a title
/// make the name ambiguous — which breaks the reference for **both** of them,
/// not just the new one. So a duplicate can't simply reuse the name; it has to
/// arrive with one of its own.
///
/// Folders are derived by splitting the title on `/` (see [`crate::tree`]), so
/// only the leaf is renamed — a copy belongs in the same folder as its
/// original. Copying a copy counts on from the existing suffix rather than
/// stacking them, so repeated duplication gives `Login (2)`, `Login (3)` …
/// instead of `Login (2) (2)`.
pub fn unique_entry_title(entries: &[HurlEntry], title: &str) -> String {
    let (prefix, leaf) = match title.rfind('/') {
        Some(i) => title.split_at(i + 1),
        None => ("", title),
    };
    // Strip any trailing " (n)" so the counter continues rather than nests.
    let stem = leaf
        .rsplit_once(" (")
        .and_then(|(head, tail)| {
            tail.strip_suffix(')')
                .filter(|d| !d.is_empty() && d.chars().all(|c| c.is_ascii_digit()))
                .map(|_| head)
        })
        .unwrap_or(leaf);
    let taken: HashSet<&str> = entries.iter().map(|e| e.title.as_str()).collect();
    // Starts at 2 because the original is, in effect, number one.
    (2..)
        .map(|n| format!("{prefix}{stem} ({n})"))
        .find(|candidate| !taken.contains(candidate.as_str()))
        .unwrap_or_else(|| title.to_string())
}

/// Where the index `i` ends up after the entry at `from` is moved to `to`.
///
/// Only indices *between* the two move, and they all move one step in the
/// opposite direction to the entry itself; `from` becomes `to` by definition.
fn shift_index(i: usize, from: usize, to: usize) -> usize {
    if i == from {
        to
    } else if from < to && i > from && i <= to {
        i - 1
    } else if to < from && i >= to && i < from {
        i + 1
    } else {
        i
    }
}

/// The synthetic `workspace_expanded` key for the virtual folder `folder`
/// (title segments) inside the collection file at `collection` — see
/// [`WsRow::RequestFolder`].
///
/// Segments are sanitised before being pushed: a request titled `"../x/y"` (or
/// one with a `\` on Windows) would otherwise produce a key pointing outside
/// the collection, which both collides with real paths and survives into
/// persisted state. The sanitised form only ever has to be *consistent*, never
/// reversible — nothing reads a folder name back out of one of these keys.
pub fn request_folder_path(collection: &Path, folder: &[String]) -> PathBuf {
    let mut path = collection.to_path_buf();
    for seg in folder {
        let safe: String = seg
            .chars()
            .map(|c| if std::path::is_separator(c) { '_' } else { c })
            .collect();
        path.push(match safe.trim_matches('.') {
            "" => "_",
            _ => safe.as_str(),
        });
    }
    path
}

/// How long a workspace tree scan is reused before the disk is read again.
///
/// The scan is a recursive `read_dir` of the whole workspace, and the graphical
/// front-end asks for the tree once per frame — so at 60fps this was real
/// filesystem I/O sixty times a second, growing with the size of the tree, just
/// to redraw a list that hadn't changed.
///
/// The window is deliberately short and deliberately *time*-based rather than
/// invalidated by the app's own file operations. A tree can change from outside
/// PaperBoy (another editor, a `git pull`, a test run dropping result files),
/// so a cache keyed only on things PaperBoy knows it did would go stale in
/// exactly the cases the tree matters most. A third of a second is below the
/// threshold at which a file list reads as "live", and it still collapses
/// ~95% of the scans.
const WS_SCAN_TTL: Duration = Duration::from_millis(300);

/// The last workspace tree read off disk, and what it was read for.
#[derive(Clone)]
struct WsScan {
    root: PathBuf,
    filter_hurl_json: bool,
    taken_at: Instant,
    /// [`crate::workspace::tree_generation`] when this was taken, so PaperBoy's
    /// own file operations don't have to wait out [`WS_SCAN_TTL`].
    generation: u64,
    entries: Vec<crate::workspace::WsEntry>,
}

/// A loaded Hurl collection (one .hurl file).
#[derive(Clone)]
pub struct Collection {
    /// Stable runtime id (used to route async capture results back here).
    pub id: u64,
    pub name: String,
    pub entries: Vec<HurlEntry>,
    pub selected_entry: usize,
    /// The Global Environment (if any) linked/"pinned" to this collection —
    /// an id into [`crate::tui::app::TuiApp::global_envs`], not an owned
    /// [`Environment`]. Any number of collections may link the same one. Its
    /// vars take precedence over the active Global Environment's on a
    /// name collision (see [`crate::request::subst_map`]).
    pub linked_env_id: Option<u64>,
    /// Source `.hurl` file this collection was loaded from (used by "Save
    /// Collection"). `None` for the built-in Request tab until saved.
    pub path: Option<PathBuf>,
    /// Where the `.hurl` file was loaded from in git, if it was (used to show
    /// the ⎇ icon on the tab title and to default "Save Collection to Git…").
    pub git_origin: Option<GitOrigin>,
    /// Editable JSON preview of the selected request (vars substituted).
    pub request_json_buf: String,
    /// Entry index `request_json_buf` was built for; `None` means stale.
    pub request_json_for: Option<usize>,
    /// Values captured from responses (Hurl `[Captures]`), available as
    /// `{{ name }}` in subsequent requests. Runtime-only (not persisted).
    pub captures: HashMap<String, String>,
    /// The folders currently open in the Requests list, each as a full path
    /// from the root. Requests are grouped into folders by splitting their
    /// `title` on `/` (see [`crate::tree`]).
    ///
    /// Purely view state, never persisted: a restored session re-derives it
    /// from the selected request, which is the one folder the user is
    /// guaranteed to want open. Anything else would either hide what they were
    /// looking at or restore a shape of the tree they had since left behind.
    pub expanded: HashSet<Vec<String>>,
    /// Index into the current folder's rows (see [`crate::tree::rows_for`]),
    /// i.e. which row is highlighted in the Requests list. Not persisted.
    pub list_cursor: usize,
    /// A typed filter over the Requests list: while non-empty, the list shows
    /// every request whose title contains this, flattened across folders (see
    /// [`crate::tree::rows_matching`]) instead of the folder being browsed.
    ///
    /// Lives on the collection rather than on either front-end so both show the
    /// same narrowed list for the same tab, the way `workspace_filter_hurl_json`
    /// already does — and so switching tabs keeps each tab's own filter.
    ///
    /// Runtime-only, deliberately: a filter restored from a previous session
    /// would present a collection that looks like it has lost most of its
    /// requests, with the reason parked in a strip nobody has looked at yet.
    pub list_query: String,
    /// How the Requests list orders its rows (see [`crate::tree::SortMode`]).
    /// Purely a view over the same entries — sorting never touches the file or
    /// the order Run All sends in. Runtime-only, like `folder` and
    /// `list_cursor`: a sort restored from a previous session would silently
    /// misrepresent a freshly-opened file's order.
    pub list_sort: tree::SortMode,
    /// Requests removed with `x` (List pane), most-recently-deleted last, so
    /// `u` (List pane) can bring them back in order — the exact parallel of
    /// [`crate::tui::app::TuiApp::closed_tabs`] for individual requests
    /// instead of whole collection tabs. Capped so a long session can't grow
    /// it unbounded. Runtime-only, not persisted.
    pub deleted_entries: Vec<(usize, HurlEntry)>,
    /// Set when this tab is bound to a Workspace folder (see
    /// [`crate::workspace`]) rather than a single stand-alone file. `path`
    /// still tracks whichever file within this folder is currently loaded
    /// (or `None` if the user hasn't picked one yet) — this field just marks
    /// *which* folder it was picked from, so `w` can reopen the picker
    /// scoped to it and the tab bar can show a folder icon.
    pub workspace_root: Option<PathBuf>,
    /// Whether the Workspace file picker for this tab is currently filtering
    /// to `.hurl`/`.json` files only (`true`, the default) or showing every
    /// file (`false`). Remembered across re-opens of the picker for this tab.
    pub workspace_filter_hurl_json: bool,
    /// True once the auto-open-picker prompt (see `TuiApp::draw`'s
    /// auto-prompt check) has been shown and dismissed (Esc/q) for this
    /// still-file-less Workspace tab, so it doesn't immediately reopen every
    /// frame — the user can still bring it back explicitly with `w`.
    /// Transient (not persisted); resets to `false` on restart, which is
    /// fine since a fresh restore re-prompts anyway if the file vanished.
    pub workspace_auto_prompt_dismissed: bool,
    /// Set alongside `workspace_root` when that folder was downloaded from
    /// git (see `TuiApp::confirm_workspace_root_from_git`), rather than
    /// picked from the user's own filesystem — a plain local folder must
    /// never be deleted by the app, but a throwaway git-downloaded temp
    /// directory can be, so closing a tab with this set to `true` offers to
    /// delete it (see `TuiApp::close_active_tab`) instead of closing it
    /// silently like every other tab.
    pub workspace_downloaded_from_git: bool,
    /// Where this Workspace's downloaded files came from in git — set
    /// alongside `workspace_downloaded_from_git`, `None` for a locally
    /// picked folder. Persisted (see `PersistedTab::workspace_git_origin`)
    /// so that if `workspace_root` vanishes (e.g. the OS clears `/tmp`
    /// between sessions), the app can offer to redownload the exact same
    /// commit rather than losing track of the workspace entirely — see
    /// `PersistedTab::into_collection`'s `PendingWorkspaceReload`.
    pub workspace_git_origin: Option<crate::remote_flow::WorkspaceGitOrigin>,
    /// For a Workspace tab, the set of *expanded* node paths (absolute) in the
    /// file-tree — both folders (whose child entries are shown) and collection
    /// files (whose inline request names are shown). A node is visible when all
    /// its ancestor folders are also in this set. Persisted so the tree state
    /// survives restarts. Absolute paths in memory; serialised relative to
    /// `workspace_root` in [`crate::persistence`].
    pub workspace_expanded: HashSet<PathBuf>,
    /// For a Workspace tab, the node in the tree the user last selected
    /// (absolute path): a collection file, a `.trail` report or a `.vars`
    /// environment. Persisted (relative to `workspace_root`) so the tab reopens
    /// on whatever was being worked on rather than an empty right-hand pane.
    ///
    /// A selected *request* is already fully described by `path` +
    /// `selected_entry`; this records the collection file in that case, which
    /// is all the restore needs on top of those two.
    ///
    /// Written by the graphical front-end only — the terminal UI drives the
    /// tree from its own cursor and simply carries this through a save/load,
    /// exactly as it does the GUI's panel geometry.
    pub workspace_selected: Option<PathBuf>,
    /// For a Workspace tab, cached request *names* (leaf titles) of expanded
    /// collection files that are **not** the currently-loaded one — the loaded
    /// file renders its rows straight from `entries`, so it needs no cache.
    /// Lets [`Self::ws_rows`] list several collections' requests at once without
    /// re-reading and parsing each file every frame. Populated when switching
    /// away from a loaded file (from its live entries) and when restoring an
    /// expanded collection from disk (see [`Self::rebuild_expanded_titles`]).
    /// Derived state — not persisted.
    pub workspace_titles: HashMap<PathBuf, Vec<WsTitle>>,
    /// The most recent workspace tree read off disk, reused for [`WS_SCAN_TTL`]
    /// so redrawing the tree isn't a recursive `read_dir` every frame. Purely
    /// derived state: dropping it only costs one extra scan, which is why it is
    /// neither persisted nor part of any equality check.
    workspace_scan: RefCell<Option<WsScan>>,
    /// Unsaved edits belonging to workspace collection files that are **not**
    /// the currently-loaded one.
    ///
    /// A Workspace tab holds exactly one file's requests in `entries` at a
    /// time, so opening a second collection from the tree used to overwrite —
    /// and silently discard — whatever the user had just typed into the first.
    /// The outgoing file's entries are parked here instead and handed straight
    /// back when it is opened again, which is what makes "edit a request, go
    /// look at another collection, come back" behave the way anyone would
    /// expect. Cleared for a file when it is written to disk
    /// ([`Self::mark_saved`]).
    ///
    /// Runtime-only. A workspace tab's entries are never a trusted snapshot
    /// across a restart (see [`crate::persistence`]), so neither are these.
    pub workspace_pending: HashMap<PathBuf, Vec<HurlEntry>>,

    /// Whether the loaded entries differ *structurally* from the file they
    /// came from — a request removed, restored or reordered.
    ///
    /// [`Self::has_unsaved_edits`] otherwise answers by scanning the entries
    /// for `user_added`/`modified` flags, which only ever say "this request
    /// was edited". Removing one leaves nothing behind to carry a flag, and
    /// reordering changes no request at all, so both read as "no edits" — and
    /// a Workspace tab, whose entries are held in memory and re-read from disk
    /// when it switches away and back, would then throw the change away
    /// without a word. Cleared by [`Self::mark_saved`] like any other marker.
    ///
    /// Runtime-only, for the same reason `workspace_pending` is.
    ///
    /// Derived rather than latched: see [`Self::refresh_structure_modified`].
    /// A flag that only ever went *true* meant undoing a reorder — dragging a
    /// request back where it started, or restoring the one just deleted — left
    /// the collection marked unsaved with nothing left to save.
    pub structure_modified: bool,

    /// What the entry list looked like when it was last read from or written to
    /// disk, as the sequence of [`HurlEntry::uid`] stamps. Compared against the
    /// live list to decide [`Self::structure_modified`].
    ///
    /// Identities rather than positions, because positions are exactly what a
    /// reorder changes; and identities rather than any part of the entry's
    /// *content*, because editing a request is a different kind of change,
    /// already carried by its own `modified` flag. This one answers only "is
    /// this still the same list, in the same order" — so a URL rewritten in
    /// place must not register, and two identically-named requests swapping
    /// places must.
    ///
    /// Runtime-only, like the flag it feeds.
    pub structure_baseline: Vec<u64>,

    /// The baselines ([`Self::structure_baseline`]) of the parked files, so a
    /// file switched away from and back is still measured against the order it
    /// had on disk rather than against whatever it had been dragged into.
    /// Without this, coming back to a reordered file and dragging the request
    /// home again would leave it looking permanently unsaved.
    pub workspace_baselines: HashMap<PathBuf, Vec<u64>>,

    /// The parked files (see `workspace_pending`) whose entries differ
    /// structurally from disk — `structure_modified` for a file that isn't the
    /// loaded one. Kept separately because `workspace_pending` stores only the
    /// entries, and a deletion is precisely the change that leaves no trace in
    /// them.
    pub workspace_structure_modified: HashSet<PathBuf>,

    /// Run results for this Workspace tab's files, keyed by file and indexed
    /// the way [`Self::workspace_titles`] is — see [`RunRecord`] for why they
    /// outlive the file being loaded, and why they are runtime-only.
    pub workspace_runs: HashMap<PathBuf, Vec<RunRecord>>,
}

static NEXT_COLLECTION_ID: AtomicU64 = AtomicU64::new(1);

/// Stamps for [`HurlEntry::uid`]. Starts at 1 so that zero keeps its meaning of
/// "never stamped", and is shared across every collection so two tabs can never
/// hand out the same identity to different requests.
static NEXT_ENTRY_UID: AtomicU64 = AtomicU64::new(1);

/// A process-unique id for a new collection.
pub fn next_collection_id() -> u64 {
    NEXT_COLLECTION_ID.fetch_add(1, Ordering::Relaxed)
}

/// Write collection text to `path`, creating the folder it lives in if that has
/// gone missing since the file was opened. The error carries the path, because
/// a bulk save spans several files and "permission denied" on its own would not
/// say which one refused.
#[cfg_attr(not(feature = "gui"), allow(dead_code))]
fn write_hurl(path: &Path, text: &str) -> Result<(), String> {
    if let Some(parent) = path.parent()
        && !parent.as_os_str().is_empty()
    {
        std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
    }
    std::fs::write(path, text).map_err(|e| format!("{}: {e}", path.display()))
}

impl Collection {
    pub fn new(name: String, entries: Vec<HurlEntry>) -> Self {
        let mut c = Self {
            id: next_collection_id(),
            name,
            entries,
            selected_entry: 0,
            linked_env_id: None,
            path: None,
            git_origin: None,
            request_json_buf: String::new(),
            request_json_for: None,
            captures: HashMap::new(),
            expanded: HashSet::new(),
            list_cursor: 0,
            list_query: String::new(),
            list_sort: tree::SortMode::default(),
            deleted_entries: Vec::new(),
            workspace_root: None,
            workspace_filter_hurl_json: true,
            workspace_auto_prompt_dismissed: false,
            workspace_downloaded_from_git: false,
            workspace_git_origin: None,
            workspace_expanded: HashSet::new(),
            workspace_selected: None,
            workspace_titles: HashMap::new(),
            workspace_scan: RefCell::new(None),
            workspace_pending: HashMap::new(),
            structure_modified: false,
            structure_baseline: Vec::new(),
            workspace_baselines: HashMap::new(),
            workspace_structure_modified: HashSet::new(),
            workspace_runs: HashMap::new(),
        };
        // Whatever a collection is built from is, by definition, what it
        // currently agrees with — a file just read, a Postman import, or an
        // empty scratch tab. Later structural edits are measured against this.
        c.reset_structure_baseline();
        c.sync_folder_to_selected();
        c
    }

    /// Serialize this collection's entries to Hurl text.
    pub fn to_hurl(&self) -> String {
        collection_to_hurl(&self.entries)
    }

    /// The first enabled `[Form]`/`[Multipart]` file field with an empty path,
    /// as `(request title, field key)`. Such a field serializes to an invalid
    /// `file,;` line that PaperBoy's own Hurl parser rejects, so a file written
    /// with one couldn't be reloaded. Saves are refused until it's filled in.
    pub fn first_empty_file_field(&self) -> Option<(String, String)> {
        self.entries.iter().find_map(|e| {
            e.first_empty_file_field()
                .map(|k| (e.title.clone(), k.to_string()))
        })
    }

    /// Discard the cached request-JSON preview so it is rebuilt from the current
    /// entry and environment. Call after the environment changes (e.g. reloaded)
    /// so freshly-resolved values flow into the next request.
    pub fn invalidate_request_json(&mut self) {
        self.request_json_buf.clear();
        self.request_json_for = None;
    }

    /// The rows to show in the Requests list: the folder tree with whatever is
    /// open in it, or — while a filter is typed — every match across the whole
    /// collection, flat.
    ///
    /// Only the flat list is sorted. A tree sorted as one sequence would tear
    /// requests away from the folders they are drawn under; the GUI sorts its
    /// own tree a level at a time, and the terminal UI leaves the order the
    /// file's, which is the order Run All uses.
    pub fn rows(&self) -> Vec<Row> {
        if self.list_filter_active() {
            let mut rows = tree::rows_matching(&self.entries, &self.list_query);
            tree::sort_rows(&mut rows, &self.entries, self.list_sort);
            return rows;
        }
        tree::rows_for(&self.entries, &self.expanded)
    }

    /// The folder a new request made from the list should land in: the folder
    /// under the cursor, or the one holding the request under it.
    ///
    /// The old breadcrumb model had one obvious answer -- the folder being
    /// browsed. In a tree the answer is what the cursor is pointing at, which
    /// is the same thing anyone looking at the screen would say.
    pub fn cursor_folder(&self) -> Vec<String> {
        match self.rows().get(self.list_cursor) {
            Some(Row::Folder { path, .. }) => path.clone(),
            Some(Row::Entry(i)) => tree::folder_of(&self.entries, *i),
            None => Vec::new(),
        }
    }

    /// Open or close the folder at `path`, closing every folder inside it too.
    ///
    /// Collapsing a folder shuts what was open within it rather than
    /// remembering it: reopening a folder to find three levels of it already
    /// unfolded is not what "open this folder" means, and the memory would be
    /// invisible state the user cannot see to correct.
    pub fn toggle_folder(&mut self, path: &[String]) {
        let path = path.to_vec();
        if self.expanded.remove(&path) {
            self.expanded
                .retain(|open| !(open.len() > path.len() && open[..path.len()] == path[..]));
        } else {
            self.expanded.insert(path);
        }
    }

    /// How many rows the left-hand list pane is showing, whichever kind of tab
    /// it is: a Workspace tab draws its filesystem tree, every other tab draws
    /// the loaded collection's requests. The two are different lists of
    /// different lengths, and reading `list_cursor` against the wrong one is
    /// how `Alt+↑↓` came to reorder requests nobody was pointing at.
    pub fn list_row_count(&self) -> usize {
        if self.is_workspace() {
            self.ws_rows().len()
        } else {
            self.rows().len()
        }
    }

    /// Whether the Requests list is currently narrowed by a typed filter.
    ///
    /// Trimmed, so a query of nothing but spaces counts as no filter at all —
    /// it matches every request anyway, and treating it as active would leave
    /// the list flattened out of its folders for no visible reason.
    pub fn list_filter_active(&self) -> bool {
        !self.list_query.trim().is_empty()
    }

    /// True when this tab is bound to a Workspace folder (so the list uses the
    /// filesystem file-tree via [`Self::ws_rows`] instead of [`Self::rows`]).
    pub fn is_workspace(&self) -> bool {
        self.workspace_root.is_some()
    }

    /// The rows to show in a Workspace tab's expand/collapse file tree.
    ///
    /// Uses [`crate::workspace::scan_workspace`] for the full depth-first tree,
    /// then applies the `workspace_expanded` visibility filter: an entry is
    /// shown only when every ancestor folder in the DFS path is in that set.
    /// Folders render with a chevron (expanded ▾ / collapsed ▸); selecting a
    /// collection file opens it (with inline requests beneath); selecting a
    /// report embeds it in the right pane.  Empty for a non-Workspace tab.
    pub fn ws_rows(&self) -> Vec<WsRow> {
        self.ws_rows_at(Instant::now())
    }

    /// The entry index under the cursor when it is a *loaded* request on a
    /// Workspace tab — that is, exactly when `m` (move) and `c` (copy) have
    /// something to transfer to another collection file.
    ///
    /// A single predicate shared by the key handler and the footer hint, so the
    /// footer can never advertise a key that would silently do nothing: a
    /// folder row, a report, or a collection file whose requests haven't been
    /// read in yet are all rows where `m`/`c` return without acting.
    pub(crate) fn ws_transfer_target(&self) -> Option<usize> {
        if !self.is_workspace() || self.workspace_root.is_none() {
            return None;
        }
        match self.ws_rows().into_iter().nth(self.list_cursor) {
            Some(WsRow::Request {
                idx, loaded: true, ..
            }) => Some(idx),
            _ => None,
        }
    }

    /// [`Self::ws_rows`] as of a given moment, so the scan cache's expiry can be
    /// tested without sleeping.
    pub(crate) fn ws_rows_at(&self, now: Instant) -> Vec<WsRow> {
        self.ws_rows_as_of(now, crate::workspace::tree_generation())
    }

    /// [`Self::ws_rows`] as of a given moment *and* a given tree generation.
    ///
    /// The generation is a parameter rather than read from the global counter
    /// so a test of the time-based expiry can't be perturbed by another test
    /// running in parallel that happens to create a workspace file.
    pub(crate) fn ws_rows_as_of(&self, now: Instant, generation: u64) -> Vec<WsRow> {
        let Some(root) = &self.workspace_root else {
            return Vec::new();
        };

        self.refresh_scan(root, now, generation);
        // Held across the whole loop so the tree is walked in place rather than
        // cloned out of the cache every frame — the point of the cache is to
        // stop doing work per frame, not to trade I/O for an allocation.
        let scan = self.workspace_scan.borrow();
        let full_tree = scan
            .as_ref()
            .map(|s| s.entries.as_slice())
            .unwrap_or_default();
        let mut out = Vec::new();

        // A typed filter searches the whole workspace, so while one is active
        // every *folder* counts as expanded: a search that could only find what
        // was already on screen would be no search at all. Collection files are
        // deliberately left alone — expanding one reads its requests off disk
        // (or out of the title cache), and doing that for every file in the
        // tree on each keystroke would stall a large workspace. So a filter
        // reaches every file, report and environment in the workspace, and the
        // requests of the collections already open.
        let filtering = self.list_filter_active();

        // `ancestor_at[d]` holds the absolute path of the most-recently-visited
        // directory at depth d.  A row at depth D is visible iff every slot
        // ancestor_at[0..D] points to a path in `workspace_expanded`.
        let mut ancestor_at: Vec<Option<PathBuf>> = Vec::new();

        for entry in full_tree {
            let d = entry.depth;

            // Moving to a shallower depth: slots d.. are no longer our ancestors.
            if ancestor_at.len() > d {
                ancestor_at.truncate(d);
            }

            // Visible iff every containing ancestor folder is expanded.
            let visible = filtering
                || ancestor_at.iter().all(|opt| {
                    opt.as_ref()
                        .is_some_and(|p| self.workspace_expanded.contains(p))
                });

            if entry.is_dir {
                // Record this directory as the current ancestor at depth d,
                // so its descendants can check its expansion state.
                if ancestor_at.len() == d {
                    ancestor_at.push(Some(entry.path.clone()));
                } else {
                    ancestor_at[d] = Some(entry.path.clone());
                }

                if visible {
                    let expanded = filtering || self.workspace_expanded.contains(&entry.path);
                    out.push(WsRow::Folder {
                        path: entry.path.clone(),
                        name: entry.display_name.clone(),
                        depth: d,
                        expanded,
                    });
                }
            } else if visible {
                if crate::workspace::is_report_file(&entry.path) {
                    out.push(WsRow::Report {
                        path: entry.path.clone(),
                        name: entry.display_name.clone(),
                        depth: d,
                    });
                } else if crate::workspace::is_env_file(&entry.path) {
                    out.push(WsRow::Environment {
                        path: entry.path.clone(),
                        name: entry.display_name.clone(),
                        depth: d,
                    });
                } else {
                    let expanded = self.workspace_expanded.contains(&entry.path);
                    out.push(WsRow::Collection {
                        path: entry.path.clone(),
                        name: entry.display_name.clone(),
                        depth: d,
                        open: expanded,
                    });
                    if expanded {
                        out.extend(self.request_rows_for(&entry.path, d + 1));
                    }
                }
            }
        }
        if filtering {
            return filter_ws_rows(out, &self.list_query);
        }
        out
    }

    /// Read the workspace tree off disk if what's cached is missing, stale, or
    /// was taken for a different root or filter.
    ///
    /// The *visibility* half of [`Self::ws_rows_at`] (the expand/collapse
    /// filter) is deliberately left out of the cache: expanding a folder must
    /// feel instant, and re-filtering an already-scanned tree costs nothing.
    fn refresh_scan(&self, root: &Path, now: Instant, generation: u64) {
        let mut slot = self.workspace_scan.borrow_mut();
        let usable = slot.as_ref().is_some_and(|s| {
            s.root == root
                && s.filter_hurl_json == self.workspace_filter_hurl_json
                && s.generation == generation
                && now.saturating_duration_since(s.taken_at) < WS_SCAN_TTL
        });
        if usable {
            return;
        }
        *slot = Some(WsScan {
            root: root.to_path_buf(),
            filter_hurl_json: self.workspace_filter_hurl_json,
            taken_at: now,
            generation,
            entries: crate::workspace::scan_workspace(root, self.workspace_filter_hurl_json),
        });
    }

    /// Every `.vars` (or env-shaped `.json`) file in this tab's workspace, for
    /// the Environments panel to list alongside the loaded environments.
    ///
    /// Served out of the same cached tree walk [`Self::ws_rows`] uses rather
    /// than scanning the disk itself: both front-ends' environment panels ask
    /// for this list several times per frame — once for the rows, once for the
    /// unfiltered rows behind the "no matches" message, once for the empty
    /// state — and each of those used to be a full recursive `read_dir` of the
    /// workspace. The cached scan holds every non-hidden file whichever way the
    /// tab's display filter is set (the filter only ever *narrows* to the
    /// workspace's own file types, and `.vars` is one of them), so it can
    /// answer this without a second walk.
    ///
    /// Empty for a tab that isn't a workspace.
    pub fn workspace_env_files(&self) -> Vec<PathBuf> {
        self.workspace_env_files_as_of(Instant::now(), crate::workspace::tree_generation())
    }

    /// [`Self::workspace_env_files`] as of a given moment and tree generation,
    /// so the cache can be tested without racing its expiry.
    pub(crate) fn workspace_env_files_as_of(&self, now: Instant, generation: u64) -> Vec<PathBuf> {
        let Some(root) = self.workspace_root.clone() else {
            return Vec::new();
        };
        self.refresh_scan(&root, now, generation);
        let scan = self.workspace_scan.borrow();
        scan.as_ref()
            .map(|s| {
                s.entries
                    .iter()
                    .filter(|e| !e.is_dir && crate::workspace::is_env_file(&e.path))
                    .map(|e| e.path.clone())
                    .collect()
            })
            .unwrap_or_default()
    }

    /// The request rows shown under an expanded collection at `path`, indented
    /// to `depth`. For the currently-loaded file the rows come straight from
    /// `entries` (full detail, `loaded: true`); for any other expanded
    /// The request rows shown under an expanded collection at `path`, indented
    /// to `depth`, nested into the virtual folders their titles encode. For the
    /// currently-loaded file the rows come straight from `entries` (full detail,
    /// `loaded: true`); for any other expanded collection they come from the
    /// cached titles in `workspace_titles` (`loaded: false`), so several
    /// collections' requests can be listed at once without re-parsing every file
    /// each frame. A collection with no cached names yet contributes no rows.
    fn request_rows_for(&self, path: &Path, depth: usize) -> Vec<WsRow> {
        // (index in the file, full title, url, method) for every request to
        // list, in file order — the one shape both sources reduce to.
        let listing: Vec<(usize, String, String, String)> = if self.path.as_deref() == Some(path) {
            self.entries
                .iter()
                .enumerate()
                .map(|(idx, e)| (idx, e.title.clone(), e.url.clone(), e.method.clone()))
                .collect()
        } else {
            match self.workspace_titles.get(path) {
                Some(titles) => titles
                    .iter()
                    .enumerate()
                    .map(|(idx, t)| (idx, t.name.clone(), t.url.clone(), t.method.clone()))
                    .collect(),
                None => return Vec::new(),
            }
        };
        let loaded = self.path.as_deref() == Some(path);
        let mut out = Vec::new();
        self.push_request_rows(path, &listing, &[], depth, loaded, &mut out);
        out
    }

    /// Append the rows for the virtual folder `folder` of the collection at
    /// `path`: its direct subfolders (each recursed into when expanded), then
    /// its direct requests.
    ///
    /// Folders come before requests, and both keep the order the file puts them
    /// in rather than being sorted — a collection is an ordered script (the
    /// login that captures a token has to read as coming first), so re-ordering
    /// it for display would misrepresent what running it does.
    fn push_request_rows(
        &self,
        path: &Path,
        listing: &[(usize, String, String, String)],
        folder: &[String],
        depth: usize,
        loaded: bool,
        out: &mut Vec<WsRow>,
    ) {
        let mut seen: Vec<String> = Vec::new();
        let mut leaves: Vec<&(usize, String, String, String)> = Vec::new();

        for item in listing {
            let segs = tree::entry_path(&item.1);
            if segs.len() <= folder.len() || segs[..folder.len()] != *folder {
                continue;
            }
            if segs.len() == folder.len() + 1 {
                leaves.push(item);
            } else if !seen.contains(&segs[folder.len()]) {
                seen.push(segs[folder.len()].clone());
            }
        }

        for name in seen {
            let mut child = folder.to_vec();
            child.push(name.clone());
            let key = request_folder_path(path, &child);
            let expanded = self.workspace_expanded.contains(&key);
            out.push(WsRow::RequestFolder {
                collection: path.to_path_buf(),
                path: key,
                name,
                depth,
                expanded,
            });
            if expanded {
                self.push_request_rows(path, listing, &child, depth + 1, loaded, out);
            }
        }

        for (idx, title, url, method) in leaves {
            out.push(WsRow::Request {
                collection: path.to_path_buf(),
                idx: *idx,
                name: ws_leaf_label(title, url),
                method: method.clone(),
                depth,
                loaded,
            });
        }
    }

    /// Cache the loaded file's request names under its own path, derived from
    /// the live `entries` (so in-memory edits/renames are reflected). Call this
    /// just before switching the loaded file away, so a collection left
    /// expanded keeps listing its requests from the cache.
    pub fn snapshot_loaded_titles(&mut self) {
        if let Some(path) = self.path.clone() {
            let titles = self.entries.iter().map(ws_request_title).collect();
            self.workspace_titles.insert(path, titles);
        }
    }

    /// Load a workspace collection file (Hurl or Postman JSON) at `path` into
    /// this tab, replacing its currently-loaded requests. Front-end agnostic —
    /// it only mutates this `Collection` (both the terminal UI and the GUI call
    /// it, then add their own focus/status handling). The tab's
    /// `workspace_root`/`workspace_filter_hurl_json` are left untouched. Caches
    /// the outgoing file's request names first so a still-expanded previous file
    /// keeps listing its requests, then re-syncs the tree cursor/selection and
    /// expands the new file's ancestors so it's visible.
    pub fn load_workspace_file(&mut self, path: PathBuf) -> std::io::Result<()> {
        // Prefer edits parked when we switched away from this file — they are
        // by definition newer than what is still on disk. Read (and fail) before
        // touching any state, so a vanished file leaves the tab as it was.
        let entries = match self.workspace_pending.get(&path) {
            Some(parked) => parked.clone(),
            None => crate::postman::parse_collection(&std::fs::read_to_string(&path)?),
        };
        self.workspace_pending.remove(&path);
        // Park the outgoing file *before* adopting the incoming file's flag,
        // since parking reads `structure_modified` for the file being left.
        self.park_pending_edits();
        // The incoming file's structural flag is about to be re-derived from its
        // baseline, so the parked copy has done its job (it existed only to
        // answer "is this parked file dirty" while the file was away).
        self.workspace_structure_modified.remove(&path);
        self.park_run_results();
        self.snapshot_loaded_titles();
        self.entries = entries;
        // A file coming back out of the park keeps the baseline it was parked
        // with, because that baseline still describes the file on disk; one read
        // fresh off disk simply *is* its own baseline. Either way the flag is
        // derived from the comparison, so a file whose reorder has since been
        // undone comes back clean instead of staying marked for the session.
        match self.workspace_baselines.remove(&path) {
            Some(baseline) => {
                self.structure_baseline = baseline;
                self.refresh_structure_modified();
            }
            None => self.reset_structure_baseline(),
        }
        self.restore_run_results(&path);
        self.selected_entry = 0;
        self.path = Some(path);
        self.invalidate_request_json();
        self.sync_folder_to_selected();
        self.expand_ancestors_for_path();
        self.sync_ws_cursor();
        Ok(())
    }

    /// Park the loaded file's unsaved edits in `workspace_pending` so they
    /// survive a switch to another file in the same Workspace tab. A file with
    /// no edits is not parked — re-reading it from disk is both cheaper and
    /// more correct, since it picks up any change made outside PaperBoy.
    fn park_pending_edits(&mut self) {
        if self.workspace_root.is_none() || !self.has_unsaved_edits() {
            return;
        }
        if let Some(path) = self.path.clone() {
            if self.structure_modified {
                self.workspace_structure_modified.insert(path.clone());
            }
            // The baseline travels with the parked entries: it describes the
            // file on disk, which is still what this file will have to be
            // compared against when it comes back.
            self.workspace_baselines
                .insert(path.clone(), self.structure_baseline.clone());
            self.workspace_pending.insert(path, self.entries.clone());
        }
    }

    /// Park the loaded file's run results so they survive a switch to another
    /// file in the same Workspace tab (see [`RunRecord`]).
    ///
    /// Unlike [`Self::park_pending_edits`] this runs whether or not the file
    /// has been edited: an unedited file is re-read from disk when it comes
    /// back, and a fresh parse has never been run.
    fn park_run_results(&mut self) {
        if self.workspace_root.is_none() {
            return;
        }
        let Some(path) = self.path.clone() else {
            return;
        };
        let records: Vec<RunRecord> = self
            .entries
            .iter()
            .map(|e| RunRecord {
                key: run_key(e),
                last_run: e.last_run,
                last_response: e.last_response.clone(),
            })
            .collect();
        // Nothing has been run: don't hold a row of empty records that would
        // only have to be checked later.
        if records
            .iter()
            .all(|r| r.last_run == RunStatus::NotRun && r.last_response.is_none())
        {
            self.workspace_runs.remove(&path);
        } else {
            self.workspace_runs.insert(path, records);
        }
    }

    /// Put previously parked run results back onto the entries just loaded
    /// from `path`, by position and only where the request still matches (see
    /// [`RunRecord::key`]). An entry that already carries a result keeps it:
    /// entries handed back from `workspace_pending` were never re-read, so
    /// theirs is the live one.
    fn restore_run_results(&mut self, path: &Path) {
        let Some(records) = self.workspace_runs.get(path) else {
            return;
        };
        for (entry, record) in self.entries.iter_mut().zip(records.iter()) {
            if entry.last_run != RunStatus::NotRun || entry.last_response.is_some() {
                continue;
            }
            if run_key(entry) == record.key {
                entry.last_run = record.last_run;
                entry.last_response = record.last_response.clone();
            }
        }
    }

    /// The run marker to show for request `idx` of the workspace file at
    /// `path`, whether or not that file is the one this tab has loaded.
    ///
    /// The tree used to draw markers for the loaded collection only, on the
    /// grounds that nothing else could have been run — which stopped being
    /// true the moment results outlived the file being loaded.
    pub fn workspace_run_status(&self, path: &Path, idx: usize) -> RunStatus {
        if self.path.as_deref() == Some(path) {
            return self
                .entries
                .get(idx)
                .map(|e| e.last_run)
                .unwrap_or(RunStatus::NotRun);
        }
        // A file with parked *edits* keeps its entries whole, results included;
        // only a file that will be re-read needs the parked records.
        if let Some(parked) = self.workspace_pending.get(path) {
            return parked
                .get(idx)
                .map(|e| e.last_run)
                .unwrap_or(RunStatus::NotRun);
        }
        self.workspace_runs
            .get(path)
            .and_then(|r| r.get(idx))
            .map(|r| r.last_run)
            .unwrap_or(RunStatus::NotRun)
    }

    /// The entry list's structural identity: the [`HurlEntry::uid`] of each
    /// entry, in order.
    fn structure_fingerprint(&self) -> Vec<u64> {
        self.entries.iter().map(|e| e.uid).collect()
    }

    /// Adopt the current entry list as "what was saved", so nothing that
    /// follows counts as a structural change until the list moves again.
    ///
    /// Stamps every entry with a fresh identity as it goes, which is what makes
    /// the comparison work at all: from here on an entry can be edited, moved
    /// or removed and its stamp goes with it, so the list can always be told
    /// apart from a rearrangement of itself. Re-stamping (rather than keeping
    /// the old numbers) is what makes a *duplicated* request — a clone, and so
    /// initially a second entry carrying the same stamp — settle back down to a
    /// list of unique identities once it is saved.
    ///
    /// Called wherever the list and the file are brought into agreement:
    /// reading a file, writing one, and constructing a collection from entries
    /// that came straight off disk.
    /// Adopt a list restored from `state.json`: stamp identities, but keep what
    /// each entry already recorded the file as saying.
    ///
    /// A restored snapshot is *not* a moment of agreement — it is whatever the
    /// user had on screen when they quit, unsaved edits and all. Treating it as
    /// one (which building any collection from entries does) overwrote each
    /// request's record of its file with its own edited text, so a restarted
    /// session lost the pencil on requests that genuinely had unsaved changes,
    /// and could no longer find any of them in their file to revert them.
    ///
    /// `modified` is re-derived here rather than trusted from the saved state,
    /// for the same reason it is derived everywhere else: the text and the
    /// baseline together are the answer, and a stored flag can only disagree
    /// with them.
    ///
    /// The baselines have to be handed in because building the collection has
    /// already restamped them: this puts back what the snapshot recorded.
    pub fn adopt_restored_entries(&mut self, baselines: Vec<Option<String>>) {
        for (e, baseline) in self.entries.iter_mut().zip(baselines) {
            if let Some(baseline) = baseline {
                e.baseline = Some(baseline);
                e.mark_edited();
            }
        }
        // The list itself may differ from the file (a request added, deleted or
        // dragged and left unsaved), and the stamps that would say so were
        // runtime-only and went with the last session. All that can be answered
        // here is the added case, which `user_added` records; the rest needs the
        // file, so `rebuild_restored_structure_baseline` refines this once the
        // path is known.
        self.structure_modified = self.entries.iter().any(|e| e.user_added);
    }

    /// Check each restored baseline against the file, and re-derive any the
    /// file does not recognise.
    ///
    /// A baseline is a record of *what the file says*, so it must appear in the
    /// file. One that does not was invented: builds before the restore path
    /// kept baselines re-stamped every restored entry from its own edited text,
    /// freezing whatever was unsaved at the time into the record of the file.
    /// The pencil then never cleared -- undoing the edit made the request
    /// differ from its "file" again -- and reverting would have put the unsaved
    /// edit back as though it were saved work.
    ///
    /// Only attempted when the list and the file are the same length, which is
    /// the same condition every other position-based answer here is given
    /// under: with a request added or deleted, position means nothing and a
    /// guess would be a silent, wrong answer about which file text belongs to
    /// which request.
    pub fn repair_restored_baselines(&mut self) {
        let Some(path) = self.path.clone() else {
            return;
        };
        let Ok(content) = std::fs::read_to_string(&path) else {
            return;
        };
        let disk = crate::postman::parse_collection(&content);
        if disk.len() != self.entries.len() {
            return;
        }
        let texts: Vec<String> = disk.iter().map(|e| e.to_hurl()).collect();
        for (i, e) in self.entries.iter_mut().enumerate() {
            let recognised = e
                .baseline
                .as_ref()
                .is_some_and(|b| texts.iter().any(|t| t == b));
            if !recognised {
                e.baseline = Some(texts[i].clone());
                e.mark_edited();
            }
        }
    }

    /// Rebuild the structural baseline from the *file* after a restore, so a
    /// request deleted or dragged and left unsaved is still counted.
    ///
    /// Building a collection stamps its entries and adopts that list as the
    /// baseline, which for a restored session means adopting whatever was on
    /// screen when the user quit -- including a deletion or a reorder they had
    /// not saved. The tab then came back looking clean, and quitting a second
    /// time asked nothing: the change was simply lost, which is the one
    /// outcome the unsaved-changes prompt exists to prevent. (An *added*
    /// request survived only because `user_added` is persisted and was checked
    /// separately.)
    ///
    /// The stamps themselves cannot answer -- they are runtime-only and went
    /// with the last session -- but each entry's recorded baseline text can:
    /// it is what the file said about that request, so matching those against
    /// the file reconstructs which of the file's requests the list still holds,
    /// and in what order. A request the file holds that the list does not gets
    /// an identity no live entry carries, so the two lists differ and the
    /// deletion shows. Matches are consumed as they are used, so two identical
    /// requests in a file are accounted for one each rather than both being
    /// credited to the same entry.
    ///
    /// Run after [`Self::repair_restored_baselines`], which is what makes the
    /// recorded texts trustworthy enough to match on.
    pub fn rebuild_restored_structure_baseline(&mut self) {
        let Some(path) = self.path.clone() else {
            return;
        };
        let Ok(content) = std::fs::read_to_string(&path) else {
            return;
        };
        let disk = crate::postman::parse_collection(&content);
        let mut used = vec![false; self.entries.len()];
        let mut baseline = Vec::with_capacity(disk.len());
        for text in disk.iter().map(|e| e.to_hurl()) {
            // A request built by hand this session is not one of the file's,
            // whatever text it carries: a copy starts life holding the copied
            // request's baseline.
            let live = self.entries.iter().enumerate().position(|(i, e)| {
                !used[i] && !e.user_added && e.baseline.as_deref() == Some(text.as_str())
            });
            match live {
                Some(i) => {
                    used[i] = true;
                    baseline.push(self.entries[i].uid);
                }
                None => baseline.push(NEXT_ENTRY_UID.fetch_add(1, Ordering::Relaxed)),
            }
        }
        self.structure_baseline = baseline;
        self.refresh_structure_modified();
    }

    pub fn reset_structure_baseline(&mut self) {
        for e in &mut self.entries {
            e.uid = NEXT_ENTRY_UID.fetch_add(1, Ordering::Relaxed);
            // The same moment settles each request's *content* baseline: this
            // is where the list and the file agree, so it is where "what the
            // file says" is worth recording (see `HurlEntry::baseline`).
            e.set_baseline();
        }
        self.structure_baseline = self.structure_fingerprint();
        self.structure_modified = false;
    }

    /// Recompute [`Self::structure_modified`] by comparing the entry list
    /// against the baseline.
    ///
    /// Every structural edit routes through here rather than setting the flag,
    /// so that undoing one clears it: putting a dragged request back where it
    /// started, or restoring the request just deleted, returns the list to the
    /// one that was saved and there is then genuinely nothing to save. A latched
    /// flag left the pencil on with nothing behind it, which teaches people to
    /// ignore the pencil.
    fn refresh_structure_modified(&mut self) {
        self.structure_modified = self.structure_fingerprint() != self.structure_baseline;
    }

    /// `true` when this collection holds requests that have been added or
    /// edited since it was last read from / written to disk.
    pub fn has_unsaved_edits(&self) -> bool {
        self.structure_modified || self.entries.iter().any(|e| e.user_added || e.modified)
    }

    /// How many unsaved changes this tab is holding, counting a Workspace
    /// tab's parked files as well as the one it is showing.
    ///
    /// Mostly this is the added-but-unsaved and edited requests, one apiece.
    /// A file that has been changed *structurally* — a request removed,
    /// restored or reordered — counts one more, because no surviving request
    /// carries a marker for it and it would otherwise total zero: this number
    /// gates the "you have unsaved edits" prompt on closing a tab
    /// ([`crate::gui::app::GuiApp::request_close_tab`]), so a delete-only
    /// change reading as nothing meant closing the tab threw it away without
    /// asking. One per file rather than one per removal, because how many
    /// there were is not recorded — only that the list no longer matches disk.
    pub fn unsaved_edit_count(&self) -> usize {
        let edited = |entries: &[HurlEntry]| {
            entries
                .iter()
                .filter(|e| e.user_added || e.modified)
                .count()
        };
        let loaded = edited(&self.entries) + usize::from(self.structure_modified);
        let parked: usize = self
            .workspace_pending
            .iter()
            // The loaded file is parked *and* live while it is being shown, so
            // counting both would double it.
            .filter(|(path, _)| self.path.as_deref() != Some(path.as_path()))
            .map(|(path, entries)| {
                edited(entries) + usize::from(self.workspace_structure_modified.contains(path))
            })
            .sum();
        loaded + parked
    }

    /// How many of this tab's request edits would be gone for good after a
    /// quit — the question to ask before warning about closing the app, as
    /// opposed to [`Self::unsaved_edit_count`], which answers what closing
    /// *this tab* would throw away.
    ///
    /// The two differ because quitting is not the same as discarding. A plain
    /// tab's entries are written to the session state verbatim, edit markers
    /// included, so its edits are still there — still flagged, still unsaved —
    /// next time the app starts; warning about those taught the user to dismiss
    /// a dialog that was never true. A Workspace tab is the exception: it is
    /// bound to a live folder rather than to a snapshot, so its entries are
    /// deliberately not persisted and its selected file is re-read from disk on
    /// restore, which does drop anything edited but not saved.
    #[cfg_attr(not(feature = "gui"), allow(dead_code))]
    pub fn edits_lost_on_exit(&self) -> usize {
        if self.workspace_root.is_some() {
            self.unsaved_edit_count()
        } else {
            0
        }
    }

    /// `true` when the workspace collection file at `path` has unsaved edits —
    /// either it is the loaded file and that has been edited, or it was edited
    /// and then switched away from (so it lives in `workspace_pending`). Drives
    /// the "edited" pencil in the workspace tree.
    pub fn workspace_file_edited(&self, path: &std::path::Path) -> bool {
        if self.workspace_pending.contains_key(path) {
            return true;
        }
        self.path.as_deref() == Some(path) && self.has_unsaved_edits()
    }

    /// Whether anything at or under `prefix` has unsaved in-memory edits — the
    /// generalisation of [`Self::workspace_file_edited`] to a whole subtree, so
    /// a delete confirmation can warn that removing a folder is about to throw
    /// away edits parked in files inside it. Covers the loaded file, the files
    /// parked in `workspace_pending`, and structural-only changes
    /// (`workspace_structure_modified`) that leave no per-request marker.
    #[cfg_attr(not(feature = "gui"), allow(dead_code))]
    pub fn workspace_unsaved_under(&self, prefix: &std::path::Path) -> bool {
        if self.path.as_deref().is_some_and(|p| p.starts_with(prefix)) && self.has_unsaved_edits() {
            return true;
        }
        self.workspace_pending.keys().any(|p| p.starts_with(prefix))
            || self
                .workspace_structure_modified
                .iter()
                .any(|p| p.starts_with(prefix))
    }

    /// Whether request `idx` of the workspace collection file at `path` has
    /// unsaved edits. Answers for a file that isn't the loaded one too, by
    /// reading the entries parked in `workspace_pending` — the tree lists a
    /// non-loaded collection's requests from the `workspace_titles` cache, which
    /// was snapshotted from those same (edited) entries, so the indices line up.
    /// Without this, opening a second collection made the first one's pencils
    /// disappear from its rows even though the edits were still pending.
    pub fn workspace_request_edited(&self, path: &std::path::Path, idx: usize) -> bool {
        let entries = if self.path.as_deref() == Some(path) {
            &self.entries
        } else {
            match self.workspace_pending.get(path) {
                Some(parked) => parked,
                None => return false,
            }
        };
        entries.get(idx).is_some_and(|e| e.user_added || e.modified)
    }

    /// Discard request `ei`'s in-memory edits by reloading that single entry
    /// out of this collection's on-disk file (#19).
    ///
    /// The entry is found on disk by the identity it has carried since the list
    /// and the file last agreed ([`HurlEntry::uid`]), *not* by its position.
    /// Position is only the same thing while nothing structural has happened,
    /// and reverting is offered from the same menu as Duplicate and drag-
    /// reorder: with an unsaved duplicate above it, request B sat at index 1 in
    /// memory and index 2 on disk, so reverting B restored C over the top of it
    /// and B's edits were gone — a silent, unrecoverable loss of exactly the
    /// work the user was trying to keep.
    ///
    /// Returns the reverted request's HTTP method on success, or `None` when
    /// there's nothing to revert to — the collection has no file (scratch), the
    /// file can't be read/parsed, the entry was never saved (a new request, or
    /// a duplicate that still shares its original's identity), or the file has
    /// since changed underneath us so no entry can be confidently matched.
    /// The other entries and their edits are untouched.
    pub fn revert_request(&mut self, ei: usize) -> Option<String> {
        let path = self.path.clone()?;
        let uid = self.entries[ei].uid;
        let content = std::fs::read_to_string(&path).ok()?;
        let mut disk = crate::postman::parse_collection(&content);
        let di = self.disk_position_of(ei, &disk)?;
        let entry = disk.swap_remove(di);
        let method = entry.method.clone();
        // A freshly parsed entry is clean (not modified/added) but carries no
        // stamp; it has to keep the one it is replacing, or the list would
        // suddenly read as structurally different from the file it just came
        // from and the collection would claim unsaved changes it doesn't have.
        self.entries[ei] = HurlEntry { uid, ..entry };
        // It came straight out of the file, so the file is what later edits are
        // measured against. Without a baseline `mark_edited` latches (see
        // `HurlEntry::baseline`), so anything that so much as touched the
        // reverted request afterwards put the pencil back on a request that
        // matched what was on disk.
        self.entries[ei].set_baseline();
        self.invalidate_request_json();
        self.sync_folder_to_selected();
        Some(method)
    }

    /// Where the request at `ei` sits in the file this collection was loaded
    /// from, if it can be matched to it at all.
    ///
    /// Split out of [`Self::revert_request`] because the front-ends need to ask
    /// the same question *before* they offer to revert: confirming a revert and
    /// only then reporting "nothing to revert" makes the user commit to
    /// something that was never going to happen. Every reason to decline that
    /// can be answered without reading the file is answered here, so the two
    /// cannot drift apart; the rest (the file changed, or can't be read since)
    /// necessarily stays with the read.
    /// Which entry of the file just read is request `ei`, if it can be pointed
    /// at with confidence.
    ///
    /// Two ways of asking, because the first only holds while the list and the
    /// file are still the same shape:
    ///
    /// * by identity and position — the stamp the entry has carried since the
    ///   list and the file last agreed, looked up in the baseline. Only
    ///   meaningful while the file is still the length that baseline describes.
    /// * by the text the entry recorded the file as holding
    ///   ([`HurlEntry::baseline`]), matched against the file. This is what
    ///   answers after a restart: a restored list adopts itself as its
    ///   structural baseline, so a request added and left unsaved before the
    ///   restart made the baseline describe a file one request longer than the
    ///   real one -- and *every* request in the tab then failed the length
    ///   check and could not be reverted at all. A unique text match is asked
    ///   for: two identical requests in a file cannot be told apart, and
    ///   restoring the wrong one would be a silent, unrecoverable loss of
    ///   exactly the work the user was trying to keep.
    fn disk_position_of(&self, ei: usize, disk: &[HurlEntry]) -> Option<usize> {
        if let Some(di) = self.saved_position_of(ei)
            && disk.len() == self.structure_baseline.len()
            && di < disk.len()
        {
            return Some(di);
        }
        let entry = self.entries.get(ei)?;
        // A request the user built by hand has no saved version, whatever text
        // it carries: a copy of another request starts life with the copied
        // request's baseline, and matching on that would "revert" the new
        // request into the one it was copied from.
        if entry.user_added {
            return None;
        }
        let baseline = entry.baseline.as_ref()?;
        let mut hits = disk
            .iter()
            .enumerate()
            .filter(|(_, e)| &e.to_hurl() == baseline)
            .map(|(i, _)| i);
        let first = hits.next()?;
        hits.next().is_none().then_some(first)
    }

    pub fn saved_position_of(&self, ei: usize) -> Option<usize> {
        self.path.as_ref()?;
        let uid = self.entries.get(ei)?.uid;
        // Zero is "never stamped" -- a request built in this session, which the
        // file has never held. A duplicate is a clone, and so carries its
        // original's stamp until the file is saved: two entries answering to
        // one identity means we cannot say which of them the file's entry
        // belongs to, so we decline.
        if uid == 0 || self.entries.iter().filter(|e| e.uid == uid).count() != 1 {
            return None;
        }
        self.structure_baseline.iter().position(|u| *u == uid)
    }

    /// Throw away every in-memory edit to the workspace collection file at
    /// `path`, so the tab shows exactly what is on disk again.
    ///
    /// Works whether or not `path` is the file this tab currently has loaded:
    /// an edited file switched away from lives on in `workspace_pending`, and
    /// its requests are what the tree lists for it, so both places have to be
    /// dropped or the edits would come back the moment it was reopened. Errors
    /// if the file can't be re-read, and changes nothing in that case.
    /// Whether request `ei` has a saved version to go back to at all, as far as
    /// can be told without reading the file.
    ///
    /// The front-ends ask before offering to revert: confirming a revert and
    /// only then reporting "nothing to revert" makes the user commit to
    /// something that was never going to happen. Either route in
    /// `disk_position_of` may find it, so either one being possible is enough.
    pub fn has_saved_version(&self, ei: usize) -> bool {
        let Some(e) = self.entries.get(ei) else {
            return false;
        };
        self.path.is_some()
            && (self.saved_position_of(ei).is_some() || (e.baseline.is_some() && !e.user_added))
    }

    pub fn revert_workspace_file(&mut self, path: &std::path::Path) -> std::io::Result<()> {
        let entries = crate::postman::parse_collection(&std::fs::read_to_string(path)?);
        self.workspace_pending.remove(path);
        if self.path.as_deref() == Some(path) {
            let sel = self.selected_entry;
            // Reverting throws away *edits*, not the record of what happened
            // when these requests were last run — so the results are parked
            // across the reload like they are across a file switch.
            self.park_run_results();
            self.entries = entries;
            // Straight off disk, so that is what later edits are measured
            // against -- see the note in `revert_request`.
            self.reset_structure_baseline();
            self.restore_run_results(path);
            self.selected_entry = sel.min(self.entries.len().saturating_sub(1));
            self.invalidate_request_json();
            self.sync_folder_to_selected();
        } else {
            // Not loaded: the tree lists it from the title cache, which was
            // snapshotted off the edited entries. Re-snapshot from disk so the
            // row names match the file again.
            let titles = entries.iter().map(ws_request_title).collect();
            self.workspace_titles.insert(path.to_path_buf(), titles);
        }
        Ok(())
    }

    /// Repoint everything this tab holds about a workspace item that has just
    /// been renamed or moved on disk from `from` to `to` — the loaded file, the
    /// remembered selection, the expand/collapse set, and every by-path cache
    /// keyed on it — so nothing goes on pointing at a path that no longer
    /// exists. [`crate::workspace::repoint`] matches the item itself *and*
    /// anything that was inside it, so renaming or moving a folder carries its
    /// children's state along too.
    ///
    /// Every by-path map is rewritten, not just the visible ones: the parked
    /// edits, structure baselines and run results are exactly the state that
    /// makes "edit a file, look at another, come back" work, and leaving them
    /// keyed on the old path would silently drop a renamed file's unsaved work.
    #[cfg_attr(not(feature = "gui"), allow(dead_code))]
    pub fn repoint_workspace_paths(&mut self, from: &std::path::Path, to: &std::path::Path) {
        use crate::workspace::repoint;
        let moved = |p: &std::path::Path| repoint(p, from, to);
        if let Some(p) = self.path.as_deref().and_then(moved) {
            self.path = Some(p);
        }
        if let Some(p) = self.workspace_selected.as_deref().and_then(moved) {
            self.workspace_selected = Some(p);
        }
        self.workspace_expanded = self
            .workspace_expanded
            .drain()
            .map(|p| moved(&p).unwrap_or(p))
            .collect();
        self.workspace_titles = self
            .workspace_titles
            .drain()
            .map(|(p, v)| (moved(&p).unwrap_or(p), v))
            .collect();
        self.workspace_pending = self
            .workspace_pending
            .drain()
            .map(|(p, v)| (moved(&p).unwrap_or(p), v))
            .collect();
        self.workspace_baselines = self
            .workspace_baselines
            .drain()
            .map(|(p, v)| (moved(&p).unwrap_or(p), v))
            .collect();
        self.workspace_structure_modified = self
            .workspace_structure_modified
            .drain()
            .map(|p| moved(&p).unwrap_or(p))
            .collect();
        self.workspace_runs = self
            .workspace_runs
            .drain()
            .map(|(p, v)| (moved(&p).unwrap_or(p), v))
            .collect();
    }

    /// Drop everything this tab was holding about the workspace item at
    /// `deleted` — and, when it is a folder, everything that was inside it —
    /// because the item has just been removed from disk.
    ///
    /// If the *loaded* file was under the deletion, the tab is reset to the
    /// file-less state a fresh Workspace tab starts in: leaving `entries`
    /// showing the requests of a file that no longer exists would be a phantom
    /// the user could keep editing and try to save into thin air. Every by-path
    /// cache is pruned of the deleted subtree so no stale pencil, run marker or
    /// parked edit survives — and so a later, same-named file can't inherit the
    /// dead one's state.
    #[cfg_attr(not(feature = "gui"), allow(dead_code))]
    pub fn prune_workspace_paths(&mut self, deleted: &std::path::Path) {
        let under = |p: &std::path::Path| p.starts_with(deleted);
        if self.path.as_deref().is_some_and(under) {
            self.path = None;
            self.entries.clear();
            self.selected_entry = 0;
            self.structure_modified = false;
            self.structure_baseline.clear();
            self.invalidate_request_json();
        }
        if self.workspace_selected.as_deref().is_some_and(under) {
            self.workspace_selected = None;
        }
        self.workspace_expanded.retain(|p| !under(p));
        self.workspace_titles.retain(|p, _| !under(p));
        self.workspace_pending.retain(|p, _| !under(p));
        self.workspace_baselines.retain(|p, _| !under(p));
        self.workspace_structure_modified.retain(|p| !under(p));
        self.workspace_runs.retain(|p, _| !under(p));
    }

    /// Clear this collection's "new"/"edited" request markers, and drop any
    /// parked edits for its file — called whenever its `.hurl` is written to
    /// disk (local Save or git push) so every save path agrees on what "saved"
    /// means.
    pub fn mark_saved(&mut self) {
        for e in &mut self.entries {
            e.user_added = false;
            e.modified = false;
        }
        // The file on disk now *is* the entry list, so it becomes the baseline
        // every later structural edit is measured against.
        self.reset_structure_baseline();
        if let Some(path) = &self.path {
            self.workspace_pending.remove(path);
            self.workspace_structure_modified.remove(path);
        }
    }

    /// Write every edited file this Workspace tab is holding back to disk — the
    /// one it is showing as well as the ones parked in `workspace_pending` —
    /// and clear the edit markers. Returns how many files were written, or the
    /// first path that could not be, so the caller can say which one failed.
    ///
    /// This is what "Save all changes" on the quit dialog needs, and it is
    /// deliberately the same set of files that [`Self::edits_lost_on_exit`]
    /// counts: an ordinary tab is left alone because its edits are persisted to
    /// the session state rather than lost, so silently writing them out to a
    /// file on the way out of the app would be doing something the user never
    /// asked for. A Workspace tab's edits, by contrast, have a file they came
    /// from and are otherwise dropped on exit.
    #[cfg_attr(not(feature = "gui"), allow(dead_code))]
    pub fn save_workspace_edits(&mut self) -> Result<usize, String> {
        if self.workspace_root.is_none() {
            return Ok(0);
        }
        let mut written = 0usize;
        // The loaded file first: saving it also drops its parked copy, so the
        // parked pass below can't then write a stale snapshot back over it.
        if self.has_unsaved_edits()
            && let Some(path) = self.path.clone()
        {
            write_hurl(&path, &self.to_hurl())?;
            written += 1;
        }
        let parked: Vec<(PathBuf, Vec<HurlEntry>)> = self
            .workspace_pending
            .iter()
            .filter(|(path, _)| self.path.as_deref() != Some(path.as_path()))
            .map(|(p, e)| (p.clone(), e.clone()))
            .collect();
        for (path, entries) in parked {
            // A parked file whose only change was a deletion or a reorder has
            // no flagged entry to find — `workspace_structure_modified` is the
            // only record that it differs from disk.
            if !self.workspace_structure_modified.contains(&path)
                && !entries.iter().any(|e| e.user_added || e.modified)
            {
                continue;
            }
            write_hurl(&path, &collection_to_hurl(&entries))?;
            written += 1;
        }
        self.workspace_pending.clear();
        // Everything parked has just been written, so no file is structurally
        // ahead of disk any more; `mark_saved` only clears the loaded one.
        self.workspace_structure_modified.clear();
        self.mark_saved();
        Ok(written)
    }

    /// Re-read the request names of every expanded collection file that isn't
    /// the currently-loaded one, populating `workspace_titles` from disk. Used    /// after restoring persisted state, where collections expanded last session
    /// must list their requests without having been opened yet this session.
    pub fn rebuild_expanded_titles(&mut self) {
        let loaded = self.path.clone();
        let paths: Vec<PathBuf> = self.workspace_expanded.iter().cloned().collect();
        for p in paths {
            if Some(&p) == loaded.as_ref()
                || !p.is_file()
                || crate::workspace::is_report_file(&p)
                || crate::workspace::is_env_file(&p)
            {
                continue;
            }
            let titles = read_collection_labels(&p);
            self.workspace_titles.insert(p, titles);
        }
    }

    /// Expand all ancestor folders of the currently-loaded file, and the file
    /// itself, so it (and its inline requests) are visible in the workspace
    /// tree.  A no-op for a non-Workspace tab or when no file is loaded.  Called
    /// by [`crate::tui::app`] after loading a file and by [`crate::persistence`]
    /// when restoring state.
    pub fn expand_ancestors_for_path(&mut self) {
        let (Some(root), Some(path)) = (&self.workspace_root, &self.path) else {
            return;
        };
        // Clone to avoid the simultaneous &self borrow.
        let root = root.clone();
        let path = path.clone();
        // The loaded file itself is expanded so its requests show by default.
        self.workspace_expanded.insert(path.clone());
        if let Some(parent) = path.parent()
            && let Ok(rel) = parent.strip_prefix(&root)
        {
            let mut cur = root;
            for component in rel.components() {
                cur.push(component);
                self.workspace_expanded.insert(cur.clone());
            }
        }
    }

    /// For a Workspace tab, move `list_cursor` onto the row for
    /// `selected_entry` (a request of the open collection) if it's visible,
    /// otherwise onto the open collection's file row, otherwise the top.
    /// A no-op for a non-Workspace tab.
    pub fn sync_ws_cursor(&mut self) {
        if !self.is_workspace() {
            return;
        }
        // A request nested in a virtual folder is hidden until that folder is
        // open, and this is the one call that says "put the cursor on the
        // selected request" — so it has to make it reachable first, or the
        // cursor would silently fall back to the file row every time a nested
        // request was selected from outside the tree (loading a file, saving
        // the wizard, renaming).
        self.expand_selected_request_folders();
        let rows = self.ws_rows();
        let sel = self.selected_entry;
        let loaded = self.path.clone();
        let target = rows
            .iter()
            .position(|r| {
                matches!(r, WsRow::Request { collection, idx, .. }
                    if *idx == sel && Some(collection) == loaded.as_ref())
            })
            .or_else(|| {
                rows.iter().position(|r| {
                    matches!(r, WsRow::Collection { path, open: true, .. }
                        if Some(path) == loaded.as_ref())
                })
            })
            .unwrap_or(0);
        self.list_cursor = target.min(rows.len().saturating_sub(1));
    }

    /// Open every virtual folder containing the loaded file's `selected_entry`,
    /// so its row is visible in the workspace tree. A no-op when the selected
    /// request sits at the top level of its file (the common case), so this
    /// doesn't fight a user who has deliberately folded things away.
    fn expand_selected_request_folders(&mut self) {
        let Some(path) = self.path.clone() else {
            return;
        };
        let Some(title) = self
            .entries
            .get(self.selected_entry)
            .map(|e| e.title.clone())
        else {
            return;
        };
        let segs = tree::entry_path(&title);
        // The last segment is the request itself, not a folder.
        for n in 1..segs.len() {
            self.workspace_expanded
                .insert(request_folder_path(&path, &segs[..n]));
        }
    }

    /// Re-derive `folder`/`list_cursor` so the Requests list is browsing (and
    /// highlighting) `selected_entry`. Call this any time `selected_entry` is
    /// changed programmatically (as opposed to normal Up/Down/Enter list
    /// navigation, which keeps the two in sync itself) — e.g. after adding,
    /// deleting, or renaming a request, or restoring persisted state.
    /// A Workspace tab's `list_cursor` indexes the file tree
    /// ([`Self::ws_rows`]), not the request list, so the row it wants is the
    /// one [`Self::sync_ws_cursor`] computes. Writing a request-list index
    /// into it here would point at an unrelated file (usually the top of the
    /// tree), which is what saving an edited request used to do: commit the
    /// wizard, and the selection left the request and jumped to the first row
    /// of the workspace.
    pub fn sync_folder_to_selected(&mut self) {
        if self.is_workspace() {
            let idx = self
                .selected_entry
                .min(self.entries.len().saturating_sub(1));
            self.selected_entry = idx;
            if !self.entries.is_empty() {
                self.reveal(idx);
            }
            self.sync_ws_cursor();
            return;
        }
        if self.entries.is_empty() {
            self.expanded.clear();
            self.list_cursor = 0;
            return;
        }
        let idx = self.selected_entry.min(self.entries.len() - 1);
        self.selected_entry = idx;
        self.reveal(idx);
        let rows = self.rows();
        self.list_cursor = rows.iter().position(|r| *r == Row::Entry(idx)).unwrap_or(0);
    }

    /// Open every folder above `entries[idx]`, so a request that is selected
    /// is a request that can be seen. Nothing else is closed: the user's other
    /// open folders are theirs.
    pub fn reveal(&mut self, idx: usize) {
        self.expanded
            .extend(tree::ancestors_of(&tree::folder_of(&self.entries, idx)));
    }

    /// Remove the entry at `idx`, recording it (with the index it came from)
    /// in `deleted_entries` so [`Self::restore_last_deleted`] can bring it
    /// back. This is the part of "delete a request" both front-ends have to
    /// agree on — one undo history and one 20-entry cap — everything around it
    /// differs (the terminal UI also moves its list cursor, sets a status line
    /// and persists state; the graphical one doesn't), so those stay in each
    /// front-end's own delete method instead of being forced in here.
    ///
    /// Returns `None` for an out-of-range `idx` rather than panicking the way
    /// `Vec::remove` would: the index reaching here came from a list row or a
    /// context menu rendered from an earlier borrow of `entries`, so it is
    /// exactly the kind of index that can go stale between being read and
    /// being used.
    pub fn remove_entry_recording_undo(&mut self, idx: usize) -> Option<HurlEntry> {
        if idx >= self.entries.len() {
            return None;
        }
        let removed = self.entries.remove(idx);
        self.refresh_structure_modified();
        self.deleted_entries.push((idx, removed.clone()));
        if self.deleted_entries.len() > 20 {
            self.deleted_entries.remove(0);
        }
        Some(removed)
    }

    /// Move the entry at `from` so it sits at index `to`, shifting everything
    /// between them along. Returns whether anything actually moved.
    ///
    /// The order of `entries` is not cosmetic: `run_all_entries` walks it in
    /// order, so it decides which request captures a token before another one
    /// uses it. Until this existed the only way to change that was to delete a
    /// request and recreate it further down.
    ///
    /// Remove-and-insert rather than a swap, because the two requests a user
    /// sees as neighbours need not be neighbours in `entries` at all — folders
    /// are derived by splitting titles on `/` (see [`crate::tree`]), so a
    /// folder's requests can be scattered through the vector with other
    /// folders' requests in between. Swapping would drag whichever unrelated
    /// request sat at `to` across to `from`; shifting leaves everything else in
    /// the order it was.
    ///
    /// Reordering is safe for reports, which address requests by title rather
    /// than position (`report::run::resolve_qualified`) — unlike renaming.
    pub fn move_entry(&mut self, from: usize, to: usize) -> bool {
        let len = self.entries.len();
        if from >= len || to >= len || from == to {
            return false;
        }
        let entry = self.entries.remove(from);
        self.entries.insert(to, entry);
        // The selection is a position, so it has to be re-derived rather than
        // left pointing at whatever slid into the old index: the moved request
        // takes its selection with it, and a selection either side of the move
        // shifts by one only if the move stepped across it.
        self.selected_entry = shift_index(self.selected_entry, from, to);
        // A reorder changes no request, so nothing else would record it — see
        // `structure_modified`. Recomputed rather than latched, so dragging a
        // request back where it started clears the marker again.
        self.refresh_structure_modified();
        self.invalidate_request_json();
        self.sync_folder_to_selected();
        true
    }

    /// Move the entry at `from` so it ends up immediately *before* the entry
    /// currently at `before` — the drag-and-drop spelling of [`Self::move_entry`],
    /// where a drop lands in the gap above a row rather than on a slot number.
    /// `before == entries.len()` means "after the last one". Returns whether
    /// anything actually moved.
    ///
    /// The index has to be adjusted when dragging *downwards*: `move_entry`
    /// removes before it inserts, so once the dragged request is lifted out
    /// every row below it slides up by one and the gap the user aimed at is now
    /// one lower. Without this the request would consistently land one place
    /// short of where it was dropped, which reads as the drop being ignored.
    ///
    /// Only the GUI drags requests; the terminal UI reorders with `Alt+↑↓`
    /// through `move_entry`, so this is dead code without the `gui` feature.
    #[cfg_attr(not(feature = "gui"), allow(dead_code))]
    pub fn move_entry_before(&mut self, from: usize, before: usize) -> bool {
        let len = self.entries.len();
        if from >= len || before > len {
            return false;
        }
        // Dropping into either gap touching the request is where it already is.
        if before == from || before == from + 1 {
            return false;
        }
        let to = if from < before { before - 1 } else { before };
        self.move_entry(from, to)
    }

    /// Reopen the most recently deleted entry (if any), re-inserting it as
    /// close as possible to the index it was removed from, and return that
    /// index so the caller can select it. `None` when there is nothing to
    /// restore, which both front-ends treat as a no-op.
    pub fn restore_last_deleted(&mut self) -> Option<usize> {
        let (idx, entry) = self.deleted_entries.pop()?;
        let idx = idx.min(self.entries.len());
        self.entries.insert(idx, entry);
        // Restoring is as much a structural change as removing — and it is not
        // assumed to *undo* one either, since the request lands at the nearest
        // surviving index rather than necessarily its old one, and anything
        // else may have moved meanwhile. So this is recomputed like the rest:
        // when it does land back where it was, the collection is once again the
        // one on disk and says so.
        self.refresh_structure_modified();
        Some(idx)
    }
}

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

    fn entry(title: &str) -> HurlEntry {
        let mut e = HurlEntry::default();
        e.title = title.into();
        e
    }

    #[test]
    fn remove_entry_recording_undo_records_index_and_entry() {
        let mut c = Collection::new("c".into(), vec![entry("a"), entry("b"), entry("c")]);
        let removed = c
            .remove_entry_recording_undo(1)
            .expect("index 1 is in range");
        assert_eq!(removed.title, "b");
        assert_eq!(
            c.entries
                .iter()
                .map(|e| e.title.as_str())
                .collect::<Vec<_>>(),
            vec!["a", "c"]
        );
        assert_eq!(c.deleted_entries.len(), 1);
        assert_eq!(c.deleted_entries[0].0, 1);
        assert_eq!(c.deleted_entries[0].1.title, "b");
    }

    #[test]
    fn deleted_entries_cap_holds_at_20() {
        let mut c = Collection::new(
            "c".into(),
            (0..25).map(|i| entry(&format!("r{i}"))).collect(),
        );
        for _ in 0..25 {
            c.remove_entry_recording_undo(0);
        }
        // The oldest deletions are dropped so the history never grows without
        // bound over a long session; only the most recent 20 survive.
        assert_eq!(c.deleted_entries.len(), 20);
        assert_eq!(c.deleted_entries.first().unwrap().1.title, "r5");
        assert_eq!(c.deleted_entries.last().unwrap().1.title, "r24");
    }

    #[test]
    fn restore_last_deleted_reinserts_at_recorded_index() {
        let mut c = Collection::new("c".into(), vec![entry("a"), entry("b"), entry("c")]);
        c.remove_entry_recording_undo(1);
        assert_eq!(
            c.entries
                .iter()
                .map(|e| e.title.as_str())
                .collect::<Vec<_>>(),
            vec!["a", "c"]
        );
        let idx = c.restore_last_deleted().unwrap();
        assert_eq!(idx, 1);
        assert_eq!(
            c.entries
                .iter()
                .map(|e| e.title.as_str())
                .collect::<Vec<_>>(),
            vec!["a", "b", "c"]
        );
        assert!(c.deleted_entries.is_empty());
    }

    #[test]
    fn removing_an_out_of_range_entry_is_a_no_op_rather_than_a_panic() {
        let mut c = Collection::new("c".into(), vec![entry("a")]);
        assert!(c.remove_entry_recording_undo(7).is_none());
        assert_eq!(c.entries.len(), 1, "nothing was removed");
        assert!(c.deleted_entries.is_empty(), "and nothing was recorded");
    }

    #[test]
    fn restore_last_deleted_is_none_when_history_empty() {
        let mut c = Collection::new("c".into(), vec![entry("a")]);
        assert!(c.restore_last_deleted().is_none());
    }
}

#[cfg(test)]
mod ws_scan_tests {
    use super::*;
    use std::fs;

    fn tmp_root(name: &str) -> PathBuf {
        let dir =
            std::env::temp_dir().join(format!("paperboy_ws_scan_{name}_{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        dir
    }

    fn workspace_at(root: &Path) -> Collection {
        let mut c = Collection::new("ws".into(), Vec::new());
        c.workspace_root = Some(root.to_path_buf());
        c
    }

    fn names(rows: &[WsRow]) -> Vec<String> {
        rows.iter()
            .map(|r| match r {
                WsRow::Folder { name, .. }
                | WsRow::Report { name, .. }
                | WsRow::Environment { name, .. }
                | WsRow::Collection { name, .. } => name.clone(),
                other => format!("{other:?}"),
            })
            .collect()
    }

    /// The graphical front-end asks for the tree once per frame. Reading it off
    /// disk that often is real I/O on every mouse move, so a scan is reused for
    /// [`WS_SCAN_TTL`] — and then genuinely re-read, because a workspace can
    /// change from outside PaperBoy.
    #[test]
    fn the_workspace_tree_is_read_off_disk_at_most_once_per_ttl() {
        let root = tmp_root("ttl");
        fs::write(root.join("a.hurl"), "").unwrap();
        let c = workspace_at(&root);

        // The generation is held fixed: this test is about the *time* window,
        // and PaperBoy is not the one making the change.
        let t0 = Instant::now();
        assert_eq!(names(&c.ws_rows_as_of(t0, 7)), vec!["a.hurl"]);

        // A file appears behind PaperBoy's back. Within the window the tree is
        // the one already in hand — that is the whole point of the cache.
        fs::write(root.join("b.hurl"), "").unwrap();
        assert_eq!(
            names(&c.ws_rows_as_of(t0 + WS_SCAN_TTL / 2, 7)),
            vec!["a.hurl"],
            "still serving the cached scan"
        );

        // Once the window passes, the disk is read again and the new file shows
        // up without anyone having told PaperBoy about it.
        assert_eq!(
            names(&c.ws_rows_as_of(t0 + WS_SCAN_TTL + Duration::from_millis(1), 7)),
            vec!["a.hurl", "b.hurl"],
            "the tree catches up with the filesystem"
        );

        let _ = fs::remove_dir_all(&root);
    }

    /// The environments panel's file list comes out of the same cached scan the
    /// tree does, so drawing the panel doesn't walk the workspace again —
    /// several times per frame, as it used to.
    #[test]
    fn the_environment_file_list_is_served_from_the_tree_scan() {
        let root = tmp_root("envscan");
        fs::write(root.join("a.hurl"), "").unwrap();
        fs::write(root.join("dev.vars"), "K=1").unwrap();
        let c = workspace_at(&root);

        let t0 = Instant::now();
        assert_eq!(
            c.workspace_env_files_as_of(t0, 7),
            vec![root.join("dev.vars")],
            "the workspace's environment files, and only those"
        );

        // Written behind PaperBoy's back and *not* seen, which is the proof:
        // a fresh scan would have found it, so this answer came from the cache
        // the tree filled in above.
        fs::write(root.join("prod.vars"), "K=2").unwrap();
        assert_eq!(
            c.workspace_env_files_as_of(t0 + WS_SCAN_TTL / 2, 7),
            vec![root.join("dev.vars")],
            "no second walk of the disk"
        );
        // And it does catch up once the window passes, like the tree does.
        assert_eq!(
            c.workspace_env_files_as_of(t0 + WS_SCAN_TTL + Duration::from_millis(1), 7),
            vec![root.join("dev.vars"), root.join("prod.vars")]
        );
        let _ = fs::remove_dir_all(&root);
    }

    /// A tab that isn't a workspace has no files to offer — and must not scan
    /// anything looking for them.
    #[test]
    fn a_non_workspace_tab_lists_no_environment_files() {
        let c = Collection::new("scratch".into(), Vec::new());
        assert!(c.workspace_env_files().is_empty());
    }

    /// The panel lists a workspace's environments whether or not the tab's
    /// display filter is narrowing the *tree* to collections — the filter
    /// chooses what the tree shows, not what environments exist.
    #[test]
    fn the_display_filter_does_not_hide_environment_files() {
        let root = tmp_root("envfilter");
        fs::write(root.join("dev.vars"), "K=1").unwrap();
        let mut c = workspace_at(&root);
        c.workspace_filter_hurl_json = true;
        assert_eq!(c.workspace_env_files(), vec![root.join("dev.vars")]);
        c.workspace_filter_hurl_json = false;
        assert_eq!(c.workspace_env_files(), vec![root.join("dev.vars")]);
        let _ = fs::remove_dir_all(&root);
    }

    /// The cache must not answer a question it wasn't asked: changing the
    /// filter (or the root) has to re-read, however fresh the last scan is.
    #[test]
    fn changing_the_filter_or_the_root_bypasses_a_fresh_scan() {
        let root = tmp_root("keys");
        fs::write(root.join("a.hurl"), "").unwrap();
        fs::write(root.join("notes.txt"), "").unwrap();
        let mut c = workspace_at(&root);

        let t0 = Instant::now();
        assert_eq!(names(&c.ws_rows_as_of(t0, 7)), vec!["a.hurl"], "filtered");

        c.workspace_filter_hurl_json = false;
        assert_eq!(
            names(&c.ws_rows_as_of(t0, 7)),
            vec!["a.hurl", "notes.txt"],
            "showing everything, at the very same instant"
        );

        let other = tmp_root("keys_other");
        fs::write(other.join("z.hurl"), "").unwrap();
        c.workspace_root = Some(other.clone());
        assert_eq!(
            names(&c.ws_rows_as_of(t0, 7)),
            vec!["z.hurl"],
            "a different root is a different tree"
        );

        let _ = fs::remove_dir_all(&root);
        let _ = fs::remove_dir_all(&other);
    }

    /// PaperBoy's own edits must not have to wait out the window: creating a
    /// file and then not finding it in the tree is a bug, not a stale cache.
    #[test]
    fn the_app_s_own_file_operations_show_up_at_once() {
        let root = tmp_root("generation");
        fs::write(root.join("a.hurl"), "").unwrap();
        let c = workspace_at(&root);

        let t0 = Instant::now();
        assert_eq!(names(&c.ws_rows_at(t0)), vec!["a.hurl"]);

        crate::workspace::create_item(&root, &root, "b", crate::workspace::NewItemKind::Collection)
            .expect("created");
        assert_eq!(
            names(&c.ws_rows_at(t0)),
            vec!["a.hurl", "b.hurl"],
            "at the very same instant, well inside the scan window"
        );

        let _ = fs::remove_dir_all(&root);
    }

    /// Expanding a folder is a *view* change, not a filesystem one, so it must
    /// take effect on the very next frame rather than waiting out the TTL.
    #[test]
    fn expanding_a_folder_shows_its_contents_immediately() {
        let root = tmp_root("expand");
        fs::create_dir_all(root.join("sub")).unwrap();
        fs::write(root.join("sub/inner.hurl"), "").unwrap();
        let mut c = workspace_at(&root);

        let t0 = Instant::now();
        assert_eq!(names(&c.ws_rows_as_of(t0, 7)), vec!["sub"], "collapsed");

        c.workspace_expanded.insert(root.join("sub"));
        assert_eq!(
            names(&c.ws_rows_as_of(t0, 7)),
            vec!["sub", "inner.hurl"],
            "no wait for the scan window: the filter isn't cached"
        );

        let _ = fs::remove_dir_all(&root);
    }
}

#[cfg(test)]
mod revert_tests {
    use super::*;
    use std::fs;

    fn tmp_root(name: &str) -> PathBuf {
        let dir =
            std::env::temp_dir().join(format!("paperboy_revert_{name}_{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        dir
    }

    /// Three requests on disk; the list is then rearranged in memory without
    /// saving. Reverting has to follow the *request*, not its position — the
    /// menu that offers Revert also offers Duplicate and drag-reorder, so the
    /// two disagree routinely, and restoring the wrong entry destroys the edits
    /// the user was trying to keep with no way back.
    fn three_on_disk(name: &str) -> (PathBuf, Collection) {
        let root = tmp_root(name);
        let file = root.join("c.hurl");
        fs::write(
            &file,
            "# A\nGET https://h/a\n\n# B\nGET https://h/b\n\n# C\nGET https://h/c\n",
        )
        .unwrap();
        let mut col = Collection::new(
            "c".into(),
            crate::postman::parse_collection(&fs::read_to_string(&file).unwrap()),
        );
        col.path = Some(file.clone());
        col.reset_structure_baseline();
        (file, col)
    }

    #[test]
    fn reverting_after_an_unsaved_duplicate_restores_the_request_that_was_asked_for() {
        let (_file, mut col) = three_on_disk("dup");
        // Duplicate A, unsaved: B now sits at index 2 in memory, index 1 on disk.
        let copy = col.entries[0].clone();
        col.entries.insert(1, copy);
        let bi = 2;
        assert_eq!(col.entries[bi].title, "B");
        col.entries[bi].url = "https://h/b-EDITED".into();
        col.entries[bi].modified = true;

        col.revert_request(bi);

        assert_eq!(col.entries[bi].title, "B", "reverting B must restore B");
        assert_eq!(col.entries[bi].url, "https://h/b");
        let titles: Vec<_> = col.entries.iter().map(|e| e.title.clone()).collect();
        assert_eq!(titles, ["A", "A", "B", "C"], "no other request may change");
    }

    #[test]
    fn reverting_after_an_unsaved_reorder_restores_the_request_that_was_asked_for() {
        let (_file, mut col) = three_on_disk("reorder");
        col.entries.swap(0, 1); // B, A, C in memory; A, B, C on disk
        col.entries[0].url = "https://h/b-EDITED".into();
        col.entries[0].modified = true;

        col.revert_request(0);

        assert_eq!(col.entries[0].title, "B");
        assert_eq!(col.entries[0].url, "https://h/b");
    }

    #[test]
    fn reverting_the_last_request_after_an_insertion_still_reverts_it() {
        let (_file, mut col) = three_on_disk("shifted");
        let copy = col.entries[0].clone();
        col.entries.insert(0, copy); // C is now index 3, past the end of the file
        let ci = 3;
        assert_eq!(col.entries[ci].title, "C");
        col.entries[ci].url = "https://h/c-EDITED".into();
        col.entries[ci].modified = true;

        assert_eq!(col.revert_request(ci).as_deref(), Some("GET"));
        assert_eq!(col.entries[ci].url, "https://h/c");
    }

    #[test]
    fn a_request_with_no_saved_version_reverts_to_nothing() {
        let (_file, mut col) = three_on_disk("unsaved");
        let mut fresh = col.entries[0].clone();
        fresh.uid = 0; // never in the list that was saved
        fresh.user_added = true;
        col.entries.push(fresh);
        assert_eq!(col.revert_request(3), None);
        assert_eq!(col.entries.len(), 4, "the request must still be there");
    }

    /// A reverted request came straight out of the file, so the file is what
    /// its later edits are measured against. Without that, the derived
    /// `modified` flag had nothing to compare to and latched the moment
    /// anything touched the request again — putting the pencil back on a
    /// request that matched what was on disk.
    #[test]
    fn a_reverted_request_is_measured_against_the_file_again() {
        let (_file, mut col) = three_on_disk("baseline");
        col.entries[1].url = "https://h/b-EDITED".into();
        col.entries[1].mark_edited();
        assert!(col.entries[1].modified);
        col.revert_request(1);
        col.entries[1].mark_edited();
        assert!(
            !col.entries[1].modified,
            "the request matches the file, so nothing about it is unsaved"
        );
        col.entries[1].url = "https://h/b-AGAIN".into();
        col.entries[1].mark_edited();
        assert!(col.entries[1].modified, "a real edit still counts");
    }

    #[test]
    fn reverting_leaves_the_list_agreeing_with_the_file() {
        let (_file, mut col) = three_on_disk("clean");
        col.entries[1].url = "https://h/b-EDITED".into();
        col.entries[1].modified = true;
        col.revert_request(1);
        assert!(
            !col.has_unsaved_edits(),
            "a reverted collection with no other edits has nothing left to save"
        );
    }

    /// A file edited and then switched away from keeps its edits in
    /// `workspace_pending`, and the tree lists its requests from the title
    /// cache snapshotted off those same edited entries. Reverting it has to
    /// clear both, or reopening the file would bring the edits back and the
    /// tree would go on showing the edited names in the meantime.
    #[test]
    fn reverting_a_file_that_isnt_loaded_drops_its_parked_edits() {
        let root = tmp_root("parked");
        let a = root.join("a.hurl");
        let b = root.join("b.hurl");
        fs::write(&a, "GET https://example.com/a\n").unwrap();
        fs::write(&b, "GET https://example.com/b\n").unwrap();
        let mut col = Collection::new("ws".into(), Vec::new());
        col.workspace_root = Some(root.clone());

        col.load_workspace_file(a.clone()).unwrap();
        col.entries[0].url = "https://edited.example".into();
        col.entries[0].modified = true;
        // Switching away parks the edits and caches the edited row names.
        col.load_workspace_file(b.clone()).unwrap();
        assert!(col.workspace_file_edited(&a), "the edits are parked");

        col.revert_workspace_file(&a).unwrap();

        assert!(!col.workspace_file_edited(&a), "and now they are gone");
        col.load_workspace_file(a.clone()).unwrap();
        assert_eq!(
            col.entries[0].url, "https://example.com/a",
            "reopening the file shows what is on disk, not the discarded edit"
        );
        let _ = fs::remove_dir_all(&root);
    }

    /// Reverting the loaded file leaves the tab showing it — same file, same
    /// request selected — with the edits gone.
    #[test]
    fn reverting_the_loaded_file_restores_it_in_place() {
        let root = tmp_root("loaded");
        let a = root.join("a.hurl");
        fs::write(
            &a,
            "GET https://example.com/a\nGET https://example.com/a2\n",
        )
        .unwrap();
        let mut col = Collection::new("ws".into(), Vec::new());
        col.workspace_root = Some(root.clone());
        col.load_workspace_file(a.clone()).unwrap();
        col.selected_entry = 1;
        col.entries[1].url = "https://edited.example".into();
        col.entries[1].modified = true;

        col.revert_workspace_file(&a).unwrap();

        assert_eq!(col.path.as_deref(), Some(a.as_path()));
        assert_eq!(col.selected_entry, 1, "the selection stays where it was");
        assert_eq!(col.entries[1].url, "https://example.com/a2");
        assert!(!col.has_unsaved_edits());
        let _ = fs::remove_dir_all(&root);
    }

    /// A file that has vanished can't be reverted to — and the attempt must
    /// leave the in-memory edits alone rather than half-clearing them.
    #[test]
    fn reverting_an_unreadable_file_changes_nothing() {
        let root = tmp_root("missing");
        let a = root.join("a.hurl");
        fs::write(&a, "GET https://example.com/a\n").unwrap();
        let mut col = Collection::new("ws".into(), Vec::new());
        col.workspace_root = Some(root.clone());
        col.load_workspace_file(a.clone()).unwrap();
        col.entries[0].url = "https://edited.example".into();
        col.entries[0].modified = true;
        fs::remove_file(&a).unwrap();

        assert!(col.revert_workspace_file(&a).is_err());
        assert_eq!(col.entries[0].url, "https://edited.example");
        assert!(col.has_unsaved_edits());
        let _ = fs::remove_dir_all(&root);
    }
}

/// The workspace tree's *virtual* folders: the ones encoded in request titles
/// inside a single collection file, as opposed to real directories.
#[cfg(test)]
mod request_folder_tests {
    use super::*;
    use std::fs;

    fn tmp_root(name: &str) -> PathBuf {
        let dir =
            std::env::temp_dir().join(format!("paperboy_reqfold_{name}_{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        dir
    }

    /// A collection whose requests carry folder-encoded titles, the way a
    /// Postman import writes them.
    fn nested_collection(root: &Path) -> (Collection, PathBuf) {
        let path = root.join("api.hurl");
        fs::write(
            &path,
            "# Auth/Login\nGET https://example.com/login\n\n\
             # Auth/Tokens/Refresh\nPOST https://example.com/refresh\n\n\
             # Health\nGET https://example.com/health\n",
        )
        .unwrap();
        let mut col = Collection::new("ws".into(), Vec::new());
        col.workspace_root = Some(root.to_path_buf());
        col.load_workspace_file(path.clone()).unwrap();
        (col, path)
    }

    /// What the tree shows, as `(indent, label)` pairs, ignoring row kind.
    fn shape(col: &Collection) -> Vec<(usize, String)> {
        col.ws_rows()
            .into_iter()
            .map(|r| match r {
                WsRow::Folder { name, depth, .. }
                | WsRow::Collection { name, depth, .. }
                | WsRow::Report { name, depth, .. }
                | WsRow::Environment { name, depth, .. }
                | WsRow::RequestFolder { name, depth, .. }
                | WsRow::Request { name, depth, .. } => (depth, name),
            })
            .collect()
    }

    /// The bug this whole feature exists for: a Postman import names its
    /// requests `folder/request`, and the workspace tree used to drop
    /// everything but the leaf — so a hundred requests from twenty folders
    /// arrived as one flat, ambiguous list with several rows called `Login`.
    #[test]
    fn titles_with_slashes_nest_instead_of_flattening_into_one_list() {
        let root = tmp_root("nest");
        let (col, _) = nested_collection(&root);

        assert_eq!(
            shape(&col),
            vec![
                (0, "api.hurl".to_string()),
                // Folders come before the file's own top-level requests, and
                // `Auth` is open because the selected request (the first one)
                // lives in it — see `expand_selected_request_folders`.
                (1, "Auth".to_string()),
                (2, "Tokens".to_string()),
                (2, "Login".to_string()),
                (1, "Health".to_string()),
            ],
            "each title segment is a row of its own"
        );
        assert!(
            !shape(&col).iter().any(|(_, n)| n.contains('/')),
            "no row still carries a raw `folder/request` name"
        );
        let _ = fs::remove_dir_all(&root);
    }

    /// A folder the selection isn't in stays shut: revealing the selected
    /// request must not amount to expanding the whole file.
    #[test]
    fn folders_the_selection_is_not_in_start_closed() {
        let root = tmp_root("closed");
        let (col, _) = nested_collection(&root);

        assert!(
            !shape(&col).iter().any(|(_, n)| n == "Refresh"),
            "Auth/Tokens is closed, so the request inside it isn't listed"
        );
        let _ = fs::remove_dir_all(&root);
    }

    /// Opening a folder reveals its direct children only — its own subfolder
    /// stays closed until asked for, exactly like a directory.
    #[test]
    fn opening_a_virtual_folder_reveals_one_level_at_a_time() {
        let root = tmp_root("open");
        let (mut col, path) = nested_collection(&root);

        col.workspace_expanded
            .insert(request_folder_path(&path, &["Auth".to_string()]));
        assert_eq!(
            shape(&col),
            vec![
                (0, "api.hurl".to_string()),
                (1, "Auth".to_string()),
                (2, "Tokens".to_string()),
                (2, "Login".to_string()),
                (1, "Health".to_string()),
            ],
            "Auth's own folder and request, indented under it"
        );

        col.workspace_expanded.insert(request_folder_path(
            &path,
            &["Auth".to_string(), "Tokens".to_string()],
        ));
        assert_eq!(
            shape(&col),
            vec![
                (0, "api.hurl".to_string()),
                (1, "Auth".to_string()),
                (2, "Tokens".to_string()),
                (3, "Refresh".to_string()),
                (2, "Login".to_string()),
                (1, "Health".to_string()),
            ],
            "the nested folder opens independently"
        );
        let _ = fs::remove_dir_all(&root);
    }

    /// A request row keeps the index of its request in the *file*, however
    /// deeply the tree nests it — that index is what selecting and running the
    /// row acts on, so nesting must not renumber anything.
    #[test]
    fn nesting_does_not_disturb_the_request_indices() {
        let root = tmp_root("idx");
        let (mut col, path) = nested_collection(&root);
        col.workspace_expanded
            .insert(request_folder_path(&path, &["Auth".to_string()]));
        col.workspace_expanded.insert(request_folder_path(
            &path,
            &["Auth".to_string(), "Tokens".to_string()],
        ));

        let found: Vec<(usize, String)> = col
            .ws_rows()
            .into_iter()
            .filter_map(|r| match r {
                WsRow::Request { idx, name, .. } => Some((idx, name)),
                _ => None,
            })
            .collect();
        assert_eq!(
            found,
            vec![
                (1, "Refresh".to_string()),
                (0, "Login".to_string()),
                (2, "Health".to_string()),
            ],
            "the file's own order is what the indices mean"
        );
        let _ = fs::remove_dir_all(&root);
    }

    /// An untitled request falls back to showing its URL — which is full of
    /// `/`. That fallback is a *label*, not a path, so it must not be split
    /// into an `https:` folder holding an `example.com` folder.
    #[test]
    fn an_untitled_requests_url_is_never_read_as_folders() {
        let root = tmp_root("untitled");
        let path = root.join("bare.hurl");
        fs::write(&path, "GET https://example.com/a/b/c\n").unwrap();
        let mut col = Collection::new("ws".into(), Vec::new());
        col.workspace_root = Some(root.clone());
        col.load_workspace_file(path).unwrap();

        assert_eq!(
            shape(&col),
            vec![
                (0, "bare.hurl".to_string()),
                (1, "https://example.com/a/b/c".to_string()),
            ],
            "one row, showing the whole URL"
        );
        let _ = fs::remove_dir_all(&root);
    }

    /// Selecting a request from outside the tree (loading a file, saving the
    /// wizard, renaming) has to make its row reachable, or the cursor would
    /// land somewhere else entirely because the row was folded away.
    #[test]
    fn selecting_a_nested_request_opens_the_folders_hiding_it() {
        let root = tmp_root("reveal");
        let (mut col, _) = nested_collection(&root);

        col.selected_entry = 1; // Auth/Tokens/Refresh
        col.sync_ws_cursor();

        let rows = col.ws_rows();
        let cursor = rows.get(col.list_cursor);
        assert!(
            matches!(cursor, Some(WsRow::Request { idx: 1, .. })),
            "the cursor is on the selected request, not on a fallback row: {cursor:?}"
        );
        let _ = fs::remove_dir_all(&root);
    }

    /// The expand/collapse key is a path, and a title is free text: `..` or a
    /// separator in a request name must not produce a key that climbs out of
    /// the collection it belongs to (and then gets persisted).
    #[test]
    fn a_folder_key_cannot_escape_its_collection() {
        let collection = Path::new("/ws/api.hurl");
        let key = request_folder_path(
            collection,
            &["..".to_string(), "a/b".to_string(), ".".to_string()],
        );
        assert!(
            key.starts_with(collection),
            "every key stays under its collection: {key:?}"
        );
        assert!(
            !key.components().any(|c| c.as_os_str() == ".."),
            "and never contains a parent hop: {key:?}"
        );
    }
}

/// A Workspace tab's edits are held in memory and re-read from disk when the
/// tab switches away and back, so anything the tab doesn't recognise as an
/// edit is silently discarded. These pin down that removing or reordering a
/// request counts — neither touches a *surviving* entry's `user_added` /
/// `modified` flags, which is all `has_unsaved_edits` used to look at.
#[cfg(test)]
mod structure_edit_tests {
    use super::*;

    fn ws_collection(dir: &std::path::Path, titles: &[&str]) -> (Collection, PathBuf) {
        let a = dir.join("a.hurl");
        let b = dir.join("b.hurl");
        let entries: Vec<HurlEntry> = titles
            .iter()
            .map(|t| HurlEntry {
                title: (*t).to_string(),
                method: "GET".into(),
                url: "http://x".into(),
                ..Default::default()
            })
            .collect();
        std::fs::write(&a, collection_to_hurl(&entries)).unwrap();
        std::fs::write(&b, "GET http://other\n").unwrap();
        let mut col = Collection::new("ws".into(), entries);
        col.workspace_root = Some(dir.to_path_buf());
        col.path = Some(a.clone());
        (col, b)
    }

    fn temp_dir(name: &str) -> PathBuf {
        let dir =
            std::env::temp_dir().join(format!("paperboy_structedit_{name}_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    #[test]
    fn deleting_a_request_survives_a_workspace_file_switch() {
        let dir = temp_dir("delete");
        let (mut col, other) = ws_collection(&dir, &["Login", "Logout"]);

        col.remove_entry_recording_undo(0);
        assert!(
            col.has_unsaved_edits(),
            "a deletion is an unsaved edit, even though no surviving entry is flagged"
        );

        let a = col.path.clone().unwrap();
        col.load_workspace_file(other).unwrap();
        col.load_workspace_file(a).unwrap();

        let titles: Vec<&str> = col.entries.iter().map(|e| e.title.as_str()).collect();
        assert_eq!(
            titles,
            vec!["Logout"],
            "the deleted request must not come back from disk"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The subtler half: a file whose only change was a deletion, parked when
    /// the tab switched away from it. `workspace_pending` holds its entries,
    /// but a deletion leaves no flagged entry among them, so the save-all pass
    /// had nothing to tell it apart from an untouched file.
    /// The count gates the GUI's "unsaved edits" prompt on closing a tab, so
    /// a delete-only change reading as zero meant the tab closed silently and
    /// the deletion went with it.
    fn titles(c: &Collection) -> Vec<&str> {
        c.entries.iter().map(|e| e.title.as_str()).collect()
    }

    fn plain(titles: &[&str]) -> Collection {
        Collection::new(
            "c".into(),
            titles
                .iter()
                .map(|t| HurlEntry {
                    title: (*t).to_string(),
                    method: "GET".into(),
                    ..Default::default()
                })
                .collect(),
        )
    }

    #[test]
    fn moving_an_entry_shifts_the_ones_it_steps_over() {
        let mut c = plain(&["a", "b", "c", "d"]);
        assert!(c.move_entry(0, 2), "a moves down past b and c");
        assert_eq!(titles(&c), vec!["b", "c", "a", "d"]);

        let mut c = plain(&["a", "b", "c", "d"]);
        assert!(c.move_entry(3, 1), "d moves up past c and b");
        assert_eq!(titles(&c), vec!["a", "d", "b", "c"]);
    }

    #[test]
    fn a_move_that_cannot_happen_is_a_no_op() {
        let mut c = plain(&["a", "b"]);
        assert!(!c.move_entry(1, 1), "nowhere to go");
        assert!(!c.move_entry(0, 9), "past the end");
        assert!(!c.move_entry(9, 0), "from nowhere");
        assert_eq!(titles(&c), vec!["a", "b"]);
        assert!(
            !c.structure_modified,
            "and a move that did not happen is not an unsaved change"
        );
    }

    /// Dropping into a gap is the drag-and-drop spelling of a move, and the
    /// index needs adjusting when the drag goes downwards — the dragged request
    /// is lifted out before it is put back, so everything below it slides up by
    /// one first.
    #[test]
    fn a_drop_lands_in_the_gap_it_was_aimed_at() {
        // Downwards: "a" dropped into the gap before "d" must end up between
        // "c" and "d", not between "b" and "c".
        let mut c = plain(&["a", "b", "c", "d"]);
        assert!(c.move_entry_before(0, 3));
        assert_eq!(titles(&c), vec!["b", "c", "a", "d"]);

        // Upwards needs no adjustment: nothing below the gap has moved.
        let mut c = plain(&["a", "b", "c", "d"]);
        assert!(c.move_entry_before(3, 1));
        assert_eq!(titles(&c), vec!["a", "d", "b", "c"]);

        // Past the last row: the one gap that isn't before any entry.
        let mut c = plain(&["a", "b", "c"]);
        assert!(c.move_entry_before(0, 3));
        assert_eq!(titles(&c), vec!["b", "c", "a"]);
    }

    /// Both gaps touching a request are where it already is, so a drop there
    /// must not register as an edit — it would mark the file unsaved for a
    /// change nobody made.
    #[test]
    fn dropping_a_request_back_where_it_started_changes_nothing() {
        let mut c = plain(&["a", "b", "c"]);
        assert!(!c.move_entry_before(1, 1), "the gap above it");
        assert!(!c.move_entry_before(1, 2), "the gap below it");
        assert!(!c.move_entry_before(9, 0), "from nowhere");
        assert!(!c.move_entry_before(0, 9), "into nowhere");
        assert_eq!(titles(&c), vec!["a", "b", "c"]);
        assert!(!c.structure_modified);
    }

    /// The selection is a position, so every move has to re-derive it.
    #[test]
    fn the_selection_follows_whatever_it_was_pointing_at() {
        // The moved entry carries the selection with it.
        let mut c = plain(&["a", "b", "c"]);
        c.selected_entry = 0;
        c.move_entry(0, 2);
        assert_eq!(c.selected_entry, 2, "still on 'a'");

        // A selection the move steps across shifts by one.
        let mut c = plain(&["a", "b", "c"]);
        c.selected_entry = 1;
        c.move_entry(0, 2);
        assert_eq!(c.selected_entry, 0, "still on 'b', which slid up");

        // A selection outside the moved span is left alone.
        let mut c = plain(&["a", "b", "c", "d"]);
        c.selected_entry = 3;
        c.move_entry(0, 2);
        assert_eq!(c.selected_entry, 3, "still on 'd'");
    }

    /// A reorder is exactly the change no request records, which is what
    /// `structure_modified` exists for.
    #[test]
    fn reordering_counts_as_an_unsaved_change() {
        let dir = temp_dir("reorder");
        let (mut col, _) = ws_collection(&dir, &["Login", "Logout"]);
        let a = col.path.clone().unwrap();

        assert!(col.move_entry(0, 1));
        assert!(col.has_unsaved_edits());
        assert_eq!(col.unsaved_edit_count(), 1);

        assert_eq!(col.save_workspace_edits().unwrap(), 1);
        let on_disk = std::fs::read_to_string(&a).unwrap();
        assert!(
            on_disk.find("Logout").unwrap() < on_disk.find("Login").unwrap(),
            "the new order reached the file: {on_disk}"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_structural_edit_counts_as_an_unsaved_change() {
        let dir = temp_dir("count");
        let (mut col, other) = ws_collection(&dir, &["Login", "Logout"]);
        assert_eq!(col.unsaved_edit_count(), 0);

        col.remove_entry_recording_undo(0);
        assert_eq!(
            col.unsaved_edit_count(),
            1,
            "the deletion is a change, even with no request left to flag it"
        );

        // Once parked, it still counts — and only once.
        col.load_workspace_file(other).unwrap();
        assert_eq!(col.unsaved_edit_count(), 1);

        col.save_workspace_edits().unwrap();
        assert_eq!(col.unsaved_edit_count(), 0, "and saving settles it");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_parked_files_structural_edit_is_written_too() {
        let dir = temp_dir("parked");
        let (mut col, other) = ws_collection(&dir, &["Login", "Logout"]);
        let a = col.path.clone().unwrap();

        col.remove_entry_recording_undo(0);
        // Switch away, so the edit is parked rather than loaded.
        col.load_workspace_file(other).unwrap();
        assert!(
            col.workspace_pending.contains_key(&a),
            "the deletion was parked rather than discarded"
        );

        assert_eq!(
            col.save_workspace_edits().unwrap(),
            1,
            "the parked file was written"
        );
        let on_disk = std::fs::read_to_string(&a).unwrap();
        assert!(
            !on_disk.contains("Login"),
            "the parked deletion reached the file: {on_disk}"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// An untouched file must still be left alone — the flag has to be cleared
    /// on the way through, or every later save would rewrite files needlessly
    /// (and stamp over changes made outside PaperBoy).
    #[test]
    fn saving_clears_the_structural_marks_it_just_wrote() {
        let dir = temp_dir("clears");
        let (mut col, _) = ws_collection(&dir, &["Login", "Logout"]);

        col.remove_entry_recording_undo(0);
        col.save_workspace_edits().unwrap();
        assert!(col.workspace_structure_modified.is_empty());
        assert!(!col.structure_modified);
        assert_eq!(
            col.save_workspace_edits().unwrap(),
            0,
            "a second save has nothing left to write"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_structural_edit_is_written_by_save_workspace_edits() {
        let dir = temp_dir("save");
        let (mut col, _) = ws_collection(&dir, &["Login", "Logout"]);
        let a = col.path.clone().unwrap();

        col.remove_entry_recording_undo(0);
        assert_eq!(
            col.save_workspace_edits().unwrap(),
            1,
            "the file was written"
        );

        let on_disk = std::fs::read_to_string(&a).unwrap();
        assert!(
            !on_disk.contains("Login"),
            "the deletion reached the file: {on_disk}"
        );
        assert!(
            !col.has_unsaved_edits(),
            "and saving clears the structural edit, like any other"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }
}

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

    fn entry(title: &str) -> HurlEntry {
        let mut e = HurlEntry::default();
        e.title = title.into();
        e
    }

    fn col() -> Collection {
        Collection::new("c".into(), vec![entry("a"), entry("b"), entry("c")])
    }

    #[test]
    fn a_freshly_built_collection_is_not_structurally_modified() {
        assert!(!col().structure_modified);
    }

    #[test]
    fn reordering_marks_the_collection_and_reordering_back_clears_it() {
        let mut c = col();
        assert!(c.move_entry(0, 1));
        assert!(
            c.structure_modified,
            "a reorder has to register — nothing else records it"
        );
        assert!(c.move_entry(1, 0));
        assert!(
            !c.structure_modified,
            "putting the request back leaves nothing to save, so the marker must clear"
        );
    }

    #[test]
    fn a_longer_walk_back_to_the_original_order_also_clears_it() {
        // Not just a single undo: any sequence of drags that happens to end in
        // the saved order is, by then, the saved order.
        let mut c = col();
        let titles = |c: &Collection| {
            c.entries
                .iter()
                .map(|e| e.title.clone())
                .collect::<Vec<_>>()
        };
        c.move_entry(0, 2);
        c.move_entry(0, 1);
        assert_eq!(titles(&c), vec!["c", "b", "a"]);
        assert!(c.structure_modified);
        c.move_entry(0, 2);
        c.move_entry(0, 1);
        assert_eq!(titles(&c), vec!["a", "b", "c"]);
        assert!(!c.structure_modified);
    }

    #[test]
    fn deleting_marks_the_collection_and_undoing_the_delete_clears_it() {
        let mut c = col();
        c.remove_entry_recording_undo(1);
        assert!(c.structure_modified);
        c.restore_last_deleted();
        assert!(
            !c.structure_modified,
            "the restored request landed back where it was, so the list matches disk again"
        );
    }

    #[test]
    fn a_restore_that_lands_somewhere_else_stays_marked() {
        // `restore_last_deleted` reinserts at the *nearest* surviving index, so
        // deleting two and restoring one need not undo anything.
        let mut c = col();
        c.remove_entry_recording_undo(0);
        c.remove_entry_recording_undo(0);
        c.restore_last_deleted();
        assert!(c.structure_modified);
    }

    /// The reason the comparison is by identity and not by anything the entry
    /// *says*. A `.hurl` file whose requests carry no `#` name gives every
    /// entry the same empty title, so a title-based fingerprint saw a reorder
    /// of them as no change at all — and a workspace file of unnamed requests
    /// is the common case, not a corner one.
    #[test]
    fn reordering_untitled_requests_is_still_detected() {
        let mut c = Collection::new("c".into(), vec![entry(""), entry(""), entry("")]);
        c.entries[0].url = "https://example.test/a".into();
        c.entries[1].url = "https://example.test/b".into();
        c.entries[2].url = "https://example.test/c".into();
        // Re-adopt, so the URLs above are part of the saved state.
        c.mark_saved();
        assert!(c.move_entry(0, 1));
        assert!(c.structure_modified, "the requests really did swap places");
        assert!(c.move_entry(1, 0));
        assert!(!c.structure_modified);
    }

    /// ...and the other half of that reason: editing a request in place is not
    /// a change to the *list*. It is already reported by the entry's own
    /// `modified` flag, and counting it twice would inflate the "N unsaved
    /// edits" warning.
    #[test]
    fn editing_a_request_in_place_is_not_a_structural_change() {
        let mut c = col();
        c.entries[1].url = "https://example.test/rewritten".into();
        c.entries[1].title = "renamed".into();
        c.entries[1].modified = true;
        assert!(
            !c.structure_modified,
            "the list is unchanged; only what one of its entries holds is"
        );
        assert!(c.has_unsaved_edits(), "still unsaved, via the entry's flag");
        assert_eq!(c.unsaved_edit_count(), 1, "counted once, not twice");
    }

    #[test]
    fn saving_adopts_the_current_order_as_the_new_baseline() {
        let mut c = col();
        c.move_entry(0, 2);
        c.mark_saved();
        assert!(!c.structure_modified);
        // Going back to the *old* order is now itself a change, because the
        // file on disk holds the new one.
        c.move_entry(2, 0);
        assert!(c.structure_modified);
    }
}