dockdoe 0.12.0

A single-binary Docker host monitor with an embedded web UI
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
//! Web layer: axum router, embedded assets, SSE streaming, and HTML rendering.
//!
//! Pages are rendered server-side with maud and kept live without a full reload
//! over a *single* SSE connection per page (`live.js`). That one stream polls
//! the shared snapshot — the same source a plain page render reads, so the live
//! view can't drift from a reload — and emits named events the client swaps in:
//! `header` (host header), `containers` (dashboard / stack member table),
//! `detail` (a container page's state + facts), and `metrics` (a JSON point for
//! the uPlot charts, seeded from the store on first load). One connection per
//! page keeps us under the browser's per-host HTTP/1.1 connection limit.

use std::collections::{BTreeMap, HashMap};
use std::convert::Infallible;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
use axum::extract::{Query, Request, State};
use axum::http::{HeaderMap, StatusCode, header};
use axum::middleware::{self, Next};
use axum::response::sse::{Event, KeepAlive, Sse};
use axum::response::{IntoResponse, Redirect, Response};
use axum::routing::get;
use axum::{Form, Json, Router};
use futures_util::{SinkExt, Stream, StreamExt};
use maud::{DOCTYPE, Markup, html};
use rust_embed::RustEmbed;
use tokio::io::AsyncWriteExt;

use crate::auth::{self, Auth};
use crate::collector::SharedDashboard;
use crate::config::OverviewConfig;
use crate::docker::{Action, DockerHandle, ExecSession, is_forbidden};
use crate::federation::NodeClient;
use crate::model::{
    ContainerMetrics, ContainerState, Dashboard, HealthState, HostEntry, Port, Snapshot,
};
use crate::store::{MetricPoint, Store};

/// How often the live SSE streams poll the latest snapshot.
const SNAPSHOT_POLL: Duration = Duration::from_secs(1);

/// Shared state for the web layer.
#[derive(Clone)]
pub struct AppState {
    /// The monitored Docker hosts, keyed by their config `name` (the URL slug).
    pub hosts: Arc<HashMap<String, HostRuntime>>,
    /// Host names in config order — drives the index page and host switcher.
    pub host_order: Arc<[String]>,
    /// Store, for seeding charts with recent history.
    pub store: Store,
    /// How far back to seed charts on first load.
    pub seed_window: Duration,
    /// Hostnames the UI may be addressed as (normalized: lowercase, no port).
    /// Empty disables the Host check; localhost forms are always allowed.
    pub allowed_hosts: Arc<[String]>,
    /// Login credentials and session signing. `None` leaves the UI open.
    pub auth: Option<Auth>,
    /// Shared-secret bearer token for machine clients (a federation hub).
    /// `None` disables token access.
    pub api_token: Option<auth::ApiToken>,
    /// Scales and cap of the dashboard overview discs.
    pub overview: OverviewConfig,
}

/// Everything the web layer needs for one monitored host.
#[derive(Clone)]
pub struct HostRuntime {
    /// The latest snapshot for this host — single source of truth for both the
    /// initial render and the live SSE streams.
    pub shared: SharedDashboard,
    /// Where this host's data and actions come from.
    pub source: HostSource,
    /// How this host's published-port pills link out.
    pub links: PortLinks,
    /// Set once a lifecycle/exec call returns `403 Forbidden` — the socket proxy
    /// is read-only. The UI then disables this host's action buttons and
    /// terminal. Latches on; cleared only by a restart. For a federated host
    /// this mirrors what the node reports instead.
    pub read_only: Arc<AtomicBool>,
}

/// Where a host's data and actions come from: a Docker endpoint we talk to
/// directly, or a federated DockDoe node reached over its JSON API.
#[derive(Clone)]
pub enum HostSource {
    Docker(DockerHandle),
    Node(NodeClient),
}

impl HostRuntime {
    fn is_read_only(&self) -> bool {
        self.read_only.load(Ordering::Relaxed)
    }
}

/// How published-port pills link out, resolved per host from `public_host` and
/// the endpoint URL.
#[derive(Debug, Clone)]
pub enum PortLinks {
    /// The pill carries `data-port` and a `localhost` fallback href, which
    /// live.js rewrites to whatever host the browser is pointed at. The right
    /// default for the local host browsed directly on the Docker machine.
    Browser,
    /// A fixed host (IP or name) the published ports are reachable at — a remote
    /// host's address, or an override when the browsing host isn't where the
    /// ports live.
    Host(String),
    /// Render ports as plain, unlinked pills — for setups reachable only through
    /// a proxy, where no direct `host:port` link works from the browser.
    Off,
}

impl PortLinks {
    /// Resolve the port-link mode for a host: an explicit `public_host` wins
    /// (`off`/`none`/`-` → no links, otherwise a fixed host); failing that, the
    /// host parsed from a `tcp`/`http`/`https` endpoint URL; failing that (a unix
    /// socket — the local host), the browsing host.
    #[must_use]
    pub fn from_config(public_host: Option<&str>, docker_url: &str) -> Self {
        if let Some(s) = public_host.map(str::trim).filter(|s| !s.is_empty()) {
            return if s.eq_ignore_ascii_case("off") || s.eq_ignore_ascii_case("none") || s == "-" {
                PortLinks::Off
            } else {
                PortLinks::Host(s.to_string())
            };
        }
        endpoint_host(docker_url).map_or(PortLinks::Browser, PortLinks::Host)
    }
}

/// The host part of a `tcp`/`http`/`https` Docker endpoint URL (for deriving the
/// default port-link host). `None` for a unix socket or a bare path.
fn endpoint_host(url: &str) -> Option<String> {
    let rest = ["tcp://", "http://", "https://"]
        .iter()
        .find_map(|scheme| url.strip_prefix(scheme))?;
    // IPv6 literal: keep everything inside the brackets.
    if let Some(after) = rest.strip_prefix('[') {
        return after.split(']').next().map(str::to_string);
    }
    let host = rest.split(['/', ':']).next().unwrap_or("");
    (!host.is_empty()).then(|| host.to_string())
}

/// Per-request render context: which host's pages we're building, and how its
/// published-port pills link out. Threaded through the `maud` helpers so every
/// in-page link is host-scoped (`/host/{host}/…`).
struct Render<'a> {
    host: &'a str,
    links: &'a PortLinks,
    /// Whether this host is read-only (action buttons + terminal disabled).
    read_only: bool,
}

#[derive(RustEmbed)]
#[folder = "assets/"]
struct Assets;

/// Build the application router.
pub fn router(state: AppState) -> Router {
    Router::new()
        .route("/", get(host_index))
        .route("/host/{host}", get(dashboard))
        .route("/host/{host}/container/{id}", get(container_detail))
        .route("/host/{host}/stack/{name}", get(stack_detail))
        .route("/host/{host}/events", get(events_dashboard))
        .route("/host/{host}/events/container/{id}", get(events_container))
        .route("/host/{host}/events/stack/{name}", get(events_stack))
        .route("/host/{host}/api/container/{id}/logs", get(container_logs))
        .route("/host/{host}/api/stack/{name}/compose", get(stack_compose))
        .route(
            "/host/{host}/api/metrics/container/{id}",
            get(metrics_container),
        )
        .route("/host/{host}/api/metrics/stack/{name}", get(metrics_stack))
        .route(
            "/host/{host}/api/history/container/{id}",
            get(history_container),
        )
        .route("/host/{host}/api/history/stack/{name}", get(history_stack))
        .route("/api/hosts", get(api_hosts))
        .route("/host/{host}/api/snapshot", get(api_snapshot))
        .route("/host/{host}/api/events", get(api_events))
        .route(
            "/host/{host}/api/container/{id}/{action}",
            axum::routing::post(container_action).layer(middleware::from_fn(require_htmx)),
        )
        .route(
            "/host/{host}/api/stack/{name}/{action}",
            axum::routing::post(stack_action).layer(middleware::from_fn(require_htmx)),
        )
        .route("/login", get(login_page).post(login_submit))
        .route("/logout", axum::routing::post(logout))
        .route("/host/{host}/ws/container/{id}/exec", get(ws_exec))
        .route("/assets/{*path}", get(asset))
        // Auth wraps everything (it allowlists /login and /assets internally);
        // the host check sits outside it so rejected hosts never reach auth.
        .layer(middleware::from_fn_with_state(state.clone(), require_auth))
        .layer(middleware::from_fn_with_state(state.clone(), check_host))
        .with_state(state)
}

/// Gate every request on a valid session when authentication is configured.
/// The login page and static assets stay public (the login page needs its CSS
/// and icon); everything else needs a valid session cookie. Unauthenticated
/// requests get an `HX-Redirect` (for htmx) or a 303 to `/login`.
async fn require_auth(State(state): State<AppState>, mut req: Request, next: Next) -> Response {
    // Machine clients (the federation hub) authenticate per request with a
    // bearer token instead of a login session. Checked before the cookie path
    // so it also works when interactive auth is off, and only when a token is
    // configured — otherwise `Authorization` headers (say, forwarded by an
    // auth proxy) keep being ignored as before. A presented-but-wrong token is
    // rejected outright: bouncing an API client to the login page helps nobody.
    if let Some(expected) = state.api_token.as_ref()
        && let Some(presented) = bearer_token(req.headers())
    {
        if expected.matches(presented) {
            req.extensions_mut().insert(BearerAuthed);
            return next.run(req).await;
        }
        return (StatusCode::UNAUTHORIZED, "invalid API token").into_response();
    }
    let Some(auth) = state.auth.as_ref() else {
        return next.run(req).await; // authentication disabled
    };
    // /logout deliberately requires a session: combined with SameSite=Lax
    // (which withholds the cookie on cross-site POSTs), a page elsewhere
    // can't log the user out — its POST arrives unauthenticated and bounces
    // to /login without touching the victim's cookie.
    let path = req.uri().path();
    if path == "/login" || path.starts_with("/assets/") {
        return next.run(req).await;
    }
    if request_is_authenticated(auth, req.headers()) {
        return next.run(req).await;
    }
    // htmx follows HX-Redirect with a client-side navigation; a plain browser
    // request gets a normal redirect to the login page.
    if is_htmx_request(req.headers()) {
        return (StatusCode::UNAUTHORIZED, [("HX-Redirect", "/login")]).into_response();
    }
    Redirect::to("/login").into_response()
}

/// Request-extension marker: this request was authenticated by the API token.
/// The CSRF guard keys off it — a bearer header is attached deliberately by
/// the client, never automatically by a browser, so CSRF doesn't apply.
#[derive(Clone, Copy)]
struct BearerAuthed;

/// The token of an `Authorization: Bearer <token>` header, if present.
fn bearer_token(headers: &HeaderMap) -> Option<&str> {
    headers
        .get(header::AUTHORIZATION)?
        .to_str()
        .ok()?
        .strip_prefix("Bearer ")
}

/// Whether the request carries a valid session cookie for `auth`.
fn request_is_authenticated(auth: &Auth, headers: &HeaderMap) -> bool {
    headers
        .get(header::COOKIE)
        .and_then(|v| v.to_str().ok())
        .and_then(|cookies| auth::cookie_value(cookies, auth::COOKIE_NAME))
        .is_some_and(|token| auth.token_valid(token, now_unix_secs()))
}

/// CSRF guard for the state-changing POST endpoints: require the
/// `HX-Request: true` header htmx adds to every request it issues. A cross-site
/// HTML form can't set custom headers, and setting one from a script makes the
/// request preflight-checked — which fails, since we never answer CORS
/// preflights. Same-origin htmx buttons are unaffected. Bearer-authenticated
/// requests (see [`BearerAuthed`]) are exempt.
async fn require_htmx(req: Request, next: Next) -> Response {
    if req.extensions().get::<BearerAuthed>().is_some() || is_htmx_request(req.headers()) {
        next.run(req).await
    } else {
        (
            StatusCode::FORBIDDEN,
            "rejected: not an htmx request (missing HX-Request header)",
        )
            .into_response()
    }
}

fn is_htmx_request(headers: &HeaderMap) -> bool {
    headers
        .get("hx-request")
        .is_some_and(|v| v.as_bytes() == b"true")
}

/// Host-header allowlist, a guard against DNS rebinding (where the attacker's
/// page *is* same-origin, so the htmx-header check above can't help). Active
/// only when hosts are configured; localhost forms always pass so local access
/// keeps working alongside a configured LAN hostname.
async fn check_host(State(state): State<AppState>, req: Request, next: Next) -> Response {
    if host_allowed(req.headers(), &state.allowed_hosts) {
        next.run(req).await
    } else {
        (StatusCode::FORBIDDEN, "rejected: Host not allowed").into_response()
    }
}

fn host_allowed(headers: &HeaderMap, allowed: &[String]) -> bool {
    if allowed.is_empty() {
        return true;
    }
    let Some(host) = headers.get(header::HOST).and_then(|v| v.to_str().ok()) else {
        return false;
    };
    let host = host_without_port(host.trim()).to_ascii_lowercase();
    matches!(host.as_str(), "localhost" | "127.0.0.1" | "::1") || allowed.contains(&host)
}

/// The hostname part of a `Host` header value: strips a `:port` suffix and the
/// brackets of an IPv6 literal (`[::1]:8080` → `::1`).
fn host_without_port(host: &str) -> &str {
    if let Some(rest) = host.strip_prefix('[') {
        rest.split(']').next().unwrap_or(rest)
    } else {
        host.rsplit_once(':').map_or(host, |(h, _)| h)
    }
}

/// Normalize the configured Host allowlist for [`AppState::allowed_hosts`]:
/// trim, drop empties, lowercase, strip ports/brackets.
pub fn normalize_allowed_hosts(hosts: &[String]) -> Arc<[String]> {
    hosts
        .iter()
        .map(|h| host_without_port(h.trim()).to_ascii_lowercase())
        .filter(|h| !h.is_empty())
        .collect()
}

/// Apply a start/stop/restart action to a container, then return the freshly
/// rendered action-button group so HTMX can swap it in place.
async fn container_action(
    State(state): State<AppState>,
    axum::extract::Path((host, id, action)): axum::extract::Path<(String, String, String)>,
) -> Response {
    let rt = match host_rt(&state, &host) {
        Ok(rt) => rt,
        Err(resp) => return resp,
    };
    let Some(parsed) = Action::parse(&action) else {
        return (StatusCode::BAD_REQUEST, "unknown action").into_response();
    };
    let docker = match &rt.source {
        HostSource::Docker(docker) => docker,
        HostSource::Node(node) => {
            // The node applies the action; the hub renders its own buttons —
            // the node's fragment would carry *its* host-scoped URLs.
            return match node
                .forward_action(&format!("/api/container/{id}/{action}"))
                .await
            {
                Ok((status, _)) if status.is_success() => {
                    tracing::info!(%host, %id, %action, "applied container action on node");
                    action_buttons(&host, &id, rt.is_read_only()).into_response()
                }
                Ok((StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN, _)) => {
                    mark_read_only(rt, &host);
                    action_buttons(&host, &id, true).into_response()
                }
                Ok((status, body)) => {
                    tracing::warn!(%host, %id, %action, %status, "node rejected container action");
                    (StatusCode::BAD_GATEWAY, body).into_response()
                }
                Err(err) => {
                    tracing::warn!(%host, %id, %action, error = %format!("{err:#}"), "forwarding action failed");
                    (StatusCode::BAD_GATEWAY, "node unreachable").into_response()
                }
            };
        }
    };
    match docker.apply(&id, parsed).await {
        Ok(()) => {
            tracing::info!(%host, %id, ?action, "applied container action");
            // The next collector cycle refreshes state; echo the buttons back.
            action_buttons(&host, &id, rt.is_read_only()).into_response()
        }
        Err(err) if is_forbidden(&err) => {
            mark_read_only(rt, &host);
            // Swap in disabled buttons so the UI reflects the read-only host.
            action_buttons(&host, &id, true).into_response()
        }
        Err(err) => {
            tracing::warn!(%host, %id, ?action, %err, "container action failed");
            (StatusCode::BAD_GATEWAY, format!("action failed: {err}")).into_response()
        }
    }
}

/// Forward a GET to the federated node's endpoint of the same shape and relay
/// status, content type and body. The node's data endpoints answer exactly
/// what the hub's own would (JSON points, HTML log/compose fragments), so
/// nothing needs re-rendering — except host-scoped URLs, which these payloads
/// deliberately don't contain.
async fn proxy_get(node: &NodeClient, api_path: &str, query: Option<&str>) -> Response {
    match node.forward_get(api_path, query).await {
        Ok(resp) => {
            let status = resp.status();
            let content_type = resp
                .headers()
                .get(header::CONTENT_TYPE)
                .and_then(|v| v.to_str().ok())
                .unwrap_or("text/plain; charset=utf-8")
                .to_string();
            match resp.bytes().await {
                Ok(body) => (status, [(header::CONTENT_TYPE, content_type)], body).into_response(),
                Err(err) => {
                    tracing::warn!(%err, api_path, "reading node response failed");
                    (StatusCode::BAD_GATEWAY, "node response failed").into_response()
                }
            }
        }
        Err(err) => {
            tracing::warn!(error = %format!("{err:#}"), api_path, "forwarding to node failed");
            (
                StatusCode::BAD_GATEWAY,
                format!("node unreachable: {err:#}"),
            )
                .into_response()
        }
    }
}

/// Latch a host into read-only after it returned `403 Forbidden` (a socket
/// proxy denying POST/exec). Logged once per flip.
fn mark_read_only(rt: &HostRuntime, host: &str) {
    if !rt.read_only.swap(true, Ordering::Relaxed) {
        tracing::warn!(%host, "host is read-only (proxy returned 403); disabling actions");
    }
}

/// Apply an action to every container in a stack, then echo the stack's action
/// buttons back for HTMX to swap.
async fn stack_action(
    State(state): State<AppState>,
    axum::extract::Path((host, name, action)): axum::extract::Path<(String, String, String)>,
) -> Response {
    let rt = match host_rt(&state, &host) {
        Ok(rt) => rt,
        Err(resp) => return resp,
    };
    let Some(parsed) = Action::parse(&action) else {
        return (StatusCode::BAD_REQUEST, "unknown action").into_response();
    };

    let docker = match &rt.source {
        HostSource::Docker(docker) => docker,
        HostSource::Node(node) => {
            // The node orchestrates its own stack; the hub only relays the
            // outcome and renders its own buttons (host-scoped URLs).
            return match node
                .forward_action(&format!("/api/stack/{name}/{action}"))
                .await
            {
                Ok((status, _)) if status.is_success() => {
                    tracing::info!(%host, stack = %name, %action, "applied stack action on node");
                    stack_action_buttons(&host, &name, rt.is_read_only()).into_response()
                }
                Ok((StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN, _)) => {
                    mark_read_only(rt, &host);
                    stack_action_buttons(&host, &name, true).into_response()
                }
                Ok((status, body)) => {
                    tracing::warn!(%host, stack = %name, %action, %status, "node rejected stack action");
                    (StatusCode::BAD_GATEWAY, body).into_response()
                }
                Err(err) => {
                    tracing::warn!(%host, stack = %name, %action, error = %format!("{err:#}"), "forwarding stack action failed");
                    (StatusCode::BAD_GATEWAY, "node unreachable").into_response()
                }
            };
        }
    };
    // Orchestrate dependency-aware: the docker layer reads the compose
    // depends_on labels and starts/stops members in the right order.
    match docker.stack_action(&name, parsed).await {
        Ok(outcome) => {
            tracing::info!(
                %host, stack = %name, ?action,
                total = outcome.total, failed = outcome.failed,
                "applied stack action"
            );
        }
        Err(err) if is_forbidden(&err) => {
            mark_read_only(rt, &host);
            return stack_action_buttons(&host, &name, true).into_response();
        }
        Err(err) => {
            tracing::warn!(%host, stack = %name, ?action, %err, "stack action failed");
            return (
                StatusCode::BAD_GATEWAY,
                format!("stack action failed: {err}"),
            )
                .into_response();
        }
    }
    stack_action_buttons(&host, &name, rt.is_read_only()).into_response()
}

/// Look up a host's runtime by its slug, or a 404 response if there's no such
/// configured host.
// The `Err` is a ready-to-return `Response`, which is a large type — that's the
// point here (callers `return` it directly), not a value to shrink.
#[allow(clippy::result_large_err, reason = "Err is a ready Response to return")]
fn host_rt<'a>(state: &'a AppState, host: &str) -> Result<&'a HostRuntime, Response> {
    state
        .hosts
        .get(host)
        .ok_or_else(|| (StatusCode::NOT_FOUND, "unknown host").into_response())
}

/// This build's version, stamped into federation payloads so a hub can detect
/// version skew against its nodes.
const VERSION: &str = env!("CARGO_PKG_VERSION");

/// `GET /api/hosts` — the monitored hosts, for a federation hub to pick one
/// and detect version skew.
async fn api_hosts(State(state): State<AppState>) -> Json<Vec<HostEntry>> {
    Json(
        state
            .host_order
            .iter()
            .map(|name| HostEntry {
                name: name.clone(),
                version: VERSION.to_string(),
            })
            .collect(),
    )
}

/// `GET /host/{host}/api/snapshot` — one host's current dashboard as JSON,
/// for a federation hub. 503 until the first collector cycle has published.
async fn api_snapshot(
    State(state): State<AppState>,
    axum::extract::Path(host): axum::extract::Path<String>,
) -> Response {
    let rt = match host_rt(&state, &host) {
        Ok(rt) => rt,
        Err(resp) => return resp,
    };
    let Some(dashboard) = current_snapshot(rt) else {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            "no snapshot yet (warming up)",
        )
            .into_response();
    };
    Json(Snapshot {
        version: VERSION.to_string(),
        read_only: rt.is_read_only(),
        dashboard,
    })
    .into_response()
}

/// `GET /host/{host}/api/events` — the snapshot as a JSON SSE stream, for a
/// federation hub: a `snapshot` event with the same payload as
/// [`api_snapshot`], pushed the moment a fresh snapshot lands. Spares the hub
/// polling and keeps a federated host as live as a local one.
async fn api_events(
    State(state): State<AppState>,
    axum::extract::Path(host): axum::extract::Path<String>,
) -> Response {
    let Some(rt) = state.hosts.get(&host) else {
        return (StatusCode::NOT_FOUND, "unknown host").into_response();
    };
    let read_only = Arc::clone(&rt.read_only);
    let stream = dashboard_stream(rt.shared.clone()).map(move |dash| {
        Event::default().event("snapshot").json_data(Snapshot {
            version: VERSION.to_string(),
            read_only: read_only.load(Ordering::Relaxed),
            dashboard: (*dash).clone(),
        })
    });
    Sse::new(stream)
        .keep_alive(KeepAlive::default())
        .into_response()
}

/// The landing page at `/`. With a single host it redirects straight to that
/// host; with several it shows a chooser.
async fn host_index(State(state): State<AppState>) -> Response {
    if let [only] = state.host_order.as_ref() {
        return Redirect::to(&format!("/host/{only}")).into_response();
    }
    host_index_page(&state.host_order, state.auth.is_some()).into_response()
}

/// The current snapshot for one host, cloned out of its shared lock.
fn current_snapshot(rt: &HostRuntime) -> Option<Dashboard> {
    rt.shared.read().ok().and_then(|guard| guard.clone())
}

/// Number of log lines to tail for the logs panel.
const LOG_TAIL_LINES: u32 = 200;

/// Return the tail of a container's logs as an HTML fragment for the logs panel.
async fn container_logs(
    State(state): State<AppState>,
    axum::extract::Path((host, id)): axum::extract::Path<(String, String)>,
) -> Response {
    let Some(rt) = state.hosts.get(&host) else {
        return html! { span.muted { "Unknown host." } }.into_response();
    };
    let docker = match &rt.source {
        HostSource::Docker(docker) => docker,
        // The node renders the same fragment (log spans carry no host-scoped
        // URLs), so it can be relayed as-is.
        HostSource::Node(node) => {
            return proxy_get(node, &format!("/api/container/{id}/logs"), None).await;
        }
    };
    match docker.logs_tail(&id, LOG_TAIL_LINES).await {
        Ok(text) if text.trim().is_empty() => html! { span.muted { "(no logs)" } }.into_response(),
        Ok(text) => render_log_lines(&strip_ansi(&text)).into_response(),
        Err(err) => {
            tracing::warn!(%host, %id, %err, "fetching logs failed");
            html! { span.muted { "Could not read logs: " (err) } }.into_response()
        }
    }
}

/// Render log lines with their daemon timestamp prefix as a styled span.
/// `data-ts` carries the timestamp truncated to seconds (plain RFC 3339, no
/// fractional part) so the browser can re-render it in local time; the span
/// text is a UTC fallback for the brief moment before that happens.
fn render_log_lines(text: &str) -> Markup {
    html! {
        @for line in text.lines() {
            @if let Some((ts, msg)) = split_log_timestamp(line) {
                span.log-ts data-ts=(format!("{}Z", &ts[..19])) {
                    (ts[..19].replacen('T', " ", 1))
                } " " (msg) "\n"
            } @else {
                (line) "\n"
            }
        }
    }
}

/// Split a daemon-timestamped log line (`2026-06-12T10:15:30.123456789Z msg`)
/// into timestamp and message. Returns `None` when the line doesn't carry the
/// expected prefix (e.g. logs from a driver without timestamp support).
fn split_log_timestamp(line: &str) -> Option<(&str, &str)> {
    let (ts, msg) = line.split_once(' ')?;
    let b = ts.as_bytes();
    if b.len() < 20 || !ts.ends_with('Z') {
        return None;
    }
    // "YYYY-MM-DDTHH:MM:SS" — digits with fixed separators. Checking every
    // byte also guarantees the `ts[..19]` slice above lands on a char boundary.
    let pattern_ok = b[..19].iter().enumerate().all(|(i, c)| match i {
        4 | 7 => *c == b'-',
        10 => *c == b'T',
        13 | 16 => *c == b':',
        _ => c.is_ascii_digit(),
    });
    pattern_ok.then_some((ts, msg))
}

/// Return a stack's compose file(s) as an HTML fragment for the compose panel.
async fn stack_compose(
    State(state): State<AppState>,
    axum::extract::Path((host, name)): axum::extract::Path<(String, String)>,
) -> Response {
    let Some(rt) = state.hosts.get(&host) else {
        return html! { span.muted { "Unknown host." } }.into_response();
    };
    let docker = match &rt.source {
        HostSource::Docker(docker) => docker,
        // The node reads the file from *its* filesystem — exactly the point:
        // the hub needs no mounts for remote stacks.
        HostSource::Node(node) => {
            return proxy_get(node, &format!("/api/stack/{name}/compose"), None).await;
        }
    };
    let paths = match docker.compose_config_files(&name).await {
        Ok(paths) => paths,
        Err(err) => {
            tracing::warn!(%host, stack = %name, %err, "resolving compose files failed");
            return html! { span.muted { "Could not determine compose file: " (err) } }
                .into_response();
        }
    };
    if paths.is_empty() {
        return html! { span.muted { "No compose file recorded for this stack." } }.into_response();
    }

    let files = tokio::task::spawn_blocking(move || read_compose_files(&paths))
        .await
        .unwrap_or_default();
    html! {
        @for (path, body) in &files {
            div.compose-file {
                div.compose-path { (path) }
                pre.logs { (body) }
            }
        }
    }
    .into_response()
}

/// Read each compose file from the host filesystem. Guarded to YAML paths so a
/// crafted container label can't make us read arbitrary files. Returns
/// `(path, contents-or-message)` pairs.
fn read_compose_files(paths: &[String]) -> Vec<(String, String)> {
    paths
        .iter()
        .map(|p| {
            let is_yaml = std::path::Path::new(p)
                .extension()
                .is_some_and(|e| e.eq_ignore_ascii_case("yml") || e.eq_ignore_ascii_case("yaml"));
            let body = if is_yaml {
                std::fs::read_to_string(p).unwrap_or_else(|e| format!("(could not read: {e})"))
            } else {
                "(refusing to read a non-YAML path)".to_string()
            };
            (p.clone(), body)
        })
        .collect()
}

/// Strip ANSI/VT escape sequences (CSI `ESC [ … final-byte`) so logs render
/// cleanly in a `<pre>` instead of showing raw escape codes.
fn strip_ansi(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    let mut chars = input.chars();
    while let Some(c) = chars.next() {
        if c == '\u{1b}' {
            // Skip the introducer and everything up to the final byte (@-~).
            if chars.next() == Some('[') {
                for seq in chars.by_ref() {
                    if ('\u{40}'..='\u{7e}').contains(&seq) {
                        break;
                    }
                }
            }
        } else {
            out.push(c);
        }
    }
    out
}

/// Serve an embedded static asset.
async fn asset(axum::extract::Path(path): axum::extract::Path<String>) -> Response {
    match Assets::get(&path) {
        Some(file) => {
            let mime = mime_for(&path);
            ([(header::CONTENT_TYPE, mime)], file.data.into_owned()).into_response()
        }
        None => (StatusCode::NOT_FOUND, "not found").into_response(),
    }
}

fn mime_for(path: &str) -> &'static str {
    match path.rsplit('.').next() {
        Some("css") => "text/css; charset=utf-8",
        Some("js") => "text/javascript; charset=utf-8",
        Some("svg") => "image/svg+xml",
        _ => "application/octet-stream",
    }
}

/// Submitted login form.
#[derive(serde::Deserialize)]
struct LoginForm {
    username: String,
    password: String,
}

/// The login page. With auth off there is nothing to log in to, so send callers
/// home; with a valid session already present, likewise.
async fn login_page(State(state): State<AppState>, req: Request) -> Response {
    match state.auth.as_ref() {
        None => Redirect::to("/").into_response(),
        Some(auth) if request_is_authenticated(auth, req.headers()) => {
            Redirect::to("/").into_response()
        }
        Some(_) => login_shell(false).into_response(),
    }
}

/// Verify submitted credentials; on success set the session cookie and send the
/// user to the dashboard, otherwise re-render the form with an error.
async fn login_submit(State(state): State<AppState>, Form(form): Form<LoginForm>) -> Response {
    let Some(auth) = state.auth.as_ref() else {
        return Redirect::to("/").into_response();
    };
    if auth.credentials_valid(&form.username, &form.password) {
        let cookie = auth.issue_cookie(now_unix_secs());
        let mut resp = Redirect::to("/").into_response();
        if let Ok(value) = cookie.parse() {
            resp.headers_mut().insert(header::SET_COOKIE, value);
        }
        resp
    } else {
        // Fixed delay on failure: the comparison itself is constant-time, but
        // attempts were unlimited and instant. Half a second caps brute force
        // at ~2 guesses/s per connection without any rate-limit state to keep;
        // being async, it doesn't tie up a worker thread.
        tokio::time::sleep(Duration::from_millis(500)).await;
        (StatusCode::UNAUTHORIZED, login_shell(true)).into_response()
    }
}

/// Query for the exec WebSocket: the command to run (defaults to `/bin/sh`).
#[derive(serde::Deserialize)]
struct ExecQuery {
    cmd: Option<String>,
}

/// A terminal resize message from the client.
#[derive(serde::Deserialize)]
struct ResizeMsg {
    cols: u16,
    rows: u16,
}

/// WebSocket endpoint backing the container terminal. Authentication (when on)
/// is already enforced by the middleware on the upgrade request, which carries
/// the session cookie. Binary frames are stdin, text frames are resize JSON.
async fn ws_exec(
    State(state): State<AppState>,
    axum::extract::Path((host, id)): axum::extract::Path<(String, String)>,
    Query(q): Query<ExecQuery>,
    ws: WebSocketUpgrade,
) -> Response {
    let Some(rt) = state.hosts.get(&host) else {
        return (StatusCode::NOT_FOUND, "unknown host").into_response();
    };
    let cmd = q.cmd.unwrap_or_default();
    let read_only = Arc::clone(&rt.read_only);
    match &rt.source {
        HostSource::Docker(docker) => {
            let docker = docker.clone();
            ws.on_upgrade(move |socket| exec_bridge(socket, docker, host, id, cmd, read_only))
        }
        HostSource::Node(node) => {
            let node = node.clone();
            ws.on_upgrade(move |socket| {
                federated_exec_bridge(socket, node, host, id, cmd, read_only)
            })
        }
    }
}

/// Bridge the browser's terminal WebSocket to the node's exec WebSocket. The
/// hub dials the node itself (it can attach the bearer token; a browser
/// can't) and then just relays frames: stdin/stdout stay binary, the resize
/// JSON stays text — the same protocol on both legs, nothing to translate.
async fn federated_exec_bridge(
    mut socket: WebSocket,
    node: NodeClient,
    host: String,
    id: String,
    cmd: String,
    read_only: Arc<AtomicBool>,
) {
    use tokio_tungstenite::tungstenite::Message as NodeMessage;

    let upstream = match node.exec_socket(&id, &cmd).await {
        Ok(upstream) => upstream,
        Err(err) => {
            // The node denying the upgrade latches read-only, mirroring a
            // socket proxy denying exec.
            if crate::federation::ws_denied(&err) && !read_only.swap(true, Ordering::Relaxed) {
                tracing::warn!(%host, "node denied exec; marking host read-only");
            }
            tracing::warn!(%host, %id, error = %format!("{err:#}"), "opening node terminal failed");
            let msg =
                format!("\r\n\x1b[31mfailed to reach the node's terminal: {err:#}\x1b[0m\r\n");
            let _ = socket.send(Message::Text(msg.into())).await;
            let _ = socket.close().await;
            return;
        }
    };
    let (mut node_tx, mut node_rx) = upstream.split();
    let (mut ws_tx, mut ws_rx) = socket.split();

    // Node → browser: terminal output. Ping/pong stays leg-local (each
    // library answers its own); a close ends the loop.
    let to_client = async {
        while let Some(Ok(msg)) = node_rx.next().await {
            let out = match msg {
                NodeMessage::Binary(bytes) => Message::Binary(bytes),
                NodeMessage::Text(text) => Message::Text(text.as_str().into()),
                NodeMessage::Close(_) => break,
                _ => continue,
            };
            if ws_tx.send(out).await.is_err() {
                break;
            }
        }
    };

    // Browser → node: stdin bytes and resize JSON, relayed unchanged.
    let from_client = async {
        while let Some(Ok(msg)) = ws_rx.next().await {
            let fwd = match msg {
                Message::Binary(bytes) => NodeMessage::Binary(bytes),
                Message::Text(text) => NodeMessage::Text(text.as_str().into()),
                Message::Close(_) => break,
                _ => continue,
            };
            if node_tx.send(fwd).await.is_err() {
                break;
            }
        }
    };

    // Whichever side ends first tears down the other: dropping the node half
    // closes the upstream socket (ending the exec on the node), dropping the
    // browser half ends the page's session.
    tokio::select! {
        () = to_client => {},
        () = from_client => {},
    }
}

/// Bridge a WebSocket to a container exec session: engine output → client
/// (binary), client input → engine stdin (binary), client resize JSON →
/// `resize_exec` (text). Ends — closing the exec — as soon as either side does.
async fn exec_bridge(
    mut socket: WebSocket,
    docker: DockerHandle,
    host: String,
    id: String,
    cmd: String,
    read_only: Arc<AtomicBool>,
) {
    let session = match docker.exec_start(&id, &cmd).await {
        Ok(session) => session,
        Err(err) => {
            // A proxy denying exec (403) latches the host read-only, so the
            // detail page disables the terminal on its next render.
            if is_forbidden(&err) && !read_only.swap(true, Ordering::Relaxed) {
                tracing::warn!(%host, "host is read-only (proxy denied exec); disabling terminal");
            }
            // Surface the failure in the terminal itself, then close.
            let msg = format!("\r\n\x1b[31mfailed to start terminal: {err}\x1b[0m\r\n");
            let _ = socket.send(Message::Text(msg.into())).await;
            let _ = socket.close().await;
            return;
        }
    };
    let ExecSession {
        exec_id,
        mut output,
        mut input,
    } = session;
    let (mut ws_tx, mut ws_rx) = socket.split();

    // Engine → client.
    let to_client = async {
        while let Some(chunk) = output.next().await {
            let Ok(out) = chunk else { break };
            if ws_tx.send(Message::Binary(out.into_bytes())).await.is_err() {
                break;
            }
        }
    };

    // Client → engine (stdin) and resize control.
    let from_client = async {
        while let Some(Ok(msg)) = ws_rx.next().await {
            match msg {
                Message::Binary(bytes) => {
                    if input.write_all(&bytes).await.is_err() {
                        break;
                    }
                    let _ = input.flush().await;
                }
                Message::Text(text) => {
                    if let Ok(r) = serde_json::from_str::<ResizeMsg>(text.as_str()) {
                        let _ = docker.exec_resize(&exec_id, r.cols, r.rows).await;
                    }
                }
                Message::Close(_) => break,
                _ => {}
            }
        }
    };

    // Whichever side ends first tears down the other (dropping `input` ends the
    // exec, closing the socket ends the browser session).
    tokio::select! {
        () = to_client => {},
        () = from_client => {},
    }
}

/// Clear the session cookie and return to the login page.
async fn logout(State(state): State<AppState>) -> Response {
    let mut resp = Redirect::to("/login").into_response();
    if let Some(auth) = state.auth.as_ref()
        && let Ok(value) = auth.clear_cookie().parse()
    {
        resp.headers_mut().insert(header::SET_COOKIE, value);
    }
    resp
}

/// Query for the chart backfill endpoints: return points at or after this
/// Unix-ms timestamp (clamped to the seed window server-side).
#[derive(serde::Deserialize)]
struct SinceQuery {
    #[serde(default)]
    since_ms: u64,
}

/// Clamp a client-supplied `since_ms` to the seed window, so a stale or
/// malicious value can't request unbounded history in one response.
fn clamp_since(since_ms: u64, window: Duration) -> u64 {
    since_ms.max(now_unix_ms().saturating_sub(duration_ms(window)))
}

/// Run a blocking store query for chart points, degrading to an empty series.
/// The charts just show what they get — but a failing store is worth a log
/// line, not silence.
async fn fetch_points<T, F>(f: F) -> Vec<T>
where
    T: Send + 'static,
    F: FnOnce() -> anyhow::Result<Vec<T>> + Send + 'static,
{
    match tokio::task::spawn_blocking(f).await {
        Ok(Ok(points)) => points,
        Ok(Err(err)) => {
            tracing::warn!(%err, "loading chart points failed");
            Vec::new()
        }
        Err(join_err) => {
            tracing::warn!(%join_err, "chart point task panicked");
            Vec::new()
        }
    }
}

/// JSON backfill for a container detail page's charts. `live.js` calls this
/// before (re)opening the SSE stream to fill the gap that built up while the
/// page was hidden, in the bfcache, or suspended.
async fn metrics_container(
    State(state): State<AppState>,
    axum::extract::Path((host, id)): axum::extract::Path<(String, String)>,
    Query(q): Query<SinceQuery>,
    axum::extract::RawQuery(raw): axum::extract::RawQuery,
) -> Response {
    if let Some(HostRuntime {
        source: HostSource::Node(node),
        ..
    }) = state.hosts.get(&host)
    {
        // The node clamps `since_ms` to its own seed window and answers the
        // same JSON this handler would build.
        return proxy_get(
            node,
            &format!("/api/metrics/container/{id}"),
            raw.as_deref(),
        )
        .await;
    }
    let since = clamp_since(q.since_ms, state.seed_window);
    let store = state.store.clone();
    Json(fetch_points(move || store.recent_container_samples(&host, &id, since)).await)
        .into_response()
}

/// JSON backfill for a stack detail page's charts (trend-based, like the seed).
async fn metrics_stack(
    State(state): State<AppState>,
    axum::extract::Path((host, name)): axum::extract::Path<(String, String)>,
    Query(q): Query<SinceQuery>,
    axum::extract::RawQuery(raw): axum::extract::RawQuery,
) -> Response {
    if let Some(HostRuntime {
        source: HostSource::Node(node),
        ..
    }) = state.hosts.get(&host)
    {
        return proxy_get(node, &format!("/api/metrics/stack/{name}"), raw.as_deref()).await;
    }
    let since = clamp_since(q.since_ms, state.seed_window);
    let store = state.store.clone();
    Json(fetch_points(move || store.recent_stack_trends(&host, &name, since)).await).into_response()
}

/// Selectable named history ranges: query value and lookback window.
// No `Duration::from_hours`/`from_days` on stable; same trade-off as elsewhere.
#[allow(clippy::duration_suboptimal_units)]
const HISTORY_RANGES: &[(&str, Duration)] = &[
    ("1h", Duration::from_secs(3600)),
    ("6h", Duration::from_secs(6 * 3600)),
    ("24h", Duration::from_secs(24 * 3600)),
    ("7d", Duration::from_secs(7 * 24 * 3600)),
    ("30d", Duration::from_secs(30 * 24 * 3600)),
];

/// Query for the history endpoints: either a named range from
/// [`HISTORY_RANGES`] or a free `since_ms`/`until_ms` window (used by the
/// drag-to-drill-down selection in the UI).
#[derive(serde::Deserialize)]
struct HistoryQuery {
    range: Option<String>,
    since_ms: Option<u64>,
    until_ms: Option<u64>,
}

/// A resolved history request window.
struct HistoryWindow {
    since: u64,
    until: u64,
    group_ms: u64,
    /// Serve from raw samples (window lies inside the raw retention) instead
    /// of trend buckets — full resolution, exact values.
    raw: bool,
}

/// Resolve a history query into a concrete window, or `None` if it is neither
/// a known named range nor a plausible custom window.
fn resolve_history(q: &HistoryQuery, seed_window: Duration) -> Option<HistoryWindow> {
    let now = now_unix_ms();
    let (since, until) = match (&q.range, q.since_ms, q.until_ms) {
        (Some(range), None, None) => {
            let &(_, window) = HISTORY_RANGES.iter().find(|r| r.0 == *range)?;
            (now.saturating_sub(duration_ms(window)), now)
        }
        (None, Some(since), Some(until)) if since < until => (since, until),
        _ => return None,
    };
    Some(HistoryWindow {
        since,
        until,
        group_ms: group_for_window(until - since),
        raw: since >= now.saturating_sub(duration_ms(seed_window)),
    })
}

/// Downsample group for a window: aim for ≤ ~1440 points, in whole trend
/// buckets (60 s). 24 h stays at one point per bucket; 30 d collapses into
/// 30 min windows.
fn group_for_window(window_ms: u64) -> u64 {
    const TARGET_POINTS: u64 = 1440;
    (window_ms / TARGET_POINTS).div_ceil(60_000).max(1) * 60_000
}

/// Downsample group for the *raw* path: same point target, but not quantized
/// to trend buckets. For windows short enough that the group stays below the
/// sample interval this is a no-op (every sample its own group) — the raw
/// path keeps its full resolution. For long windows it caps the response:
/// `raw_retention_secs` is a documented knob, and without the cap raising it
/// to days would let one request return hundreds of thousands of points,
/// stalling the browser for minutes.
fn raw_group_for_window(window_ms: u64) -> u64 {
    const TARGET_POINTS: u64 = 1440;
    (window_ms / TARGET_POINTS).max(1)
}

const INVALID_RANGE: (StatusCode, &str) = (
    StatusCode::BAD_REQUEST,
    "invalid range: pass ?range=1h|6h|24h|7d|30d or ?since_ms=&until_ms=",
);

/// History for one container's charts: median plus min–max envelope over the
/// window.
async fn history_container(
    State(state): State<AppState>,
    axum::extract::Path((host, id)): axum::extract::Path<(String, String)>,
    Query(q): Query<HistoryQuery>,
    axum::extract::RawQuery(raw): axum::extract::RawQuery,
) -> Response {
    if let Some(HostRuntime {
        source: HostSource::Node(node),
        ..
    }) = state.hosts.get(&host)
    {
        // History lives on the node — the whole point of decentralised
        // storage. Ranges, drill-down windows and grouping are its business.
        return proxy_get(
            node,
            &format!("/api/history/container/{id}"),
            raw.as_deref(),
        )
        .await;
    }
    let Some(w) = resolve_history(&q, state.seed_window) else {
        return INVALID_RANGE.into_response();
    };
    // Trend history is keyed by container *name* so it spans recreations (see
    // `Store::history_container`), but the URL carries the id. Resolve it via
    // the live snapshot; for a container that is no longer running, fall back
    // to the name its trends were recorded under.
    let snapshot_name = state.hosts.get(&host).and_then(|rt| {
        current_snapshot(rt).and_then(|d| {
            d.containers
                .iter()
                .find(|c| c.id == id)
                .map(|c| c.name.clone())
        })
    });
    let store = state.store.clone();
    let points = if w.raw {
        let group = raw_group_for_window(w.until - w.since);
        fetch_points(move || store.history_container_raw(&host, &id, w.since, w.until, group)).await
    } else {
        fetch_points(move || {
            let Some(name) =
                snapshot_name.map_or_else(|| store.container_name(&host, &id), |n| Ok(Some(n)))?
            else {
                return Ok(Vec::new());
            };
            store.history_container(&host, &name, w.since, w.until, w.group_ms)
        })
        .await
    };
    Json(points).into_response()
}

/// History for a stack's aggregate charts. Stacks have no raw series, so all
/// windows come from the trend buckets.
async fn history_stack(
    State(state): State<AppState>,
    axum::extract::Path((host, name)): axum::extract::Path<(String, String)>,
    Query(q): Query<HistoryQuery>,
    axum::extract::RawQuery(raw): axum::extract::RawQuery,
) -> Response {
    if let Some(HostRuntime {
        source: HostSource::Node(node),
        ..
    }) = state.hosts.get(&host)
    {
        return proxy_get(node, &format!("/api/history/stack/{name}"), raw.as_deref()).await;
    }
    let Some(w) = resolve_history(&q, state.seed_window) else {
        return INVALID_RANGE.into_response();
    };
    let store = state.store.clone();
    Json(
        fetch_points(move || store.history_stack(&host, &name, w.since, w.until, w.group_ms)).await,
    )
    .into_response()
}

/// Render the dashboard from the latest snapshot. The dashboard has no charts
/// of its own (the host-metrics header was removed); it only lists containers
/// and updates them live over SSE.
async fn dashboard(
    State(state): State<AppState>,
    axum::extract::Path(host): axum::extract::Path<String>,
) -> Response {
    let rt = match host_rt(&state, &host) {
        Ok(rt) => rt,
        Err(resp) => return resp,
    };
    let snapshot = current_snapshot(rt);
    dashboard_page(
        &state,
        &host,
        snapshot.as_ref(),
        &rt.links,
        rt.is_read_only(),
    )
    .into_response()
}

/// Detail page for a single container.
async fn container_detail(
    State(state): State<AppState>,
    axum::extract::Path((host, id)): axum::extract::Path<(String, String)>,
) -> Response {
    let rt = match host_rt(&state, &host) {
        Ok(rt) => rt,
        Err(resp) => return resp,
    };
    let snapshot = current_snapshot(rt);
    let r = Render {
        host: &host,
        links: &rt.links,
        read_only: rt.is_read_only(),
    };
    let live_url = format!("/host/{host}/events");
    let Some(container) = snapshot
        .as_ref()
        .and_then(|d| d.containers.iter().find(|c| c.id == id).cloned())
    else {
        let body = shell(
            &state,
            &host,
            snapshot.as_ref(),
            html! { p.empty { "Container not found." } },
            &[],
            &live_url,
            "",
            false,
        );
        return (StatusCode::NOT_FOUND, body).into_response();
    };
    let since = now_unix_ms().saturating_sub(duration_ms(state.seed_window));
    let seed = match &rt.source {
        HostSource::Docker(_) => {
            let store = state.store.clone();
            let (seed_host, seed_id) = (host.clone(), id.clone());
            fetch_points(move || store.recent_container_samples(&seed_host, &seed_id, since)).await
        }
        // The node holds the history; seed from its backfill endpoint. An
        // unreachable node degrades to an empty seed — live points still flow.
        HostSource::Node(node) => node
            .metric_points(&format!("/api/metrics/container/{id}"), since)
            .await
            .unwrap_or_else(|err| {
                tracing::warn!(%host, %id, error = %format!("{err:#}"), "seeding charts from node failed");
                Vec::new()
            }),
    };

    let live_url = format!("/host/{host}/events/container/{id}");
    let backfill_url = format!("/host/{host}/api/metrics/container/{id}");
    shell(
        &state,
        &host,
        snapshot.as_ref(),
        container_detail_main(&container, &r),
        &seed,
        &live_url,
        &backfill_url,
        true,
    )
    .into_response()
}

/// Detail page for a compose stack.
async fn stack_detail(
    State(state): State<AppState>,
    axum::extract::Path((host, name)): axum::extract::Path<(String, String)>,
) -> Response {
    let rt = match host_rt(&state, &host) {
        Ok(rt) => rt,
        Err(resp) => return resp,
    };
    let snapshot = current_snapshot(rt);
    let r = Render {
        host: &host,
        links: &rt.links,
        read_only: rt.is_read_only(),
    };
    let members: Vec<ContainerMetrics> = snapshot
        .as_ref()
        .map(|d| {
            d.containers
                .iter()
                .filter(|c| c.stack.as_deref() == Some(name.as_str()))
                .cloned()
                .collect()
        })
        .unwrap_or_default();

    if members.is_empty() {
        let body = shell(
            &state,
            &host,
            snapshot.as_ref(),
            html! { p.empty { "Stack not found." } },
            &[],
            &format!("/host/{host}/events"),
            "",
            false,
        );
        return (StatusCode::NOT_FOUND, body).into_response();
    }

    // Stack charts stream live aggregates. Raw samples aren't keyed by stack,
    // so we seed from trends: the sum of member medians per bucket, which lines
    // up with the live aggregate (sum of current member values).
    let since = now_unix_ms().saturating_sub(duration_ms(state.seed_window));
    let seed = match &rt.source {
        HostSource::Docker(_) => {
            let store = state.store.clone();
            let (seed_host, seed_name) = (host.clone(), name.clone());
            fetch_points(move || store.recent_stack_trends(&seed_host, &seed_name, since)).await
        }
        HostSource::Node(node) => node
            .metric_points(&format!("/api/metrics/stack/{name}"), since)
            .await
            .unwrap_or_else(|err| {
                tracing::warn!(%host, stack = %name, error = %format!("{err:#}"), "seeding charts from node failed");
                Vec::new()
            }),
    };

    // Members are non-empty here, so a snapshot exists; 1 is just a fallback.
    let cpu_count = snapshot.as_ref().map_or(1, |d| d.cpu_count);
    let live_url = format!("/host/{host}/events/stack/{name}");
    let backfill_url = format!("/host/{host}/api/metrics/stack/{name}");
    shell(
        &state,
        &host,
        snapshot.as_ref(),
        stack_detail_main(&name, &members, cpu_count, &r),
        &seed,
        &live_url,
        &backfill_url,
        false,
    )
    .into_response()
}

/// Single live stream for the dashboard: `header` + `containers` HTML fragments
/// per snapshot. One SSE connection per page keeps us well under the browser's
/// per-host connection limit. The dashboard has no charts, so no `metrics`.
async fn events_dashboard(
    State(state): State<AppState>,
    axum::extract::Path(host): axum::extract::Path<String>,
) -> Response {
    let Some(rt) = state.hosts.get(&host) else {
        return (StatusCode::NOT_FOUND, "unknown host").into_response();
    };
    let auth = state.auth.is_some();
    let order = Arc::clone(&state.host_order);
    let links = rt.links.clone();
    let read_only = Arc::clone(&rt.read_only);
    let stream = dashboard_stream(rt.shared.clone()).flat_map(move |dash| {
        let r = Render {
            host: &host,
            links: &links,
            read_only: read_only.load(Ordering::Relaxed),
        };
        futures_util::stream::iter([
            Ok::<_, Infallible>(header_event(&dash, &host, &order, auth)),
            Ok(containers_event(&dash, &r)),
            Ok(overview_event(&dash)),
        ])
    });
    Sse::new(stream)
        .keep_alive(KeepAlive::default())
        .into_response()
}

/// Single live stream for a container detail page: `header` plus the
/// container's `metrics` point.
async fn events_container(
    State(state): State<AppState>,
    axum::extract::Path((host, id)): axum::extract::Path<(String, String)>,
) -> Response {
    let Some(rt) = state.hosts.get(&host) else {
        return (StatusCode::NOT_FOUND, "unknown host").into_response();
    };
    let auth = state.auth.is_some();
    let order = Arc::clone(&state.host_order);
    let links = rt.links.clone();
    let stream = dashboard_stream(rt.shared.clone()).flat_map(move |dash| {
        let mut events: Vec<Result<Event, Infallible>> =
            vec![Ok(header_event(&dash, &host, &order, auth))];
        if let Some(c) = dash.containers.iter().find(|c| c.id == id) {
            events.push(Ok(detail_event(c, &links)));
            events.push(Ok(metrics_event(&MetricPoint {
                ts_ms: dash.generated_at_unix_ms,
                cpu_percent: c.cpu_percent.unwrap_or(0.0),
                mem_used: c.mem_used,
                net_rx: c.net_rx_bps,
                net_tx: c.net_tx_bps,
                disk_read: c.disk_read_bps,
                disk_write: c.disk_write_bps,
            })));
        }
        futures_util::stream::iter(events)
    });
    Sse::new(stream)
        .keep_alive(KeepAlive::default())
        .into_response()
}

/// Single live stream for a stack detail page: `header` plus an aggregate
/// `metrics` point (CPU and memory summed across the stack's containers).
async fn events_stack(
    State(state): State<AppState>,
    axum::extract::Path((host, name)): axum::extract::Path<(String, String)>,
) -> Response {
    let Some(rt) = state.hosts.get(&host) else {
        return (StatusCode::NOT_FOUND, "unknown host").into_response();
    };
    let auth = state.auth.is_some();
    let order = Arc::clone(&state.host_order);
    let links = rt.links.clone();
    let read_only = Arc::clone(&rt.read_only);
    let stream = dashboard_stream(rt.shared.clone()).flat_map(move |dash| {
        let r = Render {
            host: &host,
            links: &links,
            read_only: read_only.load(Ordering::Relaxed),
        };
        let members: Vec<&ContainerMetrics> = dash
            .containers
            .iter()
            .filter(|c| c.stack.as_deref() == Some(name.as_str()))
            .collect();
        let mut cpu = 0.0;
        let mut mem = 0u64;
        let mut io = StackIo::default();
        for c in &members {
            cpu += c.cpu_percent.unwrap_or(0.0);
            mem += c.mem_used.unwrap_or(0);
            io.add(c);
        }
        let members_event = Event::default()
            .event("containers")
            .data(stack_members_table(&members, dash.cpu_count, &r).into_string());
        futures_util::stream::iter([
            Ok::<_, Infallible>(header_event(&dash, &host, &order, auth)),
            Ok(members_event),
            Ok(metrics_event(&MetricPoint {
                ts_ms: dash.generated_at_unix_ms,
                cpu_percent: cpu,
                mem_used: Some(mem),
                net_rx: io.net_rx,
                net_tx: io.net_tx,
                disk_read: io.disk_read,
                disk_write: io.disk_write,
            })),
        ])
    });
    Sse::new(stream)
        .keep_alive(KeepAlive::default())
        .into_response()
}

/// The `detail` event: a container detail page's live region (state + facts).
fn detail_event(c: &ContainerMetrics, links: &PortLinks) -> Event {
    Event::default()
        .event("detail")
        .data(container_detail_live(c, links).into_string())
}

/// The `header` event: the host header's inner HTML.
fn header_event(dash: &Dashboard, host: &str, hosts: &[String], auth_enabled: bool) -> Event {
    Event::default()
        .event("header")
        .data(host_header_inner(Some(dash), host, hosts, auth_enabled).into_string())
}

/// The `containers` event: the container table's HTML.
fn containers_event(dash: &Dashboard, r: &Render) -> Event {
    Event::default()
        .event("containers")
        .data(container_section(&dash.containers, dash.cpu_count, r).into_string())
}

/// One container's slice of the dashboard overview discs, serialized to JSON
/// for both the page seed and the `overview` SSE event.
#[derive(serde::Serialize)]
struct OverviewEntry<'a> {
    id: &'a str,
    name: &'a str,
    stack: Option<&'a str>,
    cpu: Option<f64>,
    mem: Option<u64>,
}

/// The overview payload: snapshot timestamp plus the container list in the
/// same deterministic order as the container table (stacks alphabetically,
/// standalone last, names within) so a sector keeps its angular position.
fn overview_json(dash: &Dashboard) -> String {
    let mut containers: Vec<&ContainerMetrics> = dash.containers.iter().collect();
    containers.sort_by(|a, b| {
        stack_key(a)
            .cmp(&stack_key(b))
            .then_with(|| a.name.cmp(&b.name))
    });
    let entries: Vec<OverviewEntry<'_>> = containers
        .iter()
        .map(|c| OverviewEntry {
            id: &c.id,
            name: &c.name,
            stack: c.stack.as_deref(),
            cpu: c.cpu_percent,
            mem: c.mem_used,
        })
        .collect();
    let payload = serde_json::json!({
        "ts_ms": dash.generated_at_unix_ms,
        "containers": entries,
    });
    // `<` can only occur inside JSON strings, so escaping it globally keeps a
    // hostile container name from closing the inline `<script>` seed block.
    payload.to_string().replace('<', "\\u003c")
}

fn stack_key(c: &ContainerMetrics) -> StackKey<'_> {
    match &c.stack {
        Some(name) => StackKey::Named(name),
        None => StackKey::Standalone,
    }
}

/// The `overview` event: the dashboard discs' JSON payload.
fn overview_event(dash: &Dashboard) -> Event {
    Event::default().event("overview").data(overview_json(dash))
}

/// Accumulates a stack's per-second I/O rates across its members. A category
/// stays `None` until at least one member reports it, then sums it (members
/// without that category contribute nothing) — mirroring the trend-based seed,
/// where `SUM` over all-NULL is NULL but any value makes it that sum.
#[derive(Default)]
struct StackIo {
    net_rx: Option<f64>,
    net_tx: Option<f64>,
    disk_read: Option<f64>,
    disk_write: Option<f64>,
}

impl StackIo {
    fn add(&mut self, c: &ContainerMetrics) {
        add_opt(&mut self.net_rx, c.net_rx_bps);
        add_opt(&mut self.net_tx, c.net_tx_bps);
        add_opt(&mut self.disk_read, c.disk_read_bps);
        add_opt(&mut self.disk_write, c.disk_write_bps);
    }
}

fn add_opt(acc: &mut Option<f64>, v: Option<f64>) {
    if let Some(v) = v {
        *acc = Some(acc.unwrap_or(0.0) + v);
    }
}

/// The `metrics` event: a metric point as JSON.
fn metrics_event(point: &MetricPoint) -> Event {
    let data = serde_json::to_string(point).unwrap_or_else(|_| "{}".to_string());
    Event::default().event("metrics").data(data)
}

/// A stream of the latest snapshot: yields the current snapshot immediately,
/// then the newest one whenever it changes (deduped by timestamp). It polls the
/// shared snapshot — the same source the page render reads — so the live view
/// can never drift from a plain reload.
fn dashboard_stream(shared: SharedDashboard) -> impl Stream<Item = Arc<Dashboard>> + use<> {
    let ticker = tokio::time::interval(SNAPSHOT_POLL);
    futures_util::stream::unfold(
        (shared, 0u64, ticker),
        |(shared, last, mut ticker)| async move {
            loop {
                ticker.tick().await;
                let snapshot = shared.read().ok().and_then(|guard| guard.clone());
                if let Some(dash) = snapshot
                    && dash.generated_at_unix_ms != last
                {
                    let ts = dash.generated_at_unix_ms;
                    return Some((Arc::new(dash), (shared, ts, ticker)));
                }
            }
        },
    )
}

/// Full HTML shell shared by every page: the live host header, the page's main
/// content, and the chart machinery. `live_url` is the SSE endpoint the charts
/// subscribe to; `seed` pre-fills them with history; `backfill_url` is the JSON
/// endpoint `live.js` uses to close chart gaps before reconnecting.
// `main_content` is moved in by builder convention — callers hand off a
// freshly-built fragment they no longer need.
#[allow(
    clippy::needless_pass_by_value,
    clippy::too_many_arguments,
    reason = "page assembly genuinely needs all of these inputs"
)]
fn shell(
    state: &AppState,
    host: &str,
    snapshot: Option<&Dashboard>,
    main_content: Markup,
    seed: &[MetricPoint],
    live_url: &str,
    backfill_url: &str,
    terminal: bool,
) -> Markup {
    let auth_enabled = state.auth.is_some();
    let seed_json = serde_json::to_string(seed).unwrap_or_else(|_| "[]".to_string());
    // The history endpoints mirror the backfill endpoints by design — same
    // entity, same path shape — so the URL is derived instead of threaded
    // through every page handler.
    let history_url = backfill_url.replacen("/api/metrics/", "/api/history/", 1);
    html! {
        (DOCTYPE)
        html lang="en" {
            head {
                meta charset="utf-8";
                meta name="viewport" content="width=device-width, initial-scale=1";
                title { "DockDoe" }
                // Two favicon variants picked by the browser's tab-bar theme:
                // the dark mark for light chrome, the white one for dark.
                link rel="icon" type="image/svg+xml" href="/assets/dockdoe.svg"
                    media="(prefers-color-scheme: light)";
                link rel="icon" type="image/svg+xml" href="/assets/dockdoe-white.svg"
                    media="(prefers-color-scheme: dark)";
                link rel="stylesheet" href="/assets/vendor/uPlot.min.css";
                @if terminal {
                    link rel="stylesheet" href="/assets/vendor/xterm.css";
                }
                link rel="stylesheet" href="/assets/dockdoe.css";
            }
            body {
                header.host id="host-header" {
                    (host_header_inner(snapshot, host, &state.host_order, auth_enabled))
                }
                main { (main_content) }
                // Error toast: filled by live.js on htmx request failures.
                // Lives outside the live regions so the 1s SSE swaps of
                // #containers / #detail-live can't wipe the message.
                div id="toast" role="alert" {}
                // History overlay, opened by the expand button on any chart
                // card and driven by history.js. The inner .history-body
                // covers the whole dialog so a click landing on the <dialog>
                // element itself can only mean the backdrop.
                dialog id="history-dialog" {
                    div.history-body {
                        div.history-head {
                            span.history-title id="history-title" {}
                            // Rendered from HISTORY_RANGES so the buttons,
                            // the server's accepted values and the deep-link
                            // validation (history.js checks these buttons)
                            // stay one list.
                            div.history-ranges id="history-ranges" {
                                @for (name, _) in HISTORY_RANGES {
                                    button type="button" data-range=(name) { (name) }
                                }
                            }
                            // Shown by history.js while a drag-selected
                            // window is displayed.
                            span.history-hint id="history-hint" {
                                "double-click to zoom out"
                            }
                            span.chart-readout id="history-readout" {}
                            button.history-close id="history-close" type="button"
                                aria-label="Close" { "" }
                        }
                        div id="history-chart" {}
                    }
                }
                script id="seed-data" type="application/json"
                    data-live-url=(live_url) data-backfill-url=(backfill_url)
                    data-history-url=(history_url) {
                    (maud::PreEscaped(seed_json))
                }
                script src="/assets/vendor/htmx.min.js" {}
                script src="/assets/vendor/uPlot.iife.min.js" {}
                script src="/assets/live.js" {}
                script src="/assets/overview.js" {}
                script src="/assets/history.js" {}
                @if terminal {
                    script src="/assets/vendor/xterm.js" {}
                    script src="/assets/vendor/addon-fit.js" {}
                    script src="/assets/terminal.js" {}
                }
            }
        }
    }
}

/// The dashboard body: the overview discs plus the live container table.
fn dashboard_page(
    state: &AppState,
    host: &str,
    snapshot: Option<&Dashboard>,
    links: &PortLinks,
    read_only: bool,
) -> Markup {
    let r = Render {
        host,
        links,
        read_only,
    };
    let main = html! {
        (overview_section(&state.overview, host, snapshot))
        div id="containers" {
            @match snapshot {
                Some(d) => (container_section(&d.containers, d.cpu_count, &r)),
                None => p.empty { "Collecting first metrics sample…" },
            }
        }
    };
    // No uPlot charts here, so no metric seed or backfill endpoint; the SSE
    // stream drives the header, the container table and the overview discs.
    let live_url = format!("/host/{host}/events");
    shell(state, host, snapshot, main, &[], &live_url, "", false)
}

/// The dashboard overview: two radial "phosphor" discs (CPU + memory), one
/// sector per container, drawn by `overview.js` on the canvases below. The
/// section's data attributes hand the configured scales and the detail-page
/// URL prefix to the script; the inline JSON seed lets it paint the first
/// frame without waiting for the SSE stream.
fn overview_section(cfg: &OverviewConfig, host: &str, snapshot: Option<&Dashboard>) -> Markup {
    let seed = snapshot.map_or_else(|| "null".to_string(), overview_json);
    html! {
        section.charts.overview id="overview"
            data-container-url=(format!("/host/{host}/container/"))
            data-cpu-scale=(cfg.cpu_scale.as_str())
            data-mem-scale=(cfg.mem_scale.as_str())
            data-mem-cap=(cfg.mem_cap) {
            div.chart-card {
                div.chart-head {
                    span.chart-title { "CPU" }
                    // Filled by overview.js while hovering: "jellyfin · 5.8%".
                    span.chart-readout id="overview-readout-cpu" {}
                }
                div.overview-disc { canvas id="overview-cpu" {} }
            }
            div.chart-card {
                div.chart-head {
                    span.chart-title { "Memory" }
                    span.chart-readout id="overview-readout-mem" {}
                }
                div.overview-disc { canvas id="overview-mem" {} }
            }
            script id="overview-seed" type="application/json" { (maud::PreEscaped(seed)) }
        }
    }
}

/// Markup for a pair of live charts (CPU + memory). Data comes from `live.js`,
/// which reads the seed and live URL off the page.
fn charts_section(cpu_title: &str, mem_title: &str) -> Markup {
    html! {
        section.charts {
            div.chart-card {
                div.chart-head {
                    span.chart-title { (cpu_title) }
                    // Filled by live.js while hovering: "21:43:05 · 3.2%".
                    span.chart-readout id="readout-cpu" {}
                    button.chart-zoom type="button" data-metric="cpu"
                        title="Show history" aria-label="Show history" { "" }
                }
                div id="chart-cpu" {}
            }
            div.chart-card {
                div.chart-head {
                    span.chart-title { (mem_title) }
                    span.chart-readout id="readout-mem" {}
                    button.chart-zoom type="button" data-metric="mem"
                        title="Show history" aria-label="Show history" { "" }
                }
                div id="chart-mem" {}
            }
        }
    }
}

/// Network and disk-I/O charts: two dual-line cards (rx/read in blue,
/// tx/write in green), fed by `live.js` from the same SSE point stream as the
/// CPU/memory charts. The expand button opens the same history overlay, which
/// renders both directions with their own min–max bands.
fn io_charts_section() -> Markup {
    html! {
        section.charts {
            (io_chart_card("Network", "net", "rx", "tx"))
            (io_chart_card("Disk I/O", "disk", "read", "write"))
        }
    }
}

/// One dual-line I/O chart card: a title, a two-key colour legend, a hover
/// readout, the history-expand button, and the uPlot mount point
/// (`chart-net` / `chart-disk`).
fn io_chart_card(title: &str, key: &str, in_label: &str, out_label: &str) -> Markup {
    html! {
        div.chart-card {
            div.chart-head {
                span.chart-title { (title) }
                span.chart-legend {
                    span.k.in { (in_label) }
                    span.k.out { (out_label) }
                }
                span.chart-readout id=(format!("readout-{key}")) {}
                button.chart-zoom type="button" data-metric=(key)
                    title="Show history" aria-label="Show history" { "" }
            }
            div id=(format!("chart-{key}")) {}
        }
    }
}

/// Body of a single-container detail page.
fn container_detail_main(c: &ContainerMetrics, r: &Render) -> Markup {
    let host = r.host;
    html! {
        section.detail-head {
            div.detail-title {
                a.back href=(format!("/host/{host}")) { "← Dashboard" }
                h1 { (c.name) }
                @if let Some(stack) = &c.stack {
                    a.stack-pill href=(format!("/host/{host}/stack/{stack}")) { (stack) }
                }
            }
            (action_buttons(host, &c.id, r.read_only))
        }
        // Live region: swapped wholesale by the `detail` SSE event so state and
        // facts track reality. The charts below are left untouched.
        div id="detail-live" { (container_detail_live(c, r.links)) }
        (charts_section(&format!("{} · CPU", c.name), &format!("{} · Memory", c.name)))
        (io_charts_section())
        section.panel {
            div.panel-head {
                h3 { "Logs " span.count { "(last " (LOG_TAIL_LINES) " lines)" } }
                button.refresh type="button"
                    hx-get=(format!("/host/{host}/api/container/{}/logs", c.id))
                    hx-target="#logs" hx-swap="innerHTML" { "↻ Refresh" }
            }
            pre.logs id="logs"
                hx-get=(format!("/host/{host}/api/container/{}/logs", c.id))
                hx-trigger="load" hx-swap="innerHTML" { "Loading logs…" }
        }
        (terminal_panel(c, host, r.read_only))
    }
}

/// The interactive terminal panel. Connects lazily (a shell is a real process,
/// so we don't spawn one on every page view) and only for running containers;
/// `terminal.js` opens the WebSocket on "Connect". The `⛶` button toggles a
/// fullscreen class on the panel. Stopped containers get a disabled note.
fn terminal_panel(c: &ContainerMetrics, host: &str, read_only: bool) -> Markup {
    let interactive = c.state == ContainerState::Running && !read_only;
    html! {
        section.panel.terminal id="terminal" data-ws=(format!("/host/{host}/ws/container/{}/exec", c.id)) {
            div.panel-head {
                h3 { "Terminal" }
                @if interactive {
                    div.term-controls {
                        input.term-cmd type="text" value="/bin/sh"
                            aria-label="Command" spellcheck="false" autocapitalize="off";
                        button.term-connect type="button" { "Connect" }
                        button.term-fs type="button" title="Toggle fullscreen"
                            aria-label="Toggle fullscreen" { "" }
                    }
                }
            }
            @if interactive {
                div.term-view id="term-view" {}
            } @else if read_only {
                p.empty { "This host is read-only — the terminal is disabled." }
            } @else {
                p.empty { "Container is not running." }
            }
        }
    }
}

/// The shared table header of every container table. The column classes carry
/// fixed widths (see dockdoe.css), so tables in different stack sections line
/// up with each other — keep this the single definition.
fn container_table_head() -> Markup {
    html! {
        thead {
            tr {
                th { "Container" }
                th.col-image { "Image" }
                th.col-state { "State" }
                th.num.col-cpu { "CPU" }
                th.num.col-mem { "Memory" }
                th.actions-col { "Actions" }
            }
        }
    }
}

/// A stack's member containers as a table (live region on the stack page).
fn stack_members_table(members: &[&ContainerMetrics], cpu_count: usize, r: &Render) -> Markup {
    html! {
        section.stack {
            table {
                (container_table_head())
                tbody {
                    @for c in members { (container_row(c, cpu_count, r)) }
                }
            }
        }
    }
}

/// The live-updating part of a container detail page: state badge, health, and
/// the facts grid. Re-rendered and pushed via the `detail` SSE event.
fn container_detail_live(c: &ContainerMetrics, links: &PortLinks) -> Markup {
    html! {
        div.status-line {
            span.badge.(state_name(c.state)) { (state_name(c.state)) }
            (health_marker(c.health))
            (port_pills(&c.ports, links))
        }
        section.facts {
            (fact("Image", short_image(&c.image)))
            (fact("Container ID", &c.id.chars().take(12).collect::<String>()))
            (fact("Status", &c.status))
            (fact(
                "Memory limit",
                &c.mem_limit.map_or_else(|| "".to_string(), fmt_bytes),
            ))
        }
    }
}

/// Body of a stack detail page: aggregate charts, stack actions, and the
/// stack's containers.
fn stack_detail_main(
    name: &str,
    members: &[ContainerMetrics],
    cpu_count: usize,
    r: &Render,
) -> Markup {
    let host = r.host;
    html! {
        section.detail-head {
            div.detail-title {
                a.back href=(format!("/host/{host}")) { "← Dashboard" }
                h1 { (name) }
                span.count { "(" (members.len()) ")" }
            }
            (stack_action_buttons(host, name, r.read_only))
        }
        (charts_section(
            &format!("{name} · CPU (sum)"),
            &format!("{name} · Memory (sum)"),
        ))
        (io_charts_section())
        // Live region: the `containers` SSE event swaps the member table so its
        // states/metrics track reality.
        div id="containers" { (stack_members_table(&members.iter().collect::<Vec<_>>(), cpu_count, r)) }
        section.panel {
            div.panel-head {
                h3 { "compose.yml" }
                button.refresh type="button"
                    hx-get=(format!("/host/{host}/api/stack/{name}/compose"))
                    hx-target="#compose" hx-swap="innerHTML" { "↻ Refresh" }
            }
            div id="compose"
                hx-get=(format!("/host/{host}/api/stack/{name}/compose"))
                hx-trigger="load" hx-swap="innerHTML" { "Loading…" }
        }
    }
}

/// Start/stop/restart-all buttons for a whole stack.
fn stack_action_buttons(host: &str, name: &str, read_only: bool) -> Markup {
    html! {
        span.actions title=[read_only.then_some("host is read-only")] {
            button.act.start type="button" disabled[read_only]
                hx-post=(format!("/host/{host}/api/stack/{name}/start"))
                hx-target="closest .actions" hx-swap="outerHTML"
                title="Start all" { "" }
            button.act.restart type="button" disabled[read_only]
                hx-post=(format!("/host/{host}/api/stack/{name}/restart"))
                hx-target="closest .actions" hx-swap="outerHTML"
                hx-confirm=(format!("Restart all containers in {name}?"))
                title="Restart all" { "" }
            button.act.stop type="button" disabled[read_only]
                hx-post=(format!("/host/{host}/api/stack/{name}/stop"))
                hx-target="closest .actions" hx-swap="outerHTML"
                hx-confirm=(format!("Stop all containers in {name}?"))
                title="Stop all" { "" }
        }
    }
}

/// A labelled fact for the detail meta grid.
fn fact(label: &str, value: &str) -> Markup {
    html! {
        div.fact {
            span.fact-label { (label) }
            span.fact-value { (value) }
        }
    }
}

/// The brand mark in the header: the app icon followed by the wordmark. The
/// white icon variant is used because the UI is dark-themed throughout. `alt`
/// is empty — the adjacent "DockDoe" text already names the link.
fn brand() -> Markup {
    html! {
        a.brand href="/" {
            img.brand-icon src="/assets/dockdoe-white.svg" alt="";
            span.brand-name { "Dock" span { "Doe" } }
        }
    }
}

/// The standalone login page — deliberately minimal: the brand, a username and
/// password field, and a submit button. No header, charts, or live machinery,
/// so it needs none of the page scripts. `error` shows the failed-login notice.
fn login_shell(error: bool) -> Markup {
    html! {
        (DOCTYPE)
        html lang="en" {
            head {
                meta charset="utf-8";
                meta name="viewport" content="width=device-width, initial-scale=1";
                title { "DockDoe — Log in" }
                link rel="icon" type="image/svg+xml" href="/assets/dockdoe.svg"
                    media="(prefers-color-scheme: light)";
                link rel="icon" type="image/svg+xml" href="/assets/dockdoe-white.svg"
                    media="(prefers-color-scheme: dark)";
                link rel="stylesheet" href="/assets/dockdoe.css";
            }
            body.login-body {
                form.login method="post" action="/login" {
                    (brand())
                    @if error {
                        p.login-error { "Invalid username or password." }
                    }
                    label."visually-hidden" for="username" { "Username" }
                    input #username type="text" name="username" placeholder="Username"
                        autocomplete="username" autofocus required;
                    label."visually-hidden" for="password" { "Password" }
                    input #password type="password" name="password" placeholder="Password"
                        autocomplete="current-password" required;
                    button type="submit" { "Log in" }
                }
            }
        }
    }
}

/// The inner content of the host header (everything HTMX swaps on each update).
/// `dash` is `None` before the first snapshot arrives — then only the brand and
/// host switcher show, no tally or timestamp.
fn host_header_inner(
    dash: Option<&Dashboard>,
    host: &str,
    hosts: &[String],
    auth_enabled: bool,
) -> Markup {
    html! {
        (brand())
        (host_switch(host, hosts))
        @if let Some(d) = dash {
            (container_counts_metric(&ContainerCounts::of(&d.containers)))
        }
        span.spacer {}
        @if let Some(d) = dash {
            span.generated { "updated " (fmt_age(d.generated_at_unix_ms)) }
        }
        @if auth_enabled {
            (logout_button())
        }
    }
}

/// The header's logout control: a one-button POST form (styled as a link).
/// A GET link would let any cross-site `<img src=".../logout">` end the
/// session; a POST from elsewhere doesn't carry the SameSite=Lax cookie and
/// is turned away by the auth middleware instead.
fn logout_button() -> Markup {
    html! {
        form.logout-form method="post" action="/logout" {
            button.logout type="submit" title="Log out" { "Logout" }
        }
    }
}

/// The host switcher: one link per monitored host, the current one marked.
/// Rendered only when more than one host is configured (single-host setups have
/// nothing to switch between).
fn host_switch(current: &str, hosts: &[String]) -> Markup {
    html! {
        @if hosts.len() > 1 {
            nav.host-switch {
                @for h in hosts {
                    @if h == current {
                        span.host-tab.current { (h) }
                    } @else {
                        a.host-tab href=(format!("/host/{h}")) { (h) }
                    }
                }
            }
        }
    }
}

/// The multi-host landing page at `/`: a simple list of hosts to pick from.
/// Single-host setups never reach this (they redirect straight to the host).
fn host_index_page(hosts: &[String], auth_enabled: bool) -> Markup {
    html! {
        (DOCTYPE)
        html lang="en" {
            head {
                meta charset="utf-8";
                meta name="viewport" content="width=device-width, initial-scale=1";
                title { "DockDoe" }
                link rel="icon" type="image/svg+xml" href="/assets/dockdoe.svg"
                    media="(prefers-color-scheme: light)";
                link rel="icon" type="image/svg+xml" href="/assets/dockdoe-white.svg"
                    media="(prefers-color-scheme: dark)";
                link rel="stylesheet" href="/assets/dockdoe.css";
            }
            body {
                header.host id="host-header" {
                    (brand())
                    span.spacer {}
                    @if auth_enabled {
                        (logout_button())
                    }
                }
                main {
                    section.host-list {
                        h2 { "Hosts" }
                        ul {
                            @for h in hosts {
                                li { a href=(format!("/host/{h}")) { (h) } }
                            }
                        }
                    }
                }
            }
        }
    }
}

/// Container tally for the header, bucketed the way the badge colours are:
/// running (green), exited (red), everything else lumped as "other".
#[derive(Debug, PartialEq, Eq)]
struct ContainerCounts {
    total: usize,
    running: usize,
    exited: usize,
    other: usize,
    unhealthy: usize,
}

impl ContainerCounts {
    fn of(containers: &[ContainerMetrics]) -> Self {
        let mut counts = ContainerCounts {
            total: containers.len(),
            running: 0,
            exited: 0,
            other: 0,
            unhealthy: 0,
        };
        for c in containers {
            match c.state {
                ContainerState::Running => counts.running += 1,
                ContainerState::Exited => counts.exited += 1,
                _ => counts.other += 1,
            }
            if c.health == HealthState::Unhealthy {
                counts.unhealthy += 1;
            }
        }
        counts
    }
}

/// The header's container tally. Zero buckets are omitted ("0 exited" is
/// noise), except running — "0 running" is exactly the alarm worth seeing.
fn container_counts_metric(counts: &ContainerCounts) -> Markup {
    html! {
        div.metric {
            span.label { "Containers" }
            span.value {
                (counts.total)
                span.count-ok { " · " (counts.running) " running" }
                @if counts.exited > 0 {
                    span.count-err { " · " (counts.exited) " exited" }
                }
                @if counts.other > 0 {
                    span.count-idle { " · " (counts.other) " other" }
                }
                @if counts.unhealthy > 0 {
                    span.count-err { " · " (counts.unhealthy) " unhealthy" }
                }
            }
        }
    }
}

/// Render all containers, grouped by compose stack. Standalone containers
/// (no compose project) are grouped last under "Standalone".
fn container_section(containers: &[ContainerMetrics], cpu_count: usize, r: &Render) -> Markup {
    if containers.is_empty() {
        return html! { p.empty { "No containers found." } };
    }

    // BTreeMap keyed so that named stacks sort alphabetically and standalone
    // (None) sorts last; members within each stack are sorted by name.
    let mut groups: BTreeMap<StackKey<'_>, Vec<&ContainerMetrics>> = BTreeMap::new();
    for c in containers {
        groups.entry(stack_key(c)).or_default().push(c);
    }
    for members in groups.values_mut() {
        members.sort_by(|a, b| a.name.cmp(&b.name));
    }

    html! {
        @for (key, members) in &groups {
            @let title = match key {
                StackKey::Named(name) => *name,
                StackKey::Standalone => "Standalone",
            };
            section.stack {
                h2 {
                    @match key {
                        StackKey::Named(name) => a.stack-link href=(format!("/host/{}/stack/{name}", r.host)) { (title) },
                        StackKey::Standalone => span { (title) },
                    }
                    " " span.count { "(" (members.len()) ")" }
                }
                table {
                    (container_table_head())
                    tbody {
                        @for c in members { (container_row(c, cpu_count, r)) }
                    }
                }
            }
        }
    }
}

/// One container table row. `cpu_count` scales the CPU bar: container CPU% is
/// per-core cumulative (a busy 4-core container reads 400%), so full bar =
/// the whole host, and the bar matches what the host CPU chart would show.
fn container_row(c: &ContainerMetrics, cpu_count: usize, r: &Render) -> Markup {
    html! {
        tr {
            td.name { a href=(format!("/host/{}/container/{}", r.host, c.id)) { (c.name) } }
            td.image { (short_image(&c.image)) }
            td {
                span.badge.(state_name(c.state)) { (state_name(c.state)) }
                (health_marker(c.health))
                (port_chips(&c.ports, r.links))
            }
            td.num {
                @match c.cpu_percent {
                    Some(pct) => {
                        (format!("{pct:.1}%"))
                        (bar(pct, cpu_count.max(1) as f64 * 100.0))
                    }
                    None => span style="color:var(--muted)" { "" }
                }
            }
            td.num {
                @match c.mem_used {
                    Some(used) => {
                        (fmt_bytes(used))
                        @if let Some(limit) = c.mem_limit {
                            (bar(used as f64, limit as f64))
                        }
                    }
                    None => span style="color:var(--muted)" { "" }
                }
            }
            td.actions-cell { (action_buttons(r.host, &c.id, r.read_only)) }
        }
    }
}

/// Start/stop/restart buttons for one container. Stateless so it can be reused
/// verbatim in the row and as the HTMX response after an action. Destructive
/// actions ask for confirmation.
fn action_buttons(host: &str, id: &str, read_only: bool) -> Markup {
    html! {
        span.actions title=[read_only.then_some("host is read-only")] {
            button.act.start type="button" disabled[read_only]
                hx-post=(format!("/host/{host}/api/container/{id}/start"))
                hx-target="closest .actions" hx-swap="outerHTML"
                title="Start" { "" }
            button.act.restart type="button" disabled[read_only]
                hx-post=(format!("/host/{host}/api/container/{id}/restart"))
                hx-target="closest .actions" hx-swap="outerHTML"
                hx-confirm="Restart this container?"
                title="Restart" { "" }
            button.act.stop type="button" disabled[read_only]
                hx-post=(format!("/host/{host}/api/container/{id}/stop"))
                hx-target="closest .actions" hx-swap="outerHTML"
                hx-confirm="Stop this container?"
                title="Stop" { "" }
        }
    }
}

/// A horizontal fill bar; turns amber above 70% and red above 90%.
fn bar(value: f64, max: f64) -> Markup {
    let ratio = if max > 0.0 {
        (value / max).clamp(0.0, 1.0)
    } else {
        0.0
    };
    let pct = ratio * 100.0;
    let class = if ratio >= 0.9 {
        "bar err"
    } else if ratio >= 0.7 {
        "bar warn"
    } else {
        "bar"
    };
    html! {
        span class=(class) { span style=(format!("width:{pct:.1}%")) {} }
    }
}

fn health_marker(health: HealthState) -> Markup {
    let (class, label) = match health {
        HealthState::Healthy => ("healthy", "● healthy"),
        HealthState::Unhealthy => ("unhealthy", "● unhealthy"),
        HealthState::Starting => ("starting", "● starting"),
        HealthState::None => return html! {},
    };
    html! { span class=(format!("health {class}")) { (label) } }
}

/// All ports for the container detail page: every published port as a blue
/// link to the browsing host, every internal-only port as a muted,
/// non-clickable pill. Renders nothing when the container exposes no ports.
fn port_pills(ports: &[Port], links: &PortLinks) -> Markup {
    if ports.is_empty() {
        return html! {};
    }
    html! {
        span.ports {
            @for p in ports {
                @match p.public {
                    Some(_) => (port_link(p, true, links)),
                    None => span.port-pill.muted
                        title="exposed inside Docker, not published to the host" {
                        (p.private) (proto_suffix(&p.proto))
                    },
                }
            }
        }
    }
}

/// Compact published-port chips for the dense tables: the first two host ports
/// as links, any remainder collapsed into a neutral "+N" chip (the rest are
/// listed in its tooltip). Internal-only ports are omitted here — they show on
/// the detail page. Renders nothing without any published port.
fn port_chips(ports: &[Port], links: &PortLinks) -> Markup {
    const SHOWN: usize = 2;
    let published: Vec<&Port> = ports.iter().filter(|p| p.public.is_some()).collect();
    if published.is_empty() {
        return html! {};
    }
    html! {
        span.ports {
            @for p in published.iter().take(SHOWN) { (port_link(p, false, links)) }
            @if published.len() > SHOWN {
                span.port-more title=(overflow_list(&published[SHOWN..])) {
                    "+" (published.len() - SHOWN)
                }
            }
        }
    }
}

/// A blue pill for one published port. `full` adds the "→ container-port" detail
/// used on the container page; the dense tables show only the host port.
///
/// Whether it is a link, and to where, follows the host's [`PortLinks`]:
/// - [`PortLinks::Browser`]: a `localhost` href plus `data-port`, which live.js
///   rewrites to the actual browsing host (the only place the real hostname is
///   known).
/// - [`PortLinks::Host`]: a link straight to the configured host — for when the
///   browsing host is a proxy but the Docker host is reachable directly.
/// - [`PortLinks::Off`]: an unlinked pill, for proxy-only setups where no direct
///   `host:port` link works.
fn port_link(p: &Port, full: bool, links: &PortLinks) -> Markup {
    let public = p.public.expect("port_link called on an unpublished port");
    let title = format!("host {public} → container {}/{}", p.private, p.proto);
    let label = html! {
        (public)
        @if full { "" (p.private) }
        (proto_suffix(&p.proto))
    };
    match links {
        PortLinks::Off => html! {
            span.port-pill title=(title) { (label) }
        },
        PortLinks::Host(host) => html! {
            a.port-pill target="_blank" rel="noopener"
                href=(format!("http://{host}:{public}")) title=(title) { (label) }
        },
        PortLinks::Browser => html! {
            a.port-pill data-port=(public) target="_blank" rel="noopener"
                href=(format!("http://localhost:{public}")) title=(title) { (label) }
        },
    }
}

/// "/udp" / "/sctp" suffix for non-TCP ports; empty for plain TCP, which is the
/// overwhelming default and would only add noise.
fn proto_suffix(proto: &str) -> String {
    if proto == "tcp" {
        String::new()
    } else {
        format!("/{proto}")
    }
}

/// Space-separated list of published ports for the "+N" chip's tooltip.
fn overflow_list(rest: &[&Port]) -> String {
    rest.iter()
        .filter_map(|p| {
            p.public
                .map(|public| format!("{public}{}", proto_suffix(&p.proto)))
        })
        .collect::<Vec<_>>()
        .join("  ")
}

/// Key that sorts named stacks alphabetically before standalone containers.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
enum StackKey<'a> {
    Named(&'a str),
    Standalone,
}

/// A container state's name, used both as the badge's CSS class and as its
/// visible label (they are the same word for every state).
fn state_name(state: ContainerState) -> &'static str {
    match state {
        ContainerState::Running => "running",
        ContainerState::Exited => "exited",
        ContainerState::Dead => "dead",
        ContainerState::Paused => "paused",
        ContainerState::Restarting => "restarting",
        ContainerState::Stopping => "stopping",
        ContainerState::Removing => "removing",
        ContainerState::Created => "created",
        ContainerState::Unknown => "unknown",
    }
}

/// Strip a registry/tag down to a readable image name.
fn short_image(image: &str) -> &str {
    image.rsplit('/').next().unwrap_or(image)
}

/// Format a byte count with binary units.
fn fmt_bytes(bytes: u64) -> String {
    const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
    let mut value = bytes as f64;
    let mut unit = 0;
    while value >= 1024.0 && unit < UNITS.len() - 1 {
        value /= 1024.0;
        unit += 1;
    }
    if unit == 0 {
        format!("{bytes} B")
    } else {
        format!("{value:.1} {}", UNITS[unit])
    }
}

/// Render how long ago a Unix-ms timestamp was, relative to now. This backs
/// the header's staleness hint, so the far end matters most: a collector that
/// has been stuck for days must read as "3d ago", not "4320m ago".
fn fmt_age(unix_ms: u64) -> String {
    fmt_age_secs(now_unix_ms().saturating_sub(unix_ms) / 1000)
}

fn fmt_age_secs(secs: u64) -> String {
    match secs {
        0 => "just now".to_string(),
        s if s < 60 => format!("{s}s ago"),
        s if s < 3600 => format!("{}m ago", s / 60),
        s if s < 86_400 => format!("{}h ago", s / 3600),
        s => format!("{}d ago", s / 86_400),
    }
}

fn now_unix_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
}

fn now_unix_secs() -> u64 {
    now_unix_ms() / 1000
}

fn duration_ms(d: Duration) -> u64 {
    u64::try_from(d.as_millis()).unwrap_or(u64::MAX)
}

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

    #[test]
    fn bearer_token_parses_only_the_bearer_scheme() {
        let with = |value: &str| {
            let mut h = HeaderMap::new();
            h.insert(header::AUTHORIZATION, value.parse().unwrap());
            h
        };
        assert_eq!(bearer_token(&with("Bearer hub-secret")), Some("hub-secret"));
        // Other schemes (e.g. Basic from an auth proxy) are not ours to judge.
        assert_eq!(bearer_token(&with("Basic dXNlcjpwdw==")), None);
        assert_eq!(bearer_token(&with("bearer hub-secret")), None);
        assert_eq!(bearer_token(&with("Bearer")), None);
        assert_eq!(bearer_token(&HeaderMap::new()), None);
    }

    #[test]
    fn port_links_from_config_resolves_each_case() {
        let unix = "unix:///var/run/docker.sock";
        let host = |pub_host, url| match PortLinks::from_config(pub_host, url) {
            PortLinks::Host(h) => h,
            other => panic!("expected Host, got {other:?}"),
        };

        // An explicit public_host wins over the endpoint URL.
        assert!(matches!(
            PortLinks::from_config(Some("off"), unix),
            PortLinks::Off
        ));
        assert!(matches!(
            PortLinks::from_config(Some("OFF"), unix),
            PortLinks::Off
        ));
        assert!(matches!(
            PortLinks::from_config(Some("none"), unix),
            PortLinks::Off
        ));
        assert!(matches!(
            PortLinks::from_config(Some("-"), unix),
            PortLinks::Off
        ));
        assert_eq!(host(Some(" 192.168.1.50 "), unix), "192.168.1.50");

        // No usable public_host: a unix socket falls back to the browsing host.
        assert!(matches!(
            PortLinks::from_config(None, unix),
            PortLinks::Browser
        ));
        assert!(matches!(
            PortLinks::from_config(Some(""), unix),
            PortLinks::Browser
        ));
        assert!(matches!(
            PortLinks::from_config(Some("  "), unix),
            PortLinks::Browser
        ));

        // No public_host: derive from a tcp/http/https endpoint's host.
        assert_eq!(host(None, "tcp://nas.lan:2375"), "nas.lan");
        assert_eq!(
            host(None, "https://docker.example.com:2376/"),
            "docker.example.com"
        );
        assert_eq!(host(None, "http://10.0.0.5:2375"), "10.0.0.5");
        assert_eq!(host(None, "tcp://[::1]:2375"), "::1");
    }

    #[test]
    fn fmt_bytes_uses_binary_units() {
        assert_eq!(fmt_bytes(512), "512 B");
        assert_eq!(fmt_bytes(1024), "1.0 KiB");
        assert_eq!(fmt_bytes(1_572_864), "1.5 MiB");
        assert_eq!(fmt_bytes(2 * 1024 * 1024 * 1024), "2.0 GiB");
    }

    #[test]
    fn strip_ansi_removes_escape_sequences() {
        // Colour codes around text are removed, text kept.
        assert_eq!(strip_ansi("\u{1b}[31mred\u{1b}[0m text"), "red text");
        // Multi-line plain text is untouched.
        assert_eq!(strip_ansi("line1\nline2\n"), "line1\nline2\n");
        // Cursor/clear sequences are removed too.
        assert_eq!(strip_ansi("a\u{1b}[2Kb"), "ab");
        // A bare ESC without CSI doesn't eat following text.
        assert_eq!(strip_ansi("ok"), "ok");
    }

    #[test]
    fn resolve_history_handles_named_ranges_and_custom_windows() {
        // No `Duration::from_hours` on stable; same trade-off as in docker.rs.
        #[allow(clippy::duration_suboptimal_units)]
        let seed_window = Duration::from_secs(3600);
        let named = |range: &str| HistoryQuery {
            range: Some(range.to_string()),
            since_ms: None,
            until_ms: None,
        };
        let window = |since: u64, until: u64| HistoryQuery {
            range: None,
            since_ms: Some(since),
            until_ms: Some(until),
        };

        // 1h fits the raw retention → raw samples, full resolution.
        let w = resolve_history(&named("1h"), seed_window).unwrap();
        assert!(w.raw);
        assert_eq!(w.group_ms, 60_000);
        // 30d exceeds it → trend buckets, downsampled to 30 min groups.
        let w = resolve_history(&named("30d"), seed_window).unwrap();
        assert!(!w.raw);
        assert_eq!(w.group_ms, 1_800_000);
        assert!(w.since <= now_unix_ms() - 29 * 24 * 3_600_000);

        // A recent custom window is served raw, an older one from trends.
        let now = now_unix_ms();
        let w = resolve_history(&window(now - 600_000, now), seed_window).unwrap();
        assert!(w.raw);
        let w = resolve_history(&window(now - 86_400_000, now - 7_200_000), seed_window).unwrap();
        assert!(!w.raw);
        assert_eq!(w.until, now - 7_200_000);

        // Rejected: unknown name, inverted window, range+window mix, nothing.
        assert!(resolve_history(&named("2y"), seed_window).is_none());
        assert!(resolve_history(&window(50, 10), seed_window).is_none());
        let mut mixed = named("1h");
        mixed.since_ms = Some(0);
        mixed.until_ms = Some(10);
        assert!(resolve_history(&mixed, seed_window).is_none());
        assert!(
            resolve_history(
                &HistoryQuery {
                    range: None,
                    since_ms: None,
                    until_ms: None
                },
                seed_window
            )
            .is_none()
        );
    }

    #[test]
    fn group_for_window_targets_whole_buckets() {
        // Up to 24h: one point per 60s trend bucket.
        assert_eq!(group_for_window(3_600_000), 60_000);
        assert_eq!(group_for_window(86_400_000), 60_000);
        // 7d → 7min groups, 30d → 30min groups (≤ ~1440 points each).
        assert_eq!(group_for_window(7 * 86_400_000), 420_000);
        assert_eq!(group_for_window(30 * 86_400_000), 1_800_000);
        // Degenerate windows never yield a zero group.
        assert_eq!(group_for_window(0), 60_000);
    }

    #[test]
    fn fmt_age_scales_units_up_to_days() {
        assert_eq!(fmt_age_secs(0), "just now");
        assert_eq!(fmt_age_secs(1), "1s ago");
        assert_eq!(fmt_age_secs(59), "59s ago");
        assert_eq!(fmt_age_secs(60), "1m ago");
        assert_eq!(fmt_age_secs(3_599), "59m ago");
        // The header hint for a long-stuck collector must not read "4320m ago".
        assert_eq!(fmt_age_secs(3_600), "1h ago");
        assert_eq!(fmt_age_secs(86_399), "23h ago");
        assert_eq!(fmt_age_secs(3 * 86_400), "3d ago");
    }

    #[test]
    fn raw_group_caps_points_but_keeps_short_windows_exact() {
        // The raw path serves full-resolution samples; the group must cap what
        // a window can return even when `raw_retention_secs` is raised to days
        // (a 7d window at a 3s interval would otherwise be ~200k JSON points).
        for window_ms in [3_600_000, 86_400_000, 7 * 86_400_000] {
            let points = window_ms / raw_group_for_window(window_ms);
            assert!(
                points <= 1_441,
                "{window_ms}ms window may yield {points} raw points"
            );
        }
        // A short drill-down window's group stays below any realistic sample
        // interval, so its samples pass through at full resolution.
        assert!(raw_group_for_window(600_000) < 1_000);
        // Degenerate windows never yield a zero group.
        assert_eq!(raw_group_for_window(0), 1);
    }

    #[test]
    fn split_log_timestamp_extracts_daemon_prefix() {
        // The daemon's nanosecond timestamp is recognised and split off.
        assert_eq!(
            split_log_timestamp("2026-06-12T10:15:30.123456789Z hello world"),
            Some(("2026-06-12T10:15:30.123456789Z", "hello world"))
        );
        // Seconds-precision (no fractional part) works too.
        assert_eq!(
            split_log_timestamp("2026-06-12T10:15:30Z msg"),
            Some(("2026-06-12T10:15:30Z", "msg"))
        );
        // Lines without the prefix are left alone.
        assert_eq!(split_log_timestamp("plain log line"), None);
        assert_eq!(split_log_timestamp(""), None);
        // A first word that merely resembles a timestamp is rejected.
        assert_eq!(split_log_timestamp("2026-06-12T10:15:30 msg"), None);
        assert_eq!(split_log_timestamp("not-a-timestamp-atallZ msg"), None);
    }

    #[test]
    fn render_log_lines_wraps_timestamps_in_spans() {
        let html = render_log_lines("2026-06-12T10:15:30.5Z started\nplain line\n").into_string();
        // Timestamp lands in a span with a seconds-precision data-ts…
        assert!(html.contains(r#"<span class="log-ts" data-ts="2026-06-12T10:15:30Z">"#));
        assert!(html.contains("2026-06-12 10:15:30</span> started\n"));
        // …while prefix-less lines pass through untouched.
        assert!(html.contains("plain line\n"));
    }

    #[test]
    fn short_image_strips_registry() {
        assert_eq!(
            short_image("docker.io/library/nginx:latest"),
            "nginx:latest"
        );
        assert_eq!(short_image("redis:7"), "redis:7");
    }

    #[test]
    fn clamp_since_caps_the_lookback_window() {
        // No `Duration::from_hours` on stable; same trade-off as in docker.rs.
        #[allow(clippy::duration_suboptimal_units)]
        let window = Duration::from_secs(3600);
        let floor = now_unix_ms() - 3_600_000;
        // A zero/ancient client value is raised to the window floor…
        assert!(clamp_since(0, window) >= floor);
        // …while a recent value passes through unchanged.
        let recent = now_unix_ms() - 1_000;
        assert_eq!(clamp_since(recent, window), recent);
    }

    #[test]
    fn htmx_header_is_required_verbatim() {
        let mut headers = HeaderMap::new();
        assert!(!is_htmx_request(&headers));
        headers.insert("hx-request", "false".parse().unwrap());
        assert!(!is_htmx_request(&headers));
        headers.insert("hx-request", "true".parse().unwrap());
        assert!(is_htmx_request(&headers));
    }

    #[test]
    fn host_without_port_handles_ipv4_ipv6_and_bare_names() {
        assert_eq!(host_without_port("example.com:8080"), "example.com");
        assert_eq!(host_without_port("example.com"), "example.com");
        assert_eq!(host_without_port("127.0.0.1:8080"), "127.0.0.1");
        assert_eq!(host_without_port("[::1]:8080"), "::1");
        assert_eq!(host_without_port("[2001:db8::1]"), "2001:db8::1");
    }

    #[test]
    fn host_allowlist_permits_localhost_and_configured_names_only() {
        let allowed = normalize_allowed_hosts(&[" DockHost.lan:8080 ".to_string()]);
        let host = |value: &str| {
            let mut headers = HeaderMap::new();
            headers.insert(header::HOST, value.parse().unwrap());
            headers
        };

        // Disabled check lets anything through, even a missing Host header.
        assert!(host_allowed(&HeaderMap::new(), &[]));

        assert!(host_allowed(&host("dockhost.lan"), &allowed));
        assert!(host_allowed(&host("DockHost.lan:9000"), &allowed));
        assert!(host_allowed(&host("localhost:8080"), &allowed));
        assert!(host_allowed(&host("127.0.0.1"), &allowed));
        assert!(host_allowed(&host("[::1]:8080"), &allowed));

        assert!(!host_allowed(&host("attacker.example"), &allowed));
        assert!(!host_allowed(&HeaderMap::new(), &allowed));
    }

    #[test]
    fn container_counts_bucket_by_state_and_health() {
        let c = |state, health| ContainerMetrics {
            id: "x".to_string(),
            name: "c-x".to_string(),
            image: "img".to_string(),
            state,
            status: String::new(),
            health,
            stack: None,
            cpu_percent: None,
            mem_used: None,
            mem_limit: None,
            net_rx_bps: None,
            net_tx_bps: None,
            disk_read_bps: None,
            disk_write_bps: None,
            ports: Vec::new(),
        };
        let containers = [
            c(ContainerState::Running, HealthState::Healthy),
            c(ContainerState::Running, HealthState::Unhealthy),
            c(ContainerState::Exited, HealthState::None),
            c(ContainerState::Paused, HealthState::None),
            c(ContainerState::Created, HealthState::None),
        ];
        assert_eq!(
            ContainerCounts::of(&containers),
            ContainerCounts {
                total: 5,
                running: 2,
                exited: 1,
                other: 2,
                unhealthy: 1,
            }
        );
        assert_eq!(
            ContainerCounts::of(&[]),
            ContainerCounts {
                total: 0,
                running: 0,
                exited: 0,
                other: 0,
                unhealthy: 0,
            }
        );
    }

    #[test]
    fn stack_key_sorts_standalone_last() {
        let mut keys = vec![
            StackKey::Standalone,
            StackKey::Named("alpha"),
            StackKey::Named("beta"),
        ];
        keys.sort();
        assert_eq!(
            keys,
            vec![
                StackKey::Named("alpha"),
                StackKey::Named("beta"),
                StackKey::Standalone,
            ]
        );
    }

    #[test]
    fn overview_json_orders_and_escapes() {
        let c = |name: &str, stack: Option<&str>| ContainerMetrics {
            id: format!("id-{name}"),
            name: name.to_string(),
            image: "img".to_string(),
            state: ContainerState::Running,
            status: String::new(),
            health: HealthState::None,
            stack: stack.map(str::to_string),
            cpu_percent: Some(1.5),
            mem_used: Some(42),
            mem_limit: None,
            net_rx_bps: None,
            net_tx_bps: None,
            disk_read_bps: None,
            disk_write_bps: None,
            ports: Vec::new(),
        };
        let dash = Dashboard {
            generated_at_unix_ms: 1000,
            cpu_count: 4,
            containers: vec![
                c("zulu", None),
                c("web", Some("beta")),
                c("<evil>", Some("alpha")),
                c("db", Some("beta")),
            ],
        };
        let json = overview_json(&dash);
        let v: serde_json::Value = serde_json::from_str(&json).expect("valid JSON");
        let names: Vec<&str> = v["containers"]
            .as_array()
            .expect("array")
            .iter()
            .map(|e| e["name"].as_str().expect("name"))
            .collect();
        // Stacks alphabetically, members by name, standalone last.
        assert_eq!(names, ["<evil>", "db", "web", "zulu"]);
        assert_eq!(v["ts_ms"], 1000);
        assert_eq!(v["containers"][1]["cpu"], 1.5);
        assert_eq!(v["containers"][1]["mem"], 42);
        assert_eq!(v["containers"][1]["stack"], "beta");
        // No raw `<` survives — the seed can't close its <script> element.
        assert!(!json.contains('<'));
    }
}