1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
//! The lookout's state and its reducer: `Msg` in, `Effect` out.
//!
//! No I/O, no terminal types, no clock. [`App::update`] is synchronous, work
//! for the outside comes back as an [`Effect`] the caller runs, and every
//! `Instant` arrives on a message.
//!
//! The bus is lossy, so [`Msg::Event`] upserts and [`Msg::Snapshot`] replaces
//! the whole flock map. The cursor is a [`RowKey`], not a row index: the map is
//! replaced wholesale every two seconds, and [`App::reseat`] puts the cursor
//! back on a real row.
use core::fmt;
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::time::{Duration, Instant};
use shep_client::RequestError;
use shep_core::config::LogLevel;
use shep_core::protocol::{
BusEvent, DogSectionToml, DogSource, EnvValue, Lamb, ProcessEventKind, ProcessInfo, Request,
Response, SelectorSpec,
};
use shep_core::status::ProcStatus;
use super::field::{FieldKind, FieldSet};
use super::pane::{ConfigPane, FieldValue, Lock, PaneEdit, PanePending, PaneTarget, ReloadKind};
use super::theme::Palette;
use super::viewport::Viewport;
use crate::commands::settings::{SettingEdit, SettingField, SettingsSnapshot, settings_field_set};
use crate::style::{StyleLevel, StyleSource};
use crate::vocabulary::Reported;
/// Whether this lookout may act on a sheep.
///
/// Turned on by `--allow-control` or `lookout.allow_control` in the KV store.
/// A fat-finger catch, not a security boundary: anyone who can run lookout can
/// run `shep stop`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Control {
/// Actions refuse. Asked for by `--read-only`, or by
/// `lookout.allow_control` being `false`.
ReadOnly,
/// Actions are permitted, and the default: `x`, `R` and `L` arm a
/// confirm, Enter sends it. The apply menu is the one door that sends on
/// the press, since it names its keys on screen.
Allowed,
}
/// Which keymap is in force.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputMode {
/// The ordinary dashboard keys.
Normal,
/// The filter box is open and every printable key is text.
Text,
}
/// The keys lookout binds, named by meaning rather than by keystroke.
///
/// `super::input::map_key` builds these at the edge, so this module never
/// touches a terminal crate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyPress {
/// `q` in normal mode, or `Ctrl-C` in either.
Quit,
/// `Esc` in normal mode: cancels an armed confirm, else clears the filter,
/// else quits. The reducer decides; the keymap sees none of those states.
Escape,
/// `k` or `Up`: the selection moves up one row.
SelectUp,
/// `j` or `Down`: the selection moves down one row.
SelectDown,
/// `g` or `Home`: the first sheep in the flock.
SelectFirst,
/// `G` or `End`: the last one.
SelectLast,
/// `r`: poll now.
Refresh,
/// `x`, `R` or `L`: arms a confirm for the verb, or refuses and says why.
Action(ActionVerb),
/// `Enter` in normal mode. Sends an armed confirm; does nothing
/// otherwise.
Confirm,
/// `/`: open the filter box, carrying whatever query is already set.
FilterStart,
/// One printable character typed into whichever text field is open.
TextChar(char),
/// `Backspace` in whichever text field is open.
TextBackspace,
/// `Enter` in whichever text field is open: apply and leave.
TextApply,
/// `Esc` in whichever text field is open: abandon the edit and leave.
TextAbandon,
/// `s`: opens the settings screen, or closes it from inside.
Settings,
/// `space`: cycles the value under the settings screen's cursor. Nothing on
/// the dashboard; refuses like an action key when the gate is closed.
Cycle,
/// `e`: open the config pane for the selected sheep on the dashboard.
/// Inside the pane or its env sub-screen, edits the row under the
/// cursor or sends an armed edit, the same job `Confirm` already does
/// there: an operator should not have to remember two keys for one
/// job. `Escape` is the only key that closes a pane or a sub-screen.
Edit,
/// `h`: shows the selected field's own help text, in the config pane.
/// Pressing it again, or `Escape`, dismisses it. Bound nowhere else.
Help,
/// `d`: arms the removal of the element under the cursor, on the config
/// pane's list sub-screen. Bound nowhere else, and named for that
/// screen so every other screen's own keymap reads as the no-op it is.
ListRemove,
/// `K`: arms the element under the cursor moving up one place, on the
/// same sub-screen.
ListMoveUp,
/// `J`: the same, moving down.
ListMoveDown,
}
/// Everything that can change the dashboard.
#[derive(Debug, Clone)]
pub enum Msg {
/// A `Request::ListFlock` reply landed. `at` is when it was received, and
/// becomes every row's uptime anchor.
Snapshot {
/// The flock as the shepherd reported it.
rows: Vec<ProcessInfo>,
/// When the reply was received.
at: Instant,
},
/// One frame off the bus.
Event(BusEvent),
/// This client's own receiver fell behind and discarded frames.
/// [`BusEvent::Dropped`] is the shepherd's queue instead.
BusLagged {
/// How many frames this process lost.
count: u64,
},
/// The link task is re-dialling; `attempt` is 1-based.
Retrying {
/// Which attempt is in flight.
attempt: u32,
},
/// The link task reconnected and re-subscribed.
Relinked,
/// The reconnect ladder is exhausted. Everything on screen is now frozen.
Frozen {
/// When the link was declared lost, already rendered for display.
at_local: String,
},
/// One key.
Key(KeyPress),
/// The 1s heartbeat. `now` is what advances every running sheep's uptime.
Tick {
/// The current instant, read by the caller.
now: Instant,
},
/// The terminal changed size; nothing to update but the frame is stale.
Resize,
/// One reading of the machine this lookout runs on, off the 1s heartbeat.
/// `None` means `sysinfo` does not support this platform. Refused once the
/// link is lost.
Host {
/// What the sampler saw, or `None` on an unsupported platform.
sample: Option<super::source::HostSample>,
},
/// One refresh of the selected sheep's log files, answering an
/// [`Effect::RefreshFeed`]. Always yields [`Effect::None`].
Bleats {
/// What the read found, including what it could not show.
tail: super::tail::Tail,
},
/// A request this dashboard asked for came back. `sent` is the echo tag.
Replied {
/// What was asked.
sent: Sent,
/// What the shepherd said, or why it could not be asked.
result: Result<Response, RequestError>,
},
/// A request the caller could not hand to the link task.
///
/// The reducer is already in the in-flight state when `run_ui` tries to
/// send, so a failed `try_send` has to come back, or the
/// one-action-at-a-time guard refuses everything from then on.
Unsent {
/// What could not be sent.
sent: Sent,
},
/// The settings screen's read of `shep.toml` landed, answering an
/// [`Effect::LoadSettings`]. A `String` error, since this reducer holds no
/// error types from `commands`.
Settings {
/// The rendered snapshot, or why it could not be read.
result: Result<SettingsSnapshot, String>,
},
/// An [`Effect::WriteSetting`] has landed.
SettingWritten {
/// The edit that was sent, echoed back: the cursor can have moved on
/// while the write was in flight.
edit: SettingEdit,
/// Whether the write landed, or why it did not.
result: Result<(), String>,
},
/// An [`Effect::LoadDogPane`]'s schema probe has answered.
///
/// The schema half only: the section arrives separately over the wire
/// as [`Sent::DogSection`], since it comes from the shepherd rather
/// than the dog's own binary. This arm parks the schema and raises the
/// request for the section; the pane is built once that lands.
///
/// `Result<_, String>`, like [`Self::Settings`]: this reducer holds no
/// error types from `commands`.
DogPane {
/// The dog.
name: String,
/// The adopted binary, or [`None`] for a built-in, echoed back so
/// the pane records what it probed.
adopted_path: Option<PathBuf>,
/// The dog's schema, or why there is no pane for it.
result: Result<serde_json::Value, String>,
},
/// An [`Effect::WriteDog`] has landed. `Ok` carries the [`DogSource`] the
/// write resolved, which [`Sent::Dog`] then rides to the shepherd, so the
/// request cannot disagree with the file.
DogWritten {
/// The toggle that was sent, echoed back.
edit: DogEdit,
/// Whether the write landed and what it resolved to, or why it did
/// not.
result: Result<DogSource, String>,
},
}
/// The one gate on writing `shep.toml` from the settings screen.
///
/// [`WriteAuthority`]'s field is private, so [`WriteAuthority::granted`] is the
/// only way to build one, and it hands back [`None`] under
/// [`Control::ReadOnly`]. [`Effect::WriteSetting`] and [`Effect::WriteDog`]
/// each carry one, so a handler cannot name a write without the check.
mod authority {
use super::App;
/// Proof that `--allow-control` was on when a settings write was built.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WriteAuthority(());
impl WriteAuthority {
/// A token when `app`'s [`Control`](super::Control) permits writing,
/// [`None`] otherwise.
///
/// The sole constructor, taking `&App` rather than a `Control` so the
/// answer can only be the app's own gate.
#[must_use]
pub fn granted(app: &App) -> Option<Self> {
match app.control {
super::Control::ReadOnly => None,
super::Control::Allowed => Some(Self(())),
}
}
}
}
pub use authority::WriteAuthority;
/// What the caller has to do after an update.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Effect {
/// Nothing.
None,
/// Ask the link task for a `ListFlock` now, rather than at the next tick.
PollNow,
/// Re-read the selected sheep's log files and hand the result back as
/// [`Msg::Bleats`]. The feed has no timer of its own; it rides this.
RefreshFeed,
/// Re-read the selected sheep's log files and ask the shepherd for its
/// lambs. Raised only when the selection moved: a snapshot refreshes the
/// feed alone, since it fires every two seconds.
RefreshSelected,
/// Send a request to the shepherd. Raised by [`App::confirm`] once an
/// armed action's Enter lands; `super::run_ui` sends it.
Send(Sent),
/// Leave.
Quit,
/// Read `shep.toml`'s settings snapshot; the result lands as
/// [`Msg::Settings`]. Raised by the dashboard's `s`; once the screen is
/// open, `s` closes it instead.
LoadSettings,
/// Apply one edit to `shep.toml`; the result lands as
/// [`Msg::SettingWritten`].
///
/// Must run on `spawn_blocking`: `ConfigLock::acquire` blocks with no
/// deadline, and the UI task's redraw, tick and bus drain would block with
/// the write.
WriteSetting(SettingEdit, WriteAuthority),
/// Probe one dog for its config schema; the answer lands as
/// [`Msg::DogPane`].
///
/// A dog's schema is not persisted anywhere, so the pane asks at open:
/// `shep adopt` uses the answer for the vet and records only the path.
/// A built-in dog is this binary, so it is asked in-process
/// (`crate::dog::builtin_schema`); an adopted one is spawned with the
/// schema flag, which is why `super::run_ui` runs this on
/// `spawn_blocking`: it costs up to `VERSION_BUDGET` of somebody
/// else's binary starting up, and the redraw task cannot wait for that.
///
/// No [`WriteAuthority`]: this reads. The pane it opens is gated on
/// every keystroke that writes, the same as a sheep pane.
LoadDogPane {
/// The dog.
name: String,
/// The adopted binary, or [`None`] for a built-in.
adopted_path: Option<PathBuf>,
},
/// Apply one dog's file half; the result lands as [`Msg::DogWritten`].
///
/// Its own effect, not [`Self::WriteSetting`]: it ends in a request to the
/// shepherd ([`Sent::Dog`]) where a scalar write ends in a notice.
/// `spawn_blocking`, for [`Self::WriteSetting`]'s reason.
WriteDog(DogEdit, WriteAuthority),
}
/// The connection's state, as the dashboard reports it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Link {
/// Connected and subscribed.
Live,
/// Re-dialling. `attempt` is 1-based and bounded by
/// `super::link::RECONNECT_ATTEMPTS`.
Retrying {
/// Which attempt is in flight.
attempt: u32,
},
/// The ladder is exhausted. Terminal: nothing moves this state, and the
/// values on screen stay as they were.
Lost {
/// When it was declared lost, already rendered for display.
at_local: String,
},
}
/// One sheep's row: what the shepherd said, and when it said it.
#[derive(Debug, Clone)]
pub struct Row {
/// The shepherd's own snapshot of this sheep.
pub info: ProcessInfo,
/// When [`Self::info`] was received: the origin for this row's live
/// uptime, so a value two seconds old is never rendered as current.
pub anchor: Instant,
}
impl Row {
/// What this row's STATUS cell reports: [`Self::info`]'s status, or
/// [`Reported::Silent`] for a dog whose process is up and which has never
/// handshook this shepherd.
///
/// Mirrors `output::rows::reported`. The `dog` check is read here rather
/// than left to [`Reported::of`], so a non-dog row can never be painted
/// silent by a stray `handshook`.
#[must_use]
pub(crate) fn reported(&self) -> Reported {
if self.info.dog.is_none() {
return Reported::Live(self.info.status);
}
Reported::of(self.info.status, self.info.handshook)
}
}
/// One app's rolled-up numbers, computed from its own instances.
///
/// The fields `output::rows`'s own `GroupTotals` sums for `shep flock`.
/// Restarts, cpu and memory are summed; uptime is the minimum, so a group reads
/// as time since the app was last disturbed.
#[derive(Debug, Clone)]
pub struct GroupTotals {
/// How many instances make up this group.
pub count: usize,
/// Every instance's restarts, added up.
pub restarts: u32,
/// Every instance's CPU reading summed, `None` only when not one
/// instance has a live reading.
pub cpu: Option<f32>,
/// Every instance's memory reading summed, `None` only when not one
/// instance has a live reading.
pub memory: Option<u64>,
/// The minimum live uptime across instances, `None` only when the group
/// has none.
pub uptime_ms: Option<u64>,
}
/// One request the dashboard asked the link task to send, carried back on the
/// reply so it can be routed.
///
/// An echo tag rather than a correlation id: an `Err` reply carries no shape of
/// its own.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Sent {
/// The selected sheep's process tree.
Lambs {
/// Which sheep was asked about.
id: u32,
},
/// One action against a target: one sheep, or every instance of a named
/// app. `name` rides along so a reply can be reported by name even after
/// the target has left the flock.
Action {
/// Which verb.
verb: ActionVerb,
/// The pinned target.
target: RowKey,
/// Its name at arm time.
name: String,
},
/// One dog's daemon half, after its file half landed. `source` is what
/// the write returned, so the request cannot disagree with the file.
Dog {
/// The dog's name.
name: String,
/// `true` to start it, `false` to stop and deregister it.
enable: bool,
/// Where the binary comes from, exactly as the config write
/// answered.
source: DogSource,
},
/// One sheep's effective config, for the config pane. Raised by `e` on
/// the dashboard and by `r` from inside an open pane.
///
/// A name rather than a [`RowKey`], because [`Request::SheepConfig`]
/// takes one: the pane is about an app's stored spec, which every
/// instance of a multi-instance app shares, so an id would name a
/// narrower thing than the config it would come back with.
SheepConfig {
/// Which sheep was asked about.
name: String,
},
/// One field of one sheep's config, off the config pane's own `Enter`.
///
/// [`Self::SetEnv`]'s twin, and it is a `Request::SetSheepField`
/// rather than a one-key `Request::ApplyConfig` for the reason that
/// variant's own doc gives: an `ApplyConfig` at `ResetDepth::File`
/// moves the field and then spends the operator's override for it,
/// because that merge is a template load. This pane's value is the
/// operator's, so the sheep still differs from its file and the `*`
/// marker has to keep saying so.
///
/// The [`WriteAuthority`] is not decoration, for exactly the reason
/// [`Effect::WriteSetting`]'s own doc gives: this variant cannot be
/// named without having passed the gate, so a fifth door added
/// tomorrow cannot walk around it.
ApplyField {
/// The sheep.
name: String,
/// Which write this is, so a reply settles its own in-flight line
/// and no other. See [`PanePending::Sent`].
ticket: u64,
/// The field that moves.
key: String,
/// Its new value, in the shape that field serializes as. Wrapped,
/// so a `{:?}` of this enum cannot print it: `cwd` and `script`
/// hold a home directory and `args` holds a token (IR-41).
value: FieldValue,
/// Proof the control gate was open.
authority: WriteAuthority,
},
/// One dog's `[<name>]` section, for the dog config pane. Raised once
/// the pane's schema probe has answered, and again by `r` from inside an
/// open dog pane and after a landed write.
///
/// The schema is not asked for here and never travels the wire: it comes
/// off the dog's own binary ([`Effect::LoadDogPane`]), because nothing
/// records one. `shep adopt` uses it for the vet and writes down only
/// the path.
DogSection {
/// Which dog was asked about.
name: String,
},
/// One dog's whole section, off the dog pane's own `Enter`.
///
/// The whole section rather than one key, because
/// `Request::SetDogConfig` replaces the table: `ConfigPane::edited_section`
/// applies the edit through `toml_edit`, so the operator's comments and
/// key order survive a write shep did not author.
///
/// Not a `Request::ApplyConfig`, and not for [`Self::ApplyField`]'s
/// reason either: a dog has no override store and no Flockfile. Its
/// section is the operator's outright, and `dogs.toml` is the one copy
/// of it.
///
/// The [`WriteAuthority`] is not decoration, for the reason
/// [`Effect::WriteSetting`]'s own doc gives.
SetDogSection {
/// The dog.
name: String,
/// Which write this is, so a reply settles its own in-flight line
/// and no other. See [`PanePending::Sent`].
ticket: u64,
/// The section, edit applied. [`DogSectionToml`] rather than a
/// `String` so a `{:?}` of this enum cannot print the webhook
/// credentials a dog's section routinely holds (IR-41).
toml: DogSectionToml,
/// Proof the control gate was open.
authority: WriteAuthority,
},
/// One env key of one sheep, off the env sub-screen's own `Enter`.
///
/// Its own variant beside [`Self::ApplyField`] rather than a value of
/// it, because the two are different requests: a whole env map is
/// never sent (a pane is not told the values), so `SetSheepField`
/// refuses the `env` key outright and `SetSheepEnv` takes one key at a
/// time.
SetEnv {
/// The sheep.
name: String,
/// Which write this is, for [`Self::ApplyField`]'s reason.
ticket: u64,
/// The env key.
key: String,
/// The value, or `None` to remove the key. [`EnvValue`] rather than
/// a `String` so a `{:?}` of this enum cannot print it (IR-41).
value: Option<EnvValue>,
/// Proof the control gate was open.
authority: WriteAuthority,
},
}
impl Sent {
/// The wire request this asks for.
#[must_use]
pub fn request(&self) -> Request {
match self {
Self::Lambs { id } => Request::Describe {
selector: SelectorSpec::Id(*id),
},
Self::Action { verb, target, .. } => {
let selector = match target {
RowKey::Sheep(id) => SelectorSpec::Id(*id),
RowKey::Group(name) => SelectorSpec::Name(name.clone()),
RowKey::Section(_) => unreachable!("a header is never an action target"),
};
match verb {
ActionVerb::Stop => Request::Stop { selector },
ActionVerb::Restart => Request::Restart { selector },
ActionVerb::Reload => Request::Reload { selector },
}
}
Self::Dog {
name,
enable: true,
source,
} => Request::EnableDog {
name: name.clone(),
source: source.clone(),
},
Self::Dog {
name,
enable: false,
..
} => Request::DisableDog { name: name.clone() },
Self::SheepConfig { name } => Request::SheepConfig { name: name.clone() },
// One field, recorded as an operator override, not an
// `ApplyConfig`: see this variant's own doc for the marker that
// route silently spent.
Self::ApplyField {
name, key, value, ..
} => Request::SetSheepField {
name: name.clone(),
key: key.clone(),
// Unwrapped only here, at the wire. See `FieldValue` for
// why the protocol's own field is a bare `Value` while
// everything above it is not.
value: value.as_value().clone(),
},
Self::DogSection { name } => Request::DogConfig { name: name.clone() },
Self::SetDogSection { name, toml, .. } => Request::SetDogConfig {
name: name.clone(),
toml: toml.clone(),
},
Self::SetEnv {
name, key, value, ..
} => Request::SetSheepEnv {
name: name.clone(),
key: key.clone(),
value: value.clone(),
},
}
}
}
/// One dog toggle, ready for the file half: [`Effect::WriteDog`] carries one
/// and [`Msg::DogWritten`] echoes it back.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DogEdit {
/// The dog's name.
pub name: String,
/// `true` to enable, `false` to disable.
pub enable: bool,
}
/// A dog's schema, and the binary it was probed from.
///
/// Held on [`App`] between the probe answering ([`Msg::DogPane`]) and the
/// section landing ([`Sent::DogSection`]), and then for as long as the pane
/// is open, so a refresh re-reads the section without respawning the dog.
///
/// `Debug` is derived rather than redacted (IR-41): a name, a binary's path
/// and a JSON Schema. A schema describes values without carrying any, the
/// same argument `super::field::Field`'s own derived `Debug` makes, and a
/// dog's defaults come from its binary describing itself rather than from
/// this flock.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DogProbe {
/// The dog.
pub name: String,
/// The adopted binary, or [`None`] for a built-in.
pub adopted_path: Option<PathBuf>,
/// What it answered the schema flag with.
pub schema: serde_json::Value,
}
/// What the cursor can sit on: one sheep, or the header above an app's
/// instances.
///
/// A name earns a [`Self::Group`] only with more than one instance, every one
/// of them reporting its slot ([`App::is_grouped`]).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum RowKey {
/// One app's group header, carrying its name.
Group(String),
/// One sheep, by id.
Sheep(u32),
/// A header, never selectable. `&'static str` because the only two are
/// written here.
Section(&'static str),
}
/// What one lamb fetch came back with. The pane says a different sentence for
/// each variant.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LambWalk {
/// The shepherd walked the process table. Possibly to no descendants.
Walked(Vec<Lamb>),
/// The reply carried no walk at all, which for a `Describe` means this
/// sheep has no pid to walk from.
NotWalked,
/// The request did not come back, or came back as something this binary
/// does not understand.
Failed,
}
/// One lamb reading, and which sheep it was taken for.
#[derive(Debug, Clone)]
pub struct LambReading {
id: u32,
at: Instant,
walk: LambWalk,
}
/// A short line the status bar shows instead of the key hints, cleared by the
/// next keypress.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Notice {
text: String,
/// True for a refusal or a damage report: the status bar picks
/// [`Palette::refusal`] over [`Palette::attention`].
grave: bool,
}
impl Notice {
/// Whether this notice is a refusal or a damage report rather than an
/// informational one.
#[must_use]
pub fn is_grave(&self) -> bool {
self.grave
}
}
impl fmt::Display for Notice {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.text)
}
}
/// One row the settings screen's cursor can sit on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SettingsRow {
/// One of the six scalar fields, in [`Settings::rows`]'s fixed order.
Scalar(SettingField),
/// Index into [`SettingsSnapshot::dogs`].
Dog(usize),
}
/// The settings screen's own state. `None` on [`App`] is the dashboard.
#[derive(Debug, Clone)]
pub struct Settings {
snapshot: SettingsSnapshot,
/// The six scalars' shape: which they are, in what order, under which
/// section. The screen reads its rows, labels and section headers off
/// this rather than off a `match` per question, so a config pane and
/// this screen answer them the same way.
fields: FieldSet,
/// The cursor and, once a terminal has said how tall the body is, the
/// scroll offset. Clamped on every read rather than kept pre-clamped: a
/// refresh can shrink the dog list out from under a cursor already
/// sitting past its new end.
view: Viewport,
/// The screen's one in-flight edit, or `None`. One field rather than
/// several `Option`s, so typing, armed and sent cannot overlap.
pending: Option<Pending>,
}
/// The settings screen's own in-flight edit.
#[derive(Debug, Clone)]
enum Pending {
/// A free-text edit under construction. Only [`SettingField::Socket`] and
/// [`SettingField::MaxCronSleep`] reach this, seeded with the field's
/// on-disk value.
Typing {
/// Which scalar.
field: SettingField,
/// What the operator has typed so far.
buffer: String,
},
/// Armed: waiting for the operator's `Enter`. Nothing has gone out yet.
Armed {
/// The candidate, ready to send.
edit: SettingEdit,
/// The question this candidate reads as, rendered once at arm time.
text: String,
/// When it was armed. Only an armed edit expires.
at: Instant,
},
/// [`Self::Armed`] for a [`DogEdit`] on a [`SettingsRow::Dog`] row, which
/// [`App::confirm_setting`] sends through [`Effect::WriteDog`].
DogArmed {
/// The candidate toggle, ready to send.
edit: DogEdit,
/// The question this candidate reads as, rendered once at arm time.
text: String,
/// When it was armed. Only an armed edit expires.
at: Instant,
},
/// [`Effect::WriteSetting`] or [`Effect::WriteDog`] is in flight. Carries
/// no `edit`: every match site reads the landing message's own copy.
Sent {
/// The same rendered question, so the prompt line does not change
/// wording between the question and its own answer.
text: String,
},
}
/// What the settings screen's status line shows for its one in-flight edit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SettingsPrompt<'a> {
/// The confirm sentence: what will change, and what applying it does and
/// does not do.
pub text: &'a str,
/// False while it is a question, true once it has gone out.
pub sent: bool,
}
impl Settings {
/// A freshly opened screen, cursor on the first row.
fn new(snapshot: SettingsSnapshot) -> Self {
Self {
snapshot,
fields: settings_field_set(),
view: Viewport::new(),
pending: None,
}
}
/// The armed candidate and its prompt, or `None`.
#[must_use]
pub fn pending(&self) -> Option<SettingsPrompt<'_>> {
match &self.pending {
Some(Pending::Armed { text, .. } | Pending::DogArmed { text, .. }) => {
Some(SettingsPrompt { text, sent: false })
}
Some(Pending::Sent { text, .. }) => Some(SettingsPrompt { text, sent: true }),
Some(Pending::Typing { .. }) | None => None,
}
}
/// Whether a candidate is waiting on `Enter`: the one state a stray key
/// (movement, `Escape`, `Settings`, `Refresh`) eats rather than also doing
/// its ordinary job.
fn is_armed(&self) -> bool {
matches!(
self.pending,
Some(Pending::Armed { .. } | Pending::DogArmed { .. })
)
}
/// The field and buffer of an in-flight free-text edit, or `None`.
#[must_use]
pub fn typing(&self) -> Option<(&SettingField, &str)> {
match &self.pending {
Some(Pending::Typing { field, buffer }) => Some((field, buffer.as_str())),
_ => None,
}
}
/// The next candidate for `field`, or `None` for the two free-text fields.
///
/// Advances from a candidate already armed for this field, so a second
/// `space` walks one step further along the cycle. From nothing armed the
/// base is what the file says, which for `[style] level` is
/// [`SettingsSnapshot::style_level_in_file`] rather than the level in
/// force: cycling the resolved level could propose a write that changes
/// nothing.
fn next_candidate(&self, field: SettingField) -> Option<String> {
let armed_here = match &self.pending {
Some(Pending::Armed {
edit:
SettingEdit::Set {
field: armed_field,
value,
},
..
}) if *armed_field == field => Some(value.as_str()),
_ => None,
};
let in_file = (field == SettingField::StyleLevel)
.then_some(self.snapshot.style_level_in_file.as_deref())
.flatten();
let base: String = match (armed_here, in_file) {
(Some(value), _) | (None, Some(value)) => value.to_string(),
// A `[style]` document declaring nothing falls back to
// `StyleLevel`'s compiled default, as `style::resolve` does.
(None, None) if field == SettingField::StyleLevel => STYLE_LEVEL_ORDER[0].to_string(),
(None, None) => self.current_value(field)?.to_string(),
};
Some(match field {
SettingField::LogLevel => next_log_level(&base),
SettingField::LogJson | SettingField::AllowControl => next_bool(&base),
SettingField::StyleLevel => next_style_level(&base),
SettingField::Socket | SettingField::MaxCronSleep => return None,
})
}
/// The snapshot's own rendered value for one of the four cycled scalars.
/// `None` for the two free-text ones.
fn current_value(&self, field: SettingField) -> Option<&str> {
Some(match field {
SettingField::LogLevel => self.snapshot.log_level.value.as_str(),
SettingField::LogJson => self.snapshot.log_json.value.as_str(),
SettingField::AllowControl => self.snapshot.allow_control.value.as_str(),
SettingField::StyleLevel => self.snapshot.style_level.value.as_str(),
SettingField::Socket | SettingField::MaxCronSleep => return None,
})
}
/// Which layer `field`'s value came from. Only [`confirm_text`]'s `[style]`
/// arm acts on it.
fn source_of(&self, field: SettingField) -> StyleSource {
match field {
SettingField::LogLevel => self.snapshot.log_level.source,
SettingField::LogJson => self.snapshot.log_json.source,
SettingField::Socket => self.snapshot.socket.source,
SettingField::MaxCronSleep => self.snapshot.max_cron_sleep.source,
SettingField::AllowControl => self.snapshot.allow_control.source,
SettingField::StyleLevel => self.snapshot.style_level.source,
}
}
/// The rendered value [`App::confirm_setting`] seeds [`Pending::Typing`]'s
/// buffer with. Only the two free-text fields reach it.
fn text_seed(&self, field: SettingField) -> &str {
match field {
SettingField::Socket => self.snapshot.socket.value.as_str(),
SettingField::MaxCronSleep => self.snapshot.max_cron_sleep.value.as_str(),
SettingField::LogLevel
| SettingField::LogJson
| SettingField::AllowControl
| SettingField::StyleLevel => {
unreachable!("text_seed only ever reaches the two free-text fields")
}
}
}
/// What the screen reads off disk, and renders every row's value and source
/// from.
///
/// A landed write does not update this in place: it raises a fresh
/// [`Effect::LoadSettings`], so `Set` and `Unset` land the same way and
/// neither can drift from the rest of the document.
#[must_use]
pub fn snapshot(&self) -> &SettingsSnapshot {
&self.snapshot
}
/// Every row the cursor can sit on: the six scalars in their fixed
/// order, then one row per candidate dog.
#[must_use]
pub fn rows(&self) -> Vec<SettingsRow> {
let mut rows: Vec<SettingsRow> = self
.fields
.fields()
.iter()
.filter_map(|f| SettingField::from_key(&f.key))
.map(SettingsRow::Scalar)
.collect();
rows.extend((0..self.snapshot.dogs.len()).map(SettingsRow::Dog));
rows
}
/// The field model behind the scalar rows.
#[must_use]
pub fn fields(&self) -> &FieldSet {
&self.fields
}
/// The row the cursor sits on. `None` only if [`Self::rows`] is empty,
/// which the six unconditional scalars make unreachable.
#[must_use]
pub fn cursor(&self) -> Option<SettingsRow> {
let rows = self.rows();
rows.get(self.view.cursor().min(rows.len().saturating_sub(1)))
.copied()
}
/// Moves the cursor by `delta` rows, clamped to [`Self::rows`], never
/// wrapping.
fn move_by(&mut self, delta: isize) {
let len = self.rows().len();
self.view.move_by(delta, len);
}
fn move_to_first(&mut self) {
let len = self.rows().len();
self.view.move_to(0, len);
}
fn move_to_last(&mut self) {
let len = self.rows().len();
self.view.move_to(len.saturating_sub(1), len);
}
/// The viewport, for the renderer.
#[must_use]
pub fn view(&self) -> &Viewport {
&self.view
}
/// Records the terminal's height.
pub fn set_rows(&mut self, rows: usize) {
let len = self.rows().len();
self.view.set_rows(rows, len);
}
}
/// [`LogLevel`]'s own declared order, wrapping from `Trace` back to `Off`.
pub(crate) const LOG_LEVEL_ORDER: [LogLevel; 6] = [
LogLevel::Off,
LogLevel::Error,
LogLevel::Warn,
LogLevel::Info,
LogLevel::Debug,
LogLevel::Trace,
];
/// One step along [`LOG_LEVEL_ORDER`] from `current`. An unparseable value
/// reads as `Warn`, so it still produces a legal next one.
fn next_log_level(current: &str) -> String {
let index = LogLevel::from_name(current)
.and_then(|level| {
LOG_LEVEL_ORDER
.iter()
.position(|candidate| *candidate == level)
})
.unwrap_or(2);
LOG_LEVEL_ORDER[(index + 1) % LOG_LEVEL_ORDER.len()]
.as_str()
.to_string()
}
/// Flips `"true"`/`"false"`. Anything else reads as `false`.
fn next_bool(current: &str) -> String {
(current != "true").to_string()
}
/// [`StyleLevel`]'s own declared order, wrapping from `Bare` back to `Full`.
pub(crate) const STYLE_LEVEL_ORDER: [StyleLevel; 3] =
[StyleLevel::Full, StyleLevel::Plain, StyleLevel::Bare];
/// One step along [`STYLE_LEVEL_ORDER`] from `current`. An unparseable value
/// reads as `Full`.
fn next_style_level(current: &str) -> String {
let index = StyleLevel::parse(current)
.and_then(|level| {
STYLE_LEVEL_ORDER
.iter()
.position(|candidate| *candidate == level)
})
.unwrap_or(0);
STYLE_LEVEL_ORDER[(index + 1) % STYLE_LEVEL_ORDER.len()].to_string()
}
/// The confirm sentence for `field`'s candidate `value`, verbatim. `value` is
/// what a `next_*` function produced, never re-derived here.
///
/// Only [`SettingField::StyleLevel`] reads `source`: the other three can only
/// warn about the shepherd's env and flags, which lookout cannot see.
fn confirm_text(field: SettingField, value: &str, source: StyleSource) -> String {
match field {
SettingField::LogLevel => format!(
"set log_level to {value}? needs shep daemon reload, and will not apply if the shepherd was booted with SHEP_LOG_LEVEL or --log-level"
),
SettingField::LogJson => format!(
"set log_json to {value}? needs shep daemon reload, and will not apply if the shepherd was booted with SHEP_LOG_JSON or --log-json"
),
SettingField::AllowControl => {
let word = if value == "true" { "on" } else { "off" };
format!("turn whistle control tools {word}? needs shep whistle restarted")
}
SettingField::StyleLevel => style_confirm_text(value, source),
SettingField::Socket | SettingField::MaxCronSleep => unreachable!(
"Settings::next_candidate never arms these two -- they are task 8's Pending::Typing"
),
}
}
/// The `[style] level` half of [`confirm_text`].
///
/// Under `Env` or `Flag` the write lands and the level in force does not move,
/// so the sentence names the layer that keeps winning.
fn style_confirm_text(value: &str, source: StyleSource) -> String {
match source {
StyleSource::Config | StyleSource::Default => {
format!("set style level to {value}? the next command reads it")
}
StyleSource::Env => format!(
"set style level to {value}? it goes in the file, but $SHEP_STYLE is set and keeps winning until it is unset"
),
StyleSource::Flag => format!(
"set style level to {value}? it goes in the file, but --style was passed to this lookout and keeps winning for as long as it runs"
),
}
}
/// The confirm sentence for a free-text edit, verbatim.
///
/// Only [`SettingField::Socket`] and [`SettingField::MaxCronSleep`] reach it;
/// the other four go through [`confirm_text`] and, not being optional, are
/// never [`SettingEdit::Unset`].
fn confirm_text_for_edit(edit: &SettingEdit) -> String {
match edit {
SettingEdit::Set {
field: SettingField::Socket,
value,
} => format!(
"set socket to {value}? needs the shepherd stopped and started; a reload will not move it, and it will not apply if the shepherd was booted with SHEP_SOCKET or --socket"
),
SettingEdit::Set {
field: SettingField::MaxCronSleep,
value,
} => format!(
"set max_cron_sleep to {value}? needs shep daemon reload, and will not apply if the shepherd was booted with SHEP_MAX_CRON_SLEEP or --max-cron-sleep"
),
SettingEdit::Unset {
field: SettingField::Socket,
} => "unset socket? it goes back to the default under $SHEP_HOME, and needs the shepherd stopped and started"
.to_string(),
SettingEdit::Unset {
field: SettingField::MaxCronSleep,
} => "unset max_cron_sleep? it goes back to the daemon's own default, and needs shep daemon reload"
.to_string(),
SettingEdit::Set { .. } | SettingEdit::Unset { .. } => unreachable!(
"on_settings_text_key only ever builds an edit for socket or max_cron_sleep"
),
}
}
/// What `Msg::SettingWritten`'s `Err` arm reopens [`Pending::Typing`] with: the
/// field and the text the operator typed. `None` for the four cycled fields,
/// which have no editor to reopen.
fn typed_text_of(edit: &SettingEdit) -> Option<(SettingField, String)> {
match edit {
SettingEdit::Set {
field: field @ (SettingField::Socket | SettingField::MaxCronSleep),
value,
} => Some((*field, value.clone())),
SettingEdit::Unset {
field: field @ (SettingField::Socket | SettingField::MaxCronSleep),
} => Some((*field, String::new())),
_ => None,
}
}
/// What an action key does.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ActionVerb {
/// `x`. Stops the sheep; it stays registered.
Stop,
/// `R`, on shift because `r` is refresh.
Restart,
/// `L`, on shift for symmetry with `R`.
Reload,
}
impl ActionVerb {
/// The word the prompt and every outcome sentence begin with.
#[must_use]
pub const fn label(self) -> &'static str {
match self {
Self::Stop => "stop",
Self::Restart => "restart",
Self::Reload => "reload",
}
}
}
/// Whether an action has been sent yet.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Stage {
/// Armed, waiting for the operator's Enter. Nothing has gone out.
Armed,
/// Sent, waiting for the shepherd.
Sent,
}
/// The one action this dashboard is in the middle of.
///
/// The target is captured at arm time and never re-read from the selection: a
/// snapshot can land between the keypress and the Enter.
///
/// One field on [`App`] rather than two `Option`s, so "armed" and "in flight"
/// cannot both be true.
#[derive(Debug, Clone)]
struct Action {
verb: ActionVerb,
target: RowKey,
name: String,
/// How many processes [`Self::target`] reaches, captured at arm time: 1 for
/// a sheep, the group's own size for a [`RowKey::Group`].
count: usize,
/// When it was armed. Only an armed action expires.
at: Instant,
stage: Stage,
}
/// The offer a pane makes on its way out when the running sheep has not
/// taken every field yet.
///
/// Nothing is at risk while it is up: a pane edit reaches the override
/// store on the keystroke that makes it, so leaving costs nothing and the
/// menu says so. What it buys is the operator not walking away from parked
/// config without knowing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PaneMenu {
parked: usize,
reload: ReloadKind,
at: Instant,
}
impl PaneMenu {
/// One, over `parked` fields and the reload `reload`.
#[must_use]
pub(super) const fn new(parked: usize, reload: ReloadKind, at: Instant) -> Self {
Self { parked, reload, at }
}
/// When it opened. A menu that outlives `CONFIRM_EXPIRY` is dropped by
/// the tick, so a later keypress cannot answer a question nobody is
/// still looking at.
#[must_use]
pub const fn at(self) -> Instant {
self.at
}
/// How many fields the running sheep has not taken yet.
#[must_use]
pub const fn parked(self) -> usize {
self.parked
}
/// Which reload this sheep would get, so `L` can name its cost.
#[must_use]
pub const fn reload(self) -> ReloadKind {
self.reload
}
}
/// What the status bar needs to know about the action in progress.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ActionState<'a> {
/// Which verb.
pub verb: ActionVerb,
/// The pinned target.
pub target: &'a RowKey,
/// The pinned target's name, as it was when the key was pressed.
pub name: &'a str,
/// How many processes [`Self::target`] reaches.
pub count: usize,
/// False while it is a question, true once it has gone out.
pub sent: bool,
}
/// How long an armed confirm waits for its Enter.
///
/// Ten seconds: a prompt left armed while the operator walks away is the same
/// fat finger by a slower route. Rides `Msg::Tick`, so it needs no timer.
pub const CONFIRM_EXPIRY: Duration = Duration::from_secs(10);
/// The sentence `r` and the action keys both give when the link is gone.
const LINK_GONE: &str = "the shepherd is gone — nothing left to ask";
/// The sentence every closed-gate refusal gives, dashboard and settings alike.
const READ_ONLY_REFUSAL: &str = "read-only: from --read-only or lookout.allow_control";
/// The whole dashboard's state.
#[derive(Debug)]
pub struct App {
flock: BTreeMap<u32, Row>,
/// Which row the detail pane and the bleats feed describe. `None` only for
/// an empty flock.
///
/// A [`RowKey`], not an index: the flock map is replaced wholesale every
/// two seconds, and an index would silently start pointing at a different
/// sheep. The viewport offset is derived from this
/// ([`super::view::flock::scroll_offset`]).
selected: Option<RowKey>,
/// The live substring filter over sheep names, empty when there is none.
///
/// Case-insensitive `contains`, taken literally with no trimming. Not the
/// CLI's selector grammar, which is exact-match and so cannot narrow as you
/// type.
filter: String,
/// Which keymap [`super::input::map_key`] is called with. Normal until `/`
/// opens the box; the reducer, not the keymap, owns this state.
mode: InputMode,
/// The next config-write ticket. Monotonic and never reused, so a reply
/// can only settle the write it belongs to. See [`PanePending::Sent`].
next_write_ticket: u64,
link: Link,
notice: Option<Notice>,
palette: Palette,
control: Control,
/// The `$SHEP_HOME` this lookout watches, for the title line.
home: String,
/// The clock the view reads. Advanced by [`Msg::Tick`], and never once the
/// link is [`Link::Lost`], so a frozen dashboard's uptime column stops.
now: Instant,
/// The last host reading, or `None` before the first heartbeat and on a
/// platform `sysinfo` does not support. [`Self::host_unsupported`] tells
/// the strip which of the two it is looking at.
host: Option<super::source::HostSample>,
/// True once a sample has come back `None`, which the strip says a
/// different sentence for than a heartbeat that has not fired yet.
host_unsupported: bool,
/// The selected sheep's most recent output, as of the last refresh. An
/// empty, unlabelled tail before the first one, which the feed reads the
/// same way as a sheep that has written nothing.
feed: super::tail::Tail,
/// The last lamb reading, or `None` before there has been one. Keyed by the
/// id it was taken for, so a stale reading and a dropped request both read
/// as "not read yet".
lambs: Option<LambReading>,
/// The one action this dashboard is in the middle of, or `None`.
action: Option<Action>,
/// The settings screen's own state. `None` is the dashboard.
settings: Option<Settings>,
/// Which sheep a config pane is open for, or wanted for.
///
/// Set when the read goes out, cleared when the pane closes, checked
/// when a reply lands. Without it, two `e` presses and an `Esc` could
/// reopen a closed pane on the late reply. [`Self::config_pane`] alone
/// cannot tell those two `None` states apart.
config_target: Option<String>,
/// The dog a config pane is open for, or wanted for, and the schema its
/// binary answered with.
///
/// [`Self::config_target`]'s twin. Carries a schema because it is
/// probed once at open and reused on every re-read, so `r` never
/// respawns the dog's binary. Cleared alongside `config_target`.
dog_target: Option<DogProbe>,
/// The open config pane, or `None`. Opened by `e` on a selected sheep,
/// and closed by `e` or `Escape` from inside it.
///
/// A sibling of [`Self::settings`] rather than a field on it: the two
/// screens open from different places and neither is reachable from the
/// other. `on_key` checks this one first, so a pane opened over the
/// dashboard owns the keyboard for as long as it is up.
config_pane: Option<ConfigPane>,
/// The apply offer over the open pane, or `None`.
///
/// Opened by `Escape` on a pane with parked fields and the gate open,
/// and it owns the keyboard while it is up. Cleared with the pane, so
/// no menu can outlive the fields it counted.
pane_menu: Option<PaneMenu>,
/// The resolved style level and which layer chose it. Defaulted here and
/// overridden through [`Self::set_style`], so the STYLE LEVEL row reads the
/// same answer the rest of the CLI does.
style: (StyleLevel, StyleSource),
}
impl App {
/// A dashboard with an empty flock, a live link, and no notice.
#[must_use]
pub fn new(palette: Palette, control: Control, home: String, now: Instant) -> Self {
Self {
flock: BTreeMap::new(),
selected: None,
filter: String::new(),
mode: InputMode::Normal,
next_write_ticket: 0,
link: Link::Live,
notice: None,
palette,
control,
home,
now,
host: None,
host_unsupported: false,
feed: super::tail::Tail::default(),
lambs: None,
action: None,
settings: None,
config_target: None,
dog_target: None,
config_pane: None,
pane_menu: None,
style: (StyleLevel::Full, StyleSource::Default),
}
}
/// Applies one message and reports what the caller must do next.
pub fn update(&mut self, msg: Msg) -> Effect {
match msg {
Msg::Snapshot { rows, at } => {
// The link task has ended, so nothing is left to produce a
// snapshot. Accepting one would un-freeze the dashboard.
if matches!(self.link, Link::Lost { .. }) {
return Effect::None;
}
let previous = self.selected_index();
self.flock = rows
.into_iter()
.map(|info| (info.id, Row { info, anchor: at }))
.collect();
self.reseat(previous);
self.forget_missing_target();
// Unconditional: the selected row's log paths can change even
// when the selection does not, and this is the feed's cadence.
Effect::RefreshFeed
}
Msg::Event(event) => self.on_event(event),
Msg::BusLagged { count } => {
self.notice = Some(Notice {
text: format!(
"lookout fell behind and lost {count} events; re-reading the flock"
),
grave: false,
});
Effect::PollNow
}
Msg::Retrying { attempt } => {
if !matches!(self.link, Link::Lost { .. }) {
self.link = Link::Retrying { attempt };
self.disarm_on_link_change();
}
Effect::None
}
Msg::Relinked => {
if !matches!(self.link, Link::Lost { .. }) {
self.link = Link::Live;
}
Effect::None
}
Msg::Frozen { at_local } => {
self.link = Link::Lost { at_local };
self.disarm_on_link_change();
Effect::None
}
Msg::Tick { now } => {
if !matches!(self.link, Link::Lost { .. }) {
self.now = now;
let expired = self.action.as_ref().is_some_and(|action| {
action.stage == Stage::Armed
&& now.saturating_duration_since(action.at) >= CONFIRM_EXPIRY
});
if expired {
self.action = None;
}
let stale = self.pane_menu.as_ref().is_some_and(|menu| {
now.saturating_duration_since(menu.at()) >= CONFIRM_EXPIRY
});
if stale {
self.pane_menu = None;
}
}
// Against the tick's own `now`, not `self.now`, which stops on
// a dead link: a settings edit describes a local file that is
// no staler for the shepherd being gone.
if let Some(settings) = self.settings.as_mut() {
let expired = matches!(
settings.pending,
Some(Pending::Armed { at, .. } | Pending::DogArmed { at, .. })
if now.saturating_duration_since(at) >= CONFIRM_EXPIRY
);
if expired {
settings.pending = None;
}
}
// The pane's own expiry sits outside the link guard: an
// armed edit that can never be sent is not worth leaving
// on screen either, even with a live link. `now`, not
// `self.now`, which that guard stops advancing.
if let Some(pane) = self.config_pane.as_mut()
&& pane
.armed_at()
.is_some_and(|at| now.saturating_duration_since(at) >= CONFIRM_EXPIRY)
{
pane.cancel();
}
Effect::None
}
Msg::Resize => Effect::None,
Msg::Key(key) => self.on_key(key),
Msg::Host { sample } => {
// A strip ticking over under a banner saying the values are
// frozen contradicts it on one frame.
if matches!(self.link, Link::Lost { .. }) {
return Effect::None;
}
self.host_unsupported = sample.is_none();
self.host = sample;
Effect::None
}
// Always `Effect::None`: answering a feed update with another
// refresh would spin the UI task. The guard catches a read `run_ui`
// armed before the freeze landed.
Msg::Bleats { tail } => {
if matches!(self.link, Link::Lost { .. }) {
return Effect::None;
}
self.feed = tail;
Effect::None
}
Msg::Replied { sent, result } => match sent {
Sent::Lambs { id } => self.on_lambs(id, result),
Sent::Action { verb, target, name } => {
self.on_action_reply(verb, target, &name, result)
}
Sent::Dog { name, enable, .. } => self.on_dog_reply(name, enable, result),
Sent::SheepConfig { name } => self.on_sheep_config(&name, result),
Sent::DogSection { name } => self.on_dog_section(&name, result),
Sent::SetDogSection { name, ticket, .. } => {
self.on_dog_section_set(&name, ticket, result)
}
Sent::ApplyField {
name, ticket, key, ..
} => self.on_field_applied(&name, ticket, &key, result),
Sent::SetEnv {
name,
ticket,
key,
value,
..
} => self.on_env_set(&name, ticket, &key, value.is_some(), result),
},
Msg::Unsent { sent } => match sent {
Sent::Action { verb, target, name } => {
self.action = None;
self.notice = Some(Notice {
// No cause: `Full` is reachable while the shepherd is
// merely slow, so naming one would invent it.
text: format!("{}: it was not sent", target_prefix(verb, &target, &name)),
grave: true,
});
Effect::None
}
// A dropped lamb fetch already reads as "not read yet".
Sent::Lambs { .. } => Effect::None,
// A config read nobody took, reported rather than
// swallowed: silence here looks like a key that is not
// bound. Nothing was armed, so this is the whole report.
Sent::SheepConfig { name } => {
self.notice = Some(Notice {
text: format!("{name}: its config was not asked for"),
grave: true,
});
Effect::None
}
// Both write arms clear the pane's own `Sent` line, the
// same shape `Sent::Action`'s arm above uses: a bar still
// saying "sent, waiting for the shepherd" about a request
// nobody has is the failure `Msg::Unsent` exists for.
Sent::ApplyField {
name, ticket, key, ..
} => {
if let Some(pane) = self.config_pane.as_mut() {
pane.settle(ticket);
}
self.notice = Some(Notice {
text: format!("{name}: {key} was not sent"),
grave: true,
});
Effect::None
}
Sent::SetEnv {
name, ticket, key, ..
} => {
if let Some(pane) = self.config_pane.as_mut() {
pane.settle(ticket);
}
self.notice = Some(Notice {
text: format!("{name}: env {key} was not sent"),
grave: true,
});
Effect::None
}
// The dog twins of the two arms above: a read nobody took
// is reported, and a write nobody took clears the pane's
// "sent, waiting" line.
Sent::DogSection { name } => {
self.notice = Some(Notice {
text: format!("{name}: its config was not asked for"),
grave: true,
});
Effect::None
}
Sent::SetDogSection { name, ticket, .. } => {
if let Some(pane) = self.config_pane.as_mut() {
pane.settle(ticket);
}
self.notice = Some(Notice {
text: format!("{name}: its config was not sent"),
grave: true,
});
Effect::None
}
// The arm above, against the settings screen's pending line.
Sent::Dog { name, enable, .. } => {
if let Some(settings) = self.settings.as_mut() {
settings.pending = None;
}
let verb = if enable { "enable" } else { "disable" };
self.notice = Some(Notice {
text: format!("{verb} {name}: it was not sent"),
grave: true,
});
Effect::None
}
},
// The screen opens on what this read found; a failed read leaves
// the dashboard up. A landed write's re-read and `r` land here too,
// with `self.settings` already `Some`, so `opening` is false and
// the cursor survives.
Msg::Settings { result } => {
let opening = self.settings.is_none();
match result {
Ok(snapshot) => {
// An action armed while the read was in flight: once
// the screen is up, `on_settings_key` no-ops `Confirm`
// and the prompt would be unreachable.
self.action = None;
// A filter box left open would keep eating every
// keystroke the settings keymap owns: `on_key` checks
// the mode first. The query itself is kept.
self.mode = InputMode::Normal;
// Reset to the top only while `opening`.
// `Settings::cursor` clamps on every read, so a
// preserved `Viewport` past a shorter dogs list
// still lands somewhere real.
let view = self.settings.as_ref().map(|settings| settings.view.clone());
let mut settings = Settings::new(snapshot);
if !opening {
if let Some(view) = view {
settings.view = view;
}
let len = settings.rows().len();
settings.view.clamp(len);
}
self.settings = Some(settings);
}
Err(message) => {
self.notice = Some(Notice {
text: message,
grave: true,
});
}
}
Effect::None
}
// `Ok` re-reads rather than folding the write into the row, which
// covers `Unset` too. `Err` reopens the editor for the two
// free-text fields, so a long path need not be retyped.
Msg::SettingWritten { edit, result } => match result {
Ok(()) => {
if let Some(settings) = self.settings.as_mut() {
settings.pending = None;
}
Effect::LoadSettings
}
Err(message) => {
// Split so no borrow of `self.settings` is held across the
// `self.notice` assignment below.
if let Some((field, buffer)) = typed_text_of(&edit) {
if let Some(settings) = self.settings.as_mut() {
settings.pending = Some(Pending::Typing { field, buffer });
}
self.mode = InputMode::Text;
} else if let Some(settings) = self.settings.as_mut() {
settings.pending = None;
}
self.notice = Some(Notice {
text: message,
grave: true,
});
Effect::None
}
},
// A dog's schema probe answered. `Ok` parks the schema and asks
// the shepherd for the section; the pane is built once that
// lands. `Err` gets no pane, and the refusal names the file to
// edit instead. The settings screen stays open until then.
Msg::DogPane {
name,
adopted_path,
result,
} => match result {
Ok(schema) => {
self.dog_target = Some(DogProbe {
name: name.clone(),
adopted_path,
schema,
});
Effect::Send(Sent::DogSection { name })
}
Err(message) => {
self.notice = Some(Notice {
text: message,
grave: true,
});
Effect::None
}
},
// `Ok` raises the daemon half: `Cycle` arms, `Confirm` writes the
// file, this arm asks the shepherd. `Err` never reaches it, since
// there is nothing for the daemon half to agree with.
Msg::DogWritten { edit, result } => match result {
Ok(source) => Effect::Send(Sent::Dog {
name: edit.name,
enable: edit.enable,
source,
}),
Err(message) => {
if let Some(settings) = self.settings.as_mut() {
settings.pending = None;
}
self.notice = Some(Notice {
text: message,
grave: true,
});
Effect::None
}
},
}
}
/// Records one lamb reading. Always [`Effect::None`]: a reducer that
/// answered a reading with another request would spin the UI task.
fn on_lambs(&mut self, id: u32, result: Result<Response, RequestError>) -> Effect {
// Armed before the freeze could land: a reading reaching the frame now
// would be newer than the banner over it.
if matches!(self.link, Link::Lost { .. }) {
return Effect::None;
}
let walk = match result {
Ok(Response::Described(rows)) => rows
.into_iter()
.find(|info| info.id == id)
.map_or(LambWalk::Failed, |info| {
info.lambs.map_or(LambWalk::NotWalked, LambWalk::Walked)
}),
// Neither an `Err` nor an unrecognised reply is an empty walk:
// reporting one would say "none found" about nothing read.
_ => LambWalk::Failed,
};
self.lambs = Some(LambReading {
id,
at: self.now,
walk,
});
Effect::None
}
/// One action's answer: the shepherd's rows upserted, and one sentence.
/// Nothing provisional is invented; all three replies carry the rows.
fn on_action_reply(
&mut self,
verb: ActionVerb,
target: RowKey,
name: &str,
result: Result<Response, RequestError>,
) -> Effect {
self.action = None;
let prefix = target_prefix(verb, &target, name);
// Each verb accepts its own reply and no other: a `Stopped` answering
// a `Restart` carries rows and would upsert happily.
let rows = match result {
Ok(Response::Stopped(rows)) if verb == ActionVerb::Stop => rows,
Ok(Response::Restarted(rows)) if verb == ActionVerb::Restart => rows,
Ok(Response::Reloading(rows)) if verb == ActionVerb::Reload => rows,
Ok(_unrecognised) => {
self.notice = Some(Notice {
text: format!(
"{prefix}: the shepherd answered something this lookout does not understand"
),
grave: true,
});
return Effect::None;
}
// The daemon's own message: `RequestError`'s `Display` would put a
// Rust identifier on an operator's screen.
Err(RequestError::Rpc(err)) => {
self.notice = Some(Notice {
text: format!("{prefix}: {}", err.message),
grave: true,
});
return Effect::None;
}
Err(other) => {
self.notice = Some(Notice {
text: format!("{prefix}: {other}"),
grave: true,
});
return Effect::None;
}
};
let anchor = self.now;
let was_empty = self.flock.is_empty();
for info in rows {
self.flock.insert(info.id, Row { info, anchor });
}
self.notice = Some(Notice {
text: format!("{prefix}: {}", outcome(verb)),
grave: false,
});
if was_empty && self.reseat(None) {
return Effect::RefreshSelected;
}
Effect::None
}
/// One dog toggle's answer: the `Pending::Sent` line clears, one sentence
/// lands in the status bar, and the screen re-reads `shep.toml`.
///
/// [`Effect::LoadSettings`] on every arm, `Err` included: the file half has
/// already landed, so `DogView.enabled` is stale whatever the shepherd
/// said. No row is upserted; the next `ListFlock` repairs RUNNING.
fn on_dog_reply(
&mut self,
name: String,
enable: bool,
result: Result<Response, RequestError>,
) -> Effect {
if let Some(settings) = self.settings.as_mut() {
settings.pending = None;
}
let verb = if enable { "enable" } else { "disable" };
let prefix = format!("{verb} {name}");
// `EnableDog` answers `Response::DogStarted`; `DisableDog` answers
// `Response::Deleted`, the same reply `Delete` gives.
match result {
Ok(Response::DogStarted(_)) if enable => {
self.notice = Some(Notice {
text: format!("{prefix}: the shepherd started it"),
grave: false,
});
}
Ok(Response::Deleted(_)) if !enable => {
self.notice = Some(Notice {
text: format!("{prefix}: the shepherd stopped and deregistered it"),
grave: false,
});
}
// Also a mismatched guard above: an `EnableDog` answered by
// `Response::Deleted`, or the reverse.
Ok(_unrecognised) => {
self.notice = Some(Notice {
text: format!(
"{prefix}: the shepherd answered something this lookout does not understand"
),
grave: true,
});
}
Err(RequestError::Rpc(err)) => {
self.notice = Some(Notice {
text: format!("{prefix}: {}", err.message),
grave: true,
});
}
Err(other) => {
self.notice = Some(Notice {
text: format!("{prefix}: {other}"),
grave: true,
});
}
}
Effect::LoadSettings
}
/// One `Request::SheepConfig` reply. Opens the pane, or refreshes an
/// open one in place.
///
/// The cursor and offset are carried across a refresh rather than reset
/// to the first field, the same rule `Msg::Settings` follows and for the
/// same reason: `r` from inside the pane, and every later re-read, must
/// not throw an operator who was reading `cron_restart` back to `name`.
/// [`ConfigPane::adopt_view`] clamps what it adopts, so a field list
/// that came back shorter cannot leave the cursor past its end.
///
/// A failed read leaves whatever is on screen exactly as it was and
/// raises a grave notice, so a refusal is reported rather than
/// swallowed, and a refresh that fails does not blank a pane that was
/// showing something real.
fn on_sheep_config(&mut self, name: &str, result: Result<Response, RequestError>) -> Effect {
// A reply nobody is waiting for any more is dropped in silence:
// nothing went wrong, and the operator asked for nothing that is
// still outstanding.
if self.config_target.as_deref() != Some(name) {
return Effect::None;
}
match result {
Ok(Response::SheepConfig(view)) => {
let carried = self.config_pane.as_ref().map(|pane| pane.view().clone());
// The env sub-screen is carried too: a set re-reads the
// whole config, and without this it would close on the
// very keystroke that just added a row. Its cursor rides
// by key, not index, since a removal would rename it.
let carried_env = self
.config_pane
.as_ref()
.and_then(ConfigPane::env)
.map(|env| (env.view().clone(), env.cursor_key().map(str::to_owned)));
// The list sub-screen rides across for the same reason,
// and by index rather than by name: an element has no
// name. See `ListPane::adopt_view`.
let carried_list = self
.config_pane
.as_ref()
.and_then(ConfigPane::list)
.map(|list| (list.key().to_owned(), list.view().clone()));
// A question the operator has not answered, or a write
// still out, survives the rebuild. Only `Typing` is
// dropped. See `ConfigPane::adopt_pending_edit`.
let carried_edit = self
.config_pane
.as_ref()
.and_then(|pane| pane.pending_edit().cloned());
// Carried for the same reason as the cursor: a re-read must
// not dismiss a help note the operator has not dismissed.
let carried_help = self.config_pane.as_ref().is_some_and(ConfigPane::help_open);
let mut pane = ConfigPane::sheep(*view);
pane.adopt_pending_edit(carried_edit);
if let Some(carried) = carried {
pane.adopt_view(carried);
}
if let Some((carried, cursor_key)) = carried_env {
pane.adopt_env_view(carried, cursor_key.as_deref());
}
if let Some((key, carried)) = carried_list {
pane.adopt_list_view(&key, carried);
}
pane.set_help_open(carried_help);
self.config_pane = Some(pane);
// The rebuilt pane carries no editor, so the keyboard must
// not still think one is open.
self.release_text_mode_if_unowned();
}
Ok(_unrecognised) => {
self.notice = Some(Notice {
text: format!(
"{name}: the shepherd answered something this lookout does not understand"
),
grave: true,
});
}
// Prefixed, like every other reply handler in this file: the
// shepherd's refusals mostly name their own subject, but
// `EngineStopped` renders as `the supervisor engine has
// stopped`, naming neither the sheep nor the screen it came
// from.
Err(RequestError::Rpc(err)) => {
self.notice = Some(Notice {
text: format!("{name}: {}", err.message),
grave: true,
});
}
Err(other) => {
self.notice = Some(Notice {
text: format!("{name}: {other}"),
grave: true,
});
}
}
Effect::None
}
fn on_event(&mut self, event: BusEvent) -> Effect {
match event {
BusEvent::Process { event, info, .. } => {
if matches!(event, ProcessEventKind::Delete) {
let previous = self.selected_index();
self.flock.remove(&info.id);
self.forget_missing_target();
return if self.reseat(previous) {
Effect::RefreshSelected
} else {
Effect::None
};
}
// An upsert can orphan the selection from `visible_rows()`
// without touching `self.flock`: a rename can move the selected
// row out of the filter. `reseat` is a no-op read while the
// selection is still seated.
let previous = self.selected_index();
let anchor = self.now;
self.flock.insert(info.id, Row { info, anchor });
if self.reseat(previous) {
return Effect::RefreshSelected;
}
Effect::None
}
// The shepherd's own outbound queue overflowed. Worded differently
// from `Msg::BusLagged`: an operator cannot tell which end of the
// connection to investigate if the two read the same.
BusEvent::Dropped { count } => {
self.notice = Some(Notice {
text: format!("the shepherd dropped {count} events; re-reading the flock"),
grave: false,
});
Effect::PollNow
}
// A notice, not an exit: a dashboard that vanished would take the
// last known state with it.
BusEvent::DaemonShutdown => {
self.notice = Some(Notice {
text: "the shepherd is shutting down".to_string(),
grave: true,
});
Effect::None
}
// `BusEvent` is `#[non_exhaustive]`: a newer shepherd's variant
// must not take the dashboard down.
_ => Effect::None,
}
}
/// One `Request::DogConfig` reply: the dog's section, which is the
/// second half of an open.
///
/// Guarded on [`Self::dog_target`] the way [`Self::on_sheep_config`] is
/// guarded on `config_target`, and for the same reason: a reply for a
/// dog the operator has already left must not re-open a pane over the
/// screen they went back to.
///
/// The schema comes off `dog_target` rather than off the wire. Nothing
/// records a dog's schema, so the probe that ran at open is the only
/// copy, and a refresh reuses it rather than respawning the binary.
fn on_dog_section(&mut self, name: &str, result: Result<Response, RequestError>) -> Effect {
let Some(probe) = self.dog_target.clone().filter(|probe| probe.name == name) else {
return Effect::None;
};
match result {
Ok(Response::DogSection { toml }) => {
// Everything a refresh has to carry across, read before the
// rebuild replaces the pane: see `Self::on_sheep_config`,
// which states the argument for each. A dog pane has no env
// sub-screen, so only two of the three apply.
let carried = self.config_pane.as_ref().map(|pane| pane.view().clone());
let carried_edit = self
.config_pane
.as_ref()
.and_then(|pane| pane.pending_edit().cloned());
let carried_help = self.config_pane.as_ref().is_some_and(ConfigPane::help_open);
let mut pane = ConfigPane::dog(
probe.name,
probe.adopted_path,
probe.schema,
toml.as_str().to_owned(),
);
pane.adopt_pending_edit(carried_edit);
if let Some(carried) = carried {
pane.adopt_view(carried);
}
pane.set_help_open(carried_help);
self.config_pane = Some(pane);
// The settings screen is what a dog pane opens over, and it
// closes only now, once there is something to look at.
self.settings = None;
self.release_text_mode_if_unowned();
}
Ok(_unrecognised) => {
self.notice = Some(Notice {
text: format!(
"{name}: the shepherd answered something this lookout does not understand"
),
grave: true,
});
}
Err(RequestError::Rpc(err)) => {
self.notice = Some(Notice {
text: format!("{name}: {}", err.message),
grave: true,
});
}
Err(other) => {
self.notice = Some(Notice {
text: format!("{name}: {other}"),
grave: true,
});
}
}
Effect::None
}
/// One `Request::SetDogConfig` reply.
///
/// The pane settles either way, and a success re-reads the section,
/// the same shape [`Self::on_field_applied`] has: the screen shows
/// what the shepherd now holds rather than what the operator asked
/// for.
///
/// The sentence says the change was published and stops there.
/// Whether the dog acted on it is the dog's own answer, which this
/// reply does not carry and shep cannot predict. The pane's footer
/// states the same fact.
fn on_dog_section_set(
&mut self,
name: &str,
ticket: u64,
result: Result<Response, RequestError>,
) -> Effect {
if let Some(pane) = self.config_pane.as_mut() {
pane.settle(ticket);
}
match result {
Ok(Response::DogConfigSet { .. }) => {
self.notice = Some(Notice {
text: format!("{name}: its config is written, and {name} is told"),
grave: false,
});
Effect::Send(Sent::DogSection {
name: name.to_owned(),
})
}
Ok(_unrecognised) => {
self.notice = Some(Notice {
text: format!(
"{name}: the shepherd answered something this lookout does not understand"
),
grave: true,
});
Effect::None
}
Err(RequestError::Rpc(err)) => {
self.notice = Some(Notice {
text: format!("{name}: {}", err.message),
grave: true,
});
Effect::None
}
Err(other) => {
self.notice = Some(Notice {
text: format!("{name}: {other}"),
grave: true,
});
Effect::None
}
}
}
/// One `Request::SetSheepField` reply.
///
/// The pane settles either way: a question that has been answered is
/// not still in flight. A success re-reads the config so the screen
/// shows what the shepherd now holds, using `Effect::Send` so the
/// re-read gets `Msg::Unsent` handling for free.
///
/// `pending` is the shepherd's answer, not this pane's guess: it knows
/// about fields like `autostart` that `apply_group` cannot derive.
fn on_field_applied(
&mut self,
name: &str,
ticket: u64,
key: &str,
result: Result<Response, RequestError>,
) -> Effect {
if let Some(pane) = self.config_pane.as_mut() {
pane.settle(ticket);
}
match result {
Ok(Response::SheepFieldSet { pending, .. }) => {
self.notice = Some(Notice {
text: if pending {
format!("{name}: {key} is set, and waits for `shep reload {name}`")
} else {
format!("{name}: {key} is set")
},
grave: false,
});
Effect::Send(Sent::SheepConfig {
name: name.to_owned(),
})
}
Ok(_unrecognised) => {
self.notice = Some(Notice {
text: format!(
"{name}: the shepherd answered something this lookout does not understand"
),
grave: true,
});
Effect::None
}
Err(RequestError::Rpc(err)) => {
self.notice = Some(Notice {
text: format!("{name}: {}", err.message),
grave: true,
});
Effect::None
}
Err(other) => {
self.notice = Some(Notice {
text: format!("{name}: {other}"),
grave: true,
});
Effect::None
}
}
}
/// One `Request::SetSheepEnv` reply.
///
/// `was_set` comes off the request rather than the reply: the answer
/// names the key and deliberately never the value, so it cannot say
/// which of the two things happened.
///
/// Env is spawn-time in every case (`AppConfig::env` is
/// `ApplyGroup::NeedsRespawn`), so the sentence says so unconditionally
/// rather than reading a list that this reply does not carry.
fn on_env_set(
&mut self,
name: &str,
ticket: u64,
key: &str,
was_set: bool,
result: Result<Response, RequestError>,
) -> Effect {
if let Some(pane) = self.config_pane.as_mut() {
pane.settle(ticket);
}
match result {
Ok(Response::SheepEnvSet { .. }) => {
let verb = if was_set { "set" } else { "removed" };
self.notice = Some(Notice {
text: format!("{name}: env {key} {verb}, and waits for `shep reload {name}`"),
grave: false,
});
Effect::Send(Sent::SheepConfig {
name: name.to_owned(),
})
}
Ok(_unrecognised) => {
self.notice = Some(Notice {
text: format!(
"{name}: the shepherd answered something this lookout does not understand"
),
grave: true,
});
Effect::None
}
Err(RequestError::Rpc(err)) => {
self.notice = Some(Notice {
text: format!("{name}: {}", err.message),
grave: true,
});
Effect::None
}
Err(other) => {
self.notice = Some(Notice {
text: format!("{name}: {other}"),
grave: true,
});
Effect::None
}
}
}
fn on_key(&mut self, key: KeyPress) -> Effect {
// While the box is open every key is text.
if self.mode == InputMode::Text {
return self.on_text_key(key);
}
// The config pane owns the keyboard while it is open, ahead of the
// settings screen and the armed-confirm check below. The two
// screens cannot coexist, so this ordering is a documentation
// choice, not a correctness one.
if self.config_pane.is_some() {
return self.on_pane_key(key);
}
// The settings screen owns its own keymap while it is open.
if self.settings.is_some() {
return self.on_settings_key(key);
}
// A cancelling keypress is consumed: a stray `j` cancels the confirm
// and does not also move the selection, or the next reflexive Enter
// acts on a target the operator lost track of. Cancelling is silent.
if self
.action
.as_ref()
.is_some_and(|action| action.stage == Stage::Armed)
{
if key == KeyPress::Confirm {
return self.confirm();
}
// The one key the cancel does not consume: an operator whose
// Ctrl-C does nothing reaches for `kill -9`, past every restore
// path `super::term` has. Quitting discards the confirm.
if key == KeyPress::Quit {
return Effect::Quit;
}
self.action = None;
return Effect::None;
}
self.notice = None;
match key {
KeyPress::Quit => Effect::Quit,
// The one key whose meaning depends on state, and the bar reads
// `esc clear` for exactly as long as clearing is what it does.
KeyPress::Escape => {
if self.filter.is_empty() {
Effect::Quit
} else {
self.set_filter(String::new())
}
}
// Once the link task has ended its poll receiver is gone, so an
// `Effect::PollNow` would be silence with no reason for it.
KeyPress::Refresh => {
if matches!(self.link, Link::Lost { .. }) {
self.notice = Some(Notice {
text: LINK_GONE.to_string(),
grave: true,
});
return Effect::None;
}
Effect::PollNow
}
KeyPress::SelectUp => self.select_by(-1),
KeyPress::SelectDown => self.select_by(1),
KeyPress::SelectFirst => self.select_at(0, 1),
KeyPress::SelectLast => self.select_at(self.visible_len().saturating_sub(1), -1),
KeyPress::Action(verb) => self.arm(verb),
// Enter means nothing outside an armed confirm, including while one
// is in flight: the routing rule above fires only on `Stage::Armed`.
KeyPress::Confirm => Effect::None,
KeyPress::FilterStart => {
self.mode = InputMode::Text;
Effect::None
}
// `TextChar`/`TextBackspace`/`TextApply`/`TextAbandon` reach here
// only from text mode, already branched above. `map_key` also
// sends `ListRemove`/`ListMoveUp`/`ListMoveDown` from Normal mode
// (`d`/`K`/`J`), so those land here too, just inert.
KeyPress::TextChar(_)
| KeyPress::TextBackspace
| KeyPress::TextApply
| KeyPress::TextAbandon
| KeyPress::ListRemove
| KeyPress::ListMoveUp
| KeyPress::ListMoveDown => Effect::None,
// The read, not the open: the screen opens only once
// `Msg::Settings` lands.
KeyPress::Settings => Effect::LoadSettings,
// Also the read, not the open: the pane shows the shepherd's
// answer or nothing. `selected_row` is `None` for a group too,
// but a group's name is what `Request::SheepConfig` wants, so
// `e` still works on a multi-instance app's default row.
KeyPress::Edit => self.ask_for_config(),
// `space` acts only on the settings screen.
KeyPress::Cycle => Effect::None,
// `h` names a field's help text, and the dashboard has no
// field selected.
KeyPress::Help => Effect::None,
}
}
/// The settings screen's own keymap, in force while [`Self::settings`] is
/// `Some`. Everything not named here is ignored, an action key included.
fn on_settings_key(&mut self, key: KeyPress) -> Effect {
self.notice = None;
match key {
KeyPress::Quit => return Effect::Quit,
// Both close, but an armed confirm eats the first one, the
// cancel-before-act rule the dashboard follows. `Escape` closing
// rather than quitting is where this screen swaps that cascade.
KeyPress::Settings | KeyPress::Escape => {
let armed = self.settings.as_ref().is_some_and(Settings::is_armed);
if armed {
if let Some(settings) = self.settings.as_mut() {
settings.pending = None;
}
} else {
self.settings = None;
}
}
// An armed candidate eats the first movement key rather than also
// moving: the next reflexive Enter would otherwise apply an edit to
// a row the operator lost track of. `Sent` is untouched.
KeyPress::SelectUp
| KeyPress::SelectDown
| KeyPress::SelectFirst
| KeyPress::SelectLast => {
if let Some(settings) = self.settings.as_mut() {
if settings.is_armed() {
settings.pending = None;
} else {
match key {
KeyPress::SelectUp => settings.move_by(-1),
KeyPress::SelectDown => settings.move_by(1),
KeyPress::SelectFirst => settings.move_to_first(),
KeyPress::SelectLast => settings.move_to_last(),
_ => unreachable!(),
}
}
}
}
KeyPress::Cycle => return self.cycle_setting(),
KeyPress::Confirm => return self.confirm_setting(),
// Re-reads `shep.toml`, so another process's write shows up, and
// the cursor survives. An armed candidate eats this key too.
KeyPress::Refresh => {
if let Some(settings) = self.settings.as_mut()
&& settings.is_armed()
{
settings.pending = None;
return Effect::None;
}
return Effect::LoadSettings;
}
// The probe, not the open, same reasoning as `on_key`'s `e`:
// the pane shows the dog's real schema and section or nothing.
// An armed candidate eats it first, like every other key here.
KeyPress::Edit => {
if let Some(settings) = self.settings.as_mut()
&& settings.is_armed()
{
settings.pending = None;
return Effect::None;
}
return self.probe_dog_schema();
}
// Unreachable from here, named so a new variant cannot fall
// silently into an arm that ignores it.
KeyPress::Action(_)
| KeyPress::FilterStart
| KeyPress::TextChar(_)
| KeyPress::TextBackspace
| KeyPress::TextApply
| KeyPress::TextAbandon
| KeyPress::Help
| KeyPress::ListRemove
| KeyPress::ListMoveUp
| KeyPress::ListMoveDown => {}
}
Effect::None
}
/// `e` on the settings screen: probe the dog under the cursor for its
/// schema.
///
/// Silent on a scalar row, not refused: `space` and `Enter` already
/// edit those, and a refusal that was never going to act trains an
/// operator to ignore the status bar.
///
/// The dogs this can reach are exactly the rows already shown, so no
/// listing request is needed. An adopted-but-disabled dog stays in
/// that list: configure-then-enable is the ordinary order.
fn probe_dog_schema(&mut self) -> Effect {
let Some(settings) = self.settings.as_ref() else {
return Effect::None;
};
let Some(SettingsRow::Dog(index)) = settings.cursor() else {
return Effect::None;
};
let Some(dog) = settings.snapshot().dogs.get(index) else {
return Effect::None;
};
Effect::LoadDogPane {
name: dog.name.clone(),
adopted_path: dog.adopted_path.clone(),
}
}
/// `e`'s own handler: open a dog's pane directly, else ask the shepherd.
///
/// [`Self::selected_row`] rather than [`Self::selected_name`]: a dog
/// runs one process and is never a group row, but a group row must
/// still work with `e`.
fn ask_for_config(&mut self) -> Effect {
if let Some(row) = self.selected_row()
&& let Some(source) = row.info.dog.as_ref()
{
let adopted_path = match source {
DogSource::Adopted { path } => Some(PathBuf::from(path)),
_ => None,
};
return Effect::LoadDogPane {
name: row.info.name.clone(),
adopted_path,
};
}
match self.selected_name() {
Some(name) => {
self.config_target = Some(name.clone());
Effect::Send(Sent::SheepConfig { name })
}
None => Effect::None,
}
}
/// Puts the keyboard back to [`InputMode::Normal`] when no pane editor
/// owns it any more.
///
/// [`InputMode::Text`] is remembered on `App` while the buffer it
/// belongs to lives on the pane, so anything that drops or replaces the
/// pane can leave the two disagreeing, and a lookout in `Text` mode
/// with nothing to type into eats every keystroke until `Esc`. A
/// re-read rebuilds the whole `ConfigPane`, which is exactly that, and
/// a landed write asks for one.
///
/// Called only from paths where the config pane is the screen in
/// question. The filter box owns `Text` with no marker but the mode
/// itself, and it cannot be open while the pane is.
fn release_text_mode_if_unowned(&mut self) {
if self.mode != InputMode::Text {
return;
}
let owned = self.config_pane.as_ref().is_some_and(|pane| {
pane.env().map_or_else(
|| matches!(pane.pending_edit(), Some(PanePending::Typing { .. })),
|env| env.typing().is_some(),
)
});
if !owned {
self.mode = InputMode::Normal;
}
}
/// The config pane's own keymap, in force for as long as
/// [`Self::config_pane`] is `Some`.
///
/// Movement walks fields, `r` re-reads, `space` arms a cycle, `Enter`
/// or `e` edits the row under the cursor or sends an armed edit, `h`
/// toggles the selected field's own help text, and `Escape` closes
/// help if it is open, else the pane. Everything else is named rather
/// than wildcarded, so a stray variant cannot fall silently into an
/// arm that ignores it.
///
/// An armed edit eats the first movement key, `Escape`, `h` and `r`
/// instead of doing their ordinary job, so a reflexive `Enter` never
/// lands on a row the operator has lost track of. `Enter`, `e` and
/// `space` are exempt, since a choice or an armed edit still has to
/// reach its own next value or its own send.
fn on_pane_key(&mut self, key: KeyPress) -> Effect {
self.notice = None;
if self.pane_menu.is_some() {
return self.on_pane_menu_key(key);
}
if self
.config_pane
.as_ref()
.is_some_and(|pane| pane.list().is_some())
{
return self.on_list_key(key);
}
if self
.config_pane
.as_ref()
.is_some_and(|pane| pane.env().is_some())
{
return self.on_env_key(key);
}
if key == KeyPress::Quit {
return Effect::Quit;
}
// Checked before the dispatch below and consumed, except `Enter`,
// `e` and `space`: the same carve-out `on_settings_key` makes, so a
// choice can still reach its third value instead of needing a
// cancel in between.
if self.config_pane.as_ref().is_some_and(ConfigPane::is_armed)
&& !matches!(key, KeyPress::Confirm | KeyPress::Edit | KeyPress::Cycle)
{
if let Some(pane) = self.config_pane.as_mut() {
pane.cancel();
}
return Effect::None;
}
match key {
KeyPress::Quit => return Effect::Quit,
// Backs out one level at a time: help first, if it is open,
// else the pane. `Escape` closes rather than cascading to a
// filter clear or a quit, exactly as it does on the settings
// screen.
KeyPress::Escape => {
let help_open = self.config_pane.as_ref().is_some_and(ConfigPane::help_open);
if help_open {
if let Some(pane) = self.config_pane.as_mut() {
pane.close_help();
}
} else if let Some(menu) = self.apply_offer() {
self.pane_menu = Some(menu);
} else {
self.close_pane();
}
}
KeyPress::SelectUp
| KeyPress::SelectDown
| KeyPress::SelectFirst
| KeyPress::SelectLast => {
if let Some(pane) = self.config_pane.as_mut() {
match key {
KeyPress::SelectUp => pane.move_by(-1),
KeyPress::SelectDown => pane.move_by(1),
KeyPress::SelectFirst => pane.move_to_first(),
KeyPress::SelectLast => pane.move_to_last(),
_ => unreachable!(),
}
}
}
// Re-reads the same sheep, so an override applied from another
// window shows up. The cursor survives it: see
// `Self::on_sheep_config`.
KeyPress::Refresh => return self.reread_pane(),
KeyPress::Cycle => return self.cycle_field(),
// `e` does exactly what `Enter` does here: an operator who
// opened the pane with `e` should not have to learn a second
// key to use it.
KeyPress::Confirm | KeyPress::Edit => return self.confirm_field(),
KeyPress::Help => {
if let Some(pane) = self.config_pane.as_mut() {
pane.toggle_help();
}
}
KeyPress::Action(_)
| KeyPress::Settings
| KeyPress::FilterStart
| KeyPress::TextChar(_)
| KeyPress::TextBackspace
| KeyPress::TextApply
| KeyPress::TextAbandon
| KeyPress::ListRemove
| KeyPress::ListMoveUp
| KeyPress::ListMoveDown => {}
}
Effect::None
}
/// `r` from inside a pane: ask for the same target again, by whichever
/// of the two doors it came in.
///
/// A dog's schema is not re-probed. It came from the dog's binary at
/// open and is parked on [`Self::dog_target`]; re-probing would respawn
/// somebody else's binary on a keystroke whose job is to re-read a file.
fn reread_pane(&mut self) -> Effect {
let Some(pane) = self.config_pane.as_ref() else {
return Effect::None;
};
let name = pane.target().name().to_owned();
match pane.target() {
PaneTarget::Sheep { .. } => Effect::Send(Sent::SheepConfig { name }),
PaneTarget::Dog { .. } => Effect::Send(Sent::DogSection { name }),
}
}
/// Drops the open pane and everything a reply for it would re-open.
///
/// Both targets are cleared, always, and not only the one the pane
/// happens to hold: a read for the other kind can be in flight when this
/// runs (`e` on a dog, then the settings screen closes and `e` opens a
/// sheep), and a stale one left set is exactly the re-open behind the
/// operator's back `config_target` exists to prevent.
fn close_pane(&mut self) {
self.config_pane = None;
self.pane_menu = None;
self.config_target = None;
self.dog_target = None;
self.release_text_mode_if_unowned();
}
/// The offer this pane's `Escape` makes, or [`None`] when it just leaves.
///
/// Silent with nothing parked, so reading a pane never costs a
/// keystroke, and silent behind a closed gate, where the two keys it
/// offers would be refused anyway.
fn apply_offer(&self) -> Option<PaneMenu> {
if self.control == Control::ReadOnly {
return None;
}
let pane = self.config_pane.as_ref()?;
let parked = pane.parked_count();
(parked > 0).then(|| PaneMenu::new(parked, pane.reload_kind(), self.now))
}
/// The menu's own keymap: `L` reloads, `R` restarts, and anything else
/// that backs out leaves the fields parked.
///
/// `Escape` closes the pane rather than only the menu: it is the second
/// press of the two the operator meant as "leave", and a menu that ate
/// it would need a third.
fn on_pane_menu_key(&mut self, key: KeyPress) -> Effect {
match key {
KeyPress::Quit => Effect::Quit,
KeyPress::Action(verb @ (ActionVerb::Reload | ActionVerb::Restart)) => {
self.apply_parked(verb)
}
KeyPress::Escape => {
self.close_pane();
Effect::None
}
KeyPress::Action(ActionVerb::Stop)
| KeyPress::SelectUp
| KeyPress::SelectDown
| KeyPress::SelectFirst
| KeyPress::SelectLast
| KeyPress::Refresh
| KeyPress::Confirm
| KeyPress::Edit
| KeyPress::Cycle
| KeyPress::Help
| KeyPress::Settings
| KeyPress::FilterStart
| KeyPress::TextChar(_)
| KeyPress::TextBackspace
| KeyPress::TextApply
| KeyPress::TextAbandon
| KeyPress::ListRemove
| KeyPress::ListMoveUp
| KeyPress::ListMoveDown => Effect::None,
}
}
/// Sends the menu's chosen verb against the pane's own sheep and closes
/// the pane behind it.
///
/// The same [`Sent::Action`] the dashboard's `arm` and `confirm` build,
/// so [`Self::on_action_reply`] answers it unchanged. The menu is the
/// confirm, so there is no second one.
fn apply_parked(&mut self, verb: ActionVerb) -> Effect {
// Read rather than left to `apply_offer`: the gate is one write to
// `pane_menu` away from not covering this, and a send is not the
// place to find that out.
if self.control == Control::ReadOnly {
self.notice = Some(Notice {
text: READ_ONLY_REFUSAL.to_string(),
grave: true,
});
return Effect::None;
}
if let Some(text) = self.link_refusal() {
self.notice = Some(Notice { text, grave: true });
return Effect::None;
}
if self.action.is_some() {
self.notice = Some(Notice {
text: "one action is already in flight".to_string(),
grave: true,
});
return Effect::None;
}
let Some(name) = self
.config_pane
.as_ref()
.map(|pane| pane.target().name().to_owned())
else {
return Effect::None;
};
let Some((target, count)) = self.flock_target(&name) else {
self.notice = Some(Notice {
text: format!("{name}: it is no longer in the flock"),
grave: true,
});
self.close_pane();
return Effect::None;
};
self.action = Some(Action {
verb,
target: target.clone(),
name: name.clone(),
count,
at: self.now,
stage: Stage::Sent,
});
self.close_pane();
Effect::Send(Sent::Action { verb, target, name })
}
/// The row key `name` reaches, and how many processes that is.
///
/// A name rather than [`Self::selected`]: a pane is opened per name and
/// survives the table underneath it changing. [`None`] when the flock
/// has no such sheep left.
fn flock_target(&self, name: &str) -> Option<(RowKey, usize)> {
let ids: Vec<u32> = self
.flock
.values()
.filter(|row| row.info.name == name)
.map(|row| row.info.id)
.collect();
match ids.as_slice() {
[] => None,
[id] => Some((RowKey::Sheep(*id), 1)),
_ => Some((RowKey::Group(name.to_owned()), ids.len())),
}
}
/// The refusal a locked row gets, in that row's own words.
///
/// Two sentences for two facts, never one for both: shep refusing a
/// config write is not the same as this pane having no widget for a
/// shape a Flockfile writes perfectly well.
///
/// A refused Structural field names the verb that moves it instead.
/// The wildcard keeps a generic sentence for a Structural field this
/// binary has no remedy for, rather than guessing a verb.
fn lock_refusal(key: &str, lock: Lock) -> String {
match lock {
Lock::Refused => match key {
"instances" => {
format!("{key} is not a config write; `shep stock` moves an instance count")
}
"name" => {
format!("{key} is not a config write; a name change is a different sheep")
}
_ => {
format!("{key} is not something a config write changes, from here or anywhere")
}
},
Lock::NoWidget => {
format!("{key} has no editor in this pane; a Flockfile still sets it")
}
}
}
/// `space` on the config pane. Arms the next value for the row under
/// the cursor, or refuses and says why.
///
/// The gate is [`Self::authorize_write`], the same one every settings
/// write passes and for the same reason: a keystroke that changes a
/// running flock's config needs the fat-finger catch a keystroke that
/// stops a sheep has.
fn cycle_field(&mut self) -> Effect {
// The lock is checked ahead of the control gate, the same order
// `confirm_field` takes: it is the more specific fact, and
// `--allow-control` would not change it. A screen that answers
// one question two ways teaches an operator to believe neither.
if let Some((key, lock)) = self
.config_pane
.as_ref()
.and_then(ConfigPane::cursor_lock)
.map(|(key, lock)| (key.to_owned(), lock))
{
self.notice = Some(Notice {
text: Self::lock_refusal(&key, lock),
grave: true,
});
return Effect::None;
}
if self.authorize_write().is_none() {
return Effect::None;
}
let now = self.now;
if let Some(pane) = self.config_pane.as_mut() {
pane.cycle(now);
}
Effect::None
}
/// Sends whatever the pane has armed, whichever of its two screens
/// armed it.
///
/// One function for all three, because the arm is one field
/// ([`ConfigPane::pending_edit`]) and only its destination differs. A
/// sheep's field edit leaves as a `Request::SetSheepField` and its env
/// edit as a `Request::SetSheepEnv`, both recording an operator
/// override for one key. A dog leaves by a third door, before either:
/// `Request::SetDogConfig` carries the whole `dogs.toml` section rather
/// than a key, so the target is read first and the [`PaneEdit`] variant
/// only decides the other two.
fn send_armed(&mut self) -> Effect {
let Some(authority) = self.authorize_write() else {
return Effect::None;
};
// Read before the borrow below, and spent only once the pane really
// had something armed: a ticket burned on a no-op would still be
// unique, but the counter is easier to reason about when every
// value on it names a request that went out.
let ticket = self.next_write_ticket;
let Some(pane) = self.config_pane.as_mut() else {
return Effect::None;
};
let Some(edit) = pane.take_armed(ticket) else {
return Effect::None;
};
self.next_write_ticket += 1;
// A dog leaves by its own door and carries its whole section, not
// one key: `Request::SetDogConfig` replaces the table, and
// `edited_section` is what applies the edit through `toml_edit` so
// the operator's comments survive it. `None` there is a section that
// stopped parsing between the read and the keystroke, which is
// reported rather than sent as an empty table.
if let PaneTarget::Dog { name, .. } = pane.target().clone() {
match pane.edited_section(&edit) {
Some(toml) => {
return Effect::Send(Sent::SetDogSection {
name,
ticket,
toml: toml.into(),
authority,
});
}
// Settled here rather than left in flight: nothing went out,
// so a bar saying "sent, waiting for the shepherd" would be
// waiting on a request nobody has.
None => {
pane.settle(ticket);
self.notice = Some(Notice {
text: format!("{name}: its section in dogs.toml does not parse"),
grave: true,
});
return Effect::None;
}
}
}
let PaneTarget::Sheep { name } = pane.target().clone() else {
return Effect::None;
};
match edit {
PaneEdit::SetEnv { key, value } => Effect::Send(Sent::SetEnv {
name,
ticket,
key,
value,
authority,
}),
// No client-side validation, deliberately: the daemon already
// re-normalizes untrusted input, so a weaker copy here would
// drift the moment `AppConfig` grows a field. An empty buffer
// on a non-nullable field arms `null`, refused as `InvalidConfig`.
PaneEdit::Set { key, value } => Effect::Send(Sent::ApplyField {
name,
ticket,
key,
value,
authority,
}),
}
}
/// The operator's `Enter` on the config pane. Three meanings, picked in
/// this order, mirroring [`Self::confirm_setting`]:
///
/// - Something is armed: sends it and marks it sent.
/// - The cursor is on `env`: opens the env sub-screen.
/// - The cursor is on an array field: opens the list sub-screen.
/// - The cursor is on a typed field: opens the editor and switches
/// [`InputMode::Text`] on.
///
/// All three go through [`Self::authorize_write`], the editor included,
/// for the reason [`Self::confirm_setting`]'s own doc gives. The env
/// sub-screen is gated too: it exists only to write, since the
/// shepherd never sends a value back for it to show.
fn confirm_field(&mut self) -> Effect {
let Some(pane) = self.config_pane.as_ref() else {
return Effect::None;
};
if pane.is_armed() {
return self.send_armed();
}
let Some(kind) = pane.cursor_kind().cloned() else {
return Effect::None;
};
let locked = pane.cursor_lock().map(|(key, lock)| (key.to_owned(), lock));
let opens = matches!(
kind,
FieldKind::Map
| FieldKind::List(_)
| FieldKind::Text
| FieldKind::Integer
| FieldKind::Suggested(_)
);
// A row `Enter` was never going to open raises nothing at all: a
// refusal about a key that was never going to act trains an
// operator to ignore the status bar. A bool and a choice are
// `space`'s job, and `space` works.
if !opens && locked.is_none() {
return Effect::None;
}
// The lock is checked ahead of the control gate: it is the more
// specific of the two answers, and `--allow-control` would not
// help. Each lock says its own thing; see [`Self::lock_refusal`].
if let Some((key, lock)) = locked {
self.notice = Some(Notice {
text: Self::lock_refusal(&key, lock),
grave: true,
});
return Effect::None;
}
if self.authorize_write().is_none() {
return Effect::None;
}
let Some(pane) = self.config_pane.as_mut() else {
return Effect::None;
};
if kind == FieldKind::Map {
pane.open_env();
} else if matches!(kind, FieldKind::List(_)) {
pane.open_list();
} else {
pane.begin_typing();
self.mode = InputMode::Text;
}
Effect::None
}
/// The list sub-screen's own keymap, in force for as long as the pane
/// holds one.
///
/// `Escape` closes the sub-screen, not the pane, the same
/// innermost-first rule the env screen follows. `Enter` or `e` opens
/// the editor on the element under the cursor, or adds one on `+ new`,
/// or sends whatever is armed. `d` removes, and `K`/`J` move the
/// element one place.
///
/// A removal and a move arm rather than act: the write carries the
/// whole array, so a keystroke nobody confirmed would replace the
/// array an operator can see with one they have not read.
fn on_list_key(&mut self, key: KeyPress) -> Effect {
if key == KeyPress::Quit {
return Effect::Quit;
}
if self.config_pane.as_ref().is_some_and(ConfigPane::is_armed)
&& !matches!(key, KeyPress::Confirm | KeyPress::Edit)
{
if let Some(pane) = self.config_pane.as_mut() {
pane.cancel();
}
return Effect::None;
}
let now = self.now;
match key {
KeyPress::Quit => return Effect::Quit,
KeyPress::Escape => {
if let Some(pane) = self.config_pane.as_mut() {
pane.close_list();
}
self.release_text_mode_if_unowned();
}
KeyPress::SelectUp
| KeyPress::SelectDown
| KeyPress::SelectFirst
| KeyPress::SelectLast => {
if let Some(list) = self.config_pane.as_mut().and_then(ConfigPane::list_mut) {
match key {
KeyPress::SelectUp => list.move_by(-1),
KeyPress::SelectDown => list.move_by(1),
KeyPress::SelectFirst => list.move_to_first(),
KeyPress::SelectLast => list.move_to_last(),
_ => unreachable!(),
}
}
}
KeyPress::Refresh => return self.reread_pane(),
KeyPress::Confirm | KeyPress::Edit => {
if self.config_pane.as_ref().is_some_and(ConfigPane::is_armed) {
return self.send_armed();
}
if self.authorize_write().is_none() {
return Effect::None;
}
if let Some(list) = self.config_pane.as_mut().and_then(ConfigPane::list_mut) {
list.begin_typing();
self.mode = InputMode::Text;
}
}
KeyPress::ListRemove => {
if self.authorize_write().is_none() {
return Effect::None;
}
if let Some(pane) = self.config_pane.as_mut() {
pane.arm_list_removal(now);
}
}
KeyPress::ListMoveUp | KeyPress::ListMoveDown => {
if self.authorize_write().is_none() {
return Effect::None;
}
let delta = if key == KeyPress::ListMoveUp { -1 } else { 1 };
if let Some(pane) = self.config_pane.as_mut() {
pane.arm_list_reorder(delta, now);
}
}
KeyPress::Action(_)
| KeyPress::Cycle
| KeyPress::Settings
| KeyPress::FilterStart
| KeyPress::TextChar(_)
| KeyPress::TextBackspace
| KeyPress::TextApply
| KeyPress::TextAbandon
| KeyPress::Help => {}
}
Effect::None
}
/// The env sub-screen's own keymap, in force for as long as the pane
/// holds one.
///
/// `Escape` closes the sub-screen, not the pane, backing out of the
/// innermost thing first; `Escape` again, on the field list, is what
/// closes the pane. `Enter` or `e` opens the editor on the row under
/// the cursor, or sends whatever is armed.
///
/// Both a set and a removal arm before sending: `handle_set_sheep_env`
/// writes the override store on the same call, so the previous value
/// is gone the moment the reply lands, and this write-only screen
/// cannot read it back to restore it.
///
/// An armed edit eats the first stray key, `Enter` and `e` exempt
/// since either is the key the question is waiting for.
fn on_env_key(&mut self, key: KeyPress) -> Effect {
if key == KeyPress::Quit {
return Effect::Quit;
}
if self.config_pane.as_ref().is_some_and(ConfigPane::is_armed)
&& !matches!(key, KeyPress::Confirm | KeyPress::Edit)
{
if let Some(pane) = self.config_pane.as_mut() {
pane.cancel();
}
return Effect::None;
}
match key {
KeyPress::Quit => return Effect::Quit,
KeyPress::Escape => {
if let Some(pane) = self.config_pane.as_mut() {
pane.close_env();
}
self.release_text_mode_if_unowned();
}
KeyPress::SelectUp
| KeyPress::SelectDown
| KeyPress::SelectFirst
| KeyPress::SelectLast => {
if let Some(env) = self.config_pane.as_mut().and_then(ConfigPane::env_mut) {
match key {
KeyPress::SelectUp => env.move_by(-1),
KeyPress::SelectDown => env.move_by(1),
KeyPress::SelectFirst => env.move_to_first(),
KeyPress::SelectLast => env.move_to_last(),
_ => unreachable!(),
}
}
}
KeyPress::Refresh => return self.reread_pane(),
// `e` does exactly what `Enter` does here, the same rule the
// field list follows.
KeyPress::Confirm | KeyPress::Edit => {
if self.config_pane.as_ref().is_some_and(ConfigPane::is_armed) {
return self.send_armed();
}
if self.authorize_write().is_none() {
return Effect::None;
}
if let Some(env) = self.config_pane.as_mut().and_then(ConfigPane::env_mut) {
env.begin_typing();
self.mode = InputMode::Text;
}
}
KeyPress::Action(_)
| KeyPress::Cycle
| KeyPress::Settings
| KeyPress::FilterStart
| KeyPress::TextChar(_)
| KeyPress::TextBackspace
| KeyPress::TextApply
| KeyPress::TextAbandon
| KeyPress::Help
| KeyPress::ListRemove
| KeyPress::ListMoveUp
| KeyPress::ListMoveDown => {}
}
Effect::None
}
/// The config pane's own text keymap, in force for as long as one of
/// its two editors owns [`InputMode::Text`].
///
/// Does not trim the buffer, for the reason
/// [`Self::on_settings_text_key`]'s own doc gives: this repository does
/// not widen an accepted input grammar without a basis in the spec.
///
/// Both editors arm on `TextApply`: the operator's next `Enter`, on
/// the now-closed editor, is what sends it.
fn on_pane_text_key(&mut self, key: KeyPress) -> Effect {
if key == KeyPress::Quit {
return Effect::Quit;
}
if self
.config_pane
.as_ref()
.is_some_and(|pane| pane.list().is_some())
{
return self.on_list_text_key(key);
}
if self
.config_pane
.as_ref()
.is_some_and(|pane| pane.env().is_some())
{
return self.on_env_text_key(key);
}
let now = self.now;
let Some(pane) = self.config_pane.as_mut() else {
return Effect::None;
};
match key {
KeyPress::TextChar(typed) => pane.type_char(typed),
KeyPress::TextBackspace => pane.type_backspace(),
KeyPress::TextApply => {
pane.apply_typing(now);
// `apply_typing` keeps the editor open on an integer buffer
// that does not parse, so the mode follows what the pane
// actually did rather than what the key asked for.
if !matches!(pane.pending_edit(), Some(PanePending::Typing { .. })) {
self.mode = InputMode::Normal;
}
}
KeyPress::TextAbandon => {
pane.abandon_typing();
self.mode = InputMode::Normal;
}
_ => {}
}
Effect::None
}
/// The list sub-screen's own text keymap.
///
/// `TextApply` arms the whole array, so the operator's next `Enter`
/// sends it. An integer element whose buffer does not parse keeps the
/// editor open, which is why the mode follows what the sub-screen did
/// rather than what the key asked for.
fn on_list_text_key(&mut self, key: KeyPress) -> Effect {
let now = self.now;
let Some(pane) = self.config_pane.as_mut() else {
return Effect::None;
};
let Some(list) = pane.list_mut() else {
return Effect::None;
};
match key {
KeyPress::TextChar(typed) => list.type_char(typed),
KeyPress::TextBackspace => list.type_backspace(),
KeyPress::TextApply => {
let applied = list.apply_typing();
if list.typing().is_none() {
self.mode = InputMode::Normal;
}
if let Some(text) = applied {
pane.arm_list_element(text, now);
}
}
KeyPress::TextAbandon => {
list.abandon_typing();
self.mode = InputMode::Normal;
}
_ => {}
}
Effect::None
}
/// The env sub-screen's own text keymap.
///
/// `TextApply` arms, exactly as the field editor's does. See
/// [`Self::on_env_key`] for why an env write arms before it sends.
fn on_env_text_key(&mut self, key: KeyPress) -> Effect {
let now = self.now;
let Some(pane) = self.config_pane.as_mut() else {
return Effect::None;
};
let Some(env) = pane.env_mut() else {
return Effect::None;
};
match key {
KeyPress::TextChar(typed) => env.type_char(typed),
KeyPress::TextBackspace => env.type_backspace(),
KeyPress::TextApply => {
let applied = env.apply_typing();
self.mode = InputMode::Normal;
if let Some((key, value)) = applied {
pane.arm_env(key, value.map(EnvValue::from), now);
}
}
KeyPress::TextAbandon => {
env.abandon_typing();
self.mode = InputMode::Normal;
}
_ => {}
}
Effect::None
}
/// The [`WriteAuthority`] every settings write path has to hold, or
/// [`None`] with the refusal already raised.
///
/// The one place [`Control`] is read on this screen: `space` on a scalar or
/// a dog, and `Enter` opening or applying an edit, all come through here.
fn authorize_write(&mut self) -> Option<WriteAuthority> {
let authority = WriteAuthority::granted(self);
if authority.is_none() {
self.notice = Some(Notice {
text: READ_ONLY_REFUSAL.to_string(),
grave: true,
});
}
authority
}
/// `space` on the settings screen: arms a candidate for the cursor's row,
/// or refuses through [`Self::authorize_write`].
fn cycle_setting(&mut self) -> Effect {
if self.authorize_write().is_none() {
return Effect::None;
}
let Some(cursor) = self.settings.as_ref().and_then(Settings::cursor) else {
return Effect::None;
};
match cursor {
SettingsRow::Scalar(field) => self.cycle_scalar(field),
SettingsRow::Dog(index) => self.cycle_dog(index),
}
}
/// `space` on one of the six scalar rows. Re-arms when a candidate is
/// already armed, so a second `space` walks one step further along the
/// cycle. Does nothing on the two free-text fields.
fn cycle_scalar(&mut self, field: SettingField) -> Effect {
let Some(settings) = self.settings.as_mut() else {
return Effect::None;
};
let Some(value) = settings.next_candidate(field) else {
return Effect::None;
};
let source = settings.source_of(field);
let text = confirm_text(field, &value, source);
settings.pending = Some(Pending::Armed {
edit: SettingEdit::Set { field, value },
text,
at: self.now,
});
Effect::None
}
/// `space` on a [`SettingsRow::Dog`] row: arms the opposite of the file's
/// `enabled` bit, refusing in [`LINK_GONE`]'s words while the link is gone.
///
/// The link check is this row's own, unlike [`Self::cycle_scalar`]: a
/// confirmed toggle ends in a request to the shepherd.
fn cycle_dog(&mut self, index: usize) -> Effect {
if matches!(self.link, Link::Lost { .. }) {
self.notice = Some(Notice {
text: LINK_GONE.to_string(),
grave: true,
});
return Effect::None;
}
let Some(settings) = self.settings.as_mut() else {
return Effect::None;
};
let Some(dog) = settings.snapshot.dogs.get(index) else {
return Effect::None;
};
let name = dog.name.clone();
let enable = !dog.enabled;
let text = if enable {
format!("enable {name}? it starts now, no reload")
} else {
format!("disable {name}? it stops now and is deregistered")
};
settings.pending = Some(Pending::DogArmed {
edit: DogEdit { name, enable },
text,
at: self.now,
});
Effect::None
}
/// The operator's `Enter` on the settings screen. On a free-text row with
/// nothing pending it opens [`Pending::Typing`] and switches
/// [`InputMode::Text`] on; on an armed candidate it sends and moves to
/// [`Pending::Sent`]; anything else is untouched.
///
/// Both acting cases go through [`Self::authorize_write`]. Opening the
/// editor is gated as well as applying it, so the refusal arrives before a
/// whole socket path is typed.
fn confirm_setting(&mut self) -> Effect {
let Some(settings) = self.settings.as_ref() else {
return Effect::None;
};
let opens_editor = settings.pending.is_none()
&& matches!(
settings.cursor(),
Some(SettingsRow::Scalar(
SettingField::Socket | SettingField::MaxCronSleep
))
);
if !opens_editor && !settings.is_armed() {
return Effect::None;
}
let Some(authority) = self.authorize_write() else {
return Effect::None;
};
let Some(settings) = self.settings.as_mut() else {
return Effect::None;
};
if opens_editor {
let Some(SettingsRow::Scalar(field)) = settings.cursor() else {
return Effect::None;
};
let buffer = settings.text_seed(field).to_string();
settings.pending = Some(Pending::Typing { field, buffer });
self.mode = InputMode::Text;
return Effect::None;
}
match settings.pending.take() {
Some(Pending::Armed { edit, text, .. }) => {
settings.pending = Some(Pending::Sent { text });
Effect::WriteSetting(edit, authority)
}
Some(Pending::DogArmed { edit, text, .. }) => {
settings.pending = Some(Pending::Sent { text });
Effect::WriteDog(edit, authority)
}
other => {
settings.pending = other;
Effect::None
}
}
}
/// Why the shepherd cannot be sent to right now, if it cannot.
///
/// Shared by the dashboard's action keys and the pane's apply menu: a
/// dead link refuses the same way whichever door an operator used.
fn link_refusal(&self) -> Option<String> {
match self.link {
// Not `LINK_GONE`, which says the shepherd is gone: this is the
// status bar's own sentence for a redial (`view/status.rs`).
Link::Retrying { attempt } => Some(format!(
"the shepherd stopped answering \u{2014} reconnecting (attempt {attempt})"
)),
// The ladder is exhausted, so the shepherd really is gone.
Link::Lost { .. } => Some(LINK_GONE.to_string()),
_ => None,
}
}
/// Arms a confirm, or refuses and says why.
///
/// Every refusal happens here rather than at confirm time, so an operator
/// never answers a question that was never going to be honoured. The ladder
/// is gate, link, nothing selected, one already in flight.
fn arm(&mut self, verb: ActionVerb) -> Effect {
let refusal = if self.control == Control::ReadOnly {
Some(READ_ONLY_REFUSAL.to_string())
} else if let Some(text) = self.link_refusal() {
Some(text)
} else if self.selected.is_none() {
Some("no sheep is selected".to_string())
} else if self.action.is_some() {
Some("one action is already in flight".to_string())
} else {
None
};
if let Some(text) = refusal {
self.notice = Some(Notice { text, grave: true });
return Effect::None;
}
let key = self.selected.clone().expect("checked just above");
let (target, name, count) = match &key {
RowKey::Sheep(id) => {
let row = self
.flock
.get(id)
.expect("a selected sheep is in the flock");
(RowKey::Sheep(*id), row.info.name.clone(), 1)
}
RowKey::Group(group_name) => {
let count = self
.flock
.values()
.filter(|row| &row.info.name == group_name)
.count();
(RowKey::Group(group_name.clone()), group_name.clone(), count)
}
RowKey::Section(_) => unreachable!("a header is never selectable"),
};
self.action = Some(Action {
verb,
target,
name,
count,
at: self.now,
stage: Stage::Armed,
});
Effect::None
}
/// The operator's Enter. Sends, or refuses because the target left.
fn confirm(&mut self) -> Effect {
let Some(action) = self.action.take() else {
return Effect::None;
};
// The whole flock, not the visible set: a filter typed after arming
// hides a sheep, it does not remove it.
if !self.target_present(&action.target) {
self.notice = Some(Notice {
text: format!(
"{}: it is no longer in the flock",
target_prefix(action.verb, &action.target, &action.name)
),
grave: true,
});
return Effect::None;
}
let sent = Sent::Action {
verb: action.verb,
target: action.target.clone(),
name: action.name.clone(),
};
self.action = Some(Action {
stage: Stage::Sent,
..action
});
Effect::Send(sent)
}
/// Whether `target` still has at least one process in the flock: a
/// single sheep by id, or a group by whether any instance of its name
/// remains.
fn target_present(&self, target: &RowKey) -> bool {
match target {
RowKey::Sheep(id) => self.flock.contains_key(id),
RowKey::Group(name) => self.flock.values().any(|row| &row.info.name == name),
RowKey::Section(_) => unreachable!("a header is never an action target"),
}
}
/// Takes an armed prompt off the screen once its target is gone, rather
/// than leaving a question about nothing. An action already in flight
/// keeps its line.
fn forget_missing_target(&mut self) {
let gone = self.action.as_ref().is_some_and(|action| {
action.stage == Stage::Armed && !self.target_present(&action.target)
});
if gone {
self.action = None;
}
}
/// Takes an armed prompt off the screen when the link stops being live.
///
/// On a frozen dashboard it would never expire either, since `now` stops
/// advancing and the expiry check rides it. An action already sent keeps
/// its line: `run_connected` answers it with an `Err` before its loop ends.
fn disarm_on_link_change(&mut self) {
if self
.action
.as_ref()
.is_some_and(|action| action.stage == Stage::Armed)
{
self.action = None;
}
}
/// The text keymap's router: the filter box while the settings screen is
/// closed, [`Self::on_settings_text_key`]'s editor while it is open. The
/// two never both own [`InputMode::Text`].
fn on_text_key(&mut self, key: KeyPress) -> Effect {
// Three now, and the split is still total: the config pane and the
// settings screen cannot both be open (`e` reaches the dashboard
// only from the dashboard, and `s` only from there too), and
// neither can coexist with the filter box, which `Msg::Settings`'s
// own arm closed the window on.
if self.config_pane.is_some() {
return self.on_pane_text_key(key);
}
if self.settings.is_some() {
return self.on_settings_text_key(key);
}
self.on_filter_text_key(key)
}
/// The filter box's keymap.
///
/// Ctrl-C still quits: in raw mode it is a key event, not a signal. Does
/// not clear [`Self::notice`], unlike normal mode, since a notice can be
/// raised with no keypress involved; the status bar hides it under the box
/// and shows it again when the box closes.
fn on_filter_text_key(&mut self, key: KeyPress) -> Effect {
match key {
KeyPress::Quit => Effect::Quit,
KeyPress::TextChar(typed) => {
let mut query = self.filter.clone();
query.push(typed);
self.set_filter(query)
}
KeyPress::TextBackspace => {
let mut query = self.filter.clone();
query.pop();
self.set_filter(query)
}
KeyPress::TextApply => {
self.mode = InputMode::Normal;
Effect::None
}
KeyPress::TextAbandon => {
self.mode = InputMode::Normal;
self.set_filter(String::new())
}
_ => Effect::None,
}
}
/// The settings editor's own text keymap, in force while a
/// [`Pending::Typing`] owns [`InputMode::Text`]. The buffer is never
/// trimmed.
///
/// `TextApply` arms rather than writes: an empty buffer becomes
/// [`SettingEdit::Unset`], anything else [`SettingEdit::Set`], and the next
/// `Enter` sends it. `TextAbandon` leaves the screen open.
fn on_settings_text_key(&mut self, key: KeyPress) -> Effect {
let now = self.now;
let Some(settings) = self.settings.as_mut() else {
return Effect::None;
};
match key {
KeyPress::Quit => return Effect::Quit,
KeyPress::TextChar(typed) => {
if let Some(Pending::Typing { buffer, .. }) = settings.pending.as_mut() {
buffer.push(typed);
}
}
KeyPress::TextBackspace => {
if let Some(Pending::Typing { buffer, .. }) = settings.pending.as_mut() {
buffer.pop();
}
}
KeyPress::TextApply => {
if let Some(Pending::Typing { field, buffer }) = settings.pending.take() {
let edit = if buffer.is_empty() {
SettingEdit::Unset { field }
} else {
SettingEdit::Set {
field,
value: buffer,
}
};
let text = confirm_text_for_edit(&edit);
settings.pending = Some(Pending::Armed {
edit,
text,
at: now,
});
}
self.mode = InputMode::Normal;
}
KeyPress::TextAbandon => {
settings.pending = None;
self.mode = InputMode::Normal;
}
_ => {}
}
Effect::None
}
/// The rows the table draws, in `(name, instance, id)` order: the whole
/// flock, or whatever the filter leaves of it, split into a "Flock"
/// section and a "Dogs" section.
///
/// A [`RowKey::Group`] header comes immediately before its own
/// [`RowKey::Sheep`] entries, and a [`RowKey::Section`] header only when
/// its side has a row to introduce. The sort key is total on purpose: the
/// table repolls every two seconds, and a partial one would let two
/// instances swap places under the cursor. Every cursor move reads this
/// sequence and nothing else.
#[must_use]
pub fn visible_rows(&self) -> Vec<RowKey> {
let needle = self.filter.to_lowercase();
let mut visible: Vec<(&str, Option<u32>, u32, bool)> = self
.flock
.iter()
.filter(|(_, row)| needle.is_empty() || row.info.name.to_lowercase().contains(&needle))
.map(|(id, row)| {
(
row.info.name.as_str(),
row.info.instance,
*id,
row.info.dog.is_some(),
)
})
.collect();
visible.sort_unstable_by(|a, b| a.0.cmp(b.0).then(a.1.cmp(&b.1)).then(a.2.cmp(&b.2)));
let (dogs, sheep): (Vec<_>, Vec<_>) = visible.into_iter().partition(|entry| entry.3);
let mut out = Vec::new();
if !sheep.is_empty() {
out.push(RowKey::Section("Flock"));
self.push_grouped_rows(&sheep, &mut out);
}
if !dogs.is_empty() {
out.push(RowKey::Section("Dogs"));
self.push_grouped_rows(&dogs, &mut out);
}
out
}
/// Appends `entries`' rows to `out`, splicing a [`RowKey::Group`] header
/// before a grouped app's instances.
fn push_grouped_rows(&self, entries: &[(&str, Option<u32>, u32, bool)], out: &mut Vec<RowKey>) {
let mut at = 0;
while at < entries.len() {
let name = entries[at].0;
let end = entries[at..]
.iter()
.position(|entry| entry.0 != name)
.map_or(entries.len(), |offset| at + offset);
let group = &entries[at..end];
if self.is_grouped(name) {
out.push(RowKey::Group(name.to_string()));
}
out.extend(group.iter().map(|entry| RowKey::Sheep(entry.2)));
at = end;
}
}
/// Whether `row` names a dog. A header and a group row are neither.
#[cfg(test)]
fn is_dog_row(&self, row: &RowKey) -> bool {
match row {
RowKey::Sheep(id) => self.flock.get(id).is_some_and(|r| r.info.dog.is_some()),
RowKey::Group(_) | RowKey::Section(_) => false,
}
}
fn visible_len(&self) -> usize {
self.visible_rows().len()
}
/// Puts the selection back on a real row after the flock changed, and
/// reports whether it moved.
///
/// `previous_index` is where the selection sat before the change, read
/// while the old map was still in place. A surviving key is left alone; a
/// lost one falls to whatever now occupies that position, clamped to the
/// last row rather than to row 0.
fn reseat(&mut self, previous_index: Option<usize>) -> bool {
// `selected_index`, not `flock.contains_key`: a selection the filter
// hides is not seated, however present its id is. Must come before the
// emptiness check below, which would otherwise return early for a query
// that matches no sheep.
if self.selected_index().is_some() {
return false;
}
let before = self.selected.clone();
if self.visible_rows().is_empty() {
self.selected = None;
return before != self.selected;
}
self.select_at(previous_index.unwrap_or(0), 1);
before != self.selected
}
/// Moves the selection by `delta` rows and reports whether it moved.
/// Clamped rather than wrapping.
fn select_by(&mut self, delta: isize) -> Effect {
let Some(index) = self.selected_index() else {
return Effect::None;
};
let next = index.saturating_add_signed(delta);
let direction = if delta < 0 { -1 } else { 1 };
self.select_at(next, direction)
}
/// Selects the row at `index`, clamped to the flock, and reports whether
/// that changed anything.
///
/// `direction` is which way to search past a [`RowKey::Section`] header,
/// and a header at row 0 searches forward whatever it says.
///
/// `Effect::None` when nothing changed: [`Effect::RefreshSelected`] reads
/// two files and asks the shepherd for lambs, and a held `k` at the top
/// must not do that once per keypress.
fn select_at(&mut self, index: usize, direction: isize) -> Effect {
let visible = self.visible_rows();
if visible.is_empty() {
return Effect::None;
}
let mut index = index.min(visible.len() - 1);
if matches!(visible[index], RowKey::Section(_)) {
index = if direction < 0 && index > 0 {
index - 1
} else {
index + 1
};
}
let next = visible[index].clone();
if Some(&next) == self.selected.as_ref() {
return Effect::None;
}
self.selected = Some(next);
// A frozen dashboard re-reading live log files would put content on
// screen newer than the banner over it. The cursor still moves, and the
// detail pane re-renders from the frozen listing.
if matches!(self.link, Link::Lost { .. }) {
return Effect::None;
}
Effect::RefreshSelected
}
/// Every sheep the table's rows are drawn from, in name-then-id order: the
/// whole flock, or whatever the filter leaves of it.
///
/// A flat sheep list, not [`Self::visible_rows`]'s [`RowKey`] sequence: the
/// title bar counts this, and a group header is not a sheep.
#[must_use]
pub fn rows(&self) -> Vec<&Row> {
let needle = self.filter.to_lowercase();
let mut visible: Vec<&Row> = self
.flock
.values()
.filter(|row| needle.is_empty() || row.info.name.to_lowercase().contains(&needle))
.collect();
visible.sort_unstable_by(|a, b| {
(a.info.name.as_str(), a.info.id).cmp(&(b.info.name.as_str(), b.info.id))
});
visible
}
/// Every sheep the shepherd last reported, in id order, whatever the filter
/// hides.
///
/// The host strip sums this rather than [`Self::rows`], so a name filter
/// cannot narrow what `flock cpu`/`flock mem` add up to while the label
/// still says `flock`.
#[must_use]
pub fn all_rows(&self) -> Vec<&Row> {
self.flock.values().collect()
}
/// Replaces the filter and puts the selection back on a visible sheep: a
/// keystroke that narrows the query can hide the selected one.
fn set_filter(&mut self, query: String) -> Effect {
if self.filter == query {
return Effect::None;
}
let previous = self.selected_index();
self.filter = query;
if self.reseat(previous) && !matches!(self.link, Link::Lost { .. }) {
// The cursor moved, so the feed and the lambs are about to describe
// a different sheep.
return Effect::RefreshSelected;
}
Effect::None
}
/// The filter as typed, empty when there is none.
#[must_use]
pub fn filter(&self) -> &str {
&self.filter
}
/// Which keymap is currently in force.
#[must_use]
pub fn mode(&self) -> InputMode {
self.mode
}
/// How many sheep the shepherd last reported, whatever the filter hides.
#[must_use]
pub fn flock_len(&self) -> usize {
self.flock.len()
}
/// The selected row, or `None` for an empty flock.
#[must_use]
pub fn selected(&self) -> Option<RowKey> {
self.selected.clone()
}
/// Which row of [`Self::visible_rows`] the selection sits on, derived every
/// call rather than stored.
#[must_use]
pub fn selected_index(&self) -> Option<usize> {
let key = self.selected.clone()?;
self.visible_rows().iter().position(|row| *row == key)
}
/// The selected sheep's row, which the detail pane and the feed read.
/// `None` for a [`RowKey::Group`] selection as well as for none at all: a
/// group has no single sheep to describe.
#[must_use]
pub fn selected_row(&self) -> Option<&Row> {
match &self.selected {
Some(RowKey::Sheep(id)) => self.flock.get(id),
_ => None,
}
}
/// The selected row's app name: a sheep's own, or a group row's.
///
/// Unlike [`Self::selected_row`] this answers for a group too: a config
/// pane is about the stored spec every instance of an app shares, which
/// a group row names exactly, while the detail pane and feed describe
/// one process and have nothing to show for a group.
#[must_use]
pub fn selected_name(&self) -> Option<String> {
match &self.selected {
Some(RowKey::Group(name)) => Some(name.clone()),
Some(RowKey::Sheep(id)) => self.flock.get(id).map(|row| row.info.name.clone()),
Some(RowKey::Section(_)) => unreachable!("a header is never selectable"),
None => None,
}
}
/// One sheep by id, whatever the filter hides: the lookup a
/// [`RowKey::Sheep`] row's rendering needs.
#[must_use]
pub fn row(&self, id: u32) -> Option<&Row> {
self.flock.get(&id)
}
/// Every instance of `name`, sorted by slot: the members a
/// [`RowKey::Group`] row summarises.
#[must_use]
pub fn group_members(&self, name: &str) -> Vec<&Row> {
let mut members: Vec<&Row> = self
.flock
.values()
.filter(|row| row.info.name == name)
.collect();
members.sort_by_key(|row| row.info.instance.unwrap_or(u32::MAX));
members
}
/// Whether `name`'s instances draw under a [`RowKey::Group`] header: more
/// than one instance of the name, every one of them reporting a slot.
///
/// Read over the whole flock rather than the filtered sequence, which a
/// name query keeps whole either way.
#[must_use]
pub fn is_grouped(&self, name: &str) -> bool {
let members = self.group_members(name);
members.len() > 1 && members.iter().all(|row| row.info.instance.is_some())
}
/// `name`'s rolled-up numbers. [`GroupTotals`] gives the rule each field
/// follows.
#[must_use]
pub fn group_totals(&self, name: &str) -> GroupTotals {
let members = self.group_members(name);
GroupTotals {
count: members.len(),
restarts: members.iter().map(|row| row.info.restarts).sum(),
cpu: members
.iter()
.filter_map(|row| row.info.cpu_percent)
.fold(None, |acc, cpu| Some(acc.unwrap_or(0.0) + cpu)),
memory: members
.iter()
.filter_map(|row| row.info.memory_bytes)
.fold(None, |acc, mem| Some(acc.unwrap_or(0) + mem)),
uptime_ms: members
.iter()
.filter_map(|row| self.uptime_ms(row.info.id))
.min(),
}
}
/// `name`'s STATUS cell: the shared status word when every instance agrees,
/// else a count per state, as `output::rows::group_status` does for
/// `shep flock`.
///
/// Reads `ProcStatus` directly, never [`Row::reported`]: a dog is never
/// stocked to several instances, so a group has no handshake to report.
#[must_use]
pub fn group_status_text(&self, name: &str) -> String {
let members = self.group_members(name);
let Some(first) = members.first().map(|row| row.info.status) else {
return String::new();
};
if members.iter().all(|row| row.info.status == first) {
return first.to_string();
}
let mut counts: BTreeMap<String, usize> = BTreeMap::new();
for row in &members {
*counts.entry(row.info.status.to_string()).or_default() += 1;
}
counts
.into_iter()
.map(|(status, n)| format!("{n} {status}"))
.collect::<Vec<_>>()
.join(", ")
}
/// `name`'s status when every instance agrees on one, which the STATUS
/// colouring and the detail pane's status word key off. A mixed group's
/// plain count text wears no colour.
#[must_use]
pub fn group_uniform_status(&self, name: &str) -> Option<ProcStatus> {
let members = self.group_members(name);
let first = members.first()?.info.status;
members
.iter()
.all(|row| row.info.status == first)
.then_some(first)
}
/// The link state, as the status bar reports it.
#[must_use]
pub fn link(&self) -> &Link {
&self.link
}
/// The current notice, if the last message left one.
#[must_use]
pub fn notice(&self) -> Option<&Notice> {
self.notice.as_ref()
}
/// The resolved palette.
#[must_use]
pub fn palette(&self) -> Palette {
self.palette
}
/// Whether actions are permitted.
#[must_use]
pub fn control(&self) -> Control {
self.control
}
/// The `$SHEP_HOME` this lookout watches.
#[must_use]
pub fn home(&self) -> &str {
&self.home
}
/// The last host reading, or `None` if there has not been one.
#[must_use]
pub fn host(&self) -> Option<super::source::HostSample> {
self.host
}
/// Whether [`Self::host`] is `None` because the platform cannot be read,
/// rather than because no heartbeat has fired yet. The strip says a
/// different sentence for each: an operator shown the wrong one waits for
/// numbers that are never coming.
#[must_use]
pub fn host_unsupported(&self) -> bool {
self.host_unsupported
}
/// The selected sheep's most recent output, as of the last refresh.
#[must_use]
pub fn feed(&self) -> &super::tail::Tail {
&self.feed
}
/// One sheep's uptime as of this dashboard's own clock, in milliseconds.
///
/// A running sheep's uptime advances between polls, from the anchor its row
/// carries. One that is not running does not: its `uptime_ms` is a fact
/// about how long it ran. Nothing advances once the link is [`Link::Lost`].
#[must_use]
pub fn uptime_ms(&self, id: u32) -> Option<u64> {
let row = self.flock.get(&id)?;
if !matches!(row.info.status, ProcStatus::Online | ProcStatus::Starting) {
return Some(row.info.uptime_ms);
}
let elapsed = self.now.saturating_duration_since(row.anchor);
Some(row.info.uptime_ms.saturating_add(millis(elapsed)))
}
/// The lamb reading for sheep `id`, with its age in milliseconds.
///
/// `None` when there is no reading, or when the one there is was taken for
/// a different sheep. The age stops when the dashboard freezes.
#[must_use]
pub fn lambs_for(&self, id: u32) -> Option<(&LambWalk, u64)> {
let reading = self.lambs.as_ref().filter(|reading| reading.id == id)?;
Some((
&reading.walk,
millis(self.now.saturating_duration_since(reading.at)),
))
}
/// The action in progress, for the status bar.
#[must_use]
pub fn action(&self) -> Option<ActionState<'_>> {
let action = self.action.as_ref()?;
Some(ActionState {
verb: action.verb,
target: &action.target,
name: &action.name,
count: action.count,
sent: action.stage == Stage::Sent,
})
}
/// The settings screen's own state, or `None` while the dashboard is
/// showing.
#[must_use]
pub fn settings(&self) -> Option<&Settings> {
self.settings.as_ref()
}
/// Tells every scrollable screen how tall the body is. Called by the
/// event loop before each draw, so a screen's cursor never lands on a
/// row that was not rendered.
pub fn note_body_rows(&mut self, rows: u16) {
if let Some(settings) = self.settings.as_mut() {
settings.set_rows(usize::from(rows));
}
if let Some(pane) = self.config_pane.as_mut() {
// One less than the settings screen gets: the pane spends its
// first line on a title naming the sheep, which
// `view::pane::pane_lines` draws before any row.
let body = usize::from(rows.saturating_sub(1));
pane.set_rows(body);
if let Some(env) = pane.env_mut() {
// The sub-screen draws its own title over the pane's, so
// it pays the same one line and no more.
env.set_rows(body);
}
if let Some(list) = pane.list_mut() {
list.set_rows(body);
}
}
}
/// The open config pane, or `None` while nothing is being edited.
#[must_use]
pub fn config_pane(&self) -> Option<&ConfigPane> {
self.config_pane.as_ref()
}
/// The apply offer over the open pane, or `None`.
#[must_use]
pub fn pane_menu(&self) -> Option<PaneMenu> {
self.pane_menu
}
/// The resolved style level and which layer chose it, which the STYLE LEVEL
/// row reads rather than re-resolving.
#[must_use]
pub fn style(&self) -> (StyleLevel, StyleSource) {
self.style
}
/// Sets the resolved style level and its source. `App` reads no files, so
/// it cannot resolve this itself.
pub(crate) fn set_style(&mut self, style: (StyleLevel, StyleSource)) {
self.style = style;
}
/// Overrides the control gate a fixture built with. Every shipped fixture
/// hard-codes [`Control::ReadOnly`].
#[cfg(test)]
pub(crate) fn set_control_for_tests(&mut self, control: Control) {
self.control = control;
}
/// Sets the filter directly, bypassing [`Self::set_filter`]'s reseat.
#[cfg(test)]
pub(crate) fn set_filter_for_tests(&mut self, query: &str) {
self.filter = query.to_string();
}
/// Points the cursor at `key` without simulating keypresses.
#[cfg(test)]
fn select(&mut self, key: RowKey) {
self.selected = Some(key);
}
}
/// The prefix every action's notice shares: the verb, and the target. A single
/// sheep takes the `(id N)` form; a group names the app, having no one id.
fn target_prefix(verb: ActionVerb, target: &RowKey, name: &str) -> String {
match target {
RowKey::Sheep(id) => format!("{} {name} (id {id})", verb.label()),
RowKey::Group(_) => format!("{} all instances of {name}", verb.label()),
RowKey::Section(_) => unreachable!("a header is never an action target"),
}
}
/// Saturating `Duration` to milliseconds. Saturates for clippy's
/// `cast_possible_truncation`, not for a lookout left open 580 million years.
fn millis(d: Duration) -> u64 {
u64::try_from(d.as_millis()).unwrap_or(u64::MAX)
}
/// What the bar says once the shepherd has answered. `Response::Reloading` is
/// an acceptance, not a result: the swaps arrive later on the bus.
const fn outcome(verb: ActionVerb) -> &'static str {
match verb {
ActionVerb::Stop => "the shepherd stopped it",
ActionVerb::Restart => "the shepherd restarted it",
ActionVerb::Reload => "accepted, the swaps report themselves as they happen",
}
}
#[cfg(test)]
mod tests {
use std::path::Path;
use super::*;
use crate::lookout::pane::ListRow;
use shep_core::protocol::{ProcessEventKind, RpcError, RpcErrorCode};
use super::super::view::fixtures;
use crate::commands::settings::ScalarView;
fn sheep(id: u32, name: &str, status: ProcStatus) -> ProcessInfo {
ProcessInfo::builder(id, name, status)
.pid(Some(1000 + id))
.uptime_ms(60_000)
.build()
}
fn started() -> (App, Instant) {
let t0 = Instant::now();
let mut app = App::new(
Palette::detect(None, None, None),
Control::ReadOnly,
"/home/ada/.shep".to_string(),
t0,
);
app.update(Msg::Snapshot {
rows: vec![
sheep(1, "web", ProcStatus::Online),
sheep(2, "api", ProcStatus::Errored),
sheep(3, "worker", ProcStatus::Online),
],
at: t0,
});
(app, t0)
}
/// `started()`'s three sheep with the gate open and the cursor mid-list, on
/// `web` at id 1.
///
/// The table reads by name, so the ids disagree with the display order:
/// `api` 2, `web` 1, `worker` 3. Mid-list, because a cursor clamped at
/// either end would pass the tests that assert a stray `j` did not move it.
fn allowed() -> App {
let t0 = Instant::now();
let mut app = App::new(
Palette::detect(None, None, None),
Control::Allowed,
"/home/ada/.shep".to_string(),
t0,
);
app.update(Msg::Snapshot {
rows: vec![
sheep(1, "web", ProcStatus::Online),
sheep(2, "api", ProcStatus::Online),
sheep(3, "worker", ProcStatus::Online),
],
at: t0,
});
app.update(Msg::Tick { now: t0 });
app.update(Msg::Key(KeyPress::SelectDown));
app
}
/// `allowed()`'s shape with three instances of one app: `web` at slots 0, 1
/// and 2, ids 1 through 3. Nothing is selected; each test selects itself.
fn allowed_with_instances() -> App {
let t0 = Instant::now();
let mut app = App::new(
Palette::detect(None, None, None),
Control::Allowed,
"/home/ada/.shep".to_string(),
t0,
);
app.update(Msg::Snapshot {
rows: instanced_rows(),
at: t0,
});
app
}
/// `web`'s three instances, at slots 0, 1 and 2 and ids 1 through 3.
fn instanced_rows() -> Vec<ProcessInfo> {
(0..3)
.map(|slot| {
ProcessInfo::builder(slot + 1, "web", ProcStatus::Online)
.instance(Some(slot))
.build()
})
.collect()
}
/// The status bar's own rendered text.
fn status_line_text(app: &App) -> String {
super::super::view::fixtures::rendered(&super::super::view::status::status_line(app, 200))
}
#[test]
fn a_multi_instance_app_shows_a_group_row_above_its_slots() {
let app = allowed_with_instances();
assert_eq!(
app.visible_rows().len(),
5,
"the flock header, three slots and the group row above them"
);
assert_eq!(app.visible_rows()[0], RowKey::Section("Flock"));
assert!(matches!(app.visible_rows()[1], RowKey::Group(ref n) if n == "web"));
}
#[test]
fn a_flock_with_a_dog_draws_a_section_header_before_each_kind() {
let app = fixtures::app_with_a_dog();
let rows = app.visible_rows();
assert_eq!(rows.first(), Some(&RowKey::Section("Flock")), "{rows:?}");
let dogs = rows
.iter()
.position(|row| *row == RowKey::Section("Dogs"))
.unwrap_or_else(|| panic!("no dogs header: {rows:?}"));
// Every sheep sorts above the header and every dog below it.
assert!(
rows[..dogs].iter().all(|row| !app.is_dog_row(row)),
"{rows:?}"
);
assert!(
rows[dogs + 1..].iter().all(|row| app.is_dog_row(row)),
"{rows:?}"
);
}
#[test]
fn a_flock_with_no_dog_draws_no_dogs_header() {
let app = started().0;
let rows = app.visible_rows();
assert!(!rows.contains(&RowKey::Section("Dogs")), "{rows:?}");
}
#[test]
fn a_dog_only_flock_draws_no_flock_header_and_selects_past_the_dogs_one() {
let mut app = fixtures::app_with_a_dog();
// A filter that leaves only the dog, so the sheep side is empty.
app.set_filter("otel".to_string());
let rows = app.visible_rows();
assert!(!rows.contains(&RowKey::Section("Flock")), "{rows:?}");
assert_eq!(rows.first(), Some(&RowKey::Section("Dogs")), "{rows:?}");
// The only header is row 0, which has nowhere to search backward.
let _ = app.update(Msg::Key(KeyPress::SelectFirst));
assert!(
!matches!(app.selected(), Some(RowKey::Section(_))),
"{:?}",
app.selected()
);
}
#[test]
fn moving_down_steps_over_a_section_header() {
let mut app = fixtures::app_with_a_dog();
app.select_at(1, 1);
let before = app.selected();
// Walk the whole list; a header must never become the selection.
for _ in 0..app.visible_rows().len() + 2 {
let _ = app.update(Msg::Key(KeyPress::SelectDown));
assert!(
!matches!(app.selected(), Some(RowKey::Section(_))),
"landed on a header from {before:?}"
);
}
}
#[test]
fn moving_up_steps_over_a_section_header() {
let mut app = fixtures::app_with_a_dog();
app.select_at(app.visible_rows().len() - 1, -1);
let before = app.selected();
// Walk the whole list; a header must never become the selection.
for _ in 0..app.visible_rows().len() + 2 {
let _ = app.update(Msg::Key(KeyPress::SelectUp));
assert!(
!matches!(app.selected(), Some(RowKey::Section(_))),
"landed on a header from {before:?}"
);
}
// The walk has to actually cross the `Dogs` header going up, not
// just avoid landing on it: it should reach the first row, `api`
// sorting ahead of `web`.
assert_eq!(app.selected(), Some(RowKey::Sheep(2)), "{before:?}");
}
#[test]
fn an_action_on_a_group_row_targets_the_whole_app_by_name() {
let mut app = allowed_with_instances();
app.select(RowKey::Group("web".to_string()));
app.update(Msg::Key(KeyPress::Action(ActionVerb::Stop)));
let Effect::Send(sent) = app.update(Msg::Key(KeyPress::Confirm)) else {
panic!("Enter sends");
};
assert_eq!(
sent.request(),
Request::Stop {
selector: SelectorSpec::Name("web".to_string())
}
);
}
#[test]
fn a_group_confirm_states_how_many_processes_it_reaches() {
let mut app = allowed_with_instances();
app.select(RowKey::Group("web".to_string()));
app.update(Msg::Key(KeyPress::Action(ActionVerb::Stop)));
let prompt = status_line_text(&app);
assert!(prompt.contains('3'), "names the blast radius: {prompt}");
}
#[test]
fn selection_survives_a_poll_on_both_row_kinds() {
let mut app = allowed_with_instances();
app.select(RowKey::Group("web".to_string()));
app.update(Msg::Snapshot {
rows: instanced_rows(),
at: Instant::now(),
});
assert_eq!(app.selected(), Some(RowKey::Group("web".to_string())));
}
#[test]
fn arming_a_group_action_refuses_when_read_only() {
let mut app = allowed_with_instances();
app.set_control_for_tests(Control::ReadOnly);
app.select(RowKey::Group("web".to_string()));
app.update(Msg::Key(KeyPress::Action(ActionVerb::Stop)));
assert!(app.action().is_none());
assert_eq!(
app.notice().map(ToString::to_string).as_deref(),
Some("read-only: from --read-only or lookout.allow_control")
);
}
#[test]
fn arming_a_group_action_refuses_while_the_link_is_not_live() {
for link in [
Msg::Retrying { attempt: 2 },
Msg::Frozen {
at_local: "2026-08-16 09:00:00".to_string(),
},
] {
let mut app = allowed_with_instances();
app.select(RowKey::Group("web".to_string()));
app.update(link);
app.update(Msg::Key(KeyPress::Action(ActionVerb::Stop)));
assert!(app.action().is_none());
assert!(app.notice().is_some_and(Notice::is_grave));
}
}
#[test]
fn arming_a_group_action_refuses_while_one_is_already_in_flight() {
let mut app = allowed_with_instances();
app.select(RowKey::Group("web".to_string()));
app.update(Msg::Key(KeyPress::Action(ActionVerb::Stop)));
app.update(Msg::Key(KeyPress::Confirm));
assert!(app.action().is_some_and(|action| action.sent));
app.update(Msg::Key(KeyPress::Action(ActionVerb::Restart)));
assert_eq!(
app.notice().map(ToString::to_string).as_deref(),
Some("one action is already in flight")
);
let action = app.action().expect("the first one is untouched");
assert_eq!(action.verb, ActionVerb::Stop);
assert!(action.sent);
}
#[test]
fn an_action_key_arms_a_confirm_and_sends_nothing() {
let mut app = allowed();
assert_eq!(
app.update(Msg::Key(KeyPress::Action(ActionVerb::Stop))),
Effect::None
);
let armed = app.action().expect("armed");
assert_eq!(armed.verb, ActionVerb::Stop);
assert_eq!(armed.target, &RowKey::Sheep(1));
assert_eq!(armed.name, "web");
assert!(!armed.sent, "nothing has gone out");
}
#[test]
fn only_enter_confirms_and_every_other_key_cancels() {
for key in [
KeyPress::SelectDown,
KeyPress::SelectUp,
KeyPress::SelectFirst,
KeyPress::Refresh,
KeyPress::Escape,
KeyPress::FilterStart,
KeyPress::Action(ActionVerb::Stop),
KeyPress::Action(ActionVerb::Restart),
] {
let mut app = allowed();
app.update(Msg::Key(KeyPress::Action(ActionVerb::Stop)));
assert!(app.action().is_some(), "armed before {key:?}");
assert_eq!(
app.update(Msg::Key(key)),
Effect::None,
"{key:?} sent something"
);
assert!(app.action().is_none(), "{key:?} did not cancel");
}
let mut app = allowed();
app.update(Msg::Key(KeyPress::Action(ActionVerb::Stop)));
assert!(
matches!(app.update(Msg::Key(KeyPress::Confirm)), Effect::Send(_)),
"and Enter is the one key that sends"
);
}
/// `allowed()` parks the selection mid-list, so a `j` genuinely could move
/// it.
#[test]
fn a_cancelling_key_is_consumed_and_does_not_also_move_the_selection() {
let mut app = allowed();
app.update(Msg::Key(KeyPress::Action(ActionVerb::Restart)));
let before = app.selected();
let effect = app.update(Msg::Key(KeyPress::SelectDown));
assert!(app.action().is_none(), "the stray j cancelled the confirm");
assert_eq!(app.selected(), before, "and did not also move the cursor");
assert_eq!(effect, Effect::None, "nor ask for a feed read or a walk");
}
/// The snapshot renames the armed sheep out of the filter while another
/// enters it, so id 2 stays in `self.flock` while leaving `visible_rows()`
/// and the cursor moves to id 9. Deleting a neighbour would not separate
/// the two: `reseat` leaves a surviving id alone.
#[test]
fn the_confirm_is_pinned_to_the_id_it_was_armed_on() {
let mut app = allowed();
app.set_filter("api".to_string());
app.update(Msg::Key(KeyPress::Action(ActionVerb::Stop)));
app.update(Msg::Snapshot {
rows: vec![
sheep(2, "gateway", ProcStatus::Online),
sheep(9, "api-new", ProcStatus::Online),
],
at: Instant::now(),
});
assert_eq!(
app.selected(),
Some(RowKey::Sheep(9)),
"sanity: the cursor followed the filter off the armed id"
);
let Effect::Send(sent) = app.update(Msg::Key(KeyPress::Confirm)) else {
panic!("Enter sends");
};
assert_eq!(
sent,
Sent::Action {
verb: ActionVerb::Stop,
target: RowKey::Sheep(2),
name: "api".to_string()
}
);
}
#[test]
fn a_confirm_whose_sheep_left_the_flock_refuses_instead_of_sending() {
let mut app = allowed();
app.update(Msg::Key(KeyPress::Action(ActionVerb::Stop)));
app.update(Msg::Event(BusEvent::Process {
event: ProcessEventKind::Delete,
info: sheep(1, "web", ProcStatus::Stopped),
manually: true,
at_ms: 0,
}));
assert!(app.action().is_none());
assert_eq!(app.update(Msg::Key(KeyPress::Confirm)), Effect::None);
}
/// Driven by `Msg::Tick`, so there is no sleep here.
#[test]
fn a_confirm_expires_after_ten_seconds_of_ticks() {
let mut app = allowed();
let t0 = Instant::now();
app.update(Msg::Tick { now: t0 });
app.update(Msg::Key(KeyPress::Action(ActionVerb::Reload)));
app.update(Msg::Tick {
now: t0 + Duration::from_secs(9),
});
assert!(app.action().is_some(), "nine seconds is still armed");
app.update(Msg::Tick {
now: t0 + Duration::from_secs(10),
});
assert!(app.action().is_none(), "ten is not");
}
#[test]
fn every_action_key_refuses_while_the_link_is_not_live() {
for link in [
Msg::Retrying { attempt: 2 },
Msg::Frozen {
at_local: "2026-08-16 09:00:00".to_string(),
},
] {
let mut app = allowed();
app.update(link);
app.update(Msg::Key(KeyPress::Action(ActionVerb::Stop)));
assert!(app.action().is_none());
assert!(app.notice().is_some_and(Notice::is_grave));
}
}
#[test]
fn a_second_action_refuses_while_one_is_in_flight() {
let mut app = allowed();
app.update(Msg::Key(KeyPress::Action(ActionVerb::Stop)));
app.update(Msg::Key(KeyPress::Confirm));
assert!(app.action().is_some_and(|action| action.sent));
app.update(Msg::Key(KeyPress::Action(ActionVerb::Restart)));
assert_eq!(
app.notice().map(ToString::to_string).as_deref(),
Some("one action is already in flight")
);
let action = app.action().expect("the first one is untouched");
assert_eq!(action.verb, ActionVerb::Stop);
assert!(action.sent);
}
#[test]
fn an_in_flight_line_survives_a_keypress() {
let mut app = allowed();
app.update(Msg::Key(KeyPress::Action(ActionVerb::Stop)));
app.update(Msg::Key(KeyPress::Confirm));
app.update(Msg::Key(KeyPress::SelectDown));
assert!(
app.action().is_some_and(|action| action.sent),
"the keypress moved the cursor and left the in-flight state alone"
);
}
#[test]
fn quit_still_quits_while_a_confirm_is_armed() {
let mut app = allowed();
app.update(Msg::Key(KeyPress::Action(ActionVerb::Stop)));
assert_eq!(app.update(Msg::Key(KeyPress::Quit)), Effect::Quit);
}
#[test]
fn enter_outside_an_armed_confirm_does_nothing() {
let mut app = allowed();
assert_eq!(app.update(Msg::Key(KeyPress::Confirm)), Effect::None);
assert!(app.action().is_none());
app.update(Msg::Key(KeyPress::Action(ActionVerb::Stop)));
app.update(Msg::Key(KeyPress::Confirm));
assert!(app.action().is_some_and(|action| action.sent), "in flight");
assert_eq!(
app.update(Msg::Key(KeyPress::Confirm)),
Effect::None,
"a second Enter does not re-send"
);
}
#[test]
fn a_request_that_could_not_be_sent_says_so_and_clears_the_state() {
let mut app = allowed();
app.update(Msg::Key(KeyPress::Action(ActionVerb::Stop)));
let Effect::Send(sent) = app.update(Msg::Key(KeyPress::Confirm)) else {
panic!("Enter sends");
};
app.update(Msg::Unsent { sent });
assert!(app.action().is_none());
assert!(app.notice().is_some_and(Notice::is_grave));
}
#[test]
fn a_link_that_stops_being_live_takes_an_armed_prompt_down() {
for link in [
Msg::Retrying { attempt: 2 },
Msg::Frozen {
at_local: "2026-08-16 09:00:00".to_string(),
},
] {
let mut app = allowed();
app.update(Msg::Key(KeyPress::Action(ActionVerb::Stop)));
assert!(app.action().is_some(), "armed while live");
app.update(link);
assert!(app.action().is_none(), "and gone once the link is not");
assert_eq!(
app.update(Msg::Key(KeyPress::Confirm)),
Effect::None,
"so Enter has nothing to send"
);
}
}
#[test]
fn a_snapshot_replaces_the_flock_wholesale() {
let (mut app, t0) = started();
app.update(Msg::Event(BusEvent::Process {
event: ProcessEventKind::Start,
info: sheep(9, "ghost", ProcStatus::Starting),
manually: true,
at_ms: 0,
}));
assert_eq!(app.rows().len(), 4, "the bus event upserted");
app.update(Msg::Snapshot {
rows: vec![sheep(1, "web", ProcStatus::Online)],
at: t0,
});
assert_eq!(app.rows().len(), 1);
assert!(app.rows().iter().all(|row| row.info.id == 1));
}
#[test]
fn a_snapshot_that_shrinks_the_flock_pulls_the_selection_back() {
let (mut app, t0) = started();
app.update(Msg::Key(KeyPress::SelectLast));
assert_eq!(app.selected_index(), Some(3), "past the flock header");
app.update(Msg::Snapshot {
rows: vec![sheep(1, "web", ProcStatus::Online)],
at: t0,
});
assert_eq!(
app.selected_index(),
Some(1),
"the selection came back with the flock, past the header"
);
app.update(Msg::Snapshot {
rows: vec![],
at: t0,
});
assert_eq!(app.selected_index(), None, "an empty flock selects nothing");
}
#[test]
fn the_selection_follows_the_sheep_and_not_the_row_number() {
let (mut app, t0) = started();
app.update(Msg::Key(KeyPress::SelectDown));
app.update(Msg::Key(KeyPress::SelectDown));
assert_eq!(
app.selected(),
Some(RowKey::Sheep(3)),
"the third row, worker"
);
// Sheep 1 goes away. `worker` is now row 1 rather than row 2, where
// an index cursor would be pointing at `api`.
app.update(Msg::Snapshot {
rows: vec![
sheep(2, "api", ProcStatus::Errored),
sheep(3, "worker", ProcStatus::Online),
],
at: t0,
});
assert_eq!(app.selected(), Some(RowKey::Sheep(3)), "still worker");
assert_eq!(
app.selected_index(),
Some(2),
"which is now row 2, past the header"
);
}
#[test]
fn a_deleted_selection_falls_to_the_row_that_took_its_place() {
let (mut app, t0) = started();
app.update(Msg::Key(KeyPress::SelectDown));
assert_eq!(
app.selected(),
Some(RowKey::Sheep(1)),
"web, at index 1 by name"
);
// web dies; api and worker remain. Index 1 is now worker.
app.update(Msg::Snapshot {
rows: vec![
sheep(2, "api", ProcStatus::Online),
sheep(3, "worker", ProcStatus::Online),
],
at: t0,
});
assert_eq!(
app.selected(),
Some(RowKey::Sheep(3)),
"the row that took index 1"
);
// The last row dying clamps rather than leaving the cursor past the end.
app.update(Msg::Key(KeyPress::SelectLast));
assert_eq!(app.selected(), Some(RowKey::Sheep(3)));
app.update(Msg::Snapshot {
rows: vec![sheep(2, "api", ProcStatus::Online)],
at: t0,
});
assert_eq!(app.selected(), Some(RowKey::Sheep(2)));
app.update(Msg::Snapshot {
rows: vec![],
at: t0,
});
assert_eq!(app.selected(), None);
assert_eq!(app.selected_index(), None);
}
#[test]
fn a_selection_that_moves_refreshes_the_feed_and_one_that_cannot_does_not() {
let (mut app, _) = started();
assert_eq!(
app.update(Msg::Key(KeyPress::SelectDown)),
Effect::RefreshSelected
);
assert_eq!(
app.update(Msg::Key(KeyPress::SelectFirst)),
Effect::RefreshSelected
);
assert_eq!(
app.update(Msg::Key(KeyPress::SelectUp)),
Effect::None,
"already at the top: nothing moved, so nothing is re-read"
);
assert_eq!(
app.update(Msg::Key(KeyPress::SelectLast)),
Effect::RefreshSelected
);
assert_eq!(
app.update(Msg::Key(KeyPress::SelectDown)),
Effect::None,
"already at the bottom"
);
}
#[test]
fn moving_the_selection_asks_for_lambs() {
let (mut app, _t0) = started();
assert_eq!(
app.update(Msg::Key(KeyPress::SelectDown)),
Effect::RefreshSelected
);
}
/// `ListFlock` declines the lamb walk: a full machine enumeration every two
/// seconds, times every open lookout.
#[test]
fn a_snapshot_refreshes_the_feed_and_does_not_ask_for_lambs() {
let (mut app, t0) = started();
assert_eq!(
app.update(Msg::Snapshot {
rows: vec![sheep(1, "web", ProcStatus::Online)],
at: t0,
}),
Effect::RefreshFeed
);
}
#[test]
fn nothing_is_requested_while_the_link_is_lost() {
let (mut app, _t0) = started();
app.update(Msg::Frozen {
at_local: "2026-08-16 09:00:00".to_string(),
});
assert_eq!(app.update(Msg::Key(KeyPress::SelectDown)), Effect::None);
}
#[test]
fn a_snapshot_refreshes_the_feed_unless_the_link_is_frozen() {
let (mut app, t0) = started();
assert_eq!(
app.update(Msg::Snapshot {
rows: vec![sheep(1, "web", ProcStatus::Online)],
at: t0
}),
Effect::RefreshFeed
);
app.update(Msg::Frozen {
at_local: "2026-08-14 14:32:07".to_string(),
});
assert_eq!(
app.update(Msg::Snapshot {
rows: vec![sheep(1, "web", ProcStatus::Online)],
at: t0
}),
Effect::None,
"a frozen dashboard does not re-read anything"
);
}
/// The cursor still moves: re-rendering the detail pane from the frozen
/// listing is data already on the frame. Touching the disk is not.
#[test]
fn a_frozen_dashboard_moves_the_cursor_without_touching_a_file() {
let (mut app, _) = started();
app.update(Msg::Frozen {
at_local: "2026-08-14 14:32:07".to_string(),
});
assert_eq!(
app.update(Msg::Key(KeyPress::SelectDown)),
Effect::None,
"no file is read once the link is lost"
);
assert_eq!(
app.selected(),
Some(RowKey::Sheep(1)),
"but the cursor moved anyway"
);
assert_eq!(app.update(Msg::Key(KeyPress::SelectLast)), Effect::None);
assert_eq!(app.selected(), Some(RowKey::Sheep(3)));
}
#[test]
fn a_drop_and_a_lag_both_ask_for_an_immediate_poll() {
let (mut app, _) = started();
assert_eq!(
app.update(Msg::Event(BusEvent::Dropped { count: 12 })),
Effect::PollNow
);
assert_eq!(app.update(Msg::BusLagged { count: 3 }), Effect::PollNow);
assert_eq!(
app.update(Msg::Event(BusEvent::Process {
event: ProcessEventKind::Online,
info: sheep(1, "web", ProcStatus::Online),
manually: false,
at_ms: 0,
})),
Effect::None,
"an ordinary event needs no repair"
);
}
#[test]
fn a_shepherd_side_drop_and_a_local_lag_read_differently() {
let (mut app, _) = started();
app.update(Msg::Event(BusEvent::Dropped { count: 12 }));
let shepherd_side = app.notice().expect("a drop leaves a notice").to_string();
app.update(Msg::BusLagged { count: 3 });
let local = app.notice().expect("a lag leaves a notice").to_string();
assert!(shepherd_side.contains("the shepherd dropped"));
assert!(local.contains("lookout fell behind"));
assert_ne!(shepherd_side, local);
}
#[test]
fn a_running_sheeps_uptime_advances_with_the_heartbeat() {
let (mut app, t0) = started();
assert_eq!(app.uptime_ms(app.rows()[0].info.id), Some(60_000));
app.update(Msg::Tick {
now: t0 + Duration::from_secs(5),
});
assert_eq!(app.uptime_ms(1), Some(65_000));
}
#[test]
fn a_frozen_dashboard_stops_the_uptime_clock() {
let (mut app, t0) = started();
app.update(Msg::Tick {
now: t0 + Duration::from_secs(5),
});
app.update(Msg::Frozen {
at_local: "2026-08-14 14:32:07".to_string(),
});
let at_freeze = app.uptime_ms(1);
app.update(Msg::Tick {
now: t0 + Duration::from_secs(400),
});
assert_eq!(
app.uptime_ms(1),
at_freeze,
"the clock stopped with the link"
);
assert_eq!(at_freeze, Some(65_000));
}
#[test]
fn a_stopped_sheeps_uptime_does_not_advance() {
let t0 = Instant::now();
let mut app = App::new(
Palette::detect(None, None, None),
Control::ReadOnly,
"/home/ada/.shep".to_string(),
t0,
);
app.update(Msg::Snapshot {
rows: vec![sheep(1, "web", ProcStatus::Stopped)],
at: t0,
});
app.update(Msg::Tick {
now: t0 + Duration::from_secs(30),
});
assert_eq!(app.uptime_ms(1), Some(60_000));
}
#[test]
fn every_action_key_refuses_while_the_gate_is_closed() {
for verb in [ActionVerb::Stop, ActionVerb::Restart, ActionVerb::Reload] {
let (mut app, _t0) = started();
app.update(Msg::Key(KeyPress::Action(verb)));
assert!(
app.action().is_none(),
"{verb:?} armed behind a closed gate"
);
assert_eq!(
app.notice().map(ToString::to_string).as_deref(),
Some("read-only: from --read-only or lookout.allow_control"),
"{verb:?}"
);
}
}
/// A `DaemonShutdown` is a notice here, where in `bleats` it precedes a
/// clean exit.
#[test]
fn nothing_but_a_keypress_quits() {
let (mut app, _) = started();
for msg in [
Msg::Event(BusEvent::DaemonShutdown),
Msg::Event(BusEvent::Dropped { count: 1 }),
Msg::BusLagged { count: 1 },
Msg::Retrying { attempt: 5 },
Msg::Frozen {
at_local: "2026-08-14 14:32:07".to_string(),
},
] {
assert_ne!(app.update(msg), Effect::Quit);
}
assert_eq!(app.update(Msg::Key(KeyPress::Quit)), Effect::Quit);
}
/// `Effect::None`, not `RefreshFeed`: clearing a filter only widens the
/// visible set, so the selection stays seated and `reseat` is a no-op.
#[test]
fn esc_clears_the_filter_instead_of_quitting_while_one_is_set() {
let mut app = filtered("web");
assert_eq!(app.update(Msg::Key(KeyPress::Escape)), Effect::None);
assert_eq!(app.filter(), "");
assert_eq!(app.rows().len(), 4);
}
#[test]
fn esc_still_quits_with_no_filter_set() {
let (mut app, _t0) = started();
assert_eq!(app.update(Msg::Key(KeyPress::Escape)), Effect::Quit);
}
#[test]
fn the_table_narrows_while_the_query_is_still_being_typed() {
let (mut app, _t0) = started();
app.update(Msg::Key(KeyPress::FilterStart));
assert_eq!(app.mode(), InputMode::Text);
for letter in ['w', 'e', 'b'] {
app.update(Msg::Key(KeyPress::TextChar(letter)));
}
assert_eq!(app.rows().len(), 1, "narrowed before Enter");
app.update(Msg::Key(KeyPress::TextApply));
assert_eq!(app.mode(), InputMode::Normal);
assert_eq!(
app.rows().len(),
1,
"and applying changed nothing but the mode"
);
}
#[test]
fn backspace_widens_the_table_back_out() {
let (mut app, _t0) = started();
app.update(Msg::Key(KeyPress::FilterStart));
app.update(Msg::Key(KeyPress::TextChar('w')));
app.update(Msg::Key(KeyPress::TextChar('z')));
assert_eq!(app.rows().len(), 0);
app.update(Msg::Key(KeyPress::TextBackspace));
assert_eq!(
app.rows().len(),
2,
"wz became w, which matches web and worker"
);
}
#[test]
fn esc_while_editing_clears_the_filter_and_leaves_the_box() {
let (mut app, _t0) = started();
app.update(Msg::Key(KeyPress::FilterStart));
app.update(Msg::Key(KeyPress::TextChar('w')));
app.update(Msg::Key(KeyPress::TextAbandon));
assert_eq!(app.mode(), InputMode::Normal);
assert_eq!(app.filter(), "");
assert_eq!(app.rows().len(), 3);
}
#[test]
fn opening_the_filter_takes_a_notice_off_the_bar() {
let (mut app, _t0) = started();
app.update(Msg::Event(BusEvent::Dropped { count: 3 }));
assert!(app.notice().is_some());
app.update(Msg::Key(KeyPress::FilterStart));
assert!(app.notice().is_none(), "the box is what the bar shows now");
}
#[test]
fn a_notice_raised_while_typing_is_deferred_and_not_destroyed() {
let (mut app, _t0) = started();
app.update(Msg::Key(KeyPress::FilterStart));
app.update(Msg::Key(KeyPress::TextChar('w')));
app.update(Msg::Event(BusEvent::DaemonShutdown));
app.update(Msg::Key(KeyPress::TextChar('e')));
assert!(
app.notice().is_some(),
"typing did not wipe the shepherd's announcement"
);
assert_eq!(app.filter(), "we", "and the box kept the query");
}
#[test]
fn the_link_state_walks_live_to_retrying_to_lost_and_back() {
let (mut app, t0) = started();
assert_eq!(app.link(), &Link::Live);
app.update(Msg::Retrying { attempt: 1 });
assert_eq!(app.link(), &Link::Retrying { attempt: 1 });
app.update(Msg::Relinked);
assert_eq!(app.link(), &Link::Live);
app.update(Msg::Retrying { attempt: 5 });
app.update(Msg::Frozen {
at_local: "2026-08-14 14:32:07".to_string(),
});
assert_eq!(
app.link(),
&Link::Lost {
at_local: "2026-08-14 14:32:07".to_string()
}
);
// A late snapshot must not unfreeze it.
app.update(Msg::Snapshot {
rows: vec![],
at: t0,
});
assert!(matches!(app.link(), Link::Lost { .. }));
}
#[test]
fn the_selection_clamps_at_both_ends() {
let (mut app, _) = started();
for _ in 0..10 {
app.update(Msg::Key(KeyPress::SelectUp));
}
assert_eq!(
app.selected_index(),
Some(1),
"up past the first row stays on it, below the header"
);
for _ in 0..10 {
app.update(Msg::Key(KeyPress::SelectDown));
}
assert_eq!(
app.selected_index(),
Some(3),
"down past the last row stays on it"
);
app.update(Msg::Key(KeyPress::SelectFirst));
assert_eq!(app.selected_index(), Some(1));
app.update(Msg::Key(KeyPress::SelectLast));
assert_eq!(app.selected_index(), Some(3));
}
#[test]
fn refresh_polls_while_live_and_says_why_it_cannot_once_frozen() {
let (mut app, _) = started();
assert_eq!(app.update(Msg::Key(KeyPress::Refresh)), Effect::PollNow);
app.update(Msg::Frozen {
at_local: "2026-08-14 14:32:07".to_string(),
});
assert_eq!(
app.update(Msg::Key(KeyPress::Refresh)),
Effect::None,
"there is no link task left to ask"
);
let notice = app.notice().expect("a refusal is a notice").to_string();
assert!(notice.contains("the shepherd is gone"));
assert!(notice.contains("nothing left to ask"));
}
#[test]
fn the_next_keypress_clears_the_notice() {
let (mut app, _) = started();
app.update(Msg::Key(KeyPress::Action(ActionVerb::Stop)));
assert!(app.notice().is_some());
app.update(Msg::Key(KeyPress::SelectDown));
assert!(app.notice().is_none());
}
/// The strip reads this machine, which lookout can still see after the
/// shepherd dies, so it is the one pane that could keep ticking under a
/// banner saying the values are frozen.
#[test]
fn a_frozen_dashboard_ignores_a_host_sample() {
let (mut app, _) = started();
app.update(Msg::Host {
sample: Some(super::super::source::HostSample {
load: (2.31, 4.10, 3.88),
cores: Some(10),
memory_total_bytes: 32 << 30,
memory_used_bytes: 12 << 30,
uptime_seconds: 600,
}),
});
assert!(app.host().is_some(), "a live dashboard takes the sample");
app.update(Msg::Frozen {
at_local: "2026-08-14 14:32:07".to_string(),
});
let frozen = app.host();
assert_eq!(app.update(Msg::Host { sample: None }), Effect::None);
assert_eq!(app.host(), frozen, "the last values stay, unchanged");
assert!(
!app.host_unsupported(),
"and a refused sample changes no flag"
);
}
#[test]
fn applying_a_tail_does_not_ask_for_another_one() {
let (mut app, _) = started();
assert_eq!(
app.update(Msg::Bleats {
tail: super::super::tail::Tail::default()
}),
Effect::None
);
}
/// `run_ui`'s coalesced read is armed before the freeze, so a read can
/// still be in flight when `Msg::Frozen` lands.
#[test]
fn a_frozen_dashboard_ignores_a_bleats_tail_in_flight_at_the_freeze() {
let (mut app, _) = started();
let live_tail = super::super::tail::Tail {
lines: vec![super::super::tail::TailLine {
stream: super::super::tail::Stream::Out,
text: "read before the freeze".to_string(),
}],
..Default::default()
};
app.update(Msg::Bleats {
tail: live_tail.clone(),
});
assert_eq!(app.feed(), &live_tail, "a live dashboard takes the tail");
app.update(Msg::Frozen {
at_local: "2026-08-14 14:32:07".to_string(),
});
let in_flight_tail = super::super::tail::Tail {
lines: vec![super::super::tail::TailLine {
stream: super::super::tail::Stream::Out,
text: "read after the freeze".to_string(),
}],
..Default::default()
};
assert_eq!(
app.update(Msg::Bleats {
tail: in_flight_tail
}),
Effect::None
);
assert_eq!(
app.feed(),
&live_tail,
"the tail read after the freeze must not reach the rendered frame"
);
}
/// A dashboard whose filter is set without any keymap involved.
///
/// Four sheep, two of which contain `web`: `api-web` at id 1 and
/// `web-worker` at id 4, with `cron` and `queue` between them. The table
/// sorts by name, so the gap is what makes `j` stepping over a hidden row
/// falsifiable.
fn filtered(query: &str) -> App {
let t0 = Instant::now();
let mut app = App::new(
Palette::detect(None, None, None),
Control::ReadOnly,
"/home/ada/.shep".to_string(),
t0,
);
app.update(Msg::Snapshot {
rows: vec![
sheep(1, "api-web", ProcStatus::Online),
sheep(2, "cron", ProcStatus::Online),
sheep(3, "queue", ProcStatus::Online),
sheep(4, "web-worker", ProcStatus::Online),
],
at: t0,
});
app.set_filter(query.to_string());
app
}
/// The fixture separates the two answers: by id it is `web` 0, `api` 1,
/// `web` 2; by name then id it is `api` 1, `web` 0, `web` 2. The `(name,
/// id)` tiebreak itself is not falsifiable here, since the rows arrive in
/// id order; what this catches is the sort going missing entirely.
#[test]
fn the_table_draws_by_name_then_by_id() {
let t0 = Instant::now();
let mut app = App::new(
Palette::detect(None, None, None),
Control::ReadOnly,
"/home/ada/.shep".to_string(),
t0,
);
app.update(Msg::Snapshot {
rows: vec![
sheep(0, "web", ProcStatus::Online),
sheep(1, "api", ProcStatus::Online),
sheep(2, "web", ProcStatus::Online),
],
at: t0,
});
let drawn: Vec<(&str, u32)> = app
.rows()
.iter()
.map(|row| (row.info.name.as_str(), row.info.id))
.collect();
assert_eq!(drawn, vec![("api", 1), ("web", 0), ("web", 2)]);
}
#[test]
fn a_filter_narrows_the_rows_and_leaves_the_real_size_readable() {
let app = filtered("web");
assert_eq!(app.rows().len(), 2, "api-web and web-worker");
assert_eq!(app.flock_len(), 4, "the flock did not get smaller");
}
/// `ProcessSelector`'s `Name` compares with `==`, so borrowing the CLI's
/// selector grammar would match nothing while `web-worker` is being typed.
#[test]
fn the_filter_matches_a_substring_and_not_a_whole_name() {
assert_eq!(filtered("wor").rows().len(), 1, "web-worker, by its middle");
assert_eq!(filtered("w").rows().len(), 2, "api-web, by its own middle");
}
#[test]
fn the_filter_ignores_case_in_both_directions() {
let t0 = Instant::now();
let mut app = App::new(
Palette::detect(None, None, None),
Control::ReadOnly,
"/home/ada/.shep".to_string(),
t0,
);
app.update(Msg::Snapshot {
rows: vec![sheep(1, "WebEdge", ProcStatus::Online)],
at: t0,
});
app.set_filter("webedge".to_string());
assert_eq!(
app.rows().len(),
1,
"a lowercase query against a mixed name"
);
app.set_filter("WEBEDGE".to_string());
assert_eq!(app.rows().len(), 1, "and an uppercase one");
}
#[test]
fn j_and_k_step_only_over_visible_rows() {
let mut app = filtered("web");
assert_eq!(
app.selected(),
Some(RowKey::Sheep(1)),
"api-web, the first visible sheep"
);
app.update(Msg::Key(KeyPress::SelectDown));
assert_eq!(
app.selected(),
Some(RowKey::Sheep(4)),
"web-worker, skipping the hidden cron and queue"
);
app.update(Msg::Key(KeyPress::SelectDown));
assert_eq!(
app.selected(),
Some(RowKey::Sheep(4)),
"clamped at the last visible row"
);
app.update(Msg::Key(KeyPress::SelectUp));
assert_eq!(app.selected(), Some(RowKey::Sheep(1)));
}
#[test]
fn select_last_lands_on_the_last_visible_row() {
let mut app = filtered("web");
app.update(Msg::Key(KeyPress::SelectLast));
assert_eq!(
app.selected(),
Some(RowKey::Sheep(4)),
"web-worker, not queue at id 3"
);
}
#[test]
fn a_filter_that_hides_the_selection_clamps_to_the_nearest_visible_row() {
let mut app = filtered("");
app.update(Msg::Key(KeyPress::SelectLast));
assert_eq!(
app.selected(),
Some(RowKey::Sheep(4)),
"web-worker, position 3 of 4"
);
app.set_filter("web".to_string());
assert_eq!(
app.selected(),
Some(RowKey::Sheep(4)),
"position 3 clamps to the last visible row, which is web-worker"
);
}
#[test]
fn nothing_visible_means_nothing_selected() {
let app = filtered("zzz");
assert_eq!(app.rows().len(), 0);
assert_eq!(app.selected(), None);
assert!(app.selected_row().is_none());
assert_eq!(app.flock_len(), 4, "the flock is still four sheep");
}
#[test]
fn a_filter_survives_the_two_second_snapshot() {
let mut app = filtered("web");
let t1 = Instant::now();
app.update(Msg::Snapshot {
rows: vec![
sheep(1, "api-web", ProcStatus::Online),
sheep(2, "cron", ProcStatus::Online),
sheep(3, "queue", ProcStatus::Online),
sheep(4, "web-worker", ProcStatus::Online),
],
at: t1,
});
assert_eq!(app.filter(), "web", "the snapshot did not clear it");
assert_eq!(app.rows().len(), 2, "and did not widen the table");
assert_eq!(app.flock_len(), 4);
}
#[test]
fn an_empty_query_is_the_same_as_no_filter() {
let mut app = filtered("zzz");
app.set_filter(String::new());
assert_eq!(app.rows().len(), 4);
assert_eq!(app.selected(), Some(RowKey::Sheep(1)), "seated again");
}
/// `None` means the reply did not walk, `Some(vec![])` means it walked and
/// found nothing.
#[test]
fn a_lamb_reply_records_which_of_the_three_states_it_saw() {
let (mut app, t0) = started();
let walked = ProcessInfo::builder(1, "web", ProcStatus::Online)
.lambs(Some(vec![Lamb::new(48_220, "node")]))
.build();
app.update(Msg::Replied {
sent: Sent::Lambs { id: 1 },
result: Ok(Response::Described(vec![walked])),
});
assert!(matches!(app.lambs_for(1), Some((LambWalk::Walked(lambs), _)) if lambs.len() == 1));
let empty = ProcessInfo::builder(1, "web", ProcStatus::Online)
.lambs(Some(Vec::new()))
.build();
app.update(Msg::Replied {
sent: Sent::Lambs { id: 1 },
result: Ok(Response::Described(vec![empty])),
});
assert!(matches!(app.lambs_for(1), Some((LambWalk::Walked(lambs), _)) if lambs.is_empty()));
let unwalked = ProcessInfo::builder(1, "web", ProcStatus::Stopped).build();
app.update(Msg::Replied {
sent: Sent::Lambs { id: 1 },
result: Ok(Response::Described(vec![unwalked])),
});
assert!(matches!(app.lambs_for(1), Some((LambWalk::NotWalked, _))));
let _ = t0;
}
#[test]
fn a_reading_for_another_sheep_reads_as_not_read_yet() {
let (mut app, _t0) = started();
app.update(Msg::Replied {
sent: Sent::Lambs { id: 1 },
result: Ok(Response::Described(vec![
ProcessInfo::builder(1, "web", ProcStatus::Online)
.lambs(Some(vec![Lamb::new(48_220, "node")]))
.build(),
])),
});
assert!(app.lambs_for(1).is_some());
assert!(app.lambs_for(2).is_none(), "not this sheep's reading");
}
#[test]
fn a_failed_lamb_fetch_says_so_in_the_pane_and_raises_no_notice() {
let (mut app, _t0) = started();
app.update(Msg::Replied {
sent: Sent::Lambs { id: 1 },
result: Err(RequestError::Closed),
});
assert!(matches!(app.lambs_for(1), Some((LambWalk::Failed, _))));
assert!(app.notice().is_none(), "no notice for a decoration");
}
#[test]
fn an_unrecognised_lamb_reply_is_a_failure_and_not_an_empty_walk() {
let (mut app, _t0) = started();
app.update(Msg::Replied {
sent: Sent::Lambs { id: 1 },
result: Ok(Response::Pong),
});
assert!(matches!(app.lambs_for(1), Some((LambWalk::Failed, _))));
}
/// The fetch is armed before the freeze can land, so a reply can still be
/// in flight when `Msg::Frozen` arrives.
#[test]
fn a_lamb_reply_after_a_freeze_is_refused() {
let (mut app, _t0) = started();
app.update(Msg::Frozen {
at_local: "2026-08-16 09:00:00".to_string(),
});
app.update(Msg::Replied {
sent: Sent::Lambs { id: 1 },
result: Ok(Response::Described(vec![
ProcessInfo::builder(1, "web", ProcStatus::Online)
.lambs(Some(vec![Lamb::new(48_220, "node")]))
.build(),
])),
});
assert!(
app.lambs_for(1).is_none(),
"the frozen frame learned nothing"
);
}
#[test]
fn an_accepted_stop_upserts_the_rows_the_shepherd_returned() {
let mut app = allowed();
app.update(Msg::Key(KeyPress::Action(ActionVerb::Stop)));
app.update(Msg::Key(KeyPress::Confirm));
app.update(Msg::Replied {
sent: Sent::Action {
verb: ActionVerb::Stop,
target: RowKey::Sheep(2),
name: "api".to_string(),
},
result: Ok(Response::Stopped(vec![sheep(
2,
"api",
ProcStatus::Stopped,
)])),
});
assert_eq!(
app.rows()
.iter()
.find(|row| row.info.id == 2)
.map(|row| row.info.status),
Some(ProcStatus::Stopped),
"the table shows what the shepherd said, without waiting for a poll"
);
assert_eq!(
app.notice().map(ToString::to_string).as_deref(),
Some("stop api (id 2): the shepherd stopped it")
);
assert!(app.action().is_none(), "the in-flight state cleared");
}
/// `Response::Reloading` is an acceptance; the swaps arrive afterwards on
/// the bus, which the table consumes.
#[test]
fn a_reload_reply_does_not_claim_the_swap_finished() {
let mut app = allowed();
app.update(Msg::Key(KeyPress::Action(ActionVerb::Reload)));
app.update(Msg::Key(KeyPress::Confirm));
app.update(Msg::Replied {
sent: Sent::Action {
verb: ActionVerb::Reload,
target: RowKey::Sheep(2),
name: "api".to_string(),
},
result: Ok(Response::Reloading(vec![sheep(
2,
"api",
ProcStatus::Online,
)])),
});
let said = app.notice().map(ToString::to_string).unwrap_or_default();
assert_eq!(
said,
"reload api (id 2): accepted, the swaps report themselves as they happen"
);
assert!(!said.contains("reloaded"), "got {said:?}");
}
/// `RequestError`'s full `Display` would put a Rust identifier on screen.
#[test]
fn a_daemon_refusal_reaches_the_bar_in_the_daemons_own_words() {
let mut app = allowed();
app.update(Msg::Key(KeyPress::Action(ActionVerb::Restart)));
app.update(Msg::Key(KeyPress::Confirm));
app.update(Msg::Replied {
sent: Sent::Action {
verb: ActionVerb::Restart,
target: RowKey::Sheep(2),
name: "api".to_string(),
},
result: Err(RequestError::Rpc(RpcError {
code: RpcErrorCode::NotFound,
message: "selector matched no registered sheep".to_string(),
daemon_version: None,
})),
});
let said = app.notice().map(ToString::to_string).unwrap_or_default();
assert_eq!(
said,
"restart api (id 2): selector matched no registered sheep"
);
assert!(!said.contains("NotFound"), "no Rust identifiers: {said:?}");
assert!(app.notice().is_some_and(Notice::is_grave));
}
#[test]
fn a_connection_that_died_mid_request_says_so_under_the_same_prefix() {
let mut app = allowed();
app.update(Msg::Key(KeyPress::Action(ActionVerb::Stop)));
app.update(Msg::Key(KeyPress::Confirm));
app.update(Msg::Replied {
sent: Sent::Action {
verb: ActionVerb::Stop,
target: RowKey::Sheep(2),
name: "api".to_string(),
},
result: Err(RequestError::Closed),
});
let said = app.notice().map(ToString::to_string).unwrap_or_default();
assert!(said.starts_with("stop api (id 2): "), "got {said:?}");
assert!(said.contains(&RequestError::Closed.to_string()));
}
/// The second case is the sharper one: the right shape for the wrong verb.
/// A `Stopped` answering a `Restart` carries rows and would upsert happily.
#[test]
fn an_unrecognised_reply_says_so_rather_than_reading_as_success() {
for reply in [
Response::Pong,
Response::Stopped(vec![sheep(2, "api", ProcStatus::Stopped)]),
] {
let mut app = allowed();
app.update(Msg::Key(KeyPress::Action(ActionVerb::Restart)));
app.update(Msg::Key(KeyPress::Confirm));
app.update(Msg::Replied {
sent: Sent::Action {
verb: ActionVerb::Restart,
target: RowKey::Sheep(2),
name: "api".to_string(),
},
result: Ok(reply),
});
assert_eq!(
app.notice().map(ToString::to_string).as_deref(),
Some(
"restart api (id 2): the shepherd answered something this lookout does not understand"
)
);
assert!(app.notice().is_some_and(Notice::is_grave));
}
}
#[test]
fn s_asks_for_the_file_before_the_screen_opens() {
let mut app = fixtures::full_app();
assert_eq!(
app.update(Msg::Key(KeyPress::Settings)),
Effect::LoadSettings
);
assert!(
app.settings().is_none(),
"nothing opens until the read lands"
);
}
#[test]
fn the_screen_opens_when_the_read_lands() {
let mut app = fixtures::full_app();
let _ = app.update(Msg::Key(KeyPress::Settings));
let _ = app.update(Msg::Settings {
result: Ok(fixtures::settings_snapshot()),
});
assert!(app.settings().is_some());
}
#[test]
fn a_read_that_failed_says_so_and_leaves_the_dashboard_up() {
let mut app = fixtures::full_app();
let _ = app.update(Msg::Key(KeyPress::Settings));
let _ = app.update(Msg::Settings {
result: Err("no such file".into()),
});
assert!(app.settings().is_none());
let notice = app.notice().expect("a failed read has to say so");
assert!(notice.is_grave());
assert!(notice.to_string().contains("no such file"));
}
#[test]
fn s_closes_the_screen_again() {
let mut app = fixtures::app_in_settings();
let _ = app.update(Msg::Key(KeyPress::Settings));
assert!(app.settings().is_none());
}
/// From the dashboard with no filter `Esc` quits; from here it must not.
#[test]
fn escape_closes_the_screen_and_never_quits() {
let mut app = fixtures::app_in_settings();
assert_eq!(app.update(Msg::Key(KeyPress::Escape)), Effect::None);
assert!(app.settings().is_none());
}
#[test]
fn the_flock_cursor_and_the_filter_survive_the_swap() {
let mut app = fixtures::full_app();
let _ = app.update(Msg::Key(KeyPress::FilterStart));
for c in "web".chars() {
let _ = app.update(Msg::Key(KeyPress::TextChar(c)));
}
let _ = app.update(Msg::Key(KeyPress::TextApply));
let selected = app.selected();
let filter = app.filter().to_string();
let _ = app.update(Msg::Key(KeyPress::Settings));
let _ = app.update(Msg::Settings {
result: Ok(fixtures::settings_snapshot()),
});
let _ = app.update(Msg::Key(KeyPress::Settings));
assert_eq!(app.selected(), selected);
assert_eq!(app.filter(), filter);
}
#[test]
fn the_settings_cursor_starts_at_the_first_row_on_every_open() {
let mut app = fixtures::app_in_settings();
let _ = app.update(Msg::Key(KeyPress::SelectDown));
let _ = app.update(Msg::Key(KeyPress::SelectDown));
let _ = app.update(Msg::Key(KeyPress::Settings));
let _ = app.update(Msg::Key(KeyPress::Settings));
let _ = app.update(Msg::Settings {
result: Ok(fixtures::settings_snapshot()),
});
let first = app.settings().unwrap().rows()[0];
assert_eq!(app.settings().unwrap().cursor(), Some(first));
}
#[test]
fn the_cursor_moves_through_the_scalars_and_into_the_dogs() {
let mut app = fixtures::app_in_settings();
let rows = app.settings().unwrap().rows();
for _ in 0..rows.len() - 1 {
let _ = app.update(Msg::Key(KeyPress::SelectDown));
}
assert_eq!(
app.settings().unwrap().cursor(),
Some(*rows.last().unwrap())
);
// and it stops rather than wrapping
let _ = app.update(Msg::Key(KeyPress::SelectDown));
assert_eq!(
app.settings().unwrap().cursor(),
Some(*rows.last().unwrap())
);
}
#[test]
fn an_action_key_from_the_dashboard_is_unreachable_while_the_screen_is_up() {
let mut app = fixtures::app_in_settings_with_control();
// `x` is the stop key on the dashboard. In here it is not an action.
let _ = app.update(Msg::Key(KeyPress::Action(ActionVerb::Stop)));
assert!(app.action().is_none(), "no sheep confirm can arm from here");
}
/// Every key sequence that ends in a write, not one key: a gate guarding
/// `space` alone leaves the free-text editor's route reaching
/// `WriteSetting` on a read-only lookout.
///
/// The refusal is checked per keypress rather than at the end, because
/// `on_settings_key` clears `self.notice` on every key.
#[test]
fn no_key_route_writes_the_config_while_the_gate_is_closed() {
use KeyPress::{Confirm, Cycle, SelectDown, TextApply, TextChar};
// `Settings::rows` puts the six scalars first, then the fixture's two
// dogs: two `SelectDown`s reach `socket`, six the first dog row.
let routes: &[(&str, &[KeyPress])] = &[
("space on a cycled scalar", &[Cycle, Confirm]),
(
"the socket editor",
&[
SelectDown,
SelectDown,
Confirm,
TextChar('/'),
TextChar('x'),
TextApply,
Confirm,
],
),
(
"the max_cron_sleep editor",
&[
SelectDown,
SelectDown,
SelectDown,
Confirm,
TextChar('9'),
TextChar('s'),
TextApply,
Confirm,
],
),
(
"the whistle gate",
&[
SelectDown, SelectDown, SelectDown, SelectDown, Cycle, Confirm,
],
),
(
"space on a dog row",
&[
SelectDown, SelectDown, SelectDown, SelectDown, SelectDown, SelectDown, Cycle,
Confirm,
],
),
];
for (what, keys) in routes {
let mut app = fixtures::app_in_settings(); // Control::ReadOnly
let mut refused = false;
for key in *keys {
let effect = app.update(Msg::Key(*key));
assert!(
!matches!(effect, Effect::WriteSetting(..) | Effect::WriteDog(..)),
"{what}: a read-only lookout reached {effect:?}"
);
refused |= app.notice().is_some_and(Notice::is_grave);
}
assert!(refused, "{what}: the refusal has to say why");
assert!(
app.settings().unwrap().pending().is_none(),
"{what}: nothing is left armed"
);
assert!(
app.settings().unwrap().typing().is_none(),
"{what}: no editor is left open"
);
}
}
/// The half that keeps the closed-gate test honest: a gate that refused
/// everything would pass it and be useless.
#[test]
fn every_one_of_those_routes_writes_once_the_gate_is_open() {
use KeyPress::{Confirm, Cycle, SelectDown, TextApply, TextChar};
let routes: &[(&str, &[KeyPress])] = &[
("space on a cycled scalar", &[Cycle, Confirm]),
(
"the socket editor",
&[
SelectDown,
SelectDown,
Confirm,
TextChar('/'),
TextChar('x'),
TextApply,
Confirm,
],
),
(
"space on a dog row",
&[
SelectDown, SelectDown, SelectDown, SelectDown, SelectDown, SelectDown, Cycle,
Confirm,
],
),
];
for (what, keys) in routes {
let mut app = fixtures::app_in_settings_with_control();
let mut wrote = false;
for key in *keys {
let effect = app.update(Msg::Key(*key));
wrote |= matches!(effect, Effect::WriteSetting(..) | Effect::WriteDog(..));
}
assert!(wrote, "{what}: an open gate has to reach the write");
}
}
#[test]
fn a_read_only_lookout_opens_the_screen_and_refuses_the_edit_key() {
let mut app = fixtures::app_in_settings(); // Control::ReadOnly
assert!(app.settings().is_some(), "reading shep.toml is not gated");
let _ = app.update(Msg::Key(KeyPress::Cycle));
let notice = app.notice().expect("the refusal has to say why");
assert!(notice.is_grave());
}
#[test]
fn space_arms_a_candidate_without_changing_the_row() {
let mut app = fixtures::app_in_settings_with_control();
let before = app.settings().unwrap().snapshot().log_level.value.clone();
assert_eq!(app.update(Msg::Key(KeyPress::Cycle)), Effect::None);
assert_eq!(
app.settings().unwrap().snapshot().log_level.value,
before,
"arming is a question, so the row still shows what the file says"
);
assert!(app.settings().unwrap().pending().is_some());
}
/// Six log levels and one cycle key: without re-arming, the fourth needs a
/// cancel in between.
#[test]
fn space_advances_the_candidate_rather_than_needing_a_cancel() {
let mut app = fixtures::app_in_settings_with_control();
let _ = app.update(Msg::Key(KeyPress::Cycle));
let first = app.settings().unwrap().pending().unwrap().text.to_string();
let _ = app.update(Msg::Key(KeyPress::Cycle));
let second = app.settings().unwrap().pending().unwrap().text.to_string();
assert_ne!(first, second);
}
#[test]
fn the_daemon_confirm_names_both_layers_lookout_cannot_see() {
let mut app = fixtures::app_in_settings_with_control();
let _ = app.update(Msg::Key(KeyPress::Cycle));
let text = app.settings().unwrap().pending().unwrap().text.to_string();
assert!(text.contains("shep daemon reload"), "got: {text}");
assert!(text.contains("SHEP_LOG_LEVEL"), "got: {text}");
assert!(text.contains("--log-level"), "got: {text}");
}
#[test]
fn the_whistle_confirm_names_a_whistle_restart_and_not_a_reload() {
let mut app = fixtures::app_in_settings_on(SettingField::AllowControl);
let _ = app.update(Msg::Key(KeyPress::Cycle));
let text = app.settings().unwrap().pending().unwrap().text.to_string();
assert!(text.contains("shep whistle restarted"), "got: {text}");
assert!(
!text.contains("daemon reload"),
"a whistle key needs no reload: {text}"
);
}
#[test]
fn the_style_confirm_promises_nothing_beyond_the_next_command() {
let mut app = fixtures::app_in_settings_on(SettingField::StyleLevel);
let _ = app.update(Msg::Key(KeyPress::Cycle));
let text = app.settings().unwrap().pending().unwrap().text.to_string();
assert!(text.contains("the next command reads it"), "got: {text}");
}
/// `style::resolve` is flag over env over config, so with `$SHEP_STYLE` or
/// `--style` in play the write lands and nothing changes.
#[test]
fn a_shadowed_style_confirm_names_the_layer_that_keeps_winning() {
for (source, layer) in [
(StyleSource::Env, "$SHEP_STYLE"),
(StyleSource::Flag, "--style"),
] {
let mut app = fixtures::app_in_settings_with_shadowed_style(source);
let _ = app.update(Msg::Key(KeyPress::Cycle));
let text = app.settings().unwrap().pending().unwrap().text.to_string();
assert!(text.contains(layer), "{source} must name itself: {text}");
assert!(
text.contains("keeps winning"),
"{source} must say what it does: {text}"
);
assert!(
!text.contains("the next command reads it"),
"{source}: the next command reads {source}, not the file: {text}"
);
}
}
/// With `$SHEP_STYLE=bare` over a file saying `full`, cycling the resolved
/// value would propose `full`: a no-op write, reported as a change.
#[test]
fn the_style_cycle_starts_from_the_file_and_not_the_level_in_force() {
let mut app = fixtures::app_in_settings_with_shadowed_style(StyleSource::Env);
let _ = app.update(Msg::Key(KeyPress::Cycle));
let text = app.settings().unwrap().pending().unwrap().text.to_string();
assert!(
text.contains("set style level to plain"),
"the file says full, so one step is plain: {text}"
);
}
#[test]
fn enter_sends_the_armed_edit() {
let mut app = fixtures::app_in_settings_with_control();
let _ = app.update(Msg::Key(KeyPress::Cycle));
let effect = app.update(Msg::Key(KeyPress::Confirm));
assert!(matches!(
effect,
Effect::WriteSetting(
SettingEdit::Set {
field: SettingField::LogLevel,
..
},
_
)
));
assert!(app.settings().unwrap().pending().unwrap().sent);
}
#[test]
fn a_written_edit_updates_the_row_and_its_source() {
let mut app = fixtures::app_in_settings_with_control();
let _ = app.update(Msg::Key(KeyPress::Cycle));
let Effect::WriteSetting(edit, _) = app.update(Msg::Key(KeyPress::Confirm)) else {
panic!("Enter must send");
};
let SettingEdit::Set {
value: candidate, ..
} = edit.clone()
else {
panic!("cycling only ever arms Set");
};
let effect = app.update(Msg::SettingWritten {
edit,
result: Ok(()),
});
assert_eq!(
effect,
Effect::LoadSettings,
"a landed write re-reads rather than hand-folding the row"
);
assert!(app.settings().unwrap().pending().is_none());
// The re-read, which `run_ui` drives through `load_settings`.
let mut updated = fixtures::settings_snapshot();
updated.log_level = ScalarView {
value: candidate,
source: StyleSource::Config,
};
let _ = app.update(Msg::Settings {
result: Ok(updated.clone()),
});
assert_eq!(app.settings().unwrap().snapshot(), &updated);
}
#[test]
fn an_unset_write_returns_the_row_to_the_default() {
let mut app = fixtures::app_in_settings_on(SettingField::MaxCronSleep);
let _ = app.update(Msg::Key(KeyPress::Confirm));
for _ in 0..8 {
let _ = app.update(Msg::Key(KeyPress::TextBackspace));
}
let _ = app.update(Msg::Key(KeyPress::TextApply));
let Effect::WriteSetting(edit, _) = app.update(Msg::Key(KeyPress::Confirm)) else {
panic!("Enter must send");
};
assert!(matches!(
edit,
SettingEdit::Unset {
field: SettingField::MaxCronSleep
}
));
let effect = app.update(Msg::SettingWritten {
edit,
result: Ok(()),
});
assert_eq!(effect, Effect::LoadSettings);
let mut updated = fixtures::settings_snapshot();
updated.max_cron_sleep = ScalarView {
value: "30s".to_string(),
source: StyleSource::Default,
};
let _ = app.update(Msg::Settings {
result: Ok(updated.clone()),
});
assert_eq!(app.settings().unwrap().snapshot(), &updated);
}
/// Pins `Msg::Settings`'s `opening` check.
#[test]
fn the_cursor_survives_a_landed_writes_reload() {
let mut app = fixtures::app_in_settings_on(SettingField::MaxCronSleep);
let before = app.settings().unwrap().cursor();
let _ = app.update(Msg::Key(KeyPress::Confirm));
let _ = app.update(Msg::Key(KeyPress::TextApply));
let Effect::WriteSetting(edit, _) = app.update(Msg::Key(KeyPress::Confirm)) else {
panic!("Enter must send");
};
let _ = app.update(Msg::SettingWritten {
edit,
result: Ok(()),
});
let _ = app.update(Msg::Settings {
result: Ok(fixtures::settings_snapshot()),
});
assert_eq!(app.settings().unwrap().cursor(), before);
}
#[test]
fn the_cursor_survives_a_refresh() {
let mut app = fixtures::app_in_settings_on(SettingField::MaxCronSleep);
let before = app.settings().unwrap().cursor();
assert_eq!(
app.update(Msg::Key(KeyPress::Refresh)),
Effect::LoadSettings
);
let _ = app.update(Msg::Settings {
result: Ok(fixtures::settings_snapshot()),
});
assert_eq!(app.settings().unwrap().cursor(), before);
}
#[test]
fn a_refused_write_says_why_and_leaves_the_row_alone() {
let mut app = fixtures::app_in_settings_with_control();
let before = app.settings().unwrap().snapshot().log_level.clone();
let _ = app.update(Msg::Key(KeyPress::Cycle));
let Effect::WriteSetting(edit, _) = app.update(Msg::Key(KeyPress::Confirm)) else {
panic!("Enter must send");
};
let _ = app.update(Msg::SettingWritten {
edit,
result: Err("max_cron_sleep is 500ms, below the 1s floor".into()),
});
assert_eq!(app.settings().unwrap().snapshot().log_level, before);
let notice = app.notice().unwrap();
assert!(notice.is_grave());
assert!(notice.to_string().contains("below the 1s floor"));
}
/// The divergence from the sheep confirm, which `disarm_on_link_change`
/// clears: a settings edit is local file I/O.
#[test]
fn a_lost_link_leaves_a_scalar_confirm_armed() {
let mut app = fixtures::app_in_settings_with_control();
let _ = app.update(Msg::Key(KeyPress::Cycle));
let _ = app.update(Msg::Frozen {
at_local: "12:00:00".into(),
});
assert!(
app.settings().unwrap().pending().is_some(),
"a scalar never leaves the machine, so a dead shepherd is irrelevant to it"
);
}
/// Off the raw tick rather than `self.now`, which stops advancing once the
/// link is lost.
#[test]
fn a_settings_confirm_expires_on_a_frozen_dashboard() {
let (mut app, start) = fixtures::app_in_settings_at();
let _ = app.update(Msg::Key(KeyPress::Cycle));
let _ = app.update(Msg::Frozen {
at_local: "12:00:00".into(),
});
let _ = app.update(Msg::Tick {
now: start + CONFIRM_EXPIRY,
});
assert!(app.settings().unwrap().pending().is_none());
}
#[test]
fn escape_cancels_the_confirm_before_it_closes_the_screen() {
let mut app = fixtures::app_in_settings_with_control();
let _ = app.update(Msg::Key(KeyPress::Cycle));
let _ = app.update(Msg::Key(KeyPress::Escape));
assert!(app.settings().unwrap().pending().is_none());
assert!(
app.settings().is_some(),
"the first Esc cancels, it does not close"
);
let _ = app.update(Msg::Key(KeyPress::Escape));
assert!(app.settings().is_none());
}
/// `s` raises `Effect::LoadSettings` while `self.settings` is still `None`,
/// so `x` reaches `arm()`. Once the read lands, `on_settings_key` no-ops
/// `Confirm`, so nothing could resolve the armed action.
#[test]
fn opening_the_screen_clears_an_action_armed_while_the_read_was_in_flight() {
let mut app = fixtures::allowed_app();
let _ = app.update(Msg::Key(KeyPress::Settings));
let _ = app.update(Msg::Key(KeyPress::Action(ActionVerb::Stop)));
assert!(
app.action().is_some(),
"the arm must still succeed before the read lands"
);
let _ = app.update(Msg::Settings {
result: Ok(fixtures::settings_snapshot()),
});
assert!(
app.action().is_none(),
"no armed action may survive the screen opening"
);
}
/// `on_key` checks the text mode ahead of its settings branch, so a box
/// left open would eat every key the settings keymap owns. The query itself
/// is kept.
#[test]
fn opening_the_screen_closes_a_filter_box_left_open_while_the_read_was_in_flight() {
let mut app = fixtures::allowed_app();
let _ = app.update(Msg::Key(KeyPress::Settings));
let _ = app.update(Msg::Key(KeyPress::FilterStart));
let _ = app.update(Msg::Key(KeyPress::TextChar('w')));
let _ = app.update(Msg::Key(KeyPress::TextChar('e')));
assert_eq!(
app.mode(),
InputMode::Text,
"the box is open before the read lands"
);
let _ = app.update(Msg::Settings {
result: Ok(fixtures::settings_snapshot()),
});
assert!(app.settings().is_some(), "the screen opened");
assert_eq!(
app.mode(),
InputMode::Normal,
"the box must not survive the screen opening"
);
assert_eq!(app.filter(), "we", "the typed query is kept, not discarded");
}
#[test]
fn set_style_round_trips_exactly() {
let mut app = fixtures::full_app();
assert_eq!(
app.style(),
(StyleLevel::Full, StyleSource::Default),
"the default before anyone calls set_style"
);
app.set_style((StyleLevel::Bare, StyleSource::Flag));
assert_eq!(app.style(), (StyleLevel::Bare, StyleSource::Flag));
}
/// Against a real file whose `[style] level` names a third, different
/// level: the row reports the value threaded onto `App`, not one re-derived
/// from the file.
#[test]
fn the_style_set_on_the_app_reaches_the_settings_row_undropped() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("shep.toml");
std::fs::write(&path, "[style]\nlevel = \"bare\"\n").unwrap();
let socket_default = dir.path().join("run").join("shep.sock");
let mut app = fixtures::full_app();
app.set_style((StyleLevel::Plain, StyleSource::Flag));
let result = crate::commands::settings::load_settings(&path, &socket_default, app.style())
.map_err(|err| err.to_string());
let _ = app.update(Msg::Settings { result });
let row = &app.settings().unwrap().snapshot().style_level;
assert_eq!(
row.source,
StyleSource::Flag,
"the flag beats the file rather than being dropped by it"
);
assert_eq!(row.value, "plain");
}
#[test]
fn enter_on_a_text_row_opens_the_editor_seeded_with_the_current_value() {
let mut app = fixtures::app_in_settings_on(SettingField::MaxCronSleep);
let _ = app.update(Msg::Key(KeyPress::Confirm));
let (field, buffer) = app.settings().unwrap().typing().expect("the editor opens");
assert_eq!(*field, SettingField::MaxCronSleep);
assert_eq!(buffer, "30s");
}
#[test]
fn typing_then_enter_arms_rather_than_writing() {
let mut app = fixtures::app_in_settings_on(SettingField::MaxCronSleep);
let _ = app.update(Msg::Key(KeyPress::Confirm));
for _ in 0..3 {
let _ = app.update(Msg::Key(KeyPress::TextBackspace));
}
for c in "45s".chars() {
let _ = app.update(Msg::Key(KeyPress::TextChar(c)));
}
assert_eq!(app.update(Msg::Key(KeyPress::TextApply)), Effect::None);
let prompt = app.settings().unwrap().pending().unwrap();
assert!(
!prompt.sent,
"the editor arms; a second Enter is what sends"
);
assert!(prompt.text.contains("45s"), "got: {}", prompt.text);
assert!(
prompt.text.contains("SHEP_MAX_CRON_SLEEP"),
"got: {}",
prompt.text
);
}
#[test]
fn an_empty_editor_arms_an_unset() {
let mut app = fixtures::app_in_settings_on(SettingField::MaxCronSleep);
let _ = app.update(Msg::Key(KeyPress::Confirm));
for _ in 0..8 {
let _ = app.update(Msg::Key(KeyPress::TextBackspace));
}
let _ = app.update(Msg::Key(KeyPress::TextApply));
let text = app.settings().unwrap().pending().unwrap().text.to_string();
assert!(text.starts_with("unset max_cron_sleep?"), "got: {text}");
}
#[test]
fn the_socket_confirm_rules_out_the_reload_it_would_otherwise_imply() {
let mut app = fixtures::app_in_settings_on(SettingField::Socket);
let _ = app.update(Msg::Key(KeyPress::Confirm));
let _ = app.update(Msg::Key(KeyPress::TextApply));
let text = app.settings().unwrap().pending().unwrap().text.to_string();
assert!(text.contains("stopped and started"), "got: {text}");
assert!(text.contains("a reload will not move it"), "got: {text}");
}
/// A refusal is discovered under the lock, so it lands after the confirm,
/// and the typed text has to survive it.
#[test]
fn a_refused_write_reopens_the_editor_with_the_text_intact() {
let mut app = fixtures::app_in_settings_on(SettingField::MaxCronSleep);
let _ = app.update(Msg::Key(KeyPress::Confirm));
for _ in 0..3 {
let _ = app.update(Msg::Key(KeyPress::TextBackspace));
}
for c in "500ms".chars() {
let _ = app.update(Msg::Key(KeyPress::TextChar(c)));
}
let _ = app.update(Msg::Key(KeyPress::TextApply));
let Effect::WriteSetting(edit, _) = app.update(Msg::Key(KeyPress::Confirm)) else {
panic!("Enter must send");
};
let _ = app.update(Msg::SettingWritten {
edit,
result: Err("max_cron_sleep is 500ms, below the 1s floor".into()),
});
let (_, buffer) = app
.settings()
.unwrap()
.typing()
.expect("the editor reopens");
assert_eq!(buffer, "500ms");
assert!(
app.notice()
.unwrap()
.to_string()
.contains("below the 1s floor")
);
}
#[test]
fn escape_abandons_the_editor_and_keeps_the_screen_open() {
let mut app = fixtures::app_in_settings_on(SettingField::Socket);
let _ = app.update(Msg::Key(KeyPress::Confirm));
let _ = app.update(Msg::Key(KeyPress::TextAbandon));
assert!(app.settings().unwrap().typing().is_none());
assert!(app.settings().is_some());
}
#[test]
fn a_closed_scalar_has_no_editor() {
let mut app = fixtures::app_in_settings_with_control(); // on log_level
let _ = app.update(Msg::Key(KeyPress::Confirm));
assert!(
app.settings().unwrap().typing().is_none(),
"log_level is a cycle, not a text field"
);
}
#[test]
fn movement_cancels_an_armed_candidate_rather_than_also_moving() {
let mut app = fixtures::app_in_settings_with_control(); // cursor on log_level
let before = app.settings().unwrap().cursor();
let _ = app.update(Msg::Key(KeyPress::Cycle));
assert!(
app.settings().unwrap().pending().is_some(),
"space must arm before this test means anything"
);
let _ = app.update(Msg::Key(KeyPress::SelectDown));
assert!(
app.settings().unwrap().pending().is_none(),
"the armed candidate must not survive the movement key"
);
assert_eq!(
app.settings().unwrap().cursor(),
before,
"the cursor must not also move on the same keypress"
);
}
#[test]
fn refresh_cancels_an_armed_candidate_rather_than_silently_dropping_it() {
let mut app = fixtures::app_in_settings_with_control(); // cursor on log_level
let _ = app.update(Msg::Key(KeyPress::Cycle));
assert!(
app.settings().unwrap().pending().is_some(),
"space must arm before this test means anything"
);
let effect = app.update(Msg::Key(KeyPress::Refresh));
assert_eq!(
effect,
Effect::None,
"a cancel must not also raise a reload"
);
assert!(
app.settings().unwrap().pending().is_none(),
"the armed candidate must not survive `r`"
);
}
#[test]
fn arming_a_dog_names_the_live_apply_and_not_a_reload() {
let mut app = fixtures::app_in_settings_on_dog("metrics");
let _ = app.update(Msg::Key(KeyPress::Cycle));
let text = app.settings().unwrap().pending().unwrap().text.to_string();
assert!(text.contains("it starts now, no reload"), "got: {text}");
}
#[test]
fn disabling_says_it_deregisters() {
let mut app = fixtures::app_in_settings_on_enabled_dog("otel");
let _ = app.update(Msg::Key(KeyPress::Cycle));
let text = app.settings().unwrap().pending().unwrap().text.to_string();
assert!(text.contains("deregistered"), "got: {text}");
}
/// One message still yields one effect.
#[test]
fn a_written_dog_toggle_raises_the_daemon_half() {
let mut app = fixtures::app_in_settings_on_dog("metrics");
let _ = app.update(Msg::Key(KeyPress::Cycle));
let Effect::WriteDog(edit, _) = app.update(Msg::Key(KeyPress::Confirm)) else {
panic!("Enter must send the file half first");
};
let effect = app.update(Msg::DogWritten {
edit,
result: Ok(DogSource::BuiltIn),
});
assert!(matches!(
effect,
Effect::Send(Sent::Dog { enable: true, .. })
));
}
#[test]
fn a_refused_file_half_never_reaches_the_shepherd() {
let mut app = fixtures::app_in_settings_on_dog("metrics");
let _ = app.update(Msg::Key(KeyPress::Cycle));
let Effect::WriteDog(edit, _) = app.update(Msg::Key(KeyPress::Confirm)) else {
panic!("Enter must send the file half first");
};
let effect = app.update(Msg::DogWritten {
edit,
result: Err("permission denied".into()),
});
assert_eq!(
effect,
Effect::None,
"a failed write must not ask the shepherd"
);
assert!(app.notice().unwrap().is_grave());
}
/// The scalars never leave the machine; a dog's second half does.
#[test]
fn a_dog_toggle_refuses_while_the_link_is_gone() {
let mut app = fixtures::app_in_settings_on_dog("metrics");
let _ = app.update(Msg::Frozen {
at_local: "12:00:00".into(),
});
let effect = app.update(Msg::Key(KeyPress::Cycle));
assert_eq!(effect, Effect::None);
assert!(app.settings().unwrap().pending().is_none(), "nothing arms");
assert!(app.notice().unwrap().is_grave());
}
#[test]
fn a_scalar_still_edits_while_the_link_is_gone() {
let mut app = fixtures::app_in_settings_with_control(); // on log_level
let _ = app.update(Msg::Frozen {
at_local: "12:00:00".into(),
});
let _ = app.update(Msg::Key(KeyPress::Cycle));
assert!(
app.settings().unwrap().pending().is_some(),
"a scalar is local file I/O and needs no shepherd"
);
}
/// Drives a dog toggle to `Effect::Send`: arm, confirm the file half, then
/// land `Msg::DogWritten` so the daemon half goes out.
fn armed_and_sent_dog(name: &str) -> (App, Sent) {
let mut app = fixtures::app_in_settings_on_dog(name);
let _ = app.update(Msg::Key(KeyPress::Cycle));
let Effect::WriteDog(edit, _) = app.update(Msg::Key(KeyPress::Confirm)) else {
panic!("Enter must send the file half first");
};
let Effect::Send(sent) = app.update(Msg::DogWritten {
edit,
result: Ok(DogSource::BuiltIn),
}) else {
panic!("a landed write must raise the daemon half");
};
(app, sent)
}
/// `EnableDog` answers `Response::DogStarted`. The sentence names what the
/// shepherd did rather than a bare "done".
#[test]
fn a_landed_enable_names_what_the_shepherd_did() {
let (mut app, sent) = armed_and_sent_dog("metrics");
assert!(
app.settings().unwrap().pending().is_some(),
"the sent line stays up until the reply lands"
);
let info = ProcessInfo::builder(50, "metrics", ProcStatus::Online)
.pid(Some(50_000))
.dog(Some(DogSource::BuiltIn))
.build();
app.update(Msg::Replied {
sent,
result: Ok(Response::DogStarted(info)),
});
assert_eq!(
app.notice().map(ToString::to_string).as_deref(),
Some("enable metrics: the shepherd started it")
);
assert!(!app.notice().unwrap().is_grave());
assert!(
app.settings().unwrap().pending().is_none(),
"the sent line clears once the reply lands"
);
}
/// `DisableDog` answers `Response::Deleted`, the reply `Delete` gives. The
/// sentence names the deregistration, since the confirm is gone by now.
#[test]
fn a_landed_disable_names_the_deregistration() {
let (mut app, sent) = armed_and_sent_dog("otel");
app.update(Msg::Replied {
sent,
result: Ok(Response::Deleted(vec![50])),
});
assert_eq!(
app.notice().map(ToString::to_string).as_deref(),
Some("disable otel: the shepherd stopped and deregistered it")
);
assert!(!app.notice().unwrap().is_grave());
}
/// Whether the settings screen's own dogs list still says `name` is
/// enabled. Reads the snapshot, not the file: the two can disagree.
#[track_caller]
fn dog_enabled_in_view(app: &App, name: &str) -> bool {
app.settings()
.expect("the settings screen is open")
.snapshot()
.dogs
.iter()
.find(|dog| dog.name == name)
.expect("the fixture carries this dog")
.enabled
}
/// The file half lands first, so `DogView.enabled` is stale by the time
/// this reply arrives while running keeps updating off the poll. Without
/// the re-read a landed `enable metrics` reads `metrics | no | online`.
#[test]
fn a_landed_toggle_re_reads_the_file_in_both_directions() {
for (name, enable) in [("metrics", true), ("otel", false)] {
let (mut app, sent) = armed_and_sent_dog(name);
assert_eq!(
dog_enabled_in_view(&app, name),
!enable,
"{name}: the fixture starts on the other bit"
);
let reply = if enable {
Response::DogStarted(
ProcessInfo::builder(50, name, ProcStatus::Online)
.pid(Some(50_000))
.dog(Some(DogSource::BuiltIn))
.build(),
)
} else {
Response::Deleted(vec![50])
};
let effect = app.update(Msg::Replied {
sent,
result: Ok(reply),
});
assert_eq!(
effect,
Effect::LoadSettings,
"{name}: a landed toggle has to re-read the file it changed"
);
assert_eq!(
dog_enabled_in_view(&app, name),
!enable,
"{name}: nothing is folded into the row by hand -- the re-read is the repair"
);
// The re-read landing, with the bit the write put in the file.
let mut fresh = app.settings().unwrap().snapshot().clone();
for dog in &mut fresh.dogs {
if dog.name == name {
dog.enabled = enable;
}
}
app.update(Msg::Settings { result: Ok(fresh) });
assert_eq!(
dog_enabled_in_view(&app, name),
enable,
"{name}: and the row agrees with the file once it lands"
);
}
}
/// `metrics` is armed as an `enable`, so `Response::Deleted` is the right
/// shape for the wrong verb and `Response::Pong` is a reply this binary has
/// never heard of.
#[test]
fn an_unrecognised_dog_reply_says_so_rather_than_reading_as_success() {
for reply in [Response::Pong, Response::Deleted(vec![1])] {
let (mut app, sent) = armed_and_sent_dog("metrics");
app.update(Msg::Replied {
sent,
result: Ok(reply),
});
assert_eq!(
app.notice().map(ToString::to_string).as_deref(),
Some(
"enable metrics: the shepherd answered something this lookout does not understand"
)
);
assert!(app.notice().unwrap().is_grave());
}
}
#[test]
fn a_dog_reply_that_failed_to_send_says_so_under_the_same_prefix() {
let (mut app, sent) = armed_and_sent_dog("metrics");
app.update(Msg::Replied {
sent,
result: Err(RequestError::Closed),
});
let said = app.notice().map(ToString::to_string).unwrap_or_default();
assert!(said.starts_with("enable metrics: "), "got {said:?}");
assert!(said.contains(&RequestError::Closed.to_string()));
}
/// `e` raises the read, not the open: the pane shows the shepherd's own
/// answer or it shows nothing, the same rule `s` and `Msg::Settings`
/// already follow for the settings screen.
#[test]
fn e_asks_for_the_selected_sheeps_config_and_the_reply_opens_the_pane() {
let mut app =
fixtures::with_selection(ProcessInfo::builder(9, "web", ProcStatus::Online).build());
let effect = app.update(Msg::Key(KeyPress::Edit));
assert_eq!(
effect,
Effect::Send(Sent::SheepConfig {
name: "web".to_string()
})
);
assert!(app.config_pane().is_none(), "nothing opens on the keypress");
app.update(Msg::Replied {
sent: Sent::SheepConfig {
name: "web".to_string(),
},
result: Ok(Response::SheepConfig(Box::new(
fixtures::sheep_config_view(),
))),
});
let pane = app.config_pane().expect("the reply opens the pane");
assert_eq!(pane.target().name(), "web");
assert_eq!(pane.fields().len(), 39);
}
#[test]
fn e_with_nothing_selected_asks_for_nothing() {
let mut app = fixtures::app_with(Vec::new(), fixtures::plain());
assert_eq!(app.update(Msg::Key(KeyPress::Edit)), Effect::None);
assert!(app.config_pane().is_none());
}
/// A group has no single sheep, so `selected_row` answers `None` for
/// one. Every instance behind it shares one stored spec, and the group
/// row is what a multi-instance app shows by default.
#[test]
fn e_on_a_group_row_asks_by_the_apps_name() {
let mut app = fixtures::app_with(
vec![
ProcessInfo::builder(1, "web", ProcStatus::Online)
.instance(Some(0))
.build(),
ProcessInfo::builder(2, "web", ProcStatus::Online)
.instance(Some(1))
.build(),
],
fixtures::plain(),
);
app.update(Msg::Key(KeyPress::SelectFirst));
assert!(
app.selected_row().is_none(),
"the selection is the group row, not one instance"
);
assert_eq!(
app.update(Msg::Key(KeyPress::Edit)),
Effect::Send(Sent::SheepConfig {
name: "web".to_string()
})
);
}
#[test]
fn escape_closes_the_pane_and_does_not_quit() {
let mut app = fixtures::app_in_sheep_pane();
assert_eq!(app.update(Msg::Key(KeyPress::Escape)), Effect::None);
assert!(app.config_pane().is_none());
}
/// The behaviour change this branch exists for: `e` used to close the
/// pane, and now it does the field's own edit instead.
#[test]
fn e_no_longer_closes_the_pane() {
let mut app = fixtures::app_in_sheep_pane();
let _ = app.update(Msg::Key(KeyPress::Edit));
assert!(
app.config_pane().is_some(),
"e edits now; it does not close"
);
}
#[test]
fn e_opens_the_editor_on_a_typed_field_the_same_as_enter() {
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, "cwd");
let _ = app.update(Msg::Key(KeyPress::Edit));
assert_eq!(app.mode(), InputMode::Text, "e opens the text editor");
assert!(matches!(
app.config_pane().unwrap().pending_edit(),
Some(PanePending::Typing { .. })
));
}
#[test]
fn e_sends_an_armed_edit_the_same_as_enter() {
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, "autorestart");
let _ = app.update(Msg::Key(KeyPress::Cycle));
assert!(app.config_pane().unwrap().is_armed());
let request = wire(app.update(Msg::Key(KeyPress::Edit)));
let Request::SetSheepField { key, .. } = request else {
panic!("expected SetSheepField, got {request:?}");
};
assert_eq!(key, "autorestart");
}
#[test]
fn e_no_longer_closes_the_pane_from_the_env_sub_screen() {
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, "env");
let _ = app.update(Msg::Key(KeyPress::Confirm));
let _ = app.update(Msg::Key(KeyPress::Edit));
assert!(
app.config_pane().unwrap().env().is_some(),
"e must not close the pane or the sub-screen from in here"
);
}
#[test]
fn e_opens_the_editor_in_the_env_sub_screen_the_same_as_enter() {
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, "env");
let _ = app.update(Msg::Key(KeyPress::Confirm));
let _ = app.update(Msg::Key(KeyPress::Edit));
assert_eq!(app.mode(), InputMode::Text, "e opens the editor here too");
}
/// One escape at a time: the sub-screen first, the pane on the next
/// press. Nothing in this module tested that walk at the reducer
/// level before; `view::status`'s own test only pinned the hint text.
#[test]
fn escape_backs_out_of_the_env_sub_screen_one_level_at_a_time() {
let mut app = fixtures::app_in_sheep_pane_with_nothing_parked();
pane_to(&mut app, "env");
let _ = app.update(Msg::Key(KeyPress::Confirm));
assert!(app.config_pane().unwrap().env().is_some());
let _ = app.update(Msg::Key(KeyPress::Escape));
assert!(
app.config_pane().is_some(),
"the first escape only backs out of the sub-screen"
);
assert!(app.config_pane().unwrap().env().is_none());
let _ = app.update(Msg::Key(KeyPress::Escape));
assert!(
app.config_pane().is_none(),
"the second escape closes the pane"
);
}
#[test]
fn escape_closes_a_pane_with_nothing_parked() {
let mut app = fixtures::app_in_sheep_pane_with_nothing_parked();
let _ = app.update(Msg::Key(KeyPress::Escape));
assert!(
app.config_pane().is_none(),
"no menu when nothing is parked"
);
assert!(app.pane_menu().is_none());
}
#[test]
fn escape_on_a_parked_pane_offers_the_menu_and_escape_again_leaves() {
let mut app = fixtures::app_in_sheep_pane_with_a_parked_field();
let _ = app.update(Msg::Key(KeyPress::Escape));
assert!(
app.config_pane().is_some(),
"the pane stays up behind the menu"
);
assert!(app.pane_menu().is_some(), "the menu is open");
let _ = app.update(Msg::Key(KeyPress::Escape));
assert!(app.config_pane().is_none(), "escape twice leaves");
assert!(app.pane_menu().is_none());
}
#[test]
fn the_menu_counts_the_parked_fields_once() {
let mut app = fixtures::app_in_sheep_pane_with_two_parked_fields();
let _ = app.update(Msg::Key(KeyPress::Escape));
assert_eq!(app.pane_menu().expect("the menu is open").parked(), 2);
assert_eq!(
app.config_pane().expect("a pane").parked_count(),
2,
"the pane and the menu agree"
);
}
#[test]
fn the_menu_reads_which_reload_this_sheep_would_get() {
let mut app = fixtures::app_in_sheep_pane_with_a_parked_field();
let _ = app.update(Msg::Key(KeyPress::Escape));
assert_eq!(
app.pane_menu().expect("the menu is open").reload(),
ReloadKind::Overlap,
"the fixture sets no readiness probe"
);
}
#[test]
fn the_menu_never_opens_while_the_gate_is_closed() {
let mut app = fixtures::app_in_sheep_pane();
assert!(app.config_pane().expect("a pane").parked_count() > 0);
let _ = app.update(Msg::Key(KeyPress::Escape));
assert!(app.pane_menu().is_none(), "read-only can apply nothing");
assert!(app.config_pane().is_none());
}
#[test]
fn l_from_the_menu_reloads_the_sheep_and_leaves() {
let mut app = fixtures::app_in_sheep_pane_with_a_parked_field();
let _ = app.update(Msg::Key(KeyPress::Escape));
let request = wire(app.update(Msg::Key(KeyPress::Action(ActionVerb::Reload))));
assert!(
matches!(request, Request::Reload { .. }),
"expected Reload, got {request:?}"
);
assert!(app.config_pane().is_none());
assert!(app.pane_menu().is_none());
}
#[test]
fn r_from_the_menu_restarts_the_sheep_and_leaves() {
let mut app = fixtures::app_in_sheep_pane_with_a_parked_field();
let _ = app.update(Msg::Key(KeyPress::Escape));
let request = wire(app.update(Msg::Key(KeyPress::Action(ActionVerb::Restart))));
assert!(
matches!(request, Request::Restart { .. }),
"expected Restart, got {request:?}"
);
assert!(app.config_pane().is_none());
}
#[test]
fn escape_walks_out_of_the_sub_screen_then_the_menu_then_the_pane() {
let mut app = fixtures::app_in_sheep_pane_with_a_parked_field();
pane_to(&mut app, "env");
let _ = app.update(Msg::Key(KeyPress::Confirm));
assert!(app.config_pane().unwrap().env().is_some());
let _ = app.update(Msg::Key(KeyPress::Escape));
assert!(app.config_pane().unwrap().env().is_none());
assert!(app.pane_menu().is_none(), "the sub-screen went first");
let _ = app.update(Msg::Key(KeyPress::Escape));
assert!(app.pane_menu().is_some());
let _ = app.update(Msg::Key(KeyPress::Escape));
assert!(app.config_pane().is_none());
}
/// Help is dismissed before the menu is offered, so `h` then `esc`
/// still puts the operator back on the field list.
#[test]
fn escape_dismisses_help_before_it_offers_the_menu() {
let mut app = fixtures::app_in_sheep_pane_with_a_parked_field();
let _ = app.update(Msg::Key(KeyPress::Help));
let _ = app.update(Msg::Key(KeyPress::Escape));
assert!(!app.config_pane().unwrap().help_open());
assert!(app.pane_menu().is_none());
}
#[test]
fn h_toggles_help_and_escape_dismisses_it_before_closing_the_pane() {
let mut app = fixtures::app_in_sheep_pane();
pane_to(&mut app, "max_memory");
let _ = app.update(Msg::Key(KeyPress::Help));
assert!(app.config_pane().unwrap().help_open());
// Escape dismisses help first; the pane is still open.
let _ = app.update(Msg::Key(KeyPress::Escape));
assert!(!app.config_pane().unwrap().help_open());
assert!(
app.config_pane().is_some(),
"the first escape only closes help"
);
// A second `h` toggles it back open, and pressing it again closes it.
let _ = app.update(Msg::Key(KeyPress::Help));
assert!(app.config_pane().unwrap().help_open());
let _ = app.update(Msg::Key(KeyPress::Help));
assert!(!app.config_pane().unwrap().help_open());
// Escape with help already closed closes the pane, same as ever.
let _ = app.update(Msg::Key(KeyPress::Escape));
assert!(app.config_pane().is_none());
}
/// `h` has no field to show help for on the env sub-screen, so it is
/// silently ignored there rather than reaching back to the field list.
#[test]
fn h_does_nothing_on_the_env_sub_screen() {
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, "env");
let _ = app.update(Msg::Key(KeyPress::Confirm));
assert_eq!(app.update(Msg::Key(KeyPress::Help)), Effect::None);
assert!(!app.config_pane().unwrap().help_open());
}
#[test]
fn the_pane_owns_the_keyboard_while_it_is_open() {
let mut app = fixtures::app_in_sheep_pane();
assert_eq!(
app.update(Msg::Key(KeyPress::Action(ActionVerb::Stop))),
Effect::None
);
assert!(
app.action().is_none(),
"no action arms from inside the pane"
);
assert_eq!(app.update(Msg::Key(KeyPress::Settings)), Effect::None);
assert!(
app.settings().is_none(),
"`s` does not open a second screen"
);
assert!(app.config_pane().is_some());
}
#[test]
fn the_movement_keys_walk_the_fields() {
let mut app = fixtures::app_in_sheep_pane();
app.update(Msg::Key(KeyPress::SelectDown));
app.update(Msg::Key(KeyPress::SelectDown));
assert_eq!(app.config_pane().unwrap().view().cursor(), 2);
app.update(Msg::Key(KeyPress::SelectLast));
assert_eq!(app.config_pane().unwrap().view().cursor(), 38);
app.update(Msg::Key(KeyPress::SelectFirst));
assert_eq!(app.config_pane().unwrap().view().cursor(), 0);
}
#[test]
fn r_re_reads_the_same_sheep_and_the_cursor_survives_it() {
let mut app = fixtures::app_in_sheep_pane();
app.update(Msg::Key(KeyPress::SelectLast));
let sent = Sent::SheepConfig {
name: "web".to_string(),
};
assert_eq!(
app.update(Msg::Key(KeyPress::Refresh)),
Effect::Send(sent.clone())
);
app.update(Msg::Replied {
sent,
result: Ok(Response::SheepConfig(Box::new(
fixtures::sheep_config_view(),
))),
});
assert_eq!(app.config_pane().unwrap().view().cursor(), 38);
}
#[test]
fn a_refused_config_read_says_why_and_leaves_the_pane_alone() {
let mut app = fixtures::app_in_sheep_pane();
app.update(Msg::Replied {
sent: Sent::SheepConfig {
name: "web".to_string(),
},
result: Err(RequestError::Rpc(RpcError {
code: RpcErrorCode::NotFound,
message: "no sheep named web".to_string(),
daemon_version: None,
})),
});
let said = app.notice().map(ToString::to_string).unwrap_or_default();
assert!(said.contains("no sheep named web"), "got {said:?}");
assert!(app.notice().unwrap().is_grave());
assert!(app.config_pane().is_some(), "the pane stays as it was");
}
/// Silence looks exactly like a key that is not bound.
#[test]
fn a_config_read_that_was_never_sent_says_so() {
let mut app =
fixtures::with_selection(ProcessInfo::builder(9, "web", ProcStatus::Online).build());
app.update(Msg::Unsent {
sent: Sent::SheepConfig {
name: "web".to_string(),
},
});
let said = app.notice().map(ToString::to_string).unwrap_or_default();
assert!(said.contains("web"), "got {said:?}");
assert!(app.notice().unwrap().is_grave());
}
/// It spends its first line on a title naming the sheep, so a viewport
/// told the full body height would scroll one row late.
#[test]
fn the_pane_gets_the_body_height_minus_its_own_title() {
let mut app = fixtures::app_in_sheep_pane();
app.note_body_rows(20);
app.update(Msg::Key(KeyPress::SelectLast));
assert_eq!(app.config_pane().unwrap().view().offset(), 39 - 19);
}
/// Walks the pane's cursor onto `key`. The pane is a public type with
/// no public "go to this field" key, so the cursor is driven the way
/// an operator drives it.
fn pane_to(app: &mut App, key: &str) {
let index = app
.config_pane()
.expect("the pane is open")
.fields()
.fields()
.iter()
.position(|field| field.key == key)
.unwrap_or_else(|| panic!("no field named {key}"));
let _ = app.update(Msg::Key(KeyPress::SelectFirst));
for _ in 0..index {
let _ = app.update(Msg::Key(KeyPress::SelectDown));
}
}
/// Lands a `Request::SheepConfig` reply for `web` carrying `env_keys`,
/// the way the event loop lands one after a write or an `r`.
fn refresh_config(app: &mut App, env_keys: &[&str]) {
let mut config = shep_core::config::AppConfig {
name: "web".to_string(),
..Default::default()
};
for key in env_keys {
config.env.insert((*key).to_string(), "x".to_string());
}
app.update(Msg::Replied {
sent: Sent::SheepConfig {
name: "web".to_string(),
},
result: Ok(Response::SheepConfig(Box::new(
shep_core::protocol::SheepConfigView::new(config, Vec::new(), Vec::new()),
))),
});
}
/// The request an effect would put on the wire, or a panic naming what
/// came back instead. The seam this test module cares about: the
/// reducer's own `Sent` is an echo tag, and `Sent::request` is what the
/// link task actually sends.
fn wire(effect: Effect) -> Request {
match effect {
Effect::Send(sent) => sent.request(),
other => panic!("expected a request, got {other:?}"),
}
}
/// One field from each of the groups the pane draws, since the
/// daemon's routing classification is per field. `rpc.rs`'s
/// `a_field_edit_is_reported_as_an_operator_override` asserts the
/// other half, where the marker is actually built.
#[test]
fn one_edit_reaches_the_wire_as_a_single_field_override() {
for (key, presses) in [
("autorestart", 1usize), // control
("watch", 1), // process
("merge_logs", 1), // inputs
("autorestart", 2), // twice: a second cycle re-arms
] {
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, key);
for _ in 0..presses {
let _ = app.update(Msg::Key(KeyPress::Cycle));
}
assert!(
app.config_pane().unwrap().is_armed(),
"{key}: space must arm before Enter means anything"
);
let request = wire(app.update(Msg::Key(KeyPress::Confirm)));
let Request::SetSheepField {
name,
key: sent,
value,
} = request
else {
panic!("{key}: expected SetSheepField, got {request:?}");
};
assert_eq!(name, "web", "{key}");
assert_eq!(sent, key, "{key}");
assert!(value.is_boolean(), "{key}: {value}");
}
}
/// `cwd` and `max_restarts` between them cover text and integer, which
/// arm differently, and an integer sent as a string is refused by the
/// daemon rather than set.
#[test]
fn a_typed_field_reaches_the_wire_as_the_value_that_was_typed() {
for (key, typed, want) in [
("cwd", "/srv/web", serde_json::json!("/srv/web")),
("max_restarts", "40", serde_json::json!(40)),
] {
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, key);
let _ = app.update(Msg::Key(KeyPress::Confirm));
assert_eq!(app.mode(), InputMode::Text, "{key}: the editor opens");
for _ in 0..40 {
let _ = app.update(Msg::Key(KeyPress::TextBackspace));
}
for typed in typed.chars() {
let _ = app.update(Msg::Key(KeyPress::TextChar(typed)));
}
let _ = app.update(Msg::Key(KeyPress::TextApply));
assert_eq!(app.mode(), InputMode::Normal, "{key}: the editor closes");
let request = wire(app.update(Msg::Key(KeyPress::Confirm)));
let Request::SetSheepField {
key: sent, value, ..
} = request
else {
panic!("{key}: expected SetSheepField, got {request:?}");
};
assert_eq!(sent, key, "{key}");
assert_eq!(value, want, "{key}");
}
}
/// Routing through `ApplyConfig` would not work: no `ResetDepth`
/// names a single key.
#[test]
fn the_env_sub_screen_arms_then_sets_one_key_and_removes_another() {
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, "env");
let _ = app.update(Msg::Key(KeyPress::Confirm));
assert!(
app.config_pane().unwrap().env().is_some(),
"enter on the env row opens the sub-screen"
);
// The `+ new` row, under the two keys the fixture's sheep has.
let _ = app.update(Msg::Key(KeyPress::SelectLast));
let _ = app.update(Msg::Key(KeyPress::Confirm));
assert_eq!(app.mode(), InputMode::Text);
for typed in "API_TOKEN=hunter2".chars() {
let _ = app.update(Msg::Key(KeyPress::TextChar(typed)));
}
assert_eq!(
app.update(Msg::Key(KeyPress::TextApply)),
Effect::None,
"applying the editor arms; it does not send"
);
assert_eq!(app.mode(), InputMode::Normal);
let armed = app.config_pane().unwrap().pending_edit();
let Some(PanePending::Armed { text, .. }) = armed else {
panic!("{armed:?}");
};
assert!(text.contains("set env API_TOKEN"), "{text}");
assert!(
!text.contains("hunter2"),
"the sentence must not quote the value: {text}"
);
let request = wire(app.update(Msg::Key(KeyPress::Confirm)));
assert_eq!(
request,
Request::SetSheepEnv {
name: "web".to_owned(),
key: "API_TOKEN".to_owned(),
value: Some("hunter2".to_owned().into()),
}
);
// An existing key with an empty buffer removes it, and the question
// names the key and says the value is not recoverable from here.
let _ = app.update(Msg::Key(KeyPress::SelectFirst));
let _ = app.update(Msg::Key(KeyPress::Confirm));
let _ = app.update(Msg::Key(KeyPress::TextApply));
let armed = app.config_pane().unwrap().pending_edit();
let Some(PanePending::Armed { text, .. }) = armed else {
panic!("{armed:?}");
};
assert!(text.contains("remove env DB_HOST"), "{text}");
assert!(text.contains("cannot read the value back"), "{text}");
let request = wire(app.update(Msg::Key(KeyPress::Confirm)));
assert_eq!(
request,
Request::SetSheepEnv {
name: "web".to_owned(),
key: "DB_HOST".to_owned(),
value: None,
}
);
}
#[test]
fn a_stray_key_cancels_an_armed_env_write() {
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, "env");
let _ = app.update(Msg::Key(KeyPress::Confirm));
let _ = app.update(Msg::Key(KeyPress::Confirm));
let _ = app.update(Msg::Key(KeyPress::TextApply));
assert!(
app.config_pane().unwrap().is_armed(),
"an empty buffer arms"
);
assert_eq!(app.update(Msg::Key(KeyPress::SelectDown)), Effect::None);
assert!(!app.config_pane().unwrap().is_armed());
assert!(
app.config_pane().unwrap().env().is_some(),
"the cancel must not also close the sub-screen"
);
}
/// A removal shortens the list, so a cursor carried by index would name
/// the next key down, and a reflexive second `Enter` would arm a write
/// against a neighbour nobody chose. A key that is gone lands on
/// `+ new`, the one row where `Enter` destroys nothing.
#[test]
fn the_env_cursor_is_carried_by_key_and_not_by_index_across_a_refresh() {
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, "env");
let _ = app.update(Msg::Key(KeyPress::Confirm));
let _ = app.update(Msg::Key(KeyPress::SelectDown));
assert_eq!(
app.config_pane().unwrap().env().unwrap().cursor_key(),
Some("LOG_LEVEL")
);
// A refresh that leaves both keys in place keeps the cursor on its
// own key rather than on row 1.
refresh_config(&mut app, &["DB_HOST", "LOG_LEVEL"]);
assert_eq!(
app.config_pane().unwrap().env().unwrap().cursor_key(),
Some("LOG_LEVEL")
);
// A refresh that removed the key above it keeps it on its own key,
// which is now row 0. Carrying the index would have moved it to
// `+ new`; carrying nothing would have moved it to `DB_HOST`.
refresh_config(&mut app, &["LOG_LEVEL"]);
assert_eq!(
app.config_pane().unwrap().env().unwrap().cursor_key(),
Some("LOG_LEVEL")
);
// A refresh that removed the cursor's own key lands on `+ new`,
// never on whatever took its place.
refresh_config(&mut app, &["OTHER"]);
assert_eq!(app.config_pane().unwrap().env().unwrap().cursor_key(), None);
}
/// `settle` clears only the write that is in flight. On the env screen
/// the discarded buffer is a secret the operator cannot read back.
#[test]
fn a_reply_landing_mid_edit_leaves_the_buffer_and_the_keyboard_alone() {
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, "autorestart");
let _ = app.update(Msg::Key(KeyPress::Cycle));
let Effect::Send(sent) = app.update(Msg::Key(KeyPress::Confirm)) else {
panic!("the confirm sends");
};
// The operator moves on and starts typing while it is in flight.
pane_to(&mut app, "cwd");
let _ = app.update(Msg::Key(KeyPress::Confirm));
for typed in "/srv".chars() {
let _ = app.update(Msg::Key(KeyPress::TextChar(typed)));
}
assert_eq!(app.mode(), InputMode::Text);
let _ = app.update(Msg::Unsent { sent });
assert_eq!(app.mode(), InputMode::Text, "the keyboard is not stranded");
let pending = app.config_pane().unwrap().pending_edit();
let Some(PanePending::Typing { key, buffer }) = pending else {
panic!("the buffer survives the reply: {pending:?}");
};
assert_eq!(key, "cwd");
assert!(buffer.ends_with("/srv"), "{buffer}");
}
/// A landed write asks for a re-read, and the re-read rebuilds the
/// whole `ConfigPane`, editor included.
#[test]
fn a_refresh_that_drops_an_open_editor_puts_the_keyboard_back() {
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, "cwd");
let _ = app.update(Msg::Key(KeyPress::Confirm));
assert_eq!(app.mode(), InputMode::Text);
refresh_config(&mut app, &["DB_HOST", "LOG_LEVEL"]);
assert_eq!(app.mode(), InputMode::Normal);
assert!(app.config_pane().unwrap().pending_edit().is_none());
}
/// Only the line was ever at risk: each request names exactly its own
/// key, so neither can carry the other's value, and the config itself
/// cannot be crossed.
#[test]
fn an_arriving_reply_leaves_the_in_flight_line_of_another_write() {
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, "autorestart");
let _ = app.update(Msg::Key(KeyPress::Cycle));
let Effect::Send(first) = app.update(Msg::Key(KeyPress::Confirm)) else {
panic!("the first confirm sends");
};
pane_to(&mut app, "watch");
let _ = app.update(Msg::Key(KeyPress::Cycle));
let Effect::Send(second) = app.update(Msg::Key(KeyPress::Confirm)) else {
panic!("the second confirm sends");
};
assert!(matches!(
app.config_pane().unwrap().pending_edit(),
Some(PanePending::Sent { key, .. }) if key == "watch"
));
let _ = app.update(Msg::Replied {
sent: first,
result: Ok(Response::SheepFieldSet {
name: "web".to_owned(),
key: "autorestart".to_owned(),
pending: false,
}),
});
let pending = app.config_pane().unwrap().pending_edit();
assert!(
matches!(pending, Some(PanePending::Sent { key, .. }) if key == "watch"),
"the second write is still outstanding: {pending:?}"
);
let _ = app.update(Msg::Replied {
sent: second,
result: Ok(Response::SheepFieldSet {
name: "web".to_owned(),
key: "watch".to_owned(),
pending: false,
}),
});
assert!(app.config_pane().unwrap().pending_edit().is_none());
}
/// `instances` is `Lock::Refused`, since shep takes no config write for
/// it at all. `liveness_probe` is `Lock::NoWidget`, since this pane
/// simply has no editor for a nested object. `Lock` exists so one
/// sentence never covers both.
#[test]
fn a_refused_field_and_one_with_no_widget_refuse_for_different_reasons() {
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, "instances");
assert_eq!(app.update(Msg::Key(KeyPress::Cycle)), Effect::None);
assert!(app.config_pane().unwrap().pending_edit().is_none());
let refused = app.notice().expect("a refusal is raised").to_string();
assert!(refused.contains("instances"), "{refused}");
assert!(
!refused.contains("no editor in this pane"),
"a field shep refuses is not a field this pane merely lacks a widget for: {refused}"
);
pane_to(&mut app, "liveness_probe");
assert_eq!(app.update(Msg::Key(KeyPress::Confirm)), Effect::None);
assert!(app.config_pane().unwrap().pending_edit().is_none());
let no_widget = app.notice().expect("a refusal is raised").to_string();
assert!(no_widget.contains("liveness_probe"), "{no_widget}");
assert!(
no_widget.contains("Flockfile"),
"a shape with no widget is still one a Flockfile writes: {no_widget}"
);
assert_ne!(refused, no_widget, "two facts, two sentences");
}
#[test]
fn a_refused_field_names_the_verb_that_owns_it() {
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, "instances");
let _ = app.update(Msg::Key(KeyPress::Cycle));
let said = app.notice().expect("a refusal is raised").to_string();
assert!(said.contains("`shep stock`"), "{said}");
}
/// The lock wins over the control gate: `--allow-control` does not
/// unlock a Structural field.
#[test]
fn space_and_enter_refuse_a_locked_row_with_the_same_sentence() {
for control in [Control::ReadOnly, Control::Allowed] {
for key in ["instances", "liveness_probe"] {
let mut app = fixtures::app_in_sheep_pane();
app.set_control_for_tests(control);
pane_to(&mut app, key);
let _ = app.update(Msg::Key(KeyPress::Cycle));
let cycled = app.notice().map(ToString::to_string);
let _ = app.update(Msg::Key(KeyPress::Confirm));
let confirmed = app.notice().map(ToString::to_string);
assert_eq!(cycled, confirmed, "{control:?} {key}");
assert!(
cycled.as_deref().is_some_and(|text| text.contains(key)),
"{control:?} {key}: {cycled:?}"
);
assert_ne!(
cycled.as_deref(),
Some(READ_ONLY_REFUSAL),
"the lock is the more specific fact: {control:?} {key}"
);
}
}
}
#[test]
fn a_read_only_pane_refuses_every_door_that_writes() {
// One pair per door: `space` arms a cycle, `Enter` opens the text
// editor, `Enter` on `env` opens the sub-screen.
for (key, press) in [
("autorestart", KeyPress::Cycle),
("cwd", KeyPress::Confirm),
("env", KeyPress::Confirm),
] {
let mut app = fixtures::app_in_sheep_pane();
pane_to(&mut app, key);
assert_eq!(app.update(Msg::Key(press)), Effect::None, "{key}");
assert!(app.config_pane().unwrap().pending_edit().is_none(), "{key}");
assert!(app.config_pane().unwrap().env().is_none(), "{key}");
assert_eq!(app.mode(), InputMode::Normal, "{key}");
assert_eq!(
app.notice().map(ToString::to_string),
Some(READ_ONLY_REFUSAL.to_string()),
"{key}"
);
}
}
#[test]
fn a_stray_key_cancels_an_armed_pane_edit_and_does_nothing_else() {
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, "autorestart");
let before = app.config_pane().unwrap().view().cursor();
let _ = app.update(Msg::Key(KeyPress::Cycle));
assert!(app.config_pane().unwrap().is_armed());
assert_eq!(app.update(Msg::Key(KeyPress::SelectDown)), Effect::None);
assert!(!app.config_pane().unwrap().is_armed());
assert_eq!(app.config_pane().unwrap().view().cursor(), before);
assert!(
app.config_pane().is_some(),
"the cancel must not also close the pane"
);
}
#[test]
fn an_armed_pane_edit_expires_with_the_confirm_budget() {
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, "autorestart");
let _ = app.update(Msg::Key(KeyPress::Cycle));
assert!(app.config_pane().unwrap().is_armed());
let _ = app.update(Msg::Tick {
now: Instant::now() + CONFIRM_EXPIRY,
});
assert!(!app.config_pane().unwrap().is_armed());
}
/// `pending` is the shepherd's answer, reported verbatim rather than
/// re-derived from `apply_group`: the two disagree on `autostart`, and
/// on a field whose config subset would not normalize.
#[test]
fn a_landed_write_re_reads_the_config_and_reports_what_the_shepherd_said() {
for (pending, wanted) in [(false, "is set"), (true, "shep reload")] {
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, "autorestart");
let _ = app.update(Msg::Key(KeyPress::Cycle));
let Effect::Send(sent) = app.update(Msg::Key(KeyPress::Confirm)) else {
panic!("the confirm sends");
};
let effect = app.update(Msg::Replied {
sent,
result: Ok(Response::SheepFieldSet {
name: "web".to_owned(),
key: "autorestart".to_owned(),
pending,
}),
});
assert_eq!(
effect,
Effect::Send(Sent::SheepConfig {
name: "web".to_owned()
}),
"a landed write re-reads what the shepherd now holds"
);
assert!(app.config_pane().unwrap().pending_edit().is_none());
let notice = app.notice().expect("the outcome is reported");
assert!(!notice.is_grave(), "{notice:?}");
assert!(notice.to_string().contains(wanted), "{notice:?}");
}
}
/// Every refusal this door can meet is an `Err`, which is why
/// `Response::SheepFieldSet` carries no `refused` field: two ways to
/// say no is one a client forgets to check.
#[test]
fn a_refused_write_is_reported_and_does_not_re_read() {
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, "autorestart");
let _ = app.update(Msg::Key(KeyPress::Cycle));
let Effect::Send(sent) = app.update(Msg::Key(KeyPress::Confirm)) else {
panic!("the confirm sends");
};
let effect = app.update(Msg::Replied {
sent,
result: Err(RequestError::Rpc(shep_core::protocol::RpcError {
code: shep_core::protocol::RpcErrorCode::InvalidConfig,
message: "the store is locked by another shep".to_owned(),
daemon_version: None,
})),
});
assert_eq!(effect, Effect::None, "a refusal does not re-read");
assert!(app.config_pane().unwrap().pending_edit().is_none());
let notice = app.notice().expect("the refusal is reported");
assert!(notice.is_grave());
assert!(
notice.to_string().contains("the store is locked"),
"{notice:?}"
);
}
/// Asserted on the whole `Effect`, since that is what a diagnostic
/// would print. Nothing between here and the wire unwraps the value.
#[test]
fn a_write_effects_debug_names_no_value() {
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, "cwd");
let _ = app.update(Msg::Key(KeyPress::Confirm));
for _ in 0..40 {
let _ = app.update(Msg::Key(KeyPress::TextBackspace));
}
for typed in "/home/ada/secret-project".chars() {
let _ = app.update(Msg::Key(KeyPress::TextChar(typed)));
}
let _ = app.update(Msg::Key(KeyPress::TextApply));
let field = app.update(Msg::Key(KeyPress::Confirm));
assert_eq!(
format!("{field:?}"),
"Send(ApplyField { name: \"web\", ticket: 0, key: \"cwd\", \
value: FieldValue(<string>), authority: WriteAuthority(()) })"
);
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, "env");
let _ = app.update(Msg::Key(KeyPress::Confirm));
let _ = app.update(Msg::Key(KeyPress::Confirm));
for typed in "hunter2".chars() {
let _ = app.update(Msg::Key(KeyPress::TextChar(typed)));
}
let _ = app.update(Msg::Key(KeyPress::TextApply));
let env = app.update(Msg::Key(KeyPress::Confirm));
assert_eq!(
format!("{env:?}"),
"Send(SetEnv { name: \"web\", ticket: 0, key: \"DB_HOST\", \
value: Some(EnvValue(<7 bytes>)), authority: WriteAuthority(()) })"
);
}
/// A ticket is what closes it: the counter is monotonic and never
/// reused, so no two writes can be confused whatever field they name.
#[test]
fn two_writes_to_one_field_settle_on_their_own_replies() {
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, "autorestart");
let _ = app.update(Msg::Key(KeyPress::Cycle));
let Effect::Send(first) = app.update(Msg::Key(KeyPress::Confirm)) else {
panic!("the first confirm sends");
};
let _ = app.update(Msg::Key(KeyPress::Cycle));
let Effect::Send(second) = app.update(Msg::Key(KeyPress::Confirm)) else {
panic!("the second confirm sends");
};
assert_ne!(first, second, "two sends are two different tickets");
let _ = app.update(Msg::Replied {
sent: first,
result: Ok(Response::SheepFieldSet {
name: "web".to_owned(),
key: "autorestart".to_owned(),
pending: false,
}),
});
assert!(
matches!(
app.config_pane().unwrap().pending_edit(),
Some(PanePending::Sent { .. })
),
"the second write to the same field is still outstanding"
);
let _ = app.update(Msg::Replied {
sent: second,
result: Ok(Response::SheepFieldSet {
name: "web".to_owned(),
key: "autorestart".to_owned(),
pending: false,
}),
});
assert!(app.config_pane().unwrap().pending_edit().is_none());
}
/// The `Sent` half is reachable: two writes out, the first lands, and
/// its own re-read arrives while the second is still outstanding.
#[test]
fn a_refresh_keeps_an_armed_edit_and_an_outstanding_one() {
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, "autorestart");
let _ = app.update(Msg::Key(KeyPress::Cycle));
let armed = app.config_pane().unwrap().pending_edit().cloned();
assert!(matches!(armed, Some(PanePending::Armed { .. })));
refresh_config(&mut app, &[]);
assert_eq!(
app.config_pane().unwrap().pending_edit().cloned(),
armed,
"the question survives the rebuild, word for word"
);
let _ = app.update(Msg::Key(KeyPress::Confirm));
let sent = app.config_pane().unwrap().pending_edit().cloned();
assert!(matches!(sent, Some(PanePending::Sent { .. })));
refresh_config(&mut app, &[]);
assert_eq!(
app.config_pane().unwrap().pending_edit().cloned(),
sent,
"the in-flight line survives the landed write's own re-read"
);
}
/// A menu nobody answered is a question nobody is still looking at, and
/// `L` an hour later must not reload a sheep.
#[test]
fn the_apply_menu_expires_like_every_other_armed_thing() {
let mut app = fixtures::app_in_sheep_pane_with_control();
let _ = app.update(Msg::Key(KeyPress::Escape));
assert!(app.pane_menu().is_some(), "the menu opened");
let later = Instant::now() + CONFIRM_EXPIRY;
let _ = app.update(Msg::Tick { now: later });
assert!(app.pane_menu().is_none(), "it did not expire");
let effect = app.update(Msg::Key(KeyPress::Action(ActionVerb::Reload)));
assert_eq!(effect, Effect::None, "a stale L reloads nothing");
}
#[test]
fn the_apply_menu_refuses_on_a_dead_link_like_every_other_action() {
let mut app = fixtures::app_in_sheep_pane_with_control();
let _ = app.update(Msg::Retrying { attempt: 3 });
let _ = app.update(Msg::Key(KeyPress::Escape));
let effect = app.update(Msg::Key(KeyPress::Action(ActionVerb::Reload)));
assert_eq!(
effect,
Effect::None,
"nothing goes to a shepherd that is gone"
);
let said = app.notice().map(ToString::to_string).unwrap_or_default();
assert!(said.contains("attempt 3"), "{said}");
}
/// The pane-level test reaches `begin_typing` directly, so it passes
/// over a dead key path. This one presses the key.
#[test]
fn e_opens_the_editor_on_a_suggested_field() {
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, "kill_signal");
let _ = app.update(Msg::Key(KeyPress::Edit));
assert!(
matches!(
app.config_pane().and_then(ConfigPane::pending_edit),
Some(PanePending::Typing { .. })
),
"{:?}",
app.config_pane().and_then(ConfigPane::pending_edit)
);
}
#[test]
fn e_on_a_dog_row_opens_its_pane_instead_of_refusing() {
let mut app = fixtures::app_with_a_dog_selected_and_control();
let effect = app.update(Msg::Key(KeyPress::Edit));
let Effect::LoadDogPane { name, adopted_path } = effect else {
panic!("expected a dog pane, got {effect:?}");
};
assert_eq!(name, "otel");
// The path comes off the row, not the settings screen.
assert_eq!(adopted_path.as_deref(), Some(Path::new("/opt/otel")));
assert!(app.notice().is_none(), "{:?}", app.notice());
}
#[test]
fn e_on_a_built_in_dog_opens_a_pane_with_no_path() {
let mut app = fixtures::app_with_a_built_in_dog_selected_and_control();
let effect = app.update(Msg::Key(KeyPress::Edit));
let Effect::LoadDogPane { adopted_path, .. } = effect else {
panic!("expected a dog pane, got {effect:?}");
};
// A built-in dog is the shep binary's own argv branch, so there is no
// adopted path to probe and the pane asks the running binary instead.
assert_eq!(adopted_path, None);
}
/// `EngineStopped` is the one of this request's three refusals with no
/// subject of its own: `rpc_error` renders it as `the supervisor
/// engine has stopped`, full stop, naming neither the sheep nor the
/// screen it came from.
#[test]
fn a_refusal_that_names_nothing_still_reaches_the_operator_named() {
let mut app = fixtures::app_in_sheep_pane();
app.update(Msg::Replied {
sent: Sent::SheepConfig {
name: "web".to_string(),
},
result: Err(RequestError::Rpc(RpcError {
code: RpcErrorCode::Internal,
message: "the supervisor engine has stopped".to_string(),
daemon_version: None,
})),
});
let said = app.notice().map(ToString::to_string).unwrap_or_default();
assert_eq!(said, "web: the supervisor engine has stopped");
assert!(app.notice().unwrap().is_grave());
}
#[test]
fn a_config_reply_for_a_pane_nobody_wants_is_dropped() {
let mut app =
fixtures::with_selection(ProcessInfo::builder(9, "web", ProcStatus::Online).build());
let reply = || Msg::Replied {
sent: Sent::SheepConfig {
name: "web".to_string(),
},
result: Ok(Response::SheepConfig(Box::new(
fixtures::sheep_config_view(),
))),
};
app.update(Msg::Key(KeyPress::Edit));
app.update(Msg::Key(KeyPress::Edit));
app.update(reply());
assert!(app.config_pane().is_some(), "the first answer opens it");
app.update(Msg::Key(KeyPress::Escape));
assert!(app.config_pane().is_none());
app.update(reply());
assert!(
app.config_pane().is_none(),
"the second answer lands on a dashboard and is dropped"
);
assert!(app.notice().is_none(), "silently: nothing went wrong");
}
/// Closing must clear the target it is keyed on: left stale, it would
/// either re-open on a stray reply or refuse the next open.
#[test]
fn e_still_opens_a_pane_after_one_was_closed() {
let mut app = fixtures::app_in_sheep_pane();
app.update(Msg::Key(KeyPress::Escape));
app.update(Msg::Key(KeyPress::Edit));
app.update(Msg::Replied {
sent: Sent::SheepConfig {
name: "web".to_string(),
},
result: Ok(Response::SheepConfig(Box::new(
fixtures::sheep_config_view(),
))),
});
assert!(app.config_pane().is_some());
}
/// The path is what carries a probe to an adopted dog's own binary; a
/// built-in dog answers in-process and has none.
#[test]
fn e_on_a_settings_dog_row_probes_that_dogs_own_binary() {
let mut app = fixtures::app_in_settings_on_dog("otel");
assert_eq!(
app.update(Msg::Key(KeyPress::Edit)),
Effect::LoadDogPane {
name: "otel".to_string(),
adopted_path: Some(std::path::PathBuf::from("/usr/local/bin/shep-otel")),
}
);
assert!(
app.config_pane().is_none(),
"the pane opens on the answer, never on the keypress"
);
assert!(
app.settings().is_some(),
"and the screen stays up until it does"
);
}
/// Those rows are the settings screen's own subject, and `space` and
/// `Enter` already edit them.
#[test]
fn e_on_a_settings_scalar_row_does_nothing_at_all() {
let mut app = fixtures::app_in_settings();
assert_eq!(app.update(Msg::Key(KeyPress::Edit)), Effect::None);
assert!(app.config_pane().is_none());
assert!(app.notice().is_none(), "and says nothing about it");
}
#[test]
fn a_dog_with_no_schema_gets_no_pane_and_is_told_where_to_edit() {
let mut app = fixtures::app_in_settings_on_dog("otel");
app.update(Msg::Key(KeyPress::Edit));
assert_eq!(
app.update(Msg::DogPane {
name: "otel".to_string(),
adopted_path: None,
result: Err("otel publishes no schema; edit dogs.toml with $EDITOR".to_string()),
}),
Effect::None
);
assert!(app.config_pane().is_none());
assert!(
app.settings().is_some(),
"the screen the operator pressed `e` on is still there"
);
let notice = app.notice().expect("a refusal is reported").to_string();
assert!(notice.contains("dogs.toml"), "{notice}");
assert!(notice.contains("$EDITOR"), "{notice}");
}
/// The schema is the first of two halves. The pane cannot be drawn
/// until the shepherd answers with the section, the half this binary
/// has no copy of.
#[test]
fn a_schema_asks_for_the_section_and_the_section_opens_the_pane() {
let mut app = fixtures::app_in_settings_on_dog("metrics");
app.update(Msg::Key(KeyPress::Edit));
assert_eq!(
app.update(Msg::DogPane {
name: "metrics".to_string(),
adopted_path: None,
result: Ok(crate::dog::builtin_schema("metrics").expect("a built-in")),
}),
Effect::Send(Sent::DogSection {
name: "metrics".to_string()
})
);
assert!(app.config_pane().is_none(), "one half is not a pane");
app.update(Msg::Replied {
sent: Sent::DogSection {
name: "metrics".to_string(),
},
result: Ok(Response::DogSection {
toml: "bind = \"0.0.0.0:9615\"\n".to_string().into(),
}),
});
let pane = app.config_pane().expect("both halves are a pane");
assert_eq!(pane.target().name(), "metrics");
assert_eq!(pane.value("bind"), "0.0.0.0:9615");
assert!(
app.settings().is_none(),
"the settings screen closes once there is something to look at"
);
}
/// The same property `config_target` buys for a sheep.
#[test]
fn a_section_for_a_dog_nobody_is_waiting_for_is_dropped() {
let mut app = fixtures::app_in_dog_pane();
app.update(Msg::Key(KeyPress::Escape));
assert!(app.config_pane().is_none());
app.update(Msg::Replied {
sent: Sent::DogSection {
name: "bark".to_string(),
},
result: Ok(Response::DogSection {
toml: fixtures::dog_section().into(),
}),
});
assert!(app.config_pane().is_none(), "a late reply re-opens nothing");
}
/// Its twin above proves the pane drops once nobody is waiting; this
/// one proves the name is checked while somebody still is, the half a
/// cleared target cannot cover.
#[test]
fn a_section_for_a_different_dog_does_not_replace_the_pane() {
let mut app = fixtures::app_in_dog_pane();
app.update(Msg::Replied {
sent: Sent::DogSection {
name: "metrics".to_string(),
},
result: Ok(Response::DogSection {
toml: "bind = \"0.0.0.0:9615\"\n".to_string().into(),
}),
});
let pane = app.config_pane().expect("the bark pane is still open");
assert_eq!(pane.target().name(), "bark");
assert_eq!(
pane.value("poll"),
"60s",
"and still holds bark's own section"
);
}
/// A dog has no override store and no Flockfile, so `ApplyConfig` has
/// nothing to mean here: the write goes out through `SetDogConfig`
/// instead.
#[test]
fn a_dog_pane_write_carries_the_whole_edited_section() {
let mut app = fixtures::app_in_dog_pane();
let index = app
.config_pane()
.expect("the pane is open")
.fields()
.fields()
.iter()
.position(|field| field.key == "poll")
.expect("poll is a bark field");
app.update(Msg::Key(KeyPress::SelectFirst));
for _ in 0..index {
app.update(Msg::Key(KeyPress::SelectDown));
}
app.update(Msg::Key(KeyPress::Confirm));
for _ in 0..3 {
app.update(Msg::Key(KeyPress::TextBackspace));
}
for typed in "30s".chars() {
app.update(Msg::Key(KeyPress::TextChar(typed)));
}
app.update(Msg::Key(KeyPress::TextApply));
let Effect::Send(Sent::SetDogSection { name, toml, .. }) =
app.update(Msg::Key(KeyPress::Confirm))
else {
panic!("the confirm sends the section");
};
assert_eq!(name, "bark");
assert!(
toml.as_str().contains("poll = \"30s\""),
"{}",
toml.as_str()
);
assert!(
toml.as_str().contains("# how often"),
"a comment shep did not write survives: {}",
toml.as_str()
);
}
#[test]
fn a_landed_dog_write_re_reads_the_section_and_promises_nothing_more() {
let mut app = fixtures::app_in_dog_pane();
assert_eq!(
app.update(Msg::Replied {
sent: Sent::DogSection {
name: "bark".to_string(),
},
result: Ok(Response::DogConfigSet {
name: "bark".to_string()
}),
}),
Effect::None,
"a reply routed by its own request, and this one is not the write"
);
let Effect::Send(Sent::DogSection { name }) = app.update(Msg::Replied {
sent: Sent::SetDogSection {
name: "bark".to_string(),
ticket: 0,
toml: fixtures::dog_section().into(),
authority: WriteAuthority::granted(&app).expect("the fixture opens the gate"),
},
result: Ok(Response::DogConfigSet {
name: "bark".to_string(),
}),
}) else {
panic!("a landed write re-reads");
};
assert_eq!(name, "bark");
let notice = app
.notice()
.expect("a landed write is reported")
.to_string();
assert!(notice.contains("bark is told"), "{notice}");
}
/// The schema was read at open and is parked on the app: a keystroke
/// that re-reads a file must not respawn somebody else's process.
#[test]
fn r_in_a_dog_pane_re_reads_the_section_and_never_re_probes() {
let mut app = fixtures::app_in_dog_pane();
assert_eq!(
app.update(Msg::Key(KeyPress::Refresh)),
Effect::Send(Sent::DogSection {
name: "bark".to_string()
})
);
}
/// The env sub-screen writes through `Request::SetSheepEnv`, which
/// would name a sheep that does not exist. It refuses with
/// `Lock::NoWidget`'s own sentence instead.
#[test]
fn enter_on_a_dogs_map_field_refuses_rather_than_opening_the_env_screen() {
let mut app = fixtures::app_in_dog_pane();
let index = app
.config_pane()
.expect("the pane is open")
.fields()
.fields()
.iter()
.position(|field| field.key == "sinks")
.expect("sinks is a bark field");
app.update(Msg::Key(KeyPress::SelectFirst));
for _ in 0..index {
app.update(Msg::Key(KeyPress::SelectDown));
}
assert_eq!(app.update(Msg::Key(KeyPress::Confirm)), Effect::None);
assert!(
app.config_pane().expect("still open").env().is_none(),
"a dog has no env sub-screen"
);
let notice = app.notice().expect("a locked row answers").to_string();
assert!(notice.contains("no editor in this pane"), "{notice}");
}
/// Through `Msg::Key`, not `ConfigPane::open_list`: `confirm_field`
/// has its own gate listing which kinds `Enter` opens, and a test that
/// called the pane method would pass over it.
#[test]
fn enter_on_an_array_row_opens_the_list_sub_screen() {
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, "args");
let _ = app.update(Msg::Key(KeyPress::Confirm));
let list = app
.config_pane()
.expect("the pane is open")
.list()
.expect("enter on an array row opens the sub-screen");
assert_eq!(list.key(), "args");
assert_eq!(list.elements(), ["--port", "8080"]);
}
/// Every key the sub-screen's own hint names, driven the way an
/// operator drives them, and the array that lands on the wire at the
/// end of it.
#[test]
fn the_list_sub_screen_edits_removes_and_reorders_one_array() {
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, "args");
let _ = app.update(Msg::Key(KeyPress::Confirm));
let _ = app.update(Msg::Key(KeyPress::SelectDown));
let _ = app.update(Msg::Key(KeyPress::Edit));
assert_eq!(app.mode(), InputMode::Text, "e opens the element editor");
for _ in 0..4 {
let _ = app.update(Msg::Key(KeyPress::TextBackspace));
}
for typed in "9090".chars() {
let _ = app.update(Msg::Key(KeyPress::TextChar(typed)));
}
assert_eq!(
app.update(Msg::Key(KeyPress::TextApply)),
Effect::None,
"applying the editor arms; it does not send"
);
let request = wire(app.update(Msg::Key(KeyPress::Confirm)));
let Request::SetSheepField { key, value, .. } = request else {
panic!("expected SetSheepField, got {request:?}");
};
assert_eq!(key, "args");
assert_eq!(value, serde_json::json!(["--port", "9090"]));
let _ = app.update(Msg::Key(KeyPress::ListMoveUp));
assert_eq!(
armed_value(&app),
serde_json::json!(["8080", "--port"]),
"K moves the element under the cursor up one place"
);
let _ = app.update(Msg::Key(KeyPress::Escape));
let _ = app.update(Msg::Key(KeyPress::ListRemove));
assert_eq!(
armed_value(&app),
serde_json::json!(["--port"]),
"d drops the element under the cursor"
);
}
/// The candidate an armed edit holds.
fn armed_value(app: &App) -> serde_json::Value {
match app.config_pane().and_then(ConfigPane::pending_edit) {
Some(PanePending::Armed {
edit: PaneEdit::Set { value, .. },
..
}) => value.as_value().clone(),
other => panic!("expected an armed set, got {other:?}"),
}
}
/// `Escape` backs out of the sub-screen and leaves the pane up, the
/// same one-level-at-a-time rule the env screen follows.
#[test]
fn escape_leaves_the_list_sub_screen_before_it_closes_the_pane() {
let mut app = fixtures::app_in_sheep_pane_with_nothing_parked();
pane_to(&mut app, "args");
let _ = app.update(Msg::Key(KeyPress::Confirm));
let _ = app.update(Msg::Key(KeyPress::Escape));
assert!(app.config_pane().unwrap().list().is_none());
assert!(app.config_pane().is_some(), "the pane is still open");
let _ = app.update(Msg::Key(KeyPress::Escape));
assert!(app.config_pane().is_none());
}
/// A write re-reads the whole config, so without the carry the
/// sub-screen would shut on the operator's own keystroke.
#[test]
fn the_list_sub_screen_survives_the_refresh_a_write_triggers() {
let mut app = fixtures::app_in_sheep_pane_with_control();
pane_to(&mut app, "args");
let _ = app.update(Msg::Key(KeyPress::Confirm));
let _ = app.update(Msg::Key(KeyPress::SelectLast));
refresh_config(&mut app, &[]);
let list = app
.config_pane()
.expect("the pane is open")
.list()
.expect("the sub-screen rides across the refresh");
assert_eq!(list.key(), "args");
assert_eq!(
list.cursor(),
Some(ListRow::New),
"a cursor past the end lands on the row where enter destroys nothing"
);
}
}