microsoft-webui-cli 0.0.24

CLI tool for building WebUI applications
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

mod metafile;
mod streaming_api;

use actix_web::{web, App, HttpRequest, HttpResponse, HttpServer};
use anyhow::{Context, Result};
use clap::Args;
use expand_tilde::expand_tilde;
use mime_guess::from_path;
use serde_json::Value;
use std::collections::{HashMap, HashSet};
use std::fs;
use std::io::ErrorKind;
use std::net::{Ipv4Addr, SocketAddrV4, TcpListener};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio_stream::StreamExt;
use webui::streaming::StreamingWriter;
use webui::{Diagnostic, Protocol, WebUIHandler};
use webui_dev_server::{spawn_watcher, sse_handler, LiveReload, WatchConfig};
use webui_handler::plugin::fast_v2::FastV2HydrationPlugin;
use webui_handler::plugin::fast_v3::FastV3HydrationPlugin;
use webui_handler::plugin::webui::WebUIHydrationPlugin;
use webui_handler::{encode_safe, RenderOptions, ResponseWriter};
#[cfg(test)]
use webui_protocol::WebUIProtocol;

use super::common::*;
use crate::utils::error::CliError;
use crate::utils::output;
#[cfg(test)]
use metafile::temp_directory as metafile_temp_directory;
use metafile::write_atomic;

#[derive(Args)]
pub struct ServeArgs {
    #[command(flatten)]
    pub app_args: AppArgs,

    /// Port to bind the development server to
    #[arg(long, default_value_t = 3000)]
    pub port: u16,

    /// Path to the JSON state file used for rendering
    #[arg(long)]
    pub state: Option<PathBuf>,

    /// Optional directory to serve static assets from at /*
    #[arg(long)]
    pub servedir: Option<PathBuf>,

    /// Enable file watching + HMR (disabled by default)
    #[arg(long)]
    pub watch: bool,

    /// Port of the user's API server to proxy route requests to. Encoded path
    /// and query bytes are forwarded unchanged, except the entry route: `/` and
    /// `/index.html` both resolve backend state at `/` (query preserved).
    #[arg(long)]
    pub api_port: Option<u16>,

    /// Design token theme: a path to a JSON file or an npm package name
    /// (e.g., `@microsoft/webui-examples-theme`). Resolved from node_modules
    /// when the value doesn't point to a file on disk. Missing unresolved CSS
    /// tokens fail the build.
    #[arg(long)]
    pub theme: Option<String>,

    /// Comma-separated root component tags to emit as static CDN-loadable
    /// assets, matching `webui build --emit-component-assets`. Their templates
    /// and CSS are parsed and validated (theme tokens, HTML) on every build —
    /// even though they are not part of the initial SSR tree — so authoring
    /// errors in lazily loaded components surface in the dev server. The
    /// compiled `<tag>.webui.js` modules are served from memory.
    #[arg(long, value_delimiter = ',', value_name = "TAGS")]
    pub emit_component_assets: Vec<String>,

    /// Write an esbuild-compatible component asset metafile after each successful build
    #[arg(long, value_name = "PATH", requires = "emit_component_assets")]
    pub metafile: Option<PathBuf>,

    /// Base path for sub-path deployment (e.g., `/commerce/`).
    /// Emits a `<base href>` tag and makes asset paths relative so the
    /// app can be served behind a reverse proxy under a sub-path.
    #[arg(long)]
    pub base_path: Option<String>,
}

/// Resolved paths for `webui serve`.
#[derive(Clone)]
struct ServePaths {
    app_dir: PathBuf,
    state_file: Option<PathBuf>,
    serve_dir: Option<PathBuf>,
    metafile: Option<PathBuf>,
}

impl ServePaths {
    fn from_args(args: &ServeArgs) -> Result<Self> {
        let app_input = expand_tilde(&args.app_args.app)
            .with_context(|| format!("Failed to expand app path: {}", args.app_args.app.display()))?
            .into_owned();

        let app_dir = app_input
            .canonicalize()
            .map_err(|_| CliError::AppFolderNotFound {
                path: args.app_args.app.display().to_string(),
            })?;

        let state_file = match &args.state {
            Some(state_path) => {
                let state_input = expand_tilde(state_path)
                    .with_context(|| {
                        format!("Failed to expand state path: {}", state_path.display())
                    })?
                    .into_owned();

                let canonical =
                    state_input
                        .canonicalize()
                        .map_err(|_| CliError::StateFileNotFound {
                            path: state_path.display().to_string(),
                        })?;

                if !canonical.is_file() {
                    return Err(anyhow::anyhow!(
                        "State path must be a file: {}",
                        canonical.display()
                    ));
                }
                Some(canonical)
            }
            None => None,
        };

        let serve_dir = match &args.servedir {
            Some(serve_arg) => {
                let serve_input = expand_tilde(serve_arg)
                    .with_context(|| {
                        format!(
                            "Failed to expand serve directory path: {}",
                            serve_arg.display()
                        )
                    })?
                    .into_owned();

                let canonical =
                    serve_input
                        .canonicalize()
                        .map_err(|_| CliError::ServeDirNotFound {
                            path: serve_arg.display().to_string(),
                        })?;

                if !canonical.is_dir() {
                    return Err(anyhow::anyhow!(
                        "Serve directory path must be a directory: {}",
                        canonical.display()
                    ));
                }

                Some(canonical)
            }
            None => None,
        };

        if !app_dir.is_dir() {
            return Err(anyhow::anyhow!(
                "App path must be a directory: {}",
                app_dir.display()
            ));
        }

        let metafile = args
            .metafile
            .as_deref()
            .map(expand_tilde)
            .transpose()
            .with_context(|| "Failed to expand metafile path")?
            .map(std::borrow::Cow::into_owned)
            .map(|path| {
                if path.is_absolute() {
                    Ok(path)
                } else {
                    std::env::current_dir().map(|current| current.join(path))
                }
            })
            .transpose()?;

        Ok(Self {
            app_dir,
            state_file,
            serve_dir,
            metafile,
        })
    }

    fn watch_paths(&self) -> Vec<PathBuf> {
        let mut paths = vec![self.app_dir.clone()];

        if let Some(state_file) = &self.state_file {
            paths.push(state_file.clone());
        }

        // Note: `serve_dir` (e.g. `./dist`) is intentionally NOT watched.
        // It is the destination for client bundles that other tools
        // (esbuild, pnpm, E2E harness) write to, and re-reading those
        // writes back through HMR causes spurious page reloads while
        // tests are running. The dev server only needs to react to
        // source changes under `app_dir` and to `state_file`.

        paths
    }
}

/// Thread-safe shared state: the rendered HTML for serving.
struct SharedState {
    rendered_html: String,
    css_files: HashMap<String, String>,
    /// In-memory static component assets (`<tag>.webui.js`) emitted by
    /// `--emit-component-assets`, served from memory like generated CSS.
    component_assets: HashMap<String, String>,
    protocol: Option<Arc<Protocol>>,
    state_data: Option<Value>,
    token_css: Option<HashMap<String, String>>,
    rebuild_error: Option<String>,
    /// Entry fragment ID used for rendering (e.g., "index.html").
    entry: String,
}

/// In-memory writer implementing `ResponseWriter` for the handler.
struct MemoryWriter {
    buf: String,
}

impl MemoryWriter {
    fn with_capacity(cap: usize) -> Self {
        Self {
            buf: String::with_capacity(cap),
        }
    }
}

impl ResponseWriter for MemoryWriter {
    fn write(&mut self, content: &str) -> webui_handler::Result<()> {
        self.buf.push_str(content);
        Ok(())
    }

    fn end(&mut self) -> webui_handler::Result<()> {
        Ok(())
    }
}

/// SSE endpoint path. Root-relative so the script works under any
/// `<base href>` and across sub-path deployments.
const HMR_ENDPOINT: &str = "/__webui/livereload";

/// Environment variable that, when set to a non-empty / non-"0" value,
/// suppresses `--watch` mode at runtime. Used by `xtask e2e` so that
/// shared `start:server` package.json scripts (which include `--watch`
/// for dev) don't enable filesystem watching during E2E test runs,
/// where spurious rebuilds reload the page mid-test.
const WATCH_DISABLE_ENV: &str = "WEBUI_NO_WATCH";

fn watch_disabled_by_env() -> bool {
    match std::env::var(WATCH_DISABLE_ENV) {
        Ok(v) => !v.is_empty() && v != "0",
        Err(_) => false,
    }
}

pub fn execute(args: &ServeArgs) -> Result<()> {
    run(args).inspect_err(|err| {
        output::error(err);
        if let Some(cli_err) = err.chain().find_map(|c| c.downcast_ref::<CliError>()) {
            output::hint(cli_err.hint());
        }
        eprintln!();
    })
}

fn run(args: &ServeArgs) -> Result<()> {
    let paths = ServePaths::from_args(args)?;
    // Allow E2E / CI runs to suppress watch mode without editing the
    // package.json `start:server` script that devs share.
    let watch_enabled = args.watch && !watch_disabled_by_env();
    let livereload: Option<LiveReload> = if watch_enabled {
        Some(LiveReload::new(HMR_ENDPOINT))
    } else {
        None
    };

    let token_file = args
        .theme
        .as_deref()
        .map(|theme| load_theme(theme, &paths.app_dir))
        .transpose()?;

    let render_config = RenderConfig {
        app_args: args.app_args.clone(),
        app_dir: paths.app_dir.clone(),
        state_file: paths.state_file.clone(),
        token_file,
        component_asset_roots: args.emit_component_assets.clone(),
        metafile: paths.metafile.clone(),
        base_path: args.base_path.clone(),
    };

    output::header("WebUI Dev Server");
    output::field("App", &paths.app_dir.display());
    match &paths.state_file {
        Some(f) => output::field("State", &f.display()),
        None => output::field("State", &"(none)"),
    }
    match &paths.serve_dir {
        Some(serve_dir) => output::field("ServeDir", &serve_dir.display()),
        None => output::field("ServeDir", &"(disabled)"),
    }
    if let Some(ref theme) = args.theme {
        output::field("Theme", theme);
    } else {
        output::field("Theme", &"(none)");
    }
    output::field("Entry", &args.app_args.entry);
    output::field("Port", &args.port);
    output::field("CSS", &args.app_args.css);
    if !args.emit_component_assets.is_empty() {
        output::field("Component assets", &args.emit_component_assets.join(", "));
    }
    if let Some(ref metafile) = paths.metafile {
        output::field("Metafile", &metafile.display());
    }
    if let Some(api_port) = args.api_port {
        output::field("API Port", &api_port);
    }
    if watch_enabled {
        output::field("HMR", &format!("enabled (SSE {HMR_ENDPOINT})"));
    } else if args.watch {
        output::field("HMR", &"disabled (WEBUI_NO_WATCH)");
    } else {
        output::field("HMR", &"disabled (pass --watch to enable)");
    }
    eprintln!();

    ensure_local_port_available(args.port)?;

    // Initial build + render
    let initial_result = build_and_render(&render_config, livereload.as_ref())?;
    output::success("Initial build and render complete");
    for advisory in &initial_result.warnings {
        output::warning_diagnostic(advisory);
    }

    let state = Arc::new(Mutex::new(SharedState {
        rendered_html: initial_result.html,
        css_files: initial_result.css_files,
        component_assets: initial_result.component_assets,
        protocol: Some(initial_result.protocol),
        state_data: Some(initial_result.state_data),
        token_css: initial_result.token_css,
        rebuild_error: None,
        entry: args.app_args.entry.clone(),
    }));

    // The watcher handle must outlive the server; dropping it stops the
    // background watcher thread. We store it in an `Option` so that the
    // `--watch=false` branch is a no-op.
    let _watcher_handle = if let Some(active_lr) = &livereload {
        let mut watch_paths_list = paths.watch_paths();

        // Also watch local path component sources
        for extra_dir in
            webui_discovery::collect_watch_paths(&args.app_args.components, &paths.app_dir)
        {
            watch_paths_list.push(extra_dir);
        }

        let handle = start_file_watcher(WatcherConfig {
            watch_paths: watch_paths_list,
            projection_manifests: args.app_args.projection_manifests.clone(),
            state: Arc::clone(&state),
            render_config,
            livereload: active_lr.clone(),
            // Seed dedup with warnings already shown above (keyed by the plain
            // diagnostic body), so the first rebuild does not re-print them.
            initial_warnings: initial_result.warnings.iter().map(|d| d.body()).collect(),
        })?;
        output::success("File watcher started");
        Some(handle)
    } else {
        None
    };

    let addr = format!("127.0.0.1:{}", args.port);
    let bind_addr = addr.clone();
    let server_port = args.port;

    output::field("URL", &format!("http://{addr}/"));
    output::finish("Server is running \u{2014} press Ctrl+C to stop");

    let server_context = web::Data::new(ServerContext {
        state,
        livereload: livereload.clone(),
        assets_dir: paths.serve_dir,
        api_port: args.api_port,
        plugin: args.app_args.plugin,
        base_path: args.base_path.clone(),
        // Pool sized for typical concurrent renders × channel capacity.
        // 256 buffers × 5 KiB ≈ 1.25 MiB peak pool memory — bounded.
        chunk_pool: Arc::new(webui::streaming::ChunkPool::new(
            256,
            StreamingWriter::CHUNK_TARGET + 1024,
        )),
    });
    let lr_data = livereload.map(web::Data::new);

    let has_api_proxy = server_context.api_port.is_some();

    actix_web::rt::System::new()
        .block_on(async move {
            HttpServer::new(move || {
                let mut app = App::new()
                    .app_data(server_context.clone())
                    .route("/", web::get().to(handle_index))
                    .route("/index.html", web::get().to(handle_index));

                if let Some(lr) = &lr_data {
                    app = app
                        .app_data(lr.clone())
                        .route(HMR_ENDPOINT, web::get().to(sse_handler));
                }

                if has_api_proxy {
                    app = app.route("/api/{tail:.*}", web::route().to(handle_api_proxy));
                }

                app = app
                    .route(
                        "/_webui/templates",
                        web::get().to(handle_component_templates),
                    )
                    .route("/{tail:.*}", web::get().to(handle_asset))
                    .default_service(web::route().to(handle_not_found));

                app
            })
            .bind(&bind_addr)
            .map_err(|error| map_bind_error(server_port, &bind_addr, error))?
            .run()
            .await
            .map_err(|e| anyhow::anyhow!("{e}"))
        })
        .with_context(|| format!("Failed to start actix-web server on {addr}"))?;

    Ok(())
}

fn ensure_local_port_available(port: u16) -> Result<()> {
    let bind_addr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, port);
    let listener = TcpListener::bind(bind_addr)
        .map_err(|error| map_bind_error(port, &bind_addr.to_string(), error))?;
    drop(listener);
    Ok(())
}

fn map_bind_error(port: u16, bind_addr: &str, error: std::io::Error) -> anyhow::Error {
    if error.kind() == ErrorKind::AddrInUse {
        return CliError::PortInUse { port }.into();
    }

    anyhow::anyhow!("Failed to bind to {bind_addr}: {error}")
}

#[derive(Clone)]
struct RenderConfig {
    app_args: AppArgs,
    app_dir: PathBuf,
    state_file: Option<PathBuf>,
    /// Loaded theme file used to validate and resolve tokens on each build.
    token_file: Option<webui::TokenFile>,
    /// Root component tags emitted as static assets (`--emit-component-assets`).
    /// Parsed and validated on every build so their authoring errors surface in
    /// the dev server, even though they are not part of the initial SSR tree.
    component_asset_roots: Vec<String>,
    /// Atomic metafile destination updated only after a successful build and render.
    metafile: Option<PathBuf>,
    /// Base path for sub-path deployment (e.g., `/commerce/`).
    base_path: Option<String>,
}

/// Result of a build-and-render cycle.
struct BuildRenderResult {
    html: String,
    css_files: HashMap<String, String>,
    /// Static component assets (`<tag>.webui.js`) keyed by filename.
    component_assets: HashMap<String, String>,
    protocol: Arc<Protocol>,
    state_data: Value,
    token_css: Option<HashMap<String, String>>,
    /// Non-fatal build advisories (warning-severity diagnostics) to frame under
    /// the rebuild line.
    warnings: Vec<Diagnostic>,
}

/// Build the protocol from app templates and render with explicit state data.
fn build_and_render(
    config: &RenderConfig,
    livereload: Option<&LiveReload>,
) -> Result<BuildRenderResult> {
    let mut build_options = config.app_args.to_build_options(&config.app_dir);
    build_options.theme = config.token_file.clone();
    // Parse and validate the static-asset roots too, so theme-token / HTML
    // errors in lazily loaded components (which are not in the SSR tree) fail
    // the dev build instead of being silently skipped.
    build_options.component_asset_roots = config.component_asset_roots.clone();
    build_options.metafile = config.metafile.is_some();
    let build_result = webui::build(build_options).with_context(|| "Build failed")?;
    let token_css = match config.token_file.as_ref() {
        Some(token_file) => Some(
            webui_tokens::resolve_tokens(&build_result.protocol.tokens, token_file)
                .with_context(|| "Token resolution failed")?
                .css,
        ),
        None => None,
    };

    let mut state: Value = match &config.state_file {
        Some(path) => {
            let json = fs::read_to_string(path)
                .with_context(|| format!("Failed to read {}", path.display()))?;
            serde_json::from_str(&json)
                .with_context(|| format!("Failed to parse state JSON from {}", path.display()))?
        }
        None => Value::Object(serde_json::Map::new()),
    };

    // Inject resolved token CSS into state
    if let Some(ref token_css) = token_css {
        webui_tokens::inject_token_css(&mut state, token_css);
    }

    // Inject basePath into state so templates can use {{basePath}}.
    // Default to "/" when no --base-path is set — relative CSS paths
    // like "foo.css" need <base href="/"> to resolve correctly on
    // nested routes (e.g., /contacts/123 → /foo.css, not /contacts/foo.css).
    if let Value::Object(ref mut map) = state {
        let bp = config.base_path.as_deref().unwrap_or("/").to_string();
        map.insert("basePath".into(), Value::String(bp));
    }

    let protocol = Arc::new(Protocol::new(build_result.protocol));

    // Render to memory
    let mut writer = MemoryWriter::with_capacity(4096);
    let handler = create_handler(config.app_args.plugin);
    handler.render(
        &protocol,
        &state,
        &RenderOptions::new(&config.app_args.entry, "/"),
        &mut writer,
    )?;

    let html = match livereload {
        Some(lr) => lr.inject(&writer.buf),
        None => writer.buf,
    };

    if let Some(path) = &config.metafile {
        let metafile = build_result.metafile.as_deref().ok_or_else(|| {
            anyhow::anyhow!("component asset metafile was requested but not generated")
        })?;
        write_atomic(path, metafile)?;
    }

    let css_map: HashMap<String, String> = build_result.css_files.into_iter().collect();
    let component_assets: HashMap<String, String> = build_result
        .component_asset_files
        .into_iter()
        .map(|file| (file.name, file.content))
        .collect();

    Ok(BuildRenderResult {
        html,
        css_files: css_map,
        component_assets,
        protocol,
        state_data: state,
        token_css,
        warnings: build_result.warnings,
    })
}

fn watcher_ignore_paths(metafile: Option<&std::path::Path>) -> Vec<PathBuf> {
    let mut ignore = webui_dev_server::default_ignore_paths();
    if let Ok(out_dir) = std::env::current_dir() {
        ignore.push(out_dir.join("dist"));
    }
    if let Some(metafile) = metafile {
        ignore.extend(metafile::watch_ignore_paths(metafile));
    }
    ignore
}

fn create_handler(plugin: Option<Plugin>) -> WebUIHandler {
    match plugin {
        Some(Plugin::Fast | Plugin::FastV2) => {
            WebUIHandler::with_plugin(|| Box::new(FastV2HydrationPlugin::new()))
        }
        Some(Plugin::FastV3) => {
            WebUIHandler::with_plugin(|| Box::new(FastV3HydrationPlugin::new()))
        }
        Some(Plugin::WebUI) => WebUIHandler::with_plugin(|| Box::new(WebUIHydrationPlugin::new())),
        None => WebUIHandler::new(),
    }
}

fn rebuild_error_response(message: &str, livereload: Option<&LiveReload>) -> HttpResponse {
    if let Some(livereload) = livereload {
        let escaped = encode_safe(message);
        let script = livereload.client_script();
        let mut body = String::with_capacity(message.len() + script.len() + 160);
        body.push_str("<!doctype html><html><head><meta charset=\"utf-8\"><title>");
        body.push_str(
            "WebUI rebuild failed</title></head><body><h1>WebUI rebuild failed</h1><pre>",
        );
        body.push_str(&escaped);
        body.push_str("</pre>");
        body.push_str(script);
        body.push_str("</body></html>");
        return HttpResponse::InternalServerError()
            .content_type("text/html; charset=utf-8")
            .body(body);
    }

    let mut body = String::with_capacity(message.len() + 22);
    body.push_str("WebUI rebuild failed\n\n");
    body.push_str(message);
    HttpResponse::InternalServerError()
        .content_type("text/plain; charset=utf-8")
        .body(body)
}

fn rebuild_error_json_response(message: &str) -> HttpResponse {
    let escaped = match serde_json::to_string(message) {
        Ok(value) => value,
        Err(_) => "\"WebUI rebuild failed\"".to_string(),
    };
    let mut body = String::with_capacity(escaped.len() + 11);
    body.push_str("{\"error\":");
    body.push_str(&escaped);
    body.push('}');
    HttpResponse::InternalServerError()
        .content_type("application/json")
        .body(body)
}

// ── Route handlers ──────────────────────────────────────────────────────

struct ServerContext {
    state: Arc<Mutex<SharedState>>,
    livereload: Option<LiveReload>,
    assets_dir: Option<PathBuf>,
    api_port: Option<u16>,
    plugin: Option<Plugin>,
    /// Base path for sub-path deployment.
    base_path: Option<String>,
    /// Shared chunk-buffer pool. One pool per server; recycled across
    /// every streaming render so steady-state RPS does not allocate
    /// fresh chunk buffers per flush.
    chunk_pool: Arc<webui::streaming::ChunkPool>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct RequestPaths {
    route_path: String,
    request_path: String,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SpaFallbackKind {
    None,
    Html,
    Json,
}

fn build_request_paths(relative: &str, query: &str) -> RequestPaths {
    let route_path = if relative.is_empty() {
        "/".to_string()
    } else {
        let mut path = String::with_capacity(relative.len() + 1);
        path.push('/');
        path.push_str(relative);
        path
    };

    if query.is_empty() {
        return RequestPaths {
            request_path: route_path.clone(),
            route_path,
        };
    }

    let mut request_path = String::with_capacity(route_path.len() + query.len() + 1);
    request_path.push_str(&route_path);
    request_path.push('?');
    request_path.push_str(query);

    RequestPaths {
        route_path,
        request_path,
    }
}

fn request_paths(req: &HttpRequest) -> RequestPaths {
    let uri = req.uri();
    let route_path = uri.path().to_string();
    let request_path = uri
        .path_and_query()
        .map_or_else(|| route_path.clone(), |value| value.as_str().to_string());
    RequestPaths {
        route_path,
        request_path,
    }
}

/// Fetch state from the user's API server for a given request path, including query parameters.
async fn fetch_api_state(api_port: u16, path: &str) -> Result<Value, String> {
    let client = awc::Client::new();
    let url = format!("http://127.0.0.1:{api_port}{path}");
    let mut resp = client
        .get(&url)
        .insert_header(("Accept", "application/json"))
        .send()
        .await
        .map_err(|e| format!("API proxy error: {e}"))?;
    let body = resp
        .body()
        .await
        .map_err(|e| format!("API body error: {e}"))?;
    let json: Value = serde_json::from_slice(&body).map_err(|e| format!("API JSON error: {e}"))?;
    // Expect { "state": { ... } }, fall back to entire response
    Ok(extract_api_state(json))
}

/// Resolve state for a request: try API proxy first, then fall back to file state.
async fn resolve_state(context: &ServerContext, request_path: &str) -> Value {
    let (mut state, token_css) = if let Some(api_port) = context.api_port {
        match fetch_api_state(api_port, request_path).await {
            Ok(state) => {
                let token_css = context.state.lock().ok().and_then(|s| s.token_css.clone());
                (state, token_css)
            }
            Err(e) => {
                eprintln!("  {} {e}", console::style("\u{26a0}").yellow());
                match context.state.lock() {
                    Ok(s) => (
                        s.state_data
                            .clone()
                            .unwrap_or_else(|| Value::Object(serde_json::Map::new())),
                        s.token_css.clone(),
                    ),
                    Err(_) => (Value::Object(serde_json::Map::new()), None),
                }
            }
        }
    } else {
        match context.state.lock() {
            Ok(s) => (
                s.state_data
                    .clone()
                    .unwrap_or_else(|| Value::Object(serde_json::Map::new())),
                s.token_css.clone(),
            ),
            Err(_) => (Value::Object(serde_json::Map::new()), None),
        }
    };

    // Inject resolved token CSS into state so signals like
    // /*{{{tokens.light}}}*/ resolve at render time, regardless of
    // whether state came from a static file or the API server.
    if let Some(ref token_css) = token_css {
        webui_tokens::inject_token_css(&mut state, token_css);
    }

    // Inject basePath into state — default "/" for correct CSS resolution.
    if let Value::Object(ref mut map) = state {
        let bp = context.base_path.as_deref().unwrap_or("/").to_string();
        map.insert("basePath".into(), Value::String(bp));
    }

    state
}

/// Render a full HTML page using route matching from `route_path` and state lookup from
/// `request_path`, which may include a query string. Streams chunks via
/// [`StreamingWriter`]; when livereload is active, the dev-mode `<script>`
/// is spliced before `</body>` via `RenderOptions::with_body_inject` —
/// the handler emits it at the parser-synthesized `body_end` signal
/// boundary, with zero scan cost and no risk of false-marker mis-fire
/// on `</body>` literals appearing inside HTML comments / `srcdoc`.
async fn render_page_response(
    context: &web::Data<ServerContext>,
    route_path: &str,
    request_path: &str,
) -> HttpResponse {
    // One lock acquisition for a consistent snapshot of the rebuild status and
    // the protocol/entry it produced. Reading these separately could mix a
    // "no error" check with a protocol from a different rebuild generation.
    let (rebuild_error, protocol, entry) = match context.state.lock() {
        Ok(s) => (s.rebuild_error.clone(), s.protocol.clone(), s.entry.clone()),
        Err(_) => return HttpResponse::InternalServerError().body("Internal Server Error"),
    };

    if let Some(error) = rebuild_error.as_deref() {
        return rebuild_error_response(error, context.livereload.as_ref());
    }

    let Some(proto) = protocol else {
        return HttpResponse::InternalServerError().body("Protocol not available");
    };
    let plugin = context.plugin;
    let livereload_script: Option<Arc<str>> =
        context.livereload.as_ref().map(|lr| lr.client_script_arc());
    let route_params =
        webui_handler::route_handler::collect_nested_route_params(&proto, &entry, route_path);

    let mut state = if let Some(api_port) = context.api_port {
        let client = awc::Client::new();
        let url = format!("http://127.0.0.1:{api_port}{request_path}");
        match client
            .get(&url)
            .insert_header(("Accept", streaming_api::ACCEPT))
            .send()
            .await
        {
            Ok(response) if streaming_api::is_stream(response.headers()) => {
                let status = response.status();
                if !status.is_success() {
                    // The upstream refused before writing a single record, so no
                    // boundary has reached the browser and rule 19's "never
                    // degrade a live stream to buffering" does not apply. Treat
                    // it like any other pre-stream acquisition failure and
                    // render the page from fallback state, rather than handing
                    // the browser a raw upstream error body in place of the app.
                    log_api_state_warning(&format!(
                        "API stream unavailable (HTTP {status}); rendering with fallback state"
                    ));
                    fallback_state(context)
                } else {
                    let backend = response.map(|chunk| chunk.map_err(|error| error.to_string()));
                    let defaults = streaming_state_defaults(context, route_params);
                    return streaming_api::render(
                        backend,
                        streaming_api::RenderConfig {
                            protocol: proto,
                            entry,
                            route_path: route_path.to_owned(),
                            plugin,
                            body_inject: livereload_script,
                            chunk_pool: Arc::clone(&context.chunk_pool),
                        },
                        defaults,
                    )
                    .await;
                }
            }
            Ok(mut response) => match response.body().await {
                Ok(body) => match parse_api_state(&body) {
                    Ok(state) => state,
                    Err(error) => {
                        log_api_state_warning(&error);
                        fallback_state(context)
                    }
                },
                Err(error) => {
                    log_api_state_warning(&format!("API body error: {error}"));
                    fallback_state(context)
                }
            },
            Err(error) => {
                log_api_state_warning(&format!("API proxy error: {error}"));
                fallback_state(context)
            }
        }
    } else {
        fallback_state(context)
    };

    let defaults = streaming_state_defaults(context, route_params);
    defaults.apply(&mut state);
    render_buffered_page(
        streaming_api::RenderConfig {
            protocol: proto,
            entry,
            route_path: route_path.to_owned(),
            plugin,
            body_inject: livereload_script,
            chunk_pool: Arc::clone(&context.chunk_pool),
        },
        state,
    )
}

fn parse_api_state(body: &[u8]) -> Result<Value, String> {
    let json: Value =
        serde_json::from_slice(body).map_err(|error| format!("API JSON error: {error}"))?;
    Ok(extract_api_state(json))
}

fn extract_api_state(mut json: Value) -> Value {
    if let Value::Object(object) = &mut json {
        if let Some(state) = object.remove("state") {
            return state;
        }
    }
    json
}

fn fallback_state(context: &ServerContext) -> Value {
    context
        .state
        .lock()
        .ok()
        .and_then(|state| state.state_data.clone())
        .unwrap_or_else(|| Value::Object(serde_json::Map::new()))
}

fn streaming_state_defaults(
    context: &ServerContext,
    route_params: HashMap<String, String>,
) -> streaming_api::StateDefaults {
    let token_css = context
        .state
        .lock()
        .ok()
        .and_then(|state| state.token_css.clone());
    streaming_api::StateDefaults::new(
        token_css,
        context.base_path.as_deref().unwrap_or("/").to_owned(),
        route_params,
    )
}

fn log_api_state_warning(message: &str) {
    eprintln!("  {} {message}", console::style("\u{26a0}").yellow());
}

fn render_buffered_page(config: streaming_api::RenderConfig, state: Value) -> HttpResponse {
    let route_path_for_log = config.route_path.clone();

    // Bounded channel: backpressure when client is slow, no unbounded
    // memory growth. Capacity is in chunks (≈ 4 KB each).
    let (tx, rx) =
        tokio::sync::mpsc::channel::<bytes::Bytes>(StreamingWriter::DEFAULT_CHANNEL_CAPACITY);
    actix_web::rt::task::spawn_blocking(move || {
        // 30 s flush deadline caps slow-loris DoS: an attacker can pin
        // a render thread for at most 30 s per chunk, then we abort
        // and free the thread.
        // Pool-acquired chunk buffers recycle across requests — steady-
        // state RPS does not allocate fresh chunk Vec per flush.
        let mut writer = StreamingWriter::new_pooled(tx, Arc::clone(&config.chunk_pool))
            .with_flush_timeout(std::time::Duration::from_secs(30));
        // Build RenderOptions with optional body_inject for livereload.
        // The handler emits the inject string at the structural
        // body_end boundary identified by the parser — zero scan cost,
        // no risk of false-marker mis-firing on `</body>` literals
        // appearing inside HTML comments / srcdoc / inline scripts.
        let opts_owner = RenderOptions::new(&config.entry, &config.route_path);
        let opts = match config.body_inject.as_deref() {
            Some(script) => opts_owner.with_body_inject(script),
            None => opts_owner,
        };
        let handler = create_handler(config.plugin);
        if let Err(e) = handler.render(&config.protocol, &state, &opts, &mut writer) {
            // Status 200 + headers are already on the wire — we cannot
            // return an HTTP error. Log the detail so ops sees it;
            // emit a fixed HTML comment so an attacker-controlled
            // error message cannot break out of the comment via `-->`.
            log::error!("render failed for {route_path_for_log}: {e}");
            let _ = ResponseWriter::write(&mut writer, "<!-- webui: render error -->");
            if let Err(flush_error) = ResponseWriter::end(&mut writer) {
                log::debug!("render stream truncated for {route_path_for_log}: {flush_error}");
            }
        }
    });

    // Zero-overhead Stream adapter (no async_stream! coroutine).
    let stream =
        tokio_stream::wrappers::ReceiverStream::new(rx).map(Ok::<bytes::Bytes, actix_web::Error>);
    HttpResponse::Ok()
        .content_type("text/html; charset=utf-8")
        // Streaming responses with attacker-influencable timing should
        // not be cached by intermediaries; the body may be partial on
        // error paths.
        .insert_header(("Cache-Control", "no-store"))
        .streaming(stream)
}

async fn handle_index(req: HttpRequest, context: web::Data<ServerContext>) -> HttpResponse {
    // JSON partial render for client-side navigation
    if wants_json(&req) {
        let paths = build_request_paths("", req.query_string());
        return handle_json_partial(&req, &context, paths).await;
    }

    // With API proxy, render on-the-fly with fresh state
    if context.api_port.is_some() {
        let paths = build_request_paths("", req.query_string());
        return render_page_response(&context, &paths.route_path, &paths.request_path).await;
    }

    // Without API proxy, serve pre-rendered HTML
    let html = match context.state.lock() {
        Ok(s) => {
            if let Some(error) = s.rebuild_error.as_deref() {
                return rebuild_error_response(error, context.livereload.as_ref());
            }
            s.rendered_html.clone()
        }
        Err(_) => return HttpResponse::InternalServerError().body("Internal Server Error"),
    };

    HttpResponse::Ok()
        .content_type("text/html; charset=utf-8")
        .body(html)
}

async fn handle_component_templates(
    req: HttpRequest,
    context: web::Data<ServerContext>,
) -> HttpResponse {
    let qs = req.query_string();
    let mut tags: Vec<&str> = Vec::new();
    let mut inv = String::new();
    for pair in qs.split('&') {
        if let Some((k, v)) = pair.split_once('=') {
            match k {
                "t" => tags.extend(v.split(',')),
                "inv" => inv = v.to_string(),
                _ => {}
            }
        }
    }
    if tags.is_empty() {
        return HttpResponse::BadRequest()
            .content_type("application/json")
            .body(r#"{"error":"missing ?t= parameter"}"#);
    }
    let Ok(state) = context.state.lock() else {
        return HttpResponse::InternalServerError()
            .content_type("application/json")
            .body(r#"{"error":"lock poisoned"}"#);
    };
    if let Some(error) = state.rebuild_error.as_deref() {
        return rebuild_error_json_response(error);
    }
    let Some(ref protocol) = state.protocol else {
        return HttpResponse::InternalServerError()
            .content_type("application/json")
            .body(r#"{"error":"no protocol"}"#);
    };
    let result = match protocol.render_component_templates(&tags, &inv) {
        Ok(v) => v,
        Err(e) => {
            return HttpResponse::InternalServerError()
                .content_type("application/json")
                .body(format!(r#"{{"error":"{}"}}"#, e));
        }
    };
    HttpResponse::Ok()
        .content_type("application/json")
        .json(result)
}

async fn handle_asset(
    req: HttpRequest,
    path: web::Path<String>,
    context: web::Data<ServerContext>,
) -> HttpResponse {
    let relative = path.into_inner();

    // Check in-memory generated files first (CSS and static component assets,
    // produced by the build). These take precedence over `--servedir` so the
    // dev server always serves the freshly built output.
    if let Ok(s) = context.state.lock() {
        if let Some(css) = s.css_files.get(&relative) {
            return HttpResponse::Ok()
                .content_type("text/css; charset=utf-8")
                .body(css.clone());
        }
        if let Some(asset) = s.component_assets.get(&relative) {
            // Served as a JS module: the framework loads it via dynamic
            // `import()`, which the browser rejects under a non-JS MIME type.
            return HttpResponse::Ok()
                .content_type("text/javascript; charset=utf-8")
                .body(asset.clone());
        }
    }

    let Some(assets_dir) = &context.assets_dir else {
        // No assets dir: let the Accept header decide whether this was a route
        // navigation/partial request or a missing asset fetch.
        return spa_fallback(&req, &context).await;
    };

    let asset_path = assets_dir.join(&relative);

    let canonical = match asset_path.canonicalize() {
        Ok(p) => p,
        Err(_) => {
            // File not found: let the Accept header decide whether this was a
            // route navigation/partial request or a missing asset fetch.
            return spa_fallback(&req, &context).await;
        }
    };

    if !canonical.starts_with(assets_dir) {
        return HttpResponse::Forbidden().body("Forbidden");
    }

    let body = match fs::read(&canonical) {
        Ok(bytes) => bytes,
        Err(_) => return spa_fallback(&req, &context).await,
    };

    let content_type = from_path(&canonical).first_or_octet_stream();

    HttpResponse::Ok()
        .content_type(content_type.as_ref())
        .body(body)
}

fn accept_media_q(params: &str) -> f32 {
    for raw_param in params.split(';') {
        let Some((key, value)) = raw_param.trim().split_once('=') else {
            continue;
        };
        if key.trim().eq_ignore_ascii_case("q") {
            // HTTP qvalues are finite and within 0..=1. Anything outside that
            // range is malformed and falls back to the default of 1.0 so an
            // invalid header cannot force a 404 or skew tie-breaking.
            return value
                .trim()
                .parse::<f32>()
                .ok()
                .filter(|q| (0.0..=1.0).contains(q))
                .unwrap_or(1.0);
        }
    }
    1.0
}

/// Select the SPA fallback response explicitly accepted by the request.
///
/// `q=0` disables that media type, while malformed or out-of-range q values
/// (outside `0..=1`) are treated as absent with the default q of 1.0. When HTML
/// and JSON have the same highest acceptable q value, JSON wins because it is
/// only sent by clients opting into partial render.
fn spa_fallback_kind(req: &HttpRequest) -> SpaFallbackKind {
    let Some(accept) = req.headers().get("accept").and_then(|v| v.to_str().ok()) else {
        return SpaFallbackKind::None;
    };

    let mut html_q = 0.0;
    let mut json_q = 0.0;
    for raw_media in accept.split(',') {
        let (media, params) = raw_media
            .split_once(';')
            .map_or((raw_media, ""), |(value, params)| (value, params));
        let q = accept_media_q(params);
        if q <= 0.0 {
            continue;
        }

        let media = media.trim();
        if media.eq_ignore_ascii_case("text/html")
            || media.eq_ignore_ascii_case("application/xhtml+xml")
        {
            if q > html_q {
                html_q = q;
            }
        } else if media.eq_ignore_ascii_case("application/json") && q > json_q {
            json_q = q;
        }
    }

    if html_q <= 0.0 && json_q <= 0.0 {
        SpaFallbackKind::None
    } else if json_q >= html_q {
        SpaFallbackKind::Json
    } else {
        SpaFallbackKind::Html
    }
}

/// Check if the request explicitly accepts JSON (for partial render).
fn wants_json(req: &HttpRequest) -> bool {
    spa_fallback_kind(req) == SpaFallbackKind::Json
}

/// SPA fallback: serve HTML or JSON partial depending on Accept header.
/// Activates for explicit document navigation or JSON partial requests.
async fn spa_fallback(req: &HttpRequest, context: &web::Data<ServerContext>) -> HttpResponse {
    let kind = spa_fallback_kind(req);
    if kind == SpaFallbackKind::None {
        return HttpResponse::NotFound().body("Not Found");
    }

    // Actix decodes `web::Path` values. Route matching and backend state
    // requests must instead receive the original encoded request target.
    let paths = request_paths(req);

    // JSON partial render: return { state, templates } for client-side navigation.
    if kind == SpaFallbackKind::Json {
        return handle_json_partial(req, context, paths).await;
    }

    render_page_response(context, &paths.route_path, &paths.request_path).await
}

/// Handle a JSON partial render request for client-side navigation.
///
/// Returns `{ state, templates, inventory, path, chain }` where:
/// - `templates` only includes f-templates the client doesn't already have
/// - `inventory` is the updated hex bitmask including the new templates
async fn handle_json_partial(
    req: &HttpRequest,
    context: &web::Data<ServerContext>,
    paths: RequestPaths,
) -> HttpResponse {
    // Clone protocol from shared state (release lock quickly)
    let (protocol, entry) = match context.state.lock() {
        Ok(s) => {
            if let Some(error) = s.rebuild_error.as_deref() {
                return rebuild_error_json_response(error);
            }
            (s.protocol.clone(), s.entry.clone())
        }
        Err(_) => {
            return HttpResponse::InternalServerError().body(r#"{"error":"Internal server error"}"#)
        }
    };

    let mut state_data = resolve_state(context, &paths.request_path).await;

    // Inject route params into state from walking the fragment graph.
    if let Value::Object(ref mut map) = state_data {
        if let Some(proto) = &protocol {
            let nested_params = webui_handler::route_handler::collect_nested_route_params(
                proto,
                &entry,
                &paths.route_path,
            );
            for (k, v) in &nested_params {
                map.insert(k.clone(), Value::String(v.clone()));
            }
        }
    }

    // Get needed component templates via the handler's graph walk + inventory filter
    let client_inv_hex = req
        .headers()
        .get("x-webui-inventory")
        .and_then(|v| v.to_str().ok())
        .unwrap_or_default()
        .to_string();

    // Build the complete partial response (templateStyles, templates, inventory, path, chain)
    let partial = if let Some(proto) = &protocol {
        let state_json = match serde_json::to_string(&state_data) {
            Ok(value) => value,
            Err(error) => {
                return HttpResponse::InternalServerError()
                    .content_type("application/json")
                    .body(format!(
                        r#"{{"error":"state serialization failed: {error}"}}"#
                    ));
            }
        };
        match proto.render_partial(&state_json, &entry, &paths.route_path, &client_inv_hex) {
            Ok(value) => value,
            Err(e) => {
                return HttpResponse::InternalServerError()
                    .content_type("application/json")
                    .body(format!(r#"{{"error":"{}"}}"#, e));
            }
        }
    } else {
        "{}".to_string()
    };

    HttpResponse::Ok()
        .content_type("application/json")
        .body(partial)
}

#[cfg(test)]
fn collect_needed_template_names(
    protocol: &WebUIProtocol,
    entry_fragment_id: &str,
    request_path: &str,
    inventory_hex: &str,
) -> (Vec<String>, String) {
    let protocol = Protocol::new(protocol.clone());
    let json = protocol
        .render_partial("{}", entry_fragment_id, request_path, inventory_hex)
        .unwrap();
    let response: Value = serde_json::from_str(&json).unwrap();
    let names = response["templates"]
        .as_object()
        .map(|templates| templates.keys().cloned().collect())
        .unwrap_or_default();
    let inventory = response["inventory"]
        .as_str()
        .unwrap_or_default()
        .to_string();
    (names, inventory)
}

/// Forward requests under `/api/*` to the user's API server.
async fn handle_api_proxy(
    req: HttpRequest,
    body: web::Bytes,
    context: web::Data<ServerContext>,
) -> HttpResponse {
    let Some(api_port) = context.api_port else {
        return HttpResponse::NotFound().body("Not Found");
    };

    let uri = req.uri();
    let path_and_query = uri
        .path_and_query()
        .map_or(uri.path(), |value| value.as_str());
    const API_URL_PREFIX: &str = "http://127.0.0.1:";
    const MAX_PORT_DIGITS: usize = 5;
    let mut url =
        String::with_capacity(API_URL_PREFIX.len() + MAX_PORT_DIGITS + path_and_query.len());
    url.push_str(API_URL_PREFIX);
    // Write the port digits straight into the reserved capacity instead of
    // allocating a temporary `String` via `to_string()` on the proxy hot path.
    use std::fmt::Write as _;
    let _ = write!(url, "{api_port}");
    url.push_str(path_and_query);

    let client = awc::Client::new();
    let mut proxy_req = client.request(req.method().clone(), &url);

    // Forward content-type header if present
    if let Some(ct) = req.headers().get("content-type") {
        proxy_req = proxy_req.insert_header(("content-type", ct.clone()));
    }

    let result = if body.is_empty() {
        proxy_req.send().await
    } else {
        proxy_req.send_body(body).await
    };

    match result {
        Ok(mut resp) => {
            let status = resp.status();
            match resp.body().await {
                Ok(response_body) => {
                    let mut builder = HttpResponse::build(status);
                    if let Some(ct) = resp.headers().get("content-type") {
                        builder.insert_header(("content-type", ct.clone()));
                    }
                    builder.body(response_body)
                }
                Err(e) => HttpResponse::BadGateway().body(format!("API proxy body error: {e}")),
            }
        }
        Err(e) => HttpResponse::BadGateway().body(format!("API proxy error: {e}")),
    }
}

async fn handle_not_found() -> HttpResponse {
    HttpResponse::NotFound().body("Not Found")
}

// ── File watcher ────────────────────────────────────────────────────────

/// Filesystem-event debounce window. Editors often save in multiple
/// bursts; coalescing into one rebuild per burst feels right.
const WATCH_DEBOUNCE: Duration = Duration::from_millis(50);

/// Configuration for the file watcher.
struct WatcherConfig {
    watch_paths: Vec<PathBuf>,
    projection_manifests: Vec<PathBuf>,
    state: Arc<Mutex<SharedState>>,
    render_config: RenderConfig,
    livereload: LiveReload,
    /// Warnings already printed by the initial build, used to seed rebuild
    /// dedup so they are not re-printed on the next rebuild.
    initial_warnings: Vec<String>,
}

/// Start a debounced filesystem watcher that rebuilds and re-renders
/// when template, data, or asset files change. The returned handle owns
/// the background watcher thread; it must be kept alive for the lifetime
/// of the server.
fn start_file_watcher(config: WatcherConfig) -> Result<webui_dev_server::WatcherHandle> {
    let WatcherConfig {
        watch_paths,
        projection_manifests,
        state,
        render_config,
        livereload,
        initial_warnings,
    } = config;

    // The shared rebuild worker handles tick coalescing, success/error
    // reporting (rolling line + timestamps), and livereload broadcast.
    // The closure here is just the cli-specific render-and-update step.
    //
    // Rebuild advisories are deduplicated: a full-app rebuild fires on every
    // watched change, but a warning is only worth printing when it first
    // appears. `seen` holds the previous rebuild's warning set (seeded with the
    // initial build's), so editing an unrelated file does not re-spam unchanged
    // warnings. A resolved-then-reintroduced warning prints again. Errors are
    // intentionally not deduplicated — a broken build is surfaced every rebuild.
    let lr_for_inject = livereload.clone();
    let mut seen: HashSet<String> = initial_warnings.into_iter().collect();
    let state_for_rebuild = Arc::clone(&state);
    let retry_state = Arc::clone(&state);
    let metafile_ignore = render_config.metafile.clone();
    let tick_tx = webui_dev_server::spawn_rebuild_worker(livereload, move || {
        let warnings =
            rebuild_and_update_state(&render_config, &lr_for_inject, &state_for_rebuild)?;
        Ok(take_new_warnings(&mut seen, warnings))
    });
    let retry_unchanged_when = Arc::new(move || {
        retry_state
            .lock()
            .is_ok_and(|state| state.rebuild_error.is_some())
    });

    let ignore = watcher_ignore_paths(metafile_ignore.as_deref());

    spawn_watcher(
        WatchConfig {
            paths: watch_paths,
            explicit_files: projection_manifests,
            ignore,
            debounce: WATCH_DEBOUNCE,
            retry_unchanged_when: Some(retry_unchanged_when),
        },
        move |paths: Vec<std::path::PathBuf>| {
            // Forward the changed paths so the rebuild line can name the
            // triggering file. If the worker thread has already terminated,
            // ignore send errors.
            let _ = tick_tx.try_send(paths);
        },
    )
}

/// Return the colorized display bodies for warnings in `current` that were not
/// in `seen`, then replace `seen` with the current warning set (keyed by each
/// diagnostic's plain `body()`).
///
/// Dedupes dev-server rebuild advisories: a warning prints only when it first
/// appears (or reappears after being resolved), so editing an unrelated file —
/// which still triggers a full-app rebuild — does not re-spam unchanged
/// warnings. The returned strings are the per-line-colorized multi-line bodies
/// the reporter prints under a `⚠ build warning:` marker.
fn take_new_warnings(seen: &mut HashSet<String>, current: Vec<Diagnostic>) -> Vec<String> {
    let mut new_displays = Vec::new();
    let mut current_keys = HashSet::with_capacity(current.len());
    for diag in &current {
        let key = diag.body();
        if !seen.contains(&key) {
            new_displays.push(crate::utils::output::styled_diagnostic_body(diag));
        }
        current_keys.insert(key);
    }
    *seen = current_keys;
    new_displays
}

fn rebuild_and_update_state(
    render_config: &RenderConfig,
    livereload: &LiveReload,
    state: &Arc<Mutex<SharedState>>,
) -> Result<Vec<Diagnostic>, webui_dev_server::RebuildError> {
    match build_and_render(render_config, Some(livereload)) {
        Ok(result) => match state.lock() {
            Ok(mut s) => {
                s.rendered_html = result.html;
                s.css_files = result.css_files;
                s.component_assets = result.component_assets;
                s.protocol = Some(result.protocol);
                s.state_data = Some(result.state_data);
                s.token_css = result.token_css;
                s.rebuild_error = None;
                // The rebuild worker prints these under the "rebuilt" line.
                Ok(result.warnings)
            }
            Err(_) => Err(webui_dev_server::RebuildError::plain(
                "shared state mutex poisoned".to_owned(),
            )),
        },
        Err(err) => {
            let (display, message) = crate::utils::output::build_error_renderings(&err);
            if let Ok(mut s) = state.lock() {
                s.rebuild_error = Some(message.clone());
            }
            Err(webui_dev_server::RebuildError::new(display, message))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use actix_web::body::to_bytes;
    use actix_web::http::StatusCode;
    use actix_web::test as actix_test;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use tempfile::TempDir;
    use webui_protocol::{FragmentList, WebUIFragment, WebUIProtocol, WebUiFragmentRoute};

    fn create_app_dir(files: &[(&str, &str)]) -> TempDir {
        let dir = TempDir::new().unwrap();
        for (name, content) in files {
            let path = dir.path().join(name);
            if let Some(parent) = path.parent() {
                fs::create_dir_all(parent).unwrap();
            }
            fs::write(&path, content).unwrap();
        }
        dir
    }

    fn test_server_context(api_port: u16) -> web::Data<ServerContext> {
        web::Data::new(ServerContext {
            state: Arc::new(Mutex::new(SharedState {
                rendered_html: "<html><body>ok</body></html>".to_string(),
                css_files: HashMap::new(),
                component_assets: HashMap::new(),
                protocol: None,
                state_data: None,
                token_css: None,
                rebuild_error: None,
                entry: "index.html".to_string(),
            })),
            livereload: None,
            assets_dir: None,
            api_port: Some(api_port),
            plugin: None,
            base_path: None,
            chunk_pool: Arc::new(webui::streaming::ChunkPool::new(
                4,
                StreamingWriter::CHUNK_TARGET + 1024,
            )),
        })
    }

    fn test_route_context(protocol: Arc<Protocol>) -> web::Data<ServerContext> {
        web::Data::new(ServerContext {
            state: Arc::new(Mutex::new(SharedState {
                rendered_html: "<html><body>ok</body></html>".to_string(),
                css_files: HashMap::new(),
                component_assets: HashMap::new(),
                protocol: Some(protocol),
                state_data: Some(Value::Object(serde_json::Map::new())),
                token_css: None,
                rebuild_error: None,
                entry: "index.html".to_string(),
            })),
            livereload: None,
            assets_dir: None,
            api_port: None,
            plugin: None,
            base_path: None,
            chunk_pool: Arc::new(webui::streaming::ChunkPool::new(
                4,
                StreamingWriter::CHUNK_TARGET + 1024,
            )),
        })
    }

    fn dotted_route_protocol() -> Arc<Protocol> {
        let mut fragments = HashMap::new();
        fragments.insert(
            "index.html".to_string(),
            FragmentList {
                fragments: vec![WebUIFragment::route_from(WebUiFragmentRoute {
                    path: "/docs/:version".to_string(),
                    fragment_id: "docs-page".to_string(),
                    exact: true,
                    keep_alive: false,
                    ..Default::default()
                })],
            },
        );
        fragments.insert(
            "docs-page".to_string(),
            FragmentList {
                fragments: vec![WebUIFragment::raw("<main>docs</main>")],
            },
        );
        Arc::new(Protocol::new(WebUIProtocol::with_tokens(
            fragments,
            Vec::new(),
        )))
    }

    fn start_request_target_server() -> (u16, actix_web::dev::ServerHandle, Arc<Mutex<Vec<String>>>)
    {
        let request_targets = Arc::new(Mutex::new(Vec::new()));
        let server_targets = Arc::clone(&request_targets);
        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
        let port = listener.local_addr().unwrap().port();
        let server = HttpServer::new(move || {
            let request_targets = Arc::clone(&server_targets);
            App::new().default_service(web::to(move |req: HttpRequest| {
                let request_targets = Arc::clone(&request_targets);
                async move {
                    let request_target = req.uri().path_and_query().map_or_else(
                        || req.path().to_string(),
                        |value| value.as_str().to_string(),
                    );
                    request_targets.lock().unwrap().push(request_target.clone());
                    HttpResponse::Ok().json(serde_json::json!({
                        "state": { "requestTarget": request_target }
                    }))
                }
            }))
        })
        .listen(listener)
        .unwrap()
        .run();
        let handle = server.handle();
        actix_web::rt::spawn(server);
        (port, handle, request_targets)
    }

    #[test]
    fn test_take_new_warnings_suppresses_repeats_and_surfaces_changes() {
        // `take_new_warnings` dedupes on each diagnostic's plain `body()` and
        // returns the styled display bodies for the newly-appeared warnings.
        fn warn(token: &str) -> Diagnostic {
            Diagnostic::warning(format!("unthemed CSS token --{token}"))
        }
        let key = |token: &str| warn(token).body();

        // Seed with the initial build's warning (mirrors run(), keyed by body()).
        let mut seen: HashSet<String> = [key("colr-brand")].into_iter().collect();

        // Unrelated rebuild: same warning set → nothing new to print.
        assert!(take_new_warnings(&mut seen, vec![warn("colr-brand")]).is_empty());

        // A new warning appears → only the new one is surfaced.
        let new = take_new_warnings(&mut seen, vec![warn("colr-brand"), warn("colr-accent")]);
        assert_eq!(new.len(), 1);
        assert!(new[0].contains("--colr-accent"), "display: {}", new[0]);

        // Both persist → silent.
        assert!(
            take_new_warnings(&mut seen, vec![warn("colr-brand"), warn("colr-accent")]).is_empty()
        );

        // `colr-brand` resolved (only accent remains) → still silent (resolutions
        // aren't re-announced), but `seen` now drops it.
        assert!(take_new_warnings(&mut seen, vec![warn("colr-accent")]).is_empty());

        // `colr-brand` reintroduced → surfaced again because it left the set.
        let reintroduced =
            take_new_warnings(&mut seen, vec![warn("colr-brand"), warn("colr-accent")]);
        assert_eq!(reintroduced.len(), 1);
        assert!(
            reintroduced[0].contains("--colr-brand"),
            "display: {}",
            reintroduced[0]
        );
    }

    #[test]
    fn test_build_and_render_simple() {
        let app = create_app_dir(&[("index.html", "<h1>Hello</h1>"), ("state.json", "{}")]);
        let config = RenderConfig {
            app_args: AppArgs {
                app: app.path().to_path_buf(),
                entry: "index.html".to_string(),
                css: CssStrategy::Link,
                dom: DomStrategy::Shadow,
                plugin: None,
                components: Vec::new(),
                projection_manifests: Vec::new(),
                asset_file_name_template: DEFAULT_ASSET_FILE_NAME_TEMPLATE.to_string(),
                css_public_base: None,
                legal_comments: LegalComments::Inline,
            },
            app_dir: app.path().to_path_buf(),
            state_file: Some(app.path().join("state.json")),
            token_file: None,
            component_asset_roots: Vec::new(),
            metafile: None,
            base_path: None,
        };
        let hmr = LiveReload::new(HMR_ENDPOINT);
        let BuildRenderResult { html, .. } = build_and_render(&config, Some(&hmr)).unwrap();
        assert!(html.contains("<h1>Hello</h1>"));
    }

    #[test]
    fn test_build_and_render_with_state() {
        let app = create_app_dir(&[
            ("index.html", "<p>{{name}}</p>"),
            ("state.json", r#"{"name":"WebUI"}"#),
        ]);
        let config = RenderConfig {
            app_args: AppArgs {
                app: app.path().to_path_buf(),
                entry: "index.html".to_string(),
                css: CssStrategy::Link,
                dom: DomStrategy::Shadow,
                plugin: None,
                components: Vec::new(),
                projection_manifests: Vec::new(),
                asset_file_name_template: DEFAULT_ASSET_FILE_NAME_TEMPLATE.to_string(),
                css_public_base: None,
                legal_comments: LegalComments::Inline,
            },
            app_dir: app.path().to_path_buf(),
            state_file: Some(app.path().join("state.json")),
            token_file: None,
            component_asset_roots: Vec::new(),
            metafile: None,
            base_path: None,
        };
        let hmr = LiveReload::new(HMR_ENDPOINT);
        let BuildRenderResult { html, .. } = build_and_render(&config, Some(&hmr)).unwrap();
        assert!(html.contains("<p>WebUI</p>"));
    }

    #[test]
    fn test_build_and_render_selects_fast_plugin_versions() {
        let app = create_app_dir(&[
            (
                "index.html",
                "<html><head></head><body><my-card></my-card></body></html>",
            ),
            ("my-card.html", "<span>{{name}}</span>"),
            ("state.json", r#"{"name":"Alice"}"#),
        ]);

        let render = |plugin| {
            let config = RenderConfig {
                app_args: AppArgs {
                    app: app.path().to_path_buf(),
                    entry: "index.html".to_string(),
                    css: CssStrategy::Link,
                    dom: DomStrategy::Shadow,
                    plugin,
                    components: Vec::new(),
                    projection_manifests: Vec::new(),
                    asset_file_name_template: DEFAULT_ASSET_FILE_NAME_TEMPLATE.to_string(),
                    css_public_base: None,
                    legal_comments: LegalComments::Inline,
                },
                app_dir: app.path().to_path_buf(),
                state_file: Some(app.path().join("state.json")),
                token_file: None,
                component_asset_roots: Vec::new(),
                metafile: None,
                base_path: None,
            };
            build_and_render(&config, None).unwrap().html
        };

        let fast = render(Some(Plugin::Fast));
        assert!(fast.contains("<!--fe-b$$start$$0$$name$$fe-b-->"));
        assert!(!fast.contains("<!--fe:b-->"));
        assert!(fast.contains("id=\"webui-data\""));
        assert!(!fast.contains("window.__webui"));
        assert!(!fast.contains(r#""templates""#));
        assert!(!fast.contains("templateFns"));

        let fast_v2 = render(Some(Plugin::FastV2));
        assert!(fast_v2.contains("<!--fe-b$$start$$0$$name$$fe-b-->"));
        assert!(!fast_v2.contains("<!--fe:b-->"));
        assert!(fast_v2.contains("id=\"webui-data\""));
        assert!(!fast_v2.contains("window.__webui"));
        assert!(!fast_v2.contains(r#""templates""#));
        assert!(!fast_v2.contains("templateFns"));

        let fast_v3 = render(Some(Plugin::FastV3));
        assert!(fast_v3.contains("<!--fe:b-->"));
        assert!(!fast_v3.contains("<!--fe-b$$start$$"));
        assert!(fast_v3.contains("id=\"webui-data\""));
        assert!(!fast_v3.contains("window.__webui"));
        assert!(!fast_v3.contains(r#""templates""#));
        assert!(!fast_v3.contains("templateFns"));
    }

    #[test]
    fn test_build_and_render_without_watch_has_no_hmr_script() {
        let app = create_app_dir(&[("index.html", "<h1>Hello</h1>"), ("state.json", "{}")]);
        let config = RenderConfig {
            app_args: AppArgs {
                app: app.path().to_path_buf(),
                entry: "index.html".to_string(),
                css: CssStrategy::Link,
                dom: DomStrategy::Shadow,
                plugin: None,
                components: Vec::new(),
                projection_manifests: Vec::new(),
                asset_file_name_template: DEFAULT_ASSET_FILE_NAME_TEMPLATE.to_string(),
                css_public_base: None,
                legal_comments: LegalComments::Inline,
            },
            app_dir: app.path().to_path_buf(),
            state_file: Some(app.path().join("state.json")),
            token_file: None,
            component_asset_roots: Vec::new(),
            metafile: None,
            base_path: None,
        };
        let BuildRenderResult { html, .. } = build_and_render(&config, None).unwrap();
        assert!(!html.contains(HMR_ENDPOINT));
        assert!(!html.contains("EventSource"));
    }

    #[test]
    fn test_ensure_local_port_available_reports_port_in_use() {
        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
        let port = listener.local_addr().unwrap().port();

        let error = ensure_local_port_available(port).unwrap_err();

        assert!(
            format!("{error:#}").contains(&format!("Port {port} on 127.0.0.1 is already in use"))
        );
        drop(listener);
    }

    #[test]
    fn test_build_and_render_missing_state_file() {
        let app = create_app_dir(&[("index.html", "<h1>No State</h1>")]);
        let config = RenderConfig {
            app_args: AppArgs {
                app: app.path().to_path_buf(),
                entry: "index.html".to_string(),
                css: CssStrategy::Link,
                dom: DomStrategy::Shadow,
                plugin: None,
                components: Vec::new(),
                projection_manifests: Vec::new(),
                asset_file_name_template: DEFAULT_ASSET_FILE_NAME_TEMPLATE.to_string(),
                css_public_base: None,
                legal_comments: LegalComments::Inline,
            },
            app_dir: app.path().to_path_buf(),
            state_file: Some(app.path().join("state.json")),
            token_file: None,
            component_asset_roots: Vec::new(),
            metafile: None,
            base_path: None,
        };
        let hmr = LiveReload::new(HMR_ENDPOINT);
        let result = build_and_render(&config, Some(&hmr));
        assert!(result.is_err());
    }

    #[test]
    fn test_build_and_render_no_state_file() {
        let app = create_app_dir(&[("index.html", "<h1>Hello</h1>")]);
        let config = RenderConfig {
            app_args: AppArgs {
                app: app.path().to_path_buf(),
                entry: "index.html".to_string(),
                css: CssStrategy::Link,
                dom: DomStrategy::Shadow,
                plugin: None,
                components: Vec::new(),
                projection_manifests: Vec::new(),
                asset_file_name_template: DEFAULT_ASSET_FILE_NAME_TEMPLATE.to_string(),
                css_public_base: None,
                legal_comments: LegalComments::Inline,
            },
            app_dir: app.path().to_path_buf(),
            state_file: None,
            token_file: None,
            component_asset_roots: Vec::new(),
            metafile: None,
            base_path: None,
        };
        let result = build_and_render(&config, None).unwrap();
        assert!(result.html.contains("<h1>Hello</h1>"));
    }

    #[test]
    fn test_build_and_render_missing_template() {
        let app = create_app_dir(&[("state.json", "{}")]);
        let config = RenderConfig {
            app_args: AppArgs {
                app: app.path().to_path_buf(),
                entry: "index.html".to_string(),
                css: CssStrategy::Link,
                dom: DomStrategy::Shadow,
                plugin: None,
                components: Vec::new(),
                projection_manifests: Vec::new(),
                asset_file_name_template: DEFAULT_ASSET_FILE_NAME_TEMPLATE.to_string(),
                css_public_base: None,
                legal_comments: LegalComments::Inline,
            },
            app_dir: app.path().to_path_buf(),
            state_file: Some(app.path().join("state.json")),
            token_file: None,
            component_asset_roots: Vec::new(),
            metafile: None,
            base_path: None,
        };
        let hmr = LiveReload::new(HMR_ENDPOINT);
        let result = build_and_render(&config, Some(&hmr));
        assert!(result.is_err());
    }

    #[test]
    fn test_build_request_paths_preserves_query_string() {
        assert_eq!(
            build_request_paths("search", "q=shirt&sort=price-desc"),
            RequestPaths {
                route_path: "/search".to_string(),
                request_path: "/search?q=shirt&sort=price-desc".to_string(),
            }
        );
    }

    #[test]
    fn test_build_request_paths_handles_root_query() {
        assert_eq!(
            build_request_paths("", "q=shirt"),
            RequestPaths {
                route_path: "/".to_string(),
                request_path: "/?q=shirt".to_string(),
            }
        );
    }

    #[test]
    fn test_collect_needed_template_names_returns_active_route_payloads() {
        let mut fragments = HashMap::new();
        fragments.insert(
            "index.html".to_string(),
            FragmentList {
                fragments: vec![WebUIFragment::component("mp-app")],
            },
        );
        fragments.insert(
            "mp-app".to_string(),
            FragmentList {
                fragments: vec![
                    WebUIFragment::component("mp-category-nav"),
                    WebUIFragment::route_from(WebUiFragmentRoute {
                        path: "/search/:category".to_string(),
                        fragment_id: "mp-page-search".to_string(),
                        exact: true,
                        keep_alive: false,
                        ..Default::default()
                    }),
                    WebUIFragment::route_from(WebUiFragmentRoute {
                        path: "/product/:handle".to_string(),
                        fragment_id: "mp-page-product".to_string(),
                        exact: true,
                        keep_alive: false,
                        ..Default::default()
                    }),
                ],
            },
        );
        fragments.insert(
            "mp-category-nav".to_string(),
            FragmentList {
                fragments: vec![WebUIFragment::raw("<nav></nav>")],
            },
        );
        fragments.insert(
            "mp-page-search".to_string(),
            FragmentList {
                fragments: vec![WebUIFragment::component("mp-product-grid")],
            },
        );
        fragments.insert(
            "mp-product-grid".to_string(),
            FragmentList {
                fragments: vec![WebUIFragment::raw("<div></div>")],
            },
        );
        fragments.insert(
            "mp-page-product".to_string(),
            FragmentList {
                fragments: vec![WebUIFragment::component("mp-product-detail")],
            },
        );
        fragments.insert(
            "mp-product-detail".to_string(),
            FragmentList {
                fragments: vec![WebUIFragment::raw("<article></article>")],
            },
        );

        let mut protocol = WebUIProtocol::with_tokens(fragments, Vec::new());
        protocol
            .components
            .entry("mp-page-search".to_string())
            .or_default()
            .template = "<f-template id=search></f-template>".to_string();
        protocol
            .components
            .entry("mp-page-product".to_string())
            .or_default()
            .template = "<f-template id=product></f-template>".to_string();
        let (needed, inventory) =
            collect_needed_template_names(&protocol, "index.html", "/search/shirts", "");

        assert_eq!(needed, vec!["mp-page-search".to_string()]);
        assert!(!needed.contains(&"mp-page-product".to_string()));
        assert!(!inventory.is_empty());
    }

    #[actix_web::test]
    async fn test_fetch_api_state_preserves_query_string() {
        let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
        let port = listener.local_addr().unwrap().port();

        let server = HttpServer::new(|| {
            App::new().route(
                "/search",
                web::get().to(|query: web::Query<HashMap<String, String>>| async move {
                    HttpResponse::Ok().json(serde_json::json!({
                        "state": {
                            "query": query.get("q").cloned().unwrap_or_default(),
                            "sort": query.get("sort").cloned().unwrap_or_default(),
                        }
                    }))
                }),
            )
        })
        .listen(listener)
        .unwrap()
        .run();

        let handle = server.handle();
        actix_web::rt::spawn(server);

        let state = fetch_api_state(port, "/search?q=shirt&sort=price-desc")
            .await
            .unwrap();

        assert_eq!(state["query"], "shirt");
        assert_eq!(state["sort"], "price-desc");

        handle.stop(true).await;
    }

    #[actix_web::test]
    async fn test_route_state_fetch_preserves_encoded_request_target() {
        let request_targets = [
            "/projects/WebUI%20Fidelity%20Fixture?filter=space%20value",
            "/reviews/WebUI/ceo%2Fbranch?filter=slash%2Fvalue",
            "/discount/100%25?filter=percent%25value",
            "/city/Montr%C3%A9al?filter=unicode%C3%A9",
        ];
        let (port, handle, captured_targets) = start_request_target_server();
        let app = actix_test::init_service(
            App::new()
                .app_data(test_server_context(port))
                .route("/{tail:.*}", web::get().to(handle_asset)),
        )
        .await;

        for request_target in request_targets {
            let response = actix_test::call_service(
                &app,
                actix_test::TestRequest::get()
                    .uri(request_target)
                    .insert_header(("accept", "application/json"))
                    .to_request(),
            )
            .await;
            assert_eq!(response.status(), StatusCode::OK);
        }

        let expected: Vec<String> = request_targets
            .iter()
            .map(|target| (*target).to_string())
            .collect();
        assert_eq!(*captured_targets.lock().unwrap(), expected);
        handle.stop(true).await;
    }

    fn start_stream_status_server(status: StatusCode) -> (u16, actix_web::dev::ServerHandle) {
        let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
        let port = listener.local_addr().unwrap().port();
        let server = HttpServer::new(move || {
            App::new().default_service(web::to(move || async move {
                HttpResponse::build(status)
                    .content_type("application/x-webui-stream")
                    .body("streaming render capacity is temporarily exhausted")
            }))
        })
        .listen(listener)
        .unwrap()
        .run();
        let handle = server.handle();
        actix_web::rt::spawn(server);
        (port, handle)
    }

    fn streaming_fallback_context(api_port: u16) -> web::Data<ServerContext> {
        let mut fragments = HashMap::new();
        fragments.insert(
            "index.html".to_string(),
            FragmentList {
                fragments: vec![WebUIFragment::raw(
                    "<html><body><main>fallback rendered</main></body></html>",
                )],
            },
        );
        let protocol = Arc::new(Protocol::new(WebUIProtocol::with_tokens(
            fragments,
            Vec::new(),
        )));
        web::Data::new(ServerContext {
            state: Arc::new(Mutex::new(SharedState {
                rendered_html: String::new(),
                css_files: HashMap::new(),
                component_assets: HashMap::new(),
                protocol: Some(protocol),
                state_data: Some(Value::Object(serde_json::Map::new())),
                token_css: None,
                rebuild_error: None,
                entry: "index.html".to_string(),
            })),
            livereload: None,
            assets_dir: None,
            api_port: Some(api_port),
            plugin: None,
            base_path: None,
            chunk_pool: Arc::new(webui::streaming::ChunkPool::new(
                4,
                StreamingWriter::CHUNK_TARGET + 1024,
            )),
        })
    }

    /// A streaming API that refuses the request never produced a stream, so the
    /// dev server must degrade to a buffered render exactly like it does for a
    /// connection error — not hand the browser a raw upstream error body.
    #[actix_web::test]
    async fn test_streaming_api_error_status_degrades_to_a_rendered_page() {
        for status in [
            StatusCode::SERVICE_UNAVAILABLE,
            StatusCode::INTERNAL_SERVER_ERROR,
            StatusCode::BAD_GATEWAY,
        ] {
            let (port, handle) = start_stream_status_server(status);
            let context = streaming_fallback_context(port);

            let response = render_page_response(&context, "/", "/").await;

            assert_eq!(
                response.status(),
                StatusCode::OK,
                "upstream {status} must not surface as the page status",
            );
            let body = to_bytes(response.into_body()).await.unwrap();
            let body = String::from_utf8_lossy(&body);
            assert!(
                body.contains("fallback rendered"),
                "upstream {status} must still render the page, got: {body}",
            );
            handle.stop(true).await;
        }
    }

    fn fallback_kind_for_accept(accept: &str) -> SpaFallbackKind {
        let req = actix_test::TestRequest::default()
            .insert_header(("accept", accept))
            .to_http_request();
        spa_fallback_kind(&req)
    }

    #[test]
    fn test_spa_fallback_kind_honors_q_weights() {
        let cases = [
            ("application/json;q=0", SpaFallbackKind::None),
            ("text/html;q=0", SpaFallbackKind::None),
            (
                "text/html;q=0.8, application/json;q=0.9",
                SpaFallbackKind::Json,
            ),
            (
                "text/html;q=0.9, application/json;q=0.8",
                SpaFallbackKind::Html,
            ),
            ("text/html;q=1, application/json;q=1", SpaFallbackKind::Json),
            ("application/json", SpaFallbackKind::Json),
            (
                "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
                SpaFallbackKind::Html,
            ),
            ("APPLICATION/JSON ; Q=0.5", SpaFallbackKind::Json),
            ("application/json;q=not-a-number", SpaFallbackKind::Json),
            // Out-of-range q is malformed and falls back to the default 1.0, so
            // it neither wins tie-breaking nor disables the media type.
            ("text/html;q=2, application/json;q=1", SpaFallbackKind::Json),
            ("text/html;q=-1", SpaFallbackKind::Html),
        ];

        for (accept, expected) in cases {
            assert_eq!(fallback_kind_for_accept(accept), expected, "{accept}");
        }
    }

    #[actix_web::test]
    async fn test_spa_fallback_allows_encoded_dot_route_parameter() {
        let request_target = "/discount/100%2E5?filter=x";
        let (port, handle, captured_targets) = start_request_target_server();
        let app = actix_test::init_service(
            App::new()
                .app_data(test_server_context(port))
                .route("/{tail:.*}", web::get().to(handle_asset)),
        )
        .await;

        let response = actix_test::call_service(
            &app,
            actix_test::TestRequest::get()
                .uri(request_target)
                .insert_header(("accept", "application/json"))
                .to_request(),
        )
        .await;
        assert_eq!(response.status(), StatusCode::OK);

        let captured = match captured_targets.lock() {
            Ok(targets) => targets.clone(),
            Err(error) => panic!("captured targets mutex poisoned: {error}"),
        };
        assert_eq!(captured, vec![request_target.to_string()]);
        handle.stop(true).await;
    }

    #[actix_web::test]
    async fn test_spa_fallback_allows_literal_dot_html_route() {
        let app = actix_test::init_service(
            App::new()
                .app_data(test_route_context(dotted_route_protocol()))
                .route("/{tail:.*}", web::get().to(handle_asset)),
        )
        .await;

        let response = actix_test::call_service(
            &app,
            actix_test::TestRequest::get()
                .uri("/docs/v2.1")
                .insert_header(("accept", "text/html,application/xhtml+xml"))
                .to_request(),
        )
        .await;

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[actix_web::test]
    async fn test_spa_fallback_rejects_missing_asset_intent() {
        let app = actix_test::init_service(
            App::new()
                .app_data(test_route_context(dotted_route_protocol()))
                .route("/{tail:.*}", web::get().to(handle_asset)),
        )
        .await;

        let response = actix_test::call_service(
            &app,
            actix_test::TestRequest::get()
                .uri("/missing.js")
                .insert_header(("accept", "text/javascript,*/*;q=0.1"))
                .to_request(),
        )
        .await;
        assert_eq!(response.status(), StatusCode::NOT_FOUND);

        let response = actix_test::call_service(
            &app,
            actix_test::TestRequest::get()
                .uri("/users/john.doe")
                .insert_header(("accept", "*/*"))
                .to_request(),
        )
        .await;
        assert_eq!(response.status(), StatusCode::NOT_FOUND);

        let response = actix_test::call_service(
            &app,
            actix_test::TestRequest::get()
                .uri("/docs/v2.1")
                .to_request(),
        )
        .await;
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[actix_web::test]
    async fn test_api_proxy_preserves_encoded_request_target() {
        let request_targets = [
            "/api/projects/WebUI%20Fidelity%20Fixture?filter=space%20value",
            "/api/reviews/WebUI/ceo%2Fbranch?filter=slash%2Fvalue",
            "/api/discount/100%25?filter=percent%25value",
            "/api/city/Montr%C3%A9al?filter=unicode%C3%A9",
        ];
        let (port, handle, captured_targets) = start_request_target_server();
        let app = actix_test::init_service(
            App::new()
                .app_data(test_server_context(port))
                .route("/api/{tail:.*}", web::route().to(handle_api_proxy)),
        )
        .await;

        for request_target in request_targets {
            let response = actix_test::call_service(
                &app,
                actix_test::TestRequest::get()
                    .uri(request_target)
                    .to_request(),
            )
            .await;
            assert_eq!(response.status(), StatusCode::OK);
        }

        let expected: Vec<String> = request_targets
            .iter()
            .map(|target| (*target).to_string())
            .collect();
        assert_eq!(*captured_targets.lock().unwrap(), expected);
        handle.stop(true).await;
    }

    #[test]
    fn test_hmr_script_is_injected_when_livereload_present() {
        let app = create_app_dir(&[("index.html", "<h1>Hi</h1>"), ("state.json", "{}")]);
        let config = RenderConfig {
            app_args: AppArgs {
                app: app.path().to_path_buf(),
                entry: "index.html".to_string(),
                css: CssStrategy::Link,
                dom: DomStrategy::Shadow,
                plugin: None,
                components: Vec::new(),
                projection_manifests: Vec::new(),
                asset_file_name_template: DEFAULT_ASSET_FILE_NAME_TEMPLATE.to_string(),
                css_public_base: None,
                legal_comments: LegalComments::Inline,
            },
            app_dir: app.path().to_path_buf(),
            state_file: Some(app.path().join("state.json")),
            token_file: None,
            component_asset_roots: Vec::new(),
            metafile: None,
            base_path: None,
        };
        let lr = LiveReload::new(HMR_ENDPOINT);
        let BuildRenderResult { html, .. } = build_and_render(&config, Some(&lr)).unwrap();
        // The injected SSE bootstrap should reference the endpoint.
        assert!(html.contains(HMR_ENDPOINT));
        assert!(html.contains("EventSource"));
    }

    #[test]
    fn test_watch_paths_excludes_servedir() {
        // serve_dir is intentionally NOT watched: it is the destination
        // for client bundles written by other tools (esbuild, pnpm,
        // E2E harness). Watching it would cause spurious livereload
        // broadcasts during E2E runs.
        let dir = create_app_dir(&[("state.json", "{}"), ("public/x.css", "")]);
        let paths = ServePaths {
            app_dir: dir.path().to_path_buf(),
            state_file: Some(dir.path().join("state.json")),
            serve_dir: Some(dir.path().join("public")),
            metafile: None,
        };
        let watched = paths.watch_paths();
        assert_eq!(watched.len(), 2);
        assert!(watched.contains(&dir.path().to_path_buf()));
        assert!(watched.contains(&dir.path().join("state.json")));
        assert!(!watched.contains(&dir.path().join("public")));
    }

    #[test]
    fn test_build_and_render_hello_world_example() {
        let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        let app_dir = manifest_dir.join("../../examples/app/hello-world/src");
        let config = RenderConfig {
            app_args: AppArgs {
                app: app_dir.clone(),
                entry: "index.html".to_string(),
                css: CssStrategy::Link,
                dom: DomStrategy::Shadow,
                plugin: None,
                components: Vec::new(),
                projection_manifests: Vec::new(),
                asset_file_name_template: DEFAULT_ASSET_FILE_NAME_TEMPLATE.to_string(),
                css_public_base: None,
                legal_comments: LegalComments::Inline,
            },
            app_dir,
            state_file: Some(manifest_dir.join("../../examples/app/hello-world/data/state.json")),
            token_file: None,
            component_asset_roots: Vec::new(),
            metafile: None,
            base_path: None,
        };
        let lr = LiveReload::new(HMR_ENDPOINT);
        let BuildRenderResult { html, .. } = build_and_render(&config, Some(&lr)).unwrap();
        assert!(html.contains("Hello, WebUI!"));
        assert!(html.contains("Ali"));
        assert!(html.contains("Mohamed Mansour"));
        // HMR script should be injected
        assert!(html.contains(HMR_ENDPOINT));
    }

    #[actix_web::test]
    async fn test_route_precedence_over_asset_catch_all() {
        let livereload = LiveReload::new(HMR_ENDPOINT);
        let lr_endpoint = livereload.endpoint().to_string();
        let context = web::Data::new(ServerContext {
            state: Arc::new(Mutex::new(SharedState {
                rendered_html: "<html><body>ok</body></html>".to_string(),
                css_files: HashMap::new(),
                component_assets: HashMap::new(),
                protocol: None,
                state_data: None,
                token_css: None,
                rebuild_error: None,
                entry: "index.html".to_string(),
            })),
            livereload: Some(livereload.clone()),
            assets_dir: None,
            api_port: None,
            plugin: None,
            base_path: None,
            chunk_pool: Arc::new(webui::streaming::ChunkPool::new(
                4,
                StreamingWriter::CHUNK_TARGET + 1024,
            )),
        });

        let app = actix_test::init_service(
            App::new()
                .app_data(context.clone())
                .app_data(web::Data::new(livereload))
                .route("/", web::get().to(handle_index))
                .route("/index.html", web::get().to(handle_index))
                .route(&lr_endpoint, web::get().to(sse_handler))
                .route("/{tail:.*}", web::get().to(handle_asset))
                .default_service(web::route().to(handle_not_found)),
        )
        .await;

        // SSE endpoint takes precedence over the catch-all asset route.
        let lr_response = actix_test::call_service(
            &app,
            actix_test::TestRequest::get()
                .uri(HMR_ENDPOINT)
                .to_request(),
        )
        .await;
        assert_eq!(lr_response.status(), StatusCode::OK);
        let content_type = lr_response
            .headers()
            .get("content-type")
            .map(|v| v.to_str().unwrap_or("").to_string())
            .unwrap_or_default();
        assert!(
            content_type.starts_with("text/event-stream"),
            "expected SSE content-type, got {content_type:?}"
        );

        let index_response = actix_test::call_service(
            &app,
            actix_test::TestRequest::get()
                .uri("/index.html")
                .to_request(),
        )
        .await;
        assert_eq!(index_response.status(), StatusCode::OK);

        let index_body = actix_test::read_body(index_response).await;
        assert_eq!(
            index_body,
            web::Bytes::from_static(b"<html><body>ok</body></html>")
        );
    }

    #[actix_web::test]
    async fn test_refresh_after_rebuild_error_reports_error_instead_of_stale_html() {
        let livereload = LiveReload::new(HMR_ENDPOINT);
        let context = web::Data::new(ServerContext {
            state: Arc::new(Mutex::new(SharedState {
                rendered_html: "<html><body>stale ok</body></html>".to_string(),
                css_files: HashMap::new(),
                component_assets: HashMap::new(),
                protocol: None,
                state_data: None,
                token_css: None,
                rebuild_error: Some(
                    "missing theme token [missing-theme-token]\n    --token-c".to_string(),
                ),
                entry: "index.html".to_string(),
            })),
            livereload: Some(livereload),
            assets_dir: None,
            api_port: None,
            plugin: None,
            base_path: None,
            chunk_pool: Arc::new(webui::streaming::ChunkPool::new(
                4,
                StreamingWriter::CHUNK_TARGET + 1024,
            )),
        });

        let app = actix_test::init_service(
            App::new()
                .app_data(context)
                .route("/", web::get().to(handle_index)),
        )
        .await;

        let response =
            actix_test::call_service(&app, actix_test::TestRequest::get().uri("/").to_request())
                .await;

        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
        let body = String::from_utf8(actix_test::read_body(response).await.to_vec()).unwrap();
        assert!(body.contains("missing-theme-token"), "body: {body}");
        assert!(body.contains("--token-c"), "body: {body}");
        assert!(body.contains("EventSource"), "body: {body}");
        assert!(body.contains(HMR_ENDPOINT), "body: {body}");
        assert!(!body.contains("stale ok"), "body: {body}");
    }

    #[actix_web::test]
    async fn test_json_partial_rebuild_error_skips_api_state_fetch() {
        let api_hits = Arc::new(AtomicUsize::new(0));
        let api_hits_for_server = Arc::clone(&api_hits);
        let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
        let port = listener.local_addr().unwrap().port();
        let server = HttpServer::new(move || {
            let api_hits = Arc::clone(&api_hits_for_server);
            App::new().default_service(web::to(move || {
                let api_hits = Arc::clone(&api_hits);
                async move {
                    api_hits.fetch_add(1, Ordering::SeqCst);
                    HttpResponse::Ok()
                        .content_type("application/json")
                        .body(r#"{"state":{"name":"api"}}"#)
                }
            }))
        })
        .listen(listener)
        .unwrap()
        .run();
        let handle = server.handle();
        actix_web::rt::spawn(server);

        let context = web::Data::new(ServerContext {
            state: Arc::new(Mutex::new(SharedState {
                rendered_html: "<html><body>stale ok</body></html>".to_string(),
                css_files: HashMap::new(),
                component_assets: HashMap::new(),
                protocol: None,
                state_data: None,
                token_css: None,
                rebuild_error: Some(
                    "missing theme token [missing-theme-token]\n    --token-c".to_string(),
                ),
                entry: "index.html".to_string(),
            })),
            livereload: None,
            assets_dir: None,
            api_port: Some(port),
            plugin: None,
            base_path: None,
            chunk_pool: Arc::new(webui::streaming::ChunkPool::new(
                4,
                StreamingWriter::CHUNK_TARGET + 1024,
            )),
        });

        let app = actix_test::init_service(
            App::new()
                .app_data(context)
                .route("/", web::get().to(handle_index)),
        )
        .await;
        let response = actix_test::call_service(
            &app,
            actix_test::TestRequest::get()
                .uri("/")
                .insert_header(("accept", "application/json"))
                .to_request(),
        )
        .await;

        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
        let body = String::from_utf8(actix_test::read_body(response).await.to_vec()).unwrap();
        assert!(body.contains("missing-theme-token"), "body: {body}");
        assert_eq!(api_hits.load(Ordering::SeqCst), 0);
        handle.stop(true).await;
    }

    #[actix_web::test]
    async fn test_html_render_rebuild_error_skips_api_state_fetch() {
        // An HTML (non-JSON) request with an API proxy configured must return
        // the stored rebuild error from the single state snapshot, without
        // reaching out to the API server first.
        let api_hits = Arc::new(AtomicUsize::new(0));
        let api_hits_for_server = Arc::clone(&api_hits);
        let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
        let port = listener.local_addr().unwrap().port();
        let server = HttpServer::new(move || {
            let api_hits = Arc::clone(&api_hits_for_server);
            App::new().default_service(web::to(move || {
                let api_hits = Arc::clone(&api_hits);
                async move {
                    api_hits.fetch_add(1, Ordering::SeqCst);
                    HttpResponse::Ok()
                        .content_type("application/json")
                        .body(r#"{"state":{"name":"api"}}"#)
                }
            }))
        })
        .listen(listener)
        .unwrap()
        .run();
        let handle = server.handle();
        actix_web::rt::spawn(server);

        let context = web::Data::new(ServerContext {
            state: Arc::new(Mutex::new(SharedState {
                rendered_html: "<html><body>stale ok</body></html>".to_string(),
                css_files: HashMap::new(),
                component_assets: HashMap::new(),
                protocol: None,
                state_data: None,
                token_css: None,
                rebuild_error: Some(
                    "missing theme token [missing-theme-token]\n    --token-c".to_string(),
                ),
                entry: "index.html".to_string(),
            })),
            livereload: None,
            assets_dir: None,
            api_port: Some(port),
            plugin: None,
            base_path: None,
            chunk_pool: Arc::new(webui::streaming::ChunkPool::new(
                4,
                StreamingWriter::CHUNK_TARGET + 1024,
            )),
        });

        let app = actix_test::init_service(
            App::new()
                .app_data(context)
                .route("/", web::get().to(handle_index)),
        )
        .await;
        let response =
            actix_test::call_service(&app, actix_test::TestRequest::get().uri("/").to_request())
                .await;

        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
        let body = String::from_utf8(actix_test::read_body(response).await.to_vec()).unwrap();
        assert!(body.contains("missing-theme-token"), "body: {body}");
        assert!(!body.contains("stale ok"), "body: {body}");
        assert_eq!(api_hits.load(Ordering::SeqCst), 0);
        handle.stop(true).await;
    }

    #[test]
    fn test_incremental_rebuild_failure_persists_error_for_refresh() {
        let app = create_app_dir(&[
            ("index.html", "<my-card></my-card>"),
            ("my-card.html", "<div>Card</div>"),
            (
                "my-card.css",
                ":host { --token-a: red; --foo-bar: var(--token-a, var(--token-b, var(--token-c))); }",
            ),
        ]);
        let config = RenderConfig {
            app_args: AppArgs {
                app: app.path().to_path_buf(),
                entry: "index.html".to_string(),
                css: CssStrategy::Link,
                dom: DomStrategy::Shadow,
                plugin: None,
                components: Vec::new(),
                projection_manifests: Vec::new(),
                asset_file_name_template: DEFAULT_ASSET_FILE_NAME_TEMPLATE.to_string(),
                css_public_base: None,
                legal_comments: LegalComments::Inline,
            },
            app_dir: app.path().to_path_buf(),
            state_file: None,
            token_file: Some(webui::TokenFile {
                themes: HashMap::from([(
                    "light".to_string(),
                    HashMap::from([("token-b".to_string(), "green".to_string())]),
                )]),
            }),
            component_asset_roots: Vec::new(),
            metafile: None,
            base_path: None,
        };
        let state = Arc::new(Mutex::new(SharedState {
            rendered_html: "<html><body>stale ok</body></html>".to_string(),
            css_files: HashMap::new(),
            component_assets: HashMap::new(),
            protocol: None,
            state_data: None,
            token_css: None,
            rebuild_error: None,
            entry: "index.html".to_string(),
        }));
        let livereload = LiveReload::new(HMR_ENDPOINT);

        let result = rebuild_and_update_state(&config, &livereload, &state);

        assert!(result.is_err(), "missing token should fail rebuild");
        let error = state.lock().unwrap().rebuild_error.clone().unwrap();
        assert!(error.contains("missing-theme-token"), "error: {error}");
        assert!(error.contains("--token-c"), "error: {error}");
        // The error demands the missing `--token-c`, not the locally-defined
        // `--token-a` (which appears in the source snippet only as context).
        assert!(!error.contains("add --token-a"), "error: {error}");

        std::fs::write(
            app.path().join("my-card.css"),
            ":host { --foo-bar: var(--token-b); }",
        )
        .unwrap();
        assert!(
            rebuild_and_update_state(&config, &livereload, &state).is_ok(),
            "a later valid synchronization file must recover the rebuild loop"
        );
        assert!(state.lock().unwrap().rebuild_error.is_none());
    }

    #[test]
    fn test_incremental_rebuild_returns_theme_token_warnings() {
        // A literal-fallback token absent from the theme is a non-fatal
        // advisory; the rebuild succeeds and the worker is handed the warnings
        // to print under the "rebuilt" line.
        let app = create_app_dir(&[
            ("index.html", "<my-card></my-card>"),
            ("my-card.html", "<div>Card</div>"),
            ("my-card.css", ":host { color: var(--colr-brand, #000); }"),
        ]);
        let config = RenderConfig {
            app_args: AppArgs {
                app: app.path().to_path_buf(),
                entry: "index.html".to_string(),
                css: CssStrategy::Link,
                dom: DomStrategy::Shadow,
                plugin: None,
                components: Vec::new(),
                projection_manifests: Vec::new(),
                asset_file_name_template: DEFAULT_ASSET_FILE_NAME_TEMPLATE.to_string(),
                css_public_base: None,
                legal_comments: LegalComments::Inline,
            },
            app_dir: app.path().to_path_buf(),
            state_file: None,
            token_file: Some(webui::TokenFile {
                themes: HashMap::from([(
                    "light".to_string(),
                    HashMap::from([("color-brand".to_string(), "#abc".to_string())]),
                )]),
            }),
            component_asset_roots: Vec::new(),
            metafile: None,
            base_path: None,
        };
        let state = Arc::new(Mutex::new(SharedState {
            rendered_html: String::new(),
            css_files: HashMap::new(),
            component_assets: HashMap::new(),
            protocol: None,
            state_data: None,
            token_css: None,
            rebuild_error: None,
            entry: "index.html".to_string(),
        }));
        let livereload = LiveReload::new(HMR_ENDPOINT);

        let warnings = match rebuild_and_update_state(&config, &livereload, &state) {
            Ok(warnings) => warnings,
            Err(_) => panic!("literal-fallback typo must not fail the rebuild"),
        };
        assert_eq!(warnings.len(), 1, "warnings: {warnings:?}");
        assert!(
            warnings[0].body().contains("--colr-brand"),
            "warning: {}",
            warnings[0].body()
        );
        assert!(
            warnings[0].body().contains("did you mean --color-brand?"),
            "warning: {}",
            warnings[0].body()
        );
        assert!(state.lock().unwrap().rebuild_error.is_none());
    }

    #[test]
    fn test_build_and_render_trusts_theme_token_dependencies() {
        // `--brand` is optional because the CSS has a literal fallback. When a
        // theme defines it, serve should inject that value as-is and trust the
        // theme instead of failing on its internal `var(--missing)` reference.
        let app = create_app_dir(&[
            ("index.html", "<my-card></my-card>"),
            ("my-card.html", "<div>Card</div>"),
            ("my-card.css", ":host { color: var(--brand, #000); }"),
        ]);
        let config = RenderConfig {
            app_args: AppArgs {
                app: app.path().to_path_buf(),
                entry: "index.html".to_string(),
                css: CssStrategy::Link,
                dom: DomStrategy::Shadow,
                plugin: None,
                components: Vec::new(),
                projection_manifests: Vec::new(),
                asset_file_name_template: DEFAULT_ASSET_FILE_NAME_TEMPLATE.to_string(),
                css_public_base: None,
                legal_comments: LegalComments::Inline,
            },
            app_dir: app.path().to_path_buf(),
            state_file: None,
            token_file: Some(webui::TokenFile {
                themes: HashMap::from([(
                    "light".to_string(),
                    HashMap::from([("brand".to_string(), "var(--missing)".to_string())]),
                )]),
            }),
            component_asset_roots: Vec::new(),
            metafile: None,
            base_path: None,
        };

        let result = build_and_render(&config, None).unwrap();
        let token_css = result.token_css.expect("resolved token css");
        assert_eq!(token_css["light"], "--brand: var(--missing);");
        assert!(
            result.warnings.is_empty(),
            "warnings: {:?}",
            result.warnings
        );
    }

    #[test]
    fn test_build_and_render_emits_component_asset_into_memory() {
        // `--emit-component-assets` parity: serve compiles the static asset and
        // keeps it in memory (served like generated CSS), no `--out` needed.
        let app = create_app_dir(&[
            ("index.html", "<app-shell></app-shell>"),
            ("app-shell.html", "<div></div>"),
            ("lazy-panel.html", "<p>{{title}}</p>"),
            ("lazy-panel.css", ":host { color: red; }"),
            ("lazy-panel.ts", "export {};"),
        ]);
        let config = RenderConfig {
            app_args: AppArgs {
                app: app.path().to_path_buf(),
                entry: "index.html".to_string(),
                css: CssStrategy::Link,
                dom: DomStrategy::Shadow,
                plugin: Some(Plugin::WebUI),
                components: Vec::new(),
                projection_manifests: Vec::new(),
                asset_file_name_template: DEFAULT_ASSET_FILE_NAME_TEMPLATE.to_string(),
                css_public_base: None,
                legal_comments: LegalComments::Inline,
            },
            app_dir: app.path().to_path_buf(),
            state_file: None,
            token_file: None,
            component_asset_roots: vec!["lazy-panel".to_string()],
            metafile: None,
            base_path: None,
        };
        let result = build_and_render(&config, None).unwrap();
        let asset = result
            .component_assets
            .get("lazy-panel.webui.js")
            .unwrap_or_else(|| {
                panic!(
                    "expected lazy-panel.webui.js; got {:?}",
                    result.component_assets.keys().collect::<Vec<_>>()
                )
            });
        assert!(asset.contains("webui-component-asset"), "asset: {asset}");
    }

    #[test]
    fn test_successful_rebuild_replaces_metafile_and_failure_preserves_it() {
        let app = create_app_dir(&[
            ("index.html", "<app-shell></app-shell>"),
            ("app-shell.html", "<div></div>"),
            ("lazy-panel.html", "<p>First</p>"),
        ]);
        let metafile = app.path().join("component-assets.meta.json");
        let config = RenderConfig {
            app_args: AppArgs {
                app: app.path().to_path_buf(),
                entry: "index.html".to_string(),
                css: CssStrategy::Link,
                dom: DomStrategy::Shadow,
                plugin: Some(Plugin::WebUI),
                components: Vec::new(),
                projection_manifests: Vec::new(),
                asset_file_name_template: DEFAULT_ASSET_FILE_NAME_TEMPLATE.to_string(),
                css_public_base: None,
                legal_comments: LegalComments::Inline,
            },
            app_dir: app.path().to_path_buf(),
            state_file: None,
            token_file: None,
            component_asset_roots: vec!["lazy-panel".to_string()],
            metafile: Some(metafile.clone()),
            base_path: None,
        };

        build_and_render(&config, None).unwrap();
        let first = fs::read_to_string(&metafile).unwrap();
        fs::write(
            app.path().join("lazy-panel.html"),
            "<p>Second and larger</p>",
        )
        .unwrap();
        build_and_render(&config, None).unwrap();
        let second = fs::read_to_string(&metafile).unwrap();
        assert_ne!(first, second);

        fs::write(
            app.path().join("lazy-panel.html"),
            r#"<if condition="ready"><p>Broken</if>"#,
        )
        .unwrap();
        assert!(build_and_render(&config, None).is_err());
        assert_eq!(fs::read_to_string(&metafile).unwrap(), second);
        let ignored = watcher_ignore_paths(Some(&metafile));
        assert!(ignored.contains(&metafile::watch_ignore_paths(&metafile)[1]));
        assert!(!metafile_temp_directory(&metafile).exists());
        assert!(
            fs::read_dir(app.path()).unwrap().all(|entry| !entry
                .unwrap()
                .file_name()
                .to_string_lossy()
                .ends_with(".tmp")),
            "atomic writes must not leave temporary files"
        );
    }

    #[test]
    fn test_component_asset_root_css_token_error_fails_dev_build() {
        // The dev-server blind spot this feature closes: a theme-token error in
        // a lazily loaded component (absent from the SSR tree) must fail the
        // build — but only because it is an `--emit-component-assets` root.
        // Without the root, the component is discovered but never parsed, so
        // its CSS tokens are never validated (the bug). With the root, they are.
        let app = create_app_dir(&[
            ("index.html", "<app-shell></app-shell>"),
            ("app-shell.html", "<div></div>"),
            ("lazy-panel.html", "<p>Panel</p>"),
            ("lazy-panel.css", ":host { color: var(--brand-missing); }"),
        ]);
        let make_config = |roots: Vec<String>| RenderConfig {
            app_args: AppArgs {
                app: app.path().to_path_buf(),
                entry: "index.html".to_string(),
                css: CssStrategy::Link,
                dom: DomStrategy::Shadow,
                plugin: Some(Plugin::WebUI),
                components: Vec::new(),
                projection_manifests: Vec::new(),
                asset_file_name_template: DEFAULT_ASSET_FILE_NAME_TEMPLATE.to_string(),
                css_public_base: None,
                legal_comments: LegalComments::Inline,
            },
            app_dir: app.path().to_path_buf(),
            state_file: None,
            token_file: Some(webui::TokenFile {
                themes: HashMap::from([(
                    "light".to_string(),
                    HashMap::from([("brand-other".to_string(), "#000".to_string())]),
                )]),
            }),
            component_asset_roots: roots,
            metafile: None,
            base_path: None,
        };

        // Not an asset root → lazy-panel is never parsed → build is green.
        assert!(
            build_and_render(&make_config(Vec::new()), None).is_ok(),
            "unreferenced non-root component must not be validated"
        );

        // As an asset root → its missing theme token fails the build.
        let err = build_and_render(&make_config(vec!["lazy-panel".to_string()]), None)
            .err()
            .expect("missing theme token in asset root must fail the build");
        let message = format!("{err:#}");
        assert!(
            message.contains("missing-theme-token"),
            "message: {message}"
        );
        assert!(message.contains("--brand-missing"), "message: {message}");
    }

    #[actix_web::test]
    async fn test_handle_asset_serves_component_asset_from_memory() {
        // In-memory component assets are served with a JS MIME type (the
        // framework loads them via dynamic `import()`), taking precedence over
        // `--servedir`.
        let context = web::Data::new(ServerContext {
            state: Arc::new(Mutex::new(SharedState {
                rendered_html: String::new(),
                css_files: HashMap::new(),
                component_assets: HashMap::from([(
                    "lazy-panel.webui.js".to_string(),
                    "export default {\"type\":\"webui-component-asset\"};".to_string(),
                )]),
                protocol: None,
                state_data: None,
                token_css: None,
                rebuild_error: None,
                entry: "index.html".to_string(),
            })),
            livereload: None,
            assets_dir: None,
            api_port: None,
            plugin: None,
            base_path: None,
            chunk_pool: Arc::new(webui::streaming::ChunkPool::new(
                4,
                StreamingWriter::CHUNK_TARGET + 1024,
            )),
        });

        let app = actix_test::init_service(
            App::new()
                .app_data(context)
                .route("/{tail:.*}", web::get().to(handle_asset)),
        )
        .await;

        let response = actix_test::call_service(
            &app,
            actix_test::TestRequest::get()
                .uri("/lazy-panel.webui.js")
                .to_request(),
        )
        .await;

        assert_eq!(response.status(), StatusCode::OK);
        let content_type = response
            .headers()
            .get("content-type")
            .map(|v| v.to_str().unwrap_or("").to_string())
            .unwrap_or_default();
        assert!(
            content_type.starts_with("text/javascript"),
            "expected JS content-type, got {content_type:?}"
        );
        let body = actix_test::read_body(response).await;
        assert!(
            body.starts_with(b"export default"),
            "unexpected asset body: {body:?}"
        );
    }
}