beady-eye 0.11.0

A tree of work in flight: bead graphs annotated with the live agents working them
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
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
//! What `bdi` puts on the alternate screen.
//!
//! `Shown` is the rows and the band beneath them, held apart from the
//! terminal because none of it needs a tty; `Screen` is the terminal, and
//! putting it back however the run ends is what its `Drop` is for. They are
//! one module because the drawing reaches into the rows it draws.

use std::io;
use std::time::Duration;

use chrono::{DateTime, Utc};
use ratatui::crossterm::event::{DisableMouseCapture, EnableMouseCapture};
use ratatui::crossterm::execute;
use ratatui::crossterm::terminal::{Clear, ClearType};
use ratatui::layout::Rect;
use ratatui::{DefaultTerminal, Frame};

use crate::app::Awaited;
use crate::collect::panes::{Answer, Panes};
use crate::config::{Background, Config};
use crate::model::join::BeadKey;
use crate::model::snapshot::Snapshot;
use crate::model::types::PaneKey;
use crate::view::bindings::key_bindings;
use crate::view::forest::{self, Forest};
use crate::view::lines::Place;
use crate::view::phrase;
use crate::view::row::Layout;
use crate::view::show::{self, Show};
use crate::view::tail::{self, Tail};
use crate::view::{draw, Action, Freshness, Motion, Notch, Notice, Said, Typing};

use super::clipboard;
use super::drive::{Landed, Showing, View};
use super::due::due_after;
use super::keys::{bindings, key_row};
use super::reload::Reloaded;

/// What the config settles about the drawing, as one value read from it in
/// one place.
///
/// One value rather than a field each, because the reason a setting the
/// screen owns went on saying what the run started with was that there was
/// nowhere a fresh config was read for the screen at all. A key added to
/// `[tui]` or `[theme]` is read here or it is not read: the seam that carries
/// a reload hands over a `Config`, this is what the screen makes of one, and
/// the same call makes it at startup and after every edit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Drawing {
    /// How long after the provider answers the pane on the band is asked for
    /// again.
    tail_every: Duration,
    /// The background the reader's terminal draws on, which decides the one
    /// treatment `bdi` composes itself.
    background: Background,
    /// How far one notch of the wheel moves the forest, and the bead window
    /// over it.
    notch: usize,
    /// Which cells a bead's row draws, and in what order.
    layout: Layout,
}

impl Drawing {
    pub(super) fn to(cfg: &Config) -> Self {
        Self {
            tail_every: cfg.tui.tail_refresh(),
            background: cfg.theme.background,
            notch: cfg.tui.wheel_notch_lines,
            layout: cfg.row.clone(),
        }
    }
}

/// How long a notice settled before the first collection is said at the foot.
///
/// Long enough that a reader who started `bdi` and turned to another window
/// is still shown it when they look back, and short enough that a session
/// left up all day is not spending a row on a fact that was settled before
/// anything was drawn.
const SETTLED_AT_STARTUP_STANDS_FOR: Duration = Duration::from_secs(60);

/// What a run settled about itself before its first collection, and when it
/// stops saying so.
///
/// Held apart from what stands by where it came from rather than by which
/// notice it is. Nothing rechecks these: the socket is asked for once for the
/// life of the run, so the answer holds whether or not the reader is still
/// being told, and only a clock can take it off.
struct Retiring {
    notices: Vec<Notice>,
    /// When they stop being said, or nothing where no clock will take them
    /// off: a run that settled nothing to say, and one whose retirement is
    /// further ahead than an instant can reach.
    at: Option<DateTime<Utc>>,
}

impl Retiring {
    fn settled(notices: Vec<Notice>, started: DateTime<Utc>) -> Self {
        Self {
            at: (!notices.is_empty())
                .then(|| due_after(started, SETTLED_AT_STARTUP_STANDS_FOR))
                .flatten(),
            notices,
        }
    }

    /// What they still say, which is nothing once they have retired.
    fn said(&self, now: DateTime<Utc>) -> &[Notice] {
        match self.at {
            Some(at) if at <= now => &[],
            _ => &self.notices,
        }
    }

    /// How long until they retire, or nothing where the foot will not change
    /// for them. Nothing rather than no time at all: a deadline that goes on
    /// falling due is a loop redrawing the same frame for ever.
    fn retires_in(&self, now: DateTime<Utc>) -> Option<Duration> {
        self.at
            .and_then(|at| (at - now).to_std().ok())
            .filter(|left| !left.is_zero())
    }
}

/// The forest on the alternate screen and the tail beneath it.
///
/// Held apart from the terminal that draws it because the terminal needs a
/// tty and none of this does.
struct Shown {
    forest: Forest,
    panes: Box<dyn Panes>,
    /// Where the terminal's clipboard is written: the terminal itself, by
    /// escape sequence, so the write travels the way every other byte `bdi`
    /// puts on the screen does and needs no program outside it.
    clipboard: Box<dyn io::Write>,
    tail: Tail,
    /// The pane the band on screen is about, so a selection moving within it
    /// does not spend a call on the provider for the answer already drawn.
    tailing: Option<PaneKey>,
    /// Where the band is with the pane read it is waiting on.
    reading: Reading,
    /// What the config in force settles about the drawing.
    drawing: Drawing,
    /// When the pane on the band is next asked for, or nothing while a read
    /// of it is out, the band names no pane, or the interval is too long to
    /// reach. Armed by the answer that filled the band and disarmed by the
    /// ask it makes, as a project is.
    due: Option<DateTime<Utc>>,
    /// What the reader's last keystroke came to, said at the foot until their
    /// next key or click. Theirs and not the collector's: a collection landing
    /// a moment after the key would otherwise take the one line that says it
    /// fired off before anyone had read it.
    said: Option<Said>,
    /// What the reader has typed into the search prompt, while one is up.
    ///
    /// Held here and not on the forest for the reason the bead view's `Show`
    /// is: it is about a prompt over the rows, not about the rows. The loop
    /// holds that a prompt is up; this is what is in it.
    sought: Option<String>,
    /// What the collection in flight is reading and when it was asked for,
    /// where one is running. Every project line it names says its own rows
    /// are about to be replaced, and the rest of the screen carries on saying
    /// how stale it is.
    ///
    /// The instant is what tells a collection under way from one that has
    /// stopped answering. It is stamped where the ask happens rather than
    /// here, because being told a collection is running is not the same as
    /// one having started, and only the loop knows which it is telling us.
    ///
    /// Held here rather than on the lines because it changes without the
    /// snapshot changing: a collection starts and ends between two
    /// flattenings, and the mark on a line it names turns several times
    /// inside one of them.
    collecting: Vec<Awaited>,
    /// Where the bead view is looking, while one is up. Held here and not on
    /// the forest because it is about a window over the rows, not the rows.
    show: Show,
    /// The bead the view is on, so a collection that moves the selection off
    /// it can be told from one that leaves it there.
    ///
    /// The bead the window is showing rather than the one it was opened on:
    /// following a reference moves the selection, and a guard reading the
    /// bead a reader has left would take the window down on the very move
    /// they asked for.
    viewing: Option<BeadKey>,
    /// The beads followed to reach the one the window is on, each with where
    /// the window was looking when it was left, most recent last.
    ///
    /// A place and not a key, because going back means the copy of the bead
    /// the reader was looking at, and a bead the forest draws under two
    /// parents is drawn twice. The `Show` beside it is what puts them back
    /// on the row they followed rather than at the top of the bead.
    trail: Vec<(Place, Show)>,
    /// What this run of `bdi` cannot do, said at the foot until it can. A
    /// config that will not reload joins and leaves as the file breaks and
    /// mends.
    ///
    /// Held here rather than beside the terminal: what the foot says is a
    /// fact about the view, and a fact nothing without a tty could reach
    /// would be a fact no test could either.
    standing: Vec<Notice>,
    /// What was settled before the first collection, said until it retires.
    at_startup: Retiring,
}

/// Where the band under the forest is with the read it is waiting on.
///
/// At most one is ever out, so what a reader moving faster than the provider
/// answers costs is a run of answers dropped rather than a call per keystroke.
/// An answer is the answer to what was drawn when it was asked for, and what
/// is drawn moves on when the cursor lands on another pane.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Reading {
    /// Nothing is out, so the pane the band names is the pane to ask for.
    Nothing,
    /// A read is out, and its answer is the answer to what is drawn.
    Outstanding,
    /// A read is out, and what is drawn moved on after it was asked. Its
    /// answer is the answer to nothing on the screen, so it is dropped and
    /// the pane the band names now is asked for in its place.
    Superseded,
}

impl Shown {
    fn of(
        snapshot: Snapshot,
        panes: Box<dyn Panes>,
        clipboard: Box<dyn io::Write>,
        drawing: Drawing,
        at_startup: Vec<Notice>,
        started: DateTime<Utc>,
    ) -> Self {
        let mut forest = forest::flatten(snapshot);
        forest.laid_out_to(drawing.layout.clone());
        let mut shown = Self {
            tail: tail::tail(&forest),
            tailing: tail::target(&forest).pane().cloned(),
            forest,
            panes,
            clipboard,
            reading: Reading::Nothing,
            drawing,
            due: None,
            said: None,
            sought: None,
            // Nothing in flight until the loop says otherwise. A collection
            // is already running by the time this exists — the run asks for
            // one before it opens the screen — and it reaches this the way
            // every one after it does, through `collecting`.
            collecting: Vec::new(),
            show: Show::default(),
            viewing: None,
            trail: Vec::new(),
            standing: Vec::new(),
            at_startup: Retiring::settled(at_startup, started),
        };
        // Asked for here rather than waited for: the first frame is drawn on
        // the answer to this arriving, not on the provider getting round to it.
        shown.ask();
        shown
    }

    /// Say what the collection in flight is reading, or that none is,
    /// reporting whether the screen is any different for it.
    ///
    /// Being told again what it already says is not a change: a collection
    /// coming back with another waiting behind it names the same projects as
    /// often as not, and a redraw that puts the same frame back is a redraw
    /// for nothing.
    fn collecting(&mut self, awaited: &[Awaited]) -> bool {
        let changed = self.collecting != awaited;
        self.collecting = awaited.to_vec();
        changed
    }

    /// How long what is drawn goes on being true with nothing happening.
    ///
    /// The soonest deadline anything on the screen sets. The foot sets one
    /// where a notice settled at startup is still being said, and the rest
    /// are the project lines'. Each of them
    /// says two things — a mark, and how old its rows are — and a collection
    /// in flight does not silence the ages: they go on ticking under the mark
    /// that is turning, so a project read a moment ago is due a redraw well
    /// inside the frame.
    ///
    /// The ages are asked of `read_at` rather than of the lines, so a project
    /// drawn under any rule the forest has is covered by it. A project that is
    /// read and not drawn costs a redraw nobody sees, which is cheaper than
    /// the line that quietly stops being true.
    ///
    /// The mark is asked once of the collection, where the ages are asked one
    /// project at a time. Which projects a collection names decides which
    /// *lines* turn, and cannot decide when the screen is next due: every line
    /// a collection names turns on the one clock, so a frame falls due as soon
    /// as any of them is turning. Asking it per project would be a second way
    /// of reaching the same answer — and a collection running before anything
    /// it names has come back has no project in `read_at` to be asked about
    /// anyway, which is the startup frame.
    fn holds_for(&self, now: DateTime<Utc>) -> Option<Duration> {
        let snapshot = self.forest.snapshot();
        let ageing = snapshot
            .read_at
            .values()
            .filter_map(|at| Freshness::of(Some(*at), None, true, now));
        let turning = self
            .collecting
            .iter()
            .filter_map(|awaited| Freshness::of(None, Some(awaited), true, now));

        turning
            .into_iter()
            .chain(ageing)
            .filter_map(|how_fresh| phrase::holds_for(how_fresh, now))
            .chain(self.at_startup.retires_in(now))
            .min()
    }

    /// Everything this run has to say about itself, in the order the foot
    /// should give it up: what was settled at startup, and then what stands.
    fn says(&self, now: DateTime<Utc>) -> Vec<Notice> {
        self.at_startup
            .said(now)
            .iter()
            .chain(&self.standing)
            .cloned()
            .collect()
    }

    /// Put the band on whatever the selection is on now, and ask the provider for
    /// the pane where it is on one.
    ///
    /// Whatever the provider is already answering was asked for the band this
    /// replaces, so it is superseded here, and a read the band it replaces
    /// was due is not due any more.
    fn retail(&mut self) {
        self.tailing = tail::target(&self.forest).pane().cloned();
        self.tail = tail::tail(&self.forest);
        if self.reading == Reading::Outstanding {
            self.reading = Reading::Superseded;
        }
        self.due = None;
        self.ask();
    }

    /// Ask the provider for the pane the band is waiting on, where it is
    /// waiting on one and it has not been asked already.
    ///
    /// A reader holding an arrow key down moves faster than a slow provider
    /// answers, so every answer arrives about a screen they have already left
    /// and is dropped; the band goes on naming the pane it is waiting for
    /// until the cursor rests long enough for one answer to land. That is the
    /// trade the bound is spent on: the tail can fall behind the selection,
    /// and the keyboard never does.
    fn ask(&mut self) {
        if self.reading != Reading::Nothing {
            return;
        }
        let Tail::Reading { pane } = &self.tail else {
            return;
        };
        self.read(pane.clone());
    }

    /// Ask for the pane on the band again where its interval is up. The
    /// rows on the band stand until the answer lands: a band that said it
    /// was reading the pane every time it did would say nothing else.
    fn reread(&mut self, now: DateTime<Utc>) {
        if self.reading != Reading::Nothing || !self.due.is_some_and(|due| due <= now) {
            return;
        }
        if let Some(pane) = self.tailing.clone() {
            self.read(pane);
        }
    }

    /// Ask the provider for a pane. Nothing is due while the answer is on its
    /// way;
    /// what arms the next read is that answer landing.
    fn read(&mut self, pane: PaneKey) {
        self.panes.read(&pane, tail::LINES);
        self.reading = Reading::Outstanding;
        self.due = None;
    }

    /// How long until the pane on the band is asked for again, or nothing
    /// where it is not going to be: no pane on the band, a read still out,
    /// or an interval too long to reach.
    fn rereads_in(&self, now: DateTime<Utc>) -> Option<Duration> {
        self.due
            .map(|due| (due - now).to_std().unwrap_or(Duration::ZERO))
    }

    /// Take what a check of the config file found, reporting whether the
    /// screen is any different for it.
    ///
    /// The notice is about whether the file loaded, and nothing else: a read
    /// that brought a config identical to the one in force is a read that
    /// worked, and takes the notice off exactly as one bringing a new config
    /// does. Tying it to whether the config *changed* would leave a reader
    /// who undid a broken edit looking at a foot that still said their
    /// config was broken, with no edit left that would clear it but one
    /// changing the config to something they did not want.
    fn reloaded(&mut self, reloaded: Reloaded<'_>, now: DateTime<Utc>) -> bool {
        let (broken, redrawn) = match reloaded {
            Reloaded::Untouched => return false,
            Reloaded::Unchanged => (false, false),
            Reloaded::Fresh(written) => (false, self.draws_to(Drawing::to(written), now)),
            Reloaded::Broken => (true, false),
        };
        let said = self.standing.contains(&Notice::ConfigWouldNotReload);
        if said == broken {
            return redrawn;
        }
        if broken {
            self.standing.push(Notice::ConfigWouldNotReload);
        } else {
            self.standing
                .retain(|notice| *notice != Notice::ConfigWouldNotReload);
        }
        true
    }

    /// Draw to what the config the reader has just written settles, reporting
    /// whether the screen is any different for it.
    ///
    /// The whole value is compared rather than the one field a frame shows.
    /// What is drawn was drawn to the settings that stood before, so a screen
    /// under different ones is a screen that may say something else — and a
    /// rule naming the settings a redraw is worth is a rule that has to be
    /// added to for every key, which is the shape this bead exists to stop.
    ///
    /// The interval starts again from the check that found it, where the band
    /// is waiting on one. A due date left where the interval it was worked
    /// out from used to be is a reader who shortens the interval and waits
    /// out the one they replaced — which is the edit doing nothing, for as
    /// long as the old interval says.
    fn draws_to(&mut self, drawing: Drawing, now: DateTime<Utc>) -> bool {
        if self.drawing == drawing {
            return false;
        }
        self.drawing = drawing;
        self.forest.laid_out_to(self.drawing.layout.clone());
        if self.due.is_some() {
            self.due = due_after(now, self.drawing.tail_every);
        }
        true
    }

    /// Take what the provider said, reporting whether the screen is any different
    /// for it.
    fn tailed(&mut self, answer: Answer, now: DateTime<Utc>) -> bool {
        match answer {
            Answer::Read { pane, read } => {
                let superseded = self.reading == Reading::Superseded;
                self.reading = Reading::Nothing;
                if superseded {
                    self.ask();
                    return false;
                }
                let read = tail::read(pane, read);
                let changed = read != self.tail;
                self.tail = read;
                self.due = due_after(now, self.drawing.tail_every);
                changed
            }
            // A focus that would not come says so where the tail is, and only
            // while the tail is still that pane's: the rule above the band
            // names the pane, so a refusal about one the reader has left
            // would be drawn as a refusal about the one they are on.
            Answer::Focused { pane, focused } => match tail::focused(focused) {
                Some(said) if self.tailing.as_ref() == Some(&pane) => {
                    self.tail = said;
                    true
                }
                _ => false,
            },
        }
    }

    /// Follow the selection, where it has left the pane the tail is showing.
    fn follow(&mut self) {
        if tail::moved_on(&self.forest, self.tailing.as_ref()) {
            self.retail();
        }
    }

    /// Report a selection that may have moved, taking the tail with it where
    /// it did. Every way of moving the selection goes through here, so no
    /// route to it can leave the tail behind showing another bead's pane.
    fn moved(&mut self, changed: bool) -> bool {
        if changed {
            self.follow();
        }
        changed
    }

    /// Put the selection on one line of the forest.
    fn select(&mut self, at: usize) -> bool {
        let changed = self.forest.select_line(at);
        self.moved(changed)
    }

    /// Put the selection on the line the forest drew on one row of `screen`.
    ///
    /// Which line a row holds is a fact about the frame rather than about the
    /// click — the bands divide the screen, and the forest scrolls under its
    /// own — so the geometry is asked here, where the forest is, and the
    /// screen is all the terminal has to say about it.
    ///
    /// The forest is fitted to the band the click was measured against rather
    /// than left on the last frame's, so a pointer is answered for the screen
    /// it pointed at whatever has been drawn since.
    fn clicked(&mut self, screen: Rect, row: u16) -> bool {
        let bands = draw::regions(screen);
        self.forest.fit(bands.forest.height as usize);

        match draw::line_at(
            bands.forest,
            self.forest.from(),
            self.forest.lines().len(),
            row,
        ) {
            Some(at) => self.select(at),
            // The tail is an echo of a pane and the key row is a legend.
            // Neither holds anything the selection could sit on, and a row
            // past the last line of the forest holds nothing at all.
            None => false,
        }
    }

    /// Go to the bead named by the reference the bead window drew on one row
    /// of `screen`, saying what the click came to.
    ///
    /// A click that follows is `Enter` on the ring with the ring put where
    /// the pointer is, rather than a second way to the same bead: what the
    /// window keeps to come back to is kept by that one path, and a second
    /// would have to remember to. Which is also why the ring goes back where
    /// it was when the bead turns out not to be one the forest can reach —
    /// the reader pointed at it and arrived nowhere, and a ring left sitting
    /// on it would be a move they never asked for.
    fn clicked_bead(&mut self, screen: Rect, row: u16) -> Landed {
        let landed =
            show::selected(&self.forest).map(|node| show::drawn_at(screen, node, &self.show, row));
        let on = match landed {
            Some(show::Drawn::Related(id)) => id.to_string(),
            Some(show::Drawn::Page) => return Landed::Nothing,
            // A selection on no bead has no page either, and the window is
            // drawn from the selection: there is nothing on the screen for
            // the click to be about.
            Some(show::Drawn::Beyond) | None => return Landed::Away,
        };

        let was = self.show.clone();
        self.show.go_to(&on);
        if self.follow_related() {
            Landed::Followed
        } else {
            self.show = was;
            Landed::Nothing
        }
    }

    /// Take what the foot said back off it, reporting whether it said
    /// anything. The reader's next press is what takes it off, whatever the
    /// press turns out to mean — it was feedback on a keystroke, not a fact
    /// about the screen.
    fn pressed(&mut self) -> bool {
        self.said.take().is_some()
    }

    /// Take one keystroke into the search prompt, reporting whether the screen
    /// has changed.
    ///
    /// Enter on an empty prompt asks for nothing, so it says nothing: a reader
    /// who opened the prompt and changed their mind has pressed the other way
    /// out of it, and an answer about the empty id would be an answer to a
    /// question nobody put.
    fn typing(&mut self, typing: Typing) -> bool {
        let Some(sought) = self.sought.as_mut() else {
            return false;
        };
        match typing {
            Typing::Character(glyph) => {
                sought.push(glyph);
                true
            }
            Typing::RubbedOut => sought.pop().is_some(),
            Typing::Abandoned => {
                self.sought = None;
                true
            }
            Typing::Sought => {
                let id = std::mem::take(sought);
                self.sought = None;
                if !id.is_empty() {
                    self.seek(&id);
                }
                true
            }
        }
    }

    /// Go to a bead matching what the reader typed, and say at the foot what
    /// they cannot see for themselves.
    ///
    /// Which is both halves now, on every landing. A search takes part of an
    /// id or part of a title, so the reader has typed a fragment rather than
    /// a name: the row they land on cannot tell them which bead it is,
    /// because the id it draws is the shortened one, and no row can tell them
    /// that eleven others matched.
    ///
    /// Under the exact match this widened, the row *was* the whole answer and
    /// the foot spoke up only when a second tracker held the same id. That is
    /// two facts a count says at once, so it says them and the special case
    /// goes.
    fn seek(&mut self, query: &str) {
        self.said = Some(said_of(self.forest.seek(query)));
        self.moved(true);
    }

    /// Step to the next bead matching what was last searched for, or to the
    /// one before it, reporting whether the screen has changed.
    ///
    /// A press before anything has been searched for has nothing to step
    /// through: nothing moves, nothing has gone wrong, and the foot has
    /// nothing to say about it.
    fn step_match(&mut self, forward: bool) -> bool {
        let Some(landed) = self.forest.next_match(forward) else {
            return false;
        };
        self.said = Some(said_of(landed));
        self.moved(true);
        true
    }

    fn collected(&mut self, snapshot: Snapshot) {
        // A refresh keeps the folds and the selection, so the cursor stays on
        // the bead the user put it on however the new snapshot has moved it.
        self.forest.refresh(snapshot);
        // The pane is on the band's own clock. What a collection can do to
        // the band is move the selection off the pane it is showing.
        self.follow();
        // And what it can do to the bead window is rewrite what the bead it
        // is on names, under a reader who is looking at one of them.
        self.settle_ring();
    }

    fn apply(&mut self, action: Action) -> bool {
        // Asking for the selected bead's pane to be brought to the front
        // changes nothing on this screen, and a row with no pane is a no-op:
        // there is nothing to focus and nothing has gone wrong. What the
        // provider makes of it arrives as an answer like a reading does.
        if action == Action::Focus {
            tail::focus(&self.forest, self.panes.as_ref());
            return false;
        }
        // Showing a bead changes the screen where there is one to show, and
        // starts from its top: the view a reader scrolled to the end of was
        // another bead's. A row with no bead behind it changes nothing.
        if action == Action::ShowBead {
            let opened = show::selected(&self.forest).is_some();
            if opened {
                self.show = Show::default();
                self.viewing = self.selected_bead().cloned();
                // The way back out of a window is the forest it was opened
                // over, whatever the last one was opened over.
                self.trail.clear();
            }
            return opened;
        }
        if action == Action::NextRelated {
            return self.step_related();
        }
        if action == Action::CopyId {
            return self.copy_id();
        }
        if let Action::NextMatch | Action::PreviousMatch = action {
            return self.step_match(action == Action::NextMatch);
        }
        // The prompt goes up empty. What it holds is this side of the seam;
        // that it is up is the loop's, which is what makes a keystroke mean a
        // character of an id rather than the binding the same key carries.
        if action == Action::Search {
            self.sought = Some(String::new());
            return true;
        }

        let changed = self.forest.apply(action);
        self.moved(changed)
    }

    /// Move the bead view, leaving the selection under it where it is.
    fn scroll(&mut self, motion: Motion) -> bool {
        self.show.scroll(motion)
    }

    /// Move the forest's view, leaving the selection where the reader put it
    /// — off the screen where the notch has taken it there. The tail is not
    /// asked to follow, for the same reason: nothing has moved that the tail
    /// is an echo of.
    fn scrolled(&mut self, notch: Notch) -> bool {
        self.forest.scrolled(notch, self.drawing.notch)
    }

    /// And the bead view, by the same distance.
    fn scrolled_bead(&mut self, notch: Notch) -> bool {
        self.show.scrolled(notch, self.drawing.notch)
    }

    /// Whether the selection is still on the bead the view was opened on.
    fn bead_still_shown(&self) -> bool {
        self.viewing.is_some() && self.viewing.as_ref() == self.selected_bead()
    }

    /// Put the selected bead's id on the terminal's clipboard and say so at
    /// the foot, where the selection is on a bead. Most rows are beads; on one
    /// that is not there is nothing to copy and nothing has gone wrong, as
    /// with `f`. A write the terminal would not take is not said either:
    /// the foot would be the one line on the screen that was untrue.
    fn copy_id(&mut self) -> bool {
        let Some(key) = self.selected_bead() else {
            return false;
        };
        let id = key.id.clone();
        if clipboard::copy(self.clipboard.as_mut(), &id).is_err() {
            return false;
        }
        self.said = Some(Said::Copied(id));
        true
    }

    /// Move the window on to the next bead the shown bead names, reporting
    /// whether it moved.
    ///
    /// Only beads the forest can take the reader to are stepped on to. A
    /// reference the forest draws nowhere is still on the page and still says
    /// so; putting the ring on it would offer a reader an Enter that does
    /// nothing.
    fn step_related(&mut self) -> bool {
        let Some(node) = show::selected(&self.forest) else {
            return false;
        };
        let related = show::related(node);
        let from = self.show.on().and_then(|id| show::at(node, id));
        let to = show::stepped(from, related.len(), |at| {
            show::followable(&self.forest, related[at])
        });
        let Some(to) = to else {
            return false;
        };
        let to = related[to].id.clone();
        self.show.go_to(&to);
        true
    }

    /// The bead the window's ring is on, where it is on one the forest draws.
    fn related_key(&self) -> Option<BeadKey> {
        let node = show::selected(&self.forest)?;
        let on = show::related(node)
            .into_iter()
            .find(|named| Some(named.id.as_str()) == self.show.on())?;
        show::key_of(&self.forest, on)
    }

    /// Take the ring off a bead a collection has taken away: one this bead no
    /// longer names, or one no tree draws any more.
    ///
    /// A ring is an offer to press `Enter`, and the offer has to go when what
    /// it points at does. Left standing it is drawn on whichever bead has
    /// taken that row, so the reader sees a ring that has not moved and a key
    /// that goes somewhere they never pointed at.
    fn settle_ring(&mut self) {
        if self.show.on().is_none() {
            return;
        }
        let still_there = show::selected(&self.forest)
            .map(show::related)
            .unwrap_or_default()
            .into_iter()
            .find(|named| Some(named.id.as_str()) == self.show.on())
            .is_some_and(|named| show::followable(&self.forest, named));
        if !still_there {
            self.show.go_nowhere();
        }
    }

    /// Follow the reference the ring is on, reporting whether the window
    /// moved.
    ///
    /// The selection moves to the bead, and the window follows it there
    /// because the window is drawn from the selection. What is kept to come
    /// back to is where the reader was — the copy of the bead they were
    /// reading, and the row of it they pressed on.
    fn follow_related(&mut self) -> bool {
        let Some(key) = self.related_key() else {
            return false;
        };
        let Some(came_from) = self.forest.place().cloned() else {
            return false;
        };
        if !self.forest.go_to(&key) {
            return false;
        }
        self.trail.push((came_from, self.show.clone()));
        self.show = Show::default();
        self.viewing = Some(key);
        self.moved(true);
        true
    }

    /// Go back to the bead the reader followed a reference from, reporting
    /// whether there was one to go back to.
    ///
    /// A bead the forest has stopped drawing since is passed over rather than
    /// landed on, so a collection that takes a step of the way back out of
    /// the tree leaves the reader further back rather than nowhere.
    ///
    /// The ring that comes back with it is settled here as well, because a
    /// collection settles the window the reader is looking at and reaches
    /// none of the ones parked behind it. The way back is where a stale one
    /// arrives.
    fn retrace(&mut self) -> bool {
        while let Some((place, show)) = self.trail.pop() {
            if self.forest.go_to_place(&place) {
                self.show = show;
                self.viewing = self.selected_bead().cloned();
                self.settle_ring();
                self.moved(true);
                return true;
            }
        }
        false
    }

    /// The bead the selection is on: a bead's own row, or a tree's header,
    /// which carries its root.
    fn selected_bead(&self) -> Option<&BeadKey> {
        self.forest.lines().get(self.forest.selected_line())?.bead()
    }
}

/// The alternate screen, and what is drawn on it.
///
/// The terminal is on the alternate screen, in raw mode and reporting the
/// mouse for as long as this lives, so dropping it puts the terminal back
/// however the loop ended. `ratatui::init` hooks panics as well, and `Drop`
/// runs as the panic unwinds, so a crash does not leave a wedged tty behind
/// either. A signal arrives as an event the loop returns on, so it is the
/// same drop again rather than a second way of restoring anything.
pub(super) struct Screen {
    terminal: DefaultTerminal,
    shown: Shown,
}

impl Screen {
    pub(super) fn showing(
        snapshot: Snapshot,
        panes: Box<dyn Panes>,
        at_startup: Vec<Notice>,
        drawing: Drawing,
        started: DateTime<Utc>,
    ) -> anyhow::Result<Self> {
        let terminal = ratatui::try_init()?;
        // Built before the mouse is asked for, so that a terminal which
        // refuses is still put back by the `Drop` this now has.
        let screen = Self {
            terminal,
            shown: Shown::of(
                snapshot,
                panes,
                Box::new(io::stdout()),
                drawing,
                at_startup,
                started,
            ),
        };

        // Capture costs the reader the terminal's own mouse: while `bdi` is
        // up, dragging over the window no longer selects text in it. It is
        // taken anyway and unconditionally, because in the terminal this is
        // read in it costs less than it looks. herdr owns the mouse above
        // the pane and keeps its copy mode, which selects by keyboard; kitty
        // keeps its shift-drag, which bypasses whatever the application
        // grabbed. So what is given up is drag-selection inside one pane,
        // and what is bought is the pointer working at all.
        execute!(io::stdout(), EnableMouseCapture)?;

        // Nothing above has erased anything: entering the alternate screen is
        // the terminal's business, and the first frame writes only the cells
        // it has ink for, so every cell it leaves blank keeps whatever the
        // terminal was showing there. Erasing here is what makes the screen
        // `bdi`'s.
        //
        // Not `terminal.clear()`, which opens by asking the terminal where
        // the cursor is and waiting for the reply.
        execute!(io::stdout(), Clear(ClearType::All))?;

        Ok(screen)
    }
}

/// One frame: the forest, the tail beneath it, the height the forest is told
/// it has, and the window over it when one is up — the bindings, or a bead.
///
/// Outside the `terminal.draw` closure so a test backend can drive the whole
/// frame. This is the only place the three bands are agreed on, and `^D` and
/// `^U` are the part of that agreement nothing on screen would show was
/// broken. A window goes on last because it sits over the forest rather
/// than in place of it.
/// What the foot says about where a search got to.
///
/// The forest reports what it did and this decides what to say about it, so
/// the forest goes on knowing nothing about the foot.
fn said_of(landed: forest::Landed) -> Said {
    match landed {
        forest::Landed::Nowhere(sought) => Said::NothingMatched(sought),
        forest::Landed::On { key, at, of } => Said::Matched { key, at, of },
    }
}

#[allow(clippy::too_many_arguments)]
fn paint(
    frame: &mut Frame,
    forest: &mut Forest,
    layout: &Layout,
    tail: draw::Band<'_>,
    over: Over<'_>,
    foot: draw::Foot,
    collecting: &[Awaited],
    now: DateTime<Utc>,
) {
    let bands = draw::regions(frame.area());
    forest.fit(bands.forest.height as usize);
    draw::draw(frame, frame.area(), forest, layout, collecting, now, foot);
    draw::draw_tail(frame, bands.tail, tail);
    match over {
        Over::Nothing => {}
        Over::Bindings => key_bindings(frame, frame.area(), &bindings()),
        Over::Bead(show) => {
            if let Some(node) = show::selected(forest) {
                // Whether any bead this one names can be gone to is the
                // forest's to answer, and the title says which keys are worth
                // pressing on the strength of it.
                let follows = show::related(node)
                    .into_iter()
                    .any(|related| show::followable(forest, related));
                show::show(frame, frame.area(), node, show, follows);
            }
        }
    }
}

/// The window over the forest, where one is up, with what drawing it needs:
/// the loop's `Showing`, met by the view the screen holds for it.
enum Over<'a> {
    Nothing,
    Bindings,
    Bead(&'a mut Show),
}

#[cfg(panic = "abort")]
compile_error!(
    "putting the terminal back is `Screen`'s `Drop`, and a build with \
     `panic = \"abort\"` runs no `Drop`: a panic under it leaves the alternate \
     screen up, the terminal in raw mode, and the mouse reporting every move"
);

impl Drop for Screen {
    fn drop(&mut self) {
        // Ahead of the restore, mirroring the order they were turned on in.
        // A terminal left reporting the mouse writes an escape sequence into
        // whatever runs next for every cell the pointer crosses, and there
        // is nothing left running to ask it to stop.
        //
        // Every way the run can end comes through here — the loop returning
        // on 'q', a panic unwinding, and a signal, which the loop answers by
        // returning.
        let _ = execute!(io::stdout(), DisableMouseCapture);
        ratatui::restore();
    }
}

impl View for Screen {
    fn collected(&mut self, snapshot: Snapshot) {
        self.shown.collected(snapshot);
    }

    fn collecting(&mut self, awaited: &[Awaited]) -> bool {
        self.shown.collecting(awaited)
    }

    fn holds_for(&self, drawn_at: DateTime<Utc>) -> Option<Duration> {
        self.shown.holds_for(drawn_at)
    }

    fn tailed(&mut self, answer: Answer, now: DateTime<Utc>) -> bool {
        self.shown.tailed(answer, now)
    }

    fn reread(&mut self, now: DateTime<Utc>) {
        self.shown.reread(now);
    }

    fn reloaded(&mut self, reloaded: Reloaded<'_>, now: DateTime<Utc>) -> bool {
        self.shown.reloaded(reloaded, now)
    }

    fn rereads_in(&self, now: DateTime<Utc>) -> Option<Duration> {
        self.shown.rereads_in(now)
    }

    fn pressed(&mut self) -> bool {
        self.shown.pressed()
    }

    fn apply(&mut self, action: Action) -> bool {
        self.shown.apply(action)
    }

    fn typing(&mut self, typing: Typing) -> bool {
        self.shown.typing(typing)
    }

    fn scroll(&mut self, motion: Motion) -> bool {
        self.shown.scroll(motion)
    }

    fn scrolled(&mut self, notch: Notch) -> bool {
        self.shown.scrolled(notch)
    }

    fn scrolled_bead(&mut self, notch: Notch) -> bool {
        self.shown.scrolled_bead(notch)
    }

    fn bead_still_shown(&self) -> bool {
        self.shown.bead_still_shown()
    }

    fn follow(&mut self) -> bool {
        self.shown.follow_related()
    }

    fn retrace(&mut self) -> bool {
        self.shown.retrace()
    }

    fn clicked(&mut self, row: u16) -> bool {
        let screen = self.terminal.get_frame().area();
        self.shown.clicked(screen, row)
    }

    fn clicked_bead(&mut self, row: u16) -> Landed {
        let screen = self.terminal.get_frame().area();
        self.shown.clicked_bead(screen, row)
    }

    fn draw(&mut self, showing: Showing, now: DateTime<Utc>) -> anyhow::Result<()> {
        let says = self.shown.says(now);
        let Shown {
            forest,
            tail,
            show,
            collecting,
            said,
            sought,
            drawing,
            ..
        } = &mut self.shown;
        let over = match showing {
            Showing::Forest | Showing::Searching => Over::Nothing,
            Showing::Bindings => Over::Bindings,
            Showing::Bead => Over::Bead(show),
        };
        let foot = draw::Foot {
            standing: &says,
            said: said.as_ref(),
            prompt: sought.as_deref(),
            keys: &key_row(),
        };
        let band = draw::Band {
            tail,
            background: drawing.background,
        };
        self.terminal.draw(|frame| {
            paint(
                frame,
                forest,
                &drawing.layout,
                band,
                over,
                foot,
                collecting,
                now,
            )
        })?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::Wanted;
    use crate::collect::run::{FailureKind, RunFailure};
    use crate::config::Scope;
    use crate::model::edges::Related;
    use crate::model::join::{AgentRef, BeadKey, JoinSource};
    use crate::model::snapshot::{
        a_provider, Counts, Filter, Node, ProviderState, TrackerState, Tree,
    };
    use crate::model::tree::Link;
    use crate::model::types::testing::key as pane_key;
    use crate::model::types::{Edge, PaneStatus, Status};
    use crate::tui::fixtures::{a_snapshot, atlas, ferry, reading, PATIENCE};
    use crate::tui::keys::tests::key;
    use crate::tui::keys::{action, BINDINGS};
    use crate::view::bindings::bindings_window;
    use crate::view::lines::{Content, GroupKind};
    use crate::view::painted::{Painted, Run};
    use crate::view::row::Cell;
    use crate::view::walk::{self, Rows};
    use crate::view::Motion;
    use base64::prelude::{Engine as _, BASE64_STANDARD};
    use chrono::Utc;
    use ratatui::crossterm::event::KeyCode;
    use ratatui::layout::Rect;
    use ratatui::style::{Color, Modifier};
    use ratatui::widgets::Block;
    use std::collections::BTreeMap;
    use std::sync::{Arc, Mutex};

    /// What the bindings window has inside its border, one string per row,
    /// with the forest it sits over left out. Trailing blanks are trimmed, so
    /// anything the window failed to clear survives into the assertion.
    fn window_inner(width: u16, height: u16) -> Vec<String> {
        let mut forest = forest::flatten(a_grove(30));
        let screen = screen_of(
            &mut forest,
            &Tail::Silent("nothing to tail"),
            width,
            height,
            Over::Bindings,
        )
        .rows();
        let inner =
            Block::bordered().inner(bindings_window(Rect::new(0, 0, width, height), &bindings()));

        (inner.y..inner.y + inner.height)
            .map(|y| {
                screen[y as usize]
                    .chars()
                    .skip(inner.x as usize)
                    .take(inner.width as usize)
                    .collect::<String>()
                    .trim_end()
                    .to_string()
            })
            .collect()
    }

    /// The instant a test frame is drawn at. Nothing in these fixtures has
    /// been read, so no line quotes it; it is here because a frame is always
    /// drawn at some instant and a test must not pick a moving one.
    fn an_instant() -> DateTime<Utc> {
        use chrono::TimeZone;
        Utc.with_ymd_and_hms(2026, 8, 30, 10, 22, 14).unwrap()
    }

    /// A run that found everything it looked for at startup, so the foot
    /// begins with nothing on it but the keys.
    fn nothing_said() -> Vec<Notice> {
        Vec::new()
    }

    /// The bead this view exists for: a binding added to the table and left
    /// out of the view is the failure being guarded against, so the view is
    /// asserted against the table rather than against a list beside it.
    #[test]
    fn the_key_bindings_view_names_every_binding_the_mapping_holds() {
        let drawn = window_inner(100, BINDINGS.len() as u16 + 2);

        for binding in BINDINGS {
            let named = binding
                .keys
                .iter()
                .map(|bound| bound.named)
                .collect::<Vec<_>>()
                .join(", ");
            assert!(
                drawn
                    .iter()
                    .any(|row| row.contains(&named) && row.contains(binding.does)),
                "{named} ({}) has no line in {drawn:#?}",
                binding.does
            );
        }
    }

    /// The bead's short terminal, decided rather than left to a cut: as many
    /// bindings as fit from the top of the table, then a count of what is
    /// missing. Nothing is drawn with its bottom sheared off, and what
    /// survives is the half a reader could not have guessed.
    ///
    /// The way out is the window's title rather than a row, so it is checked
    /// on the border above these.
    #[test]
    fn eight_rows_hold_the_keys_worth_most_and_a_count_of_the_rest() {
        assert_eq!(
            window_inner(80, 8),
            vec![
                "  Enter     show the selected bead, or focus its pane from the bead view",
                "  f         focus the selected bead's pane",
                "  Space     fold or unfold the selected node",
                "  a         show every tree, not only those with a live agent",
                "  ?         show these key bindings",
                "  … 23 more bindings · no room on a screen this short",
            ]
        );
    }

    /// A reader who cannot see how to leave is stuck in a view they may have
    /// opened by accident, so the way out is the one thing a window too short
    /// for any binding at all still carries.
    #[test]
    fn the_way_out_is_the_windows_title_however_short_the_screen() {
        for height in [8, 24] {
            let window = bindings_window(Rect::new(0, 0, 80, height), &bindings());
            let mut forest = forest::flatten(a_grove(30));
            let screen = screen_of(
                &mut forest,
                &Tail::Silent("nothing to tail"),
                80,
                height,
                Over::Bindings,
            )
            .rows();

            assert!(
                screen[window.y as usize].contains("Key bindings · press any key to close"),
                "no way out on the window's own top row at {height} rows: {:?}",
                screen[window.y as usize]
            );
        }
    }

    /// The bead: a reader opens `?` to look up the key for the row they are
    /// on, so that row has to still be on the screen. The full-screen view
    /// this replaced took the whole forest away.
    ///
    /// Asserted a row taller than the table, which is where the property is
    /// the window's rather than the table's. The table wants a row per
    /// binding plus its two borders, and it has outgrown a twenty-four-row
    /// screen — so on the terminal size everything else here is measured at,
    /// the forest survives in the columns beside the window and in no row
    /// above or below it. That is the clamp doing what it does on every
    /// screen too short for the table.
    ///
    /// The width is the half that binds now. A `does:` line long enough to
    /// take the window to the full eighty columns takes the forest away in
    /// the other direction, which is the same defect the height clamp exists
    /// to avoid — so this is what a binding's wording is measured against.
    ///
    /// Nothing here fires when the table outgrows a given terminal, because
    /// that crossing is not an event: `bindings_window` says why the screen is
    /// the only ceiling, and `every_binding_is_drawn_or_counted_at_every_height`
    /// beside it is what watches the growth instead, over every size of table
    /// rather than at one height.
    #[test]
    fn the_forest_is_still_drawn_around_the_bindings_window() {
        let tall = bindings().len() as u16 + 3;
        let mut forest = forest::flatten(a_grove(30));
        let tail = Tail::Silent("nothing to tail");
        let alone = screen_of(&mut forest, &tail, 80, tall, Over::Nothing).rows();
        let over = screen_of(&mut forest, &tail, 80, tall, Over::Bindings).rows();
        let window = bindings_window(Rect::new(0, 0, 80, tall), &bindings());

        assert!(
            window.height < tall && window.width < 80,
            "a window the size of the screen is the view this replaced: {window:?}"
        );

        let beside = window.x as usize;
        assert!(
            beside > 0,
            "no forest is left beside a window flush to the edge"
        );

        for (n, (row, was)) in over.iter().zip(alone.iter()).enumerate() {
            if !(window.y..window.y + window.height).contains(&(n as u16)) {
                assert_eq!(
                    row, was,
                    "row {n} is above or below the window and changed anyway"
                );
                continue;
            }
            let left: String = row.chars().take(beside).collect();
            assert_eq!(
                left,
                was.chars().take(beside).collect::<String>(),
                "the forest beside the window on row {n}"
            );
        }
    }

    /// `Clear` is what stops the trees showing between the bindings. Every
    /// row is asserted whole, so forest text surviving in the columns a
    /// shorter binding does not reach is a failure rather than a trim.
    ///
    /// On a screen tall enough for the whole table, taken from the table
    /// rather than written down: a height too short for it would cut the
    /// bottom rows off and this would stop asserting them, silently and
    /// without failing.
    #[test]
    fn no_forest_shows_through_the_bindings_window() {
        assert_eq!(
            window_inner(80, bindings().len() as u16 + 3),
            vec![
                "  Enter     show the selected bead, or focus its pane from the bead view",
                "  f         focus the selected bead's pane",
                "  Space     fold or unfold the selected node",
                "  a         show every tree, not only those with a live agent",
                "  ?         show these key bindings",
                "  F         draw the selected bead as the only root, or put the forest back",
                "  /         find part of a bead's id or title, wherever the forest draws it",
                "  n         go to the next bead matching the search",
                "  N         go to the one before it",
                "  q, ^C     quit",
                "  Esc       go back to the forest from the bead view",
                "  Tab       move to the next bead the shown bead names; Enter follows it",
                "  ^R        collect from the trackers again now",
                "  e         expand the selected node and everything under it",
                "  E         expand the whole forest",
                "  c         collapse the selected node and everything under it",
                "  C         collapse the whole forest",
                "  d         restore the default folds under the selected node",
                "  D         restore the default folds across the whole forest",
                "  y         copy the selected bead's id to the clipboard",
                "  Down, j   move down one row",
                "  Up, k     move up one row",
                "  Right, l  expand, or move to the first child when it is already expanded",
                "  Left, h   collapse, or move to the parent when it is already collapsed",
                "  ^D, PgDn  move down half a screen",
                "  ^U, PgUp  move up half a screen",
                "  Home, g   move to the first row",
                "  End, G    move to the last row",
            ]
        );
    }

    /// A window two columns narrower than the screen it sits in, on the
    /// narrowest screen anyone uses. `q, ^C quit` is the line that must
    /// survive: a reader who cannot find it is stuck.
    ///
    /// Tall enough for the whole table, taken from the table rather than
    /// written down, because this is about what forty columns cost and a
    /// height that has to be revisited when a binding is added would answer
    /// about the rows instead.
    #[test]
    fn a_forty_column_screen_keeps_the_keys_and_cuts_only_what_it_must() {
        let tall = bindings().len() as u16 + 3;
        let window = bindings_window(Rect::new(0, 0, 40, tall), &bindings());
        assert_eq!(
            window.width, 40,
            "a window wider than the screen has to clamp"
        );

        let drawn = window_inner(40, tall);

        assert_eq!(row_naming(&drawn, "q, ^C"), "  q, ^C     quit");
        assert_eq!(
            drawn[0], "  Enter     show the selected bead, o…",
            "a line too long for forty columns, cut with the cut marked"
        );
        assert_eq!(
            row_naming(&drawn, "Right, l"),
            "  Right, l  expand, or move to the fi…"
        );
        assert_eq!(drawn.len(), BINDINGS.len(), "a narrow screen loses no rows");
    }

    /// The one drawn row whose keys are the ones named, whichever row that
    /// turns out to be.
    fn row_naming<'a>(drawn: &'a [String], keys: &str) -> &'a str {
        drawn
            .iter()
            .find(|row| row.trim_start().starts_with(keys))
            .unwrap_or_else(|| panic!("no row names {keys}: {drawn:#?}"))
    }

    /// The row is cut from its own end, so one that outgrew the narrowest
    /// screen anyone uses would lose `q quit` — which is what a reader who
    /// cannot get out is looking for. `bdi-2bb.12` cut `^R` from it to make
    /// room for keys named in words, and it has been full to the column ever
    /// since: expanding and collapsing the whole forest and restoring the
    /// default are named in `?` alone for exactly that reason.
    #[test]
    fn the_row_under_the_tail_is_drawn_whole_on_the_narrowest_screen() {
        let mut forest = an_open_grove(30);
        let screen = screen_of(
            &mut forest,
            &Tail::Silent("nothing to tail"),
            40,
            24,
            Over::Nothing,
        )
        .rows();

        assert_eq!(
            screen.last().expect("a screen with rows on it").trim_end(),
            key_row()
        );
    }

    /// A tree with enough beads under it that a half-screen motion has room
    /// to land somewhere that says how far it moved.
    fn a_grove(beads: usize) -> Snapshot {
        a_grove_of((1..=beads).collect())
    }

    /// The same grove, with its children in the order a tracker would report
    /// them after every one of them changed priority.
    fn a_grove_reordered(beads: usize) -> Snapshot {
        a_grove_of((1..=beads).rev().collect())
    }

    fn a_grove_of(children: Vec<usize>) -> Snapshot {
        let bead = |id: String| Node {
            id,
            title: "a bead in the grove".to_string(),
            status: Status::InProgress,
            issue_type: "task".to_string(),
            priority: 2,
            ready: true,
            blocked_by: Vec::new(),
            started_at: None,
            closed_at: None,
            badges: Vec::new(),
            undrawn: Vec::new(),
            agent: None,
            anomalies: Vec::new(),
            description: String::new(),
            notes: String::new(),
            owner: None,
            parent: None,
            depends_on: Vec::new(),
            blocks: Vec::new(),
        };

        let mut beads = vec![bead("grv-1".to_string())];
        beads.extend(children.iter().map(|n| bead(format!("grv-1.{n}"))));
        let mut links = vec![(1..beads.len())
            .map(|bead| Link {
                bead,
                edge: Edge::ParentChild,
                first: true,
            })
            .collect()];
        links.resize(beads.len(), Vec::new());

        let tree = Arc::new(Tree {
            project: "grove".to_string(),
            root: "grv-1".to_string(),
            title: "a tree with a great many beads".to_string(),
            counts: Counts {
                total: children.len(),
                closed: 0,
                live_agents: 0,
                anomalies: 0,
            },
            tracker: TrackerState::Ok,
            beads,
            children: links,
            dangling: Vec::new(),
            cycles: Vec::new(),
        });

        Snapshot {
            filter: Filter::All,
            trees: vec![Arc::clone(&tree)],
            collected: vec![tree],
            ..a_snapshot_of(Vec::new())
        }
    }

    fn a_snapshot_of(trees: Vec<Arc<Tree>>) -> Snapshot {
        Snapshot {
            generated_at: Utc::now(),
            agents: a_provider(ProviderState::Answering),
            filter: Filter::LiveAgents,
            trees: trees.clone(),
            hidden_trees: Vec::new(),
            failed_projects: Vec::new(),
            unattributed: Vec::new(),
            unconfigured: Vec::new(),
            conflicts: Vec::new(),
            projects_named_without_git: Vec::new(),
            read_at: BTreeMap::new(),
            collected: trees,
            projects: vec!["grove".to_string()],
            scope: Scope::default(),
        }
    }

    /// One frame, drawn as `paint` draws it, on a session with nothing to
    /// say at its foot but the keys and whatever the reader just copied.
    /// What the reader's last keystroke left on the foot: what it came to,
    /// and what they have typed into the prompt while one is up. One argument
    /// because they are one row's worth of the same thing — the press the
    /// reader has just made — and because the frame takes enough already.
    #[derive(Default)]
    struct Pressed<'a> {
        said: Option<&'a Said>,
        prompt: Option<&'a str>,
    }

    fn painted(
        forest: &mut Forest,
        tail: &Tail,
        over: Over<'_>,
        pressed: Pressed<'_>,
        collecting: &[Awaited],
        width: u16,
        height: u16,
    ) -> Painted {
        let keys = key_row();
        let foot = draw::Foot {
            standing: &[],
            said: pressed.said,
            prompt: pressed.prompt,
            keys: &keys,
        };
        Painted::drawn_by(width, height, |frame| {
            paint(
                frame,
                forest,
                &Layout::default(),
                draw::Band {
                    tail,
                    background: Background::Dark,
                },
                over,
                foot,
                collecting,
                an_instant(),
            );
        })
    }

    fn screen_of(
        forest: &mut Forest,
        tail: &Tail,
        width: u16,
        height: u16,
        over: Over<'_>,
    ) -> Painted {
        painted(forest, tail, over, Pressed::default(), &[], width, height)
    }

    /// The screen with the bead view up, drawn from the view the screen is
    /// holding rather than a fresh one, so a motion between two draws is a
    /// motion of the same view.
    fn bead_view(shown: &mut Shown, width: u16, height: u16) -> Vec<String> {
        let (forest, tail, show) = (&mut shown.forest, &shown.tail, &mut shown.show);
        screen_of(forest, tail, width, height, Over::Bead(show)).rows()
    }

    /// The same screen with a collection in flight, so a project line the
    /// collection names says what it is doing.
    fn screen_collecting(
        forest: &mut Forest,
        tail: &Tail,
        collecting: &[Awaited],
        width: u16,
        height: u16,
    ) -> Painted {
        painted(
            forest,
            tail,
            Over::Nothing,
            Pressed::default(),
            collecting,
            width,
            height,
        )
    }

    /// `bdi-7ao.51`, on the screen a reader is looking at rather than in any
    /// one of the cells beneath it: a collection that has stopped answering is
    /// drawn as having stopped, where one still under way turns.
    ///
    /// The two are asserted together and from one fixture, because the defect
    /// was never that either state drew wrongly — it was that they drew the
    /// same, and a test that only knew what a hung tracker looks like could
    /// not have told.
    #[test]
    fn a_screen_says_which_of_its_projects_have_stopped_answering() {
        let mut snapshot = a_grove(2);
        snapshot.read_at.insert(
            "grove".to_string(),
            an_instant() - chrono::TimeDelta::seconds(30),
        );
        let mark = |asked_at| {
            let mut forest = forest::flatten(snapshot.clone());
            let row = screen_collecting(
                &mut forest,
                &Tail::Silent("nothing to tail"),
                &[reading(Wanted::Everything, asked_at)],
                60,
                10,
            )
            .rows()[0]
                .clone();
            assert!(row.contains("grove"), "the project's own line: {row:?}");
            row
        };

        assert!(
            mark(an_instant() - PATIENCE).contains("⠿ 30s ago"),
            "a collection past its patience: {:?}",
            mark(an_instant() - PATIENCE)
        );
        assert!(
            !mark(an_instant()).contains(''),
            "a collection just asked for: {:?}",
            mark(an_instant())
        );
    }

    /// Nothing on screen shows that `^D` moved by the wrong amount, so the
    /// frame is what says the forest was told how tall it is.
    #[test]
    fn a_frame_tells_the_forest_how_far_a_half_screen_is() {
        let mut forest = an_open_grove(30);

        forest.apply(Action::Move(Motion::HalfScreenDown));
        assert_eq!(
            forest.selected_line(),
            2,
            "a forest no frame has measured has no band to halve, so it moves \
             a row rather than nowhere"
        );

        let mut forest = an_open_grove(30);
        screen_of(
            &mut forest,
            &Tail::Silent("nothing to tail"),
            60,
            24,
            Over::Nothing,
        )
        .rows();
        forest.apply(Action::Move(Motion::HalfScreenDown));

        assert_eq!(
            forest.selected_line(),
            9,
            "half of the sixteen rows the forest was given, not half the frame"
        );
    }

    /// The provider, remembering what it was asked and answering nothing.
    ///
    /// Nothing here answers, because nothing in `Shown` waits for an answer:
    /// what the provider said arrives through `tailed`, and a test hands it one
    /// itself, whenever it likes and about whichever pane it likes.
    #[derive(Clone, Default)]
    struct Asking {
        reads: Arc<Mutex<Vec<String>>>,
        focuses: Arc<Mutex<Vec<String>>>,
    }

    impl Asking {
        fn reads(&self) -> Vec<String> {
            self.reads
                .lock()
                .expect("no test panics holding this")
                .clone()
        }

        fn focuses(&self) -> Vec<String> {
            self.focuses
                .lock()
                .expect("no test panics holding this")
                .clone()
        }
    }

    impl Panes for Asking {
        fn read(&self, pane: &PaneKey, lines: u16) {
            self.reads
                .lock()
                .expect("no test panics holding this")
                .push(format!("{} {lines}", pane.id));
        }

        fn focus(&self, pane: &PaneKey) {
            self.focuses
                .lock()
                .expect("no test panics holding this")
                .push(pane.id.clone());
        }
    }

    /// What the provider said about a pane it read.
    fn read(pane: &str, lines: &[&str]) -> Answer {
        Answer::Read {
            pane: pane_key(pane),
            read: Ok(lines.iter().map(|line| (*line).to_string()).collect()),
        }
    }

    impl Rows for Shown {
        fn rows(&self) -> usize {
            self.forest.rows()
        }
    }

    /// Press down until the selection is on the last row, and say how many
    /// presses moved it.
    fn to_the_last_row(shown: &mut Shown) -> usize {
        let rows = shown.rows();
        let from = shown.forest.selected_line();

        let moved = walk::until(
            shown,
            |shown| shown.forest.selected_line() + 1 == rows,
            |shown| {
                shown.apply(Action::Move(Motion::NextRow));
            },
            |shown| {
                format!(
                    "a walk from row {from} of {rows} stopped at row {}",
                    shown.forest.selected_line()
                )
            },
        );

        assert_eq!(
            moved,
            rows - 1 - from,
            "a walk from row {from} of {rows} reaches the last row in one press per row after it"
        );
        moved
    }

    /// Press the key at `code` the way the loop presses it: through the
    /// table, so a test here fails when the key is bound to nothing.
    fn press(shown: &mut Shown, code: KeyCode) -> bool {
        let asked = action(key(code)).unwrap_or_else(|| panic!("{code:?} is bound to nothing"));
        shown.apply(asked)
    }

    /// Home from the bottom of a grove taller than the screen: the selection
    /// is on the first row and the band has scrolled back up to draw it.
    #[test]
    fn home_puts_the_selection_on_the_first_row_from_anywhere() {
        let mut shown = shown(a_grove(30));
        let root = |band: &[String]| band.iter().any(|row| row.contains("grv-1 "));
        assert!(
            root(&forest_band(&mut shown, 60, 24)),
            "the walk starts with the root on screen, and that frame is what \
             tells the forest how tall its band is"
        );

        to_the_last_row(&mut shown);
        assert!(
            !root(&forest_band(&mut shown, 60, 24)),
            "the fixture has to scroll the root off the screen first"
        );

        assert!(press(&mut shown, KeyCode::Home));

        assert_eq!(shown.forest.selected_line(), 0);
        let band = forest_band(&mut shown, 60, 24);
        assert!(root(&band), "{band:#?}");
    }

    /// End from partway down: the selection is on the last row and the band
    /// has scrolled down to draw it.
    #[test]
    fn end_puts_the_selection_on_the_last_row_from_anywhere() {
        let mut shown = shown(a_grove(30));
        let rows = shown.rows();
        walk::until(
            &mut shown,
            |shown| shown.forest.selected_line() >= 3,
            |shown| {
                shown.apply(Action::Move(Motion::NextRow));
            },
            |shown| format!("stopped at row {}", shown.forest.selected_line()),
        );
        let last = |band: &[String]| band.iter().any(|row| row.contains(" .30 "));
        assert!(
            !last(&forest_band(&mut shown, 60, 24)),
            "the fixture has to start with the last row off the screen"
        );

        assert!(press(&mut shown, KeyCode::End));

        assert_eq!(shown.forest.selected_line() + 1, rows);
        let band = forest_band(&mut shown, 60, 24);
        assert!(last(&band), "{band:#?}");
    }

    /// A selection already at the end it was sent to stays where it is.
    #[test]
    fn home_and_end_move_nothing_when_the_selection_is_already_there() {
        let mut shown = shown(a_grove(6));
        press(&mut shown, KeyCode::Home);
        let at_home = shown.forest.selected_line();

        assert!(!press(&mut shown, KeyCode::Home));
        assert_eq!(shown.forest.selected_line(), at_home);

        press(&mut shown, KeyCode::End);
        let at_end = shown.forest.selected_line();

        assert!(!press(&mut shown, KeyCode::End));
        assert_eq!(shown.forest.selected_line(), at_end);
    }

    /// The provider refusing to bring a pane to the front.
    fn refused(pane: &str) -> Answer {
        Answer::Focused {
            pane: pane_key(pane),
            focused: Err(RunFailure {
                kind: FailureKind::Gone,
                program: "a provider".to_string(),
                detail: "the test said so".to_string(),
                unreadable: None,
            }),
        }
    }

    /// The grove with its root opened by hand. Nobody is working in it and
    /// nothing is wrong with it, so the fold default rests it as its header,
    /// and what these tests are about is the rows under it.
    /// The grove with its tree open, which is how it rests: every bead in it
    /// is ready and the fold opens down to ready work. Asserted rather than
    /// toggled, because a toggle over a tree already open shuts it and takes
    /// every row under the header with it.
    fn an_open_grove(beads: usize) -> forest::Forest {
        let forest = forest::flatten(a_grove(beads));
        assert_eq!(
            forest.lines()[0].folded,
            Some(true),
            "the grove's beads are ready, so its tree rests open"
        );
        forest
    }

    /// How long the band waits after an answer before asking for its pane
    /// again, for every screen here. Never slept: the tests that are about
    /// it hand the screen instants a chosen distance apart.
    const EVERY: Duration = Duration::from_millis(250);

    /// How far a notch moves every screen here, unless its own subject is
    /// the setting that says so.
    const A_NOTCH: usize = 3;

    /// A config settling exactly what every screen here already draws to, so
    /// a test whose subject is the foot is a test about the foot alone.
    fn the_config_in_force() -> Config {
        Config::naming(Vec::new())
    }

    /// What every screen here draws to, unless its own subject is one of the
    /// settings.
    fn drawing() -> Drawing {
        Drawing {
            tail_every: EVERY,
            background: Background::Dark,
            notch: A_NOTCH,
            layout: Layout::default(),
        }
    }

    fn shown(snapshot: Snapshot) -> Shown {
        Shown::of(
            snapshot,
            Box::new(Asking::default()),
            Box::new(io::sink()),
            drawing(),
            nothing_said(),
            an_instant(),
        )
    }

    /// The same, over a run that settled something about itself before its
    /// first collection, opened at the instant the caller names. Both matter
    /// together: what a startup notice does is measured from when the run
    /// started, so a screen whose start is not chosen cannot be asked about
    /// it.
    fn shown_saying(snapshot: Snapshot, at_startup: Vec<Notice>, started: DateTime<Utc>) -> Shown {
        Shown::of(
            snapshot,
            Box::new(Asking::default()),
            Box::new(io::sink()),
            drawing(),
            at_startup,
            started,
        )
    }

    /// The same, with the record of what the provider was asked kept beside it.
    fn shown_asking(snapshot: Snapshot) -> (Shown, Asking) {
        shown_asking_every(snapshot, EVERY)
    }

    /// The same again, waiting a gap of the caller's choosing rather than the
    /// one every other screen here waits.
    fn shown_asking_every(snapshot: Snapshot, every: Duration) -> (Shown, Asking) {
        let panes = Asking::default();
        (
            Shown::of(
                snapshot,
                Box::new(panes.clone()),
                Box::new(io::sink()),
                Drawing {
                    tail_every: every,
                    ..drawing()
                },
                nothing_said(),
                an_instant(),
            ),
            panes,
        )
    }

    /// The screen opens on a snapshot already collected, so there is nothing
    /// to say is running. Opening on a collection would set a mark turning on
    /// every project line that only the next refresh could take off.
    #[test]
    fn a_screen_opens_over_a_collection_that_has_already_finished() {
        assert_eq!(shown(a_snapshot()).collecting, []);
    }

    /// What is being read and since when, not whether something is: each
    /// project line answers for its own rows, so the screen is told the
    /// collection's own `Wanted` and asks that which projects it names — and
    /// the instant beside it, so a line can say the tracker has stopped
    /// answering rather than that a collection is under way.
    #[test]
    fn a_screen_holds_what_the_collection_in_flight_is_reading_and_since_when() {
        let mut shown = shown(a_snapshot());
        let reading_atlas = reading(atlas(), an_instant());

        shown.collecting(std::slice::from_ref(&reading_atlas));
        assert_eq!(shown.collecting, [reading_atlas]);

        shown.collecting(&[]);
        assert_eq!(shown.collecting, []);
    }

    /// The loop draws on a change and this is what it asks. Told again what
    /// it already says, the screen is no different and a redraw would put
    /// the same frame back — which a collection queued behind another does
    /// whenever the two name the same projects.
    #[test]
    fn a_screen_told_again_what_it_already_says_reports_no_change() {
        let mut shown = shown(a_snapshot());
        let at = an_instant();

        assert!(
            shown.collecting(&[reading(atlas(), at)]),
            "None to one project"
        );
        assert!(
            !shown.collecting(&[reading(atlas(), at)]),
            "the same collection again"
        );
        assert!(
            shown.collecting(&[reading(ferry(), at)]),
            "one project to another"
        );
        assert!(shown.collecting(&[]), "and back to nothing running");
        assert!(!shown.collecting(&[]), "which is also said only once");
    }

    /// A fresh collection of the projects the last one named is not the same
    /// collection, whatever it names: its wait starts over, and a line that
    /// went on counting from the first ask would report the tracker as having
    /// stopped answering seconds into a collection that had only just begun.
    #[test]
    fn a_screen_told_of_a_new_collection_of_the_same_projects_reports_a_change() {
        let mut shown = shown(a_snapshot());
        let at = an_instant();

        assert!(shown.collecting(&[reading(atlas(), at)]));
        assert!(shown.collecting(&[reading(atlas(), at + chrono::TimeDelta::seconds(1))]));
    }

    /// `codex review` on this change, and it is right: the foot said
    /// `collected 10:21:44`, which is true for as long as it is on the
    /// screen. An age is not. A `bdi` whose projects are all reported for
    /// polls nothing, so with no work moving it would sit saying `0s ago`
    /// for as long as the reader left it.
    #[test]
    fn a_screen_at_rest_over_a_read_goes_stale_and_says_when() {
        let mut snapshot = a_snapshot();
        let read = an_instant();
        snapshot.read_at.insert("orbital".to_string(), read);

        let shown = shown(snapshot);

        assert_eq!(
            shown.holds_for(read + chrono::TimeDelta::milliseconds(250)),
            Some(Duration::from_millis(750)),
            "the second it is saying is three quarters over"
        );
    }

    /// The soonest of them, because the newest read is the one whose words
    /// change first and the line must not be wrong in between.
    #[test]
    fn a_screen_holds_only_as_long_as_its_newest_read_does() {
        let mut snapshot = a_snapshot();
        let read = an_instant();
        snapshot.read_at.insert("ferry".to_string(), read);
        snapshot
            .read_at
            .insert("orbital".to_string(), read - chrono::TimeDelta::hours(2));

        let shown = shown(snapshot);

        assert_eq!(
            shown.holds_for(read + chrono::TimeDelta::seconds(4)),
            Some(Duration::from_secs(1)),
            "the four-second-old read, not the two-hour-old one"
        );
    }

    /// With nothing read there is no age on the screen, so the mark turning
    /// is the whole of what expires.
    #[test]
    fn a_screen_with_a_collection_on_it_and_no_age_holds_for_one_frame() {
        let mut shown = shown(a_snapshot());
        shown.collecting(&[reading(atlas(), an_instant())]);

        assert_eq!(shown.holds_for(an_instant()), Some(phrase::FRAME));
    }

    /// The other end of the same case, and the one a reviewer reads as the
    /// deadline failing to fire: a first collection that never answers leaves
    /// a still mark over no rows, and there is nothing in that cell for time
    /// alone to falsify. What carried the screen across the deadline was the
    /// turning mark, which was still running up to it.
    #[test]
    fn a_screen_whose_first_collection_stopped_answering_has_nothing_left_to_expire() {
        let mut shown = shown(a_snapshot());
        let asked_at = an_instant();
        shown.collecting(&[reading(atlas(), asked_at)]);

        assert_eq!(
            shown.holds_for(asked_at + chrono::TimeDelta::seconds(30)),
            None
        );
    }

    /// And with rows on the screen, a hung tracker comes off the frame clock
    /// and onto the age's. The mark has stopped moving, so redrawing it 12
    /// times a second for however long the tracker stays quiet would be
    /// wakeups for a screen that cannot change.
    #[test]
    fn a_hung_tracker_is_redrawn_for_its_rows_age_rather_than_for_a_still_mark() {
        let mut snapshot = a_snapshot();
        let read = an_instant();
        snapshot.read_at.insert("atlas".to_string(), read);
        let mut shown = shown(snapshot);
        shown.collecting(&[reading(atlas(), read)]);

        assert_eq!(
            shown.holds_for(read + chrono::TimeDelta::seconds(30)),
            Some(Duration::from_secs(1)),
            "the age turning over, not the frame the mark has stopped on"
        );
    }

    /// `bdi-7ao.58`: the age stays on the line under the turning mark, so it
    /// goes on expiring under it. A screen that held for a whole frame
    /// whenever a collection ran would leave `0s ago` on it into its second
    /// second — the mark turning the whole time and saying nothing about the
    /// age beside it.
    #[test]
    fn a_collection_in_flight_does_not_stop_the_ages_beneath_it_running_out() {
        let mut snapshot = a_snapshot();
        let read = an_instant();
        snapshot.read_at.insert("atlas".to_string(), read);
        let mut shown = shown(snapshot);
        shown.collecting(&[reading(atlas(), read)]);

        assert_eq!(
            shown.holds_for(read + chrono::TimeDelta::milliseconds(970)),
            Some(Duration::from_millis(30)),
            "the age turns over inside the frame the mark is on"
        );
    }

    /// And the other way: an age that is not going to change for another day
    /// leaves the turning mark deciding when the screen is next due.
    #[test]
    fn a_collection_over_day_old_rows_is_redrawn_for_the_mark_rather_than_the_age() {
        let mut snapshot = a_snapshot();
        let read = an_instant();
        let now = read + chrono::TimeDelta::seconds(86_400);
        snapshot.read_at.insert("atlas".to_string(), read);
        let mut shown = shown(snapshot);
        shown.collecting(&[reading(atlas(), now)]);

        assert_eq!(shown.holds_for(now), Some(phrase::FRAME));
    }

    /// Nothing read and nothing running: there is no age on the screen, so
    /// there is nothing for time alone to falsify and no reason to wake.
    #[test]
    fn a_screen_no_project_has_been_read_for_stays_true_however_long_it_is_left() {
        assert_eq!(shown(a_snapshot()).holds_for(an_instant()), None);
    }

    /// Where the cursor is, by the bead its line carries. `Forest` does not
    /// answer this: a tree's header line carries its root, so a caller that
    /// read the key without telling a header from a bead would tail the root
    /// of whatever tree the cursor's header stands for.
    fn cursor(shown: &Shown) -> Option<&BeadKey> {
        let forest = &shown.forest;
        forest.lines()[forest.selected_line()].bead()
    }

    fn bead(project: &str, id: &str) -> BeadKey {
        BeadKey {
            project: project.to_string(),
            id: id.to_string(),
        }
    }

    /// The band as drawn, not the selected index: a selection restored into a
    /// viewport that scrolled back to the top is the same bug wearing a
    /// different hat, and only the rows show the difference.
    fn forest_band(shown: &mut Shown, width: u16, height: u16) -> Vec<String> {
        let bands = draw::regions(Rect::new(0, 0, width, height));
        let rows = screen_of(&mut shown.forest, &shown.tail, width, height, Over::Nothing).rows();
        rows[..bands.forest.height as usize].to_vec()
    }

    /// The pane on the row a staffed grove opens with.
    const A_SELECTED_PANE: &str = "w:p0";

    /// The same grove with every bead saying something of itself, so the
    /// bead view has something to show that no row of the forest carries.
    fn a_described_grove(beads: usize) -> Snapshot {
        let mut snapshot = a_grove(beads);
        for tree in &mut snapshot.collected {
            let tree = Arc::make_mut(tree);
            for node in &mut tree.beads {
                node.description = format!("what {} is about", node.id);
            }
        }
        snapshot.trees = snapshot.collected.clone();
        snapshot
    }

    /// The rows inside the bead window's border, trimmed, with the forest
    /// around it left out.
    fn bead_window_inner(shown: &mut Shown, width: u16, height: u16) -> Vec<String> {
        let rows = bead_view(shown, width, height);
        let window = window_of(&rows);
        let (x, y) = (window.x as usize, window.y as usize);
        rows[y + 1..y + window.height as usize - 1]
            .iter()
            .map(|row| {
                row.chars()
                    .skip(x + 1)
                    .take(window.width as usize - 2)
                    .collect::<String>()
                    .trim()
                    .to_string()
            })
            .collect()
    }

    /// The bead window's rectangle, read off the screen by its corners.
    fn bead_window(shown: &mut Shown, width: u16, height: u16) -> Rect {
        window_of(&bead_view(shown, width, height))
    }

    /// The bead window's rectangle on the screen, by its corners: the title
    /// row's `┌` and `┐`, and the `└` beneath the first in the rows below.
    /// The forest's own `└──` connectors sit elsewhere on their rows.
    fn window_of(rows: &[String]) -> Rect {
        let y = rows
            .iter()
            .position(|row| row.contains("Esc to go back"))
            .expect("the bead window's title is on the screen");
        let top: Vec<char> = rows[y].chars().collect();
        let x = top.iter().position(|c| *c == '').unwrap();
        let right = top.iter().rposition(|c| *c == '').unwrap();
        let bottom = rows[y + 1..]
            .iter()
            .position(|row| row.chars().nth(x) == Some(''))
            .map(|n| y + 1 + n)
            .expect("the bead window's bottom edge is on the screen");
        Rect::new(
            x as u16,
            y as u16,
            (right - x + 1) as u16,
            (bottom - y + 1) as u16,
        )
    }

    /// A grove whose first bead's description runs to `lines` lines, so the
    /// bead is taller than any window a screen in these tests offers.
    fn a_grove_with_a_tall_bead(lines: usize) -> Snapshot {
        let mut snapshot = a_described_grove(6);
        let tree = Arc::make_mut(&mut snapshot.collected[0]);
        tree.beads[0].description = (1..=lines)
            .map(|n| format!("line {n} of the description"))
            .collect::<Vec<_>>()
            .join("\n");
        snapshot.trees = snapshot.collected.clone();
        snapshot
    }

    /// A grove whose first bead's description carries a heading, an item, a
    /// code span and emphasis.
    fn a_grove_with_a_marked_up_bead() -> Snapshot {
        let mut snapshot = a_described_grove(6);
        let tree = Arc::make_mut(&mut snapshot.collected[0]);
        tree.beads[0].description = "## Shape\n\n- keep `wrap` *soft*".to_string();
        snapshot.trees = snapshot.collected.clone();
        snapshot
    }

    /// `bdi-2bb.45`: the description is rendered as markdown in the window's
    /// own styling — a heading bold, an item behind a bullet, a code span in
    /// a tone of its own, emphasis italic — as the screen paints it.
    #[test]
    fn the_bead_window_styles_the_descriptions_markdown() {
        let mut shown = shown(a_grove_with_a_marked_up_bead());
        assert!(shown.apply(Action::ShowBead));
        let (forest, tail, show) = (&mut shown.forest, &shown.tail, &mut shown.show);
        let painted = screen_of(forest, tail, 80, 24, Over::Bead(show));

        let runs: Vec<Run> = (0..24).flat_map(|y| painted.row(y)).collect();
        let run_of = |said: &str| {
            runs.iter()
                .find(|run| run.said == said)
                .unwrap_or_else(|| panic!("{said:?} is drawn in a run of its own: {runs:#?}"))
                .clone()
        };
        assert!(run_of("Shape").style.add_modifier.contains(Modifier::BOLD));
        assert_eq!(run_of("wrap").style.fg, Some(Color::Cyan));
        assert!(run_of("soft").style.add_modifier.contains(Modifier::ITALIC));
        assert!(
            painted.rows().iter().any(|row| row.contains("• keep")),
            "{:#?}",
            painted.rows()
        );
    }

    /// `bdi-2bb.44`: the window follows the terminal rather than stopping at
    /// eighty columns. Both sides are four fifths of the screen's, centred, so
    /// a bigger terminal gets a bigger window and not the same box in the
    /// middle of a bigger forest.
    #[test]
    fn the_bead_window_is_four_fifths_of_the_screen_on_either_side() {
        let mut shown = shown(a_grove_with_a_tall_bead(100));
        assert!(shown.apply(Action::ShowBead));

        assert_eq!(bead_window(&mut shown, 120, 40), Rect::new(12, 4, 96, 32));
        assert_eq!(bead_window(&mut shown, 200, 60), Rect::new(20, 6, 160, 48));
    }

    /// A bead shorter than four fifths of the screen keeps a window its own
    /// height: the room is offered, not filled with nothing.
    #[test]
    fn a_short_bead_keeps_a_short_window_on_a_tall_screen() {
        let mut shown = shown(a_described_grove(6));
        assert!(shown.apply(Action::ShowBead));

        let window = bead_window(&mut shown, 200, 60);
        assert_eq!(window.width, 160);
        assert!(window.height < 48, "{window:?}");
        assert_eq!(
            bead_window_inner(&mut shown, 200, 60).len() + 2,
            window.height as usize,
            "the window is as tall as the bead and its border"
        );
    }

    /// A bead taller than four fifths of a big screen fills that height and
    /// scrolls for the rest, the title saying so, the same as on a small one.
    #[test]
    fn a_bead_taller_than_the_window_scrolls_by_motion_on_a_big_screen() {
        let mut shown = shown(a_grove_with_a_tall_bead(100));
        assert!(shown.apply(Action::ShowBead));

        let rows = bead_view(&mut shown, 200, 60);
        assert!(
            rows[6].contains("j, k to scroll"),
            "the title says the bead scrolls: {:?}",
            rows[6]
        );
        let top = bead_window_inner(&mut shown, 200, 60);
        assert_eq!(top.len(), 46);

        assert!(shown.scroll(Motion::NextRow));
        let down_one = bead_window_inner(&mut shown, 200, 60);
        assert_eq!(down_one[0], top[1]);

        assert!(shown.scroll(Motion::LastRow));
        let bottom = bead_window_inner(&mut shown, 200, 60);
        assert_eq!(bottom[45], "line 100 of the description");
        assert!(!shown.scroll(Motion::NextRow), "nothing below the last row");
    }

    /// The bead, with a bead row selected: Enter shows what `bd show` would
    /// say of it, from the rows `bdi` already holds — the fields the bead
    /// lists, and nothing a row of the forest could have carried.
    #[test]
    fn enter_on_a_bead_row_shows_the_bead() {
        let mut shown = shown(a_described_grove(6));
        assert_eq!(cursor(&shown), Some(&bead("grove", "grv-1")));

        assert!(shown.apply(Action::ShowBead));

        let inner = bead_window_inner(&mut shown, 80, 24);
        assert_eq!(inner[0], "◐ grv-1  a bead in the grove");
        assert!(inner.contains(&"DESCRIPTION".to_string()), "{inner:#?}");
        assert!(
            inner.contains(&"what grv-1 is about".to_string()),
            "{inner:#?}"
        );
    }

    /// A project's line is not a bead, so there is nothing to show: Enter
    /// there does nothing and says nothing, the same as before.
    #[test]
    fn enter_on_a_row_that_is_not_a_bead_does_nothing() {
        let mut shown = shown(a_described_grove(6));
        assert!(shown.select(0), "onto the project's own line");
        assert_eq!(cursor(&shown), None);
        let before = forest_band(&mut shown, 80, 24);

        assert!(!shown.apply(Action::ShowBead));

        assert_eq!(forest_band(&mut shown, 80, 24), before);
    }

    /// Put the selection on the hidden grove's row: the line over its
    /// project's hidden trees rests shut, so open it and step in.
    fn select_hidden_tree(shown: &mut Shown) {
        let group = shown
            .forest
            .lines()
            .iter()
            .position(|line| {
                matches!(&line.content, Content::Group(group) if group.kind == GroupKind::HiddenTrees)
            })
            .expect("the filter hid the grove");
        assert!(shown.forest.select_line(group));
        shown.apply(Action::ExpandOrChild);
        shown.apply(Action::ExpandOrChild);
    }

    /// A hidden tree's row names its root, so Enter there shows that bead
    /// as it does on any root's row: the filter took the tree off the
    /// screen, not the bead out of hand.
    #[test]
    fn enter_on_a_hidden_trees_row_shows_its_root() {
        let mut shown = shown(a_hidden_grove_above_a_shown_tree());
        select_hidden_tree(&mut shown);
        assert_eq!(cursor(&shown), Some(&bead("grove", "grv-1")));

        assert!(shown.apply(Action::ShowBead));

        let inner = bead_window_inner(&mut shown, 80, 24);
        assert_eq!(inner[0], "◐ grv-1  a bead in the grove");
    }

    /// Leaving the view puts the reader back on the row it was opened from,
    /// with the forest exactly as they left it: the motions that moved the
    /// bead moved nothing under it.
    #[test]
    fn leaving_the_bead_view_puts_the_reader_back_on_the_same_row() {
        let mut shown = shown(a_described_grove(30));
        forest_band(&mut shown, 80, 12);
        for _ in 0..4 {
            assert!(shown.apply(Action::Move(Motion::NextRow)));
        }
        let at = shown.forest.selected_line();
        let on = cursor(&shown).cloned();
        let before = forest_band(&mut shown, 80, 12);

        assert!(shown.apply(Action::ShowBead));
        bead_view(&mut shown, 80, 5);
        assert!(shown.scroll(Motion::NextRow), "the view had rows to scroll");
        assert!(shown.scroll(Motion::LastRow));
        bead_view(&mut shown, 80, 5);

        assert_eq!(shown.forest.selected_line(), at);
        assert_eq!(cursor(&shown).cloned(), on);
        assert_eq!(forest_band(&mut shown, 80, 12), before);
    }

    /// A motion while the bead is up moves the bead, and a motion that would
    /// move it nowhere reports no change: the row under it is not what the
    /// key is about.
    #[test]
    fn a_motion_in_the_bead_view_moves_the_bead_and_not_the_selection() {
        let mut shown = shown(a_described_grove(6));
        let at = shown.forest.selected_line();
        assert!(shown.apply(Action::ShowBead));
        let top = bead_window_inner(&mut shown, 80, 6);

        assert!(shown.scroll(Motion::NextRow));
        let down_one = bead_window_inner(&mut shown, 80, 6);

        assert_ne!(down_one, top);
        assert_eq!(down_one[0], top[1]);
        assert_eq!(shown.forest.selected_line(), at);
        assert!(shown.scroll(Motion::PreviousRow), "back to the top");
        assert!(
            !shown.scroll(Motion::PreviousRow),
            "and nowhere further, so nothing to redraw"
        );
        assert_eq!(shown.forest.selected_line(), at);
    }

    // ---- following a bead the window names --------------------------------

    /// A grove whose first child names three beads: its parent, which the
    /// forest draws; a bead the tracker's answer does not hold, which it
    /// cannot; and a sibling, which it does.
    ///
    /// The unfollowable one sits in the middle on purpose — the ring has to
    /// step over it rather than stop at it, and a fixture with it at either
    /// end would pass on a ring that simply stopped.
    fn a_grove_that_names_its_beads() -> Snapshot {
        let mut snapshot = a_described_grove(6);
        let names = |id: &str, edge: Edge, status: Option<Status>| Related {
            id: id.to_string(),
            edge,
            status,
            title: Some("a bead in the grove".to_string()),
        };
        for tree in &mut snapshot.collected {
            let tree = Arc::make_mut(tree);
            for node in &mut tree.beads {
                if node.id != "grv-1.1" {
                    continue;
                }
                node.parent = Some(names("grv-1", Edge::ParentChild, Some(Status::InProgress)));
                node.depends_on = vec![names("grv-404", Edge::Blocks, None)];
                node.blocks = vec![names("grv-1.2", Edge::Blocks, Some(Status::InProgress))];
            }
        }
        snapshot.trees = snapshot.collected.clone();
        snapshot
    }

    /// The window open on `grv-1.1`, which is the bead that names the others.
    fn shown_on_the_bead_that_names_beads() -> Shown {
        let mut shown = shown(a_grove_that_names_its_beads());
        shown.apply(Action::ExpandOrChild);
        assert_eq!(cursor(&shown), Some(&bead("grove", "grv-1.1")));
        assert!(shown.apply(Action::ShowBead));
        shown
    }

    /// The window opens on no reference at all, so `Enter` still means what it
    /// meant before there were any: focus the pane.
    #[test]
    fn the_window_opens_on_none_of_the_beads_it_names() {
        let mut shown = shown_on_the_bead_that_names_beads();

        assert_eq!(shown.show.on(), None);
        assert!(!shown.follow_related(), "nothing to follow from nowhere");
    }

    /// `Tab` puts it on the first bead this one names that the forest can
    /// take the reader to — here its parent, which is the root above it.
    #[test]
    fn tab_puts_the_window_on_the_first_bead_it_can_follow() {
        let mut shown = shown_on_the_bead_that_names_beads();

        assert!(shown.apply(Action::NextRelated));

        assert_eq!(shown.show.on(), Some("grv-1"));
        assert_eq!(
            shown.related_key(),
            Some(bead("grove", "grv-1")),
            "the ring is on the parent, which is the tree's root"
        );
    }

    /// `grv-404` is drawn on the page and says the answer does not hold it.
    /// The ring steps over it to the sibling below, so no ring the reader can
    /// see is an `Enter` that does nothing.
    #[test]
    fn the_ring_steps_over_a_bead_the_forest_cannot_go_to() {
        let mut shown = shown_on_the_bead_that_names_beads();
        assert!(shown.apply(Action::NextRelated));

        assert!(shown.apply(Action::NextRelated));

        assert_eq!(
            shown.related_key(),
            Some(bead("grove", "grv-1.2")),
            "the ring landed on the bead in the middle, which goes nowhere"
        );
    }

    /// Only the forest can say whether a bead this one names can be gone to,
    /// and the title offers the keys on the strength of its answer. Asserted
    /// on the frame the screen draws rather than on the phrase, because the
    /// phrase is told what to say and this is about who tells it.
    #[test]
    fn the_title_offers_the_keys_that_follow_where_the_forest_can_go_to_one() {
        let mut shown = shown_on_the_bead_that_names_beads();

        let drawn = bead_view(&mut shown, 80, 24);

        assert!(
            drawn.iter().any(|row| row.contains("Tab, Enter to follow")),
            "{drawn:#?}"
        );
    }

    /// And a bead whose every reference the forest draws nowhere offers
    /// neither key: a reader told about `Tab` there presses it for nothing.
    #[test]
    fn the_title_offers_no_keys_where_the_forest_can_go_to_none_of_them() {
        let mut shown = shown(a_described_grove(6));
        shown.apply(Action::ExpandOrChild);
        assert!(shown.apply(Action::ShowBead));

        let drawn = bead_view(&mut shown, 80, 24);

        assert!(
            !drawn.iter().any(|row| row.contains("to follow")),
            "{drawn:#?}"
        );
    }

    /// It is still drawn, and still says so — degrade, never disappear. The
    /// ring passing over it is not the page leaving it out.
    #[test]
    fn a_bead_the_forest_cannot_go_to_is_still_drawn_and_still_says_so() {
        let mut shown = shown_on_the_bead_that_names_beads();
        let inner = bead_window_inner(&mut shown, 80, 24);

        assert!(
            inner.iter().any(|row| row.contains("grv-404")),
            "{inner:#?}"
        );
    }

    /// Stepping past the last comes round to the first rather than stopping,
    /// which is what makes one key enough to reach every bead this one names.
    #[test]
    fn stepping_past_the_last_bead_comes_round_to_the_first() {
        let mut shown = shown_on_the_bead_that_names_beads();
        assert!(shown.apply(Action::NextRelated));
        assert!(shown.apply(Action::NextRelated));
        assert_eq!(shown.related_key(), Some(bead("grove", "grv-1.2")));

        assert!(shown.apply(Action::NextRelated));

        assert_eq!(shown.related_key(), Some(bead("grove", "grv-1")));
    }

    /// A collection can rewrite what the bead the reader is on names, and the
    /// ring stays on the bead rather than on the row.
    ///
    /// `codex review` on this change, and it is right: while the ring was an
    /// ordinal it survived a reordering and came to stand for a different
    /// bead — so the ring appeared not to move, and `Enter` went somewhere
    /// nobody had pointed at. There is nothing on the screen to say it has
    /// happened, which is what makes it worth a test rather than a caveat.
    #[test]
    fn a_collection_that_reorders_what_a_bead_names_leaves_the_ring_on_its_bead() {
        let mut shown = shown_on_the_bead_that_names_beads();
        assert!(shown.apply(Action::NextRelated));
        assert_eq!(shown.related_key(), Some(bead("grove", "grv-1")));

        shown.collected(what_the_bead_names_reordered());

        assert_eq!(
            shown.related_key(),
            Some(bead("grove", "grv-1")),
            "the ring moved to whatever took that row"
        );
    }

    /// And a collection that stops the bead naming it takes the ring off
    /// altogether. A ring is an offer to press `Enter`, and the offer goes
    /// when what it points at does.
    #[test]
    fn a_collection_that_drops_the_bead_the_ring_is_on_takes_the_ring_off() {
        let mut shown = shown_on_the_bead_that_names_beads();
        assert!(shown.apply(Action::NextRelated));
        assert_eq!(shown.related_key(), Some(bead("grove", "grv-1")));

        shown.collected(a_described_grove(6));

        assert_eq!(shown.show.on(), None);
        assert!(
            !shown.follow_related(),
            "Enter still goes somewhere from a ring that is not drawn"
        );
    }

    /// A collection reaches the window the reader is looking at, and none of
    /// the ones parked behind it on the way back — so the way back is where a
    /// ring the collection invalidated arrives, one press after it could have
    /// been settled.
    ///
    /// `codex review` on this change, and it is right: the first fix settled
    /// only the current `Show`, so retracing restored a ring drawn on a bead
    /// the reader could no longer go to, and `Enter` fell through to focusing
    /// the pane. Same class as the finding above it, one level up.
    #[test]
    fn a_ring_the_collection_invalidated_is_settled_by_the_way_back_too() {
        let mut shown = shown_on_the_bead_that_names_beads();
        assert!(shown.apply(Action::NextRelated));
        assert!(shown.follow_related());
        shown.collected(a_described_grove(6));

        assert!(shown.retrace());

        assert_eq!(cursor(&shown), Some(&bead("grove", "grv-1.1")));
        assert_eq!(
            shown.show.on(),
            None,
            "the way back restored a ring on a bead that is no longer named"
        );
    }

    /// The same beads, named in the other order — so an ordinal kept across
    /// the collection stands for a different bead while the reader's ring has
    /// not moved.
    fn what_the_bead_names_reordered() -> Snapshot {
        let mut snapshot = a_grove_that_names_its_beads();
        for tree in &mut snapshot.collected {
            let tree = Arc::make_mut(tree);
            for node in &mut tree.beads {
                if node.id != "grv-1.1" {
                    continue;
                }
                let parent = node.parent.take().expect("the fixture names a parent");
                node.blocks = vec![parent];
                node.parent = None;
                node.depends_on = vec![Related {
                    id: "grv-1.2".to_string(),
                    edge: Edge::Blocks,
                    status: Some(Status::InProgress),
                    title: Some("a bead in the grove".to_string()),
                }];
            }
        }
        snapshot.trees = snapshot.collected.clone();
        snapshot
    }

    /// The move the whole feature is for, and the assertion is that the
    /// window is *still up* rather than anything about the bead it now shows.
    ///
    /// `bead_still_shown` closes the window when the selection leaves the bead
    /// `viewing` names, to catch a collection moving it out from under the
    /// reader. A follow moves the selection deliberately, and a guard written
    /// for the involuntary move cannot tell one from the other — so a follow
    /// that did not write `viewing` would close the window on the very press
    /// that asked for the bead.
    #[test]
    fn following_a_bead_moves_the_selection_to_it_and_leaves_the_window_up() {
        let mut shown = shown_on_the_bead_that_names_beads();
        assert!(shown.apply(Action::NextRelated));

        assert!(shown.follow_related());

        assert_eq!(cursor(&shown), Some(&bead("grove", "grv-1")));
        assert!(
            shown.bead_still_shown(),
            "the window closed on the press that asked for the bead"
        );
    }

    /// The window is drawn from the selection, so following one redraws it on
    /// the bead arrived at without anything asking it to.
    #[test]
    fn the_window_shows_the_bead_that_was_followed_to() {
        let mut shown = shown_on_the_bead_that_names_beads();
        assert!(shown.apply(Action::NextRelated));
        assert!(shown.follow_related());

        let inner = bead_window_inner(&mut shown, 80, 12);

        assert!(inner.iter().any(|row| row.contains("grv-1 ")), "{inner:#?}");
    }

    /// Going back is the bead followed from, and the row of it that was
    /// followed — landing at the top of the bead would lose the reader's
    /// place in a bead they had scrolled through.
    #[test]
    fn going_back_returns_to_the_bead_followed_from_and_the_ring_it_was_on() {
        let mut shown = shown_on_the_bead_that_names_beads();
        assert!(shown.apply(Action::NextRelated));
        let was = shown.show.clone();
        assert!(shown.follow_related());

        assert!(shown.retrace());

        assert_eq!(cursor(&shown), Some(&bead("grove", "grv-1.1")));
        assert_eq!(shown.show, was, "the window is where it was left");
        assert!(shown.bead_still_shown(), "the way back closed the window");
    }

    /// On the bead the window was opened on there is nowhere further back, and
    /// saying so is what leaves the view for the forest.
    #[test]
    fn there_is_nowhere_back_from_the_bead_the_window_was_opened_on() {
        let mut shown = shown_on_the_bead_that_names_beads();

        assert!(!shown.retrace());
        assert_eq!(cursor(&shown), Some(&bead("grove", "grv-1.1")));
    }

    /// The way back out of a window is the forest it was opened over, whatever
    /// the last one was opened over: a reader who followed three beads, left,
    /// and opened another has no way back to the first three and does not
    /// expect one.
    #[test]
    fn opening_the_window_again_forgets_the_way_back() {
        let mut shown = shown_on_the_bead_that_names_beads();
        assert!(shown.apply(Action::NextRelated));
        assert!(shown.follow_related());

        assert!(shown.apply(Action::ShowBead));

        assert!(!shown.retrace(), "a way back to a window that was left");
        assert_eq!(shown.show.on(), None, "and no ring carried over with it");
    }

    /// Opening the view again starts it from the top: a reader who scrolled
    /// one bead to the end and opened another wants the other's start.
    #[test]
    fn opening_the_bead_view_starts_it_at_the_top() {
        let mut shown = shown(a_described_grove(6));
        assert!(shown.apply(Action::ShowBead));
        bead_view(&mut shown, 80, 6);
        assert!(shown.scroll(Motion::LastRow));

        assert!(shown.apply(Action::Move(Motion::NextRow)));
        assert!(shown.apply(Action::ShowBead));

        let inner = bead_window_inner(&mut shown, 80, 6);
        assert_eq!(inner[0], "◐ grv-1.1  a bead in the grove");
    }

    /// A collection that leaves the selection on its bead leaves the view
    /// on it too, however the rows around it moved.
    #[test]
    fn a_collection_that_keeps_the_selection_on_its_bead_keeps_the_view_on_it() {
        let mut shown = shown(a_described_grove(6));
        shown.apply(Action::ExpandOrChild);
        shown.apply(Action::Move(Motion::LastRow));
        assert_eq!(cursor(&shown), Some(&bead("grove", "grv-1.6")));
        assert!(shown.apply(Action::ShowBead));

        let mut reordered = a_grove_reordered(6);
        for tree in &mut reordered.collected {
            let tree = Arc::make_mut(tree);
            for node in &mut tree.beads {
                node.description = format!("what {} is about", node.id);
            }
        }
        reordered.trees = reordered.collected.clone();
        shown.collected(reordered);

        assert_eq!(cursor(&shown), Some(&bead("grove", "grv-1.6")));
        assert!(shown.bead_still_shown());
        assert!(
            bead_window_inner(&mut shown, 80, 24).contains(&"what grv-1.6 is about".to_string())
        );
    }

    /// A collection that drops the bead the view was opened on moves the
    /// selection onto the nearest forebear that survived — which is another
    /// bead, and not the one the reader opened. The view says it is no
    /// longer on its bead, so the loop can take it down rather than draw
    /// the forebear under the title the reader opened.
    #[test]
    fn a_collection_that_drops_the_bead_the_view_is_on_says_the_view_is_off_it() {
        let mut shown = shown(a_described_grove(6));
        shown.apply(Action::ExpandOrChild);
        shown.apply(Action::Move(Motion::LastRow));
        assert_eq!(cursor(&shown), Some(&bead("grove", "grv-1.6")));
        assert!(shown.apply(Action::ShowBead));

        shown.collected(a_described_grove(3));

        assert_ne!(cursor(&shown), Some(&bead("grove", "grv-1.6")));
        assert!(!shown.bead_still_shown());
    }

    /// `Clear` is what stops the trees showing between the rows. Every row
    /// inside the border is asserted to hold nothing of the forest.
    #[test]
    fn no_forest_shows_through_the_bead_window() {
        let mut shown = shown(a_described_grove(30));
        assert!(shown.apply(Action::ShowBead));

        let rows = bead_view(&mut shown, 80, 24);
        let inside = rows.iter().filter(|row| row.starts_with(''));

        for row in inside {
            assert!(
                !row.contains("grv-1."),
                "a row of the forest shows through the window: {row:?}"
            );
        }
    }

    /// The same grove with a live agent on every bead, so that moving the
    /// selection changes which pane the tail is reading.
    fn a_staffed_grove(beads: usize) -> Snapshot {
        let mut snapshot = a_grove(beads);
        for tree in &mut snapshot.collected {
            let tree = Arc::make_mut(tree);
            for (at, node) in tree.beads.iter_mut().enumerate() {
                node.agent = Some(AgentRef {
                    pane: pane_key(&format!("w:p{at}")),
                    pane_status: PaneStatus::Working,
                    title: None,
                    source: JoinSource::AgentPane,
                });
            }
        }
        snapshot.trees = snapshot.collected.clone();
        snapshot
    }

    /// A click is another way to move the selection and not another kind of
    /// selection. Where a keystroke would have taken the tail, a click that
    /// lands on the same row has to take it to the same place — the tail
    /// going stale under the pointer is a screen that quietly disagrees with
    /// itself.
    #[test]
    fn a_click_takes_the_tail_with_it_exactly_as_a_keystroke_does() {
        let mut by_key = shown(a_staffed_grove(6));
        by_key.apply(Action::Move(Motion::LastRow));

        let mut by_click = shown(a_staffed_grove(6));
        let at_rest = by_click.tailing.clone();
        assert!(by_click.select(by_key.forest.selected_line()));

        assert_ne!(
            by_key.tailing, at_rest,
            "the fixture has to move the tail at all"
        );
        assert_eq!(by_click.tailing, by_key.tailing);
    }

    /// A click selects the line the forest drew on that row. Which line that
    /// is is a question about the screen rather than about the click: a
    /// forest scrolled under its window draws a different line on the same
    /// row, and a click that answered from the row alone would select the
    /// wrong bead on every screen the forest has outgrown.
    #[test]
    fn a_click_selects_the_line_the_forest_drew_on_that_row() {
        let screen = Rect::new(0, 0, 60, 24);
        let band = draw::regions(screen).forest;
        let mut shown = shown(a_grove(30));

        assert!(shown.clicked(screen, band.y + 3));
        assert_eq!(shown.forest.selected_line(), 3);

        to_the_last_row(&mut shown);
        let last = shown.forest.selected_line();
        assert!(
            last + 1 > band.height as usize,
            "the grove has to outgrow the band for the scroll to be the \
             difference between the two clicks"
        );
        assert!(shown.clicked(screen, band.y));
        assert_eq!(
            shown.forest.selected_line(),
            last + 1 - band.height as usize,
            "the last line is on the band's last row, so its first row holds \
             the line a bandful before it"
        );
    }

    /// The tail is an echo of a pane and the key row is a legend. A click on
    /// either holds nothing the selection could sit on, and leaves it where
    /// it was.
    #[test]
    fn a_click_beneath_the_forest_selects_nothing() {
        let screen = Rect::new(0, 0, 60, 24);
        let bands = draw::regions(screen);
        let mut shown = shown(a_grove(30));
        shown.clicked(screen, bands.forest.y + 3);
        let selected = shown.forest.selected_line();

        for row in [bands.tail.y, bands.keys.y] {
            assert!(!shown.clicked(screen, row), "the click at row {row} moved");
            assert_eq!(shown.forest.selected_line(), selected);
        }
    }

    /// A click on a reference the forest can reach goes to that bead, and
    /// leaves the way back behind it — the same path `Enter` on the ring
    /// takes, with the ring put where the pointer is.
    #[test]
    fn a_click_on_a_reference_goes_to_the_bead_it_names() {
        let mut shown = shown_on_the_bead_that_names_beads();
        let rows = bead_view(&mut shown, WIDE, TALL);

        assert_eq!(
            shown.clicked_bead(over(WIDE, TALL), drawn_on(&rows, "")),
            Landed::Followed
        );

        assert_eq!(cursor(&shown), Some(&bead("grove", "grv-1")));
        assert!(
            shown.retrace(),
            "the click left no way back to the bead it followed from"
        );
        assert_eq!(cursor(&shown), Some(&bead("grove", "grv-1.1")));
    }

    /// A click on a reference the forest cannot take the reader to goes
    /// nowhere and leaves the ring where it was.
    ///
    /// The ring is an offer to press `Enter`, so one left sitting on a bead
    /// the reader pointed at and did not arrive at is a move they never asked
    /// for — and the next `Tab` would step on from a place they have never
    /// been.
    #[test]
    fn a_click_on_a_reference_the_forest_cannot_reach_goes_nowhere() {
        let mut shown = shown_on_the_bead_that_names_beads();
        let rows = bead_view(&mut shown, WIDE, TALL);
        let was = shown.show.on().map(str::to_string);

        assert_eq!(
            shown.clicked_bead(over(WIDE, TALL), drawn_on(&rows, "grv-404")),
            Landed::Nothing
        );

        assert_eq!(cursor(&shown), Some(&bead("grove", "grv-1.1")));
        assert_eq!(shown.show.on().map(str::to_string), was);
    }

    /// A click on the page that names no bead goes nowhere, so a reader who
    /// aims at a reference and misses by a row keeps the window.
    #[test]
    fn a_click_on_the_page_that_names_no_bead_goes_nowhere() {
        let mut shown = shown_on_the_bead_that_names_beads();
        let rows = bead_view(&mut shown, WIDE, TALL);

        assert_eq!(
            shown.clicked_bead(over(WIDE, TALL), drawn_on(&rows, "PARENT")),
            Landed::Nothing
        );
        assert_eq!(cursor(&shown), Some(&bead("grove", "grv-1.1")));
    }

    /// A click off the page — the window's own border, or the forest round it
    /// — is what takes the window away.
    #[test]
    fn a_click_off_the_page_takes_the_window_away() {
        let mut shown = shown_on_the_bead_that_names_beads();
        let rows = bead_view(&mut shown, WIDE, TALL);
        let window = window_of(&rows);
        assert!(window.y > 0, "the window has to leave a row above it");

        for row in [window.y - 1, window.y, window.bottom() - 1] {
            assert_eq!(
                shown.clicked_bead(over(WIDE, TALL), row),
                Landed::Away,
                "the click at row {row} did not take the window away: {rows:#?}"
            );
        }
    }

    /// Wide enough for the window's rows to be drawn whole, and tall enough
    /// for every section of the bead and a row of forest above it.
    const WIDE: u16 = 80;
    const TALL: u16 = 24;

    /// The whole of a screen of that size.
    fn over(width: u16, height: u16) -> Rect {
        Rect::new(0, 0, width, height)
    }

    /// The row of a drawn screen something was drawn on — read back off the
    /// frame rather than counted out, because where the window falls follows
    /// from the screen's size and the bead's length.
    fn drawn_on(rows: &[String], drawn_as: &str) -> u16 {
        let on = rows
            .iter()
            .position(|row| row.contains(drawn_as))
            .unwrap_or_else(|| panic!("{drawn_as:?} was drawn on no row of {rows:#?}"));
        u16::try_from(on).expect("no screen is that tall")
    }

    #[test]
    fn a_refresh_that_changes_nothing_leaves_the_forest_exactly_as_it_was() {
        let grove = a_grove(30);
        let mut shown = shown(grove.clone());
        forest_band(&mut shown, 60, 24);
        shown.apply(Action::Move(Motion::LastRow));

        let before = forest_band(&mut shown, 60, 24);
        shown.collected(grove);

        assert_eq!(forest_band(&mut shown, 60, 24), before);
    }

    #[test]
    fn a_refresh_that_reorders_around_the_selection_keeps_it_on_its_bead() {
        let mut shown = shown(a_grove(6));
        shown.apply(Action::ExpandOrChild);
        shown.apply(Action::Move(Motion::LastRow));
        let was = shown.forest.selected_line();

        assert_eq!(cursor(&shown), Some(&bead("grove", "grv-1.6")));

        shown.collected(a_grove_reordered(6));

        assert_eq!(cursor(&shown), Some(&bead("grove", "grv-1.6")));
        assert_ne!(shown.forest.selected_line(), was);
    }

    /// A quiet grove the live-agent filter hides, drawn ahead of a tree it
    /// keeps, so dropping the filter moves the surviving tree down the
    /// forest rather than leaving it where it already was.
    fn a_hidden_grove_above_a_shown_tree() -> Snapshot {
        let grove = a_grove(6).trees[0].clone();
        let atlas = a_snapshot().trees[0].clone();
        let both = vec![grove, atlas];

        let mut snapshot = Snapshot {
            collected: both,
            projects: vec!["grove".to_string(), "atlas".to_string()],
            ..a_snapshot_of(Vec::new())
        };
        snapshot.refilter(Filter::LiveAgents);
        snapshot
    }

    #[test]
    fn dropping_the_filter_keeps_the_cursor_on_its_bead() {
        let mut shown = shown(a_hidden_grove_above_a_shown_tree());
        let was = shown.forest.selected_line();

        assert_eq!(cursor(&shown), Some(&bead("atlas", "a-1")));

        assert!(shown.apply(Action::ToggleFilter));

        assert_eq!(shown.forest.snapshot().filter, Filter::All);
        assert_eq!(cursor(&shown), Some(&bead("atlas", "a-1")));
        assert_ne!(
            shown.forest.selected_line(),
            was,
            "the grove came back above it"
        );
    }

    #[test]
    fn a_refresh_that_changes_nothing_keeps_the_folds_set_by_hand() {
        let grove = a_grove(6);
        let mut shown = shown(grove.clone());
        shown.apply(Action::ToggleFold);
        let folded = forest_band(&mut shown, 60, 24);

        shown.collected(grove);

        assert_eq!(forest_band(&mut shown, 60, 24), folded);
    }

    /// The screen opens on what the band has to say while the provider is still
    /// answering, and asks for the reading rather than waiting on it. The
    /// startup path used to pay the whole of `PATIENCE` before the first
    /// frame, on a screen that had nothing to announce it with.
    #[test]
    fn the_screen_opens_naming_the_pane_it_is_waiting_on() {
        let (shown, panes) = shown_asking(a_staffed_grove(6));

        assert_eq!(
            shown.tail,
            Tail::Reading {
                pane: pane_key(A_SELECTED_PANE)
            }
        );
        assert_eq!(
            panes.reads(),
            [format!("{A_SELECTED_PANE} {}", tail::LINES)],
            "the pane is asked for exactly the lines the band has room for"
        );
    }

    /// A bead nobody is working names no pane, so there is nothing to ask
    /// the provider and the band says so on its own.
    #[test]
    fn a_row_with_no_pane_asks_the_provider_nothing() {
        let (shown, panes) = shown_asking(a_grove(6));

        assert_eq!(shown.tail, Tail::Silent(phrase::no_agent_to_tail()));
        assert!(panes.reads().is_empty());
    }

    #[test]
    fn what_was_read_for_the_pane_selected_is_what_the_band_shows() {
        let (mut shown, _) = shown_asking(a_staffed_grove(6));

        assert!(shown.tailed(read(A_SELECTED_PANE, &["rebuilt .#larkspur"]), an_instant()));

        assert_eq!(
            shown.tail,
            Tail::Pane {
                pane: pane_key(A_SELECTED_PANE),
                lines: vec!["rebuilt .#larkspur".to_string()],
            }
        );
    }

    /// A reader holding an arrow key down moves faster than a slow provider
    /// answers. Every move asks for the pane it landed on, but only one
    /// question is ever out, so what a run of keystrokes costs is one
    /// call — not one per key — and the band goes on naming the pane it is
    /// waiting for.
    ///
    /// The tail falling behind the selection is the price of the keyboard
    /// never doing so, and it is a decision rather than an accident: the loop
    /// answers every one of these moves at once, and the rows under the
    /// forest arrive when the cursor rests long enough for an answer to land.
    #[test]
    fn moving_faster_than_the_provider_answers_costs_one_read_at_a_time() {
        let (mut shown, panes) = shown_asking(a_staffed_grove(6));
        let opened_on = panes.reads();

        let moved = to_the_last_row(&mut shown);

        assert!(moved > 1, "the forest has rows to move down");
        assert_eq!(
            panes.reads(),
            opened_on,
            "a read was already out, so none of the moves asked for another"
        );
        let resting_on = match &shown.tail {
            Tail::Reading { pane } => pane.clone(),
            other => panic!("the band is still waiting on a pane: {other:?}"),
        };
        assert_ne!(
            resting_on,
            pane_key(A_SELECTED_PANE),
            "the selection left the pane the read is out for"
        );

        // The answer to the read started before any of that arrives, about a
        // pane the reader is nowhere near.
        assert!(
            !shown.tailed(
                read(A_SELECTED_PANE, &["nothing should reach the screen"]),
                an_instant()
            ),
            "an answer about a pane the selection has left changes no screen"
        );

        assert_eq!(
            shown.tail,
            Tail::Reading {
                pane: resting_on.clone()
            },
            "the band still names the pane the cursor is on"
        );
        assert_eq!(
            panes.reads(),
            [
                opened_on,
                vec![format!("{} {}", resting_on.id, tail::LINES)]
            ]
            .concat(),
            "and that pane is what the provider is asked for next"
        );
    }

    /// The pane is read on the band's own clock and not on the collection's:
    /// a collection landing under the same pane leaves the rows on the band
    /// standing and asks the provider for nothing.
    ///
    /// It used to be the other way — the collection was the tick the pane
    /// was re-read on, and a read out when it landed was superseded so the
    /// band would not show the pane as it was. The band's own interval is
    /// what bounds that now, and it is far shorter than a collection's.
    #[test]
    fn a_collection_landing_under_the_pane_leaves_the_band_to_its_own_clock() {
        let grove = a_staffed_grove(6);
        let (mut shown, panes) = shown_asking(grove.clone());
        let opened_on = panes.reads();
        assert!(shown.tailed(read(A_SELECTED_PANE, &["what it says"]), an_instant()));

        shown.collected(grove);

        assert_eq!(
            panes.reads(),
            opened_on,
            "the collection asked the provider for nothing"
        );
        assert_eq!(
            shown.tail,
            Tail::Pane {
                pane: pane_key(A_SELECTED_PANE),
                lines: vec!["what it says".to_string()],
            },
            "and the rows on the band stand"
        );
        assert_eq!(
            shown.rereads_in(an_instant()),
            Some(EVERY),
            "the band's own clock is what reads the pane next"
        );
    }

    /// The bead: the pane is asked for again one interval after the answer
    /// that filled the band, and not before. Nothing on the band changes for
    /// the ask — the rows stand until the answer lands — because a band that
    /// said *reading that pane* four times a second would be a band nobody
    /// could read.
    #[test]
    fn the_pane_is_read_again_one_interval_after_the_answer_that_filled_the_band() {
        let (mut shown, panes) = shown_asking(a_staffed_grove(6));
        let opened_on = panes.reads();
        let answered = an_instant();
        shown.tailed(read(A_SELECTED_PANE, &["what it says"]), answered);
        let filled = shown.tail.clone();

        assert_eq!(shown.rereads_in(answered), Some(EVERY));
        shown.reread(answered + EVERY / 2);
        assert_eq!(panes.reads(), opened_on, "half an interval in, not yet");
        assert_eq!(
            shown.rereads_in(answered + EVERY / 2),
            Some(EVERY / 2),
            "and half is what is left to wait"
        );

        shown.reread(answered + EVERY);

        assert_eq!(
            panes.reads(),
            [
                opened_on,
                vec![format!("{A_SELECTED_PANE} {}", tail::LINES)]
            ]
            .concat(),
            "the interval came round and the pane was asked for"
        );
        assert_eq!(
            shown.tail, filled,
            "the rows stand while the answer is on its way"
        );
        assert_eq!(
            shown.rereads_in(answered + EVERY),
            None,
            "nothing is due while a read is out"
        );
    }

    /// A pane that has said nothing new since the last read is the common
    /// case four times a second, and it is not a change to the screen.
    #[test]
    fn an_answer_that_repeats_the_rows_on_the_band_changes_nothing() {
        let (mut shown, _) = shown_asking(a_staffed_grove(6));
        let answered = an_instant();
        assert!(shown.tailed(read(A_SELECTED_PANE, &["what it says"]), answered));
        shown.reread(answered + EVERY);

        let again = answered + EVERY * 2;
        assert!(
            !shown.tailed(read(A_SELECTED_PANE, &["what it says"]), again),
            "the same rows again are not a change"
        );
        assert_eq!(
            shown.rereads_in(again),
            Some(EVERY),
            "and the answer still arms the read after it"
        );
    }

    /// The answer to that read arms the next, so a pane the cursor rests on
    /// is read for as long as it rests there.
    #[test]
    fn every_answer_arms_the_read_after_it() {
        let (mut shown, panes) = shown_asking(a_staffed_grove(6));
        let answered = an_instant();
        shown.tailed(read(A_SELECTED_PANE, &["first"]), answered);
        shown.reread(answered + EVERY);
        let asked_twice = panes.reads();

        let again = answered + EVERY * 2;
        assert!(shown.tailed(read(A_SELECTED_PANE, &["second"]), again));
        shown.reread(again + EVERY);

        assert_eq!(panes.reads().len(), asked_twice.len() + 1);
        assert_eq!(
            shown.tail,
            Tail::Pane {
                pane: pane_key(A_SELECTED_PANE),
                lines: vec!["second".to_string()],
            }
        );
    }

    /// The largest whole number of milliseconds — the unit
    /// `tail_refresh_millis` is read in — that still lands inside the range
    /// an instant can hold, read off chrono's own last instant rather than
    /// quoted from its documentation. It shrinks as the clock advances,
    /// which is why the answer is checked where the add happens rather than
    /// bounded once at config load.
    fn millis_to_the_end_of_time(from: DateTime<Utc>) -> u64 {
        u64::try_from(
            (DateTime::<Utc>::MAX_UTC - from)
                .to_std()
                .expect("the end of time is after this instant")
                .as_millis(),
        )
        .expect("a gap an instant can hold counts in milliseconds a u64 holds")
    }

    #[test]
    fn a_config_that_would_not_load_is_said_at_the_foot() {
        let mut shown = shown(a_staffed_grove(6));

        assert!(
            shown.reloaded(Reloaded::Broken, an_instant()),
            "the foot has changed"
        );
        assert_eq!(shown.standing, [Notice::ConfigWouldNotReload]);
    }

    /// The sequence a reader who breaks their config and undoes the edit
    /// walks: the file is back to exactly what `bdi` is already working to,
    /// so nothing reloads — and the notice has to come off all the same. A
    /// foot that cleared it only on a config that *changed* would leave them
    /// with no edit that clears it but one changing the config to something
    /// they did not want.
    #[test]
    fn undoing_a_broken_edit_takes_the_notice_off_though_nothing_reloaded() {
        let mut shown = shown(a_staffed_grove(6));
        shown.reloaded(Reloaded::Broken, an_instant());

        assert!(
            shown.reloaded(Reloaded::Unchanged, an_instant()),
            "the foot has changed"
        );
        assert_eq!(shown.standing, []);
    }

    #[test]
    fn a_config_that_loads_again_takes_the_notice_off() {
        let mut shown = shown(a_staffed_grove(6));
        shown.reloaded(Reloaded::Broken, an_instant());

        assert!(
            shown.reloaded(Reloaded::Fresh(&the_config_in_force()), an_instant()),
            "the foot has changed"
        );
        assert_eq!(shown.standing, []);
    }

    /// A `[row]` edit is read where a `[theme]` edit is, and reaches both
    /// holders of the layout: the drawer's, through `Drawing`, and the
    /// forest's, which measures its identity widths over it. A forest left
    /// laid out to the old row would size a column of cells the row no
    /// longer draws.
    #[test]
    fn a_row_edit_lays_the_forest_out_again_to_the_new_cells() {
        let mut shown = shown(a_grove(6));
        assert!(shown.forest.lines().widths().of(&Cell::Id) > 0);
        let mut written = the_config_in_force();
        written.row = Layout {
            identity: vec![Cell::Glyph],
            ..Layout::default()
        };

        assert!(
            shown.reloaded(Reloaded::Fresh(&written), an_instant()),
            "the screen has changed"
        );

        assert_eq!(shown.drawing.layout, written.row);
        assert_eq!(shown.forest.lines().widths().of(&Cell::Id), 0);
    }

    /// A check that read nothing says nothing, which is what leaves the
    /// notice up between one check and the next: the file is still broken and
    /// nobody has written it since.
    #[test]
    fn a_check_that_read_nothing_leaves_the_foot_as_it_was() {
        let mut shown = shown(a_staffed_grove(6));
        shown.reloaded(Reloaded::Broken, an_instant());

        assert!(
            !shown.reloaded(Reloaded::Untouched, an_instant()),
            "nothing has changed"
        );
        assert_eq!(shown.standing, [Notice::ConfigWouldNotReload]);
    }

    /// Being told again what the foot already says is not a change. The loop
    /// draws on this, and a check every couple of seconds that always
    /// reported one would redraw the screen for ever.
    #[test]
    fn a_foot_told_again_what_it_already_says_has_not_changed() {
        let mut shown = shown(a_staffed_grove(6));

        assert!(
            !shown.reloaded(Reloaded::Unchanged, an_instant()),
            "nothing to take off"
        );
        shown.reloaded(Reloaded::Broken, an_instant());
        assert!(
            !shown.reloaded(Reloaded::Broken, an_instant()),
            "already said"
        );
        assert_eq!(shown.standing, [Notice::ConfigWouldNotReload]);
    }

    /// Nothing rechecks what was settled before the first collection — the
    /// socket is asked for once for the life of the run — so on a machine
    /// that sets no `$XDG_RUNTIME_DIR` it is true of every session there will
    /// ever be, and a foot that said it for ever would spend a row describing
    /// the ordinary way `bdi` runs there.
    #[test]
    fn a_notice_settled_at_startup_leaves_the_foot_after_a_minute() {
        let started = an_instant();
        let shown = shown_saying(a_snapshot(), vec![Notice::NoInboundChannel], started);

        assert_eq!(shown.says(started), [Notice::NoInboundChannel]);
        assert_eq!(
            shown.says(started + chrono::TimeDelta::seconds(59)),
            [Notice::NoInboundChannel],
            "still there for a reader who has only just looked back"
        );
        assert_eq!(shown.says(started + chrono::TimeDelta::seconds(60)), []);
    }

    /// The retirement is a deadline the loop sleeps to, so the foot loses the
    /// notice on a frame nothing else asked for. One lost on the reader's
    /// next keystroke instead would stay for as long as they kept their hands
    /// still, which on a screen nothing else is changing is the whole run.
    #[test]
    fn the_frame_holds_only_as_long_as_a_notice_settled_at_startup_does() {
        let started = an_instant();
        let shown = shown_saying(a_snapshot(), vec![Notice::NoInboundChannel], started);

        assert_eq!(shown.holds_for(started), Some(Duration::from_secs(60)));
        assert_eq!(
            shown.holds_for(started + chrono::TimeDelta::seconds(60)),
            None,
            "retired on the instant, so nothing is left to falsify"
        );
        assert_eq!(
            shown.holds_for(started + chrono::TimeDelta::hours(3)),
            None,
            "and retired long since"
        );
    }

    /// The clock reaches what was settled before the first collection and
    /// nothing else. A config that will not reload is looked at every couple
    /// of seconds and comes off the foot when the file mends, so it is still
    /// said hours after the startup notices have gone — and it joins them
    /// underneath rather than in front, which is the order the foot gives
    /// them up in.
    #[test]
    fn a_config_that_will_not_reload_outlasts_the_notices_settled_at_startup() {
        let started = an_instant();
        let mut shown = shown_saying(a_snapshot(), vec![Notice::NoInboundChannel], started);
        let broke = started + chrono::TimeDelta::seconds(30);
        let hours_later = started + chrono::TimeDelta::hours(3);

        shown.reloaded(Reloaded::Broken, broke);
        assert_eq!(
            shown.says(broke),
            [Notice::NoInboundChannel, Notice::ConfigWouldNotReload]
        );
        assert_eq!(shown.says(hours_later), [Notice::ConfigWouldNotReload]);

        shown.reloaded(Reloaded::Fresh(&the_config_in_force()), hours_later);
        assert_eq!(shown.says(hours_later), []);
    }

    /// A run that found everything it looked for has no retirement to wake
    /// for, so the deadline is not a wakeup every run pays for.
    #[test]
    fn a_run_with_nothing_settled_at_startup_has_no_retirement_to_wake_for() {
        assert_eq!(shown(a_snapshot()).holds_for(an_instant()), None);
    }

    /// The gap `tail_refresh_millis` can be given and still be waited out.
    /// One millisecond more is the test below, and the two of them are what
    /// pin the answer to the bound rather than to somewhere past it.
    #[test]
    fn a_band_whose_interval_reaches_the_end_of_time_still_rereads() {
        let every = Duration::from_millis(millis_to_the_end_of_time(an_instant()));
        let (mut shown, _) = shown_asking_every(a_staffed_grove(6), every);

        shown.tailed(read(A_SELECTED_PANE, &["what it says"]), an_instant());

        assert_eq!(shown.rereads_in(an_instant()), Some(every));
    }

    /// A `tail_refresh_millis` past what an instant can hold is a gap
    /// nothing waits out, rather than a panic on the first answer the
    /// provider gives. Nothing is what this already says for a band with no
    /// pane on it, so the answer is one the caller can already meet.
    #[test]
    fn a_band_whose_interval_outruns_time_rereads_no_more() {
        let every = Duration::from_millis(millis_to_the_end_of_time(an_instant()) + 1);
        let (mut shown, panes) = shown_asking_every(a_staffed_grove(6), every);

        shown.tailed(read(A_SELECTED_PANE, &["what it says"]), an_instant());
        let asked_once = panes.reads();

        assert_eq!(shown.rereads_in(an_instant()), None);
        shown.reread(an_instant() + EVERY * 10);

        assert_eq!(panes.reads(), asked_once);
    }

    /// A row with no pane has nothing to read again, so the band sets no
    /// deadline and the loop is not woken for it.
    #[test]
    fn a_band_with_no_pane_is_never_due_to_read_one() {
        let (mut shown, panes) = shown_asking(a_grove(6));

        assert_eq!(shown.rereads_in(an_instant()), None);
        shown.reread(an_instant() + EVERY * 10);

        assert!(panes.reads().is_empty());
    }

    /// The selection leaving the pane disarms the read that was due for it:
    /// the pane it lands on is asked for at once, and that answer is what
    /// arms the next.
    #[test]
    fn leaving_the_pane_for_another_disarms_the_read_that_was_due_for_it() {
        let (mut shown, panes) = shown_asking(a_staffed_grove(6));
        let answered = an_instant();
        shown.tailed(read(A_SELECTED_PANE, &["what it says"]), answered);
        assert_eq!(shown.rereads_in(answered), Some(EVERY));

        shown.apply(Action::Move(Motion::NextRow));
        let Tail::Reading { pane: landed_on } = shown.tail.clone() else {
            panic!("the row below is another agent's pane: {:?}", shown.tail);
        };
        assert_ne!(landed_on, pane_key(A_SELECTED_PANE));

        assert_eq!(
            panes.reads().last(),
            Some(&format!("{} {}", landed_on.id, tail::LINES)),
            "the pane landed on is asked for at once"
        );
        assert_eq!(
            shown.rereads_in(answered),
            None,
            "and nothing is due while that read is out"
        );
        let asked = panes.reads();
        shown.reread(answered + EVERY);
        assert_eq!(
            panes.reads(),
            asked,
            "the first pane's interval coming round asks for nothing"
        );
    }

    /// The read the answer above asked for lands where the cursor is resting,
    /// so a tail that falls behind catches up rather than stopping.
    #[test]
    fn the_tail_catches_up_once_the_cursor_rests() {
        let (mut shown, _) = shown_asking(a_staffed_grove(6));
        to_the_last_row(&mut shown);
        let resting_on = match &shown.tail {
            Tail::Reading { pane } => pane.clone(),
            other => panic!("the band is still waiting on a pane: {other:?}"),
        };

        shown.tailed(
            read(A_SELECTED_PANE, &["about the pane left behind"]),
            an_instant(),
        );
        assert!(shown.tailed(
            read(&resting_on.id, &["about the pane rested on"]),
            an_instant()
        ));

        assert_eq!(
            shown.tail,
            Tail::Pane {
                pane: resting_on,
                lines: vec!["about the pane rested on".to_string()],
            }
        );
    }

    /// `⏎` asks for the pane and nothing on this screen changes for it:
    /// what changes is which terminal pane is in front of the reader.
    #[test]
    fn enter_asks_for_the_pane_and_draws_nothing() {
        let (mut shown, panes) = shown_asking(a_staffed_grove(6));

        assert!(!shown.apply(Action::Focus));

        assert_eq!(panes.focuses(), [A_SELECTED_PANE]);
    }

    #[test]
    fn a_pane_that_will_not_come_to_the_front_says_so_where_the_tail_is() {
        let (mut shown, _) = shown_asking(a_staffed_grove(6));

        assert!(shown.tailed(refused(A_SELECTED_PANE), an_instant()));

        assert_eq!(
            shown.tail,
            Tail::Silent(phrase::pane_unreadable(FailureKind::Gone))
        );
    }

    /// The rule above the band names the pane the band is about, so a refusal
    /// about a pane the reader has left would read as a refusal about the one
    /// they are on. It is dropped instead.
    #[test]
    fn a_focus_refused_for_a_pane_the_reader_has_left_is_not_drawn_over_the_one_they_are_on() {
        let (mut shown, _) = shown_asking(a_staffed_grove(6));
        assert!(shown.apply(Action::Move(Motion::NextRow)));
        let was = shown.tail.clone();

        assert!(!shown.tailed(refused(A_SELECTED_PANE), an_instant()));

        assert_eq!(shown.tail, was);
    }

    /// What the terminal was handed for its clipboard, byte for byte.
    #[derive(Clone, Default)]
    struct Clipboard(Arc<Mutex<Vec<u8>>>);

    impl Clipboard {
        fn written(&self) -> Vec<u8> {
            self.0.lock().expect("no test panics holding this").clone()
        }
    }

    impl io::Write for Clipboard {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.0
                .lock()
                .expect("no test panics holding this")
                .extend_from_slice(buf);
            Ok(buf.len())
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    /// The same, with what was written to the terminal's clipboard kept
    /// beside it.
    fn shown_copying(snapshot: Snapshot) -> (Shown, Clipboard) {
        let clipboard = Clipboard::default();
        (
            Shown::of(
                snapshot,
                Box::new(Asking::default()),
                Box::new(clipboard.clone()),
                drawing(),
                nothing_said(),
                an_instant(),
            ),
            clipboard,
        )
    }

    /// The text one OSC 52 sequence carries, where the bytes are exactly one
    /// such sequence and nothing else. Decoded rather than matched, so the
    /// test says what the terminal will paste and not what `bdi` wrote.
    fn on_the_clipboard(written: &[u8]) -> String {
        let payload = written
            .strip_prefix(b"\x1b]52;c;")
            .and_then(|rest| rest.strip_suffix(b"\x07"))
            .unwrap_or_else(|| panic!("not one OSC 52 sequence and nothing else: {written:?}"));
        String::from_utf8(BASE64_STANDARD.decode(payload).expect("base64")).expect("utf-8")
    }

    /// `y` on a bead row puts that bead's id — the id alone, exactly as `bd`
    /// takes it — on the terminal's clipboard, and writes nothing else.
    #[test]
    fn y_on_a_bead_row_puts_its_id_on_the_clipboard_and_nothing_else() {
        let (mut shown, clipboard) = shown_copying(a_grove(6));
        assert_eq!(cursor(&shown), Some(&bead("grove", "grv-1")));

        press(&mut shown, KeyCode::Char('y'));

        assert_eq!(on_the_clipboard(&clipboard.written()), "grv-1");
    }

    /// A project line and a group's line name no bead, so there is nothing
    /// to copy and nothing has gone wrong — the same as Enter there.
    #[test]
    fn y_on_a_row_that_is_not_a_bead_writes_nothing() {
        let (mut shown, clipboard) = shown_copying(a_hidden_grove_above_a_shown_tree());
        shown.apply(Action::Move(Motion::FirstRow));
        assert_eq!(cursor(&shown), None, "a project's line names no bead");

        assert!(!shown.apply(Action::CopyId));

        assert_eq!(clipboard.written(), b"");
    }

    /// A hidden tree's row names its root, so `y` there copies that id.
    #[test]
    fn y_on_a_hidden_trees_row_copies_its_root() {
        let (mut shown, clipboard) = shown_copying(a_hidden_grove_above_a_shown_tree());
        select_hidden_tree(&mut shown);

        press(&mut shown, KeyCode::Char('y'));

        assert_eq!(on_the_clipboard(&clipboard.written()), "grv-1");
    }

    // ---- searching for a bead by id ---------------------------------------

    /// Type an id into the prompt and ask for it.
    fn search_for(shown: &mut Shown, id: &str) {
        press(shown, KeyCode::Char('/'));
        for glyph in id.chars() {
            shown.typing(Typing::Character(glyph));
        }
        shown.typing(Typing::Sought);
    }

    /// The prompt takes the foot for as long as it is up, and what the reader
    /// types appears in it behind the key they opened it with — which is how
    /// every terminal they have searched in draws one.
    #[test]
    fn the_prompt_draws_what_the_reader_has_typed_into_it() {
        let mut shown = shown(a_grove(6));

        press(&mut shown, KeyCode::Char('/'));
        assert_eq!(foot_of(&mut shown, 80, 24).trim_end(), "/");

        for glyph in "grv-1.3".chars() {
            shown.typing(Typing::Character(glyph));
        }

        assert_eq!(foot_of(&mut shown, 80, 24).trim_end(), "/grv-1.3");
    }

    /// Backspace takes the last character back, and on an empty prompt it
    /// takes nothing and changes nothing — a reader holding it down has
    /// already arrived where they were going.
    #[test]
    fn backspace_takes_the_last_character_of_the_id_back() {
        let mut shown = shown(a_grove(6));
        press(&mut shown, KeyCode::Char('/'));
        for glyph in "grv".chars() {
            shown.typing(Typing::Character(glyph));
        }

        assert!(shown.typing(Typing::RubbedOut));
        assert_eq!(foot_of(&mut shown, 80, 24).trim_end(), "/gr");

        assert!(shown.typing(Typing::RubbedOut));
        assert!(shown.typing(Typing::RubbedOut));
        assert!(
            !shown.typing(Typing::RubbedOut),
            "an empty prompt gave a character back"
        );
        assert_eq!(foot_of(&mut shown, 80, 24).trim_end(), "/");
    }

    /// The selection moves onto the bead and the foot names it whole, even
    /// where it was the only match.
    ///
    /// The row cannot say it: the id drawn there is the *shortened* one, and
    /// the reader typed a fragment rather than a name, so what they landed on
    /// is exactly what they cannot read off the screen.
    #[test]
    fn a_search_moves_the_selection_onto_the_bead_and_names_it_whole() {
        let mut shown = shown(a_grove(6));
        assert_eq!(cursor(&shown), Some(&bead("grove", "grv-1")));

        search_for(&mut shown, "grv-1.3");

        assert_eq!(cursor(&shown), Some(&bead("grove", "grv-1.3")));
        assert!(
            foot_of(&mut shown, 80, 24).contains("grove · grv-1.3 — the only match"),
            "{:?}",
            foot_of(&mut shown, 80, 24)
        );
    }

    /// A search matching more than one bead says which of them the reader is
    /// on and how many there are. No row can say the second half, and the
    /// count is the whole reason a search that lands still speaks up.
    #[test]
    fn a_search_matching_several_beads_says_which_one_of_how_many() {
        let mut shown = shown(a_grove(6));

        search_for(&mut shown, "grv-1.");

        assert!(
            foot_of(&mut shown, 80, 24).contains("grove · grv-1.1 — 1 of 6 matching"),
            "{:?}",
            foot_of(&mut shown, 80, 24)
        );
    }

    /// `n` walks on to the next one, and the count walks with it.
    #[test]
    fn n_steps_to_the_next_match_and_the_foot_counts_along() {
        let mut shown = shown(a_grove(6));
        search_for(&mut shown, "grv-1.");

        press(&mut shown, KeyCode::Char('n'));

        assert_eq!(cursor(&shown), Some(&bead("grove", "grv-1.2")));
        assert!(
            foot_of(&mut shown, 80, 24).contains("grove · grv-1.2 — 2 of 6 matching"),
            "{:?}",
            foot_of(&mut shown, 80, 24)
        );
    }

    /// `n` before anything has been searched for has nothing to step through.
    /// Nothing has gone wrong, so nothing is said and nothing moves — the
    /// same answer `f` gives a row with no pane behind it.
    #[test]
    fn n_before_a_search_says_nothing_and_moves_nothing() {
        let mut shown = shown(a_grove(6));
        let was = cursor(&shown).cloned();

        press(&mut shown, KeyCode::Char('n'));

        assert_eq!(cursor(&shown).cloned(), was);
        assert_eq!(foot_of(&mut shown, 80, 24).trim_end(), key_row());
    }

    /// Text no tracker read holds says so, and says it as what `bdi` has read
    /// rather than as what exists — a tracker that refused holds beads no
    /// read has seen. The selection is left exactly where it was.
    #[test]
    fn text_no_tracker_read_holds_is_said_at_the_foot_and_moves_nothing() {
        let mut shown = shown(a_grove(6));
        press(&mut shown, KeyCode::Char('j'));
        let was = cursor(&shown).cloned();

        search_for(&mut shown, "grv-404");

        assert_eq!(cursor(&shown).cloned(), was);
        assert!(
            foot_of(&mut shown, 80, 24)
                .contains("nothing matching \"grv-404\" in any tracker read"),
            "{:?}",
            foot_of(&mut shown, 80, 24)
        );
    }

    /// The bead's own rule: Esc leaves the prompt with the selection where it
    /// was, whatever was typed into it.
    #[test]
    fn esc_leaves_the_prompt_with_the_selection_where_it_was() {
        let mut shown = shown(a_grove(6));
        press(&mut shown, KeyCode::Char('j'));
        let was = cursor(&shown).cloned();

        press(&mut shown, KeyCode::Char('/'));
        for glyph in "grv-1.3".chars() {
            shown.typing(Typing::Character(glyph));
        }
        assert!(shown.typing(Typing::Abandoned));

        assert_eq!(cursor(&shown).cloned(), was);
        assert_eq!(
            foot_of(&mut shown, 80, 24).trim_end(),
            key_row(),
            "a prompt nobody asked anything of answered anyway"
        );
    }

    /// Enter on an empty prompt asks nothing and answers nothing. The reader
    /// opened the prompt and changed their mind, and an answer about the
    /// empty id would be an answer to a question nobody put.
    #[test]
    fn enter_on_an_empty_prompt_says_nothing_and_moves_nothing() {
        let mut shown = shown(a_grove(6));
        let was = cursor(&shown).cloned();

        search_for(&mut shown, "");

        assert_eq!(cursor(&shown).cloned(), was);
        assert_eq!(foot_of(&mut shown, 80, 24).trim_end(), key_row());
    }

    /// What the foot says back to a keystroke goes on the reader's next press
    /// whatever that press means — the same rule a copied id has always kept,
    /// and the reason both are one field rather than two cleared alike.
    #[test]
    fn the_readers_next_press_takes_a_searchs_answer_off_the_foot() {
        let mut shown = shown(a_grove(6));
        search_for(&mut shown, "grv-404");
        assert!(foot_of(&mut shown, 80, 24).contains("nothing matching \"grv-404\""));

        assert!(shown.pressed());

        assert_eq!(foot_of(&mut shown, 80, 24).trim_end(), key_row());
    }

    /// The row at the foot of a frame of this screen, as drawn.
    fn foot_of(shown: &mut Shown, width: u16, height: u16) -> String {
        painted(
            &mut shown.forest,
            &shown.tail,
            Over::Nothing,
            Pressed {
                said: shown.said.as_ref(),
                prompt: shown.sought.as_deref(),
            },
            &[],
            width,
            height,
        )
        .rows()
        .pop()
        .expect("a screen with rows on it")
    }

    /// Nothing else on the screen changes for a copy, so the foot is where a
    /// reader learns the key fired — and which id it took, on a row whose id
    /// may be abbreviated.
    #[test]
    fn after_y_the_foot_says_which_id_was_copied() {
        let (mut shown, _) = shown_copying(a_grove(6));

        assert!(shown.apply(Action::CopyId), "the foot has changed");

        assert!(
            foot_of(&mut shown, 80, 24).contains("copied grv-1"),
            "{:?}",
            foot_of(&mut shown, 80, 24)
        );
    }

    /// The reader's next press takes it off, whatever the press turns out to
    /// mean: it was feedback on a keystroke, not a fact about the screen. The
    /// screen has changed for that alone, so the press is one to redraw on.
    #[test]
    fn the_readers_next_press_takes_the_copied_id_off_the_foot() {
        let (mut shown, _) = shown_copying(a_grove(6));
        shown.apply(Action::CopyId);

        assert!(shown.pressed(), "the foot has changed");

        assert!(!foot_of(&mut shown, 80, 24).contains("copied"));
    }

    /// With nothing on the foot to take off, a press changes nothing here,
    /// so a key bound to nothing goes on costing no redraw.
    #[test]
    fn a_press_with_nothing_copied_changes_nothing() {
        assert!(!shown(a_grove(6)).pressed());
    }

    /// What happens behind the reader's back is not the reader's next
    /// action: a collection landing a moment after `y` would otherwise take
    /// the feedback off before anyone had read it.
    #[test]
    fn a_collection_landing_leaves_the_copied_id_on_the_foot() {
        let (mut shown, _) = shown_copying(a_grove(6));
        shown.apply(Action::CopyId);

        shown.collected(a_grove(6));

        assert!(foot_of(&mut shown, 80, 24).contains("copied grv-1"));
    }

    /// A terminal that will not take the write.
    struct Refusing;

    impl io::Write for Refusing {
        fn write(&mut self, _: &[u8]) -> io::Result<usize> {
            Err(io::Error::from(io::ErrorKind::BrokenPipe))
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    /// A foot that said *copied* over a write that never reached the terminal
    /// would be the one line on the screen that was untrue.
    #[test]
    fn a_write_the_terminal_refused_is_not_reported_as_copied() {
        let mut shown = Shown::of(
            a_grove(6),
            Box::new(Asking::default()),
            Box::new(Refusing),
            drawing(),
            nothing_said(),
            an_instant(),
        );

        assert!(!shown.apply(Action::CopyId));

        assert!(!foot_of(&mut shown, 80, 24).contains("copied"));
    }

    #[test]
    fn a_frame_puts_the_tail_in_the_band_reserved_for_it() {
        let mut forest = an_open_grove(30);
        let tail = Tail::Pane {
            pane: pane_key("w:p1"),
            lines: vec!["rebuilt .#larkspur".to_string()],
        };

        let rows = screen_of(&mut forest, &tail, 40, 12, Over::Nothing).rows();
        let bands = draw::regions(Rect::new(0, 0, 40, 12));

        assert!(
            rows[bands.tail.y as usize].contains("w:p1"),
            "the rule naming the pane opens the tail's band: {rows:?}"
        );
        assert!(rows[bands.tail.y as usize + 1].starts_with("  rebuilt .#larkspur"));
        assert!(
            rows[bands.tail.y as usize - 1].contains("a bead in the grove"),
            "the row above the tail is still the forest's"
        );
        assert!(rows[bands.keys.y as usize].contains("q quit"));
    }
}