fluxframe-cli 0.10.0

fluxframe CLI binary: list, check, run, benchmark.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
//! End-to-end runtime supervisor.
//!
//! Owns the lifetime of input/output pipelines, the processing worker
//! thread and the Ctrl-C signal handler.  Stage 1 wired `videotestsrc`
//! → effect chain → fakesink/autovideosink only; Stage 2 adds the V4L2
//! capture and v4l2loopback sink paths.
//!
//! GStreamer is intentionally absent from this module's surface: bus
//! events arrive through the typed [`fluxframe_gst::BusEvent`] enum,
//! draining is owned by [`fluxframe_gst::BusListener`], and the supervisor
//! itself only juggles `std::sync` primitives.

use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock, Weak};
use std::time::{Duration, Instant};

use fluxframe_core::context::{FrameContext, ProcessingContext};
use fluxframe_core::error::PipelineError;
use fluxframe_core::{FluxConfig, FluxError, InputDevice, Preset, SubchainKind};
use fluxframe_effects::EffectChain;
use fluxframe_gst::input::{InputParams, InputPipeline};
use fluxframe_gst::output::{OutputParams, OutputPipeline, OutputSink};
use fluxframe_gst::{BusEvent, BusListener, BusSource, LatestFrameSlot, WatchedPipeline};
use tracing::{debug, error, info, warn};

use crate::control::{
    self, Command as ControlCommand, ListenerHandle, Response as ControlResponse,
};
use crate::metrics_reporter::MetricsReporter;
use crate::preset;
use crate::runtime_metrics::RuntimeMetrics;
use crate::session::ControlSession;
use fluxframe_core::paths::ConfigBase;

/// Worker-response cap for the listener thread. The worker only polls
/// between frames; at 30 fps one cycle is ~33 ms, so 5 s is generous
/// for a `set` and tight enough to surface a wedged worker.
const WORKER_RESPONSE_TIMEOUT: Duration = Duration::from_secs(5);

/// Depth of the listener → worker command channel. Sized to absorb a
/// short burst of commands without blocking the listener.
const CONTROL_CHANNEL_DEPTH: usize = 16;

/// Depth of the worker → listener reply channel. Each command gets a
/// fresh oneshot, so depth 1 is sufficient.
const REPLY_CHANNEL_DEPTH: usize = 1;

/// Envelope passed from the listener thread to the worker: a parsed
/// command plus the channel the worker uses to send the response
/// back. Reply channel acts as a oneshot ([`REPLY_CHANNEL_DEPTH`] = 1).
pub(crate) struct ControlEnvelope {
    pub cmd: ControlCommand,
    pub reply_tx: crossbeam_channel::Sender<ControlResponse>,
}

/// Bridge from the listener's `CommandHandler` trait into the
/// worker's command channel.
struct ChannelHandler {
    tx: crossbeam_channel::Sender<ControlEnvelope>,
}

impl control::CommandHandler for ChannelHandler {
    fn handle(&self, cmd: ControlCommand) -> ControlResponse {
        let (reply_tx, reply_rx) =
            crossbeam_channel::bounded::<ControlResponse>(REPLY_CHANNEL_DEPTH);
        if self.tx.send(ControlEnvelope { cmd, reply_tx }).is_err() {
            return ControlResponse::err("worker channel closed", None);
        }
        match reply_rx.recv_timeout(WORKER_RESPONSE_TIMEOUT) {
            Ok(r) => r,
            Err(_) => ControlResponse::err(
                "worker did not respond within timeout",
                Some("the pipeline may be wedged; check the supervisor log".into()),
            ),
        }
    }
}

/// The control socket plus the receiving end of its command channel.
///
/// Owned by `commands::run` for the whole process rather than by a
/// pipeline run: runs end and restart whenever the camera goes away,
/// and the socket — with the clients connected to it — must survive
/// that. Dropping the plane unlinks the socket file.
pub(crate) struct ControlPlane {
    _listener: Option<ListenerHandle>,
    rx: Option<crossbeam_channel::Receiver<ControlEnvelope>>,
}

impl ControlPlane {
    /// Spawn the listener when `[control].enabled = true`. A bind
    /// failure is logged, not fatal: the daemon then runs without live
    /// reconfiguration.
    pub(crate) fn spawn(cfg: &FluxConfig) -> Self {
        let disabled = Self {
            _listener: None,
            rx: None,
        };
        if !cfg.control.enabled {
            return disabled;
        }
        let socket_path = cfg
            .control
            .socket_path
            .clone()
            .unwrap_or_else(control::default_socket_path);
        let (tx, rx) = crossbeam_channel::bounded::<ControlEnvelope>(CONTROL_CHANNEL_DEPTH);
        let handler = ChannelHandler { tx };
        match control::spawn(socket_path, handler) {
            Ok(handle) => Self {
                _listener: Some(handle),
                rx: Some(rx),
            },
            Err(e) => {
                warn!(error = %e, "control socket failed to bind; live-reconfig disabled");
                disabled
            }
        }
    }

    /// Receiver the worker drains commands from; `None` when the socket
    /// is disabled.
    pub(crate) fn rx(&self) -> Option<&crossbeam_channel::Receiver<ControlEnvelope>> {
        self.rx.as_ref()
    }
}

/// Short stable label for a control [`ControlCommand`] variant. Used
/// by the worker loop to tag the per-command telemetry line, so
/// elapsed time can be filtered by command kind in log queries
/// without binding payload values into the log target.
fn command_label(cmd: &ControlCommand) -> &'static str {
    match cmd {
        ControlCommand::ListPresets => "list_presets",
        ControlCommand::CurrentPreset => "current_preset",
        ControlCommand::ListEffects => "list_effects",
        ControlCommand::GetConfig { .. } => "get_config",
        ControlCommand::SetPreset { .. } => "set_preset",
        ControlCommand::Set { .. } => "set",
        ControlCommand::SetChain { .. } => "set_chain",
        ControlCommand::SetEnabled { .. } => "set_enabled",
        ControlCommand::Reload => "reload",
        ControlCommand::SavePreset => "save_preset",
        ControlCommand::SavePresetAs { .. } => "save_preset_as",
        ControlCommand::ConfigPath => "config_path",
        ControlCommand::DaemonInfo => "daemon_info",
        // `ControlCommand` is `#[non_exhaustive]` for forward-compat
        // with future wire variants. Tag unknowns explicitly so log
        // queries surface "we received something we cannot label yet".
        _ => "unknown",
    }
}

/// Answer the commands that only read the session; `None` for every
/// command that changes the preset or the chain.
///
/// Shared by [`apply_control_command`] and [`apply_offline_command`], so
/// a read-only command behaves the same with and without a running
/// pipeline.
fn apply_read_only_command(
    session: &ControlSession,
    cmd: &ControlCommand,
) -> Option<ControlResponse> {
    let response = match cmd {
        ControlCommand::ListPresets => {
            let names: Vec<&str> = session.cfg.presets.keys().map(String::as_str).collect();
            ControlResponse::ok_with(serde_json::json!(names))
        }
        ControlCommand::CurrentPreset => {
            ControlResponse::ok_with(serde_json::json!(session.active_preset_name))
        }
        ControlCommand::GetConfig { path } => {
            apply_get_config_command(&session.active_preset, path.as_deref())
        }
        ControlCommand::ListEffects => apply_list_effects_command(),
        ControlCommand::ConfigPath => apply_config_path_command(session.config_path.as_deref()),
        ControlCommand::DaemonInfo => apply_daemon_info_command(&session.cfg),
        _ => return None,
    };
    Some(response)
}

/// Answer a control command while no pipeline is running: the
/// auto-input poll, camera acquire backoff, in-place recovery.
///
/// Read-only commands are served from the session. Anything that would
/// reconfigure or rebuild the chain is refused: there is no chain to
/// apply it to, and queueing it would make the reply lie about the
/// outcome.
fn apply_offline_command(session: &ControlSession, cmd: &ControlCommand) -> ControlResponse {
    apply_read_only_command(session, cmd).unwrap_or_else(|| {
        ControlResponse::err(
            "pipeline is not running (waiting for the camera)",
            Some("read-only commands keep working; retry once the camera is back".into()),
        )
    })
}

/// Apply a single control command against the running chain. Returns
/// the response the worker hands back to the listener thread.
fn apply_control_command(
    session: &mut ControlSession,
    processing_ctx: &ProcessingContext,
    chain: &mut EffectChain,
    telemetry: &fluxframe_core::EffectTelemetry,
    cmd: ControlCommand,
) -> ControlResponse {
    if let Some(response) = apply_read_only_command(session, &cmd) {
        return response;
    }
    let ControlSession {
        cfg,
        config_path,
        config_base,
        active_preset_name,
        active_preset,
    } = session;
    let config_path = config_path.as_deref();
    match cmd {
        ControlCommand::SetPreset { name } => {
            let Some(new_preset) = cfg.presets.get(&name) else {
                let available: Vec<&str> = cfg.presets.keys().map(String::as_str).collect();
                return ControlResponse::err(
                    format!("preset '{name}' not defined"),
                    Some(format!("available: {}", available.join(", "))),
                );
            };
            let mut new_chain = match preset::build_chain(&name, new_preset, config_base) {
                Ok(c) => c,
                Err(e) => return ControlResponse::err(format!("build chain failed: {e}"), None),
            };
            if let Err(e) = new_chain.prepare_all(processing_ctx) {
                return ControlResponse::err(
                    format!("prepare failed: {e}"),
                    Some(format!(
                        "preset '{name}' parsed but did not initialise at runtime"
                    )),
                );
            }
            // Swap in the new chain; old chain is shut down on the
            // local variable.
            std::mem::swap(chain, &mut new_chain);
            if let Err(e) = new_chain.shutdown_all() {
                warn!(error = %e, "old chain shutdown reported an error");
            }
            active_preset_name.clone_from(&name);
            // Refresh the working preset copy from the source-of-truth
            // config so `current_config` / `set` see the new pipeline.
            *active_preset = new_preset.clone();
            info!(preset = %name, "control: swapped active preset");
            ControlResponse::ok()
        }
        ControlCommand::Set { path, value } => {
            apply_set_command(chain, active_preset, config_base, &path, value)
        }
        ControlCommand::SetChain {
            section,
            chain: new_names,
        } => apply_set_chain_command(
            chain,
            active_preset,
            telemetry,
            section,
            &new_names,
            config_base,
        ),
        ControlCommand::SetEnabled {
            section,
            effect,
            enabled,
        } => apply_set_enabled_command(chain, active_preset, telemetry, section, &effect, enabled),
        ControlCommand::Reload => apply_reload_command(
            cfg,
            config_path,
            processing_ctx,
            chain,
            active_preset_name,
            active_preset,
        ),
        ControlCommand::SavePreset => {
            apply_save_preset_command(cfg, config_path, active_preset_name, active_preset)
        }
        ControlCommand::SavePresetAs { name } => {
            apply_save_preset_as_command(cfg, config_path, active_preset, &name)
        }
        // `ControlCommand` is `#[non_exhaustive]`; a future variant
        // that this build does not yet handle gets a structured
        // error rather than panicking the worker thread.
        _ => ControlResponse::err(
            "unknown command — daemon was built without support for this wire variant",
            Some("update the daemon, or check the client is not ahead of the daemon".into()),
        ),
    }
}

/// Persist the in-memory active preset back into the operator's
/// TOML config file. The runtime mirror in `cfg.presets` is refreshed
/// so a subsequent `Reload` sees consistent state (otherwise a Reload
/// right after a Save would silently revert the unsaved in-memory
/// edits that landed via `Set` since the last load).
fn apply_save_preset_command(
    cfg: &mut FluxConfig,
    config_path: Option<&std::path::Path>,
    active_preset_name: &str,
    active_preset: &Preset,
) -> ControlResponse {
    let Some(path) = config_path else {
        return ControlResponse::err(
            "daemon has no writable config path",
            Some(
                "restart the daemon with --config <PATH> or without --no-default-config to enable Save"
                    .into(),
            ),
        );
    };
    if let Err(e) = crate::persist::save_preset(path, active_preset_name, active_preset) {
        return ControlResponse::err(
            format!("save failed: {e}"),
            Some(format!("path: {}", path.display())),
        );
    }
    cfg.presets
        .insert(active_preset_name.to_string(), active_preset.clone());
    info!(
        path = %path.display(),
        preset = %active_preset_name,
        "control: saved active preset to disk",
    );
    ControlResponse::ok()
}

/// Persist the active preset under a new name. Inserts the new
/// preset into the in-memory `cfg.presets` mirror so a follow-up
/// `ListPresets` reflects the new entry immediately.
fn apply_save_preset_as_command(
    cfg: &mut FluxConfig,
    config_path: Option<&std::path::Path>,
    active_preset: &Preset,
    new_name: &str,
) -> ControlResponse {
    let Some(path) = config_path else {
        return ControlResponse::err(
            "daemon has no writable config path",
            Some(
                "restart the daemon with --config <PATH> or without --no-default-config to enable Save"
                    .into(),
            ),
        );
    };
    // Race with the in-memory mirror: a preset that already exists in
    // the running daemon (e.g. one defined in the TOML at startup, or
    // created earlier via another SavePresetAs) must not be silently
    // overwritten. `persist::save_preset_as` already checks the
    // on-disk file, but we mirror that check against the in-memory
    // state so the operator gets the same answer when the file was
    // edited externally between the load and this command.
    if cfg.presets.contains_key(new_name) {
        return ControlResponse::err(
            format!("preset '{new_name}' already exists"),
            Some("pick a different name or use Save to overwrite the active preset".into()),
        );
    }
    if let Err(e) = crate::persist::save_preset_as(path, new_name, active_preset) {
        return ControlResponse::err(
            format!("save-as failed: {e}"),
            Some(format!("path: {}", path.display())),
        );
    }
    cfg.presets
        .insert(new_name.to_string(), active_preset.clone());
    info!(
        path = %path.display(),
        preset = %new_name,
        "control: saved active preset under new name",
    );
    ControlResponse::ok()
}

/// Report the daemon's writable config path (or `null`) so the GUI
/// can show "Saves to: …" and grey out the Save button when the
/// daemon was started without a resolvable config target.
fn apply_config_path_command(config_path: Option<&std::path::Path>) -> ControlResponse {
    match config_path {
        Some(p) => ControlResponse::ok_with(serde_json::json!({ "path": p })),
        None => ControlResponse::ok_with(serde_json::Value::Null),
    }
}

/// Apply `daemon_info`: where the processed video is published, so a
/// client (the GUI preview) does not have to guess the device.
fn apply_daemon_info_command(cfg: &FluxConfig) -> ControlResponse {
    use fluxframe_core::{DaemonInfo, OutputInfo};

    let output = match classify_output(cfg) {
        OutputSpec::V4l2(device) => OutputInfo::V4l2 { device },
        OutputSpec::Pipewire(node) => OutputInfo::Pipewire { node },
        OutputSpec::Auto => OutputInfo::Auto,
        OutputSpec::Fake => OutputInfo::Fakesink,
        OutputSpec::Unsupported(device) => {
            return ControlResponse::err(format!("output '{device}' is not supported"), None);
        }
    };
    match serde_json::to_value(DaemonInfo { output }) {
        Ok(data) => ControlResponse::ok_with(data),
        Err(e) => ControlResponse::err(format!("serialise failed: {e}"), None),
    }
}

/// Walk the three sub-chain registries and return their full metadata
/// inventory keyed by section. The GUI uses this on startup to build
/// param widgets without hard-coding which effects exist.
///
/// The response also includes a `build_features` array of strings
/// (e.g. `["ml", "image-fill"]`) so the GUI can distinguish a slim
/// daemon (which yields `post = []` and may omit `image_fill` from
/// the plane registry) from a full daemon that happens to have those
/// entries unconfigured. The JSON shape would otherwise be ambiguous.
///
/// Under a slim build (`--no-default-features`) `image_fill` is absent
/// from the plane registry and therefore from the response, which is
/// the correct behaviour: the GUI should only offer effects the daemon
/// can actually instantiate.
///
/// The payload is built once per process and cached in a file-local
/// `OnceLock<serde_json::Value>` — effect metadata is fully static,
/// and this handler runs on the hot worker thread between frames
/// (~33 ms budget at 30 fps).  Subsequent calls clone the cached
/// `Value` instead of rebuilding three `Vec<&EffectMetadata>` and
/// re-serialising them.  Exactly one cfg branch is active per build,
/// so the cache covers both ml and slim configurations.
fn apply_list_effects_command() -> ControlResponse {
    static CACHE: OnceLock<serde_json::Value> = OnceLock::new();
    let payload = CACHE.get_or_init(|| {
        use fluxframe_effects::{mask_effects, plane_effects};

        let mask: Vec<_> = mask_effects::default_registry().iter_metadata().collect();
        let background: Vec<_> = plane_effects::default_registry().iter_metadata().collect();
        // foreground and background currently share the same plane
        // registry; if that changes (e.g. foreground-only effects),
        // split the call site and update the GUI contract.
        let foreground = background.clone();
        // Post effects exist only when the `ml` feature is enabled
        // (the composite path itself is ml-gated). Under a slim build
        // the section is reported empty so the GUI knows not to offer
        // post-effect editing.
        #[cfg(feature = "ml")]
        let post: Vec<_> = fluxframe_effects::post_effects::default_registry()
            .iter_metadata()
            .collect();
        #[cfg(not(feature = "ml"))]
        let post: Vec<&'static fluxframe_core::EffectMetadata> = Vec::new();

        // Build-feature inventory: lets the GUI distinguish a slim
        // daemon from a full one without inferring it from the
        // (possibly empty) effect lists. `mut` is conditional because
        // under a fully-slim build no `push` is reachable.
        #[allow(
            unused_mut,
            reason = "slim build leaves `features` empty; mut is needed when any feature is enabled"
        )]
        let mut features: Vec<&'static str> = Vec::new();
        #[cfg(feature = "ml")]
        features.push("ml");
        #[cfg(feature = "image-fill")]
        features.push("image-fill");

        serde_json::json!({
            "mask": mask,
            "background": background,
            "foreground": foreground,
            "post": post,
            "build_features": features,
        })
    });
    ControlResponse::ok_with(payload.clone())
}

/// Apply `reload`. Re-reads the TOML file from disk, validates it,
/// re-binds the daemon's `cfg`, then rebuilds the currently-active
/// preset (looking up the same name in the new config). CLI
/// overrides are NOT re-applied — they were captured at startup and
/// remain in effect through `working_cfg`.
fn apply_reload_command(
    cfg: &mut FluxConfig,
    config_path: Option<&std::path::Path>,
    processing_ctx: &ProcessingContext,
    chain: &mut EffectChain,
    active_preset_name: &mut String,
    active_preset: &mut Preset,
) -> ControlResponse {
    let Some(path) = config_path else {
        return ControlResponse::err(
            "no config path provided at startup",
            Some("pass --config <PATH> on the command line to enable reload".into()),
        );
    };
    let new_cfg = match crate::config_merge::load(Some(path)) {
        Ok(c) => c,
        Err(e) => {
            return ControlResponse::err(
                format!("re-read failed: {e}"),
                Some(format!("path: {}", path.display())),
            );
        }
    };
    if let Err(e) = new_cfg.validate() {
        return ControlResponse::err(format!("validation failed: {e}"), None);
    }
    let Some(new_preset) = new_cfg.presets.get(active_preset_name) else {
        let available: Vec<&str> = new_cfg.presets.keys().map(String::as_str).collect();
        return ControlResponse::err(
            format!("active preset '{active_preset_name}' is gone from the reloaded config"),
            Some(format!(
                "available presets after reload: {}",
                available.join(", ")
            )),
        );
    };
    let config_base = ConfigBase::for_config(Some(path));
    let mut new_chain = match preset::build_chain(active_preset_name, new_preset, &config_base) {
        Ok(c) => c,
        Err(e) => return ControlResponse::err(format!("build chain failed: {e}"), None),
    };
    if let Err(e) = new_chain.prepare_all(processing_ctx) {
        return ControlResponse::err(
            format!("prepare on reloaded chain failed: {e}"),
            Some("the live chain is unchanged".into()),
        );
    }
    std::mem::swap(chain, &mut new_chain);
    if let Err(e) = new_chain.shutdown_all() {
        warn!(error = %e, "old chain shutdown reported an error during reload");
    }
    *active_preset = new_preset.clone();
    *cfg = new_cfg;
    info!(path = %path.display(), preset = %active_preset_name, "control: reloaded config from disk");
    ControlResponse::ok()
}

/// Apply `get_config { path }`. With `path = None`, serialise the
/// whole active preset; otherwise walk the dot-path into the JSON
/// representation and return that subtree.
fn apply_get_config_command(active_preset: &Preset, path: Option<&str>) -> ControlResponse {
    let full = match serde_json::to_value(active_preset) {
        Ok(v) => v,
        Err(e) => return ControlResponse::err(format!("serialise failed: {e}"), None),
    };
    let Some(path) = path else {
        return ControlResponse::ok_with(full);
    };
    // Walk dot-path into the serialised value. Components must exist
    // as object keys at each step.
    let mut current = &full;
    for component in path.split('.') {
        if component.is_empty() {
            return ControlResponse::err(format!("empty component in path '{path}'"), None);
        }
        match current.get(component) {
            Some(v) => current = v,
            None => {
                return ControlResponse::err(
                    format!("path '{path}' has no value at '{component}'"),
                    None,
                );
            }
        }
    }
    ControlResponse::ok_with(current.clone())
}

/// Apply a `set <path> <value>` command. Parses the dot-path,
/// converts the JSON value to TOML, merges the field into the active
/// preset's `per_effect[effect]` table, builds a fresh `RawEffectParams`
/// from the merged table, and calls into the chain's named-effect
/// reconfiguration.
fn apply_set_command(
    chain: &mut EffectChain,
    active_preset: &mut Preset,
    config_base: &ConfigBase,
    path: &str,
    value: serde_json::Value,
) -> ControlResponse {
    let set_path = match crate::control::commands::parse_set_path(path) {
        Ok(p) => p,
        Err(e) => return ControlResponse::err(e, None),
    };
    if set_path.field == fluxframe_core::EFFECT_ENABLED_KEY {
        return ControlResponse::err(
            format!(
                "`{}` is not an effect parameter",
                fluxframe_core::EFFECT_ENABLED_KEY
            ),
            Some("use set_enabled to switch an effect on or off".into()),
        );
    }
    let toml_value = match crate::control::commands::json_to_toml(value) {
        Ok(v) => v,
        Err(e) => return ControlResponse::err(e, None),
    };
    // `was_absent` lets the Err arm below revert a section materialised
    // purely on behalf of a doomed Set.
    let (section_mut, was_absent) = match set_target_section(active_preset, set_path.section) {
        Ok(target) => target,
        Err(response) => return response,
    };
    // Read the existing per-effect table for this effect (defaulting
    // to empty), insert the new field, then hand the merged table to
    // the chain for reconfiguration. On failure we revert the in-memory
    // copy AND re-call reconfigure with the ORIGINAL params so the
    // live effect's `self.config` matches what we kept in memory —
    // important for effects with lazy reload (image_fill, blur) that
    // pick up the new config on the next `process()`.
    let original_entry = section_mut.per_effect.get(&set_path.effect).cloned();
    let mut effect_table = match original_entry.clone() {
        Some(toml::Value::Table(t)) => t,
        _ => toml::Table::new(),
    };
    effect_table.insert(set_path.field.clone(), toml_value);
    let merged_entry = toml::Value::Table(effect_table);
    let metadata = effect_metadata(set_path.section, &set_path.effect);
    let result = live_effect_params(&set_path.effect, Some(&merged_entry), metadata, config_base)
        .and_then(|params| {
            chain.reconfigure_named_effect(set_path.section, &set_path.effect, params)
        });
    section_mut
        .per_effect
        .insert(set_path.effect.clone(), merged_entry);
    match result {
        Ok(()) => {
            info!(
                section = %set_path.section,
                effect = %set_path.effect,
                field = %set_path.field,
                "control: live-reconfigured effect"
            );
            ControlResponse::ok()
        }
        Err(e) => {
            tracing::debug!(
                section = %set_path.section,
                effect = %set_path.effect,
                field = %set_path.field,
                error = %e,
                "control: set rejected",
            );
            // Revert the in-memory copy.
            match &original_entry {
                Some(v) => {
                    section_mut
                        .per_effect
                        .insert(set_path.effect.clone(), v.clone());
                }
                None => {
                    section_mut.per_effect.remove(&set_path.effect);
                }
            }
            // Best-effort revert of the live effect: reconfigure with
            // the ORIGINAL params so an effect that already swapped
            // its `self.config` rolls back. Replay `original_entry` (or
            // an empty table). If this second call also fails, log a
            // warn — we cannot do better without tearing the chain down.
            let revert = live_effect_params(
                &set_path.effect,
                original_entry.as_ref(),
                metadata,
                config_base,
            )
            .and_then(|params| {
                chain.reconfigure_named_effect(set_path.section, &set_path.effect, params)
            });
            if let Err(revert_err) = revert {
                warn!(
                    section = %set_path.section,
                    effect = %set_path.effect,
                    error = %revert_err,
                    "control: revert reconfigure also failed; live effect may be in an inconsistent state",
                );
            }
            // If we materialised the section purely to host this doomed
            // Set, undo the materialisation. We only do this when the
            // section is now empty (no chain, no per_effect entries
            // besides the one we just removed) — a non-empty section
            // means someone else populated it concurrently or the Set
            // partially succeeded, and we should leave it alone.
            revert_absent_section_if_empty(active_preset, set_path.section, was_absent);
            effect_error_response(&e)
        }
    }
}

/// The sub-section of `preset` a `set` writes into, and whether it was
/// absent before the call.
///
/// Plane and post sections are materialised on demand. A missing mask is
/// an error pointing at a preset with `[mask]`: the composite needs an
/// ONNX model the control protocol cannot supply.
fn set_target_section(
    preset: &mut Preset,
    section: SubchainKind,
) -> Result<(&mut fluxframe_core::PipelineSection, bool), ControlResponse> {
    let was_absent = section_is_absent(preset, section);
    if section != SubchainKind::Mask {
        return Ok((
            ensure_plane_or_post_section_mut(preset, section),
            was_absent,
        ));
    }
    mask_section_mut(preset)
        .map(|mask| (mask, was_absent))
        .ok_or_else(|| {
            ControlResponse::err(
                "preset does not have a [mask] sub-section",
                Some(
                    "this preset has no segmentation; switch to a preset with [mask] to add post-process effects"
                        .into(),
                ),
            )
        })
}

/// Parameters a live effect is reconfigured with for its preset table
/// `table`: the table without the `enabled` flag, which is not an
/// effect parameter, with relative path parameters resolved against
/// `config_base`. An absent table yields an empty one, so the effect's
/// serde defaults apply.
fn live_effect_params(
    effect: &str,
    table: Option<&toml::Value>,
    metadata: Option<&fluxframe_core::EffectMetadata>,
    config_base: &ConfigBase,
) -> Result<fluxframe_core::traits::RawEffectParams, fluxframe_core::EffectError> {
    let (_, mut params) = fluxframe_core::split_effect_table(effect, table)?;
    if let Some(metadata) = metadata {
        fluxframe_core::resolve_path_params(&mut params, metadata, config_base);
    }
    Ok(toml::Value::Table(params))
}

/// Metadata of effect `name` in the registry of `section`; `None` when
/// the effect is not registered there (the chain rejects it itself).
fn effect_metadata(
    section: SubchainKind,
    name: &str,
) -> Option<&'static fluxframe_core::EffectMetadata> {
    match section {
        SubchainKind::Mask => fluxframe_effects::mask_effects::default_registry().metadata(name),
        SubchainKind::Background | SubchainKind::Foreground => {
            fluxframe_effects::plane_effects::default_registry().metadata(name)
        }
        #[cfg(feature = "ml")]
        SubchainKind::Post => fluxframe_effects::post_effects::default_registry().metadata(name),
        #[cfg(not(feature = "ml"))]
        SubchainKind::Post => None,
    }
}

/// Mutable handle to the `[mask]` sub-section of `preset`. Returns
/// `None` when the preset declares no mask — the mask section is the
/// only sub-section that **cannot** be materialised on demand because
/// the composite requires an ONNX model that the control protocol
/// has no way to synthesise.
fn mask_section_mut(preset: &mut Preset) -> Option<&mut fluxframe_core::PipelineSection> {
    preset.mask.as_mut()
}

/// Mutable handle to a plane (Background/Foreground) or Post
/// sub-section, creating it from `PipelineSection::default()` if
/// absent. Used by [`apply_set_chain_command`] so the control protocol
/// can extend a preset with a section it did not originally declare in
/// TOML (e.g. add a `[post]` chain to a preset that only had
/// `[mask]` + `[background]`).
///
/// **Caller MUST be prepared to revert the materialisation** on
/// subsequent failure (e.g. effect-name typo, prepare error). See
/// [`apply_set_chain_command`] for the snapshot/revert pattern.
///
/// `tracing::info!` fires when a new section is created so the
/// operator can correlate "preset now has [post]" with the originating
/// command.
fn ensure_plane_or_post_section_mut(
    preset: &mut Preset,
    section: SubchainKind,
) -> &mut fluxframe_core::PipelineSection {
    let slot: &mut Option<fluxframe_core::PipelineSection> = match section {
        SubchainKind::Background => &mut preset.background,
        SubchainKind::Foreground => &mut preset.foreground,
        SubchainKind::Post => &mut preset.post,
        SubchainKind::Mask => {
            // `Mask` is filtered out by the `PlaneOrPostKind` typestate
            // approach we considered, but for now a runtime check with
            // debug_assert! suffices — callers that hit this arm are
            // programming errors, not user-facing.
            debug_assert!(
                false,
                "ensure_plane_or_post_section_mut called with Mask — use mask_section_mut"
            );
            // Fall back to mask in release builds; this restores the
            // pre-fix behaviour (silent None propagation) rather than
            // panicking on operators.
            return preset.mask.get_or_insert_with(|| {
                tracing::info!(
                    section = "mask",
                    "materialised absent mask section on demand (fallback)"
                );
                fluxframe_core::PipelineSection::default()
            });
        }
    };
    if slot.is_none() {
        tracing::info!(section = %section, "materialised absent sub-section on demand");
    }
    slot.get_or_insert_with(Default::default)
}

/// Apply `set_chain <section> [...]`. Rebuilds the named sub-chain
/// against the live registry, configures each effect with the
/// matching `per_effect` payload from the active preset (defaults
/// when absent), prepares them against the composite's stored
/// `ProcessingContext`, and swaps them in.
///
/// Available only with the `ml` feature: `set_chain` rebuilds the
/// composite's sub-chains, which depend on the composite effect (and
/// the post/mask/plane registries that the composite owns).
#[cfg(feature = "ml")]
fn apply_set_chain_command(
    chain: &mut EffectChain,
    active_preset: &mut Preset,
    telemetry: &fluxframe_core::EffectTelemetry,
    section: SubchainKind,
    new_names: &[String],
    config_base: &ConfigBase,
) -> ControlResponse {
    let Some(composite) = chain.composite_mut() else {
        return ControlResponse::err(
            "active chain has no composite (preset has no [mask] section)",
            Some(
                "this preset has no segmentation; switch to a preset with [mask] to add post-process effects"
                    .into(),
            ),
        );
    };
    // Snapshot whether the targeted section existed BEFORE we touch
    // the preset; failures below revert any materialisation we did.
    let was_absent = section_is_absent(active_preset, section);
    // Mask cannot be materialised on demand (the composite is bound to
    // a model that the control protocol cannot synthesise). The
    // `composite_mut()` guard above ensures the composite exists, which
    // implies the original preset had `[mask]`. If the active preset
    // somehow lacks it, that's an internal inconsistency.
    let section_data = if section == SubchainKind::Mask {
        let Some(s) = mask_section_mut(active_preset) else {
            debug_assert!(
                false,
                "internal: composite present but active preset has no [mask] section"
            );
            return ControlResponse::err(
                "internal: composite present but mask section missing",
                Some("this is a bug; please report".into()),
            );
        };
        s
    } else {
        ensure_plane_or_post_section_mut(active_preset, section)
    };
    // Effects that leave the chain stop reporting stage timings; their
    // last samples are dropped once the swap succeeds.
    let old_names = section_data.chain.clone();
    // Build new effects + configure them from the existing `per_effect`
    // tables (metadata defaults when an effect has none).
    let result =
        build_and_configure_subchain(section, new_names, &section_data.per_effect, config_base);
    let payload = match result {
        Ok(o) => o,
        Err(e) => {
            // Revert the materialisation if we created an empty section
            // purely to host this doomed `set_chain`.
            revert_absent_section_if_empty(active_preset, section, was_absent);
            return ControlResponse::err(e.reason, e.hint);
        }
    };
    // Hand the new chain to the composite. `replace_subchain` runs
    // `prepare()` against the stored ProcessingContext and atomically
    // swaps. On failure, the old chain stays intact and we don't
    // touch active_preset.
    match composite.replace_subchain(payload) {
        Ok(()) => {
            // Re-borrow because the previous `section_data` borrow was
            // released when we handed `payload` to the composite.
            let section_data = match section {
                SubchainKind::Mask => mask_section_mut(active_preset)
                    .expect("mask presence checked above and not removed since"),
                SubchainKind::Background | SubchainKind::Foreground | SubchainKind::Post => {
                    ensure_plane_or_post_section_mut(active_preset, section)
                }
            };
            section_data.chain = new_names.to_vec();
            // Prune per-effect tables for effects no longer in the
            // chain. Without this, GUI flow "add → tune → remove"
            // would leave an orphan `[<section>.<effect>]` table in
            // `active_preset`, which then (a) survives Save into the
            // TOML file, (b) trips the composite builder's
            // `reject_unknown_table_keys` validation next time the
            // preset is loaded (the operator sees "sub-table has no
            // matching entry in chain"). Reserved keys (`model`,
            // `fallback_threshold`) are not effect
            // names but the `Set` handler could conceivably put them
            // into `per_effect`; keep them so a future Set on a mask
            // sub-section stays intact.
            section_data.per_effect.retain(|key, _| {
                new_names.iter().any(|n| n == key)
                    || fluxframe_core::PipelineSection::is_reserved_key(key)
            });
            for gone in old_names.iter().filter(|n| !new_names.contains(n)) {
                telemetry.forget_stage(section.as_str(), gone);
            }
            info!(
                section = %section,
                chain = ?new_names,
                disabled = ?composite.disabled_effects(section),
                "control: replaced sub-chain"
            );
            ControlResponse::ok()
        }
        Err(e) => {
            revert_absent_section_if_empty(active_preset, section, was_absent);
            ControlResponse::err(
                format!("prepare on new chain failed: {e}"),
                Some("the previous chain is still active".into()),
            )
        }
    }
}

/// Whether the given sub-section of `preset` is currently `None`.
/// Snapshot helper used by [`apply_set_command`] and
/// [`apply_set_chain_command`] before any code path that might
/// materialise the section via [`ensure_plane_or_post_section_mut`].
fn section_is_absent(preset: &Preset, section: SubchainKind) -> bool {
    match section {
        SubchainKind::Mask => preset.mask.is_none(),
        SubchainKind::Background => preset.background.is_none(),
        SubchainKind::Foreground => preset.foreground.is_none(),
        SubchainKind::Post => preset.post.is_none(),
    }
}

/// If `was_absent` is `true` AND the target section is now empty
/// (no chain entries, no per-effect overrides), revert it to `None`.
/// Used by [`apply_set_chain_command`] and [`apply_set_command`] to
/// undo a section materialisation when the command that triggered it
/// fails — keeps `active_preset` in sync with the TOML's structural
/// shape so the operator does not see a phantom `[post]` they never
/// created.
fn revert_absent_section_if_empty(
    active_preset: &mut Preset,
    section: SubchainKind,
    was_absent: bool,
) {
    if !was_absent {
        return;
    }
    let now_empty = match section {
        SubchainKind::Mask => active_preset
            .mask
            .as_ref()
            .is_some_and(|s| s.chain.is_empty() && s.per_effect.is_empty()),
        SubchainKind::Background => active_preset
            .background
            .as_ref()
            .is_some_and(|s| s.chain.is_empty() && s.per_effect.is_empty()),
        SubchainKind::Foreground => active_preset
            .foreground
            .as_ref()
            .is_some_and(|s| s.chain.is_empty() && s.per_effect.is_empty()),
        SubchainKind::Post => active_preset
            .post
            .as_ref()
            .is_some_and(|s| s.chain.is_empty() && s.per_effect.is_empty()),
    };
    if now_empty {
        match section {
            SubchainKind::Mask => active_preset.mask = None,
            SubchainKind::Background => active_preset.background = None,
            SubchainKind::Foreground => active_preset.foreground = None,
            SubchainKind::Post => active_preset.post = None,
        }
    }
}

/// Slim-build stub for `set_chain`: the post/mask/plane registries
/// and the composite effect are all `ml`-gated, so this command is
/// unavailable without `--features ml`.
#[cfg(not(feature = "ml"))]
fn apply_set_chain_command(
    _chain: &mut EffectChain,
    _active_preset: &mut Preset,
    _telemetry: &fluxframe_core::EffectTelemetry,
    _section: SubchainKind,
    _new_names: &[String],
    _config_base: &ConfigBase,
) -> ControlResponse {
    ControlResponse::err(
        "set_chain unavailable: built without ml feature",
        Some("rebuild with `--features fluxframe-cli/ml` to enable composite live-reconfig".into()),
    )
}

/// Apply `set_enabled <section> <effect> <enabled>`: bypass (or run
/// again) every chain entry named `effect`, then record the flag in the
/// active preset so `get_config` and Save see it. The live chain is
/// toggled first; the preset is only touched once that succeeded.
///
/// Canonical form in the preset: `enabled = false` in the effect table
/// when disabled, no key when enabled — and a table left empty by
/// removing the key is dropped, so off→on restores the original preset.
#[cfg(feature = "ml")]
fn apply_set_enabled_command(
    chain: &mut EffectChain,
    active_preset: &mut Preset,
    telemetry: &fluxframe_core::EffectTelemetry,
    section: SubchainKind,
    effect: &str,
    enabled: bool,
) -> ControlResponse {
    use fluxframe_core::EFFECT_ENABLED_KEY;

    let section_data = match section {
        SubchainKind::Mask => active_preset.mask.as_mut(),
        SubchainKind::Background => active_preset.background.as_mut(),
        SubchainKind::Foreground => active_preset.foreground.as_mut(),
        SubchainKind::Post => active_preset.post.as_mut(),
    };
    let Some(section_data) = section_data else {
        return ControlResponse::err(
            format!("preset does not have a [{section}] sub-section"),
            Some(format!("add effects to [{section}] before toggling them")),
        );
    };
    if !section_data.chain.iter().any(|name| name == effect) {
        return ControlResponse::err(
            format!("no effect named '{effect}' in the '{section}' chain"),
            Some(format!("chain: {}", section_data.chain.join(", "))),
        );
    }
    if section_data
        .per_effect
        .get(effect)
        .is_some_and(|entry| !entry.is_table())
    {
        return ControlResponse::err(
            format!("[{section}.{effect}] is not a table"),
            Some("fix the preset in fluxframe.toml and reload".into()),
        );
    }

    let changed = match chain.set_effect_enabled(section, effect, enabled) {
        Ok(changed) => changed,
        Err(e) => {
            tracing::debug!(
                section = %section,
                effect,
                enabled,
                error = %e,
                "control: set_enabled rejected",
            );
            return effect_error_response(&e);
        }
    };

    if enabled {
        if let Some(toml::Value::Table(table)) = section_data.per_effect.get_mut(effect) {
            table.remove(EFFECT_ENABLED_KEY);
            if table.is_empty() {
                section_data.per_effect.remove(effect);
            }
        }
    } else {
        let entry = section_data
            .per_effect
            .entry(effect.to_string())
            .or_insert_with(|| toml::Value::Table(toml::Table::new()));
        if let toml::Value::Table(table) = entry {
            table.insert(EFFECT_ENABLED_KEY.into(), toml::Value::Boolean(false));
        }
        // The stage stops running; do not keep reporting its last samples.
        telemetry.forget_stage(section.as_str(), effect);
    }
    info!(section = %section, effect, enabled, changed, "control: toggled effect");
    ControlResponse::ok()
}

/// Slim-build stub for `set_enabled`: the composite is `ml`-gated.
#[cfg(not(feature = "ml"))]
fn apply_set_enabled_command(
    _chain: &mut EffectChain,
    _active_preset: &mut Preset,
    _telemetry: &fluxframe_core::EffectTelemetry,
    _section: SubchainKind,
    _effect: &str,
    _enabled: bool,
) -> ControlResponse {
    ControlResponse::err(
        "set_enabled unavailable: built without ml feature",
        Some("rebuild with `--features fluxframe-cli/ml` to enable composite live-reconfig".into()),
    )
}

/// Error response for an [`fluxframe_core::EffectError`]: an
/// `InvalidConfig` keeps its reason and hint, anything else is rendered
/// whole.
fn effect_error_response(e: &fluxframe_core::EffectError) -> ControlResponse {
    match e {
        fluxframe_core::EffectError::InvalidConfig { reason, hint, .. } => {
            ControlResponse::err(reason.clone(), hint.clone())
        }
        other => ControlResponse::err(format!("{other}"), None),
    }
}

/// Sub-error type the chain-build path can surface.
#[cfg(feature = "ml")]
struct SubChainError {
    reason: String,
    hint: Option<String>,
}

/// Resolve effect names against the right registry and configure each
/// with the matching `per_effect` table. Mirrors what
/// `CompositeBuilder` does at construction time, but exposed here so
/// the worker can rebuild a single sub-chain at runtime.
#[cfg(feature = "ml")]
#[allow(
    clippy::too_many_lines,
    reason = "four enum arms × build+configure pattern; trait-object types differ so each arm is its own monomorphisation"
)]
fn build_and_configure_subchain(
    section: SubchainKind,
    names: &[String],
    per_effect: &std::collections::BTreeMap<String, toml::Value>,
    config_base: &ConfigBase,
) -> Result<fluxframe_effects::composite::SubChainPayload, SubChainError> {
    use fluxframe_effects::composite::{Slot, SubChainPayload};
    use fluxframe_effects::{mask_effects, plane_effects, post_effects};

    /// Local helper: trait object with a `configure()` method, used
    /// to drive each effect's `configure()` after registry build.
    /// Implemented in this crate for the three sub-effect dyn types
    /// because the unified `SubEffectAdapter` lives `pub(crate)` in
    /// `fluxframe-effects` and is not exposed here.
    trait Configure {
        fn configure_mut(
            &mut self,
            params: fluxframe_core::traits::RawEffectParams,
        ) -> Result<(), fluxframe_core::EffectError>;
    }
    impl Configure for dyn fluxframe_core::MaskEffect {
        fn configure_mut(
            &mut self,
            params: fluxframe_core::traits::RawEffectParams,
        ) -> Result<(), fluxframe_core::EffectError> {
            self.configure(params)
        }
    }
    impl Configure for dyn fluxframe_core::PlaneEffect {
        fn configure_mut(
            &mut self,
            params: fluxframe_core::traits::RawEffectParams,
        ) -> Result<(), fluxframe_core::EffectError> {
            self.configure(params)
        }
    }
    impl Configure for dyn fluxframe_core::PostEffect {
        fn configure_mut(
            &mut self,
            params: fluxframe_core::traits::RawEffectParams,
        ) -> Result<(), fluxframe_core::EffectError> {
            self.configure(params)
        }
    }

    /// Configure each built effect and pair it with its `enabled` flag.
    fn configure_each<E>(
        chain: Vec<Box<E>>,
        names: &[String],
        per_effect: &std::collections::BTreeMap<String, toml::Value>,
        lookup_metadata: impl Fn(&str) -> Option<&'static fluxframe_core::EffectMetadata>,
        config_base: &ConfigBase,
    ) -> Result<Vec<Slot<E>>, SubChainError>
    where
        E: ?Sized + Configure,
    {
        chain
            .into_iter()
            .zip(names.iter())
            .map(|(mut effect, name)| {
                // An effect added via the GUI (`Command::SetChain` with
                // just names) has no table, or only an `enabled` flag;
                // the resolver synthesises its metadata defaults so
                // `configure` never sees an empty table for
                // required-field structs (color_fill.rgb, image_fill.path).
                let resolved = fluxframe_core::resolve_effect_params(
                    name,
                    per_effect.get(name),
                    lookup_metadata(name),
                    config_base,
                )
                .map_err(configure_error)?;
                effect
                    .configure_mut(resolved.params)
                    .map_err(configure_error)?;
                Ok(Slot::new(effect, resolved.enabled))
            })
            .collect()
    }

    fn configure_error(e: fluxframe_core::EffectError) -> SubChainError {
        match e {
            fluxframe_core::EffectError::InvalidConfig { reason, hint, .. } => {
                SubChainError { reason, hint }
            }
            other => SubChainError {
                reason: format!("configure failed: {other}"),
                hint: None,
            },
        }
    }

    fn build_error(section: SubchainKind, e: &fluxframe_core::EffectError) -> SubChainError {
        SubChainError {
            reason: format!("{section} chain build failed: {e}"),
            hint: None,
        }
    }

    match section {
        SubchainKind::Mask => {
            let registry = mask_effects::default_registry();
            let built = registry
                .build_chain(names)
                .map_err(|e| build_error(section, &e))?;
            let slots = configure_each::<dyn fluxframe_core::MaskEffect>(
                built,
                names,
                per_effect,
                |n| registry.metadata(n),
                config_base,
            )?;
            Ok(SubChainPayload::Mask(slots))
        }
        SubchainKind::Background | SubchainKind::Foreground => {
            let registry = plane_effects::default_registry();
            let built = registry
                .build_chain(names)
                .map_err(|e| build_error(section, &e))?;
            let slots = configure_each::<dyn fluxframe_core::PlaneEffect>(
                built,
                names,
                per_effect,
                |n| registry.metadata(n),
                config_base,
            )?;
            Ok(if section == SubchainKind::Background {
                SubChainPayload::Background(slots)
            } else {
                SubChainPayload::Foreground(slots)
            })
        }
        SubchainKind::Post => {
            let registry = post_effects::default_registry();
            let built = registry
                .build_chain(names)
                .map_err(|e| build_error(section, &e))?;
            let slots = configure_each::<dyn fluxframe_core::PostEffect>(
                built,
                names,
                per_effect,
                |n| registry.metadata(n),
                config_base,
            )?;
            Ok(SubChainPayload::Post(slots))
        }
    }
}

/// How long the worker waits on an empty frame slot before re-checking the
/// shutdown flag.  Short enough to be responsive to Ctrl-C, long enough to
/// avoid spinning when the source briefly stalls.
const WORKER_POLL_TIMEOUT: Duration = Duration::from_millis(50);

/// Reconcile slot drop counter into [`RuntimeMetrics`] every Nth frame.
/// Picked low enough that a brief burst surfaces within a second at
/// 30 fps; high enough to keep the supervisor loop free of per-frame
/// atomic chatter on the slot's counter.
const DROPPED_SYNC_INTERVAL: u64 = 30;

/// Process-wide registry of live [`RunToken`]s.  The Ctrl-C signal handler
/// walks this list and broadcasts a shutdown request to every concurrent
/// run.  Tokens are stored as [`Weak`] references so a run that has
/// already torn down does not keep its slot alive.
static REGISTERED_TOKENS: OnceLock<Mutex<Vec<Weak<RunToken>>>> = OnceLock::new();

/// Process-wide shutdown flag.  Set to `true` by the Ctrl-C handler;
/// drained by [`is_shutdown_requested`] / [`wait_for_shutdown`] so
/// non-pipeline polling loops (e.g. the `device = "auto"` wait state)
/// can break out promptly.  Distinct from per-run `RunToken::flag`
/// because the auto wait loop lives OUTSIDE any active run.
///
/// Uses [`Ordering::Relaxed`] because this flag carries a single bit
/// with no companion data — the polling loops only need eventual
/// visibility, not happens-before with any other variable. Per-run
/// `RunToken::flag` keeps Acquire/Release because it is read alongside
/// `slot.close()` and must order frame-slot tear-down.
///
/// TODO(post-MVP): unify SHUTDOWN_REQUESTED into the tokens_registry by
/// adding an idle/global token, so the auto wait loop and the run loop
/// share one shutdown surface. The current two-tier split is honest
/// (each loop only reads what it owns) but doubles the bookkeeping.
static SHUTDOWN_REQUESTED: AtomicBool = AtomicBool::new(false);

fn tokens_registry() -> &'static Mutex<Vec<Weak<RunToken>>> {
    REGISTERED_TOKENS.get_or_init(|| Mutex::new(Vec::new()))
}

// ---------------------------------------------------------------------------
// Loopback visibility tracking
// ---------------------------------------------------------------------------
//
// How long `/dev/video10` had no producer holding it open. With
// `exclusive_caps=1` the node only advertises CAPTURE capabilities while
// a producer is attached, so this window is exactly the time a client
// enumerating devices does not see the camera at all — the operator-
// visible symptom behind "the app can't find FluxFrame, restart it".
//
// It is deliberately process-global rather than part of `RuntimeMetrics`:
// the window lives *between* runs, and a per-run metrics bundle is
// created after the output is already back up. A storm of 164 restarts
// would have reset a per-run counter 164 times and reported zero.

/// Wall-clock ms accumulated across every completed invisible window.
static OUTPUT_INVISIBLE_MS_TOTAL: AtomicU64 = AtomicU64::new(0);
/// Number of times the output pipeline was (re)built from scratch.
static OUTPUT_REBUILDS_TOTAL: AtomicU64 = AtomicU64::new(0);
/// Monotonic ms since process start marking when the output went down,
/// or `0` when the output is currently live. Stored as a scalar rather
/// than an `Instant` so it can live in a plain atomic.
static OUTPUT_DOWN_SINCE_MS: AtomicU64 = AtomicU64::new(0);

/// Process start, the epoch for [`OUTPUT_DOWN_SINCE_MS`].
fn process_epoch() -> Instant {
    static EPOCH: OnceLock<Instant> = OnceLock::new();
    *EPOCH.get_or_init(Instant::now)
}

fn elapsed_ms_since_epoch() -> u64 {
    u64::try_from(process_epoch().elapsed().as_millis()).unwrap_or(u64::MAX)
}

/// Record that the loopback output is live and advertising CAPTURE caps.
/// Closes any open invisible window and logs its duration.
pub(crate) fn mark_output_live() {
    let since = OUTPUT_DOWN_SINCE_MS.swap(0, Ordering::Relaxed);
    if since == 0 {
        // First start of the process — there was no preceding window,
        // so this start is not a *re*build. Counting it here (the
        // previous behaviour) made `rebuilds_total` permanently one
        // larger than the number of outages an operator can observe.
        // Incrementing only after a recorded down-edge keeps the
        // counter paired 1:1 with `mark_output_down`.
        return;
    }
    OUTPUT_REBUILDS_TOTAL.fetch_add(1, Ordering::Relaxed);
    let down_ms = elapsed_ms_since_epoch().saturating_sub(since);
    OUTPUT_INVISIBLE_MS_TOTAL.fetch_add(down_ms, Ordering::Relaxed);
    info!(
        down_ms,
        invisible_ms_total = OUTPUT_INVISIBLE_MS_TOTAL.load(Ordering::Relaxed),
        rebuilds_total = OUTPUT_REBUILDS_TOTAL.load(Ordering::Relaxed),
        "loopback output back up — clients can enumerate the camera again"
    );
}

/// Record that the loopback output has been torn down, starting an
/// invisible window. `reason` is the error (or `None` for a clean exit)
/// that ended the run.
pub(crate) fn mark_output_down(reason: Option<&FluxError>) {
    // Keep the earliest down-edge if this is called twice without an
    // intervening `mark_output_live` — the window is "since the output
    // last worked", not "since the last teardown".
    let now = elapsed_ms_since_epoch().max(1);
    let _ = OUTPUT_DOWN_SINCE_MS.compare_exchange(0, now, Ordering::Relaxed, Ordering::Relaxed);
    if let Some(e) = reason {
        warn!(error = %e, "loopback output torn down — camera unavailable to clients");
    } else {
        info!("loopback output torn down (clean exit)");
    }
}

/// Returns `true` if Ctrl-C has been received since process start.
#[must_use]
pub(crate) fn is_shutdown_requested() -> bool {
    SHUTDOWN_REQUESTED.load(Ordering::Relaxed)
}

/// Sleep for `total` or until shutdown is requested, whichever comes
/// first.  Returns `true` if the sleep was cut short by a shutdown
/// request.  Polls every ~100 ms so a Ctrl-C during a long wait is
/// reflected promptly.
pub(crate) fn wait_for_shutdown(total: Duration) -> bool {
    let deadline = Instant::now() + total;
    while Instant::now() < deadline {
        if is_shutdown_requested() {
            return true;
        }
        let remaining = deadline.saturating_duration_since(Instant::now());
        std::thread::sleep(remaining.min(Duration::from_millis(100)));
    }
    is_shutdown_requested()
}

/// [`wait_for_shutdown`] that keeps answering the control socket.
///
/// Used wherever the daemon waits with no worker loop draining commands
/// — the auto-input poll, camera acquire backoff, in-place recovery — so
/// a client is answered promptly (see [`apply_offline_command`]) instead
/// of timing out after [`WORKER_RESPONSE_TIMEOUT`]. Queued commands are
/// answered before shutdown is checked, so none is left without a reply.
pub(crate) fn wait_serving_control(
    total: Duration,
    control_rx: Option<&crossbeam_channel::Receiver<ControlEnvelope>>,
    session: &ControlSession,
) -> bool {
    let Some(rx) = control_rx else {
        return wait_for_shutdown(total);
    };
    let deadline = Instant::now() + total;
    loop {
        let step = deadline
            .saturating_duration_since(Instant::now())
            .min(Duration::from_millis(100));
        match rx.recv_timeout(step) {
            Ok(envelope) => {
                // Best-effort, as in `drain_control_commands`.
                let _ = envelope
                    .reply_tx
                    .send(apply_offline_command(session, &envelope.cmd));
            }
            Err(crossbeam_channel::RecvTimeoutError::Timeout) => {}
            // The listener is gone; keep the wait's timing honest.
            Err(crossbeam_channel::RecvTimeoutError::Disconnected) => std::thread::sleep(step),
        }
        if is_shutdown_requested() {
            return true;
        }
        if Instant::now() >= deadline {
            return false;
        }
    }
}

/// Make sure the process-wide Ctrl-C handler is installed.  Idempotent
/// — call from anywhere that needs the handler before opening a slot
/// (currently: per-run setup and the `device = "auto"` wait loop).
pub(crate) fn ensure_ctrlc_handler() {
    install_ctrlc_once();
}

/// Per-run shutdown state.  Held inside an [`Arc`] so the signal handler
/// can flip the flag and close the slot without owning the run.
struct RunToken {
    /// Shutdown flag: `true` while the run is active, set to `false` by
    /// the signal handler or the supervisor itself to request termination.
    flag: Arc<AtomicBool>,
    /// Frame slot to close when shutdown is requested, so the worker
    /// loop wakes from `recv_timeout` immediately.
    slot: LatestFrameSlot,
}

/// Install the Ctrl-C handler at most once for the entire process.  If the
/// handler cannot be installed (e.g. another component already claimed it)
/// we log a warning and continue without one: tests routinely run inside
/// harnesses that grab SIGINT for themselves.
fn install_ctrlc_once() {
    static INSTALLED: OnceLock<()> = OnceLock::new();
    INSTALLED.get_or_init(|| {
        let result = ctrlc::set_handler(|| {
            info!("Ctrl-C received - broadcasting shutdown");
            SHUTDOWN_REQUESTED.store(true, Ordering::Relaxed);
            let mut reg = tokens_registry()
                .lock()
                .expect("tokens registry poisoned");
            reg.retain(|w| w.upgrade().is_some());
            for token in reg.iter().filter_map(Weak::upgrade) {
                token.flag.store(false, Ordering::Release);
                token.slot.close();
            }
        });
        if let Err(e) = result {
            warn!(
                error = %e,
                "could not install Ctrl-C handler (another one is already set); continuing without one",
            );
        }
    });
}

/// RAII guard that owns a [`RunToken`] for the duration of a single run.
///
/// On drop the guard removes its token's weak reference from the global
/// registry, which keeps the registry from growing unboundedly when many
/// runs come and go inside the same process (the integration test suite
/// is the obvious caller).
struct TokenGuard {
    token: Arc<RunToken>,
}

impl Drop for TokenGuard {
    fn drop(&mut self) {
        let reg = tokens_registry();
        let mut tokens = reg.lock().expect("tokens registry poisoned");
        tokens.retain(|w| {
            w.upgrade()
                .is_some_and(|other| !Arc::ptr_eq(&other, &self.token))
        });
    }
}

/// Register a fresh [`RunToken`] for the current run and return a guard
/// plus the per-run shutdown flag.  The guard must remain in scope until
/// the run finishes; dropping it removes the token from the registry.
fn register_token(slot: LatestFrameSlot) -> (TokenGuard, Arc<AtomicBool>) {
    install_ctrlc_once();
    let token = Arc::new(RunToken {
        flag: Arc::new(AtomicBool::new(true)),
        slot,
    });
    let flag = Arc::clone(&token.flag);
    let weak = Arc::downgrade(&token);
    tokens_registry()
        .lock()
        .expect("tokens registry poisoned")
        .push(weak);
    (TokenGuard { token }, flag)
}

/// Parsed input source resolved from a [`FluxConfig`].
///
/// Routing rules:
///
/// * [`InputDevice::Testsrc`] → [`Self::Testsrc`].
/// * [`InputDevice::Path`]    → [`Self::V4l2`] (path is *not*
///   canonicalised here — that happens inside
///   [`fluxframe_gst::input::InputPipeline::build_v4l2`]).
/// * [`InputDevice::Auto`]    → [`Self::Unsupported`]; `commands::run`
///   intercepts `Auto` and dispatches to the polling loop before this
///   function is called, so reaching `classify_input` with `Auto` is a
///   bug in the caller.
///
/// Adding a variant turns every CLI match site into a compile error,
/// which is what we want at the `pub(crate)` boundary; `#[non_exhaustive]`
/// would only matter cross-crate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum InputSpec {
    /// Synthetic test source (`videotestsrc`).
    Testsrc,
    /// V4L2 capture device (path is *not* canonicalised here — that
    /// happens inside [`fluxframe_gst::input::InputPipeline::build_v4l2`]).
    V4l2(PathBuf),
    /// Unrecognised — caller surfaces a structured error.
    Unsupported(String),
}

/// Classify the input section of `cfg` into an [`InputSpec`].
///
/// [`InputDevice::Auto`] should never reach this function: the
/// `commands::run` entry point intercepts it and routes the run through
/// the polling loop (`run_auto`) which substitutes the picked path back
/// into `cfg.input.device` before calling here. Returning
/// `InputSpec::Unsupported` is the safe escape hatch.
#[must_use]
pub(crate) fn classify_input(cfg: &FluxConfig) -> InputSpec {
    match &cfg.input.device {
        InputDevice::Testsrc => InputSpec::Testsrc,
        InputDevice::Path(p) => InputSpec::V4l2(p.clone()),
        InputDevice::Auto => InputSpec::Unsupported(
            "auto (should have been handled in commands::run before classify_input)".into(),
        ),
    }
}

/// Parsed output sink resolved from a [`FluxConfig`].
///
/// Mirrors [`InputSpec`] on the output side: a typed enum collapses the
/// `device == "auto" | "fakesink" | /dev/...` triage into one match site
/// so `commands::check` and `commands::run` cannot drift apart.
///
/// Adding a variant turns every CLI match site into a compile error,
/// which is what we want at the `pub(crate)` boundary; `#[non_exhaustive]`
/// would only matter cross-crate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum OutputSpec {
    /// `autovideosink` (manual glance verification).
    Auto,
    /// `fakesink` (CI / dev smoke without a loopback).
    Fake,
    /// `v4l2sink` to a loopback (or other writable V4L2) device.
    V4l2(PathBuf),
    /// `pipewiresink` publishing a PipeWire node.  Optional name shows
    /// up in PipeWire graph tools (`pw-cli`, `helvum`).
    Pipewire(Option<String>),
    /// Unrecognised — caller surfaces a structured error.
    Unsupported(String),
}

/// Classify the output section of `cfg` into an [`OutputSpec`].
///
/// Recognised forms:
///   * `auto` / `fakesink` — built-in GStreamer sinks.
///   * `/dev/video*` — v4l2loopback (or any writable V4L2 device).
///   * `pipewire` / `pipewire:<node-name>` — PipeWire stream.  The
///     optional name suffix labels the PipeWire client in graph tools
///     and lets multiple FluxFrame instances co-exist.
#[must_use]
pub(crate) fn classify_output(cfg: &FluxConfig) -> OutputSpec {
    let device = cfg.output.device.as_str();
    if let Some(suffix) = device.strip_prefix("pipewire") {
        if suffix.is_empty() {
            return OutputSpec::Pipewire(None);
        }
        if let Some(rest) = suffix.strip_prefix(':') {
            let trimmed = rest.trim();
            return OutputSpec::Pipewire(if trimmed.is_empty() {
                None
            } else {
                Some(trimmed.to_string())
            });
        }
        // `pipewireFOO` etc — neither bare nor `pipewire:NAME`.  Fall
        // through to Unsupported so the operator sees a clear error.
    }
    match device {
        "auto" => OutputSpec::Auto,
        "fakesink" => OutputSpec::Fake,
        other if other.starts_with("/dev/") => OutputSpec::V4l2(PathBuf::from(other)),
        other => OutputSpec::Unsupported(other.to_string()),
    }
}

/// Run a passthrough-style chain on `videotestsrc`, emitting to the sink
/// resolved from the configuration.
///
/// # Errors
///
/// Propagates [`FluxError`] from pipeline construction, effect chain
/// preparation, or runtime failures.
#[tracing::instrument(skip_all, fields(sink = ?cfg.output.device, preset = %session.active_preset_name))]
pub(crate) fn run_testsrc_chain(
    cfg: &FluxConfig,
    session: &mut ControlSession,
    control_rx: Option<&crossbeam_channel::Receiver<ControlEnvelope>>,
    chain: EffectChain,
) -> Result<(), FluxError> {
    run_chain(
        cfg,
        session,
        control_rx,
        chain,
        "testsrc",
        InputPipeline::build_testsrc,
    )
}

/// Run the effect chain against a V4L2 capture device.
///
/// # Errors
///
/// Propagates [`FluxError`] from pipeline construction (including a
/// structured [`PipelineError::InputDeviceUnavailable`] when the
/// pre-open check fails), effect chain preparation, or runtime failures.
#[tracing::instrument(skip_all, fields(device = %cfg.input.device, sink = ?cfg.output.device, preset = %session.active_preset_name))]
pub(crate) fn run_v4l2_chain(
    cfg: &FluxConfig,
    session: &mut ControlSession,
    control_rx: Option<&crossbeam_channel::Receiver<ControlEnvelope>>,
    chain: EffectChain,
) -> Result<(), FluxError> {
    // Detect the camera's native fps so the operator's `[input] fps`
    // hint becomes an upper bound, not a hard requirement: requesting
    // 30 fps from a 15 fps camera silently capped to 15 is friendlier
    // than failing the pipeline.
    //
    // Width/height are NOT overridden — operator's `[input]
    // width/height` is the source of truth and propagates through to
    // the output dimensions (which v4l2loopback then exposes to
    // consumers).  Doing it the other way (cfg follows camera) made
    // the output size change every time the camera changed, which
    // broke the v4l2loopback `VIDIOC_S_FMT` negotiation on switch
    // and made the consumer-visible resolution non-deterministic.
    // `videoscale` in the input pipeline pads with `add-borders=true`
    // so the aspect ratio is preserved across the resize.
    let device_path = match &cfg.input.device {
        InputDevice::Path(p) => p.clone(),
        // run_v4l2_chain is only reachable from the V4l2 branch of
        // classify_input, which extracts a path. Auto / Testsrc would
        // never get here, but surface a structured error rather than
        // panic if someone wires this up incorrectly later.
        other => {
            return Err(FluxError::Config {
                reason: format!(
                    "run_v4l2_chain invoked with non-path input device '{other}' (this is a CLI \
                     dispatch bug)",
                ),
                hint: None,
            });
        }
    };
    // Stage 16: detection now lives INSIDE the input builder so it runs
    // on every (re)acquire attempt — the camera may be busy at startup
    // and become free later. `detect_native_mode` opens the device and
    // drops its `v4l::Device` before `build_v4l2` re-opens it via
    // `v4l2src`, so there is no VIDIOC_REQBUFS race within a single
    // attempt. Output fps comes from `cfg.input.fps`; only the *input*
    // adopts the detected native fps (width/height stay operator-set).
    let device_path_for_builder = device_path.clone();
    run_chain(cfg, session, control_rx, chain, "v4l2src", move |params| {
        let detected =
            fluxframe_gst::v4l2_caps::detect_native_mode(&device_path_for_builder, params.fps)?;
        let resolved = InputParams::new(params.width, params.height, detected.fps, params.format);
        InputPipeline::build_v4l2(&device_path_for_builder, resolved)
    })
}

/// Shared driver for all input backends: takes a closure that builds the
/// input pipeline so the bus-listener / processing-loop / teardown plumbing
/// lives in exactly one place.
fn run_chain<F>(
    cfg: &FluxConfig,
    session: &mut ControlSession,
    control_rx: Option<&crossbeam_channel::Receiver<ControlEnvelope>>,
    mut chain: EffectChain,
    source_label: &'static str,
    input_builder: F,
) -> Result<(), FluxError>
where
    F: Fn(InputParams) -> Result<InputPipeline, PipelineError>,
{
    fluxframe_gst::init()?;

    // Build metrics BEFORE `prepare_all` so the runtime can hand the
    // shared `Arc<Counters>` to effects through `ProcessingContext`.
    // This lets, e.g., the Stage 7 sticky-fallback decorator inside
    // `BackgroundBlurEffect`'s blur backend publish transition events
    // through the same counter bundle the supervisor reads later.
    let metrics = RuntimeMetrics::new();
    // Publish the effective effect-processing pool size (set once by
    // `cap_rayon_pool` at startup) as a gauge so operators can confirm
    // the cap and watch for oversubscription against `inference_p95`.
    metrics
        .counters
        .set_processing_threads(rayon::current_num_threads() as u64);

    // Stage 16: build + start the output (loopback) producer FIRST, so
    // `/dev/video10` is enumerable by Chrome and streams a placeholder
    // even while the camera is busy/absent. The input is acquired
    // afterwards (with backoff on the supervised path).
    let (output, mut processing_ctx, sink_label) = build_output(cfg)?;
    processing_ctx.counters = Some(Arc::clone(&metrics.counters));
    // Per-effect TOML configuration happens inside the composite
    // builder (preset path) and at construction for [`PassthroughEffect`],
    // so the runtime only needs to drive `prepare_all` here. The chain
    // never sees standalone effects with unconfigured state.
    chain
        .prepare_all(&processing_ctx)
        .map_err(FluxError::from)?;

    let (effective_out_w, effective_out_h) = cfg
        .output
        .effective_dimensions(cfg.input.width, cfg.input.height);
    info!(
        source = source_label,
        sink = sink_label,
        effects = ?chain.names(),
        input_w = cfg.input.width,
        input_h = cfg.input.height,
        input_fps = cfg.input.fps,
        output_w = effective_out_w,
        output_h = effective_out_h,
        output_scale = cfg.output.scale.value(),
        input_format = ?cfg.input.format,
        output_format = ?cfg.output.format,
        "starting pipeline ({source_label} -> {sink_label})",
    );

    output.start()?;
    // From here the node advertises CAPTURE caps again; close any
    // invisible window opened by the previous run's teardown.
    mark_output_live();

    // Stage 16: acquire the input AFTER the output is live. On the
    // supervised path a busy/absent camera streams the placeholder and
    // retries with backoff instead of tearing the loopback down.
    //
    // `prepare_input` tears the output + chain down itself on both
    // non-`Some` arms (clean shutdown, or a permanent error), so the
    // invisible window opens here rather than in `run_auto` — which
    // only ever sees `device = "auto"`.
    let input = match prepare_input(
        cfg,
        &input_builder,
        &output,
        &metrics,
        &mut chain,
        control_rx,
        session,
    ) {
        Ok(Some(input)) => input,
        Ok(None) => {
            // Shutdown requested while waiting for the camera;
            // prepare_input already tore the output + chain down.
            mark_output_down(None);
            return Ok(());
        }
        Err(e) => {
            mark_output_down(Some(&e));
            return Err(e);
        }
    };

    let slot = input.slot();
    // The token guard MUST live until the end of this function: when it
    // drops it removes the run's weak entry from the global registry.
    let (_token_guard, running) = register_token(slot.clone());

    // Bus listener relays GStreamer fatal errors and EOS into the shared
    // shutdown flag, and surfaces any captured error back to the caller.
    // Input-side failures are split off into `input_failure` so they can
    // be recovered in place instead of taking the loopback down.
    let bus_error: Arc<Mutex<Option<FluxError>>> = Arc::new(Mutex::new(None));
    // Starts disabled and is armed below, once we know an idle runtime
    // (and therefore a placeholder) actually exists. Config alone is not
    // enough: `build_idle_runtime` can still bail out on a bad
    // placeholder path or an unresolvable sink, and recovering with no
    // placeholder would leave the writer thread re-pushing the last live
    // frame — a frozen picture the consumer cannot tell from a working
    // camera.
    let input_failure = Arc::new(InputFailureSignal::new());
    let _bus_listener = build_bus_listener(
        &input,
        &output,
        Arc::clone(&running),
        Arc::clone(&bus_error),
        slot.clone(),
        Arc::clone(&input_failure),
    );

    // `metrics` was constructed above (before `prepare_all`) so the
    // counters Arc could be threaded into `ProcessingContext`.  Same
    // bundle owns the histograms used by the periodic reporter below.

    // Periodic reporter: emits per-window fps + percentiles via `info!`
    // at the cadence configured in `[realtime] metrics_interval_secs`.
    // `metrics_interval_secs = 0` disables it (teardown summary still
    // runs). `_reporter` is dropped at the end of this function — its
    // `Drop` impl joins the thread before we tear down counters.
    let _reporter = spawn_metrics_reporter(cfg, &metrics, &running);

    // Stage 15 idle runtime: detector spawn + state machine + cached
    // placeholder. Returns `None` (Stage 14 fallthrough) when idle
    // mode is disabled, the sink is non-V4L2, or the host is non-Linux.
    let base = &session.config_base;
    let mut idle_runtime = build_idle_runtime(cfg, base, &input, &output, &running, &metrics);
    if supervised_acquire(cfg) && idle_runtime.is_some() {
        input_failure.arm();
    }

    let process_result = run_supervised_loop(
        WorkerDeps {
            cfg,
            processing_ctx: &processing_ctx,
            metrics: &metrics,
            control_rx,
        },
        session,
        &running,
        &slot,
        &mut chain,
        &output,
        &mut idle_runtime,
        SupervisedInput {
            pipeline: &input,
            failure: &input_failure,
        },
    );

    // Ensure the bus listener wakes and exits.  Dropping `_bus_listener`
    // at the end of the function calls `BusListener::stop` via Drop, but
    // we also flip the flag here so the listener observes shutdown even
    // before the drop runs.
    running.store(false, Ordering::Release);
    slot.close();

    teardown(&input, &output, &mut chain);

    // Final reconciliation: pull whatever the slot dropped between the
    // last sync inside the loop and shutdown.
    metrics.sync_dropped(slot.dropped_count());
    let snap = metrics.snapshot();
    // Absolute totals at teardown. Shares the single-source-of-truth
    // field list with the periodic reporter via `emit_metrics_line`
    // (passing `None` — no rolling-window deltas here), so every counter
    // is emitted from one place under the `fluxframe::metrics` target.
    fluxframe_core::emit_metrics_line(&snap, None);

    // Surface bus-reported errors when the processing loop itself was
    // clean, so the operator sees the real cause of shutdown.
    let bus_err = bus_error.lock().expect("bus_error mutex poisoned").take();
    let outcome = match (process_result, bus_err) {
        (Ok(()), Some(e)) | (Err(e), _) => Err(e),
        (Ok(()), None) => Ok(()),
    };

    // The output stopped in `teardown` a few lines above; open the
    // invisible window here, once the run's real cause of death is
    // known (it may have arrived via the bus rather than from the
    // worker loop). This lives in `run_chain` — not in `run_auto` —
    // because every backend and every device form (`auto` or a fixed
    // `/dev/videoN`) passes through here, whereas `run_auto` only ever
    // sees `device = "auto"`. `mark_output_down` keeps the earliest
    // down-edge, so the pairing with `mark_output_live` stays 1:1.
    mark_output_down(outcome.as_ref().err());
    outcome
}

/// Stop the already-started output and shut the effect chain down —
/// the partial-teardown path when input acquisition aborts (shutdown)
/// or fails permanently, before the full [`teardown`] wiring exists.
fn teardown_partial(output: &OutputPipeline, chain: &mut EffectChain) {
    if let Err(e) = output.stop() {
        warn!(error = %e, "output.stop failed during acquire teardown");
    }
    if let Err(e) = chain.shutdown_all() {
        warn!(error = %e, "chain shutdown reported an error during acquire teardown");
    }
}

/// Build the idle placeholder (supervised path only) and acquire the
/// input. Returns `Some(input)` to proceed, `None` if shutdown was
/// requested while waiting for the camera (output + chain already torn
/// down here), or `Err` on a permanent acquire failure (also torn down
/// here, so the caller just propagates).
fn prepare_input<F>(
    cfg: &FluxConfig,
    input_builder: &F,
    output: &OutputPipeline,
    metrics: &RuntimeMetrics,
    chain: &mut EffectChain,
    control_rx: Option<&crossbeam_channel::Receiver<ControlEnvelope>>,
    session: &ControlSession,
) -> Result<Option<Arc<InputPipeline>>, FluxError>
where
    F: Fn(InputParams) -> Result<InputPipeline, PipelineError>,
{
    let (out_w, out_h) = cfg
        .output
        .effective_dimensions(cfg.input.width, cfg.input.height);
    let placeholder: Option<Box<dyn crate::idle::Placeholder>> = if supervised_acquire(cfg) {
        match crate::idle::build_placeholder(
            &cfg.idle.resolve_paths(&session.config_base),
            out_w,
            out_h,
        ) {
            Ok(p) => Some(p),
            Err(e) => {
                warn!(error = %e, "failed to build acquire placeholder — falling back to single-attempt input acquisition");
                None
            }
        }
    } else {
        None
    };
    match acquire_input(
        cfg,
        input_builder,
        output,
        metrics,
        placeholder.as_deref(),
        control_rx,
        session,
    ) {
        Ok(Some(input)) => Ok(Some(Arc::new(input))),
        Ok(None) => {
            teardown_partial(output, chain);
            Ok(None)
        }
        Err(e) => {
            teardown_partial(output, chain);
            Err(e)
        }
    }
}

/// Build the output (loopback) pipeline and the processing context,
/// independent of the input. Stage 16 brings the output up *first* so
/// `/dev/video10` advertises CAPTURE caps and streams a placeholder
/// while the camera is acquired (or retried) — see [`acquire_input`].
fn build_output(
    cfg: &FluxConfig,
) -> Result<(OutputPipeline, ProcessingContext, &'static str), FluxError> {
    let sink = resolve_output_sink(cfg)?;
    let sink_label = output_sink_label(&sink);
    // Sink dimensions = input × `output.scale`, rounded to even pixels.
    // fps is inherited from `cfg.input.fps` verbatim; the camera's
    // detected native fps is applied to the *input* at acquire time, and
    // the output writer thread decouples the two cadences (it re-pushes
    // the latest composite at the output rate, deduped by sequence).
    let (sink_w, sink_h) = cfg
        .output
        .effective_dimensions(cfg.input.width, cfg.input.height);
    let output_params = OutputParams::new(sink_w, sink_h, cfg.input.fps, cfg.input.format, sink)
        .with_sink_format(cfg.output.format);

    let output = OutputPipeline::build(output_params)?;

    let processing_ctx = ProcessingContext {
        width: cfg.input.width,
        height: cfg.input.height,
        format: cfg.input.format,
        fps: cfg.input.fps,
        // `run_chain` fills in the supervisor's `Arc<Counters>` after
        // this returns.  `None` is the correct default for any
        // standalone caller that doesn't run a full supervisor.
        counters: None,
    };

    Ok((output, processing_ctx, sink_label))
}

/// Whether the supervised (Stage 16) always-on path applies: idle mode
/// on, a v4l2loopback sink (so a placeholder keeps the device visible),
/// and a v4l2 camera input (the only source that can be busy/absent).
/// testsrc never contends, so it keeps the plain single-attempt path.
fn supervised_acquire(cfg: &FluxConfig) -> bool {
    cfg.idle.enabled
        && matches!(classify_output(cfg), OutputSpec::V4l2(_))
        && matches!(classify_input(cfg), InputSpec::V4l2(_))
}

/// `true` for input errors that are device-contention (camera busy or
/// temporarily absent) — the only class the supervisor retries forever.
/// Everything else (missing element, bad caps/format, config) is treated
/// as permanent and propagated so a real misconfiguration fails fast.
fn is_input_contention(e: &FluxError) -> bool {
    matches!(
        e,
        FluxError::Pipeline(fluxframe_core::PipelineError::InputDeviceUnavailable { .. })
    )
}

/// Acquire (build + start) the input pipeline.
///
/// Non-supervised path: a single attempt; any error propagates (the
/// `run_auto` layer decides whether to retry).
///
/// Supervised path (Stage 16, [`supervised_acquire`]): the output is
/// already streaming, so on a *contention* error this keeps pushing the
/// placeholder to `output` and retries with exponential backoff
/// (`input.acquire_backoff_base_ms` → … → `_max_ms`), forever. A
/// permanent error still propagates. `Ok(None)` signals shutdown was
/// requested while waiting — the caller exits cleanly.
fn acquire_input<F>(
    cfg: &FluxConfig,
    input_builder: &F,
    output: &OutputPipeline,
    metrics: &RuntimeMetrics,
    placeholder: Option<&dyn crate::idle::Placeholder>,
    control_rx: Option<&crossbeam_channel::Receiver<ControlEnvelope>>,
    session: &ControlSession,
) -> Result<Option<InputPipeline>, FluxError>
where
    F: Fn(InputParams) -> Result<InputPipeline, PipelineError>,
{
    let (ph_w, ph_h) = cfg
        .output
        .effective_dimensions(cfg.input.width, cfg.input.height);
    let base = Duration::from_millis(u64::from(cfg.input.acquire_backoff_base_ms));
    let max = Duration::from_millis(u64::from(cfg.input.acquire_backoff_max_ms));
    let mut backoff = base;
    let mut logged_kind: Option<String> = None;

    loop {
        if is_shutdown_requested() {
            return Ok(None);
        }
        metrics.counters.inc_input_acquire_attempts();
        let params = InputParams::new(
            cfg.input.width,
            cfg.input.height,
            cfg.input.fps,
            cfg.input.format,
        );
        // build + start in one shot; both can surface a busy device.
        //
        // On a failed `start` the pipeline has usually reached Ready or
        // Paused, which means `v4l2src` already holds a device fd and
        // its streaming threads exist. `InputPipeline` has no `Drop`, so
        // simply dropping it here would leak both. That was survivable
        // when this ran once at startup; the supervised path retries in
        // a loop, so a camera missing for minutes would leak one
        // pipeline per attempt.
        let attempt = input_builder(params).and_then(|input| match input.start() {
            Ok(()) => Ok(input),
            Err(e) => {
                let _ = input.set_state_null();
                Err(e)
            }
        });
        match attempt {
            Ok(input) => return Ok(Some(input)),
            Err(e) => {
                let fe = FluxError::from(e);
                let Some(placeholder) = placeholder.filter(|_| is_input_contention(&fe)) else {
                    // Not supervised, or a permanent error → propagate.
                    return Err(fe);
                };
                let cont = backoff_after_contention(
                    &fe,
                    &mut logged_kind,
                    backoff,
                    placeholder,
                    ph_w,
                    ph_h,
                    cfg.input.format,
                    output,
                    metrics,
                    control_rx,
                    session,
                )?;
                if !cont {
                    // Shutdown requested during the backoff sleep.
                    return Ok(None);
                }
                backoff = (backoff * 2).min(max);
            }
        }
    }
}

/// Handle one contention failure during [`acquire_input`]: count it, log
/// it (rate-limited — `warn` once per distinct error text, `debug` on
/// repeats), push a placeholder so the loopback stays visible, then
/// sleep the current `backoff` in Ctrl-C-responsive chunks. Returns
/// `Ok(false)` if shutdown was requested during the sleep, `Ok(true)` to
/// keep retrying, `Err` only if the output itself is broken.
#[expect(
    clippy::too_many_arguments,
    reason = "extracted from acquire_input's loop purely to satisfy too-many-lines; \
              the arguments are the acquire context and bundling them adds no clarity"
)]
fn backoff_after_contention(
    fe: &FluxError,
    logged_kind: &mut Option<String>,
    backoff: Duration,
    placeholder: &dyn crate::idle::Placeholder,
    ph_w: u32,
    ph_h: u32,
    format: fluxframe_core::frame::PixelFormat,
    output: &OutputPipeline,
    metrics: &RuntimeMetrics,
    control_rx: Option<&crossbeam_channel::Receiver<ControlEnvelope>>,
    session: &ControlSession,
) -> Result<bool, FluxError> {
    metrics.counters.inc_input_acquire_failures();
    let kind = fe.to_string();
    if logged_kind.as_deref() == Some(kind.as_str()) {
        tracing::debug!(
            target: "fluxframe::idle",
            backoff_ms = backoff.as_millis() as u64,
            "input still unavailable — retrying",
        );
    } else {
        warn!(
            target: "fluxframe::idle",
            error = %kind,
            backoff_ms = backoff.as_millis() as u64,
            "input device unavailable — streaming placeholder, retrying with backoff",
        );
        *logged_kind = Some(kind);
    }
    // Output itself broken → genuinely fatal (propagates).
    push_placeholder(placeholder, ph_w, ph_h, format, output, metrics)?;
    // Ctrl-C is honoured within ~100 ms regardless of the current
    // backoff, and the control socket keeps answering meanwhile.
    Ok(!wait_serving_control(backoff, control_rx, session))
}

/// Build the [`BusListener`] watching both pipelines.  The listener is
/// returned so the caller can keep it alive (its `Drop` joins the thread).
fn build_bus_listener(
    input: &InputPipeline,
    output: &OutputPipeline,
    running: Arc<AtomicBool>,
    bus_error: Arc<Mutex<Option<FluxError>>>,
    slot: LatestFrameSlot,
    input_failure: Arc<InputFailureSignal>,
) -> BusListener {
    let pipelines = vec![
        WatchedPipeline {
            source: BusSource::Input,
            bus: input.bus(),
        },
        WatchedPipeline {
            source: BusSource::Output,
            bus: output.bus(),
        },
    ];
    BusListener::spawn(pipelines, move |event| {
        on_bus_event(&event, &running, &bus_error, &slot, &input_failure);
    })
}

/// Upper bound on how long we keep trying to recover the camera in
/// place before giving up and letting the run restart.
///
/// Escalation is not a defeat, it is the second half of the strategy:
/// `InputPipeline::reacquire` reopens *the same* device node, so a
/// camera that came back on a different `/dev/videoN` (very common after
/// a physical replug) can only be found by the auto-input loop
/// re-enumerating. Retrying in place forever would turn that case into a
/// permanent hang — the exact self-healing behaviour this path must not
/// regress.
///
/// It also bounds how long control-socket commands go unanswered: the
/// recovery runs on the worker thread, so nothing drains the command
/// channel until it finishes one way or the other.
const INPUT_RECOVERY_BUDGET: Duration = Duration::from_secs(60);

/// What [`run_supervised_loop`] should do after the worker loop returns.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LoopAction {
    /// Recover the camera in place; the output pipeline stays up.
    ReacquireInput,
    /// Hand control back to the caller (and thus to the auto-input
    /// loop, which rebuilds everything and re-selects the device).
    TeardownAll,
    /// Normal shutdown — Ctrl-C or a clean end of stream.
    Exit,
}

/// Decide what to do after the worker loop returned.
///
/// Pure so the matrix can be tested without GStreamer: building an
/// `OutputPipeline` needs a live `/dev/video10`, which no unit test has.
fn next_action(running: bool, input_failed: bool, worker_failed: bool) -> LoopAction {
    if worker_failed {
        // A chain/output error is not something reacquiring the camera
        // can fix.
        return LoopAction::TeardownAll;
    }
    if !running {
        return LoopAction::Exit;
    }
    if input_failed {
        LoopAction::ReacquireInput
    } else {
        LoopAction::Exit
    }
}

/// Run the worker loop, recovering from input-side failures in place.
///
/// The loopback output, the effect chain, the control socket, the
/// metrics reporter and the consumer detector are all created by the
/// caller and deliberately live *outside* this loop: recreating the
/// detector on every camera hiccup would reset its verdict to `Unknown`
/// (read as "consumer present"), so idle would stop engaging until the
/// consumer next reconnected.
#[expect(
    clippy::too_many_arguments,
    reason = "`session` is the one `&mut` collaborator and cannot ride in the `Copy` WorkerDeps"
)]
fn run_supervised_loop(
    deps: WorkerDeps<'_>,
    session: &mut ControlSession,
    running: &AtomicBool,
    slot: &LatestFrameSlot,
    chain: &mut EffectChain,
    output: &OutputPipeline,
    idle: &mut Option<IdleRuntime>,
    input: SupervisedInput<'_>,
) -> Result<(), FluxError> {
    // Snapshotted once here and thereafter *returned by*
    // `recover_input`, which takes it immediately before the successful
    // `reacquire()` attempt. Re-snapshotting at the top of each
    // iteration would race the bus drain in both directions: the tail of
    // the burst that killed the camera would arrive after the snapshot
    // and trigger an immediate second recovery of a healthy device,
    // while a genuinely new failure landing between `reacquire`'s
    // success and the snapshot would be swallowed, leaving the worker
    // spinning on a `recv_timeout` that can never yield a frame.
    let mut entry_generation = input.failure.generation();
    loop {
        let watch = InputFailureWatch {
            signal: input.failure,
            entry_generation,
        };
        let worker_result = run_process_loop(
            WorkerDeps { ..deps },
            session,
            running,
            slot,
            chain,
            output,
            idle.as_mut(),
            watch,
        );
        let worker_failed = worker_result.is_err();
        let action = next_action(
            running.load(Ordering::Acquire),
            watch.tripped(),
            worker_failed,
        );
        match action {
            LoopAction::Exit | LoopAction::TeardownAll => return worker_result,
            LoopAction::ReacquireInput => {
                entry_generation = recover_input(
                    deps.cfg,
                    deps.control_rx,
                    session,
                    input.pipeline,
                    output,
                    idle.as_mut(),
                    deps.metrics,
                    slot,
                    input.failure,
                    running,
                )?;
            }
        }
    }
}

/// Bring the camera back without touching the output pipeline.
///
/// Uses `InputPipeline::reacquire` — the same object, so the worker's
/// frame slot and the bus watch stay valid. Building a fresh
/// `InputPipeline` here would create a new slot and a new bus that
/// nothing is subscribed to, orphaning both.
///
/// Returns `Err` once [`INPUT_RECOVERY_BUDGET`] is spent, so the caller
/// escalates to a full restart and the auto-input loop can re-select the
/// device.
///
/// On success returns the input-failure generation observed immediately
/// before the winning `reacquire()` attempt — see [`retry_reacquire`]
/// for why the caller must adopt it verbatim.
#[allow(
    clippy::too_many_arguments,
    reason = "recovery context: every argument is a distinct collaborator the retry loop needs"
)]
fn recover_input(
    cfg: &FluxConfig,
    control_rx: Option<&crossbeam_channel::Receiver<ControlEnvelope>>,
    session: &ControlSession,
    input: &Arc<InputPipeline>,
    output: &OutputPipeline,
    idle: Option<&mut IdleRuntime>,
    metrics: &RuntimeMetrics,
    slot: &LatestFrameSlot,
    signal: &InputFailureSignal,
    running: &AtomicBool,
) -> Result<u64, FluxError> {
    let started = Instant::now();

    // Snapshot what the retry loop needs from the idle runtime, so the
    // `&mut` borrow ends here rather than spanning the whole loop.
    let placeholder = idle.as_ref().map(|rt| {
        (
            Arc::clone(&rt.placeholder),
            rt.output_w,
            rt.output_h,
            rt.output_format,
        )
    });

    if let Some(rt) = idle {
        // Join any in-flight idle-resume reload before touching the
        // pipeline: both paths drive `set_state(Null/Playing)` on the
        // same `gst::Pipeline`, and racing those transitions wedges the
        // input. This is why recovery has a single owner.
        if let Some(handle) = rt.reload_handle.take() {
            debug!("joining an in-flight reload before recovering the input");
            if handle.join().is_err() {
                warn!(
                    target: "fluxframe::idle",
                    "reload thread panicked; continuing with input recovery"
                );
            }
        }
        // `engine_ready` is deliberately left alone. It tracks the ML
        // session, which in-place recovery never unloads, and only
        // `spawn_reload_thread` ever sets it back to `true` — on the
        // idle Active-resume edge. Clearing it here would therefore pin
        // it to `false` for the rest of the run whenever a consumer
        // stayed attached across the outage, and `tick_idle` would
        // publish the placeholder forever even though the camera came
        // back. There is no window to protect either way: the worker
        // loop has already returned, so nothing ticks while we recover.
    }

    // Publish a placeholder before anything else. Until we do, the
    // output writer thread keeps re-pushing the last composite it saw,
    // so the consumer stares at a frozen frame that looks exactly like a
    // working camera.
    let push_fill = |metrics: &RuntimeMetrics| {
        if let Some((ph, w, h, fmt)) = placeholder.as_ref() {
            if let Err(e) = push_placeholder(ph.as_ref(), *w, *h, *fmt, output, metrics) {
                warn!(error = %e, "placeholder push failed during input recovery");
            }
        }
    };
    push_fill(metrics);

    if let Err(e) = input.set_state_null() {
        warn!(error = %e, "set_state_null failed while recovering the input");
    }
    // Drop whatever the dying device published last — a torn or
    // half-written frame would otherwise be the first thing the
    // consumer sees after recovery.
    slot.clear();

    let policy = RecoveryPolicy {
        budget: INPUT_RECOVERY_BUDGET,
        backoff_base: Duration::from_millis(u64::from(cfg.input.acquire_backoff_base_ms)),
        backoff_max: Duration::from_millis(u64::from(cfg.input.acquire_backoff_max_ms)),
    };
    let generation = retry_reacquire(
        &**input,
        signal,
        running,
        &metrics.counters,
        policy,
        started,
        |backoff| {
            // Keep the loopback's ring buffer fresh while we retry:
            // consumers that filter on capabilities drop a node that
            // stops producing.
            push_fill(metrics);
            wait_serving_control(backoff, control_rx, session)
        },
    )?;
    // Clear again: `reacquire` may have let a first frame land while we
    // were still deciding.
    slot.clear();
    Ok(generation)
}

/// Reopening the camera device, behind a trait so the retry loop can be
/// unit-tested without a live GStreamer pipeline and a real `/dev/video*`.
/// Mirrors the `UsageSource` seam in [`crate::idle::detector`].
trait Reacquire {
    /// Take the input pipeline to `Null` and start it again.
    fn reacquire(&self) -> Result<(), FluxError>;
}

impl Reacquire for InputPipeline {
    fn reacquire(&self) -> Result<(), FluxError> {
        // Inherent method wins name resolution here, so this is the real
        // pipeline transition rather than an infinite recursion.
        InputPipeline::reacquire(self).map_err(FluxError::from)
    }
}

/// Timing policy for [`retry_reacquire`]. Parameterised rather than read
/// from [`INPUT_RECOVERY_BUDGET`] / the config directly so tests can drive
/// the loop with millisecond-scale values.
#[derive(Debug, Clone, Copy)]
struct RecoveryPolicy {
    /// Wall-clock budget measured from `started`; once spent the loop
    /// gives up so the caller can escalate to a full restart.
    budget: Duration,
    /// First delay between attempts.
    backoff_base: Duration,
    /// Ceiling the doubling backoff saturates at.
    backoff_max: Duration,
}

/// Retry `target.reacquire()` until it succeeds, the budget is spent, or
/// the run is asked to stop.
///
/// Returns the input-failure generation observed **immediately before**
/// the winning attempt started. The supervisor adopts that value as the
/// next worker loop's entry generation, which makes the
/// failure-absorption window exact: everything raised before the attempt
/// belongs to the outage we just handled, everything raised after it is a
/// genuinely new failure that must trigger another recovery. Snapshotting
/// after the call returns instead would both re-trigger on the tail of
/// the original message burst and swallow a real new failure landing in
/// the gap.
///
/// Early exits (shutdown or `running` cleared) return the current
/// generation: the caller is on its way out and no window matters.
///
/// GStreamer-free: the pipeline arrives as `&dyn Reacquire`, and pushing
/// the placeholder plus sleeping the backoff are delegated to `pause`,
/// which returns `true` when shutdown was requested during the wait.
fn retry_reacquire(
    target: &dyn Reacquire,
    signal: &InputFailureSignal,
    running: &AtomicBool,
    counters: &fluxframe_core::metrics::Counters,
    policy: RecoveryPolicy,
    started: Instant,
    mut pause: impl FnMut(Duration) -> bool,
) -> Result<u64, FluxError> {
    let mut backoff = policy.backoff_base;
    let mut attempt: u32 = 0;
    loop {
        // `running` is the per-run token flag; `is_shutdown_requested`
        // the process-wide Ctrl-C. A run torn down through the token
        // alone used to sit here until the budget expired.
        if is_shutdown_requested() || !running.load(Ordering::Acquire) {
            return Ok(signal.generation());
        }
        attempt += 1;
        counters.inc_input_reacquire();
        let generation = signal.generation();
        match target.reacquire() {
            Ok(()) => {
                let down = started.elapsed();
                counters.add_input_down_ms(u64::try_from(down.as_millis()).unwrap_or(u64::MAX));
                info!(
                    attempt,
                    down_ms = down.as_millis() as u64,
                    "camera reacquired — output was never interrupted"
                );
                return Ok(generation);
            }
            Err(e) => {
                counters.inc_input_reacquire_failures();
                if started.elapsed() >= policy.budget {
                    warn!(
                        attempt,
                        elapsed_secs = started.elapsed().as_secs(),
                        error = %e,
                        "in-place camera recovery budget exhausted — restarting the run \
                         so the device can be re-selected"
                    );
                    return Err(e);
                }
                debug!(attempt, error = %e, "reacquire failed; will retry");
                if pause(backoff) {
                    return Ok(signal.generation());
                }
                backoff = (backoff * 2).min(policy.backoff_max);
            }
        }
    }
}

/// Shared "the input died" signal between the bus listener and the
/// worker loop.
///
/// A generation counter rather than a flag. The GStreamer bus is drained
/// on a timer, so losing a camera delivers a burst of messages: with a
/// boolean, clearing it after handling the first would immediately be
/// re-raised by the rest of the burst (an endless reacquire loop), while
/// clearing it before draining would swallow a genuinely new failure
/// that arrived during recovery. Comparing generations makes "has
/// anything failed since I started recovering?" exactly answerable.
///
/// `enabled` is false when the run has no supervised recovery path
/// (`idle.enabled = false`, or a sink with no placeholder). There an
/// input failure must stay fatal: with no placeholder to publish, the
/// writer thread would keep re-pushing the last live frame and the
/// consumer would see a frozen picture indistinguishable from a working
/// camera.
#[derive(Debug)]
pub(crate) struct InputFailureSignal {
    generation: AtomicU64,
    enabled: AtomicBool,
}

impl InputFailureSignal {
    fn new() -> Self {
        Self {
            generation: AtomicU64::new(0),
            enabled: AtomicBool::new(false),
        }
    }

    /// Take responsibility for input-side failures from now on.
    ///
    /// Separate from construction because the bus listener has to exist
    /// before the idle runtime it depends on, and only the idle runtime
    /// can tell us whether a placeholder is available to cover the
    /// outage.
    fn arm(&self) {
        self.enabled.store(true, Ordering::Release);
    }

    /// Does this signal take responsibility for failures from `source`?
    fn handles(&self, source: BusSource) -> bool {
        self.enabled.load(Ordering::Acquire) && source == BusSource::Input
    }

    /// Record an input failure.
    fn raise(&self) {
        self.generation.fetch_add(1, Ordering::Release);
    }

    /// Current generation. Snapshot it before recovering, and compare
    /// afterwards to tell "the failure I already handled" from "another
    /// one happened while I was recovering".
    fn generation(&self) -> u64 {
        self.generation.load(Ordering::Acquire)
    }
}

/// Translate a [`BusEvent`] into supervisor side-effects.  Extracted so
/// the closure passed to [`BusListener::spawn`] stays a one-liner and so
/// the handler is unit-testable.
///
/// Fatal-error promotion (busy device → typed [`PipelineError`]) lives in
/// [`fluxframe_gst::translate_fatal`] so input-side and output-side bus
/// traffic agree on phrasing.
fn on_bus_event(
    event: &BusEvent,
    running: &AtomicBool,
    bus_error: &Mutex<Option<FluxError>>,
    slot: &LatestFrameSlot,
    input_failure: &InputFailureSignal,
) {
    match event {
        BusEvent::FatalError {
            element,
            message,
            debug: debug_payload,
            source,
        } => {
            // An input-side fatal error is recoverable in place when the
            // supervised path is active: the camera is gone, but the
            // loopback output is not, and tearing it down is what makes
            // clients lose the virtual camera entirely. Route it to the
            // reacquire path instead of killing the run.
            if input_failure.handles(*source) {
                warn!(
                    ?source,
                    %element,
                    %message,
                    debug = ?debug_payload,
                    action = "reacquire",
                    "input pipeline failed — recovering without tearing the output down",
                );
                input_failure.raise();
                // Deliberately NOT `slot.close()`: `LatestFrameSlot` has
                // no reopen, so closing it here would make every frame
                // after a successful reacquire a silent no-op. The worker
                // wakes on its own poll timeout anyway.
                //
                // Deliberately NOT recorded in `bus_error` either: that
                // latch is returned at end-of-run, so a recovered failure
                // would still surface as the run's error and could mask a
                // later, real one.
                return;
            }
            error!(
                ?source,
                %element,
                %message,
                debug = ?debug_payload,
                "bus fatal error",
            );
            if let Some(pipeline_err) = fluxframe_gst::translate_fatal(event) {
                let mut guard = bus_error.lock().expect("bus_error mutex poisoned");
                if guard.is_none() {
                    *guard = Some(FluxError::from(pipeline_err));
                }
            }
            running.store(false, Ordering::Release);
            slot.close();
        }
        BusEvent::Warning {
            source,
            element,
            message,
            debug: debug_payload,
        } => {
            warn!(
                ?source,
                %element,
                %message,
                debug = ?debug_payload,
                "bus warning",
            );
        }
        BusEvent::Eos { source } => {
            // `v4l2src` reports a hot-unplug as EOS at least as often as
            // it reports an error, so this needs the same treatment —
            // otherwise the most common way to lose the camera still
            // takes the loopback down with it.
            if input_failure.handles(*source) {
                warn!(?source, action = "reacquire", "input pipeline reached EOS");
                input_failure.raise();
                return;
            }
            info!(?source, "pipeline EOS");
            running.store(false, Ordering::Release);
            slot.close();
        }
        // `BusEvent` is `#[non_exhaustive]`: future variants land here
        // until the supervisor is taught to interpret them.
        _ => {
            warn!(?event, "unhandled bus event variant");
        }
    }
}

/// Build a [`MetricsReporter`] when periodic reporting is enabled by
/// the config, otherwise return `None`.  A `None` return means the
/// teardown summary is the only line the operator sees — useful for
/// CI / tests that do not want the per-window noise.
fn spawn_metrics_reporter(
    cfg: &FluxConfig,
    metrics: &RuntimeMetrics,
    running: &Arc<AtomicBool>,
) -> Option<MetricsReporter> {
    let secs = cfg.realtime.metrics_interval_secs;
    if secs == 0 {
        tracing::debug!("metrics reporter disabled by config (metrics_interval_secs = 0)");
        return None;
    }
    let interval = Duration::from_secs(u64::from(secs));
    match MetricsReporter::spawn(metrics.clone(), interval, Arc::clone(running)) {
        Ok(handle) => {
            tracing::debug!(secs, "metrics reporter spawned");
            Some(handle)
        }
        Err(e) => {
            warn!(error = %e, "could not spawn metrics reporter; teardown summary only");
            None
        }
    }
}

/// Mutable per-iteration state of the worker thread.
///
/// Carved out of [`run_process_loop`] so the orchestration skeleton
/// stays a thin wrapper while per-frame and control-drain logic each
/// live in their own helpers. Stage 15 idle wiring is grafted onto
/// the same struct without bloating the loop body.
///
/// Both `working_cfg` and `active_preset` are owned working copies,
/// not references into the caller's config: `reload` rebinds
/// `working_cfg` to a freshly-read `FluxConfig`, and Stage 13
/// `Set`/`SetChain` commands mutate `active_preset` alongside the live
/// chain so `current_config`/introspection stay consistent and chain
/// composition changes have a stable rebuild source.
struct WorkerState {
    frame_context: FrameContext,
    /// Track fallback edges so a single-frame visual artefact
    /// ("flicker") caused by an inference miss surfaces as a warn line
    /// tied to the exact frame_seq, instead of being lost in the
    /// per-frame debug noise.
    prev_fallback: bool,
    frames_seen: u64,
    // Deliberately no preset or config state: that lives in
    // `ControlSession`, which outlives this struct. `WorkerState` is
    // rebuilt every time the worker loop is re-entered after camera
    // recovery, and keeping the preset here used to roll it back to the
    // startup one while the edited chain kept running.
}

impl WorkerState {
    fn new(metrics: &RuntimeMetrics) -> Self {
        Self {
            frame_context: FrameContext {
                telemetry: metrics.effect_telemetry(),
                ..FrameContext::default()
            },
            prev_fallback: false,
            frames_seen: 0,
        }
    }
}

/// Drain any pending control commands before processing the next
/// frame. Each command is fully applied (or rejected) before the
/// worker reads from the slot, so the swap is atomic with respect to
/// frame boundaries.
fn drain_control_commands(
    session: &mut ControlSession,
    control_rx: Option<&crossbeam_channel::Receiver<ControlEnvelope>>,
    processing_ctx: &ProcessingContext,
    chain: &mut EffectChain,
    telemetry: &fluxframe_core::EffectTelemetry,
) {
    let Some(rx) = control_rx else {
        return;
    };
    while let Ok(envelope) = rx.try_recv() {
        // Capture variant label BEFORE the move into
        // `apply_control_command`. Slow control commands silently eat
        // frame budget (~33 ms at 30 fps), so surface elapsed_us per
        // command for diagnosis.
        let cmd_kind = command_label(&envelope.cmd);
        let start = Instant::now();
        let response =
            apply_control_command(session, processing_ctx, chain, telemetry, envelope.cmd);
        tracing::debug!(
            command = cmd_kind,
            elapsed_us = start.elapsed().as_micros() as u64,
            "control command applied",
        );
        // Best-effort: if the listener already dropped the reply
        // receiver, the client has disconnected and we simply move on.
        let _ = envelope.reply_tx.send(response);
    }
}

/// Run the effect chain on a single frame and forward it to the
/// output sink. Returns `Err` only on unrecoverable failure — the
/// caller stops the worker loop.
fn process_one_frame(
    state: &mut WorkerState,
    mut frame: fluxframe_core::frame::VideoFrame,
    chain: &mut EffectChain,
    output: &OutputPipeline,
    metrics: &RuntimeMetrics,
    slot: &LatestFrameSlot,
    no_consumer: bool,
) -> Result<(), FluxError> {
    let recv_at = Instant::now();
    metrics.counters.inc_frames_in();
    state.frames_seen += 1;

    state.frame_context.frame_sequence = frame.meta.sequence;
    state.frame_context.frame_timestamp = frame.meta.timestamp;
    state.frame_context.fallback_active = false;

    let pre_process = Instant::now();
    if let Err(e) = chain.process(&mut frame, &mut state.frame_context) {
        metrics.counters.inc_effect_error();
        error!(error = %e, "effect chain failed; stopping");
        return Err(FluxError::from(e));
    }
    metrics.processing.record_duration(pre_process.elapsed());

    if state.frame_context.fallback_active != state.prev_fallback {
        warn!(
            frame_seq = state.frame_context.frame_sequence,
            fallback_active = state.frame_context.fallback_active,
            "effect-chain fallback state changed (passthrough frame)"
        );
        if state.frame_context.fallback_active {
            // Count edges into fallback only — a steady passthrough
            // run would otherwise inflate the counter every frame.
            metrics.counters.inc_fallback();
        }
        state.prev_fallback = state.frame_context.fallback_active;
    }

    let pre_push = Instant::now();
    if let Err(e) = output.push_frame(frame) {
        error!(error = %e, "output.push_frame failed; stopping");
        return Err(e.into());
    }
    metrics.output.record_duration(pre_push.elapsed());
    metrics.end_to_end.record_duration(recv_at.elapsed());
    metrics.counters.inc_frames_out();
    if no_consumer {
        metrics.counters.inc_frames_out_while_no_consumer();
    }

    if state.frames_seen % DROPPED_SYNC_INTERVAL == 0 {
        metrics.sync_dropped(slot.dropped_count());
    }
    Ok(())
}

/// May the worker pull a real frame and run the effect chain?
///
/// Both conditions are load-bearing, and the second one is a trap worth
/// naming: `engine_ready` is only ever set back to `true` by the idle
/// Active-resume edge. Anything that clears it outside that flow pins
/// the daemon to the placeholder for the rest of the run — the camera
/// keeps working, the logs look healthy, and the consumer sees a still
/// image. Clear it only where a resume edge is guaranteed to follow.
fn active_allowed(level: crate::idle::IdleLevel, engine_ready: bool) -> bool {
    matches!(level, crate::idle::IdleLevel::Active) && engine_ready
}

/// Does the consumer detector currently say nobody is reading the
/// loopback?
///
/// A `None` idle runtime (idle disabled, or a sink with no detector)
/// means there is no presence signal at all, so frames are never
/// attributed as wasted — an absent signal is not evidence of an absent
/// consumer.
fn no_consumer_attached(idle: Option<&IdleRuntime>) -> bool {
    idle.is_some_and(|rt| {
        crate::idle::ConsumerStatus::from_u8(rt.consumer_status.load(Ordering::Acquire))
            == crate::idle::ConsumerStatus::Absent
    })
}

/// Push a pre-rendered placeholder frame to the output, bypassing
/// the effect chain. Used by the worker loop while in Idle to keep
/// v4l2loopback's ring buffer fresh (and the device enumerable by
/// Chrome) without paying the cost of the full pipeline.
fn push_placeholder(
    placeholder: &dyn crate::idle::Placeholder,
    width: u32,
    height: u32,
    format: fluxframe_core::frame::PixelFormat,
    output: &OutputPipeline,
    metrics: &RuntimeMetrics,
) -> Result<(), FluxError> {
    let frame = placeholder.render(width, height, format)?;
    if let Err(e) = output.push_frame(frame) {
        error!(error = %e, "output.push_frame failed during idle placeholder push");
        return Err(e.into());
    }
    metrics.counters.inc_idle_frames_pushed();
    Ok(())
}

/// Bundle of Stage 15 idle infrastructure handed to the worker loop.
/// `None` when idle mode is disabled or unavailable (non-V4L2 sink,
/// non-Linux host); the loop then runs the Stage 14 path verbatim.
struct IdleRuntime {
    /// Pure state machine — owned exclusively by the worker thread.
    state_machine: crate::idle::IdleStateMachine,
    /// Detector → worker status atomic. Worker `Acquire`-loads each
    /// tick; the detector thread `Release`-stores on transition.
    consumer_status: Arc<std::sync::atomic::AtomicU8>,
    /// Cached placeholder built once at startup (or supervisor
    /// reload) for the configured `(output_w, output_h, format)`.
    placeholder: Arc<dyn crate::idle::Placeholder>,
    /// Output appsrc dimensions + format — the placeholder was
    /// built for exactly these and the worker passes them on every
    /// `render` call.
    output_w: u32,
    output_h: u32,
    output_format: fluxframe_core::frame::PixelFormat,
    /// Shared input handle. The worker calls `set_state_null` on
    /// EnterIdle and the reload thread calls `start` on resume.
    input: Arc<InputPipeline>,
    /// `false` whenever the supervisor must not call
    /// `chain.process` — true in Active, cleared on resume while the
    /// reload thread restarts the input, re-armed by that thread.
    engine_ready: Arc<AtomicBool>,
    /// Live reload thread, if one is currently in flight. The
    /// worker checks `is_finished` periodically to surface failures
    /// in logs (Step 5 wires a `resume_latency_ms` histogram here).
    reload_handle: Option<std::thread::JoinHandle<crate::idle::reload::ResumeOutcome>>,
    /// Fix #7: tracks whether the previous worker iteration ran the
    /// full chain (`true`) or pushed a placeholder (`false`). The
    /// supervisor logs a one-shot `info!` line at every false→true
    /// transition so "stuck in placeholder?" troubleshooting surfaces
    /// the resume edge as an obvious line in the log stream.
    /// Defaults to `true` because a freshly-built runtime is in the
    /// Active level by construction.
    was_active: bool,
    /// Detector thread handle, kept alive for the duration of the
    /// run. Its `Drop` impl joins the detector thread.
    #[cfg(target_os = "linux")]
    _detector: crate::idle::ConsumerDetector,
}

/// Construct the idle-runtime bundle if the configuration enables
/// it, the host platform supports the detector, and the sink is a
/// V4L2 loopback. Returns `None` for non-V4L2 sinks, non-Linux
/// hosts, or when `idle.enabled = false` — the caller then runs
/// the Stage 14 worker loop unchanged.
fn build_idle_runtime(
    cfg: &FluxConfig,
    config_base: &ConfigBase,
    input: &Arc<InputPipeline>,
    output: &OutputPipeline,
    running: &Arc<AtomicBool>,
    metrics: &RuntimeMetrics,
) -> Option<IdleRuntime> {
    if !cfg.idle.enabled {
        return None;
    }
    #[cfg(target_os = "linux")]
    {
        let sink = resolve_output_sink(cfg).ok()?;
        // Fix #6: surface the silent fallback so an operator who set
        // `idle.enabled = true` with a non-V4L2 sink sees why idle is
        // not taking effect, rather than silently running the Stage 14
        // path.
        let Some(device_path) = crate::idle::device_path(&sink) else {
            warn!(
                "idle.enabled = true but sink is not v4l2loopback — idle disabled \
                 (the consumer-presence detector needs a /dev/videoN device path for the \
                 inotify watch + /proc/*/fd walk)"
            );
            return None;
        };
        let my_pid = std::process::id();

        let (sink_w, sink_h) = cfg
            .output
            .effective_dimensions(cfg.input.width, cfg.input.height);
        // Placeholder format must match the appsrc's caps — that's
        // the *input* format on the supervisor's pipeline. The
        // output's sink format is reached via videoconvert downstream.
        let placeholder_format = cfg.input.format;
        let placeholder: Arc<dyn crate::idle::Placeholder> = match crate::idle::build_placeholder(
            &cfg.idle.resolve_paths(config_base),
            sink_w,
            sink_h,
        ) {
            Ok(p) => p.into(),
            Err(e) => {
                warn!(error = %e, "failed to build idle placeholder — idle mode disabled");
                return None;
            }
        };

        // Ask the loopback for a capture-usage subscription. `None`
        // means this sink owns no device fd (only the direct-write path
        // does); `Err` means the driver predates the event. Neither is
        // fatal — the detector decides what to do based on
        // `presence_source`, and only `kernel_event` insists on it.
        let watch = match output.subscribe_consumer_events() {
            Some(Ok(watch)) => Some(watch),
            Some(Err(e)) => {
                warn!(
                    error = %e,
                    "could not subscribe to loopback client-usage events \
                     (v4l2loopback older than 0.13?)"
                );
                None
            }
            None => None,
        };

        let detector_running = Arc::clone(running);
        let detector = crate::idle::ConsumerDetector::spawn(
            crate::idle::DetectorParams {
                device_path,
                my_pid,
                poll_interval: std::time::Duration::from_millis(u64::from(
                    cfg.idle.poll_interval_ms,
                )),
                mode: cfg.idle.presence_source,
                // Never decay a balance-backed verdict faster than the
                // grace period the operator chose for entering idle:
                // below that, the decay would race the very hysteresis
                // it sits behind.
                stale_balance_after: std::time::Duration::from_secs(u64::from(
                    cfg.idle.teardown_secs.max(1),
                )),
                // The same knob, but a different contract: this one is
                // the floor under the resync path's event-silence
                // threshold, and must not follow a retune of the
                // heuristic's decay above.
                teardown_grace: std::time::Duration::from_secs(u64::from(
                    cfg.idle.teardown_secs.max(1),
                )),
                // `0` is the operator's "never re-read" switch; the
                // detector takes the absence of an interval rather than
                // a zero-length one, so the off case cannot be confused
                // with "as often as possible".
                resync_interval: (cfg.idle.resync_interval_secs > 0).then(|| {
                    std::time::Duration::from_secs(u64::from(cfg.idle.resync_interval_secs))
                }),
            },
            detector_running,
            Arc::clone(&metrics.counters),
            watch,
        );
        // The detector handle moves into the runtime so its Drop
        // runs when the worker loop exits.
        let consumer_status = detector.status_handle();

        Some(IdleRuntime {
            state_machine: crate::idle::IdleStateMachine::new(Instant::now()),
            consumer_status,
            placeholder,
            output_w: sink_w,
            output_h: sink_h,
            output_format: placeholder_format,
            input: Arc::clone(input),
            engine_ready: Arc::new(AtomicBool::new(true)),
            reload_handle: None,
            was_active: true,
            _detector: detector,
        })
    }
    #[cfg(not(target_os = "linux"))]
    {
        let _ = (config_base, input, running, metrics);
        warn!(
            target: "fluxframe::idle",
            "idle mode requested but host is not Linux — idle disabled (the /proc/*/fd consumer detector is Linux-only)"
        );
        None
    }
}

/// Non-blocking reap of a finished reload thread. Returns its
/// [`crate::idle::reload::ResumeOutcome`] when the thread has already
/// exited (the `join` is then instant); leaves an in-flight handle in
/// place and returns `None`. Called by [`tick_idle`] every iteration.
///
/// Takes the handle slot directly (rather than the whole `IdleRuntime`)
/// so it stays unit-testable without fabricating a full runtime. The
/// shutdown path does its own *blocking* join instead — it must wait for
/// an in-flight reload to finish before teardown, which this
/// non-blocking reaper deliberately does not.
fn reap_reload(
    reload_handle: &mut Option<std::thread::JoinHandle<crate::idle::reload::ResumeOutcome>>,
) -> Option<crate::idle::reload::ResumeOutcome> {
    let handle = reload_handle.take()?;
    if !handle.is_finished() {
        *reload_handle = Some(handle);
        return None;
    }
    if let Ok(outcome) = handle.join() {
        Some(outcome)
    } else {
        warn!(target: "fluxframe::idle", "reload thread panicked");
        None
    }
}

/// Handle the side effects of an `IdleEdge`. Updates counters,
/// reconfigures the input pipeline, and spawns the off-worker
/// reload thread when needed.
fn handle_idle_edge(
    idle: &mut IdleRuntime,
    edge: crate::idle::IdleEdge,
    slot: &LatestFrameSlot,
    output: &OutputPipeline,
    metrics: &RuntimeMetrics,
) {
    use crate::idle::IdleEdge;
    match edge {
        IdleEdge::None => {}
        IdleEdge::EnterIdle => {
            metrics.counters.inc_idle_entered();
            info!(target: "fluxframe::idle", "entering idle — tearing down input pipeline");
            if let Err(e) = idle.input.set_state_null() {
                warn!(error = %e, "set_state_null failed on idle entry");
            }
            // Discard any in-flight frame the capture thread published
            // before the pipeline transitioned to Null — resuming with
            // a stale frame on the chain would be visible to the
            // consumer as a single mis-timed image.
            slot.clear();
        }
        IdleEdge::ResumeActive => {
            info!(target: "fluxframe::idle", "consumer reconnected — spawning reload thread");
            // Push one placeholder immediately to clear
            // v4l2loopback's stale-frame replay before any real
            // frames arrive (50–300 ms warmup on UVC).
            if let Err(e) = push_placeholder(
                idle.placeholder.as_ref(),
                idle.output_w,
                idle.output_h,
                idle.output_format,
                output,
                metrics,
            ) {
                warn!(error = %e, "resume-edge placeholder push failed");
            }
            // Spawn the reload coordinator. The engine reloader is a
            // no-op here because the ONNX session is kept warm across
            // Idle; `input.reacquire()` inside `spawn_reload_thread` is
            // the meaningful work.
            //
            // Double-spawn guard: a finished reload was already reaped
            // (and acted on) in `tick_idle` before this edge dispatch,
            // so `reload_handle` is either empty or an in-flight thread.
            // Never kick a second reload over an in-flight one — racing
            // the GStreamer state transitions would wedge the input.
            if let Some(handle) = idle.reload_handle.take() {
                if !handle.is_finished() {
                    warn!("a previous reload thread is still in flight; not spawning a second one");
                    idle.reload_handle = Some(handle);
                    return;
                }
                // Straggler — unreachable in the normal flow (tick_idle
                // reaps finished handles first); join to avoid detaching.
                let _ = handle.join();
            }
            // Clear `engine_ready` synchronously on this (worker) thread
            // before launching, so no tick observes `Active + ready`
            // during the resume window (the input was just set to Null
            // on EnterIdle).
            idle.engine_ready.store(false, Ordering::Release);
            let input = Arc::clone(&idle.input);
            let engine_ready = Arc::clone(&idle.engine_ready);
            idle.reload_handle = Some(crate::idle::reload::spawn_reload_thread(
                input,
                engine_ready,
                || Ok(()),
            ));
        }
    }
}

/// Result of [`tick_idle`]: tells [`run_process_loop`] whether the
/// idle state-machine handled this iteration (`Continue`) or whether
/// the worker should fall through and pull a real frame
/// (`ProcessFrame`). The variant carries no payload — placeholder
/// pushes are issued inside the helper so the caller only sees a
/// two-arm match.
enum IdleTickAction {
    /// Idle helper either pushed a placeholder or parked on the
    /// slot; the caller should `continue` to the next loop iteration.
    Continue,
    /// No idle handling required (idle disabled OR Active level with
    /// engine ready); the caller should pull a frame and run the
    /// chain.
    ProcessFrame,
}

/// Run one tick of the idle state machine and dispatch the resulting
/// edge + level.  Pulled out of [`run_process_loop`] so the orchestrator
/// loop stays a thin three-stage skeleton (drain control commands → tick
/// idle → process frame). Mixing the state-machine tick, edge dispatch,
/// placeholder push and shutdown-aware park inside the loop body
/// stacked three abstraction levels on top of each other; this helper
/// owns one of them.
///
/// `session` is only read — the one field used is `session.cfg.idle`,
/// which the idle state machine uses as its timing source.
fn tick_idle(
    idle: Option<&mut IdleRuntime>,
    session: &ControlSession,
    slot: &LatestFrameSlot,
    output: &OutputPipeline,
    metrics: &RuntimeMetrics,
    input_failure: &InputFailureSignal,
) -> Result<IdleTickAction, FluxError> {
    let Some(idle_rt) = idle else {
        return Ok(IdleTickAction::ProcessFrame);
    };
    // Reap a finished reload thread BEFORE ticking the state machine so
    // its outcome is never dropped or double-spawned. A failed camera
    // reacquire returns a transient error here, which unwinds
    // `run_process_loop` → `run_chain` → `run_once`. Under
    // `device = "auto"` that re-enters `run_auto`, which re-enumerates
    // and re-selects the (re-plugged) device; for a fixed device path
    // the daemon exits and relies on the service supervisor to restart
    // it (documented in the changelog). Either way beats the old
    // behaviour of spinning in placeholder forever.
    if let Some(outcome) = reap_reload(&mut idle_rt.reload_handle) {
        use crate::idle::reload::ResumeOutcome;
        match outcome {
            // The reload thread already logs completion (at info, with
            // elapsed); nothing to do here but drop the reaped handle.
            ResumeOutcome::Completed => {}
            ResumeOutcome::EngineFailed(reason) => {
                // ORT/disk problem, not the camera — stay in placeholder;
                // a later ResumeActive edge re-spawns the reload attempt.
                warn!(
                    target: "fluxframe::idle",
                    error = %reason,
                    "reload: engine rebuild failed — staying in placeholder mode"
                );
            }
            ResumeOutcome::InputFailed(e) => {
                metrics.counters.inc_resume_failures();
                if input_failure.handles(fluxframe_gst::BusSource::Input) {
                    // Hand this to the supervised recovery path instead
                    // of unwinding the run. This is the single most
                    // common way the camera is lost in practice — the
                    // consumer reconnects, we resume, and the device is
                    // not back yet — and unwinding here tore the
                    // loopback down every time, which is precisely what
                    // made clients lose the virtual camera.
                    warn!(
                        target: "fluxframe::idle",
                        error = %e,
                        action = "reacquire",
                        "reload: camera reacquire failed — recovering without \
                         tearing the output down"
                    );
                    input_failure.raise();
                    return Ok(IdleTickAction::Continue);
                }
                warn!(
                    target: "fluxframe::idle",
                    error = %e,
                    "reload: camera reacquire failed — restarting chain to re-select the device"
                );
                return Err(e);
            }
        }
    }
    let status =
        crate::idle::ConsumerStatus::from_u8(idle_rt.consumer_status.load(Ordering::Acquire));
    let tick = idle_rt
        .state_machine
        .tick(status, Instant::now(), &session.cfg.idle);
    handle_idle_edge(idle_rt, tick.edge, slot, output, metrics);
    let active_allowed = active_allowed(tick.level, idle_rt.engine_ready.load(Ordering::Acquire));
    if !active_allowed {
        if let Err(e) = push_placeholder(
            idle_rt.placeholder.as_ref(),
            idle_rt.output_w,
            idle_rt.output_h,
            idle_rt.output_format,
            output,
            metrics,
        ) {
            error!(error = %e, "placeholder push failed; stopping");
            return Err(e);
        }
        idle_rt.was_active = false;
        // Park up to `next_tick_in` on the slot (which doubles as a
        // shutdown signal) so we don't busy-loop. The worker still
        // gets woken if a real frame ever lands (resume happened and
        // the input came back).
        let _ = slot.recv_timeout(tick.next_tick_in);
        return Ok(IdleTickAction::Continue);
    }
    // Fix #7: log the one-shot resume edge — placeholder mode → active
    // processing. The state machine's own `EnterIdle`/`ResumeActive`
    // edges fire on the consumer-status transition; this complementary
    // line surfaces when the worker actually goes back to running the
    // full chain (which may lag the `ResumeActive` edge by the reload
    // thread's `input.start()` window).
    if !idle_rt.was_active {
        info!(target: "fluxframe::idle", "resumed active processing");
        idle_rt.was_active = true;
    }
    Ok(IdleTickAction::ProcessFrame)
}

/// Stable-during-run dependencies handed to [`run_process_loop`].
///
/// The supervisor's worker loop reaches for ~10 values — some of them
/// never change across iterations (the run's `FluxConfig`, the
/// processing context, the metrics bundle, the control receiver).
/// Bundling those in one struct keeps the loop's signature manageable
/// and makes the genuinely per-iteration handles (`running`, `slot`,
/// `chain`, `output`, `idle`) stand out at the call site. The
/// [`ControlSession`] travels separately: it is mutable and outlives
/// the run.
///
/// All fields are borrowed references, so the struct is `Copy` and
/// can be passed by value to the loop without imposing a borrow
/// lifetime past the call.
#[derive(Clone, Copy)]
struct WorkerDeps<'a> {
    cfg: &'a FluxConfig,
    processing_ctx: &'a ProcessingContext,
    metrics: &'a RuntimeMetrics,
    /// Control-socket receiver, or `None` when the socket is disabled.
    control_rx: Option<&'a crossbeam_channel::Receiver<ControlEnvelope>>,
}

/// The input-failure signal paired with the generation observed when
/// the worker loop was entered.
///
/// Carrying the two together makes the only meaningful question —
/// "has the input failed *since I started*?" — a method rather than a
/// comparison the caller could get subtly wrong.
#[derive(Clone, Copy)]
struct InputFailureWatch<'a> {
    signal: &'a InputFailureSignal,
    entry_generation: u64,
}

/// The input side of a supervised run: the pipeline to recover and the
/// signal that says when it needs recovering. Paired because neither is
/// useful to the supervisor without the other.
#[derive(Clone, Copy)]
struct SupervisedInput<'a> {
    pipeline: &'a Arc<InputPipeline>,
    failure: &'a InputFailureSignal,
}

impl InputFailureWatch<'_> {
    /// Has a new input failure been raised since this watch was taken?
    fn tripped(&self) -> bool {
        self.signal.generation() != self.entry_generation
    }
}

#[expect(
    clippy::too_many_arguments,
    reason = "`session` is the one `&mut` collaborator and cannot ride in the `Copy` WorkerDeps"
)]
fn run_process_loop(
    deps: WorkerDeps<'_>,
    session: &mut ControlSession,
    running: &AtomicBool,
    slot: &LatestFrameSlot,
    chain: &mut EffectChain,
    output: &OutputPipeline,
    mut idle: Option<&mut IdleRuntime>,
    input_failure: InputFailureWatch<'_>,
) -> Result<(), FluxError> {
    let mut state = WorkerState::new(deps.metrics);
    // Leaving on a *new* input failure hands control to the supervisor,
    // which recovers the camera and calls back in. Without this the loop
    // would spin against a dead input: `tick_idle` still reports Active
    // while a consumer is attached, so every iteration would fall
    // through to a `recv_timeout` that can never succeed.
    while running.load(Ordering::Acquire) && !input_failure.tripped() {
        drain_control_commands(
            session,
            deps.control_rx,
            deps.processing_ctx,
            chain,
            &state.frame_context.telemetry,
        );

        // Stage 15 idle integration: tick the state machine, dispatch
        // any side-effect edge, choose between Active level (pull a
        // real frame + run chain) and Placeholder level (push the
        // cached fill).
        match tick_idle(
            idle.as_deref_mut(),
            session,
            slot,
            output,
            deps.metrics,
            input_failure.signal,
        )? {
            IdleTickAction::Continue => continue,
            IdleTickAction::ProcessFrame => {}
        }

        let Some(frame) = slot.recv_timeout(WORKER_POLL_TIMEOUT) else {
            // Either timeout (no frame within the poll window) or slot
            // closed by shutdown.  Re-check the flag and continue.
            continue;
        };
        process_one_frame(
            &mut state,
            frame,
            chain,
            output,
            deps.metrics,
            slot,
            no_consumer_attached(idle.as_deref()),
        )?;
    }
    // Reap any in-flight reload thread so it doesn't outlive the
    // supervisor. Surface the wall-clock cost so a reload that was
    // racing shutdown shows up in the teardown log line instead of
    // disappearing into a dropped `JoinHandle`.
    if let Some(idle_rt) = idle.as_mut() {
        if let Some(handle) = idle_rt.reload_handle.take() {
            match handle.join() {
                Ok(outcome) => {
                    tracing::debug!(
                        target: "fluxframe::idle",
                        ?outcome,
                        "reload thread reaped at shutdown",
                    );
                }
                Err(_) => {
                    warn!(target: "fluxframe::idle", "reload thread panicked during shutdown");
                }
            }
        }
    }
    Ok(())
}

fn teardown(input: &InputPipeline, output: &OutputPipeline, chain: &mut EffectChain) {
    if let Err(e) = input.stop() {
        warn!(error = %e, "input.stop failed");
    }
    if let Err(e) = output.stop() {
        warn!(error = %e, "output.stop failed");
    }
    if let Err(e) = chain.shutdown_all() {
        warn!(error = %e, "effect chain shutdown reported an error");
    }
}

fn resolve_output_sink(cfg: &FluxConfig) -> Result<OutputSink, FluxError> {
    // Routing rules (see Stage 2 plan, §"Output side"):
    //   * "auto"             -> autovideosink (manual glance verification).
    //   * "fakesink"         -> fakesink (CI / dev smoke without a loopback).
    //   * /dev/...           -> v4l2sink to a loopback device.
    //   * "pipewire[:name]"  -> pipewiresink publishing a PW node.
    //   * everything else    -> structured §27 Config error.
    //
    // Triage lives in [`classify_output`]; this function only maps the
    // typed `OutputSpec` onto the GStreamer-facing `OutputSink`.
    match classify_output(cfg) {
        OutputSpec::Auto => Ok(OutputSink::Auto),
        OutputSpec::Fake => Ok(OutputSink::Fake),
        OutputSpec::V4l2(device) => Ok(OutputSink::V4l2Loopback { device }),
        OutputSpec::Pipewire(node_name) => Ok(OutputSink::Pipewire { node_name }),
        OutputSpec::Unsupported(d) => Err(FluxError::Config {
            reason: format!("output '{d}' is not supported"),
            hint: Some("supported outputs: auto, fakesink, /dev/video<N>, pipewire[:name]".into()),
        }),
    }
}

fn output_sink_label(sink: &OutputSink) -> &'static str {
    // `OutputSink` is not `#[non_exhaustive]` inside the workspace, so
    // this match is genuinely exhaustive: adding a variant will produce
    // a compile-time prompt here.  Borrowed because `V4l2Loopback` owns
    // a `PathBuf` and is therefore no longer `Copy`.
    match sink {
        OutputSink::Fake => "fakesink",
        OutputSink::Auto => "autovideosink",
        OutputSink::V4l2Loopback { .. } => "v4l2sink",
        OutputSink::Pipewire { .. } => "pipewiresink",
    }
}

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

    fn base_cfg() -> FluxConfig {
        // Default Test configuration: start from `FluxConfig::default()`.
        // The fields tweaked here are the ones exercised by each test.
        FluxConfig::default()
    }

    // --- bus-event routing -------------------------------------------

    fn fatal(source: BusSource) -> BusEvent {
        BusEvent::FatalError {
            source,
            element: "input_src".into(),
            message: "Device '/dev/video0' is busy".into(),
            debug: None,
        }
    }

    /// Run one bus event against fresh state and report what it did.
    fn route(event: &BusEvent, supervised: bool) -> (bool, bool, u64, bool) {
        let running = AtomicBool::new(true);
        let bus_error = Mutex::new(None);
        let slot = LatestFrameSlot::new();
        let signal = InputFailureSignal::new();
        if supervised {
            signal.arm();
        }
        on_bus_event(event, &running, &bus_error, &slot, &signal);
        (
            running.load(Ordering::Acquire),
            slot.is_closed(),
            signal.generation(),
            bus_error.lock().expect("poisoned").is_some(),
        )
    }

    #[test]
    fn supervised_input_fatal_is_recovered_not_fatal() {
        let (running, closed, generation, latched) = route(&fatal(BusSource::Input), true);
        assert!(running, "an input failure must not stop the run");
        // The load-bearing assertion: `LatestFrameSlot` has no reopen, so
        // closing it here would silently discard every frame produced
        // after a successful recovery.
        assert!(!closed, "the frame slot must stay open across recovery");
        assert_eq!(generation, 1, "the supervisor must be told to recover");
        assert!(
            !latched,
            "a recovered failure must not be returned as the run's error"
        );
    }

    #[test]
    fn output_fatal_is_always_fatal() {
        // Nothing about reacquiring the camera can fix the sink.
        let (running, closed, generation, latched) = route(&fatal(BusSource::Output), true);
        assert!(!running);
        assert!(closed);
        assert_eq!(generation, 0);
        assert!(latched);
    }

    #[test]
    fn unsupervised_input_fatal_stays_fatal() {
        // Without a placeholder the writer thread would keep re-pushing
        // the last live frame, so the consumer would see a frozen image
        // instead of any indication that the camera is gone.
        let (running, closed, generation, latched) = route(&fatal(BusSource::Input), false);
        assert!(!running);
        assert!(closed);
        assert_eq!(generation, 0);
        assert!(latched);
    }

    #[test]
    fn supervised_input_eos_is_recovered() {
        // `v4l2src` reports a hot-unplug as EOS at least as often as it
        // reports an error.
        let (running, closed, generation, _) = route(
            &BusEvent::Eos {
                source: BusSource::Input,
            },
            true,
        );
        assert!(running);
        assert!(!closed);
        assert_eq!(generation, 1);
    }

    #[test]
    fn output_eos_still_ends_the_run() {
        let (running, closed, generation, _) = route(
            &BusEvent::Eos {
                source: BusSource::Output,
            },
            true,
        );
        assert!(!running);
        assert!(closed);
        assert_eq!(generation, 0);
    }

    #[test]
    fn warnings_have_no_side_effects() {
        let (running, closed, generation, latched) = route(
            &BusEvent::Warning {
                source: BusSource::Input,
                element: "input_src".into(),
                message: "something odd".into(),
                debug: None,
            },
            true,
        );
        assert!(running);
        assert!(!closed);
        assert_eq!(generation, 0);
        assert!(!latched);
    }

    #[test]
    fn a_burst_of_failures_raises_distinct_generations() {
        // The bus is drained on a timer, so losing a camera delivers
        // several messages. A boolean flag could not distinguish "the
        // failure I am already recovering from" from "another one just
        // happened", which is why this is a counter.
        let signal = InputFailureSignal::new();
        signal.arm();
        assert_eq!(signal.generation(), 0);
        signal.raise();
        signal.raise();
        assert_eq!(signal.generation(), 2);
    }

    // --- supervisor decision matrix ----------------------------------

    #[test]
    fn an_unarmed_signal_leaves_input_failures_fatal() {
        // Config may say "supervised", but if `build_idle_runtime` bailed
        // out there is no placeholder to cover the outage, and recovering
        // would leave the consumer staring at a frozen frame.
        let signal = InputFailureSignal::new();
        assert!(!signal.handles(BusSource::Input));
        signal.arm();
        assert!(signal.handles(BusSource::Input));
        // Arming never claims the output side.
        assert!(!signal.handles(BusSource::Output));
    }

    #[test]
    fn active_frames_need_both_an_active_level_and_a_ready_engine() {
        use crate::idle::IdleLevel;
        assert!(active_allowed(IdleLevel::Active, true));
        // Regression guard: anything that clears `engine_ready` outside
        // the idle resume edge pins the daemon to the placeholder for the
        // rest of the run, because only that edge ever sets it back.
        assert!(!active_allowed(IdleLevel::Active, false));
        assert!(!active_allowed(IdleLevel::Placeholder, true));
    }

    #[test]
    fn next_action_recovers_only_a_live_run_with_a_failed_input() {
        assert_eq!(next_action(true, true, false), LoopAction::ReacquireInput);
        // Clean exit of the worker loop.
        assert_eq!(next_action(true, false, false), LoopAction::Exit);
        // Ctrl-C.
        assert_eq!(next_action(false, false, false), LoopAction::Exit);
        // Shutdown wins over a concurrent input failure.
        assert_eq!(next_action(false, true, false), LoopAction::Exit);
        // A chain/output error is not recoverable by reacquiring.
        assert_eq!(next_action(true, true, true), LoopAction::TeardownAll);
        assert_eq!(next_action(true, false, true), LoopAction::TeardownAll);
    }

    // --- retry_reacquire ---------------------------------------------
    //
    // The in-place recovery loop is the most dangerous code in this
    // module (it is what keeps the loopback output alive across a camera
    // outage) and the least reachable from a test: the real
    // `InputPipeline` needs a live GStreamer and a real `/dev/video*`.
    // The `Reacquire` seam removes both, exactly like `UsageSource` does
    // for the idle detector.

    /// A `Reacquire` that fails a scripted number of times before
    /// succeeding, counts attempts, and can run a side effect *during*
    /// an attempt (used to simulate a bus burst landing mid-recovery).
    struct ScriptedReacquire<'a> {
        failures_before_success: usize,
        attempts: std::cell::Cell<usize>,
        during_attempt: Option<&'a dyn Fn()>,
    }

    impl ScriptedReacquire<'_> {
        fn new(failures_before_success: usize) -> Self {
            Self {
                failures_before_success,
                attempts: std::cell::Cell::new(0),
                during_attempt: None,
            }
        }
    }

    impl Reacquire for ScriptedReacquire<'_> {
        fn reacquire(&self) -> Result<(), FluxError> {
            let n = self.attempts.get() + 1;
            self.attempts.set(n);
            if let Some(hook) = self.during_attempt {
                hook();
            }
            if n > self.failures_before_success {
                Ok(())
            } else {
                Err(FluxError::Config {
                    reason: "device busy".into(),
                    hint: None,
                })
            }
        }
    }

    fn policy(budget_ms: u64, base_ms: u64, max_ms: u64) -> RecoveryPolicy {
        RecoveryPolicy {
            budget: Duration::from_millis(budget_ms),
            backoff_base: Duration::from_millis(base_ms),
            backoff_max: Duration::from_millis(max_ms),
        }
    }

    #[test]
    fn retry_reacquire_succeeds_on_the_first_attempt() {
        let target = ScriptedReacquire::new(0);
        let signal = InputFailureSignal::new();
        // Two bus messages from the outage we are recovering from.
        signal.raise();
        signal.raise();
        let running = AtomicBool::new(true);
        let counters = fluxframe_core::metrics::Counters::new();
        // Pretend the outage started 50 ms ago so `down_ms` is non-zero.
        let started = Instant::now()
            .checked_sub(Duration::from_millis(50))
            .expect("monotonic clock is well past 50 ms since boot");

        let generation = retry_reacquire(
            &target,
            &signal,
            &running,
            &counters,
            policy(60_000, 1, 8),
            started,
            |_| panic!("a first-attempt success must never pause"),
        )
        .expect("recovery should succeed");

        // The whole burst was raised before the attempt, so it is
        // absorbed: the next worker loop must not treat it as new.
        assert_eq!(generation, 2);
        assert_eq!(generation, signal.generation());
        assert_eq!(target.attempts.get(), 1);
        let snap = counters.snapshot();
        assert_eq!(snap.input_reacquire_total, 1);
        assert_eq!(snap.input_reacquire_failures_total, 0);
        assert!(snap.input_down_ms_total >= 50);
    }

    #[test]
    fn retry_reacquire_succeeds_on_the_third_attempt_with_growing_backoff() {
        let target = ScriptedReacquire::new(2);
        let signal = InputFailureSignal::new();
        let running = AtomicBool::new(true);
        let counters = fluxframe_core::metrics::Counters::new();
        let mut pauses: Vec<Duration> = Vec::new();

        let generation = retry_reacquire(
            &target,
            &signal,
            &running,
            &counters,
            policy(60_000, 1, 8),
            Instant::now(),
            |backoff| {
                pauses.push(backoff);
                false
            },
        )
        .expect("third attempt should succeed");

        assert_eq!(generation, 0);
        assert_eq!(target.attempts.get(), 3);
        // Two failed attempts → two paused waits, doubling from the base.
        assert_eq!(
            pauses,
            vec![Duration::from_millis(1), Duration::from_millis(2)]
        );
        let snap = counters.snapshot();
        assert_eq!(snap.input_reacquire_total, 3);
        assert_eq!(snap.input_reacquire_failures_total, 2);
    }

    #[test]
    fn retry_reacquire_backoff_doubles_up_to_the_ceiling() {
        // Never succeeds; we stop it via `running` after six waits so the
        // whole doubling curve is observable without a real sleep.
        let target = ScriptedReacquire::new(usize::MAX);
        let signal = InputFailureSignal::new();
        let running = AtomicBool::new(true);
        let counters = fluxframe_core::metrics::Counters::new();
        let mut pauses: Vec<Duration> = Vec::new();

        let result = retry_reacquire(
            &target,
            &signal,
            &running,
            &counters,
            policy(60_000, 1, 8),
            Instant::now(),
            |backoff| {
                pauses.push(backoff);
                if pauses.len() >= 6 {
                    running.store(false, Ordering::Release);
                }
                false
            },
        );

        assert!(result.is_ok(), "stopping via `running` is not an error");
        assert_eq!(
            pauses,
            vec![
                Duration::from_millis(1),
                Duration::from_millis(2),
                Duration::from_millis(4),
                Duration::from_millis(8),
                Duration::from_millis(8),
                Duration::from_millis(8),
            ]
        );
    }

    #[test]
    fn retry_reacquire_gives_up_when_the_budget_is_spent() {
        let target = ScriptedReacquire::new(usize::MAX);
        let signal = InputFailureSignal::new();
        let running = AtomicBool::new(true);
        let counters = fluxframe_core::metrics::Counters::new();

        // A 20 ms budget with a 5 ms base: the loop really sleeps, but
        // the whole test still finishes in tens of milliseconds.
        let result = retry_reacquire(
            &target,
            &signal,
            &running,
            &counters,
            policy(20, 5, 10),
            Instant::now(),
            |backoff| {
                std::thread::sleep(backoff);
                false
            },
        );

        assert!(result.is_err(), "an exhausted budget must escalate");
        let snap = counters.snapshot();
        assert!(snap.input_reacquire_total >= 2);
        assert_eq!(
            snap.input_reacquire_total,
            snap.input_reacquire_failures_total
        );
        // No success, so no completed outage was accounted.
        assert_eq!(snap.input_down_ms_total, 0);
    }

    #[test]
    fn retry_reacquire_returns_immediately_when_the_run_is_stopping() {
        // Previously the loop only watched the process-wide Ctrl-C flag,
        // so a run torn down through its own token sat here for the full
        // recovery budget.
        let target = ScriptedReacquire::new(usize::MAX);
        let signal = InputFailureSignal::new();
        signal.raise();
        let running = AtomicBool::new(false);
        let counters = fluxframe_core::metrics::Counters::new();

        let generation = retry_reacquire(
            &target,
            &signal,
            &running,
            &counters,
            policy(60_000, 1, 8),
            Instant::now(),
            |_| panic!("must not even attempt a reacquire"),
        )
        .expect("a stopping run exits cleanly");

        assert_eq!(generation, 1);
        assert_eq!(target.attempts.get(), 0);
        assert_eq!(counters.snapshot().input_reacquire_total, 0);
    }

    #[test]
    fn a_failure_raised_during_the_winning_attempt_is_not_absorbed() {
        // The exact race the returned generation exists to close: the
        // camera dies again while `reacquire()` is running. Snapshotting
        // after the call would swallow it and leave the worker spinning
        // on a `recv_timeout` that can never yield a frame.
        let signal = InputFailureSignal::new();
        signal.raise();
        let raise_again = || signal.raise();
        let target = ScriptedReacquire {
            failures_before_success: 0,
            attempts: std::cell::Cell::new(0),
            during_attempt: Some(&raise_again),
        };
        let running = AtomicBool::new(true);
        let counters = fluxframe_core::metrics::Counters::new();

        let generation = retry_reacquire(
            &target,
            &signal,
            &running,
            &counters,
            policy(60_000, 1, 8),
            Instant::now(),
            |_| false,
        )
        .expect("recovery should succeed");

        assert_eq!(generation, 1, "snapshot is taken before the attempt");
        assert_eq!(signal.generation(), 2);
        // The supervisor's watch therefore trips and recovers again.
        let watch = InputFailureWatch {
            signal: &signal,
            entry_generation: generation,
        };
        assert!(watch.tripped());
    }

    // --- reap_reload -------------------------------------------------

    fn spawn_finished(
        outcome: crate::idle::reload::ResumeOutcome,
    ) -> std::thread::JoinHandle<crate::idle::reload::ResumeOutcome> {
        let handle = std::thread::spawn(move || outcome);
        // Wait so `is_finished()` is observably true before the reap.
        while !handle.is_finished() {
            std::thread::sleep(std::time::Duration::from_millis(1));
        }
        handle
    }

    #[test]
    fn reap_reload_none_when_empty() {
        let mut handle = None;
        assert!(reap_reload(&mut handle).is_none());
    }

    #[test]
    fn reap_reload_leaves_in_flight_handle() {
        use std::sync::mpsc;
        let (tx, rx) = mpsc::channel::<()>();
        let mut handle = Some(std::thread::spawn(move || {
            let _ = rx.recv(); // block until released
            crate::idle::reload::ResumeOutcome::Completed
        }));
        // Still running → None, and the handle must be put back.
        assert!(reap_reload(&mut handle).is_none());
        assert!(handle.is_some(), "in-flight handle must be preserved");
        tx.send(()).unwrap();
        handle.take().unwrap().join().unwrap();
    }

    #[test]
    fn reap_reload_returns_input_failed_outcome() {
        use crate::idle::reload::ResumeOutcome;
        use fluxframe_core::error::PipelineError;
        let mut handle = Some(spawn_finished(ResumeOutcome::InputFailed(FluxError::from(
            PipelineError::StateChangeFailed {
                reason: "synthetic reacquire failure".into(),
            },
        ))));
        let outcome = reap_reload(&mut handle);
        assert!(
            matches!(outcome, Some(ResumeOutcome::InputFailed(ref e)) if e.is_transient()),
            "InputFailed must be surfaced and be transient so run_auto retries, got {outcome:?}"
        );
        assert!(handle.is_none(), "reaped handle must be consumed");
    }

    #[test]
    fn reap_reload_returns_completed_outcome() {
        use crate::idle::reload::ResumeOutcome;
        let mut handle = Some(spawn_finished(ResumeOutcome::Completed));
        assert!(matches!(
            reap_reload(&mut handle),
            Some(ResumeOutcome::Completed)
        ));
        assert!(handle.is_none());
    }

    #[test]
    fn classify_input_recognises_testsrc() {
        let mut cfg = base_cfg();
        cfg.input.device = InputDevice::Testsrc;
        assert_eq!(classify_input(&cfg), InputSpec::Testsrc);
    }

    #[test]
    fn is_input_contention_retries_only_device_unavailable() {
        // Camera busy/absent → retry (the only contention class).
        let busy = FluxError::Pipeline(fluxframe_core::PipelineError::InputDeviceUnavailable {
            device: "/dev/video0".into(),
            reason: "device is busy".into(),
            hint: "another app holds it".into(),
        });
        assert!(is_input_contention(&busy));

        // A missing element or a config error is permanent → fail fast,
        // never spin forever on a real misconfiguration.
        let missing = FluxError::Pipeline(fluxframe_core::PipelineError::MissingElement {
            element: "v4l2src".into(),
            hint: "install gst-plugins-good".into(),
        });
        assert!(!is_input_contention(&missing));
        let cfg_err = FluxError::Config {
            reason: "bad".into(),
            hint: None,
        };
        assert!(!is_input_contention(&cfg_err));
    }

    #[test]
    fn supervised_acquire_requires_idle_loopback_and_v4l2_input() {
        // idle off → not supervised regardless of devices.
        let mut cfg = base_cfg();
        cfg.idle.enabled = false;
        cfg.input.device = InputDevice::Path("/dev/video0".into());
        cfg.output.device = "/dev/video10".into();
        assert!(!supervised_acquire(&cfg));

        // idle on + v4l2 loopback sink + v4l2 camera input → supervised.
        cfg.idle.enabled = true;
        assert!(supervised_acquire(&cfg));

        // testsrc input never contends → not supervised.
        cfg.input.device = InputDevice::Testsrc;
        assert!(!supervised_acquire(&cfg));
    }

    #[test]
    fn classify_input_classifies_real_device_as_v4l2() {
        let mut cfg = base_cfg();
        cfg.input.device = InputDevice::Path(PathBuf::from("/dev/video0"));
        assert_eq!(
            classify_input(&cfg),
            InputSpec::V4l2(PathBuf::from("/dev/video0"))
        );
    }

    #[test]
    fn classify_input_marks_auto_as_unsupported_escape_hatch() {
        // `Auto` must be intercepted by `commands::run` before reaching
        // `classify_input`; returning `Unsupported` is the deliberate
        // safe escape so a dispatch bug surfaces as a §27 error rather
        // than a panic.
        let mut cfg = base_cfg();
        cfg.input.device = InputDevice::Auto;
        match classify_input(&cfg) {
            InputSpec::Unsupported(s) => {
                assert!(s.contains("auto"), "diagnostic should mention auto: {s}");
            }
            other => panic!("expected Unsupported, got {other:?}"),
        }
    }

    #[test]
    fn resolve_output_sink_maps_auto() {
        let mut cfg = base_cfg();
        cfg.output.device = "auto".into();
        assert_eq!(
            resolve_output_sink(&cfg).expect("auto resolves"),
            OutputSink::Auto
        );
    }

    #[test]
    fn resolve_output_sink_maps_dev_path_to_v4l2_loopback() {
        let mut cfg = base_cfg();
        cfg.output.device = "/dev/video10".into();
        assert_eq!(
            resolve_output_sink(&cfg).expect("dev path resolves"),
            OutputSink::V4l2Loopback {
                device: PathBuf::from("/dev/video10"),
            }
        );
    }

    #[test]
    fn resolve_output_sink_maps_fakesink() {
        let mut cfg = base_cfg();
        cfg.output.device = "fakesink".into();
        assert_eq!(
            resolve_output_sink(&cfg).expect("fakesink resolves"),
            OutputSink::Fake
        );
    }

    #[test]
    fn resolve_output_sink_rejects_unsupported() {
        let mut cfg = base_cfg();
        cfg.output.device = "http://example.com/stream".into();
        let err = resolve_output_sink(&cfg).expect_err("unsupported sink must fail");
        let msg = format!("{err}");
        assert!(msg.contains("not supported"), "got: {msg}");
    }

    #[test]
    fn classify_output_marks_unsupported() {
        let mut cfg = base_cfg();
        cfg.output.device = "http://example.com/stream".into();
        assert_eq!(
            classify_output(&cfg),
            OutputSpec::Unsupported("http://example.com/stream".to_string())
        );
    }

    #[test]
    fn output_sink_label_covers_each_variant() {
        assert_eq!(output_sink_label(&OutputSink::Fake), "fakesink");
        assert_eq!(output_sink_label(&OutputSink::Auto), "autovideosink");
        assert_eq!(
            output_sink_label(&OutputSink::V4l2Loopback {
                device: PathBuf::from("/dev/video10"),
            }),
            "v4l2sink"
        );
    }

    #[test]
    fn classify_input_path_returns_v4l2_with_path() {
        let mut cfg = base_cfg();
        cfg.input.device = InputDevice::Path(PathBuf::from("/dev/video2"));
        assert_eq!(
            classify_input(&cfg),
            InputSpec::V4l2(PathBuf::from("/dev/video2"))
        );
    }

    #[test]
    fn classify_output_maps_auto() {
        let mut cfg = base_cfg();
        cfg.output.device = "auto".into();
        assert_eq!(classify_output(&cfg), OutputSpec::Auto);
    }

    #[test]
    fn classify_output_maps_fakesink() {
        let mut cfg = base_cfg();
        cfg.output.device = "fakesink".into();
        assert_eq!(classify_output(&cfg), OutputSpec::Fake);
    }

    #[test]
    fn classify_output_maps_dev_path() {
        let mut cfg = base_cfg();
        cfg.output.device = "/dev/video10".into();
        assert_eq!(
            classify_output(&cfg),
            OutputSpec::V4l2(PathBuf::from("/dev/video10"))
        );
    }

    #[test]
    fn classify_output_maps_pipewire_bare() {
        let mut cfg = base_cfg();
        cfg.output.device = "pipewire".into();
        assert_eq!(classify_output(&cfg), OutputSpec::Pipewire(None));
    }

    #[test]
    fn classify_output_maps_pipewire_with_name() {
        let mut cfg = base_cfg();
        cfg.output.device = "pipewire:my-cam".into();
        assert_eq!(
            classify_output(&cfg),
            OutputSpec::Pipewire(Some("my-cam".to_string()))
        );
    }

    #[test]
    fn classify_output_treats_pipewire_typos_as_unsupported() {
        // `pipewireFOO` is not a `pipewire:NAME` form — surface as
        // unsupported rather than silently treating as PipeWire with
        // garbage suffix.
        let mut cfg = base_cfg();
        cfg.output.device = "pipewirefoo".into();
        match classify_output(&cfg) {
            OutputSpec::Unsupported(s) => assert_eq!(s, "pipewirefoo"),
            other => panic!("expected Unsupported, got {other:?}"),
        }
    }

    #[test]
    fn classify_output_pipewire_colon_with_empty_name_is_anonymous() {
        let mut cfg = base_cfg();
        cfg.output.device = "pipewire:".into();
        assert_eq!(classify_output(&cfg), OutputSpec::Pipewire(None));
    }

    #[test]
    fn resolve_output_sink_maps_pipewire() {
        let mut cfg = base_cfg();
        cfg.output.device = "pipewire:flux".into();
        assert_eq!(
            resolve_output_sink(&cfg).expect("pipewire resolves"),
            OutputSink::Pipewire {
                node_name: Some("flux".into())
            }
        );
    }

    // ----------------------------------------------------------------
    // Control-socket dispatcher tests (Stage 13)
    //
    // These exercise `apply_control_command` / `apply_set_command` /
    // `apply_get_config_command` / `apply_reload_command` directly
    // with a stub `EffectChain` (a single `PassthroughEffect`). The
    // dispatch logic does not touch GStreamer, so we can synthesise
    // the inputs without the rest of the supervisor.
    // ----------------------------------------------------------------

    use fluxframe_core::PipelineSection;
    use fluxframe_core::frame::PixelFormat;
    use fluxframe_effects::EffectChain as StubEffectChain;
    use fluxframe_effects::PassthroughEffect;

    /// Build a chain containing one `PassthroughEffect`. Sufficient
    /// for tests that exercise the dispatcher control flow without
    /// caring about per-frame processing.
    /// Chain holding a real composite built from `preset` (its mask
    /// model path is never opened: nothing here calls `prepare`).
    #[cfg(feature = "ml")]
    fn composite_chain(preset: &Preset) -> StubEffectChain {
        let mask_reg = fluxframe_effects::mask_effects::default_registry();
        let plane_reg = fluxframe_effects::plane_effects::default_registry();
        let post_reg = fluxframe_effects::post_effects::default_registry();
        let composite =
            fluxframe_effects::composite::CompositeBuilder::new(&mask_reg, &plane_reg, &post_reg)
                .build(
                    preset.mask.as_ref().expect("test preset has [mask]"),
                    preset.background.as_ref(),
                    preset.foreground.as_ref(),
                    preset.post.as_ref(),
                    &ConfigBase::default(),
                )
                .expect("test composite builds");
        StubEffectChain::new(vec![Box::new(composite)])
    }

    fn stub_chain() -> StubEffectChain {
        StubEffectChain::new(vec![Box::new(PassthroughEffect::new())])
    }

    fn stub_ctx() -> ProcessingContext {
        ProcessingContext {
            width: 4,
            height: 4,
            format: PixelFormat::Rgb,
            fps: 30,
            counters: None,
        }
    }

    fn ok_payload(r: &ControlResponse) -> &serde_json::Value {
        match r {
            ControlResponse::Ok { data } => data,
            ControlResponse::Err { .. } => panic!("expected Ok, got {r:?}"),
            _ => panic!("non-exhaustive Response variant: {r:?}"),
        }
    }

    fn err_reason(r: &ControlResponse) -> &str {
        match r {
            ControlResponse::Err { error, .. } => error.as_str(),
            ControlResponse::Ok { .. } => panic!("expected Err, got {r:?}"),
            _ => panic!("non-exhaustive Response variant: {r:?}"),
        }
    }

    #[test]
    fn apply_control_command_list_presets_returns_names() {
        let mut cfg = base_cfg();
        cfg.presets.insert("a".into(), Preset::default());
        cfg.presets.insert("b".into(), Preset::default());
        let mut session = test_session(cfg, "a");
        let resp = apply_control_command(
            &mut session,
            &stub_ctx(),
            &mut stub_chain(),
            &fluxframe_core::EffectTelemetry::default(),
            ControlCommand::ListPresets,
        );
        let data = ok_payload(&resp);
        let arr = data.as_array().expect("ListPresets returns array");
        let names: Vec<&str> = arr.iter().filter_map(|v| v.as_str()).collect();
        assert!(names.contains(&"a"), "names: {names:?}");
        assert!(names.contains(&"b"), "names: {names:?}");
    }

    /// The GUI decodes `list_effects` into `EffectSchema`; every
    /// shipped effect's metadata must survive that decode unchanged.
    #[test]
    fn apply_list_effects_payload_decodes_into_effect_schema() {
        let resp = apply_list_effects_command();
        let data = ok_payload(&resp);
        for section in fluxframe_core::SubchainKind::ALL {
            let rows = data[section.as_str()].clone();
            let decoded: Vec<fluxframe_core::EffectSchema> = serde_json::from_value(rows.clone())
                .unwrap_or_else(|e| panic!("section '{section}' fails to decode: {e}"));
            assert_eq!(
                serde_json::to_value(&decoded).expect("re-serialise"),
                rows,
                "section '{section}' changes shape through EffectSchema"
            );
        }
    }

    #[test]
    fn apply_list_effects_returns_inventory_for_all_sections() {
        use fluxframe_effects::{mask_effects, plane_effects};

        let resp = apply_list_effects_command();
        let data = ok_payload(&resp);
        let obj = data.as_object().expect("ListEffects returns object");
        // All four section keys present, even under slim build.
        for section in ["mask", "background", "foreground", "post"] {
            let arr = obj
                .get(section)
                .and_then(serde_json::Value::as_array)
                .unwrap_or_else(|| panic!("section '{section}' missing or not array"));
            for row in arr {
                let row_obj = row.as_object().expect("metadata is object");
                assert!(row_obj.contains_key("name"));
                assert!(row_obj.contains_key("params"));
            }
        }
        // mask/background/foreground always populated; `post` only
        // under the `ml` feature.
        for section in ["mask", "background", "foreground"] {
            assert!(
                !obj[section].as_array().unwrap().is_empty(),
                "section '{section}' must list at least one effect"
            );
        }
        #[cfg(feature = "ml")]
        assert!(
            !obj["post"].as_array().unwrap().is_empty(),
            "post must populate under ml feature"
        );
        // Spot-check a known effect.
        let mask_spot: Vec<_> = obj["mask"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(|v| v["name"].as_str())
            .collect();
        assert!(mask_spot.contains(&"threshold"), "got: {mask_spot:?}");

        // Cross-check each section against the registry's own
        // `names()` so a future drift between the registry and the
        // response (duplicate registrations, missing entries, order
        // changes) trips the test rather than silently shipping.
        let mask_names: Vec<&str> = obj["mask"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(|v| v["name"].as_str())
            .collect();
        assert_eq!(
            mask_names,
            mask_effects::default_registry().names(),
            "ListEffects mask list must equal default_registry().names()",
        );
        let bg_names: Vec<&str> = obj["background"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(|v| v["name"].as_str())
            .collect();
        assert_eq!(
            bg_names,
            plane_effects::default_registry().names(),
            "ListEffects background list must equal plane registry names()",
        );
        let fg_names: Vec<&str> = obj["foreground"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(|v| v["name"].as_str())
            .collect();
        assert_eq!(
            fg_names,
            plane_effects::default_registry().names(),
            "ListEffects foreground list must equal plane registry names()",
        );
        #[cfg(feature = "ml")]
        {
            use fluxframe_effects::post_effects;
            let post_names: Vec<&str> = obj["post"]
                .as_array()
                .unwrap()
                .iter()
                .filter_map(|v| v["name"].as_str())
                .collect();
            assert_eq!(
                post_names,
                post_effects::default_registry().names(),
                "ListEffects post list must equal post registry names() under ml",
            );
        }
        // Contract: `build_features` is always present so the GUI
        // can distinguish slim-by-build from missing-by-config.
        assert!(
            obj.contains_key("build_features"),
            "build_features must be present in ListEffects response",
        );
        assert!(
            obj["build_features"].is_array(),
            "build_features must be an array",
        );
    }

    #[test]
    fn apply_list_effects_foreground_equals_background_today() {
        // foreground and background share the same plane registry, so
        // their inventories MUST match element-by-element. If the
        // codebase ever introduces foreground-only or background-only
        // effects, this test fails — at which point the GUI contract
        // (and the comment near the `background.clone()` call) need
        // updating.
        let resp = apply_list_effects_command();
        let data = ok_payload(&resp);
        let obj = data.as_object().expect("ListEffects returns object");
        let bg = obj["background"].as_array().expect("background is array");
        let fg = obj["foreground"].as_array().expect("foreground is array");
        assert_eq!(
            bg.len(),
            fg.len(),
            "foreground and background must have the same length today",
        );
        for (i, (b, f)) in bg.iter().zip(fg.iter()).enumerate() {
            assert_eq!(
                b, f,
                "foreground[{i}] must equal background[{i}] (shared plane registry)",
            );
        }
    }

    #[test]
    fn apply_control_command_set_preset_unknown_name_lists_available() {
        let mut cfg = base_cfg();
        cfg.presets.insert("alpha".into(), Preset::default());
        let mut session = test_session(cfg, "alpha");
        let resp = apply_control_command(
            &mut session,
            &stub_ctx(),
            &mut stub_chain(),
            &fluxframe_core::EffectTelemetry::default(),
            ControlCommand::SetPreset {
                name: "missing".into(),
            },
        );
        match resp {
            ControlResponse::Err { error, hint } => {
                assert!(error.contains("missing"), "error: {error}");
                let hint = hint.expect("hint must list available presets");
                assert!(hint.contains("alpha"), "hint: {hint}");
            }
            ControlResponse::Ok { .. } => panic!("expected Err"),
            _ => panic!("non-exhaustive Response variant"),
        }
    }

    fn test_session(cfg: FluxConfig, preset_name: &str) -> ControlSession {
        let active_preset = cfg.presets.get(preset_name).cloned().unwrap_or_default();
        ControlSession {
            cfg,
            config_path: None,
            config_base: ConfigBase::default(),
            active_preset_name: preset_name.into(),
            active_preset,
        }
    }

    /// The preset state lives in the session, not in the per-run worker
    /// state: a switch made through the socket must stay what
    /// `current_preset` reports after the pipeline around it is rebuilt.
    #[test]
    fn preset_switch_lands_in_the_session() {
        let mut cfg = base_cfg();
        cfg.presets.insert("alpha".into(), Preset::default());
        cfg.presets.insert("beta".into(), Preset::default());
        let mut session = test_session(cfg, "alpha");
        let resp = apply_control_command(
            &mut session,
            &stub_ctx(),
            &mut stub_chain(),
            &fluxframe_core::EffectTelemetry::default(),
            ControlCommand::SetPreset {
                name: "beta".into(),
            },
        );
        ok_payload(&resp);
        assert_eq!(session.active_preset_name, "beta");
        let current = apply_offline_command(&session, &ControlCommand::CurrentPreset);
        assert_eq!(ok_payload(&current), &serde_json::json!("beta"));
    }

    #[test]
    fn offline_commands_serve_reads_and_refuse_edits() {
        let mut cfg = base_cfg();
        cfg.presets.insert("alpha".into(), Preset::default());
        let session = test_session(cfg, "alpha");
        for cmd in [
            ControlCommand::ListPresets,
            ControlCommand::CurrentPreset,
            ControlCommand::ListEffects,
            ControlCommand::GetConfig { path: None },
            ControlCommand::ConfigPath,
            ControlCommand::DaemonInfo,
        ] {
            let resp = apply_offline_command(&session, &cmd);
            assert!(
                matches!(resp, ControlResponse::Ok { .. }),
                "{cmd:?} must be answered without a pipeline, got {resp:?}"
            );
        }
        for cmd in [
            ControlCommand::SetPreset {
                name: "alpha".into(),
            },
            ControlCommand::SetChain {
                section: SubchainKind::Background,
                chain: Vec::new(),
            },
            ControlCommand::Reload,
            ControlCommand::SavePreset,
        ] {
            let resp = apply_offline_command(&session, &cmd);
            assert!(
                err_reason(&resp).contains("pipeline is not running"),
                "{cmd:?} must be refused without a pipeline"
            );
        }
    }

    #[test]
    fn daemon_info_reports_the_configured_output() {
        let mut cfg = base_cfg();
        cfg.output.device = "pipewire:studio".into();
        let session = test_session(cfg, "default");
        let resp = apply_offline_command(&session, &ControlCommand::DaemonInfo);
        assert_eq!(
            ok_payload(&resp),
            &serde_json::json!({"output": {"kind": "pipewire", "node": "studio"}})
        );
    }

    /// While the daemon waits for a camera no worker loop drains the
    /// socket; the wait itself must answer, or every request times out
    /// after `WORKER_RESPONSE_TIMEOUT`.
    #[test]
    fn waiting_without_a_pipeline_still_answers_the_socket() {
        let mut cfg = base_cfg();
        cfg.presets.insert("alpha".into(), Preset::default());
        let session = test_session(cfg, "alpha");
        let (tx, rx) = crossbeam_channel::bounded::<ControlEnvelope>(CONTROL_CHANNEL_DEPTH);
        let (reply_tx, reply_rx) = crossbeam_channel::bounded(REPLY_CHANNEL_DEPTH);
        tx.send(ControlEnvelope {
            cmd: ControlCommand::CurrentPreset,
            reply_tx,
        })
        .expect("command channel is open");
        let _ = wait_serving_control(Duration::from_millis(20), Some(&rx), &session);
        let reply = reply_rx
            .try_recv()
            .expect("the wait answered the queued command");
        assert_eq!(ok_payload(&reply), &serde_json::json!("alpha"));
    }

    #[test]
    fn apply_set_command_revert_on_invalid_value() {
        // Stub chain has no composite, so `reconfigure_named_effect`
        // returns Err for any path. The in-memory preset must NOT
        // grow the new key — the revert path puts it back the way it
        // was.
        let mut chain = stub_chain();
        let mut preset = Preset {
            background: Some(PipelineSection::default()),
            ..Preset::default()
        };
        let before = preset.background.as_ref().unwrap().per_effect.clone();
        let resp = apply_set_command(
            &mut chain,
            &mut preset,
            &ConfigBase::default(),
            "background.blur.radius",
            serde_json::json!(42),
        );
        assert!(matches!(resp, ControlResponse::Err { .. }));
        let after = preset.background.as_ref().unwrap().per_effect.clone();
        assert_eq!(
            before, after,
            "in-memory preset must be unchanged after revert"
        );
    }

    /// Regression: `set` on an effect whose table carries
    /// `enabled = false` handed the flag to `configure`, which
    /// `deny_unknown_fields` configs (blur) reject — for both the write
    /// and its revert.
    #[cfg(feature = "ml")]
    #[test]
    fn apply_set_command_on_disabled_effect_ignores_enabled_flag() {
        let mut preset: Preset = toml::from_str(
            r#"
[mask]
model = "/tmp/dummy.onnx"
chain = ["threshold"]

[background]
chain = ["blur"]

[background.blur]
enabled = false
radius = 10
"#,
        )
        .expect("test preset parses");
        let mut chain = composite_chain(&preset);

        let resp = apply_set_command(
            &mut chain,
            &mut preset,
            &ConfigBase::default(),
            "background.blur.passes",
            serde_json::json!(3),
        );
        assert!(matches!(resp, ControlResponse::Ok { .. }), "{resp:?}");
        let blur = &preset.background.as_ref().unwrap().per_effect["blur"];
        assert_eq!(blur.get("enabled"), Some(&toml::Value::Boolean(false)));
        assert_eq!(blur.get("passes"), Some(&toml::Value::Integer(3)));

        // A rejected write reverts to the flagged table without error.
        let before = preset.clone();
        let resp = apply_set_command(
            &mut chain,
            &mut preset,
            &ConfigBase::default(),
            "background.blur.passes",
            serde_json::json!("many"),
        );
        assert!(matches!(resp, ControlResponse::Err { .. }), "{resp:?}");
        assert_eq!(preset, before);
    }

    #[test]
    fn apply_set_command_rejects_enabled_field() {
        let mut chain = stub_chain();
        let mut preset = Preset::default();
        let resp = apply_set_command(
            &mut chain,
            &mut preset,
            &ConfigBase::default(),
            "background.blur.enabled",
            serde_json::json!(false),
        );
        assert!(
            err_reason(&resp).contains("not an effect parameter"),
            "{resp:?}"
        );
        assert_eq!(preset, Preset::default());
    }

    /// A live `set` opens a relative image path next to the config file,
    /// exactly as the preset build does.
    #[cfg(feature = "image-fill")]
    #[test]
    fn set_resolves_relative_image_paths_against_the_config_base() {
        let base = ConfigBase::for_config(Some(std::path::Path::new("/etc/ff/fluxframe.toml")));
        let table = toml::Value::Table(
            toml::from_str("enabled = false\npath = \"bg.png\"").expect("valid TOML"),
        );
        let params = live_effect_params(
            "image_fill",
            Some(&table),
            effect_metadata(SubchainKind::Background, "image_fill"),
            &base,
        )
        .expect("params resolve");
        assert_eq!(
            params,
            toml::Value::Table(toml::from_str("path = \"/etc/ff/bg.png\"").expect("valid TOML"))
        );
    }

    /// Preset for the `set_enabled` tests: `color_fill` without a table,
    /// `blur` with explicit params.
    #[cfg(feature = "ml")]
    fn toggle_preset() -> Preset {
        toml::from_str(
            r#"
[mask]
model = "/tmp/dummy.onnx"
chain = ["threshold"]

[background]
chain = ["color_fill", "blur"]

[background.blur]
radius = 10
"#,
        )
        .expect("test preset parses")
    }

    #[cfg(feature = "ml")]
    fn live_disabled(chain: &mut StubEffectChain, section: SubchainKind) -> Vec<String> {
        chain
            .composite_mut()
            .expect("chain hosts a composite")
            .disabled_effects(section)
            .into_iter()
            .map(str::to_string)
            .collect()
    }

    #[cfg(feature = "ml")]
    fn table(text: &str) -> toml::Value {
        toml::Value::Table(toml::from_str(text).expect("valid TOML"))
    }

    #[cfg(feature = "ml")]
    #[test]
    fn apply_set_enabled_command_toggles_live_chain_and_canonical_preset() {
        let original = toggle_preset();
        let mut preset = original.clone();
        let mut chain = composite_chain(&preset);
        let stages = std::sync::Arc::new(fluxframe_core::StageTimings::with_capacity(4));
        let telemetry =
            fluxframe_core::EffectTelemetry::default().with_stages(std::sync::Arc::clone(&stages));
        telemetry.record_stage(
            fluxframe_core::StageKey::new("background", "color_fill"),
            Duration::from_micros(5),
        );
        let bg = SubchainKind::Background;
        let ok =
            |resp: ControlResponse| assert!(matches!(resp, ControlResponse::Ok { .. }), "{resp:?}");

        // No table yet: disabling creates `{ enabled = false }`.
        ok(apply_set_enabled_command(
            &mut chain,
            &mut preset,
            &telemetry,
            bg,
            "color_fill",
            false,
        ));
        assert_eq!(live_disabled(&mut chain, bg), vec!["color_fill"]);
        let per_effect = &preset.background.as_ref().unwrap().per_effect;
        assert_eq!(per_effect["color_fill"], table("enabled = false"));
        assert!(stages.snapshot().is_empty(), "disabled stage is forgotten");

        // Explicit params survive a round of off/on.
        ok(apply_set_enabled_command(
            &mut chain,
            &mut preset,
            &telemetry,
            bg,
            "blur",
            false,
        ));
        let per_effect = &preset.background.as_ref().unwrap().per_effect;
        assert_eq!(per_effect["blur"], table("enabled = false\nradius = 10"));
        ok(apply_set_enabled_command(
            &mut chain,
            &mut preset,
            &telemetry,
            bg,
            "blur",
            true,
        ));
        let per_effect = &preset.background.as_ref().unwrap().per_effect;
        assert_eq!(per_effect["blur"], table("radius = 10"));

        // Re-enabling drops the table that only held the flag, so the
        // preset (and the GUI's dirty marker) returns to the original.
        ok(apply_set_enabled_command(
            &mut chain,
            &mut preset,
            &telemetry,
            bg,
            "color_fill",
            true,
        ));
        assert!(live_disabled(&mut chain, bg).is_empty());
        assert_eq!(preset, original);

        // Enabling an enabled effect without a table does not create one.
        ok(apply_set_enabled_command(
            &mut chain,
            &mut preset,
            &telemetry,
            bg,
            "color_fill",
            true,
        ));
        assert_eq!(preset, original);
    }

    #[cfg(feature = "ml")]
    #[test]
    fn apply_set_enabled_command_keeps_mask_segmentation_fields() {
        let mut preset = toggle_preset();
        let mut chain = composite_chain(&preset);
        let telemetry = fluxframe_core::EffectTelemetry::default();
        let resp = apply_set_enabled_command(
            &mut chain,
            &mut preset,
            &telemetry,
            SubchainKind::Mask,
            "threshold",
            false,
        );
        assert!(matches!(resp, ControlResponse::Ok { .. }), "{resp:?}");
        let mask = preset.mask.as_ref().unwrap();
        assert_eq!(
            mask.model.as_deref(),
            Some(std::path::Path::new("/tmp/dummy.onnx"))
        );
        assert_eq!(mask.per_effect["threshold"], table("enabled = false"));
    }

    #[cfg(feature = "ml")]
    #[test]
    fn apply_set_enabled_command_rejections_leave_preset_untouched() {
        let base = toggle_preset();
        let telemetry = fluxframe_core::EffectTelemetry::default();
        let mut preset = base.clone();
        let mut chain = composite_chain(&preset);

        let resp = apply_set_enabled_command(
            &mut chain,
            &mut preset,
            &telemetry,
            SubchainKind::Background,
            "vignette",
            false,
        );
        assert!(err_reason(&resp).contains("no effect named"), "{resp:?}");
        assert_eq!(preset, base);

        let resp = apply_set_enabled_command(
            &mut chain,
            &mut preset,
            &telemetry,
            SubchainKind::Post,
            "mirror",
            false,
        );
        assert!(err_reason(&resp).contains("[post]"), "{resp:?}");
        assert_eq!(preset, base);

        preset
            .background
            .as_mut()
            .unwrap()
            .per_effect
            .insert("color_fill".into(), toml::Value::Integer(1));
        let malformed = preset.clone();
        let resp = apply_set_enabled_command(
            &mut chain,
            &mut preset,
            &telemetry,
            SubchainKind::Background,
            "color_fill",
            false,
        );
        assert!(err_reason(&resp).contains("not a table"), "{resp:?}");
        assert_eq!(preset, malformed);
        assert!(live_disabled(&mut chain, SubchainKind::Background).is_empty());

        let mut maskless = Preset::default();
        let resp = apply_set_enabled_command(
            &mut stub_chain(),
            &mut maskless,
            &telemetry,
            SubchainKind::Mask,
            "threshold",
            false,
        );
        assert!(err_reason(&resp).contains("[mask]"), "{resp:?}");
        assert_eq!(maskless, Preset::default());
    }

    /// Regression: after `set_enabled false` an effect added without
    /// params has a table holding only the flag; the next `set_chain`
    /// rebuild treated that as explicit params and `color_fill` failed on
    /// its missing `rgb`. The rebuild must synthesise defaults and keep
    /// the effect disabled.
    #[cfg(feature = "ml")]
    #[test]
    fn subchain_rebuild_synthesises_defaults_and_keeps_disabled_flag() {
        let per_effect: std::collections::BTreeMap<String, toml::Value> =
            toml::from_str("[color_fill]\nenabled = false\n").expect("valid TOML");
        let names = ["vignette".to_string(), "color_fill".to_string()];
        let Ok(payload) = build_and_configure_subchain(
            SubchainKind::Background,
            &names,
            &per_effect,
            &ConfigBase::default(),
        ) else {
            panic!("rebuild must succeed for a flag-only table");
        };
        let fluxframe_effects::composite::SubChainPayload::Background(slots) = payload else {
            panic!("background payload expected");
        };
        assert!(slots[0].is_enabled());
        assert!(!slots[1].is_enabled());
    }

    #[test]
    fn apply_get_config_command_walks_nested_path() {
        // Build a preset with a known nested shape so we can walk
        // into it via the dot-path.
        let section = PipelineSection {
            chain: vec!["blur".into()],
            ..PipelineSection::default()
        };
        let preset = Preset {
            background: Some(section),
            ..Preset::default()
        };
        let resp = apply_get_config_command(&preset, Some("background.chain"));
        let data = ok_payload(&resp);
        let arr = data.as_array().expect("chain returns array");
        assert_eq!(arr.len(), 1);
        assert_eq!(arr[0].as_str(), Some("blur"));
    }

    #[test]
    fn apply_get_config_command_rejects_empty_component() {
        let preset = Preset::default();
        let resp = apply_get_config_command(&preset, Some("background..chain"));
        let reason = err_reason(&resp);
        assert!(reason.contains("empty"), "reason: {reason}");
    }

    #[test]
    fn ensure_plane_or_post_section_mut_materialises_absent_post() {
        let mut p = fluxframe_core::Preset::default();
        assert!(p.post.is_none(), "fixture preset has no [post]");
        let section = ensure_plane_or_post_section_mut(&mut p, SubchainKind::Post);
        assert!(
            section.chain.is_empty(),
            "newly-materialised chain is empty"
        );
        assert!(section.per_effect.is_empty(), "no per-effect overrides");
        assert!(p.post.is_some(), "section persisted into preset");
    }

    #[test]
    fn ensure_plane_or_post_section_mut_returns_existing_background() {
        let mut p = fluxframe_core::Preset {
            background: Some(fluxframe_core::PipelineSection {
                chain: vec!["blur".to_string()],
                ..Default::default()
            }),
            ..Default::default()
        };
        let section = ensure_plane_or_post_section_mut(&mut p, SubchainKind::Background);
        assert_eq!(
            section.chain,
            vec!["blur".to_string()],
            "existing chain preserved"
        );
    }

    #[test]
    fn mask_section_mut_does_not_materialise_absent() {
        let mut p = fluxframe_core::Preset::default();
        assert!(mask_section_mut(&mut p).is_none(), "absent mask stays None");
        assert!(p.mask.is_none(), "preset.mask is not mutated");
    }

    #[test]
    fn mask_section_mut_returns_existing() {
        let mut p = fluxframe_core::Preset {
            mask: Some(fluxframe_core::PipelineSection {
                chain: vec!["threshold".to_string()],
                ..Default::default()
            }),
            ..Default::default()
        };
        assert!(mask_section_mut(&mut p).is_some());
    }

    #[test]
    fn apply_reload_command_without_path_errors() {
        let mut cfg = base_cfg();
        let mut chain = stub_chain();
        let mut name = "default".to_string();
        let mut preset = Preset::default();
        let ctx = stub_ctx();
        let resp = apply_reload_command(&mut cfg, None, &ctx, &mut chain, &mut name, &mut preset);
        let reason = err_reason(&resp);
        assert!(reason.contains("config path"), "reason: {reason}");
    }
}

#[cfg(all(test, feature = "ml", feature = "image-fill"))]
mod default_synthesis_tests {
    use super::*;
    use std::collections::BTreeMap;

    #[test]
    fn synthesises_color_fill_defaults_when_per_effect_missing() {
        let per_effect = BTreeMap::new();
        let result = build_and_configure_subchain(
            SubchainKind::Background,
            &["color_fill".to_string()],
            &per_effect,
            &ConfigBase::default(),
        );
        assert!(
            result.is_ok(),
            "color_fill should succeed with metadata-synthesised defaults; got {:?}",
            result.as_ref().err().map(|e| &e.reason),
        );
    }

    #[test]
    fn rejects_image_fill_with_helpful_message() {
        let per_effect = BTreeMap::new();
        // `SubChainPayload` does not implement `Debug`, so we cannot
        // use `expect_err`; use `let...else` instead.
        let Err(err) = build_and_configure_subchain(
            SubchainKind::Background,
            &["image_fill".to_string()],
            &per_effect,
            &ConfigBase::default(),
        ) else {
            panic!("image_fill should fail without an explicit path")
        };
        assert!(
            err.reason.contains("missing required field"),
            "expected missing-field error, got: {}",
            err.reason,
        );
        assert!(
            err.reason.contains("path"),
            "expected `path` mentioned in error, got: {}",
            err.reason,
        );
        assert!(
            err.hint.is_some(),
            "expected hint with editor suggestion, got reason={} hint={:?}",
            err.reason,
            err.hint,
        );
    }
}