taimux-cli 0.26.0

The taimux picker: the TUI, the row layout, restart, resurrect and ssh federation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
//! The picker, drawn here instead of by fzf.
//!
//! Step 1 answered the questions this depends on, inside a real `tmux
//! display-popup -E`, and the answers are worth keeping written down:
//!
//! - **The alternate screen nests inside a popup** and unwinds cleanly. That was
//!   the one genuine unknown, since fzf runs `--height=100%` here and so says
//!   nothing about it.
//! - **Bracketed paste arrives as `Event::Paste`**, one event carrying its own
//!   text, embedded line break included. This is the structural fix for the bug
//!   that put `~/.tmux.conf.local` into live agent sessions: fzf reads a pasted
//!   line break as Enter, and every guard against that is a heuristic. Here there
//!   is nothing left to defeat. A pasted line break arrives as CR, not LF.
//! - **Resize is an event**, not a reload.
//! - **The window is sized by the POPUP**, 126x34 inside an 80% popup of a 160x45
//!   terminal, so the rows are fitted to what they are actually drawn in rather
//!   than to `tput cols` less a guess at fzf's chrome.
//!
//! Drawing goes to `/dev/tty` and input comes from there too (crossterm's
//! use-dev-tty), which leaves stdout carrying exactly one line, the chosen pane
//! id. atuin swaps file descriptors in its shell widget to get the same effect.
//!
//! Owning the state is most of what this buys. fzf has no state store, so the
//! bash picker keeps its mode in the BORDER LABEL and reads it back out by
//! matching words in it, carries the mode and the search flag through every
//! reload as quoted arguments because a child spawned by a reload cannot be
//! relied on to see the new label yet, and needs `--track --id-nth=2` so a reload
//! does not drop the cursor. All of that is a field here.

use std::cmp::Reverse;
use std::collections::{HashMap, HashSet};
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::process::Command;
use std::sync::mpsc::{Receiver, TryRecvError};
use std::sync::Arc;
use std::time::{Duration, Instant};

use crossterm::event::{
    self, DisableBracketedPaste, DisableMouseCapture, EnableBracketedPaste, EnableMouseCapture,
    Event, KeyCode, KeyEventKind, KeyModifiers, KeyboardEnhancementFlags, MouseButton, MouseEvent,
    MouseEventKind, PopKeyboardEnhancementFlags, PushKeyboardEnhancementFlags,
};
use crossterm::{execute, terminal};
use fuzzy_matcher::skim::SkimMatcherV2;
use fuzzy_matcher::FuzzyMatcher;
use ratatui::backend::CrosstermBackend;
use ratatui::layout::{Constraint, Layout};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, List, ListItem, ListState, Paragraph, Wrap};
use ratatui::Terminal;

use crate::{ansi, rows};
use taimux_core::{env, index};

/// How close two clicks on one row have to be to read as a double-click, which
/// is what accepts it. Long enough to be reachable without hurrying, short
/// enough that two deliberate single clicks on the same row do not switch panes
/// by accident. Claude Code's own stray-click guard sits in the same range.
const DOUBLE_CLICK: Duration = Duration::from_millis(400);

/// Which list is on screen. Tab steps round the cycle.
///
/// The first four are the same question asked of the same list, and the last
/// four are not states at all: Background and Outdated ask different questions
/// of it (what did this session leave RUNNING, what code is it running, rather
/// than what is it doing), and Panes and Dead change what the list IS, every
/// pane on the server whether a session runs in it or not, and the sessions
/// that have ended. So they sit at the far end, in that order, rather than
/// between two states of a running session. Background comes first of them
/// because it is nearest to idle, where most of its rows are, and Dead stays
/// last, the one stop with no pane in it at all.
///
/// Run is the one state list that also takes rows outside its state: the
/// sessions Background lists, since work a finished turn left running is still
/// work going on, and the working list is where you look for what is busy.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Mode {
    All,
    Input,
    Run,
    Idle,
    Background,
    Outdated,
    Panes,
    Dead,
}

impl Mode {
    /// The state filter this mode passes to the layout; empty means every row.
    ///
    /// Outdated is empty because being behind is not a state: a session waiting,
    /// working or idle can each be running code a self-update has replaced, and
    /// that filter rides on `Input::outdated` instead. Background is empty for
    /// the same reason, and rides on `Input::background`: a turn that left a
    /// shell running is idle, and one started since can be working with that
    /// shell still going. Run's filter is widened by that same flag, as
    /// `Input::with_background`, so its idle rows with work in flight come too.
    fn filter(self) -> &'static str {
        match self {
            Mode::All => "",
            Mode::Input => "input",
            Mode::Run => "run",
            Mode::Idle => "idle",
            Mode::Background => "",
            Mode::Outdated => "",
            // Every row, the panes with no session in them as well: those ride
            // on `Input::panes`, since a pane is not a state of a session.
            Mode::Panes => "",
            Mode::Dead => "dead",
        }
    }

    fn label(self) -> &'static str {
        match self {
            Mode::All => "agent sessions",
            Mode::Input => "waiting for an answer",
            // Says what else is in it, since those rows keep their idle marker
            // and would otherwise read as having strayed into the wrong list.
            Mode::Run => "working or running background work",
            Mode::Idle => "idle at the prompt",
            Mode::Background => "running background work",
            Mode::Outdated => "running outdated code",
            Mode::Panes => "every pane",
            Mode::Dead => "past sessions",
        }
    }

    /// The name this mode is carried across a reopen by. Its own word rather
    /// than the state filter, since Background, Outdated and All share that.
    pub fn key(self) -> &'static str {
        match self {
            Mode::All => "all",
            Mode::Input => "input",
            Mode::Run => "run",
            Mode::Idle => "idle",
            Mode::Background => "background",
            Mode::Outdated => "outdated",
            Mode::Panes => "panes",
            Mode::Dead => "dead",
        }
    }

    pub fn from_key(k: &str) -> Mode {
        match k {
            "input" => Mode::Input,
            "run" => Mode::Run,
            "idle" => Mode::Idle,
            "background" => Mode::Background,
            "outdated" => Mode::Outdated,
            "panes" => Mode::Panes,
            "dead" => Mode::Dead,
            _ => Mode::All,
        }
    }

    /// The ring Tab walks, and which stops are worth landing on.
    ///
    /// A stop with nothing that could ever be in it is left OUT rather than
    /// reached and found empty: no cache of past sessions, no past stop, and
    /// nothing installed to compare a version against, no outdated stop. An
    /// empty list you can still land on is one you have to press Tab past every
    /// time round.
    ///
    /// The background stop is always on, as the states are: it can be empty
    /// right now, but nothing about the machine says it always will be. So is
    /// the every-pane stop, which never is: the picker is itself in a pane.
    fn cycle(ended: bool, outdated: bool) -> [(Mode, bool); 8] {
        [
            (Mode::All, true),
            (Mode::Input, true),
            (Mode::Run, true),
            (Mode::Idle, true),
            (Mode::Background, true),
            (Mode::Outdated, outdated),
            (Mode::Panes, true),
            (Mode::Dead, ended),
        ]
    }

    /// One step round the ring, forwards or back, skipping the stops that are
    /// not on.
    fn step(self, back: bool, ended: bool, outdated: bool) -> Mode {
        let cycle = Mode::cycle(ended, outdated);
        let n = cycle.len();
        let at = cycle.iter().position(|(m, _)| *m == self).unwrap_or(0);
        // `at + n - k` rather than `at - k`, so going backwards past the first
        // stop stays in usize and wraps on the modulo like every other step.
        (1..=n)
            .map(|k| if back { at + n - k } else { at + k })
            .map(|i| cycle[i % n])
            .find(|(_, on)| *on)
            .map(|(m, _)| m)
            .unwrap_or(Mode::All)
    }

    /// One step round: all, waiting, working, idle, background, outdated,
    /// every pane, ended, all.
    fn next(self, ended: bool, outdated: bool) -> Mode {
        self.step(false, ended, outdated)
    }

    /// The same ring the other way, which is what shift-tab walks.
    ///
    /// Worth binding because the ring is short and the stop you want is as
    /// often the one behind you as the one ahead: overshooting "waiting for an
    /// answer" by one used to cost four more presses to come back to.
    fn prev(self, ended: bool, outdated: bool) -> Mode {
        self.step(true, ended, outdated)
    }
}

/// Where rows come from, and what does not change while the picker is open.
///
/// `fetch` is a closure rather than a string so ctrl-r and the refresh timer can
/// ask again. `ended` is separate because the ended list is not the pane list
/// filtered: it comes off the sessions cache and nothing in it has a pane at all.
pub struct Source {
    /// Shared and thread-safe because a refresh runs OFF the input loop: see
    /// `start_refresh`. It was a plain closure until a sweep froze the picker
    /// for the 85 seconds its restarts took, with no key accepted and nothing
    /// on screen to say why.
    pub fetch: Arc<dyn Fn() -> String + Send + Sync>,
    /// The panes with a restart in flight, for the marker column, asked on the
    /// same thread and just before `fetch`. The rows already come back held at
    /// what they were (see `restarting` in core), so this only says WHICH rows
    /// are held, which nothing in a row can.
    pub restarting: Arc<dyn Fn() -> HashSet<String> + Send + Sync>,
    /// The ended list stays synchronous: it is a read of one cache file, with no
    /// fork in it, and it is what Tab's last stop shows the instant you land on
    /// it. Nothing here has ever been slow, and making it async would mean
    /// showing pane rows under the "past sessions" label while it arrived.
    pub ended: Option<Box<dyn Fn() -> String>>,
    pub cur: String,
    /// Where the pane the picker was opened from IS, for the case where that
    /// pane is not an agent session: `cur` then matches no row at all and these
    /// are what the cursor is placed by instead. See `nearest`.
    ///
    /// Empty means "not known", which is what every entry point but `pick` hands
    /// over, and the cursor then opens at the top of the list as it always did.
    pub cur_cwd: String,
    pub cur_target: String,
    pub home: String,
    pub newver: String,
    /// The taimux script, for the two keys that act rather than navigate. Unset
    /// means they are not bound, and the header then does not advertise them:
    /// the header only ever says what is really there.
    pub script: Option<String>,
    /// Set only when the binding said so with `-e TAIMUX_POPUP=1`. It is what
    /// allows the picker to close and reopen itself at a new size, which would
    /// be wrong for a picker running inline in a pane: tmux resizes a PANE with
    /// the client already, so there is nothing to do there and everything to
    /// lose by guessing.
    pub popup: bool,
    /// What a previous instance was doing when the terminal grew under it.
    pub state: State,
}

/// Which row to open on when the pane the picker was opened from is not an agent
/// session, and so is not in the list at all.
///
/// Pressed from a shell, `cur` matches nothing, and the cursor used to land on
/// the top of the list: a row chosen by whichever session tmux happens to list
/// first, which is to say by nothing. The question it should answer is "which of
/// these sessions is the one I am working on", and the best evidence for that is
/// the DIRECTORY. A shell in `~/projects/web` and an agent in `~/projects/web`
/// are the same piece of work; one in `~/projects/web/docs` very nearly is; one
/// in `~/notes` is not.
///
/// So the working directory is the primary key and the tmux list only breaks its
/// ties, which is the case where two sessions are equally close to the directory
/// and the nearer pane is the likelier one. Ties in BOTH keep the list's own
/// order, since `min_by_key` takes the first of equal minimums.
fn nearest(rows: &[&rows::Row], cwd: &str, target: &str) -> Option<usize> {
    rows.iter()
        .enumerate()
        .min_by_key(|(_, r)| {
            let (shared, apart) = cwd_near(cwd, &r.cwd);
            (Reverse(shared), apart, tmux_near(target, r))
        })
        .map(|(i, _)| i)
}

/// Path components, ignoring the empties a leading, doubled or trailing slash
/// leaves, so `/a/b`, `/a/b/` and `//a/b` are one directory rather than three.
fn comps(p: &str) -> Vec<&str> {
    p.split('/').filter(|c| !c.is_empty()).collect()
}

/// How near two directories are: how much of the path they share from the root,
/// then how many steps apart they are through the deepest directory they have in
/// common. The same directory is `(n, 0)`, a subdirectory of it `(n, 1)`, a
/// sibling `(n-1, 2)`.
///
/// Both halves are load-bearing, and in that order. Shared components first, so
/// a session one level DOWN from the directory you are in beats one a level up:
/// the deeper of the two is the more specific answer, and the parent is often
/// just where several unrelated projects happen to live. Then the distance, so
/// the directory itself beats a subdirectory of it.
///
/// Nothing in common answers `(0, 0)` rather than `(0, distance)`: the paths
/// diverge at their first component, so the directory says nothing about which
/// row is nearer, and ranking on the distance alone would put whichever session
/// sits closest to the root in front for a reason nobody could read off the
/// screen. The tie then falls through to the tmux list, which is the honest
/// answer. Same for an unknown directory on either side, which is empty and so
/// shares nothing with anything.
fn cwd_near(cur: &str, row: &str) -> (usize, usize) {
    let (a, b) = (comps(cur), comps(row));
    let shared = a.iter().zip(b.iter()).take_while(|(x, y)| x == y).count();
    if shared == 0 {
        return (0, 0);
    }
    (shared, (a.len() - shared) + (b.len() - shared))
}

/// How near a row's pane is to the pane the picker was opened from, in the list
/// tmux itself keeps: the same session first, nearest window and then nearest
/// pane inside it, then anything else on this server, then another host, whose
/// panes are not in this server's list at all and whose window numbers mean
/// nothing here.
fn tmux_near(cur: &str, r: &rows::Row) -> (u8, usize, usize) {
    /// Somewhere on this server, but not near anything: a different session, or
    /// a row that names no pane (an ended session's label is its age).
    const ELSEWHERE: (u8, usize, usize) = (1, 0, 0);
    if !r.host.is_empty() {
        return (2, 0, 0);
    }
    let (Some((sess, win, pane)), Some((rsess, rwin, rpane))) =
        (target_parts(cur), target_parts(&r.target))
    else {
        return ELSEWHERE;
    };
    if sess != rsess {
        return ELSEWHERE;
    }
    (0, win.abs_diff(rwin), pane.abs_diff(rpane))
}

/// `session:window.pane`, split into the three things it names, or `None` for
/// anything that is not one.
fn target_parts(t: &str) -> Option<(&str, usize, usize)> {
    let (sess, rest) = t.split_once(':')?;
    let (win, pane) = rest.split_once('.')?;
    Some((sess, win.parse().ok()?, pane.parse().ok()?))
}

/// Throw away what ratatui thinks is on the terminal, so the next draw repaints
/// in full.
///
/// `resize` and NOT `Terminal::clear`, which is the obvious call and is a trap
/// here: clear snapshots the cursor first, and the crossterm backend does that
/// with `crossterm::cursor::position()`, which writes ESC[6n to the PROCESS's
/// stdout rather than to the backend's writer. Stdout carries exactly one thing
/// in this program, the chosen pane id, so anything using clear puts `[6n` where
/// the caller reads the answer.
///
/// This was fixed once for ctrl-l and left in place for the two keys that hand
/// the terminal to a child, which need it MORE: they always repaint, so they
/// always leaked, and the list came back blank after every restart.
fn repaint<B: ratatui::backend::Backend>(term: &mut Terminal<B>) {
    if let Ok(size) = term.size() {
        let _ = term.resize(size.into());
    }
}

/// Run one of the two keys that act, with the terminal handed over.
///
/// Its output goes to **/dev/tty**, not to the picker's stdout. Inherited, the
/// child's whole screen ends up in the one thing this program writes to stdout,
/// the chosen pane id: measured, the caller of `taimux tui` got the sweep's
/// plan, its prompt and its closing message, and then the pane id on the end.
/// In a popup stdout happens to BE the tty, which is why it looked right there
/// and was wrong everywhere else.
/// Run a child that owns the terminal while it runs.
///
/// All THREE streams are pointed at the terminal, stdin included. The picker's
/// own stdin is not the terminal (its stdout carries the chosen pane id, and it
/// draws to /dev/tty for exactly that reason), so a child left to inherit it
/// gets a stdin that is not where the person is typing, while its output goes
/// somewhere else entirely. The child then reads its own /dev/tty to get around
/// that, which works but means the parent hands over a terminal it has only
/// half set up.
fn act_child(script: &str, args: &[&str]) -> std::io::Result<std::process::ExitStatus> {
    let mut c = Command::new(script);
    c.args(args);
    if let Ok(tty) = OpenOptions::new().write(true).open("/dev/tty") {
        if let Ok(err) = tty.try_clone() {
            c.stdout(tty).stderr(err);
        }
    }
    if let Ok(inp) = OpenOptions::new().read(true).open("/dev/tty") {
        c.stdin(inp);
    }
    c.status()
}

/// Raw mode, the alternate screen and bracketed paste, undone on the way out.
///
/// A guard rather than a pair of calls because every early return, `?` and panic
/// has to restore the terminal: the failure mode is a shell left in raw mode with
/// no echo, which is indistinguishable from a hung machine to whoever is looking
/// at it. This is the part bash could never do properly, since a trap does not
/// survive a kill.
struct Guard {
    out: File,
    kitty: bool,
    mouse: bool,
}

impl Guard {
    fn new(kitty: bool) -> std::io::Result<Guard> {
        let mut out = OpenOptions::new().write(true).open("/dev/tty")?;
        terminal::enable_raw_mode()?;
        // Mouse capture goes everywhere bracketed paste goes, including the
        // suspend/resume pair below, or handing the terminal to a child would
        // leave the picker with a dead wheel when it came back.
        //
        // fzf had this on by default and the port never asked for it, which is
        // the same way Page Up and Page Down went missing: nothing referenced
        // the behaviour, so nothing pointed at its absence. TAIMUX_MOUSE=0
        // turns it off, for a terminal where capture costs more than it gives
        // (it takes over drag-to-select, and tmux's own copy mode with it).
        execute!(out, terminal::EnterAlternateScreen, EnableBracketedPaste)?;
        let mouse = env::var("TAIMUX_MOUSE").is_none_or(|v| v != "0");
        if mouse {
            let _ = execute!(out, EnableMouseCapture);
        }
        if kitty {
            // Makes a bare ESC arrive on its own rather than as the head of a
            // possible chord. Only some terminals answer; the flags are harmless
            // where they are ignored, and they also turn on key-release events,
            // which is why the loop filters on KeyEventKind::Press.
            let _ = execute!(
                out,
                PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
            );
        }
        Ok(Guard { out, kitty, mouse })
    }

    /// Hand the terminal back so a child can own it, as fzf's `execute()` does.
    fn suspend(&mut self) {
        if self.mouse {
            let _ = execute!(self.out, DisableMouseCapture);
        }
        let _ = execute!(
            self.out,
            DisableBracketedPaste,
            terminal::LeaveAlternateScreen
        );
        let _ = terminal::disable_raw_mode();
    }

    fn resume(&mut self) {
        let _ = terminal::enable_raw_mode();
        // Wipe what the child drew, BEFORE going back to the alternate screen.
        //
        // The child owned the NORMAL screen while it had the terminal, so its
        // last frame is still sitting there under the picker. Leaving the
        // alternate screen on the way out then reveals it, and what you get,
        // seconds after picking a row, is the sweep's "restart every outdated
        // session" screen back on your terminal as if it had run again.
        // Reported that way, and it is only ever a leftover.
        //
        // Nothing of the caller's is lost: this runs only after a child that
        // cleared the screen for itself.
        let _ = execute!(
            self.out,
            terminal::Clear(terminal::ClearType::All),
            crossterm::cursor::MoveTo(0, 0),
            terminal::EnterAlternateScreen,
            EnableBracketedPaste
        );
        if self.mouse {
            let _ = execute!(self.out, EnableMouseCapture);
        }
    }
}

impl Drop for Guard {
    fn drop(&mut self) {
        if self.kitty {
            let _ = execute!(self.out, PopKeyboardEnhancementFlags);
        }
        self.suspend();
    }
}

/// The columns a row is laid out for: the drawn area less the border and less the
/// two the pointer takes. fzf reserves the same two and reports the rest in
/// FZF_COLUMNS, a figure that only exists once fzf is already up, which is why
/// the bash picker has to guess a width for its first render.
fn row_width(area_width: u16) -> usize {
    (area_width as usize).saturating_sub(4)
}

/// Under this many characters a term is in every transcript and a match would
/// say nothing, so a short query filters on the row alone.
fn search_min() -> usize {
    env::var("TAIMUX_SEARCH_MIN")
        .and_then(|v| v.parse().ok())
        .unwrap_or(3)
}

/// Text search is on unless it is turned off, the same knob the bash picker
/// reads. Note that it still starts OFF at the ctrl-t toggle; this only says
/// whether the key does anything.
fn search_enabled() -> bool {
    env::on("TAIMUX_SEARCH")
}

fn sessions_enabled() -> bool {
    env::on("TAIMUX_SESSIONS")
}

/// Following the terminal is on unless it is turned off. `0` leaves a popup at
/// whatever size it opened with, which is what every version before this did.
fn resize_enabled() -> bool {
    env::on("TAIMUX_RESIZE")
}

/// The ended-sessions list, or nothing where the sessions cache is turned off.
/// `Source.ended` being None is what takes that mode out of the Tab cycle, so
/// the decision is made once, here.
pub fn ended_source() -> Option<Box<dyn Fn() -> String>> {
    sessions_enabled().then(|| Box::new(|| index::dead_rows(now())) as Box<dyn Fn() -> String>)
}

fn now() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0)
}

/// The rows the query keeps: best match first, or `by_date` newest first by
/// when each session last said something.
///
/// Terms are ANDed and their scores summed, which is fzf's extended-search
/// default rather than one fuzzy match over the whole query. With no query the
/// list keeps its own order; the sort is stable, so ties do too.
///
/// By date sorts on each row's `since`, so it holds with no query as well: the
/// live lists come in tmux order and the past list newest first already. A row
/// that cannot say when it last spoke (an agent that reports nothing, a host
/// whose taimux predates the field) goes after every row that can, keeping the
/// order it came in.
///
/// Under a query, by date is NOT fzf's `--no-sort`, which leaves every match
/// where it stands. That was tried against the real history and is the version
/// nobody wants: the letters of `ha-bert`, in order but scattered, are in a dozen
/// rows that have nothing to do with it, and the ranking was all that kept those
/// under the rows that actually SAY it. With it gone, the top of the list was all
/// noise. So the rows holding every term as typed come first, newest first, and
/// the loose matches follow, newest first too. The rows are the same either way;
/// only their order changes.
///
/// The haystack is the row's PLAIN text: fzf is handed `--ansi` and has to parse
/// our own colours back out to match on them, which is work this does not do.
fn filter(list: &[rows::Row], query: &str, matcher: &SkimMatcherV2, by_date: bool) -> Vec<usize> {
    // Newest first, and `None` after every date, since it is the smallest.
    let newest = |i: usize| Reverse(list[i].since);
    let terms: Vec<&str> = query.split_whitespace().collect();
    if terms.is_empty() {
        let mut all: Vec<usize> = (0..list.len()).collect();
        if by_date {
            all.sort_by_key(|&i| newest(i));
        }
        return all;
    }
    // Folded, as the matcher ignores case too.
    let folded: Vec<String> = terms.iter().map(|t| t.to_lowercase()).collect();
    let mut kept: Vec<(i64, bool, usize)> = Vec::new();
    for (i, r) in list.iter().enumerate() {
        let hay = r.plain();
        let mut total = 0i64;
        let mut all = true;
        for t in &terms {
            match matcher.fuzzy_match(&hay, t) {
                Some(s) => total += s,
                None => {
                    all = false;
                    break;
                }
            }
        }
        if all {
            let loose = by_date && {
                let low = hay.to_lowercase();
                !folded.iter().all(|t| low.contains(t.as_str()))
            };
            kept.push((total, loose, i));
        }
    }
    if by_date {
        kept.sort_by_key(|&(_, loose, i)| (loose, newest(i)));
    } else {
        kept.sort_by_key(|&(score, _, _)| Reverse(score));
    }
    kept.into_iter().map(|(_, _, i)| i).collect()
}

/// What the picker says it can do. Only what is really bound: a header promising
/// a key that does nothing is worse than a shorter one.
fn header(script: bool, ended: bool, search_key: bool, search_on: bool, by_date: bool) -> String {
    let mut h = String::from("enter: switch");
    if ended {
        h.push_str("/resume");
    }
    h.push_str("   tab: filter   ctrl-r: refresh   ctrl-/: preview");
    if search_key {
        h.push_str(if search_on {
            "   ctrl-t: search text (on)"
        } else {
            "   ctrl-t: search text"
        });
    }
    h.push_str(if by_date {
        "   ctrl-s: sort by date (on)"
    } else {
        "   ctrl-s: sort by date"
    });
    if script {
        // "outdated" and not "stale", which it said until the list of those rows
        // got a Tab stop of its own: two words for one thing on the same screen
        // reads as two different things.
        h.push_str("   ctrl-x: restart   ctrl-o: hand off   f8: restart all outdated");
    }
    h
}

/// The bottom-right stamp: which taimux drew this list.
///
/// Worth a permanent corner of the chrome because the answer is not obvious from
/// anywhere else. The picker is a popup launched by a tmux binding, one binary
/// per host, and a self-update swaps the launcher under a running tmux server
/// without touching the panes: the same keypress can therefore draw a different
/// version tomorrow, and until now nothing on screen said which. It is the crate
/// version, the same string `taimux version` prints, so a row's `claude 2.1.229`
/// and this cannot be confused for each other: this one is named.
fn version_tag() -> String {
    format!(" taimux {} ", env!("CARGO_PKG_VERSION"))
}

/// …but only where the bottom border can carry it AND the count.
///
/// ratatui gives a right-aligned title precedence over a left-aligned one, so
/// without this the stamp eats the count on a narrow window: measured at 20
/// columns it left ` 5/`, and at 16 the count was gone altogether. That is the
/// priority backwards. The count is live and read constantly, the stamp is
/// reference read once after an update, so the stamp is what gives way.
///
/// `+ 2` is the two corner characters the border spends whatever else happens.
fn room_for_tag(width: u16, count: &str) -> bool {
    width as usize >= count.chars().count() + version_tag().chars().count() + 2
}

/// What to say where the rows would be, when there are none.
///
/// Four different silences, and they mean different things: nothing running at
/// all, nothing in the state you are filtering on, nothing matching what you
/// typed, and no ended sessions recorded yet. Saying which is the whole point,
/// since the picker used to say nothing and simply close.
///
/// `search_hint` is whether ctrl-t would search what was said and is not doing
/// so here, which is when a query that matches no row may still be in a
/// transcript. A URL pasted into the past list with its search off found nothing
/// and said nothing about why, which is exactly the moment to name the key.
///
/// `live_hits` is how many sessions still open in a pane the same query matches,
/// counted only where the past list has nothing of its own (see `App::live_hits`).
/// A claude session open in a pane is left out of the past list, so the session a
/// pasted merge request URL came from sat one Tab away while this list said
/// "Nothing matches" and no more, and the search was given up as a miss.
fn empty_note(
    mode: Mode,
    query: &str,
    scanning: bool,
    nothing_scanned: bool,
    ended: bool,
    search_hint: bool,
    live_hits: usize,
) -> Vec<Line<'static>> {
    let mut lines: Vec<String> = Vec::new();
    if scanning {
        // The first scan is off the loop like every other, so this is what a
        // popup shows for the ~90ms it usually takes, and what it keeps showing
        // instead of going blank when something makes it slow.
        lines.push("Looking for agent sessions…".into());
        lines.push(String::new());
        lines.push("Esc closes this.".into());
        return lines
            .into_iter()
            .map(|l| Line::from(format!("  {}", l)))
            .collect();
    }
    if !query.is_empty() {
        lines.push(format!("Nothing matches {}", query));
        if search_hint {
            lines.push("ctrl-t searches what was said in them too.".into());
        }
        // Tab, because the past list is the last stop on the ring and the next
        // stop round lists every live session.
        match live_hits {
            0 => {}
            1 => lines.push("A session still open in a pane matches it: Tab shows it.".into()),
            n => lines.push(format!(
                "{} sessions still open in panes match it: Tab shows them.",
                n
            )),
        }
        lines.push("ctrl-u clears it.".into());
    } else if mode == Mode::Dead {
        lines.push("No past conversations have been found here yet.".into());
        lines.push("They are remembered as sessions come and go.".into());
    } else if mode == Mode::Panes {
        // Only a row source that lists no panes at all gets here: tmux always
        // has one, the pane the picker was opened from.
        lines.push("No panes were found.".into());
        lines.push("Tab moves on to the next list.".into());
    } else if nothing_scanned {
        lines.push("No agent sessions on this machine.".into());
        lines.push(
            if ended {
                "Nothing is running one. Tab reaches the conversations that ended."
            } else {
                "Nothing is running one."
            }
            .into(),
        );
    } else {
        lines.push(format!("Nothing is {} right now.", mode.label()));
        lines.push("Tab moves on to the next list.".into());
    }
    lines.push(String::new());
    lines.push("Esc closes this.".into());
    lines
        .into_iter()
        .map(|l| Line::from(format!("  {}", l)))
        .collect()
}

/// Whether a scan found no session at all: no row in it but the panes with no
/// agent in them, which it always brings back as well (see `Mode::Panes`).
///
/// Asked of the scan rather than of whether it is empty, which it used to be and
/// can no longer be: every pane is in it, so a machine with nothing running
/// would read as one whose sessions are all in some other state.
fn no_sessions(tsv: &str) -> bool {
    !tsv.lines().any(|l| {
        let f: Vec<&str> = l.split('\t').collect();
        f.len() >= 7 && f[5] != taimux_core::panes::PANE
    })
}

/// The border label: which list and in what order, whether the timer and text
/// search are on, and whether a refresh is taking long enough to be worth
/// mentioning.
fn label(mode: Mode, by_date: bool, live: bool, search: bool, refreshing: bool) -> String {
    let mut s = format!(" {}", mode.label());
    // Straight after the name, since it says what order that list is in. It is
    // a setting, like ⌕, so it shows whether a query is typed or not: a label
    // that came and went as you typed would read as the order changing under you.
    if by_date {
        s.push_str(" · by date");
    }
    if live {
        s.push_str(" · live");
    }
    if search {
        s.push_str(" · ⌕");
    }
    // Last, and only after a second: on a healthy machine the answer is back
    // before the next draw, so a label that flashed on every tick would be noise
    // about nothing. It is here for the case where the list is NOT arriving, so
    // that a picker waiting on a slow scan reads as busy rather than as dead.
    if refreshing {
        s.push_str(" · refreshing");
    }
    s.push(' ');
    s
}

/// A captured screen and when it was taken.
///
/// The preview is redrawn on every tick and every keypress, and capturing a pane
/// per redraw would be a fork per keystroke. Cached by pane, so it costs one
/// capture per row the cursor lands on, per TTL. Short on purpose: a preview is
/// read to see what a session is doing NOW, and a stale screen is worse than a
/// slow one.
const PREVIEW_TTL: Duration = Duration::from_millis(750);

/// …and longer for one that costs an ssh. The remote screen is no fresher for
/// being asked more often, since the fetch itself is the slow part.
const REMOTE_TTL: Duration = Duration::from_secs(3);

struct App {
    src: Source,
    matcher: SkimMatcherV2,
    mode: Mode,
    /// Typing searches what sessions SAID, not only what their rows show, in the
    /// lists of live sessions. On by default since 2026-09-24, Patrick's call,
    /// after it was off for as long as the bash picker existed. The reason it
    /// HAD to be off (a paste read as Enter) went with fzf, see the module
    /// comment, and what was left was a default that made the one search people
    /// reach for, a link or an error string, find nothing until ctrl-t.
    search: bool,
    /// The same, for the past list, which is where it went on first: a pasted
    /// URL matched nothing there while rses, which always searched content,
    /// found the very sessions it came from. Each list keeps its own switch, so
    /// ctrl-t to jump by name among the live sessions leaves the history
    /// searching what was said.
    search_past: bool,
    /// Order the list by when each session last said something, newest first,
    /// rather than in its own order or ranked best match first (loose matches
    /// still go last, see `filter`). One switch for every list, holding across
    /// Tab as `search` does.
    ///
    /// It was bound on the idle and past lists alone until 2026-10-16, on the
    /// reasoning that a session working or holding a question is listed for
    /// what it is doing now. Patrick's call to open it up: "which of these
    /// spoke last" is a question worth asking of any of them.
    by_date: bool,
    preview: bool,
    query: String,
    width: usize,
    /// The pane rows, as the last scan brought them back.
    tsv: String,
    /// The past list's rows, as the sessions cache last gave them.
    ///
    /// Its own buffer because it is its own list, not the panes filtered. The
    /// two used to share one, and that is how a scan still out when Tab reached
    /// this list landed on top of it: "past sessions" showed live panes until
    /// the next tick, and going back the other way drew the past rows under the
    /// live label until a scan came back.
    past: String,
    all: Vec<rows::Row>,
    view: Vec<usize>,
    sel: usize,
    shot: Option<(String, Instant, String)>,
    /// The last screen each remote row sent back, and when.
    ///
    /// One per row rather than the single `shot`, because a remote screen costs
    /// an ssh and the cursor going back over a row it has just left should not
    /// pay for it again before showing anything.
    remote: HashMap<String, (Instant, String)>,
    /// The remote screen on its way, on a worker thread, and whose it is.
    ///
    /// The ssh used to run inside the draw, so every cursor landing on a remote
    /// row held the keys for a round trip (0.1 s on a warm ControlMaster, the 4 s
    /// bound on a host gone quiet), and holding an arrow down over a column of
    /// them queued the repeats up behind it. One at a time, which is also what
    /// coalesces a fast scroll: the rows passed over while one is out are never
    /// asked for, and the row the cursor stops on is asked next.
    fetching: Option<(String, Receiver<String>)>,
    /// How far the preview is scrolled from its default view, in rows, negative
    /// towards the start of the body.
    poff: i32,
    /// The row `poff` was measured against. Comparing it in `preview()` resets
    /// the offset on every way the cursor can move (a key, the wheel, a click, a
    /// rebuild, the refresh timer) from ONE place, rather than needing each of
    /// those to remember to do it. An offset carried onto another row is a lie:
    /// it was measured against a different session's screen.
    poff_for: String,
    /// A refresh running on a worker thread, and when it started.
    ///
    /// The picker used to call the row source straight from the input loop, so
    /// for as long as that took there was no draw and no key: a refresh that
    /// normally costs 90ms froze the whole picker for 85 SECONDS after an F8
    /// sweep, showing the sweep's last screen the entire time, with Esc, ctrl-c
    /// and even tmux's own F1 all apparently dead. Nothing about that told its
    /// owner it was alive.
    ///
    /// One at a time: the timer must not stack refreshes on a machine where they
    /// take longer than the interval, which is exactly the machine this matters
    /// on.
    pending: Option<Receiver<Refresh>>,
    pending_since: Instant,
    /// The client as of the last refresh, for the resize check.
    client: Option<(String, (u16, u16))>,
    /// Panes with a restart in flight, as of the last refresh.
    ///
    /// Only the marker column reads it. Holding the ROW is the scan's job: a
    /// restart takes the session away for a second or so, and the pane used to
    /// drop out of the list for it and come back, with every row below it
    /// moving up and down again. This picker held the one row ctrl-x was
    /// pressed on, from what it had on screen, and nothing else held anything:
    /// an F8 sweep blinked out every row it touched. The restart now writes the
    /// row down itself and the scan lists it from there, for every list.
    restarting: HashSet<String>,
    /// How many live sessions the query matches, while the past list is on
    /// screen and matches none: what its empty note points at. Counted when the
    /// query is applied rather than when the note is drawn, since a draw runs on
    /// every tick and this lays out the live rows and reads their index files.
    live_hits: usize,
}

impl App {
    /// The preview for the row under the cursor, in two parts: a header saying
    /// exactly where the session is, and the body to show under it.
    ///
    /// Split rather than concatenated so the header can be PINNED while the body
    /// scrolls. The third value says where the body's default view sits: a live
    /// pane is anchored at the BOTTOM, because what a session is doing is the
    /// last thing on its screen, while an ended conversation reads from the top.
    /// One offset then means the same thing for both, "rows towards the start",
    /// and the clamp does the rest.
    ///
    /// The header comes off the row rather than out of a `tmux display-message`,
    /// which is a fork the bash preview pays every time the cursor moves.
    fn preview(&mut self) -> (Vec<Line<'static>>, Vec<Line<'static>>, bool) {
        let Some(r) = self.view.get(self.sel).map(|&i| &self.all[i]) else {
            return (Vec::new(), Vec::new(), false);
        };
        let (id, target, cwd, host) = (
            r.pane_id.clone(),
            r.target.clone(),
            r.cwd.clone(),
            r.host.clone(),
        );
        if self.poff_for != id {
            self.poff = 0;
            self.poff_for = id.clone();
        }
        // Where the words you typed turn up in what this session actually SAID.
        // The row has room for one window of context; this has room for several,
        // so the preview is where you find out whether the hit is the one you
        // were after before jumping to it.
        let mut out: Vec<Line<'static>> = Vec::new();
        let mut body: Vec<Line<'static>> = Vec::new();
        if self.searching() && self.query.chars().count() >= search_min() {
            let hits = index::preview_match(
                &id,
                &index::Query::new(&self.query),
                env::var("TAIMUX_SEARCH_PREVIEW")
                    .and_then(|v| v.parse().ok())
                    .unwrap_or(4),
            );
            for h in hits {
                out.push(Line::from(vec![
                    Span::styled("⌕ ", Style::default().fg(Color::Yellow)),
                    Span::raw(h),
                ]));
            }
            if !out.is_empty() {
                out.push(Line::from(""));
            }
        }
        out.push(Line::from(vec![
            Span::styled(
                target,
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw("   "),
            Span::styled(cwd, Style::default().add_modifier(Modifier::DIM)),
        ]));
        out.push(Line::from(Span::styled(
            "─".repeat(44),
            Style::default().fg(Color::DarkGray),
        )));
        out.push(Line::from(""));

        // A past conversation has no screen to capture: what it has is the
        // last things that were said in it.
        if id.starts_with("dead:") {
            if id == "dead:!" {
                body.push(Line::from(Span::styled(
                    "the list is still being built",
                    Style::default().fg(Color::DarkGray),
                )));
                return (out, body, false);
            }
            let Some((agent, key)) = taimux_core::index::split_past_id(&id) else {
                body.push(Line::from(Span::styled(
                    "that row does not name a conversation",
                    Style::default().fg(Color::Red),
                )));
                return (out, body, false);
            };
            // A conversation kept in a database has no file to be missing, and
            // its store answered when the list was built.
            if key.starts_with('/') && !std::path::Path::new(key).is_file() {
                body.push(Line::from(Span::styled(
                    "this conversation is no longer on disk",
                    Style::default().fg(Color::Red),
                )));
                return (out, body, false);
            }
            let want = env::var("TAIMUX_DEAD_TURNS")
                .and_then(|v| v.parse().ok())
                .unwrap_or(6);
            let turns = taimux_core::agents::turns(agent, key, want);
            if turns.is_empty() {
                body.push(Line::from(Span::styled(
                    "(nothing was said in this one)",
                    Style::default().fg(Color::DarkGray),
                )));
            }
            for t in turns {
                // Two lines a turn is enough to recognise one, and the preview
                // pane is short.
                let cap = self.width.max(20) * 2;
                let what = if t.text.chars().count() > cap {
                    format!("{}…", t.text.chars().take(cap).collect::<String>())
                } else {
                    t.text
                };
                let (mark, st) = if t.you {
                    (
                        "❯ ",
                        Style::default()
                            .fg(Color::Cyan)
                            .add_modifier(Modifier::BOLD),
                    )
                } else {
                    ("  ", Style::default().add_modifier(Modifier::DIM))
                };
                body.push(Line::from(vec![
                    Span::styled(mark, st),
                    Span::styled(what, st),
                ]));
                body.push(Line::from(""));
            }
            // From the top: a conversation reads forwards, and its opening is
            // already on the row as the title, so what you want first is what
            // came after it.
            return (out, body, false);
        }
        // capture-pane only works where the pane IS, so a session on another host
        // renders its own. That is an ssh, and the script already knows how to
        // make it: which taimux is over there, the bound it runs under, and what
        // to say when a host stops answering between the list and the cursor
        // landing on its row. It beats keeping a second copy of that knowledge
        // here, and it runs on a thread (see `fetching`), so the draw only ever
        // shows what has already come back.
        if !host.is_empty() {
            let Some(script) = self.src.script.clone() else {
                body.push(Line::from(Span::styled(
                    format!("on {}: no taimux to ask", host),
                    Style::default().fg(Color::DarkGray),
                )));
                return (out, body, false);
            };
            self.take_remote();
            let fresh = matches!(self.remote.get(&id), Some((at, _)) if at.elapsed() < REMOTE_TTL);
            if !fresh {
                self.fetch_remote(&script, &id);
            }
            // A row seen before shows what it showed last while the new screen
            // is out: a tenth of a second of an older screen reads better than a
            // blank one flashing in between.
            match self.remote.get(&id) {
                Some((_, text)) => body.extend(tail(text, usize::MAX)),
                None => body.push(Line::from(Span::styled(
                    format!("asking {}…", host),
                    Style::default().fg(Color::DarkGray),
                ))),
            }
            return (out, body, true);
        }
        let fresh = matches!(&self.shot, Some((k, at, _))
                             if *k == id && at.elapsed() < PREVIEW_TTL);
        if !fresh {
            self.shot = Some((
                id.clone(),
                Instant::now(),
                taimux_core::tmux::capture_coloured(&id).unwrap_or_default(),
            ));
        }
        let screen = self
            .shot
            .as_ref()
            .map(|(_, _, s)| s.clone())
            .unwrap_or_default();
        // The WHOLE screen, and the renderer takes the last screenful of it, so
        // there is something above the default view to scroll into. The padding
        // to the pane height is trimmed here either way, or the tail would be
        // all padding: the same trap that made every waiting session read as
        // idle when the state reader was ported.
        body.extend(tail(&screen, usize::MAX));
        // Anchored at the bottom: what a session is doing is the last thing on
        // its screen.
        (out, body, true)
    }
}

/// The last `room` lines of a captured screen, which is where what a session is
/// doing lives.
///
/// The trailing blanks come off first. `capture-pane` pads its output to the pane
/// height, so a tail taken without trimming is all padding: that is the exact
/// trap that made every session waiting for an answer read as idle when the state
/// reader was ported, and it is the same capture being read here.
fn tail(screen: &str, room: usize) -> Vec<Line<'static>> {
    let mut lines = ansi::to_lines(screen);
    while lines
        .last()
        .is_some_and(|l| l.spans.iter().all(|s| s.content.trim().is_empty()))
    {
        lines.pop();
    }
    let over = lines.len().saturating_sub(room);
    lines.drain(..over);
    lines
}

/// What a refresh brings back: the rows, how long they took, and what the time
/// went on.
struct Refresh {
    tsv: String,
    restarting: HashSet<String>,
    took: Duration,
    /// Empty unless something forked; see `stat`.
    spent: String,
    /// The client this popup is on, asked for only when we are in a popup that
    /// may reopen itself, and only when tmux can name it without guessing. It
    /// rides along with the refresh because that already runs off the input
    /// loop: a resize check of its own would be another fork on it.
    client: Option<(String, (u16, u16))>,
}

/// Our own session, out of `$TMUX`: socket, server pid, session id.
fn own_session() -> Option<String> {
    let tmux = std::env::var("TMUX").ok()?;
    let id = tmux.split(',').nth(2)?.trim();
    (!id.is_empty()).then(|| format!("${}", id))
}

/// The client this popup is drawn on, and its size, or None when that cannot be
/// answered without guessing.
///
/// **Asking tmux for `#{client_width}` with no target is the bug this exists to
/// avoid.** An untargeted query answers for whichever client tmux considers
/// current, and Patrick routinely has two attached to one session: a 213-column
/// desktop and a 46-column phone. A picker opened on the PHONE then measured
/// itself against the desktop, decided a 44-column popup had been outgrown,
/// closed itself, and reopened on the desktop over whatever pane was there. That
/// is what "stuck after selecting another session" turned out to be: a popup
/// arriving unbidden on the other client.
///
/// So the client has to be unambiguous. One client on our session is our client.
/// Two, and nothing here can tell which of them the popup belongs to (tmux
/// exposes no format for it, and `display-popup -e` does not expand formats, so
/// the binding cannot pass it either), which is exactly when this must do
/// nothing at all.
fn own_client() -> Option<(String, (u16, u16))> {
    let session = own_session()?;
    let out = taimux_core::tmux::ask(&[
        "list-clients",
        "-t",
        &session,
        "-F",
        "#{client_tty} #{client_width} #{client_height}",
    ])?;
    let mut lines = out.lines().filter(|l| !l.trim().is_empty());
    let only = lines.next()?;
    if lines.next().is_some() {
        return None; // more than one client: whose popup is this?
    }
    let mut f = only.split_whitespace();
    let (tty, w, h) = (f.next()?, f.next()?.parse().ok()?, f.next()?.parse().ok()?);
    (w > 0 && h > 0).then(|| (tty.to_string(), (w, h)))
}

/// Could this popup usefully be bigger than it is?
///
/// tmux SHRINKS a popup to fit a client that got smaller and grows it back up to
/// the size it was asked for, so the only case left over is a terminal that grew
/// PAST that: a popup opened on a phone in portrait stays portrait-width after
/// the rotation, at 63% of a screen it was told to take 80% of. Measured, both
/// directions, before any of this was written.
///
/// `slack` is what keeps it from firing on a rounding difference of a column or
/// two, which would close and reopen the popup for nothing.
fn outgrown(ours: (u16, u16), client: (u16, u16), slack: u16) -> bool {
    let (pw, ph) = crate::install::popup_geometry(client.0 as usize);
    // A popup's usable area is its geometry less the border it draws.
    let want_w = (client.0 as u32 * pw as u32 / 100).saturating_sub(2) as u16;
    let want_h = (client.1 as u32 * ph as u32 / 100).saturating_sub(2) as u16;
    want_w > ours.0.saturating_add(slack) || want_h > ours.1.saturating_add(slack)
}

/// Everything the picker has to carry across a reopen, so a resize costs you
/// your popup's geometry and nothing else.
///
/// Its Default is an ORDINARY open, not an empty struct: `preview` is on unless
/// something turned it off, and deriving Default silently opened every picker
/// with the preview hidden, which showed up as the list being twice as tall as
/// the page keys expected.
#[derive(Debug, PartialEq, Eq)]
pub struct State {
    pub query: String,
    pub mode: &'static str,
    pub search: bool,
    /// Whether the past list searches what was said, which it does unless
    /// ctrl-t turned that off there.
    pub search_past: bool,
    pub by_date: bool,
    pub preview: bool,
    /// The row the cursor was on, by pane id.
    pub on: String,
    /// The client whose popup this was, so the reopen goes to THAT one rather
    /// than to whichever tmux considers current a moment later.
    pub client: String,
}

impl Default for State {
    fn default() -> Self {
        State {
            query: String::new(),
            mode: "all",
            search: true,
            search_past: true,
            by_date: false,
            preview: true,
            on: String::new(),
            client: String::new(),
        }
    }
}

/// How the picker finished.
pub enum Outcome {
    Chosen(String),
    Aborted,
    /// The terminal grew: reopen at the geometry the binding would use now,
    /// with this state. Only ever returned from a popup that was told it is one.
    Resize(State),
}

/// How slow a refresh has to be before it is written down.
///
/// Two seconds is well past anything healthy here (a full scan of 171 panes is
/// 90ms) and well short of the freeze that prompted this, so the log stays empty
/// on a normal day and names the culprit on a bad one.
fn slow_after() -> Duration {
    Duration::from_secs_f32(
        env::var("TAIMUX_SLOW_REFRESH")
            .and_then(|v| v.parse().ok())
            .unwrap_or(2.0),
    )
}

/// A refresh that took too long, written where the sweep already sends you.
///
/// Appended rather than printed: the picker owns the screen, and the whole point
/// is that this happens while nobody can see anything.
fn log_slow(r: &Refresh) {
    let line = format!(
        "--- {} picker refresh took {:.1}s{}{}\n",
        taimux_core::log::stamp(),
        r.took.as_secs_f32(),
        if r.spent.is_empty() { "" } else { ": " },
        r.spent
    );
    let path = taimux_core::paths::runtime_dir().join("restart.log");
    if let Some(d) = path.parent() {
        let _ = std::fs::create_dir_all(d);
    }
    if let Ok(mut f) = OpenOptions::new().create(true).append(true).open(&path) {
        let _ = f.write_all(line.as_bytes());
    }
}

impl App {
    /// Rows now, on this thread. Startup and the ended list only: everything the
    /// loop does goes through `start_refresh` instead.
    fn fetch(&mut self) {
        if self.mode == Mode::Dead {
            self.past = self.src.ended.as_ref().map(|f| f()).unwrap_or_default();
        } else {
            self.restarting = (self.src.restarting)();
            self.tsv = (self.src.fetch)();
        }
    }

    /// Ask for rows on a worker thread, leaving the loop free to draw and to
    /// read keys while the answer is on its way.
    ///
    /// The ended list is fetched inline, since it is a cache read with no fork in
    /// it and swapping it in late would mean drawing pane rows under the "ended
    /// sessions" label.
    fn start_refresh(&mut self) {
        if self.mode == Mode::Dead {
            self.fetch();
            self.rebuild();
            return;
        }
        if self.pending.is_some() {
            return;
        }
        let f = self.src.fetch.clone();
        let held = self.src.restarting.clone();
        let watch = self.src.popup;
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            taimux_core::stat::reset();
            let at = Instant::now();
            // Before the scan, not after. A restart that ends between the two
            // leaves the session's new row marked for one refresh; the other
            // way round, a row the scan held could come back unmarked.
            let restarting = held();
            let tsv = f();
            let _ = tx.send(Refresh {
                tsv,
                restarting,
                took: at.elapsed(),
                spent: taimux_core::stat::report(),
                client: watch.then(own_client).flatten(),
            });
        });
        self.pending = Some(rx);
        self.pending_since = Instant::now();
    }

    /// Take a refresh that has landed. True when the list changed, which is what
    /// tells the loop to rebuild.
    ///
    /// A thread that died without sending (a panic in the row source) drops the
    /// sender, and that arrives here as Disconnected: the refresh is simply
    /// forgotten and the next tick tries again, rather than the picker waiting
    /// on it forever.
    fn take_refresh(&mut self) -> bool {
        let Some(rx) = &self.pending else {
            return false;
        };
        match rx.try_recv() {
            Ok(r) => {
                if r.took >= slow_after() {
                    log_slow(&r);
                }
                self.client = r.client;
                // Pane rows, whichever list is on screen. One that lands under
                // the past list goes where it belongs and waits for the Tab back.
                self.tsv = r.tsv;
                self.restarting = r.restarting;
                self.pending = None;
                true
            }
            Err(TryRecvError::Empty) => false,
            Err(TryRecvError::Disconnected) => {
                self.pending = None;
                false
            }
        }
    }

    /// Ask for a remote row's screen on a worker thread, unless one is already
    /// out. The draw asks again once that one lands, for whichever row the cursor
    /// is on by then.
    fn fetch_remote(&mut self, script: &str, id: &str) {
        if self.fetching.is_some() {
            return;
        }
        let (script, which) = (script.to_string(), id.to_string());
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let text = Command::new(&script)
                .args(["preview", &which])
                .output()
                .ok()
                .filter(|o| o.status.success())
                .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
                .unwrap_or_default();
            let _ = tx.send(text);
        });
        self.fetching = Some((id.to_string(), rx));
    }

    /// Keep a remote screen that has landed. A thread that died without
    /// answering is forgotten, as a refresh is, and the next draw asks again.
    fn take_remote(&mut self) {
        let Some((id, rx)) = &self.fetching else {
            return;
        };
        match rx.try_recv() {
            Ok(text) => {
                self.remote.insert(id.clone(), (Instant::now(), text));
                self.fetching = None;
            }
            Err(TryRecvError::Empty) => {}
            Err(TryRecvError::Disconnected) => self.fetching = None,
        }
    }

    /// Has a refresh been out long enough to be worth saying so on the border?
    ///
    /// Not from the first millisecond: every tick would flicker the label on a
    /// healthy machine, where the answer is back before the next draw.
    fn refreshing(&self) -> bool {
        self.pending.is_some() && self.pending_since.elapsed() > Duration::from_secs(1)
    }

    /// The snippets the query earns in `mode`'s list, or none.
    ///
    /// **The "at least TAIMUX_SEARCH_MIN characters" gate lives here, not in the
    /// layout**, exactly as it does in bash: under three characters a term is in
    /// every transcript and a match would say nothing. Handing the layout a
    /// snippet map for a one-letter query turns every row into a search hit.
    fn snippets(&self, mode: Mode) -> HashMap<String, String> {
        if !self.searching_in(mode) || self.query.chars().count() < search_min() {
            return HashMap::new();
        }
        // Only the conversations this list can show: see `index::Scope`.
        let scope = if mode == Mode::Dead {
            index::Scope::Past
        } else {
            index::Scope::Live
        };
        index::snippets(&index::Query::new(&self.query), scope)
    }

    /// Whether typing searches what was said, for the list on screen.
    fn searching(&self) -> bool {
        self.searching_in(self.mode)
    }

    /// …and for any list: the past list has its own switch, on by default, and
    /// every other list shares one.
    fn searching_in(&self, mode: Mode) -> bool {
        if mode == Mode::Dead {
            self.search_past
        } else {
            self.search
        }
    }

    /// ctrl-t: the list on screen's own switch. The past list and the live ones
    /// default differently, so turning one off must not turn the other on.
    fn toggle_search(&mut self) {
        if self.mode == Mode::Dead {
            self.search_past = !self.search_past;
        } else {
            self.search = !self.search;
        }
        self.rebuild();
    }

    /// Whether the list on screen is in date order, newest first, rather than in
    /// its own order or ranked best match first.
    fn dated(&self) -> bool {
        self.by_date
    }

    /// Re-lay the rows out and re-apply the query, putting the cursor back on the
    /// same SESSION rather than the same index. That is what `--track --id-nth=2`
    /// buys fzf, and owning the state makes it a lookup.
    fn rebuild(&mut self) {
        let on = self.selected().map(|r| r.pane_id.clone());
        self.all = self.layout(self.mode);
        self.apply_query();
        self.sel = on
            .and_then(|id| self.view.iter().position(|&i| self.all[i].pane_id == id))
            .unwrap_or(0);
        self.clamp();
    }

    /// `mode`'s list, laid out for the query typed, before the query filters it.
    fn layout(&self, mode: Mode) -> Vec<rows::Row> {
        // The ended list is a different list, not this one filtered, so its own
        // rows are already only ended ones and asking for the filter as well
        // would be asking twice.
        let (lines, only) = if mode == Mode::Dead {
            (&self.past, "")
        } else {
            (&self.tsv, mode.filter())
        };
        rows::build(
            lines,
            &rows::Input {
                cur: &self.src.cur,
                width: self.width,
                home: &self.src.home,
                newver: &self.src.newver,
                only,
                // A row held through a restart keeps the version it had, so the
                // one you just pressed ctrl-x on stays in this list, marked ↻,
                // until it comes back on the installed one and drops out of it.
                outdated: mode == Mode::Outdated,
                // A row whose work reports back while you watch drops out at
                // the next refresh, so the list empties itself as the outdated
                // one does.
                background: mode == Mode::Background,
                // The working list takes those rows too, and loses them the same
                // way as their work reports back.
                with_background: mode == Mode::Run,
                // The one list that also holds the panes no session runs in.
                panes: mode == Mode::Panes,
                query: &self.query,
                snips: self.snippets(mode),
                // A live pane can publish no title at all: claude sets one at a
                // turn boundary, so one restored by tmux-resurrect and not
                // prompted since has nothing there.
                ptitles: index::pane_titles(),
                restarting: self.restarting.clone(),
            },
        )
    }

    /// Filter the rows in hand by the query, and recount what the past list's
    /// empty note points at.
    fn apply_query(&mut self) {
        self.view = filter(&self.all, &self.query, &self.matcher, self.dated());
        self.live_hits = self.count_live_hits();
    }

    /// How many rows the live list would keep for this query, asked only where
    /// the past list keeps none: anywhere else it would be a second layout and
    /// a second read of the index on every keystroke, for a note nobody sees.
    ///
    /// It is the live list's OWN answer, its search switch included, rather
    /// than a count of index files that hold the words, so the note never
    /// promises a row that Tab does not then show.
    fn count_live_hits(&self) -> usize {
        if self.mode != Mode::Dead || !self.view.is_empty() || self.query.trim().is_empty() {
            return 0;
        }
        filter(&self.layout(Mode::All), &self.query, &self.matcher, false).len()
    }

    /// The query changed.
    ///
    /// With text search on this is a full rebuild, not just a re-filter: a row
    /// that is in the list because of what its session SAID carries the snippet
    /// where its path would be, which is what puts the typed words ON the row so
    /// the matcher can keep working in the ordinary way. Re-filtering alone
    /// leaves the old rows in place, nothing carries the words, and every row
    /// disappears the moment you type something only a transcript holds.
    ///
    /// With search off it is only a filter, which is what makes typing into a
    /// picker you merely opened to jump as cheap as it always was.
    fn query_changed(&mut self) {
        if self.searching() {
            self.rebuild();
        } else {
            self.apply_query();
            self.clamp();
        }
    }

    /// Move to the next list, or with `back` to the one before it.
    ///
    /// Re-filtered from the rows already in hand, so the new list is on screen
    /// at once; the scan behind it lands when it lands.
    fn step_mode(&mut self, back: bool) {
        // Nothing installed to compare against and the outdated stop is not in
        // the ring at all: every row there would be judged against an empty
        // version, so the list could only ever be empty.
        let (ended, outdated) = (self.src.ended.is_some(), !self.src.newver.is_empty());
        self.mode = if back {
            self.mode.prev(ended, outdated)
        } else {
            self.mode.next(ended, outdated)
        };
        self.rebuild();
        self.start_refresh();
    }

    fn clamp(&mut self) {
        if self.view.is_empty() {
            self.sel = 0;
        } else if self.sel >= self.view.len() {
            self.sel = self.view.len() - 1;
        }
    }

    /// Drop the last word of the query, which is fzf's `unix-word-rubout` and
    /// `backward-kill-word`. The trailing space goes with it, so a query ending
    /// in one loses a whole word rather than just the gap.
    fn kill_word(&mut self) {
        while self.query.ends_with(char::is_whitespace) {
            self.query.pop();
        }
        while !self.query.is_empty() && !self.query.ends_with(char::is_whitespace) {
            self.query.pop();
        }
        self.query_changed();
    }

    /// Put the cursor on a pane, if it is in the list. Silent when it is not,
    /// which is the case where there is nothing to put it on, and `false` so the
    /// one caller that HAS somewhere else to put it can.
    fn focus(&mut self, id: &str) -> bool {
        match self.view.iter().position(|&i| self.all[i].pane_id == id) {
            Some(i) => {
                self.sel = i;
                true
            }
            None => false,
        }
    }

    /// Put the cursor on the row nearest the pane the picker was opened from,
    /// for when that pane is not an agent session and so is not a row itself.
    /// See `nearest` for what "nearest" is.
    ///
    /// Not knowing where that pane is means not knowing, so the cursor is left
    /// where the rebuild put it (the top of the list) rather than moved on a
    /// guess. That is what every entry point but `pick` gets.
    fn focus_nearest(&mut self) {
        if self.src.cur_cwd.is_empty() && self.src.cur_target.is_empty() {
            return;
        }
        let rows: Vec<&rows::Row> = self.view.iter().map(|&i| &self.all[i]).collect();
        if let Some(i) = nearest(&rows, &self.src.cur_cwd, &self.src.cur_target) {
            self.sel = i;
        }
    }

    /// Where the first scan puts the cursor: on the pane the picker was opened
    /// from, and when that pane is not an agent session at all, which is what F1
    /// from a shell is, on the row nearest to where it is.
    ///
    /// Not on the past list. A scan that lands there is one Tab was pressed
    /// ahead of, its rows are not on screen, and moving the cursor anyway is a
    /// jump through a list the scan has nothing to do with.
    fn open_on(&mut self, id: &str) {
        if self.mode != Mode::Dead && !self.focus(id) {
            self.focus_nearest();
        }
    }

    fn selected(&self) -> Option<&rows::Row> {
        self.view.get(self.sel).map(|&i| &self.all[i])
    }

    fn move_by(&mut self, d: isize) {
        if self.view.is_empty() {
            return;
        }
        let n = self.view.len() as isize;
        self.sel = (((self.sel as isize + d) % n + n) % n) as usize; // --cycle
    }

    /// A screenful, and it CLAMPS where `move_by` cycles.
    ///
    /// fzf's page-up and page-down do not cycle even under `--cycle`, and that
    /// is the right behaviour rather than an inconsistency: a page that wrapped
    /// would be unusable for what paging is for. Holding Page Down to reach the
    /// bottom of a list would sail past the end and land back at the top, and
    /// nothing on the row tells you it happened.
    ///
    /// `page` is the list's drawn height, so it follows the popup's size and the
    /// preview being open. Zero is possible on a pane too short to draw a row,
    /// and would make the key do nothing.
    fn move_page(&mut self, pages: isize, page: usize) {
        if self.view.is_empty() {
            return;
        }
        let step = page.max(1) as isize;
        let last = self.view.len() as isize - 1;
        self.sel = (self.sel as isize + pages * step).clamp(0, last) as usize;
    }
}

/// Returns the row that was chosen, an abort, or a request to be reopened at a
/// new size.
pub fn run(src: Source) -> std::io::Result<Outcome> {
    let kitty = env::var("TAIMUX_TUI_KITTY").is_some_and(|v| v == "1");
    let mut guard = Guard::new(kitty)?;
    let backend = CrosstermBackend::new(guard.out.try_clone()?);
    let mut term = Terminal::new(backend)?;

    // 0 turns the timer off, as TAIMUX_REFRESH does for the fzf picker. There is
    // no idle gate here: fzf needs one because a reload blocks its input loop and
    // swallows keystrokes, and a tick in this loop is just a redraw.
    //
    // One second, down from three on 2026-09-20. Three was inherited from the
    // bash picker, where a refresh re-execed the script and blocked fzf's input
    // loop while it did; here it runs on a thread, the rows already on screen
    // stay up while it is out, and what the interval buys is how fast a session
    // that starts waiting for you turns `✳` while you are looking at the list.
    // Measured on 35 panes a scan is 85 ms, so a second apart it is under a tenth
    // of one core, and only while a picker is open.
    //
    // Not lower, and this is the floor rather than a preference: the screen
    // capture a daemon serves is cached for 750 ms, so two refreshes closer than
    // that would be answered from one capture, and the second would report a
    // state that had already been read rather than looking again.
    let refresh: f32 = env::var("TAIMUX_REFRESH")
        .and_then(|v| v.parse().ok())
        .unwrap_or(1.0);
    let live = refresh > 0.0;

    let mut app = App {
        // Not `smart_case`, which is fzf's default and was this picker's: see
        // `index::Query`. The two matchers have to agree about what a capital
        // means, and the answer both give now is "nothing".
        matcher: SkimMatcherV2::default().ignore_case(),
        mode: Mode::All,
        search: false,
        search_past: false,
        by_date: false,
        preview: true,
        query: String::new(),
        width: row_width(term.size()?.width),
        tsv: String::new(),
        past: String::new(),
        all: Vec::new(),
        view: Vec::new(),
        sel: 0,
        shot: None,
        remote: HashMap::new(),
        fetching: None,
        poff: 0,
        poff_for: String::new(),
        pending: None,
        pending_since: Instant::now(),
        client: None,
        restarting: HashSet::new(),
        live_hits: 0,
        src,
    };
    // Whatever a previous instance was doing when the terminal grew under it.
    // Default-empty otherwise, which is an ordinary open.
    app.query = std::mem::take(&mut app.src.state.query);
    app.mode = Mode::from_key(app.src.state.mode);
    // Only where there is a search to switch on. TAIMUX_SEARCH=0 takes ctrl-t and
    // the index away together, and the border must not then claim a ⌕ that has
    // nothing behind it.
    app.search = app.src.state.search && search_enabled();
    app.search_past = app.src.state.search_past && search_enabled();
    app.by_date = app.src.state.by_date;
    app.preview = app.src.state.preview;
    // Even the FIRST scan runs off the loop. It used to be synchronous, on the
    // reasoning that there is nothing to draw until it lands, and what that
    // produced was a POPUP WITH NOTHING IN IT for as long as the scan took:
    // reported as another stuck picker, an empty box over a session, no keys.
    // There is something to draw, and it is "looking for them".
    //
    // An empty answer used to close the picker too. It says one thing, and it is
    // the thing you need: F1 on a machine with no agent sessions was
    // indistinguishable from F1 not being bound, from taimux not being
    // installed, and from the popup failing to start.
    app.start_refresh();
    // The cursor opens on the pane the picker was opened from, which is the row
    // marked ●, and on the row nearest to that pane when it is not an agent
    // session and so has no row of its own (see `nearest`). After a reopen it
    // goes back where it was instead, since that is the row you were looking at
    // when the terminal changed shape under you. Applied when the rows arrive,
    // since there is nothing to put it on before that.
    let opening_on = if app.src.state.on.is_empty() {
        app.src.cur.clone()
    } else {
        app.src.state.on.clone()
    };
    let mut opened = false;

    let mut state = ListState::default();
    let mut chosen: Option<String> = None;
    // Set when the terminal has grown past what this popup can use.
    let mut outgrew = false;
    let mut ticked = Instant::now();
    // How tall the list came out, written by the draw below and read by Page
    // Up / Page Down. Taken from the drawn area rather than recomputed from the
    // terminal size, because the layout it would have to reproduce (a border,
    // two fixed lines, and a preview that takes 60% only when there is room for
    // it) is exactly the sort of arithmetic that drifts from the real thing.
    let mut page: usize = 1;
    // Where the list starts on screen, for turning a click's row into a row of
    // the list. Same reasoning as `page`: measured, not recomputed.
    let mut list_y: u16 = 0;
    // The last left click, so a second one on the same row reads as a
    // double-click. crossterm reports presses, never double-clicks, so the only
    // way to have the gesture fzf had is to time it.
    let mut clicked: Option<(u16, Instant)> = None;

    loop {
        state.select(if app.view.is_empty() {
            None
        } else {
            Some(app.sel)
        });
        term.draw(|f| {
            let count = format!(" {}/{} ", app.view.len(), app.all.len());
            let mut block = Block::bordered()
                .title(label(
                    app.mode,
                    app.dated(),
                    live,
                    app.searching(),
                    app.refreshing(),
                ))
                .title_bottom(Line::from(count.clone()));
            // Dim, and in the corner furthest from the cursor: it is reference,
            // read once after an update and never again, so it must not compete
            // with the count beside it or the list above.
            if room_for_tag(f.area().width, &count) {
                block = block.title_bottom(
                    Line::from(Span::styled(
                        version_tag(),
                        Style::default().fg(Color::DarkGray),
                    ))
                    .right_aligned(),
                );
            }
            let inner = block.inner(f.area());
            f.render_widget(block, f.area());

            let [prompt, head, body] = Layout::vertical([
                Constraint::Length(1),
                Constraint::Length(1),
                Constraint::Min(1),
            ])
            .areas(inner);

            f.render_widget(
                Paragraph::new(Line::from(vec![
                    Span::styled("pick ❯ ", Style::default().fg(Color::Cyan)),
                    Span::raw(app.query.clone()),
                ])),
                prompt,
            );
            f.render_widget(
                Paragraph::new(Line::from(Span::styled(
                    header(
                        app.src.script.is_some(),
                        app.src.ended.is_some(),
                        search_enabled(),
                        app.searching(),
                        app.dated(),
                    ),
                    Style::default().fg(Color::DarkGray),
                ))),
                head,
            );

            // The preview takes the bottom 60%, as --preview-window=down,60% does.
            let (body, prev) = if app.preview && body.height >= 8 {
                let [a, b] =
                    Layout::vertical([Constraint::Percentage(40), Constraint::Percentage(60)])
                        .areas(body);
                (a, Some(b))
            } else {
                (body, None)
            };
            page = body.height as usize;
            list_y = body.y;

            let items: Vec<ListItem> = app
                .view
                .iter()
                .map(|&i| {
                    ListItem::new(Line::from(
                        app.all[i]
                            .cells
                            .iter()
                            .map(|c| Span::styled(c.text.clone(), c.paint.style()))
                            .collect::<Vec<_>>(),
                    ))
                })
                .collect();
            if app.view.is_empty() {
                // Where the rows would be, in the same place your eye already
                // is, rather than a line tucked under the header.
                f.render_widget(
                    Paragraph::new(empty_note(
                        app.mode,
                        &app.query,
                        // Nothing has come back yet, which is not the same as
                        // nothing being there.
                        !opened,
                        // The RAW scan, not the laid-out rows: those already
                        // have the mode filter applied, so one idle session
                        // viewed through the waiting list read as a machine
                        // with nothing running on it at all.
                        no_sessions(&app.tsv),
                        app.src.ended.is_some(),
                        search_enabled() && !app.searching(),
                        app.live_hits,
                    ))
                    .style(Style::default().fg(Color::DarkGray))
                    .wrap(Wrap { trim: false }),
                    body,
                );
            } else {
                f.render_stateful_widget(
                    List::new(items)
                        .highlight_symbol("▶ ")
                        .highlight_style(Style::default().add_modifier(Modifier::REVERSED)),
                    body,
                    &mut state,
                );
            }

            if let Some(area) = prev {
                let block = Block::default()
                    .borders(Borders::TOP)
                    .border_style(Style::default().fg(Color::DarkGray));
                let inner = block.inner(area);
                f.render_widget(block, area);
                let (head, text, at_bottom) = app.preview();
                // The header stays put and the body scrolls under it. Pinning it
                // is the whole reason the two are built separately: it says
                // WHICH session this is, and scrolling that off the top would
                // leave a screenful of text belonging to nothing in particular.
                let hh = (head.len() as u16).min(inner.height);
                let [hrect, brect] =
                    Layout::vertical([Constraint::Length(hh), Constraint::Min(0)]).areas(inner);
                f.render_widget(Paragraph::new(head).wrap(Wrap { trim: false }), hrect);

                // Where the window sits in the body. `poff` is rows away from
                // the default view, negative towards the start, and the clamp is
                // what lets one offset mean the same thing for a live pane
                // (anchored at the bottom) and an ended conversation (anchored
                // at the top): at either extreme it simply stops.
                //
                // The body is NOT wrapped, and that is what makes the arithmetic
                // exact. `Paragraph::scroll` counts WRAPPED rows while this
                // counts lines, so with wrapping on a capture padded to a wider
                // pane every line became two rows: each keypress moved half a
                // line and the clamp stopped a third of the way up. Unwrapped, a
                // line is a row. It also suits what this is, a viewport onto a
                // pane: a line too long for the preview reads better clipped
                // than re-flowed, since that is what the pane looks like. The
                // header keeps its wrap, being prose.
                let most = text.len().saturating_sub(brect.height as usize) as i32;
                let base = if at_bottom { most } else { 0 };
                let start = (base + app.poff).clamp(0, most.max(0));
                // Write the clamped offset BACK, or it accumulates past the end
                // of the body: hold shift-up at the top for a second and coming
                // back down takes as many presses as went in, with nothing on
                // screen moving for any of them. The limits are only known here,
                // where the body and the area both are, which is why the field
                // cannot clamp itself.
                app.poff = start - base;
                f.render_widget(Paragraph::new(text).scroll((start as u16, 0)), brect);
            }
        })?;

        // A refresh that has landed is taken here, between two draws, so the
        // rebuild it costs is the only work the loop ever does off the input
        // path. The ASK for one is free: it hands the row source to a thread.
        if app.take_refresh() {
            app.rebuild();
            if !opened {
                opened = true;
                app.open_on(&opening_on);
            }
            // The terminal has grown past what this popup was asked for, and
            // tmux will not grow a popup on its own. Leaving the loop is how the
            // picker asks to be reopened: the popup closes with it, and what it
            // was doing goes out in the Outcome.
            if let Some((_, size)) = app.client.clone() {
                if resize_enabled() && outgrown(term.size().map(|s| (s.width, s.height))?, size, 2)
                {
                    outgrew = true;
                    break;
                }
            }
        }
        if live && ticked.elapsed().as_secs_f32() >= refresh {
            ticked = Instant::now();
            app.start_refresh();
        }
        // Sooner while a remote screen is out, since nothing else wakes the loop
        // to draw it: the 120 ms would be more than the ssh it is waiting on.
        let wait = if app.fetching.is_some() { 20 } else { 120 };
        if !event::poll(Duration::from_millis(wait))? {
            continue;
        }
        match event::read()? {
            // One event, carrying its own text, with no way to mistake it for
            // Enter. A pasted line break arrives as CR, so both are split on.
            Event::Paste(text) => {
                let first = text.split(['\r', '\n']).next().unwrap_or_default();
                app.query.push_str(first);
                app.query_changed();
            }
            // The wheel is the arrow keys, and a click is the cursor, which is
            // what fzf's default mouse handling did. Restored because the port
            // simply never asked the terminal for mouse events.
            Event::Mouse(MouseEvent { kind, row: my, .. }) => match kind {
                // Wrapping, because these ARE Up and Down: a wheel that stopped
                // where the arrow key it stands in for cycles would be the odd
                // one out. Over the preview too, since that pane has no scroll
                // of its own to offer instead.
                MouseEventKind::ScrollUp => app.move_by(-1),
                MouseEventKind::ScrollDown => app.move_by(1),
                // A click at or below where the list starts. Above it is the
                // prompt or the header, which are not rows.
                MouseEventKind::Down(MouseButton::Left) if my >= list_y => {
                    // Which row was under the pointer. `offset` is what the List
                    // widget has scrolled to, so this stays right on a list
                    // longer than the window, and a click past the last row
                    // lands on nothing rather than off the end.
                    let i = state.offset() + (my - list_y) as usize;
                    if i < app.view.len() {
                        app.sel = i;
                        // A second click on the row already under the cursor,
                        // soon enough, accepts it. fzf's double-click, with the
                        // clock this has to keep because crossterm reports
                        // presses and never the gesture.
                        let again =
                            clicked.is_some_and(|(r, t)| r == my && t.elapsed() < DOUBLE_CLICK);
                        clicked = Some((my, Instant::now()));
                        if again {
                            if let Some(r) = app.selected() {
                                chosen = Some(r.pane_id.clone());
                            }
                            break;
                        }
                    }
                }
                _ => {}
            },
            Event::Resize(w, _) => {
                app.width = row_width(w);
                app.rebuild();
            }
            Event::Key(k) => {
                // A terminal with the kitty flags pushed reports releases too, and
                // acting on both double-counts every key.
                if k.kind != KeyEventKind::Press {
                    continue;
                }
                let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);
                let alt = k.modifiers.contains(KeyModifiers::ALT);
                let shift = k.modifiers.contains(KeyModifiers::SHIFT);
                match k.code {
                    // fzf aborts on all four of these, and abort is the one
                    // action worth having several ways to reach.
                    KeyCode::Esc => break,
                    KeyCode::Char('c') | KeyCode::Char('g') | KeyCode::Char('q') if ctrl => break,
                    KeyCode::Enter => {
                        if let Some(r) = app.selected() {
                            chosen = Some(r.pane_id.clone());
                        }
                        break;
                    }
                    // Scroll the PREVIEW, not the list, which is what fzf points
                    // these at. A live pane's preview opens on the bottom of its
                    // screen, so shift-up is how you see what came before it; an
                    // ended conversation opens at the top, so shift-down is how
                    // you read forwards through it. The offset is clamped at both
                    // ends of the body and reset whenever the cursor moves.
                    KeyCode::Up if shift => app.poff -= 1,
                    KeyCode::Down if shift => app.poff += 1,
                    KeyCode::Down => app.move_by(1),
                    KeyCode::Up => app.move_by(-1),
                    // Both pairs, as fzf binds both. ctrl-j is safe to take
                    // here: a terminal sends LF for it and CR for Enter, and
                    // crossterm keeps them apart, so this does not shadow
                    // accept. Checked rather than assumed.
                    KeyCode::Char('n') | KeyCode::Char('j') if ctrl => app.move_by(1),
                    KeyCode::Char('p') | KeyCode::Char('k') if ctrl => app.move_by(-1),
                    // The ends of the LIST. fzf points these at the ends of the
                    // QUERY by default, which in a picker you rarely type into is
                    // a key that visibly does nothing at all.
                    KeyCode::Home => app.sel = 0,
                    KeyCode::End => app.sel = app.view.len().saturating_sub(1),
                    // A screenful, by the height the list was actually drawn at,
                    // so it tracks the popup's size and whether the preview is
                    // open. fzf bound these itself and the port simply dropped
                    // them: Home and End were ported and these were not, which is
                    // why one pair kept working and the other went quiet.
                    KeyCode::PageDown => app.move_page(1, page),
                    KeyCode::PageUp => app.move_page(-1, page),
                    // Shift-tab walks the ring the other way. A terminal sends
                    // it as BackTab, and one with the kitty flags pushed sends
                    // Tab carrying SHIFT instead, so both are taken. BackTab is
                    // matched on its own rather than or-ed into the guarded arm
                    // below, because the modifier it arrives with is the part
                    // that differs between terminals and the key is not.
                    KeyCode::BackTab => app.step_mode(true),
                    KeyCode::Tab if shift => app.step_mode(true),
                    KeyCode::Tab => app.step_mode(false),
                    KeyCode::Char('r') if ctrl => app.start_refresh(),
                    // Nothing is bound when search is turned off, and the
                    // picker then behaves exactly as it did before there was any.
                    KeyCode::Char('t') if ctrl && search_enabled() => app.toggle_search(),
                    // By date: newest first by when each session last said
                    // something, the rows that say what was typed ahead of the
                    // loose matches (see `filter`). Bound on every list, and a
                    // rebuild rather than a re-filter so the cursor stays on the
                    // session it was on: a second press then lands exactly where
                    // the first one started. It arrives as a key and not as XOFF,
                    // since raw mode turns flow control off.
                    KeyCode::Char('s') if ctrl => {
                        app.by_date = !app.by_date;
                        app.rebuild();
                    }
                    // ctrl-/ reaches a terminal as several different bytes, so
                    // all of them are taken rather than one.
                    KeyCode::Char('/') | KeyCode::Char('_') | KeyCode::Char('\u{1f}') if ctrl => {
                        app.preview = !app.preview;
                    }
                    KeyCode::Char('u') if ctrl => {
                        app.query.clear();
                        app.query_changed();
                    }
                    // A word back, which fzf gives both of these. Worth having
                    // even though the query has no cursor: deleting the last
                    // word of "claude renovate" is a thing you want, and the
                    // alternative is holding backspace.
                    KeyCode::Char('w') if ctrl => app.kill_word(),
                    // Before the bare Backspace below, or alt-backspace would
                    // take a single character. It took one until now: the arm
                    // ignored modifiers, so fzf's backward-kill-word quietly
                    // behaved as plain backspace.
                    KeyCode::Backspace if alt => app.kill_word(),
                    // ctrl-h is backspace as far as fzf is concerned, and some
                    // terminals send it for the key. It needs naming separately
                    // because it arrives as a ctrl-char, not as Backspace.
                    KeyCode::Backspace => {
                        app.query.pop();
                        app.query_changed();
                    }
                    KeyCode::Char('h') if ctrl => {
                        app.query.pop();
                        app.query_changed();
                    }
                    // A full repaint, for a screen something else has written
                    // over. Every loop redraws already, so this only has to
                    // throw away what ratatui thinks is on the terminal.
                    //
                    // `resize` and NOT `Terminal::clear`, which would be the
                    // obvious call and is a trap here: it snapshots the cursor
                    // first, and the crossterm backend does that with
                    // `crossterm::cursor::position()`, which writes ESC[6n to
                    // the PROCESS's stdout rather than to the backend's writer.
                    // Stdout carries exactly one thing in this program, the
                    // chosen pane id, so ctrl-l put `[6n` where the caller reads
                    // the answer. Measured, not theorised.
                    //
                    // resize() on a fullscreen viewport takes the same path
                    // minus that snapshot: it clears through the backend's own
                    // writer and resets the back buffer, so the next draw
                    // repaints in full.
                    KeyCode::Char('l') if ctrl => repaint(&mut term),
                    // The two keys that act rather than navigate. They run the
                    // script the way fzf's execute() does: hand the terminal over,
                    // let the child own it, take it back.
                    KeyCode::Char('x') if ctrl => {
                        if let (Some(s), Some(r)) = (app.src.script.clone(), app.selected()) {
                            let id = r.pane_id.clone();
                            // Nothing to hold here: the restart writes the row
                            // down before its first keystroke and every scan
                            // lists it from there until the session is back,
                            // marked ↻. See `restarting` in core.
                            guard.suspend();
                            if let Err(e) = act_child(&s, &["_restart", &id]) {
                                crate::act::report_failed_child("the restart", &e);
                            }
                            guard.resume();
                            repaint(&mut term);
                            // Rebuilt from the rows already in hand and drawn on
                            // the next pass, so the list is back on screen at
                            // once. Asking for fresh rows here and WAITING for
                            // them is what left the picker showing the child's
                            // last screen, unable to draw or read a key, for as
                            // long as the scan took.
                            app.rebuild();
                            app.start_refresh();
                            // …and the cursor goes back on it explicitly, which
                            // the rebuild only does when it can re-pin the row
                            // it was on, so a press that did nothing never
                            // leaves the cursor somewhere else.
                            app.focus(&id);
                        }
                    }
                    // ctrl-o: carry this conversation into a different agent.
                    // Same shape as ctrl-x, and for the same reason: it draws a
                    // menu, waits on a key and then opens a window, none of
                    // which the picker's own loop can do while it is drawing.
                    KeyCode::Char('o') if ctrl => {
                        if let (Some(s), Some(r)) = (app.src.script.clone(), app.selected()) {
                            let id = r.pane_id.clone();
                            guard.suspend();
                            if let Err(e) = act_child(&s, &["_handoff", &id]) {
                                crate::act::report_failed_child("the handoff", &e);
                            }
                            guard.resume();
                            repaint(&mut term);
                            // Nothing in the list changed: a handoff opens a NEW
                            // window and leaves the conversation it came from
                            // exactly where it was. So the cursor goes straight
                            // back on the row rather than the list being rebuilt.
                            app.focus(&id);
                        }
                    }
                    KeyCode::F(8) => {
                        if let Some(s) = app.src.script.clone() {
                            guard.suspend();
                            if let Err(e) = act_child(&s, &["_sweep"]) {
                                crate::act::report_failed_child("the sweep", &e);
                            }
                            guard.resume();
                            repaint(&mut term);
                            // Same as ctrl-x, and this is the press it was
                            // REPORTED on: a sweep restarts every outdated
                            // session at once, so the scan that follows it is the
                            // slowest one the picker ever runs.
                            app.rebuild();
                            app.start_refresh();
                        }
                    }
                    // Anything else printable joins the query. `!alt` matters as
                    // much as `!ctrl` and was missing: ALT is not CTRL, so every
                    // alt-chord fell in here and TYPED ITS LETTER. Holding alt
                    // and pressing b put a "b" in the query, which is fzf's
                    // backward-word, and any stray chord the terminal passed
                    // through corrupted the search with no way to tell.
                    KeyCode::Char(c) if !ctrl && !alt => {
                        app.query.push(c);
                        app.query_changed();
                    }
                    _ => {}
                }
            }
            _ => {}
        }
    }

    drop(term);
    drop(guard);
    Ok(match (chosen, outgrew) {
        (Some(id), _) => Outcome::Chosen(id),
        (None, true) => Outcome::Resize(State {
            query: app.query.clone(),
            mode: app.mode.key(),
            search: app.search,
            search_past: app.search_past,
            by_date: app.by_date,
            preview: app.preview,
            on: app
                .selected()
                .map(|r| r.pane_id.clone())
                .unwrap_or_default(),
            client: app.client.clone().map(|(tty, _)| tty).unwrap_or_default(),
        }),
        (None, false) => Outcome::Aborted,
    })
}

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

    fn src(tsv: &str) -> Source {
        let t = tsv.to_string();
        Source {
            fetch: Arc::new(move || t.clone()),
            restarting: Arc::new(HashSet::new),
            ended: None,
            cur: String::new(),
            cur_cwd: String::new(),
            cur_target: String::new(),
            home: "/h".into(),
            newver: String::new(),
            script: None,
            popup: false,
            state: Default::default(),
        }
    }

    fn app(tsv: &str) -> App {
        let mut a = App {
            src: src(tsv),
            matcher: SkimMatcherV2::default().ignore_case(),
            mode: Mode::All,
            search: false,
            search_past: false,
            by_date: false,
            preview: true,
            query: String::new(),
            width: 100,
            tsv: String::new(),
            past: String::new(),
            all: Vec::new(),
            view: Vec::new(),
            sel: 0,
            shot: None,
            remote: HashMap::new(),
            fetching: None,
            poff: 0,
            poff_for: String::new(),
            pending: None,
            pending_since: Instant::now(),
            client: None,
            restarting: HashSet::new(),
            live_hits: 0,
        };
        a.fetch();
        a.rebuild();
        a
    }

    fn ids(a: &App) -> Vec<String> {
        a.view.iter().map(|&i| a.all[i].pane_id.clone()).collect()
    }

    /// The marker column says a restart is in flight. It goes there and not into
    /// the summary because the summary strips a leading marker glyph.
    ///
    /// The row itself is the scan's: a restart writes it down before its first
    /// keystroke and the scan lists it from there (see `restarting` in core), so
    /// all the picker adds is which rows those are.
    #[test]
    fn a_row_with_a_restart_in_flight_is_marked() {
        let mut a = app(THREE);
        a.src.restarting = Arc::new(|| HashSet::from(["%2".to_string()]));
        a.fetch();
        a.rebuild();
        let text = |id: &str| a.all.iter().find(|r| r.pane_id == id).unwrap().to_ansi();
        assert!(
            text("%2").contains('↻'),
            "expected the restart marker in {:?}",
            text("%2")
        );
        // …and it does not borrow the waiting star, which means something else
        assert!(!text("%2").contains('✳'), "must not read as asking");
        assert!(!text("%1").contains('↻'), "only the row being restarted");
    }

    /// The mark comes and goes with the scan it was read beside, on the worker
    /// thread every refresh but the first runs on, so it is gone the moment the
    /// restart is over rather than lingering on a session already back.
    #[test]
    fn the_mark_rides_each_refresh_and_goes_with_the_restart() {
        let held = Arc::new(std::sync::Mutex::new(HashSet::from(["%2".to_string()])));
        let mut a = app(THREE);
        let h = held.clone();
        a.src.restarting = Arc::new(move || h.lock().unwrap().clone());
        let refresh = |a: &mut App| {
            a.start_refresh();
            for _ in 0..100 {
                if a.take_refresh() {
                    a.rebuild();
                    return;
                }
                std::thread::sleep(Duration::from_millis(10));
            }
            panic!("the refresh never arrived");
        };
        let marked = |a: &App| a.all.iter().any(|r| r.to_ansi().contains('↻'));

        refresh(&mut a);
        assert!(marked(&a), "in flight");
        held.lock().unwrap().clear();
        refresh(&mut a);
        assert!(!marked(&a), "over");
        assert_eq!(ids(&a), ["%1", "%2", "%3"]);
    }

    /// The bug this is all for: the picker used to call the row source from its
    /// input loop, so a scan that took 85 seconds after an F8 sweep was 85
    /// seconds with no draw and no key. Asking must return AT ONCE.
    #[test]
    fn asking_for_a_refresh_does_not_wait_for_it() {
        let mut a = app(THREE);
        a.src.fetch = Arc::new(|| {
            std::thread::sleep(Duration::from_millis(400));
            "%9\tz:1.1\t/h\tclaude\t1\tidle\t-\tlate arrival".to_string()
        });
        let at = Instant::now();
        a.start_refresh();
        assert!(
            at.elapsed() < Duration::from_millis(100),
            "start_refresh blocked for {:?}",
            at.elapsed()
        );
        assert!(!a.take_refresh(), "nothing has landed yet");
        assert_eq!(a.all.len(), 3, "and the old rows are still there to draw");

        // …and it lands later, without anything having waited on it.
        let mut got = false;
        for _ in 0..100 {
            if a.take_refresh() {
                got = true;
                break;
            }
            std::thread::sleep(Duration::from_millis(20));
        }
        assert!(got, "the refresh never arrived");
        a.rebuild();
        assert_eq!(ids(&a), ["%9"]);
    }

    /// One at a time. The timer must not stack refreshes on a machine where they
    /// take longer than the interval, which is the machine this matters on.
    #[test]
    fn a_second_refresh_is_not_started_while_one_is_out() {
        let mut a = app(THREE);
        let runs = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let r = runs.clone();
        a.src.fetch = Arc::new(move || {
            r.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            std::thread::sleep(Duration::from_millis(300));
            String::new()
        });
        a.start_refresh();
        a.start_refresh();
        a.start_refresh();
        std::thread::sleep(Duration::from_millis(500));
        assert_eq!(runs.load(std::sync::atomic::Ordering::SeqCst), 1);
    }

    /// A row source that panics drops its sender rather than answering. The
    /// picker has to forget that refresh and carry on, not wait on it forever.
    #[test]
    fn a_refresh_that_never_answers_is_forgotten() {
        let mut a = app(THREE);
        a.src.fetch = Arc::new(|| panic!("the scan blew up"));
        a.start_refresh();
        for _ in 0..100 {
            if a.pending.is_none() {
                break;
            }
            let _ = a.take_refresh();
            std::thread::sleep(Duration::from_millis(20));
        }
        assert!(a.pending.is_none(), "still waiting on a dead thread");
        assert_eq!(a.all.len(), 3, "and the list it had is untouched");
    }

    fn body_text(a: &mut App) -> String {
        let (_, body, _) = a.preview();
        body.iter()
            .map(|l| {
                l.spans
                    .iter()
                    .map(|s| s.content.as_ref())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// A remote row's screen is an ssh, and it used to be fetched inside the
    /// draw: every cursor landing on a remote row held the keys for a round
    /// trip. The draw now only shows what has come back, a fast scroll asks
    /// for one screen rather than one per row passed over, and the row the
    /// cursor stops on is the one asked next.
    #[test]
    fn a_remote_preview_never_holds_up_the_draw() {
        let d = std::env::temp_dir().join(format!("taimux-tui-remote-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&d);
        std::fs::create_dir_all(&d).unwrap();
        let script = d.join("taimux");
        std::fs::write(
            &script,
            format!(
                "#!/bin/sh\necho \"$2\" >> {}\nsleep 0.3\necho \"screen of $2\"\n",
                d.join("asked").display()
            ),
        )
        .unwrap();
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
        }
        let mut a = app("ha:%1\tw:1.1\t/h/a\tclaude\t1\tidle\t-\tone\n\
                         ha:%2\tw:1.2\t/h/b\tclaude\t1\tidle\t-\ttwo\n\
                         ha:%3\tw:1.3\t/h/c\tclaude\t1\tidle\t-\tthree");
        a.src.script = Some(script.display().to_string());
        let asked = || std::fs::read_to_string(d.join("asked")).unwrap_or_default();

        let at = Instant::now();
        assert_eq!(body_text(&mut a), "asking ha…");
        a.move_by(1);
        assert_eq!(body_text(&mut a), "asking ha…");
        a.move_by(1);
        assert_eq!(body_text(&mut a), "asking ha…");
        assert!(
            at.elapsed() < Duration::from_millis(200),
            "three draws over remote rows took {:?}",
            at.elapsed()
        );

        let wait_for = |a: &mut App, want: &str| {
            for _ in 0..100 {
                let b = body_text(a);
                if b == want {
                    return;
                }
                std::thread::sleep(Duration::from_millis(20));
            }
            panic!("never showed {:?}", want);
        };
        wait_for(&mut a, "screen of ha:%3");
        assert_eq!(asked(), "ha:%1\nha:%3\n", "%2 was only passed over");

        // Back over a row already fetched shows it straight away.
        a.move_by(-2);
        assert_eq!(body_text(&mut a), "screen of ha:%1");
        let _ = std::fs::remove_dir_all(&d);
    }

    /// The border says so, but only once it has been a second: on a healthy
    /// machine the answer is back before the next draw, and a label that flashed
    /// every tick would be noise about nothing.
    #[test]
    fn the_border_says_refreshing_only_when_it_is_worth_saying() {
        let mut a = app(THREE);
        a.src.fetch = Arc::new(|| {
            std::thread::sleep(Duration::from_millis(1500));
            String::new()
        });
        a.start_refresh();
        assert!(!a.refreshing(), "not from the first millisecond");
        a.pending_since = Instant::now() - Duration::from_secs(2);
        assert!(a.refreshing());
        assert_eq!(
            label(Mode::All, false, true, false, true),
            " agent sessions · live · refreshing "
        );
    }

    /// The picker used to CLOSE itself when the list came out empty, and that
    /// is what was reported as "F1 no longer works": on a machine with no agent
    /// sessions the popup opened and closed too fast to see, which looks exactly
    /// like an unbound key, a missing binary, or a popup that failed to start.
    /// The four silences mean different things and it now says which.
    #[test]
    fn an_empty_list_says_which_kind_of_empty_it_is() {
        let text = |ls: Vec<Line<'static>>| -> String {
            ls.iter()
                .map(|l| {
                    l.spans
                        .iter()
                        .map(|s| s.content.to_string())
                        .collect::<String>()
                })
                .collect::<Vec<_>>()
                .join("\n")
        };

        // nothing running at all, which is the reported case
        let none = text(empty_note(Mode::All, "", false, true, false, false, 0));
        assert!(none.contains("No agent sessions on this machine"), "{none}");
        assert!(none.contains("Esc closes this"), "{none}");
        // …and with an ended list to offer, it offers it
        let none_ended = text(empty_note(Mode::All, "", false, true, true, false, 0));
        assert!(none_ended.contains("Tab reaches the conversations that ended"));

        // something IS running, just not in this state
        let filtered = text(empty_note(Mode::Input, "", false, false, true, false, 0));
        assert!(
            filtered.contains("Nothing is waiting for an answer right now"),
            "{filtered}"
        );
        assert!(!filtered.contains("No agent sessions"), "{filtered}");

        // a query nobody matches, which says what to press to undo it
        let q = text(empty_note(Mode::All, "zzz", false, false, true, false, 0));
        assert!(q.contains("Nothing matches zzz"), "{q}");
        assert!(q.contains("ctrl-u"), "{q}");
        assert!(!q.contains("ctrl-t"), "no search to offer: {q}");
        assert!(!q.contains("still open"), "no live hit to point at: {q}");
        // …and names ctrl-t when what was said is not being searched but could
        // be, which is where a pasted URL used to find nothing and say nothing
        let hint = text(empty_note(
            Mode::Dead,
            "https://x/273",
            false,
            false,
            true,
            true,
            0,
        ));
        assert!(
            hint.contains("ctrl-t searches what was said in them too"),
            "{hint}"
        );
        // …and points at the live list when the match is a session still open
        // in a pane, which the past list leaves out
        let one = text(empty_note(
            Mode::Dead,
            "https://x/13",
            false,
            false,
            true,
            false,
            1,
        ));
        assert!(
            one.contains("A session still open in a pane matches it: Tab shows it."),
            "{one}"
        );
        assert!(one.contains("ctrl-u"), "{one}");
        let two = text(empty_note(
            Mode::Dead,
            "https://x/13",
            false,
            false,
            true,
            false,
            2,
        ));
        assert!(
            two.contains("2 sessions still open in panes match it: Tab shows them."),
            "{two}"
        );

        // the ended list, before anything has ended
        let dead = text(empty_note(Mode::Dead, "", false, false, true, false, 0));
        assert!(
            dead.contains("No past conversations have been found here yet"),
            "{dead}"
        );

        // …and before the first scan has come back at all, which is the state a
        // popup used to show as an empty box. It outranks every other case,
        // because none of them is known yet.
        let scanning = text(empty_note(Mode::All, "", true, true, true, false, 0));
        assert!(
            scanning.contains("Looking for agent sessions"),
            "{scanning}"
        );
        assert!(!scanning.contains("No agent sessions"), "{scanning}");
        let scanning_q = text(empty_note(Mode::Input, "zzz", true, false, true, false, 0));
        assert!(
            scanning_q.contains("Looking for agent sessions"),
            "{scanning_q}"
        );
    }

    /// The default state is an ORDINARY open, which above all means the preview
    /// is ON. Deriving Default gave `preview: false` and every picker opened
    /// with it hidden; the tell was the page keys moving twice as far, since the
    /// list had the preview's half of the window too.
    #[test]
    fn the_default_state_is_an_ordinary_open() {
        let d = State::default();
        assert!(d.preview);
        // every list searches what was said from the start
        assert!(d.search);
        assert!(d.search_past);
        assert!(!d.by_date);
        assert_eq!(Mode::from_key(d.mode), Mode::All);
        assert!(d.query.is_empty() && d.on.is_empty());
    }

    /// tmux shrinks a popup to fit a client that got smaller and grows it back
    /// up to the size it was ASKED for, so the only case the picker has to act
    /// on is a terminal that grew past that. Both directions were measured
    /// before this was written; these are the numbers that came back.
    #[test]
    fn only_a_terminal_that_grew_past_the_popup_counts() {
        // opened at 160x50, so 80% is 128x40 and the usable area 126x38
        assert!(
            !outgrown((126, 38), (160, 50), 2),
            "the size it was opened at is not a reason to reopen"
        );
        // the client grew to 200x60: 80% of that is 160x48, well past 126x38
        assert!(outgrown((126, 38), (200, 60), 2));
        // …and the same popup on a client that SHRANK is tmux's business, not
        // ours: it has already clamped the popup to fit.
        assert!(!outgrown((58, 18), (60, 20), 2));
    }

    /// A column or two of rounding must not close and reopen the popup, and the
    /// rule switches at 100 columns, so a phone rotating between portrait and
    /// landscape crosses it in both directions.
    #[test]
    fn the_slack_stops_a_reopen_over_rounding() {
        // 80 columns is "small", so the popup is 100% wide: 78 usable
        assert!(!outgrown((78, 19), (80, 24), 2));
        // one column of growth is not worth a flicker
        assert!(!outgrown((78, 19), (81, 24), 2));
        // portrait to landscape: 80 -> 140 crosses the rule, 80% of 140 is 112
        assert!(outgrown((78, 19), (140, 40), 2));
    }

    /// What a resize carries over. Losing the query or the cursor to a rotation
    /// would make the reopen worse than the stuck popup it replaces.
    #[test]
    fn a_resize_hands_over_what_the_picker_was_doing() {
        let mut a = app(THREE);
        a.query = "banana".into();
        a.mode = Mode::Run;
        a.search = true;
        a.by_date = true;
        a.preview = false;
        a.query_changed();
        let state = State {
            query: a.query.clone(),
            mode: a.mode.key(),
            search: a.search,
            search_past: a.search_past,
            by_date: a.by_date,
            preview: a.preview,
            on: a.selected().map(|r| r.pane_id.clone()).unwrap_or_default(),
            // The client the popup was on, which the reopen must target rather
            // than asking tmux which one is "current".
            client: "/dev/pts/7".into(),
        };
        assert_eq!(
            state,
            State {
                query: "banana".into(),
                mode: "run",
                search: true,
                search_past: false,
                by_date: true,
                preview: false,
                on: "%2".into(),
                client: "/dev/pts/7".into(),
            }
        );
        // …and it comes back as the same picker on the other side
        assert_eq!(Mode::from_key(state.mode), Mode::Run);
        assert_eq!(Mode::from_key("outdated"), Mode::Outdated);
        assert_eq!(Mode::from_key("background"), Mode::Background);
        assert_eq!(Mode::from_key(""), Mode::All);
    }

    /// focus() is what covers a REFUSED restart: nothing is held, so the rebuild
    /// has nothing to re-pin to, and without it the cursor fell to the top on
    /// exactly the presses that did nothing.
    #[test]
    fn focus_puts_the_cursor_back_and_is_silent_when_it_cannot() {
        let mut a = app(THREE);
        a.sel = 0;
        assert!(a.focus("%3"));
        assert_eq!(a.selected().map(|r| r.pane_id.as_str()), Some("%3"));
        assert!(!a.focus("%404"));
        assert_eq!(
            a.selected().map(|r| r.pane_id.as_str()),
            Some("%3"),
            "a pane that is not listed leaves the cursor alone"
        );
    }

    /// The picker as `pick` opens it: a scan, plus where the pane it was opened
    /// from is, and no ● row because that pane runs no agent.
    fn app_at(tsv: &str, cwd: &str, target: &str) -> App {
        let mut a = app(tsv);
        a.src.cur_cwd = cwd.into();
        a.src.cur_target = target.into();
        a.focus_nearest();
        a
    }

    fn on(a: &App) -> &str {
        a.selected().map(|r| r.pane_id.as_str()).unwrap_or("")
    }

    /// Four sessions around one project tree, in a session the pane pressing F1
    /// is not in, so nothing but the directory can separate them.
    const TREE: &str = "%1\tw:1.1\t/h/notes\tclaude\t1\tidle\t-\tnotes\n\
                        %2\tw:2.1\t/h/proj/web\tclaude\t1\tidle\t-\tweb\n\
                        %3\tw:3.1\t/h/proj/web/docs\tclaude\t1\tidle\t-\tdocs\n\
                        %4\tw:4.1\t/h/proj\tclaude\t1\tidle\t-\tproj";

    /// F1 from a shell: the pane it was pressed in runs no agent, so there is no
    /// ● row to open on, and the cursor used to land on whichever row the scan
    /// listed first, which is to say on nothing.
    #[test]
    fn a_pane_with_no_agent_opens_on_the_session_in_its_own_directory() {
        assert_eq!(on(&app_at(TREE, "/h/proj/web", "z:1.1")), "%2");
        // the same directory wins however it is written
        assert_eq!(on(&app_at(TREE, "/h/proj/web/", "z:1.1")), "%2");
        assert_eq!(on(&app_at(TREE, "/h/notes", "z:1.1")), "%1");
    }

    /// Nothing is in the directory itself, so the nearest one is taken: DOWN the
    /// tree before up it, since the deeper session is the more specific answer
    /// and the parent is often just where several projects happen to live.
    #[test]
    fn a_subdirectory_beats_the_parent_directory() {
        let two = "%3\tw:3.1\t/h/proj/web/docs\tclaude\t1\tidle\t-\tdocs\n\
                   %4\tw:4.1\t/h/proj\tclaude\t1\tidle\t-\tproj";
        assert_eq!(on(&app_at(two, "/h/proj/web", "z:1.1")), "%3");
        // …and from deeper in, the session on the way back up
        assert_eq!(on(&app_at(TREE, "/h/proj/web/docs/api", "z:1.1")), "%3");
    }

    /// The directory outranks the list: a session next door in the wrong tree is
    /// not the one you are working on.
    #[test]
    fn the_directory_outranks_how_near_the_pane_is() {
        let two = "%1\tw:1.1\t/h/proj\tclaude\t1\tidle\t-\tright tree\n\
                   %2\tw:4.1\t/h/other\tclaude\t1\tidle\t-\tnext door";
        assert_eq!(on(&app_at(two, "/h/proj", "w:5.1")), "%1");
    }

    /// …and only then the list, which is what separates sessions the directory
    /// cannot: the same session first, nearest window in it, then anything else
    /// on this server, then another host, whose window numbers mean nothing here.
    #[test]
    fn equal_directories_are_separated_by_the_tmux_list() {
        let same = "%1\tother:1.1\t/h/proj\tclaude\t1\tidle\t-\tanother session\n\
                    %2\tw:9.1\t/h/proj\tclaude\t1\tidle\t-\tfar window\n\
                    %3\tw:2.1\t/h/proj\tclaude\t1\tidle\t-\tnext window";
        assert_eq!(on(&app_at(same, "/h/proj", "w:3.1")), "%3");

        let remote = "ha:%9\tw:1.1\t/h/proj\tclaude\t1\tidle\t-\tover there\n\
                      %1\tother:1.1\t/h/proj\tclaude\t1\tidle\t-\there";
        assert_eq!(on(&app_at(remote, "/h/proj", "w:3.1")), "%1");
    }

    /// A directory with nothing in common says nothing about which row is
    /// nearer, so the tie falls through to the list rather than to whichever
    /// session happens to sit closest to the root.
    #[test]
    fn a_directory_that_shares_nothing_falls_through_to_the_list() {
        let two = "%1\tw:1.1\t/h/a/b/c\tclaude\t1\tidle\t-\tdeep\n\
                   %2\tw:4.1\t/h/b\tclaude\t1\tidle\t-\tshallow";
        assert_eq!(on(&app_at(two, "/tmp/scratch", "w:5.1")), "%2");
    }

    /// Not knowing where the pane is means not knowing: the cursor stays at the
    /// top rather than moving on a guess. That is every entry point but `pick`.
    #[test]
    fn an_unknown_position_leaves_the_cursor_at_the_top() {
        assert_eq!(on(&app_at(TREE, "", "")), "%1");
    }

    const THREE: &str = "%1\ta:1.1\t/h\tclaude\t1\tidle\t-\tapple pie\n\
                         %2\tb:1.1\t/h\tclaude\t1\trun\t-\tbanana bread\n\
                         %3\tc:1.1\t/h\tclaude\t1\tinput\t-\tcherry tart";

    /// The rows are fitted to the area they are drawn in, less the border and the
    /// pointer. Getting this wrong is invisible until a row is one column too
    /// long and the right-hand columns fall off.
    #[test]
    fn the_row_width_excludes_the_border_and_the_pointer() {
        assert_eq!(row_width(130), 126);
        assert_eq!(row_width(2), 0); // narrower than its own chrome
        assert_eq!(row_width(0), 0);
    }

    #[test]
    fn tab_steps_round_the_cycle_and_starts_over() {
        let mut m = Mode::All;
        let seen: Vec<Mode> = (0..8)
            .map(|_| {
                m = m.next(true, true);
                m
            })
            .collect();
        assert_eq!(
            seen,
            vec![
                Mode::Input,
                Mode::Run,
                Mode::Idle,
                Mode::Background,
                Mode::Outdated,
                Mode::Panes,
                Mode::Dead,
                Mode::All
            ]
        );
    }

    /// Shift-tab is the same ring read backwards, so a step each way from
    /// anywhere lands back where it started.
    #[test]
    fn shift_tab_steps_the_other_way_round_the_cycle() {
        let mut m = Mode::All;
        let seen: Vec<Mode> = (0..8)
            .map(|_| {
                m = m.prev(true, true);
                m
            })
            .collect();
        assert_eq!(
            seen,
            vec![
                Mode::Dead,
                Mode::Panes,
                Mode::Outdated,
                Mode::Background,
                Mode::Idle,
                Mode::Run,
                Mode::Input,
                Mode::All
            ]
        );
        for m in [
            Mode::All,
            Mode::Input,
            Mode::Run,
            Mode::Idle,
            Mode::Background,
            Mode::Outdated,
            Mode::Panes,
            Mode::Dead,
        ] {
            assert_eq!(m.next(true, true).prev(true, true), m);
            assert_eq!(m.prev(true, true).next(true, true), m);
        }
    }

    /// Ended is skipped where there is nothing to show, rather than trapping the
    /// picker in a mode with no rows in it.
    #[test]
    fn the_ended_mode_is_skipped_without_a_sessions_cache() {
        assert_eq!(Mode::Panes.next(false, false), Mode::All);
        assert_eq!(Mode::Panes.next(true, false), Mode::Dead);
        // and backwards it is skipped the same way
        assert_eq!(Mode::All.prev(false, false), Mode::Panes);
        assert_eq!(Mode::All.prev(true, false), Mode::Dead);
    }

    /// …and so is outdated, where nothing is installed to judge a version
    /// against: every row would be measured against an empty version, so the
    /// list could only ever be empty.
    #[test]
    fn the_outdated_mode_is_skipped_when_no_version_is_installed() {
        assert_eq!(Mode::Background.next(false, true), Mode::Outdated);
        assert_eq!(Mode::Outdated.next(false, true), Mode::Panes);
        // both gates off: background goes straight on to every pane
        assert_eq!(Mode::Background.next(false, false), Mode::Panes);
        // …and going back from every pane skips it just the same
        assert_eq!(Mode::Panes.prev(false, false), Mode::Background);
        assert_eq!(Mode::Panes.prev(false, true), Mode::Outdated);
    }

    /// The every-pane stop is always in the ring, as the states are, and sits
    /// just before the past list, which stays the last stop.
    #[test]
    fn the_every_pane_mode_is_always_on_just_before_the_past_list() {
        for (ended, outdated) in [(false, false), (true, false), (false, true), (true, true)] {
            assert_eq!(Mode::Dead.prev(true, outdated), Mode::Panes);
            assert_eq!(
                Mode::Panes.next(ended, outdated),
                if ended { Mode::Dead } else { Mode::All }
            );
        }
        assert_eq!(Mode::from_key(Mode::Panes.key()), Mode::Panes);
        assert_eq!(Mode::Panes.filter(), "");
    }

    /// A machine with only shells on it has no sessions, even though every one
    /// of its panes is in the scan: the note says so rather than claiming the
    /// sessions are all in some other list.
    #[test]
    fn a_scan_of_only_plain_panes_found_no_session() {
        assert!(no_sessions(""));
        assert!(no_sessions("%1\tw:1.1\t/w\tbash\t\tpane\t-\tlogs\t-\t-\n"));
        assert!(!no_sessions(
            "%1\tw:1.1\t/w\tbash\t\tpane\t-\tlogs\t-\t-\n\
             %2\tw:2.1\t/w\tclaude\t2.1\tidle\t-\tone\t-\t-\n"
        ));
        // a host that stopped answering is still something the scan found
        assert!(!no_sessions("ha:!\tha\t-\t-\t\tunknown\t-\tunreachable\n"));
        let note: Vec<String> = empty_note(Mode::Panes, "", false, true, false, false, 0)
            .into_iter()
            .map(|l| l.to_string())
            .collect();
        assert!(note.iter().any(|l| l.contains("No panes were found")));
    }

    /// The background stop is never skipped, as no state stop is: it comes
    /// straight after idle whatever else is installed.
    #[test]
    fn the_background_mode_follows_idle_whatever_is_installed() {
        for (ended, outdated) in [(false, false), (true, false), (false, true), (true, true)] {
            assert_eq!(Mode::Idle.next(ended, outdated), Mode::Background);
            assert_eq!(Mode::Background.prev(ended, outdated), Mode::Idle);
        }
    }

    #[test]
    fn the_label_says_which_list_and_what_is_on() {
        assert_eq!(
            label(Mode::All, false, false, false, false),
            " agent sessions "
        );
        assert_eq!(
            label(Mode::Input, false, true, false, false),
            " waiting for an answer · live "
        );
        assert_eq!(
            label(Mode::Outdated, false, false, false, false),
            " running outdated code "
        );
        assert_eq!(
            label(Mode::Background, false, false, false, false),
            " running background work "
        );
        assert_eq!(
            label(Mode::Dead, false, true, true, false),
            " past sessions · live · ⌕ "
        );
        // the order goes straight after the name, since it describes that list
        assert_eq!(
            label(Mode::Dead, true, true, true, false),
            " past sessions · by date · live · ⌕ "
        );
    }

    /// Past conversations, newest first as the list arrives. Two SAY "tart", the
    /// older one where a word starts, which the matcher ranks higher; the newest
    /// of all only has its letters, scattered across four words.
    const PAST: &str =
        "dead:claude:/n.jsonl\t30m\t/h/a\tclaude\t1\tdead\t-\ttrial and error then tests\n\
         dead:claude:/r.jsonl\t1h\t/h/r\tclaude\t1\tdead\t-\trestart the ledger\n\
         dead:claude:/m.jsonl\t2d\t/h/b\tclaude\t1\tdead\t-\tapple pie\n\
         dead:claude:/o.jsonl\t9d\t/h/c\tclaude\t1\tdead\t-\tcherry tart";

    fn app_past(query: &str) -> App {
        let mut a = app(THREE);
        a.src.ended = Some(Box::new(|| PAST.to_string()));
        a.mode = Mode::Dead;
        a.query = query.into();
        a.fetch();
        a.rebuild();
        a
    }

    /// The reason for the key. A query ranks the past list best match first,
    /// which scatters what it keeps across the months; by date keeps the same
    /// matches, newest first, the order the list had before anything was typed.
    #[test]
    fn ctrl_s_keeps_the_past_list_newest_first_while_a_query_filters_it() {
        let mut a = app_past("tart");
        assert_eq!(
            ids(&a),
            [
                "dead:claude:/o.jsonl",
                "dead:claude:/r.jsonl",
                "dead:claude:/n.jsonl"
            ],
            "ranked, the word start wins, and the loose match comes last"
        );
        a.by_date = true;
        a.rebuild();
        assert_eq!(
            ids(&a),
            [
                "dead:claude:/r.jsonl",
                "dead:claude:/o.jsonl",
                "dead:claude:/n.jsonl"
            ],
            "by date, the two that say it newest first, THEN the loose one"
        );
        // …and typing more keeps that order rather than ranking again
        a.query = "tart e".into();
        a.query_changed();
        assert_eq!(
            ids(&a),
            [
                "dead:claude:/r.jsonl",
                "dead:claude:/o.jsonl",
                "dead:claude:/n.jsonl"
            ]
        );
    }

    /// The past list leaves out a claude session still open in a pane, so a
    /// query whose only match is one of those used to read as a miss: a pasted
    /// merge request URL answered "Nothing matches" there while the session that
    /// opened it was one Tab away. Where the past list keeps nothing, it now
    /// counts what the live list would keep, and that live list is the next stop.
    #[test]
    fn an_empty_past_list_counts_the_live_sessions_the_query_matches() {
        // only the live "banana bread" says it
        let mut a = app_past("banana");
        assert!(a.view.is_empty(), "no past row says it: {:?}", ids(&a));
        assert_eq!(a.live_hits, 1);
        // …recounted as the query changes, on the path that only re-filters
        // too, which is the one typing takes with this list's search off
        a.query = "zzz".into();
        a.query_changed();
        assert_eq!(a.live_hits, 0, "nothing anywhere says that");
        a.query = "bread".into();
        a.query_changed();
        assert_eq!(a.live_hits, 1);
        // …and Tab from the past list does land on the live one, as the note says
        assert_eq!(Mode::Dead.next(true, true), Mode::All);
        assert_eq!(Mode::Dead.next(true, false), Mode::All);
        a.step_mode(false);
        assert_eq!(a.mode, Mode::All);
        assert_eq!(ids(&a), ["%2"]);

        // a past list with a match of its own needs no pointer, even when a live
        // row says it too
        let b = app_past("tart");
        assert!(!b.view.is_empty());
        assert_eq!(b.live_hits, 0);

        // and the live lists never count it: the rows there are the live ones
        let mut c = app(THREE);
        c.query = "zzz".into();
        c.query_changed();
        assert!(c.view.is_empty());
        assert_eq!(c.live_hits, 0);
    }

    /// Why by date is not simply "leave every match where it stands". The
    /// letters of a query turn up scattered in rows that have nothing to do with
    /// it, and the ranking was what kept those under the rows that say it: tried
    /// on the real history without this, the top of the list was all noise. So
    /// the loose match stays last even as the newest row there is.
    #[test]
    fn by_date_keeps_the_loose_matches_under_the_ones_that_say_it() {
        let mut a = app_past("tart");
        a.by_date = true;
        a.rebuild();
        assert_eq!(
            ids(&a).last().map(String::as_str),
            Some("dead:claude:/n.jsonl")
        );
        // With nothing but loose matches, they are simply newest first.
        a.query = "tlr".into();
        a.query_changed();
        assert_eq!(ids(&a), ["dead:claude:/n.jsonl", "dead:claude:/r.jsonl"]);
    }

    /// The cursor stays on the conversation it was on, so a second press lands
    /// exactly where the first one started.
    #[test]
    fn sorting_by_date_keeps_the_cursor_on_the_same_conversation() {
        let mut a = app_past("tart");
        assert_eq!(on(&a), "dead:claude:/o.jsonl");
        a.by_date = true;
        a.rebuild();
        assert_eq!(on(&a), "dead:claude:/o.jsonl");
        assert_eq!(a.sel, 1, "which is now below the newer one");
        a.by_date = false;
        a.rebuild();
        assert_eq!((on(&a), a.sel), ("dead:claude:/o.jsonl", 0));
    }

    /// Every list sorts by date, not only the idle and past ones it started on,
    /// and the one switch holds through Tab: the working sessions by which spoke
    /// last, and all of them at once the same way.
    #[test]
    fn ctrl_s_orders_every_list_by_the_last_message() {
        let mut a = app("%1\ta:1.1\t/h\tclaude\t1\trun\t-\tcherry tart\t1000\n\
                         %2\tb:1.1\t/h\tclaude\t1\tidle\t-\ttrial and error then tests\t3000\n\
                         %3\tc:1.1\t/h\tclaude\t1\trun\t-\trestart the ledger\t2000");
        a.query = "tart".into();
        a.rebuild();
        assert_eq!(ids(&a), ["%1", "%3", "%2"], "ranked, the word start first");
        a.by_date = true;
        a.rebuild();
        assert!(a.dated(), "all sessions at once sorts too");
        assert_eq!(ids(&a), ["%3", "%1", "%2"], "the loose match still last");
        a.query.clear();
        a.query_changed();
        assert_eq!(
            ids(&a),
            ["%2", "%3", "%1"],
            "and with no query, newest first"
        );
        a.mode = Mode::Run;
        a.rebuild();
        assert!(a.dated(), "the flag rides the Tab");
        assert_eq!(ids(&a), ["%3", "%1"]);
        a.by_date = false;
        a.rebuild();
        assert_eq!(ids(&a), ["%1", "%3"], "back to tmux order");
    }

    /// Idle sessions in tmux order, as the scan lists them, each with when it
    /// last said something, except the codex one, which cannot say.
    const IDLE: &str = "%1\ta:1.1\t/h\tclaude\t1\tidle\t-\tapple pie\t1000\n\
                        %2\tb:1.1\t/h\tclaude\t1\tidle\t-\tbanana bread\t3000\n\
                        %3\tc:1.1\t/h\tcodex\t1\tidle\t-\tcherry tart\t-\n\
                        %4\td:1.1\t/h\tclaude\t1\tidle\t-\tdate loaf\t2000\n\
                        %5\te:1.1\t/h\tclaude\t1\trun\t-\telder cake\t9000";

    /// The idle list by when each session last said something, newest first,
    /// with the one that cannot say after all of them. That list comes in tmux
    /// order, so unlike the past one it changes with no query typed at all.
    #[test]
    fn ctrl_s_orders_the_idle_list_by_the_last_message() {
        let mut a = app(IDLE);
        a.mode = Mode::Idle;
        a.rebuild();
        assert_eq!(ids(&a), ["%1", "%2", "%3", "%4"], "tmux order");
        a.by_date = true;
        a.rebuild();
        assert!(a.dated());
        assert_eq!(ids(&a), ["%2", "%4", "%1", "%3"]);
        // …and under a query: "a" is in every one of them as typed
        a.query = "a".into();
        a.query_changed();
        assert_eq!(ids(&a), ["%2", "%4", "%1", "%3"]);
    }

    /// The race the past list's own buffer is for. A scan still out when Tab
    /// reaches that list lands afterwards, and it used to land ON it: "past
    /// sessions" showed live panes until the next tick.
    #[test]
    fn a_scan_that_lands_after_tab_leaves_the_past_list_alone() {
        let mut a = app(THREE);
        a.src.ended = Some(Box::new(|| PAST.to_string()));
        a.src.fetch = Arc::new(|| {
            std::thread::sleep(Duration::from_millis(150));
            THREE.to_string()
        });
        a.start_refresh();
        a.step_mode(true); // shift-tab from the first stop is the past list
        assert_eq!(a.mode, Mode::Dead);
        let past = ids(&a);
        assert_eq!(past.len(), 4);
        let mut landed = false;
        for _ in 0..100 {
            if a.take_refresh() {
                landed = true;
                break;
            }
            std::thread::sleep(Duration::from_millis(20));
        }
        assert!(landed, "the scan never arrived");
        a.rebuild();
        assert_eq!(ids(&a), past, "the past list is still the past list");
    }

    /// …and the other way round. Leaving the past list used to draw ITS rows
    /// under the live label until a scan came back; the panes last seen are
    /// there at once instead.
    #[test]
    fn leaving_the_past_list_shows_the_panes_at_once() {
        let mut a = app_past("");
        a.step_mode(false); // tab from the last stop is back to all
        assert_eq!(a.mode, Mode::All);
        assert_eq!(ids(&a), ["%1", "%2", "%3"]);
    }

    /// Every list searches what was said from an ordinary open, and ctrl-t flips
    /// the list on screen alone: turning it off to jump by name among the live
    /// sessions must leave the past list searching, and the other way round.
    #[test]
    fn ctrl_t_switches_the_list_on_screen_alone() {
        let mut a = app(THREE);
        (a.search, a.search_past) = (true, true); // an ordinary open, search allowed
        assert!(a.searching(), "a live list searches what was said");
        a.toggle_search();
        assert!(!a.searching(), "ctrl-t turns it off there");
        a.src.ended = Some(Box::new(|| PAST.to_string()));
        a.step_mode(true); // shift-tab from the first stop is the past list
        assert!(a.searching(), "…leaving the past list searching");
        a.toggle_search();
        assert!(!a.searching(), "ctrl-t turns the past list's off");
        a.step_mode(false); // back to all sessions
        a.toggle_search();
        assert!(a.searching(), "ctrl-t on a live list again");
        a.step_mode(true);
        assert!(!a.searching(), "…leaves the past list off, as it was left");
    }

    /// The first scan places the cursor by the pane the picker was opened from,
    /// but not when it lands under the past list: none of the rows there is a
    /// pane, and moving the cursor anyway is a jump nobody asked for.
    #[test]
    fn the_first_scan_leaves_the_cursor_alone_on_the_past_list() {
        let mut a = app_past("");
        a.src.cur_cwd = "/h/c".into();
        a.open_on("%9");
        assert_eq!(a.sel, 0, "not moved to the row in that directory");
        // on a list of panes it does what it always did
        let mut b = app(TREE);
        b.src.cur_cwd = "/h/proj/web".into();
        b.open_on("%404");
        assert_eq!(on(&b), "%2");
    }

    /// The list ctrl-x and F8 act on, gathered in one place. It crosses the four
    /// state modes, because being behind is not a state.
    #[test]
    fn the_outdated_mode_lists_the_rows_a_restart_would_act_on() {
        let mut a = app(VERSIONS);
        a.src.newver = "2.1.243".into();
        a.mode = Mode::Outdated;
        a.rebuild();
        assert_eq!(ids(&a), ["%1", "%2"], "behind, whatever they are doing");

        // …and with nothing installed to compare against, nothing is behind.
        a.src.newver = String::new();
        a.rebuild();
        assert!(a.view.is_empty());
    }

    /// The background stop lists the sessions that left work in flight, idle or
    /// working, and Tab lands on it straight from the idle one.
    #[test]
    fn the_background_mode_lists_the_sessions_with_work_in_flight() {
        let mut a = app("%1\ta:1.1\t/h\tclaude\t1\tidle\t-\twatching ci\t-\tbg\n\
                         %2\tb:1.1\t/h\tclaude\t1\tidle\t-\tall done\t-\t-\n\
                         %3\tc:1.1\t/h\tclaude\t1\trun\t-\tanother turn\t-\tbg\n\
                         %4\td:1.1\t/h\tcodex\t1\tidle\t-\tcannot say");
        a.mode = Mode::Idle;
        a.step_mode(false);
        assert_eq!(a.mode, Mode::Background);
        assert_eq!(
            ids(&a),
            ["%1", "%3"],
            "idle or working, whatever is still running"
        );
        // …and once that work has reported back the row drops out
        a.tsv = a.tsv.replace("watching ci\t-\tbg", "watching ci\t-\t-");
        a.rebuild();
        assert_eq!(ids(&a), ["%3"]);
    }

    /// The working list holds the working sessions and, in the same tmux order,
    /// the idle ones with work in flight; the idle list keeps those too, since
    /// their state has not changed.
    #[test]
    fn the_working_mode_takes_the_sessions_with_work_in_flight_too() {
        let mut a = app("%1\ta:1.1\t/h\tclaude\t1\tidle\t-\twatching ci\t-\tbg\n\
                         %2\tb:1.1\t/h\tclaude\t1\tidle\t-\tall done\t-\t-\n\
                         %3\tc:1.1\t/h\tclaude\t1\trun\t-\tbusy\t-\t-\n\
                         %4\td:1.1\t/h\tclaude\t1\tinput\t-\tasking\t-\tbg\n\
                         %5\te:1.1\t/h\tcodex\t1\trun\t-\tcannot say");
        a.mode = Mode::Run;
        a.rebuild();
        assert_eq!(ids(&a), ["%1", "%3", "%4", "%5"]);
        assert_eq!(
            label(Mode::Run, false, false, false, false),
            " working or running background work "
        );
        a.mode = Mode::Idle;
        a.rebuild();
        assert_eq!(ids(&a), ["%1", "%2"], "still idle, so still here");
        // …and once that work has reported back it is only idle
        a.mode = Mode::Run;
        a.tsv = a.tsv.replace("watching ci\t-\tbg", "watching ci\t-\t-");
        a.rebuild();
        assert_eq!(ids(&a), ["%3", "%4", "%5"]);
    }

    const VERSIONS: &str = "%1\ta:1.1\t/h\tclaude\t2.1.229\tidle\t-\tbehind\n\
                            %2\tb:1.1\t/h\tclaude\t2.1.229\tinput\t-\tbehind and asking\n\
                            %3\tc:1.1\t/h\tclaude\t2.1.243\trun\t-\tcurrent\n\
                            ha:%4\td:1.1\t/h\tclaude\t2.1.229\tidle\t-\tover there";

    /// The stamp names the tool as well as the version, or a bare number in a
    /// corner would read as one more agent version like the ones down the right
    /// of every row. It is the crate version, which is what `taimux version`
    /// prints and what release-please bumps, so the three cannot drift.
    #[test]
    fn the_stamp_names_the_tool_and_carries_the_crate_version() {
        let tag = version_tag();
        assert!(tag.contains("taimux"));
        assert!(tag.contains(env!("CARGO_PKG_VERSION")));
        // padded both sides, so it does not touch the border corner
        assert!(tag.starts_with(' ') && tag.ends_with(' '));
    }

    /// The stamp gives way to the count, never the other way round: ratatui
    /// gives a right-aligned title precedence, so without the check the count
    /// is what gets eaten, and the count is the live half.
    #[test]
    fn the_stamp_yields_to_the_count_on_a_narrow_border() {
        let count = " 5/5 ";
        let need = count.len() + version_tag().chars().count() + 2;
        assert!(room_for_tag(need as u16, count));
        assert!(!room_for_tag(need as u16 - 1, count));
        // a four-figure list needs more room for the same window
        assert!(!room_for_tag(need as u16, " 1000/1000 "));
        // and a window narrower than the stamp alone never gets it
        assert!(!room_for_tag(16, count));
    }

    /// The header only ever advertises what is really bound: a key that does
    /// nothing is worse than a shorter header.
    #[test]
    fn the_header_advertises_only_bound_keys() {
        let bare = header(false, false, false, false, false);
        assert!(!bare.contains("ctrl-x"));
        assert!(!bare.contains("resume"));
        assert!(!bare.contains("ctrl-t"));
        assert!(header(true, false, false, false, false).contains("ctrl-x"));
        assert!(header(false, true, false, false, false).contains("enter: switch/resume"));
        assert!(header(false, false, true, true, false).contains("(on)"));
        assert!(!header(false, false, true, false, false).contains("(on)"));
        // ctrl-s is bound on every list, so every header says it
        assert!(bare.contains("ctrl-s: sort by date") && !bare.contains("(on)"));
        assert!(header(false, false, false, false, true).contains("ctrl-s: sort by date (on)"));
    }

    #[test]
    fn a_mode_shows_only_that_state() {
        let mut a = app(THREE);
        assert_eq!(a.view.len(), 3);
        a.mode = Mode::Run;
        a.rebuild();
        assert_eq!(a.view.len(), 1);
        assert!(a.selected().unwrap().plain().contains("banana"));
    }

    #[test]
    fn the_query_filters_and_ranks() {
        let mut a = app(THREE);
        a.query = "banana".into();
        a.view = filter(&a.all, &a.query, &a.matcher, false);
        assert_eq!(a.view.len(), 1);

        // an AND of terms, as fzf's extended search does, not one fuzzy match
        a.query = "apple tart".into();
        a.view = filter(&a.all, &a.query, &a.matcher, false);
        assert!(a.view.is_empty());
    }

    #[test]
    fn no_query_keeps_the_lists_own_order() {
        let a = app(THREE);
        assert_eq!(a.view, vec![0, 1, 2]);
    }

    /// A rebuild puts the cursor back on the same SESSION, not the same index.
    /// That is what --track --id-nth=2 buys fzf, and it matters because the
    /// refresh timer rebuilds under you while you are moving.
    #[test]
    fn a_rebuild_keeps_the_cursor_on_the_same_session() {
        let mut a = app(THREE);
        a.sel = 2;
        let was = a.selected().unwrap().pane_id.clone();
        // a session vanishes from the top of the list
        a.src = src("%2\tb:1.1\t/h\tclaude\t1\trun\t-\tbanana bread\n\
                     %3\tc:1.1\t/h\tclaude\t1\tinput\t-\tcherry tart");
        a.fetch();
        a.rebuild();
        assert_eq!(a.selected().unwrap().pane_id, was);
        assert_eq!(a.sel, 1);
    }

    #[test]
    fn a_cursor_whose_row_is_gone_falls_back_to_the_top() {
        let mut a = app(THREE);
        a.sel = 2;
        a.src = src("%1\ta:1.1\t/h\tclaude\t1\tidle\t-\tapple pie");
        a.fetch();
        a.rebuild();
        assert_eq!(a.sel, 0);
    }

    #[test]
    fn the_cursor_wraps_both_ways() {
        let mut a = app(THREE);
        a.move_by(-1);
        assert_eq!(a.sel, 2);
        a.move_by(1);
        assert_eq!(a.sel, 0);
    }

    /// A page CLAMPS where a single step wraps, and the difference is the point:
    /// holding Page Down to reach the bottom of a long list must not sail past
    /// the end and land back at the top, with nothing on the row to say so.
    #[test]
    fn a_page_clamps_where_a_single_step_wraps() {
        let mut a = app(THREE);
        a.move_page(1, 2);
        assert_eq!(a.sel, 2);
        a.move_page(1, 2); // already at the end, and it stays there
        assert_eq!(a.sel, 2);
        a.move_page(-1, 2);
        assert_eq!(a.sel, 0);
        a.move_page(-1, 2);
        assert_eq!(a.sel, 0);
    }

    /// A list drawn zero rows tall (a pane too short for one) would otherwise
    /// make the key do nothing at all, which reads as the key being unbound.
    #[test]
    fn a_page_of_no_rows_still_moves_one() {
        let mut a = app(THREE);
        a.move_page(1, 0);
        assert_eq!(a.sel, 1);
    }

    /// Page Up and Page Down were the two keys the port dropped: fzf bound them
    /// itself, `Home` and `End` were ported by hand and these were not, so one
    /// pair kept working and the other went quiet. Nothing failed, which is why
    /// it took a report. The suite drives the real keys in a real terminal (see
    /// tests/run.sh); this is the arithmetic underneath.
    #[test]
    fn an_empty_view_pages_without_panicking() {
        let mut a = app(THREE);
        a.query = "zzzzz".into();
        a.query_changed();
        assert!(a.view.is_empty());
        a.move_page(1, 8);
        a.move_page(-1, 8);
        assert_eq!(a.sel, 0);
    }

    /// An empty list must not be indexed into, and every key still has to work on
    /// one: a query that matches nothing is the ordinary way to get here.
    #[test]
    fn an_empty_view_is_safe_to_navigate() {
        let mut a = app(THREE);
        a.query = "zzzzz".into();
        a.view = filter(&a.all, &a.query, &a.matcher, false);
        assert!(a.view.is_empty());
        a.move_by(1);
        a.move_by(-1);
        a.clamp();
        assert!(a.selected().is_none());
    }

    /// The padding `capture-pane` adds is what made every waiting session read as
    /// idle when the state reader was ported. Same capture, same trap, so the
    /// preview trims before it takes a tail.
    #[test]
    fn the_preview_tail_ignores_the_padding_capture_pane_adds() {
        let screen = "one\ntwo\nthree\n\n\n\n\n\n\n\n";
        let t = tail(screen, 2);
        let text: Vec<String> = t
            .iter()
            .map(|l| l.spans.iter().map(|s| s.content.to_string()).collect())
            .collect();
        assert_eq!(text, vec!["two", "three"]);
    }

    #[test]
    fn a_screen_shorter_than_the_room_is_shown_whole() {
        assert_eq!(tail("one\ntwo\n", 40).len(), 2);
        assert!(tail("", 40).is_empty());
        assert!(tail("\n\n\n", 40).is_empty());
    }

    /// The whole point of the exercise: a paste is text, never an Enter. Its
    /// first line joins the query and the rest is dropped, rather than being
    /// submitted into whatever is behind the picker.
    #[test]
    fn a_pasted_newline_stays_out_of_the_query() {
        let text = "set -g @plugin foo\rdo not write below this line";
        let first = text.split(['\r', '\n']).next().unwrap();
        assert_eq!(first, "set -g @plugin foo");
    }
}