day-script 0.6.2

Declarative app development API using native UI toolkits
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! day-script: the embedded dayscript engine (DESIGN.md §14). Bind-only-when-invited: the
//! server starts only when DAYSCRIPT_PORT + DAYSCRIPT_TOKEN are present in the environment
//! (never otherwise), listens on 127.0.0.1, and accepts only the step catalog. Steps execute
//! as synthesized Day events on the main thread between flushes, deterministic and
//! toolkit-uniform. Locator steps get an implicit bounded wait (default 5s).

use std::collections::BTreeMap;
use std::io::{BufRead, BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::{Arc, mpsc};
use std::time::{Duration, Instant};

use day_core::{NodeProbe, rnode_to_id, with_tree};

/// The dayscript **recorder** and in-process **playback** (§14.6): capture the events an app
/// receives back into a replayable dayscript, and replay one against the live UI. See
/// [`record::start`]/[`record::play`].
pub mod record;
pub use record::play;
/// The in-app test runner behind `day test` (docs/testing.md).
pub mod conformance;
mod memory;
mod memory_watch;
/// The PNG reader behind `sample_pixel` (docs/testing.md).
pub mod png;

/// How long one dispatch may wait for the main thread before the step is failed.
///
/// This is not the step's implicit-wait budget ([`DEFAULT_TIMEOUT_SECS`], §14.3). That one governs
/// re-asking a question whose answer may change ("is it visible yet?"). This one governs a main
/// thread that has not answered *at all*: a CI runner compositing its first frame on a shared vCPU,
/// a debug build faulting in pages, a compositor stall. Those are properties of the machine, not of
/// the script, which is why `DAY_SCRIPT_MAIN_TIMEOUT_SECS` can raise it without editing a
/// walkthrough. It was a flat 10s, and a single Windows runner hiccup mid-walkthrough was enough to
/// fail an otherwise perfect 407-step run.
pub const DEFAULT_MAIN_TIMEOUT_SECS: f64 = 30.0;

// Preserve the embedded engine's public protocol API; the definitions live in the leaf crate.
pub use day_script_protocol::{DEFAULT_TIMEOUT_SECS, DialogMode, Reply, Request, Step};

/// `size_class:`'s `width:` spelling → the class. Kebab-case, matching how the docs name them.
fn parse_width_class(s: &str) -> Option<day_spec::WidthClass> {
    use day_spec::WidthClass as W;
    match s {
        "compact" => Some(W::Compact),
        "medium" => Some(W::Medium),
        "expanded" => Some(W::Expanded),
        "large" => Some(W::Large),
        "extra-large" => Some(W::ExtraLarge),
        _ => None,
    }
}

/// `size_class:`'s `height:` spelling → the class.
fn parse_height_class(s: &str) -> Option<day_spec::HeightClass> {
    use day_spec::HeightClass as H;
    match s {
        "compact" => Some(H::Compact),
        "medium" => Some(H::Medium),
        "expanded" => Some(H::Expanded),
        _ => None,
    }
}

/// The `undo:`/`redo:` steps' shared body: through the installed bridge, or a non-retryable
/// failure when the app has no undo stack.
fn drive_undo(redo: bool) -> Result<Reply, Reply> {
    if day_core::invoke_undo(redo) {
        day_reactive::flush_sync();
        Ok(Reply::ok())
    } else {
        Err(Reply::fail("no undo stack installed".to_string(), false))
    }
}

// ---------------------------------------------------------------------------
// Engine activation + server
// ---------------------------------------------------------------------------

/// Start the engine iff invited via env (call before `launch_with`; inert otherwise).
pub fn init() {
    // Recording (§14.6) is independent of the socket engine: `DAY_RECORD=<path>` (from `day launch
    // --record`, or set directly) starts a headless recorder that continuously flushes a replayable
    // dayscript to that file for the app's lifetime; no port/token needed. Checked before the
    // engine gate so `--record` works on an ordinary launch, and on every backend that calls
    // `init()`.
    if let Some(path) = std::env::var_os("DAY_RECORD").filter(|p| !p.is_empty()) {
        record::start_to_file(path);
    }
    // `DAY_LOG_ACTIONS=1` narrates every action to stdout without recording anything (§14.6): the
    // same lines a recording echoes. An app can also switch it on for itself with
    // `day::record::log_actions(true)`; the env var is here so any app gets it without a rebuild.
    if std::env::var("DAY_LOG_ACTIONS").is_ok_and(|v| v == "1") {
        record::log_actions(true);
    }
    let (Ok(port), Ok(token)) = (
        std::env::var("DAYSCRIPT_PORT"),
        std::env::var("DAYSCRIPT_TOKEN"),
    ) else {
        return;
    };
    let Ok(port) = port.parse::<u16>() else {
        return;
    };
    std::thread::spawn(move || serve(port, token));
}

// ---------------------------------------------------------------------------
// Web transport (docs/web.md): the host page pipes newline-JSON request lines from a
// WebSocket into [`web_line`], and replies leave through the sender given to [`web_init`]
// (the day-cli dev server bridges that WebSocket to the same TCP protocol the runner
// already speaks, so `day drive`/`--script` are unchanged). Everything runs on the one
// wasm thread: the implicit bounded wait reschedules through the delayed poster instead
// of sleeping, and there is no `Instant` (it traps on wasm), so attempts are counted.
// ---------------------------------------------------------------------------

/// Retry cadence of the implicit bounded wait, shared by both transports.
const RETRY_MS: u32 = 100;

#[cfg(target_arch = "wasm32")]
mod web {
    use super::*;
    use std::cell::RefCell;

    /// One reply line out to the page (installed by [`web_init`]).
    type WebSender = Box<dyn Fn(&str)>;

    thread_local! {
        /// (token, reply sender) once [`web_init`] ran; requests before/without it are dropped.
        static WEB: RefCell<Option<(String, WebSender)>> = const { RefCell::new(None) };
        static WATCH: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
    }

    /// Arm the web transport: `token` authenticates each request (the query-parameter
    /// spelling of `DAYSCRIPT_TOKEN`), `send` carries one reply line back to the page.
    pub fn web_init(token: String, send: impl Fn(&str) + 'static) {
        WATCH.with(|w| w.set(w.get() + 1));
        WEB.with(|w| *w.borrow_mut() = Some((token, Box::new(send))));
    }

    /// One request line from the page. Executes on the main thread now; a retryable failure
    /// reschedules itself until the shared step timeout is spent, then the reply goes out
    /// through the sender. Requests are answered in order because the runner awaits each
    /// reply before sending the next step.
    pub fn web_line(line: &str) {
        let reply = match serde_json::from_str::<Request>(line.trim()) {
            Ok(req) => {
                let authed = WEB.with(|w| {
                    w.borrow()
                        .as_ref()
                        .map(|(t, _)| *t == req.token)
                        .unwrap_or(false)
                });
                if authed {
                    if let Step::MemoryWatch { interval_ms } = req.step {
                        if !memory_watch::valid_interval(interval_ms) {
                            send_reply(Reply::fail(
                                "memory_watch interval must be 0 or 100..60000 ms",
                                false,
                            ));
                            return;
                        }
                        let generation = WATCH.with(|w| {
                            w.set(w.get() + 1);
                            w.get()
                        });
                        send_reply(memory_watch::sample());
                        if interval_ms > 0 {
                            watch_tick(generation, interval_ms as u32);
                        }
                        send_reply(Reply::ok());
                        return;
                    }
                    let budget_ms = (req.step.wait_budget_secs() * 1000.0) as u32;
                    attempt(req.step, budget_ms, next_capture_revision());
                    return;
                }
                Reply::fail("bad token", false)
            }
            Err(e) => Reply::fail(format!("bad request: {e}"), false),
        };
        send_reply(reply);
    }

    fn attempt(step: Step, remaining_ms: u32, revision: u32) {
        let reply = exec(step.clone(), revision);
        if reply.ok || !reply.retryable || remaining_ms == 0 {
            send_reply(reply);
            return;
        }
        let interval = if reply.capture_pending { 16 } else { RETRY_MS };
        let delay = interval.min(remaining_ms);
        day_reactive::on_main_delayed(delay, move || attempt(step, remaining_ms - delay, revision));
    }

    fn watch_tick(generation: u64, interval: u32) {
        day_reactive::on_main_delayed(interval, move || {
            if WATCH.with(|w| w.get()) == generation {
                send_reply(memory_watch::sample());
                watch_tick(generation, interval);
            }
        });
    }

    fn send_reply(reply: Reply) {
        let mut out = serde_json::to_string(&reply).unwrap_or_else(|_| "{\"ok\":false}".into());
        out.push('\n');
        WEB.with(|w| {
            if let Some((_, send)) = w.borrow().as_ref() {
                send(&out);
            }
        });
    }
}
#[cfg(target_arch = "wasm32")]
pub use web::{web_init, web_line};

fn serve(port: u16, token: String) {
    // Give the app time to mount before binding traffic arrives.
    std::thread::sleep(Duration::from_millis(300));
    // Retry, because the port is a fixed per-target number and a capture sweep relaunches the
    // app on it every variant: the previous instance can still be letting go of the socket when
    // this one starts. Giving up on the first EADDRINUSE is what made that silent: the engine
    // thread ended, the app carried on without one, and the runner then talked to
    // whatever was still listening. That is the previous variant's app, which shares this run's
    // token and answers every step, so a locale sweep re-photographs the earlier locale instead
    // of failing.
    let deadline = std::time::Instant::now() + Duration::from_secs(15);
    let mut said = false;
    let listener = loop {
        match TcpListener::bind(("127.0.0.1", port)) {
            Ok(l) => break l,
            Err(e) if std::time::Instant::now() < deadline => {
                // Once, not per attempt: a sweep that waits a second or two per variant would
                // otherwise bury the run's own output.
                if !said {
                    said = true;
                    log::warn!("day-script: 127.0.0.1:{port} still busy ({e}) — waiting for it");
                }
                std::thread::sleep(Duration::from_millis(250));
            }
            Err(e) => {
                // Loud: an app with no engine looks exactly like a healthy one until a script
                // drives the wrong process.
                log::error!(
                    "day-script: bind 127.0.0.1:{port} failed after 15s: {e} — this app has NO \
                     dayscript engine; anything driving this port is reaching a DIFFERENT process"
                );
                return;
            }
        }
    };
    for stream in listener.incoming().flatten() {
        handle_conn(stream, &token);
    }
}

fn handle_conn(stream: TcpStream, token: &str) {
    let _ = stream.set_nodelay(true);
    let _ = stream.set_write_timeout(Some(Duration::from_secs(15)));
    let mut reader = BufReader::new(stream.try_clone().expect("clone stream"));
    let writer = Arc::new(std::sync::Mutex::new(stream));
    let mut watch = None;
    let mut line = String::new();
    loop {
        line.clear();
        match reader.read_line(&mut line) {
            Ok(0) | Err(_) => return,
            Ok(_) => {}
        }
        let reply = match serde_json::from_str::<Request>(line.trim()) {
            Ok(req) if req.token == token => {
                if let Step::MemoryWatch { interval_ms } = req.step {
                    if memory_watch::valid_interval(interval_ms) {
                        drop(watch.take());
                        if interval_ms > 0 {
                            watch = Some(memory_watch::Watch::start(writer.clone(), interval_ms));
                        }
                        Reply::ok()
                    } else {
                        Reply::fail("memory_watch interval must be 0 or 100..60000 ms", false)
                    }
                } else {
                    run_step_with_wait(req.step)
                }
            }
            Ok(_) => Reply::fail("bad token", false),
            Err(e) => Reply::fail(format!("bad request: {e}"), false),
        };
        let mut out = serde_json::to_string(&reply).unwrap_or_else(|_| "{\"ok\":false}".into());
        out.push('\n');
        if writer.lock().unwrap().write_all(out.as_bytes()).is_err() {
            return;
        }
    }
}

/// How many times in a row a failed window snapshot is retried before the engine answers
/// "unsupported" (the `screenshot` step): about three seconds at [`RETRY_MS`].
const SNAPSHOT_RETRIES: u32 = 30;
/// Consecutive failed snapshots of the current `screenshot` step.
static SNAPSHOT_MISSES: AtomicU32 = AtomicU32::new(0);
/// A snapshot has succeeded in this process, so a failure is a window not ready, not a backend
/// that cannot capture.
static SNAPSHOT_WORKS: AtomicBool = AtomicBool::new(false);
/// The retries ran out before any snapshot ever succeeded: this backend does not capture, and
/// later `screenshot` steps answer "unsupported" at once.
static SNAPSHOT_NEVER: AtomicBool = AtomicBool::new(false);

/// Implicit bounded wait (§14.3): retryable failures poll on the main thread until timeout
/// (the shared default, or the step's `timeout_secs` where it declares one).
static CAPTURE_REVISION: AtomicU32 = AtomicU32::new(1);
fn next_capture_revision() -> u32 {
    CAPTURE_REVISION.fetch_add(1, Ordering::Relaxed)
}

/// Run one step on the calling thread, which must be Day's UI thread with a tree installed:
/// the entry a harness that already sits on that thread (the mock, `cargo test`) uses instead
/// of the socket.
pub fn step(step: Step) -> Reply {
    exec(step, next_capture_revision())
}

fn run_step_with_wait(step: Step) -> Reply {
    let revision = next_capture_revision();
    let budget = Duration::from_secs_f64(step.wait_budget_secs());
    let deadline = Instant::now() + budget;
    let main_budget = main_thread_budget(budget);
    loop {
        let reply = run_on_main(step.clone(), main_budget, revision);
        if reply.ok || !reply.retryable || Instant::now() > deadline {
            return reply;
        }
        let retry_ms = if reply.capture_pending { 16 } else { RETRY_MS };
        std::thread::sleep(Duration::from_millis(u64::from(retry_ms)));
    }
}

/// The main-thread budget for one dispatch: [`DEFAULT_MAIN_TIMEOUT_SECS`], overridable by
/// `DAY_SCRIPT_MAIN_TIMEOUT_SECS`, and never shorter than the step's wait budget: a step that
/// declares `timeout_secs: 60` is saying the app may legitimately take that long.
fn main_thread_budget(step_budget: Duration) -> Duration {
    let secs = std::env::var("DAY_SCRIPT_MAIN_TIMEOUT_SECS")
        .ok()
        .and_then(|v| v.parse::<f64>().ok())
        .filter(|v| v.is_finite() && *v > 0.0)
        .unwrap_or(DEFAULT_MAIN_TIMEOUT_SECS);
    Duration::from_secs_f64(secs).max(step_budget)
}

fn run_on_main(step: Step, budget: Duration, revision: u32) -> Reply {
    let (tx, rx) = mpsc::sync_channel::<Reply>(1);
    // A dispatch that times out leaves its closure queued on the main thread, where it would run
    // later and apply a `navigate`/`tap` the runner has already given up on, moving the app to a
    // state the rest of the script does not expect, so the real damage shows up as a later step
    // failing for no visible reason. The flag makes an abandoned dispatch a no-op. (It is checked
    // before `exec`, so a dispatch that starts in the instant before the timeout still runs; that
    // window is inherent without cancelling work already on the main thread.)
    let abandoned = Arc::new(AtomicBool::new(false));
    let flag = Arc::clone(&abandoned);
    day_reactive::on_main(move || {
        if flag.load(Ordering::SeqCst) {
            return;
        }
        // The engine listens from the moment `day_script::init` runs, which is before the
        // backend has built the tree; a runner that connects during a slow startup (day-piece-crash-reporter
        // reconciling a crash from the previous launch is the reliable way to be slow) can land
        // a step in that window. Answering "retryable" hands it back to the bounded wait, which
        // is exactly the "not there yet" case that machinery exists for; running it anyway would
        // panic inside `with_tree`.
        if !day_core::has_tree() {
            let _ = tx.send(Reply::fail("the app is still starting", true));
            return;
        }
        let _ = tx.send(exec(step, revision));
    });
    match rx.recv_timeout(budget) {
        Ok(reply) => reply,
        Err(_) => {
            abandoned.store(true, Ordering::SeqCst);
            Reply {
                main_thread_stalled: true,
                ..Reply::fail(
                    format!(
                        "main thread did not respond within {:.0}s — raise \
                         DAY_SCRIPT_MAIN_TIMEOUT_SECS if this machine is just slow",
                        budget.as_secs_f64()
                    ),
                    false,
                )
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Step execution (main thread; events go through the normal Day path)
// ---------------------------------------------------------------------------

/// Resolve a Fluent key (+ JSON args) in the current locale: the shared engine for the
/// `key:`-flavored script fields (assert_text, input).
/// Walk the app-menu model for `Action` leaves matching the `menu:` step's target: by
/// exact label, or (when the step used `key:`) by the role's core-catalog key (the
/// injected Preferences item carries an empty label; its role is its identity). `path`
/// filters by ancestor submenu labels (suffix match). Returns `(id, enabled, trail)`.
/// `[shift, primary, alt]` (with `cmd`/`ctrl` accepted for `primary`) → the day mask.
fn parse_modifiers(names: &[String]) -> day_spec::Modifiers {
    let mut m = day_spec::Modifiers::default();
    for n in names {
        match n.to_ascii_lowercase().as_str() {
            "shift" => m.shift = true,
            "primary" | "cmd" | "ctrl" | "meta" => m.primary = true,
            "alt" | "option" => m.alt = true,
            _ => {}
        }
    }
    m
}

fn find_menu_actions(
    items: &[day_spec::MenuItem],
    target_label: &str,
    target_key: Option<&str>,
    target_id: Option<&str>,
    path: &[(String, String)],
) -> Vec<(u64, bool, Vec<String>)> {
    // Mirrors day-pieces' role_catalog_key (docs/menus.md), the stable `day_*` key set.
    fn role_key(role: day_spec::MenuRole) -> &'static str {
        use day_spec::MenuRole as R;
        match role {
            R::Cut => "day_cut",
            R::Copy => "day_copy",
            R::Paste => "day_paste",
            R::SelectAll => "day_select_all",
            R::Undo => "day_undo",
            R::Redo => "day_redo",
            R::Delete => "day_delete",
            R::About => "day_about",
            R::Quit => "day_quit",
            R::Preferences => "day_preferences",
            R::Minimize => "day_minimize",
            R::CloseWindow => "day_close",
            R::Fullscreen => "day_fullscreen",
            R::NewWindow => "day_new_window",
            R::CheckForUpdates => "day_check_for_updates",
        }
    }
    #[allow(clippy::too_many_arguments)]
    fn walk(
        items: &[day_spec::MenuItem],
        trail: &mut Vec<String>,
        target_label: &str,
        target_key: Option<&str>,
        target_id: Option<&str>,
        path: &[(String, String)],
        out: &mut Vec<(u64, bool, Vec<String>)>,
    ) {
        for it in items {
            match it {
                day_spec::MenuItem::Action {
                    id,
                    action,
                    label,
                    enabled,
                    role,
                    ..
                } => {
                    // An `id:` step is an exact address and nothing else may answer it: matching
                    // the label too would let a step that named a missing id quietly hit some
                    // other item whose title happened to read the same.
                    let by_id = target_id.is_some_and(|w| id.as_deref() == Some(w));
                    let by_label =
                        target_id.is_none() && !label.is_empty() && label == target_label;
                    let by_key = target_id.is_none()
                        && target_key.is_some_and(|k| role.is_some_and(|r| role_key(r) == k));
                    let path_ok = path.is_empty()
                        || (path.len() <= trail.len()
                            && trail[trail.len() - path.len()..]
                                .iter()
                                .zip(path)
                                .all(|(seen, want)| seen == &want.0 || seen == &want.1));
                    if (by_id || by_label || by_key) && path_ok {
                        out.push((*action, *enabled, trail.clone()));
                    }
                }
                day_spec::MenuItem::Submenu { label, items, .. } => {
                    trail.push(label.clone());
                    walk(items, trail, target_label, target_key, target_id, path, out);
                    trail.pop();
                }
                day_spec::MenuItem::Separator => {}
            }
        }
    }
    let mut out = Vec::new();
    walk(
        items,
        &mut Vec::new(),
        target_label,
        target_key,
        target_id,
        path,
        &mut out,
    );
    out
}

fn format_key(key: &str, args: Option<BTreeMap<String, serde_json::Value>>) -> String {
    let mut lt = day_localization_ui::tr(key);
    for (name, v) in args.unwrap_or_default() {
        lt = match v {
            serde_json::Value::Number(n) => lt.arg(&name, n.as_f64().unwrap_or(0.0)),
            serde_json::Value::String(s) => lt.arg(&name, s),
            other => lt.arg(&name, other.to_string()),
        };
    }
    lt.format()
}

fn find(id: &str) -> Result<day_core::RNode, Reply> {
    with_tree(|t| t.find_by_id(id)).ok_or_else(|| Reply::fail(format!("no element {id:?}"), true))
}

fn probe(id: &str) -> Result<NodeProbe, Reply> {
    let node = find(id)?;
    with_tree(|t| t.node_probe(node)).ok_or_else(|| Reply::fail("element vanished", true))
}

fn emit(id: &str, ev: day_spec::Event) -> Result<(), Reply> {
    let node = find(id)?;
    day_core::enqueue_event(rnode_to_id(node), ev);
    day_reactive::flush_sync();
    Ok(())
}

fn visible(id: &str) -> Result<(), Reply> {
    let node = find(id)?;
    let frame = with_tree(|t| t.node_frame(node));
    match frame {
        Some(f) if f.size.width > 0.0 && f.size.height > 0.0 => Ok(()),
        _ => Err(Reply::fail(format!("{id:?} has no visible frame"), true)),
    }
}

/// `#rrggbb` as its three channels.
fn parse_hex_color(s: &str) -> Option<[u8; 3]> {
    let hex = s.strip_prefix('#')?;
    if hex.len() != 6 {
        return None;
    }
    let channel = |i: usize| u8::from_str_radix(hex.get(i..i + 2)?, 16).ok();
    Some([channel(0)?, channel(2)?, channel(4)?])
}

fn norm(s: &str) -> String {
    day_localization_ui::strip_isolates(s)
}

/// Hosts that present frames of their own (`day_spec::capture::register_hold`) must have them
/// on screen before a capture checkpoint is requested: a frame that lands after the checkpoint
/// commits is not in the capture, and the fence for this revision does not rearm.
fn hosts_settled() -> Result<(), Reply> {
    if day_spec::capture::holds_settled() {
        Ok(())
    } else {
        Err(Reply {
            capture_pending: true,
            ..Reply::fail("waiting for a host's pending frame", true)
        })
    }
}

fn id_catalog() -> Result<&'static day_script_protocol::IdCatalog, String> {
    static CATALOG: std::sync::OnceLock<Result<day_script_protocol::IdCatalog, String>> =
        std::sync::OnceLock::new();
    CATALOG
        .get_or_init(|| {
            Ok(day_script_protocol::IdCatalog {
                schema_version: 1,
                declarations: day_core::element_id::registry()?
                    .iter()
                    .cloned()
                    .map(|d| day_script_protocol::IdDeclaration {
                        family: d.family,
                        keyed: d.keyed,
                        package: d.package,
                        version: d.version,
                        locations: d.locations,
                    })
                    .collect(),
            })
        })
        .as_ref()
        .map_err(Clone::clone)
}

fn exec(step: Step, revision: u32) -> Reply {
    let evidence_class = step.evidence_class();
    let evidence_id = step.element_references().into_iter().next();
    // An optional absent action succeeds without an interaction. Capture presence before
    // executing, since a successful button can remove itself or close its window.
    let absent_optional_action = matches!(&step,
        Step::Tap { id, if_present: true, .. }
        | Step::Select { id, if_present: true, .. }
        | Step::ContextMenu { id, if_present: true, .. } if find(id).is_err());

    use day_spec::Event;
    use day_spec::present::PresentResult;
    let result: Result<Reply, Reply> = (|| {
        match step {
            Step::IdMounted => Ok(Reply {
                data: Some(serde_json::json!(with_tree(|t| t.mounted_id_families()))),
                ..Reply::ok()
            }),
            Step::IdCatalog => {
                let catalog = id_catalog().map_err(|e| Reply::fail(e, false))?;
                Ok(Reply {
                    data: Some(serde_json::to_value(catalog).unwrap()),
                    ..Reply::ok()
                })
            }
            Step::WaitFor { id, .. } => {
                visible(&id)?;
                Ok(Reply::ok())
            }
            Step::WaitIdle => {
                day_reactive::flush_sync();
                if !with_tree(|t| t.ui_idle()) {
                    return Err(Reply::fail("ui transitions still settling", true));
                }
                Ok(Reply::ok())
            }
            Step::MemoryUsage { fail_if_above } => Ok(memory::sample(fail_if_above)),
            Step::MemoryWatch { .. } => Err(Reply::fail(
                "memory_watch requires a transport connection",
                false,
            )),
            Step::Tap {
                id,
                if_present,
                repeat,
                at,
                modifiers,
            } => {
                // Finding a node is not proof that a user can activate it. In particular,
                // Button's enabled gate silently ignores Pressed while an async operation
                // is finishing. Retry BEFORE dispatch, never replay an accepted action.
                day_reactive::flush_sync();
                if !with_tree(|t| t.ui_idle()) {
                    return Err(Reply::fail("ui transitions still settling", true));
                }
                if if_present && with_tree(|t| t.find_by_id(&id)).is_none() {
                    return Ok(Reply::ok());
                }
                visible(&id)?;
                if !probe(&id)?.enabled {
                    return Err(Reply::fail(format!("{id:?} is disabled"), true));
                }
                // Deliver a button `Pressed` and a gesture `Tap` (at `at`, or the node's local
                // center), so one step exercises buttons (which ignore `Tap`) and
                // shape/`.on_tap` pieces (which ignore `Pressed`) alike; the native
                // recognizers deliver the same `Tap`.
                let node = find(&id)?;
                let point = match at {
                    Some([x, y]) => day_spec::Point::new(x, y),
                    None => with_tree(|t| t.node_frame(node))
                        .map(|f| day_spec::Point::new(f.size.width / 2.0, f.size.height / 2.0))
                        .unwrap_or(day_spec::Point::ZERO),
                };
                // Declared modifiers stand in for held keys while the tap dispatches
                // (`day::modifiers()` answers them), then clear, since a synthetic tap cannot
                // hold a real shift key.
                if !modifiers.is_empty() {
                    day_core::set_modifier_override(Some(parse_modifiers(&modifiers)));
                }
                for _ in 0..repeat.unwrap_or(1).max(1) {
                    day_core::enqueue_event(rnode_to_id(node), Event::Pressed);
                    day_core::enqueue_event(rnode_to_id(node), Event::Tap(point));
                }
                day_reactive::flush_sync();
                day_core::set_modifier_override(None);
                Ok(Reply::ok())
            }
            Step::Key { key, id, modifiers } => {
                // Keys follow focus, so a synthetic one lands where the platform would put it:
                // on the named piece, else on whatever holds focus. With nothing focused there
                // is no target and the step says so, rather than dropping the key silently the
                // way delivering it to the window used to.
                let target = match &id {
                    Some(id) => rnode_to_id(find(id)?),
                    None => match day_core::focused_node() {
                        Some(n) => rnode_to_id(n),
                        None => {
                            return Err(Reply::fail(
                                "nothing has focus — name an `id`, or `focus:` a piece first",
                                true,
                            ));
                        }
                    },
                };
                let m = parse_modifiers(&modifiers);
                let mut mask = 0u8;
                if m.shift {
                    mask |= day_spec::KeyEvent::SHIFT;
                }
                if m.primary {
                    mask |= day_spec::KeyEvent::PRIMARY;
                }
                if m.alt {
                    mask |= day_spec::KeyEvent::ALT;
                }
                day_core::enqueue_event(
                    target,
                    Event::Key(day_spec::KeyEvent {
                        key,
                        modifiers: mask,
                    }),
                );
                day_reactive::flush_sync();
                Ok(Reply::ok())
            }
            Step::Drag {
                id,
                from,
                to,
                steps,
                modifiers,
            } => {
                let node = find(&id)?;
                let (fx, fy) = (from[0], from[1]);
                let (tx, ty) = (to[0], to[1]);
                let n = steps.unwrap_or(4).max(1);
                let emit_drag = |phase, x: f64, y: f64| {
                    day_core::enqueue_event(
                        rnode_to_id(node),
                        Event::Drag {
                            phase,
                            location: day_spec::Point::new(x, y),
                            translation: day_spec::Point::new(x - fx, y - fy),
                        },
                    );
                };
                // Held for the whole gesture rather than one phase: a drag that reads
                // modifiers reads them at `Began`, and the override has to still be in place
                // at `Ended` for a handler that re-reads them there.
                if !modifiers.is_empty() {
                    day_core::set_modifier_override(Some(parse_modifiers(&modifiers)));
                }
                emit_drag(day_spec::DragPhase::Began, fx, fy);
                day_reactive::flush_sync();
                for i in 1..=n {
                    let f = i as f64 / n as f64;
                    emit_drag(
                        day_spec::DragPhase::Changed,
                        fx + (tx - fx) * f,
                        fy + (ty - fy) * f,
                    );
                    day_reactive::flush_sync();
                }
                emit_drag(day_spec::DragPhase::Ended, tx, ty);
                day_reactive::flush_sync();
                day_core::set_modifier_override(None);
                Ok(Reply::ok())
            }
            Step::Hover { id, at, leave } => {
                let node = find(&id)?;
                let location = match at {
                    Some([x, y]) => day_spec::Point::new(x, y),
                    None => {
                        let f = with_tree(|t| t.node_frame(node)).unwrap_or_default();
                        day_spec::Point::new(f.size.width / 2.0, f.size.height / 2.0)
                    }
                };
                let phase = if leave {
                    day_spec::DragPhase::Ended
                } else {
                    day_spec::DragPhase::Began
                };
                day_core::enqueue_event(rnode_to_id(node), Event::Hover { phase, location });
                day_reactive::flush_sync();
                Ok(Reply::ok())
            }
            Step::Pan { id, by, steps } => {
                let node = find(&id)?;
                let f = with_tree(|t| t.node_frame(node)).unwrap_or_default();
                let location = day_spec::Point::new(f.size.width / 2.0, f.size.height / 2.0);
                let n = steps.unwrap_or(4).max(1);
                let emit_pan = |phase, dx: f64, dy: f64| {
                    day_core::enqueue_event(
                        rnode_to_id(node),
                        Event::Pan {
                            phase,
                            delta: day_spec::Point::new(dx, dy),
                            location,
                        },
                    );
                    day_reactive::flush_sync();
                };
                emit_pan(day_spec::DragPhase::Began, 0.0, 0.0);
                // Incremental deltas, as the platforms report them, adding up to `by`.
                for _ in 0..n {
                    emit_pan(
                        day_spec::DragPhase::Changed,
                        by[0] / n as f64,
                        by[1] / n as f64,
                    );
                }
                emit_pan(day_spec::DragPhase::Ended, 0.0, 0.0);
                Ok(Reply::ok())
            }
            Step::Pinch { id, scale, steps } => {
                let node = find(&id)?;
                let f = with_tree(|t| t.node_frame(node)).unwrap_or_default();
                let location = day_spec::Point::new(f.size.width / 2.0, f.size.height / 2.0);
                let n = steps.unwrap_or(4).max(1);
                let emit_pinch = |phase, s: f64| {
                    day_core::enqueue_event(
                        rnode_to_id(node),
                        Event::Pinch {
                            phase,
                            scale: s,
                            location,
                        },
                    );
                    day_reactive::flush_sync();
                };
                emit_pinch(day_spec::DragPhase::Began, 1.0);
                // Cumulative since `Began`, as the platforms report it.
                for i in 1..=n {
                    emit_pinch(
                        day_spec::DragPhase::Changed,
                        1.0 + (scale - 1.0) * i as f64 / n as f64,
                    );
                }
                emit_pinch(day_spec::DragPhase::Ended, scale);
                Ok(Reply::ok())
            }
            Step::Submit { id } => emit(&id, Event::Submitted).map(|()| Reply::ok()),
            Step::Input {
                id,
                text,
                key,
                args,
            } => {
                let value = match key {
                    Some(k) => format_key(&k, args),
                    None => text.unwrap_or_default(),
                };
                // Paint-then-event via the shared synthesizer (day-core): the widget must
                // show the typed text, not only deliver it to the app's signal.
                let node = find(&id)?;
                day_core::synthesize_text(node, value);
                day_reactive::flush_sync();
                Ok(Reply::ok())
            }
            Step::SetValue { id, value } => {
                // Both, for the same reason `tap` sends `Pressed` and `Tap`: a binding follows
                // the live value and anything durable follows the committed one, and a replayed
                // `set_value` is a user who dragged and let go, so it has to look like one.
                emit(&id, Event::ValueChanged(value))?;
                emit(&id, Event::ValueCommitted(value))?;
                Ok(Reply::ok())
            }
            Step::Toggle { id, value } => {
                let target = match value {
                    Some(v) => v,
                    None => !probe(&id)?.flag,
                };
                emit(&id, Event::ToggleChanged(target))?;
                Ok(Reply::ok())
            }
            Step::Activate { id, index } => {
                emit(&id, Event::ListActivated(index))?;
                Ok(Reply::ok())
            }
            Step::Select {
                id,
                index,
                if_present,
            } => {
                if if_present {
                    // Absent only counts once the UI has settled: a control still being
                    // built is one to wait for, not one to skip (the same rule as `tap`).
                    day_reactive::flush_sync();
                    if !with_tree(|t| t.ui_idle()) {
                        return Err(Reply::fail("ui transitions still settling", true));
                    }
                    if with_tree(|t| t.find_by_id(&id)).is_none() {
                        return Ok(Reply::ok());
                    }
                }
                let node = find(&id)?;
                let state = probe(&id)?;
                if with_tree(|t| t.node_kind(node)) == Some(day_spec::kinds::PICKER)
                    && (index < 0 || index as usize >= state.options.len())
                {
                    return Err(Reply::fail(
                        format!(
                            "select {id:?}: index {index} is out of range for {} options",
                            state.options.len()
                        ),
                        false,
                    ));
                }
                emit(&id, Event::SelectionChanged(index))?;
                Ok(Reply::ok())
            }
            Step::Reorder { id, from, to } => {
                let node = find(&id)?;
                match day_core::list_try_reorder(node, from, to) {
                    Ok(_) => Ok(Reply::ok()),
                    // Not retryable: a guard denial or a non-reorderable list won't change by
                    // waiting; surface it to the runner immediately.
                    Err(e) => Err(Reply::fail(
                        format!("reorder {id:?} {from}->{to}: {e}"),
                        false,
                    )),
                }
            }
            Step::Undo => drive_undo(false),
            Step::Redo => drive_undo(true),
            Step::Expand { id, row, expanded } => {
                let node = find(&id)?;
                let driver = day_core::tree_driver(node).ok_or_else(|| {
                    Reply::fail(format!("expand {id:?}: no tree at this node"), false)
                })?;
                let token = (driver.resolve_row)(&row).ok_or_else(|| {
                    // Retryable: the row may appear after a pending reload (or the tree may
                    // not carry `.row_id`s at all, which the timeout will surface).
                    Reply::fail(format!("expand {id:?}: no row {row:?}"), true)
                })?;
                emit(&id, Event::TreeExpanded { token, expanded })?;
                Ok(Reply::ok())
            }
            Step::TreeMove {
                id,
                row,
                parent,
                index,
            } => {
                let node = find(&id)?;
                let driver = day_core::tree_driver(node).ok_or_else(|| {
                    Reply::fail(format!("tree_move {id:?}: no tree at this node"), false)
                })?;
                let token = (driver.resolve_row)(&row).ok_or_else(|| {
                    Reply::fail(format!("tree_move {id:?}: no row {row:?}"), true)
                })?;
                let parent_tok = match &parent {
                    Some(p) => Some((driver.resolve_row)(p).ok_or_else(|| {
                        Reply::fail(format!("tree_move {id:?}: no parent row {p:?}"), true)
                    })?),
                    None => None,
                };
                match day_core::tree_try_move(node, token, parent_tok, index) {
                    Ok(()) => Ok(Reply::ok()),
                    // Not retryable: a guard denial or an immovable tree won't change by waiting.
                    Err(e) => Err(Reply::fail(format!("tree_move {id:?} {row:?}: {e}"), false)),
                }
            }
            Step::DeleteRow { id, row } => {
                let node = find(&id)?;
                match day_core::list_try_delete(node, row) {
                    Ok(()) => Ok(Reply::ok()),
                    // Not retryable: a guard refusal or a non-deletable list won't change by
                    // waiting; surface it to the runner immediately.
                    Err(e) => Err(Reply::fail(format!("delete_row {id:?} {row}: {e}"), false)),
                }
            }
            Step::SwipeRow {
                id,
                row,
                edge,
                action,
                label,
                key,
            } => {
                let node = find(&id)?;
                let edge = match edge.as_deref() {
                    None | Some("trailing") => day_spec::SwipeEdge::Trailing,
                    Some("leading") => day_spec::SwipeEdge::Leading,
                    Some(other) => {
                        return Err(Reply::fail(
                            format!("swipe_row {id:?}: edge {other:?} (leading|trailing)"),
                            false,
                        ));
                    }
                };
                let expected = match (&label, &key) {
                    (Some(l), _) => Some(l.clone()),
                    (None, Some(k)) => Some(format_key(k, None)),
                    (None, None) => None,
                };
                // The pin is checked before the press (docs/list.md): a mismatched offer
                // refuses the activation rather than flipping state the script did not mean
                // to flip, which is how one aborted run would poison every later one.
                match day_core::list_try_swipe(node, row, edge, action, expected.as_deref()) {
                    Ok(_) => Ok(Reply::ok()),
                    // Not retryable: the offer was pulled live; a list without swipe offers, an
                    // out-of-offer action, or a different button at this position won't
                    // change by waiting. Surface it to the runner immediately.
                    Err(e) => Err(Reply::fail(format!("swipe_row {id:?} {row}: {e}"), false)),
                }
            }
            Step::WebEval {
                id,
                script,
                contains,
                text,
                ..
            } => {
                // The eval resolves at a later event drain, and a step handler cannot block
                // the pump it needs, so the step is a retryable poll: the first pass starts
                // the evaluation, retries within the runner's implicit wait collect it, and
                // an assertion mismatch discards the result so the retry re-evaluates (a page
                // mid-load settles into passing). Keyed by (id, script): the runner resends
                // the identical step on retry, and that pair is what identifies the request.
                use std::cell::RefCell;
                use std::rc::Rc;
                type EvalCell = Rc<RefCell<Option<Result<String, String>>>>;
                thread_local! {
                    static WEB_EVALS: RefCell<
                        std::collections::HashMap<(String, String), (u32, EvalCell)>,
                    > = RefCell::new(std::collections::HashMap::new());
                }
                let node = find(&id)?;
                let key = (id.clone(), script.clone());
                let pending = WEB_EVALS.with(|m| m.borrow().get(&key).map(|(_, c)| c.clone()));
                let Some(cell) = pending else {
                    let cell: EvalCell = Rc::new(RefCell::new(None));
                    let done = {
                        let cell = cell.clone();
                        Box::new(move |r: Result<String, String>| *cell.borrow_mut() = Some(r))
                    };
                    if !day_core::piece_operation(node, "day.webview.eval", &script, done) {
                        return Err(Reply::fail(
                            format!(
                                "web_eval {id:?}: not a web view (or no webview piece registered an evaluator)"
                            ),
                            false,
                        ));
                    }
                    WEB_EVALS.with(|m| m.borrow_mut().insert(key, (0, cell)));
                    return Err(Reply::fail(
                        format!("web_eval {id:?}: awaiting the engine"),
                        true,
                    ));
                };
                let Some(result) = cell.borrow_mut().take() else {
                    // Still pending. A reply that never comes (a torn-down view drops its
                    // callback) must not wedge every later identical step: after enough
                    // polls, forget the request so the next retry starts fresh.
                    let stale = WEB_EVALS.with(|m| {
                        let mut m = m.borrow_mut();
                        match m.get_mut(&key) {
                            Some((polls, _)) => {
                                *polls += 1;
                                *polls > 25
                            }
                            None => false,
                        }
                    });
                    if stale {
                        WEB_EVALS.with(|m| m.borrow_mut().remove(&key));
                    }
                    return Err(Reply::fail(
                        format!("web_eval {id:?}: awaiting the engine"),
                        true,
                    ));
                };
                WEB_EVALS.with(|m| m.borrow_mut().remove(&key));
                match result {
                    // Retryable: a throw from a page still loading (`document` half-built)
                    // resolves with time; a permanent error just spends the wait.
                    Err(e) => Err(Reply::fail(format!("web_eval {id:?}: {e}"), true)),
                    Ok(json) => {
                        // A string value compares as itself; anything else as its JSON text.
                        let value = serde_json::from_str::<serde_json::Value>(&json)
                            .ok()
                            .and_then(|v| v.as_str().map(str::to_string))
                            .unwrap_or(json);
                        let failed = match (&contains, &text) {
                            (Some(c), _) if !value.contains(c.as_str()) => {
                                Some(format!("result {value:?} does not contain {c:?}"))
                            }
                            (_, Some(t)) if value != *t => {
                                Some(format!("result {value:?}, expected {t:?}"))
                            }
                            _ => None,
                        };
                        match failed {
                            // Retryable: the page may still be settling; the retry
                            // re-evaluates against its current state.
                            Some(why) => Err(Reply::fail(format!("web_eval {id:?}: {why}"), true)),
                            None => Ok(Reply::ok()),
                        }
                    }
                }
            }
            Step::ContextMenu {
                id,
                if_present,
                item_id,
                item,
                key,
                path,
            } => {
                if if_present {
                    // The `tap` rule: absent counts only once the UI has settled.
                    day_reactive::flush_sync();
                    if !with_tree(|t| t.ui_idle()) {
                        return Err(Reply::fail("ui transitions still settling", true));
                    }
                    if with_tree(|t| t.find_by_id(&id)).is_none() {
                        return Ok(Reply::ok());
                    }
                }
                let node = find(&id)?;
                let menu = with_tree(|t| t.context_menu_of(node)).ok_or_else(|| {
                    Reply::fail(
                        format!("context_menu {id:?}: the element has no menu"),
                        true,
                    )
                })?;
                // Asked outside the tree borrow, at the origin, as a native summon asks it: a
                // provider may select what it was summoned over and flush.
                let items = menu(day_spec::Point::ZERO);
                let target_label = match (&item_id, &item, &key) {
                    (Some(_), _, _) => String::new(),
                    (None, Some(l), _) => l.clone(),
                    (None, None, Some(k)) => format_key(k, None),
                    (None, None, None) => {
                        return Err(Reply::fail(
                            "context_menu: needs `item_id:`, `item:` or `key:`",
                            false,
                        ));
                    }
                };
                let path: Vec<(String, String)> = path
                    .unwrap_or_default()
                    .into_iter()
                    .map(|p| {
                        let resolved = format_key(&p, None);
                        (p, resolved)
                    })
                    .collect();
                let matches = find_menu_actions(
                    &items,
                    &target_label,
                    key.as_deref(),
                    item_id.as_deref(),
                    &path,
                );
                let what = match &item_id {
                    Some(want) => format!("id {want:?}"),
                    None => format!("{target_label:?}"),
                };
                match matches.as_slice() {
                    [] => Err(Reply::fail(
                        format!("context_menu {id:?}: no item {what}"),
                        true,
                    )),
                    [(action, enabled, _)] => {
                        if *action == 0 {
                            Err(Reply::fail(
                                format!(
                                    "context_menu {id:?}: {what} runs a native command (no day \
                                     action)"
                                ),
                                false,
                            ))
                        } else if !enabled {
                            Err(Reply::fail(
                                format!("context_menu {id:?}: {what} is disabled"),
                                false,
                            ))
                        } else {
                            day_core::dispatch_menu_action(*action);
                            day_reactive::flush_sync();
                            Ok(Reply::ok())
                        }
                    }
                    _ => Err(Reply::fail(
                        format!("context_menu {id:?}: {what} is ambiguous; add a path"),
                        false,
                    )),
                }
            }
            Step::Menu {
                id,
                item,
                key,
                path,
            } => {
                let target_label = match (&id, &item, &key) {
                    (Some(_), _, _) => String::new(),
                    (None, Some(l), _) => l.clone(),
                    (None, None, Some(k)) => format_key(k, None),
                    (None, None, None) => {
                        return Err(Reply::fail("menu: needs `id:`, `item:` or `key:`", false));
                    }
                };
                // Each `path:` entry matches an ancestor submenu by its literal label OR by
                // its Fluent key resolved in the run's locale, so `path: [menu_file]` works
                // wherever `key: menu_file` does.
                let path: Vec<(String, String)> = path
                    .unwrap_or_default()
                    .into_iter()
                    .map(|p| {
                        let resolved = format_key(&p, None);
                        (p, resolved)
                    })
                    .collect();
                let matches = find_menu_actions(
                    &day_core::menu::app_menu_model(),
                    &target_label,
                    key.as_deref(),
                    id.as_deref(),
                    &path,
                );
                // The auto items (docs/windows.md) exist even when the app never installed a
                // menu (the backend's default menu carries them): resolve their keys straight
                // to the registered dispatch actions when the model has no entry.
                let auto_id = match (matches.is_empty(), key.as_deref()) {
                    (true, Some("day_preferences")) => {
                        Some(day_core::windows::preferences_action_id())
                    }
                    (true, Some("day_new_window")) => {
                        Some(day_core::windows::new_window_action_id())
                    }
                    (true, Some("day_about")) => Some(day_core::windows::about_action_id()),
                    (true, Some("day_check_for_updates")) => {
                        Some(day_core::windows::check_for_updates_action_id())
                    }
                    _ => None,
                };
                if let Some(id) = auto_id
                    && id != 0
                {
                    day_core::dispatch_menu_action(id);
                    day_reactive::flush_sync();
                    return Ok(Reply::ok());
                }
                // Name the item back the way the step named it, so a failure says which spelling
                // it was actually asked to find.
                let what = match &id {
                    Some(want) => format!("id {want:?}"),
                    None => format!("{target_label:?}"),
                };
                match matches.as_slice() {
                    [] => Err(Reply::fail(
                        // Retryable: the (reactive) app menu may not have installed yet.
                        format!("menu: no item {what}"),
                        true,
                    )),
                    [(action, enabled, _)] => {
                        if *action == 0 {
                            Err(Reply::fail(
                                format!(
                                    "menu: {what} runs a native selector (no day action) — not \
                                     invokable from dayscript"
                                ),
                                false,
                            ))
                        } else if !enabled {
                            Err(Reply::fail(format!("menu: {what} is disabled"), false))
                        } else {
                            day_core::dispatch_menu_action(*action);
                            day_reactive::flush_sync();
                            Ok(Reply::ok())
                        }
                    }
                    many => Err(Reply::fail(
                        format!(
                            "menu: {what} is ambiguous — disambiguate with path: {:?}",
                            many.iter()
                                .map(|(_, _, p)| p.join(" ▸ "))
                                .collect::<Vec<_>>()
                        ),
                        false,
                    )),
                }
            }
            Step::Toolbar {
                item,
                text,
                key,
                args,
                on,
                index,
                submit,
            } => {
                // `key` resolves through the run's locale, like `input`'s does; `text` stays a
                // literal. Resolved before the item lookup so a bad key fails as a bad key.
                let text = match key {
                    Some(k) => Some(format_key(&k, args)),
                    None => text,
                };
                // Every live chrome's items (docs/toolbars.md): the window's own, plus whichever
                // pages are showing. One bar per window at a time, so an id that appears twice is
                // an app bug rather than an ambiguity to resolve here.
                let model = day_core::toolbar::toolbar_model();
                let Some(found) = model.iter().find(|i| i.id == item) else {
                    // The reserved search id names one field wherever the platform put it
                    // (docs/search.md): on the bar it is the item found above; inline, on a
                    // phone's navigation surface, there is no item and the host answers for it.
                    // The text goes in as the native field would send it, so the same query and
                    // the same outbound patch (the field showing the text) follow on both.
                    if item == day_spec::SEARCH_ITEM_ID
                        && let Some(host) = day_core::inline_search_host()
                    {
                        let Some(t) = text else {
                            return Err(Reply::fail(
                                "toolbar: day::search rides the navigation surface here, which takes text (or key) only",
                                false,
                            ));
                        };
                        day_core::enqueue_event(rnode_to_id(host), Event::SearchChanged(t.clone()));
                        if submit {
                            day_core::enqueue_event(rnode_to_id(host), Event::SearchSubmitted(t));
                        }
                        day_reactive::flush_sync();
                        return Ok(Reply::ok());
                    }
                    // Retryable: a reactive toolbar may not have installed yet.
                    return Err(Reply::fail(format!("toolbar: no item {item:?}"), true));
                };
                if !found.enabled {
                    return Err(Reply::fail(format!("toolbar: {item:?} is disabled"), false));
                }
                // The sidebar affordance a host supplies for itself is an ordinary button
                // whose action carries its host, so it is pressed like any other: the same
                // path a click takes (docs/toolbars.md).
                if found.action == 0 {
                    return Err(Reply::fail(
                        format!("toolbar: {item:?} has no command"),
                        false,
                    ));
                }
                // A toggle's action lives in the value registry, not the menu-action one, so a
                // bare `toolbar: { item }` on one used to dispatch into the wrong registry and
                // do nothing at all: the step passed, the app did not move, and the script was
                // left asserting against a state it never reached. Say what is missing instead.
                // A segmented item takes an index; nothing else in the vocabulary does, and a
                // bare press on one would have no choice to make.
                if let day_spec::ToolbarItemKind::Segmented { segments, .. } = &found.kind {
                    let Some(i) = index else {
                        return Err(Reply::fail(
                            format!("toolbar: {item:?} is segmented — say `index: <n>`"),
                            false,
                        ));
                    };
                    if i >= segments.len() {
                        return Err(Reply::fail(
                            format!(
                                "toolbar: {item:?} has {} segments, asked for {i}",
                                segments.len()
                            ),
                            false,
                        ));
                    }
                    day_core::toolbar::dispatch_toolbar_value(
                        found.action,
                        &day_spec::ToolbarValue::Selected(i),
                    );
                    day_reactive::flush_sync();
                    return Ok(Reply::ok());
                }
                if matches!(found.kind, day_spec::ToolbarItemKind::Toggle { .. })
                    && on.is_none()
                    && text.is_none()
                {
                    return Err(Reply::fail(
                        format!("toolbar: {item:?} is a toggle — say `on: true` or `on: false`"),
                        false,
                    ));
                }
                if submit && text.is_none() {
                    return Err(Reply::fail(
                        format!("toolbar: submitting {item:?} needs `text:` (or `key:`)"),
                        false,
                    ));
                }
                match (text, on) {
                    (Some(t), _) => {
                        day_core::toolbar::synthesize_toolbar_value(
                            found.action,
                            &day_spec::ToolbarValue::Text(t.clone()),
                        );
                        if submit {
                            day_reactive::flush_sync();
                            day_core::toolbar::dispatch_toolbar_value(
                                found.action,
                                &day_spec::ToolbarValue::Submit(t),
                            );
                        }
                    }
                    (None, Some(v)) => day_core::toolbar::dispatch_toolbar_value(
                        found.action,
                        &day_spec::ToolbarValue::On(v),
                    ),
                    (None, None) => day_core::dispatch_menu_action(found.action),
                }
                day_reactive::flush_sync();
                Ok(Reply::ok())
            }
            Step::AssertVisible { id } => {
                visible(&id)?;
                Ok(Reply::ok())
            }
            Step::AssertHidden { id } => {
                let Some(node) = with_tree(|t| t.find_by_id(&id)) else {
                    return Ok(Reply::ok());
                };
                let empty = with_tree(|t| t.node_frame(node))
                    .is_none_or(|f| f.size.width <= 0.0 || f.size.height <= 0.0);
                let native = with_tree(|t| t.read_native(node)).unwrap_or_default();
                if empty || (native.found && native.visible == Some(false)) {
                    Ok(Reply::ok())
                } else {
                    Err(Reply::fail(format!("element {id:?} is shown"), true))
                }
            }
            Step::AssertMissing { id } => match with_tree(|t| t.find_by_id(&id)) {
                Some(_) => Err(Reply::fail(format!("element {id:?} is present"), true)),
                None => Ok(Reply::ok()),
            },
            Step::AssertText {
                id,
                text,
                key,
                args,
                ..
            } => {
                let actual = norm(&probe(&id)?.text);
                let expected = if let Some(k) = key {
                    norm(&format_key(&k, args))
                } else {
                    norm(&text.unwrap_or_default())
                };
                if actual == expected {
                    Ok(Reply::ok())
                } else {
                    Err(Reply::fail(
                        format!("{id:?}: expected {expected:?}, found {actual:?}"),
                        true,
                    ))
                }
            }
            Step::AssertNoPlaceholders { allow } => {
                let unexpected: Vec<&str> = day_spec::placeholder::seen()
                    .into_iter()
                    .filter(|k| !allow.iter().any(|a| a == k))
                    .collect();
                if unexpected.is_empty() {
                    Ok(Reply::ok())
                } else {
                    Err(Reply::fail(
                        format!(
                            "rendered a placeholder for {} — no renderer on this backend. Enable \
                             the piece's feature for this toolkit, or add the kind to `allow:` if \
                             the gap is intended.",
                            unexpected.join(", ")
                        ),
                        true,
                    ))
                }
            }
            Step::AssertValue { id, value } => {
                let p = probe(&id)?;
                let ok = match &value {
                    serde_json::Value::Bool(b) => p.flag == *b,
                    serde_json::Value::Number(n) => {
                        (p.value - n.as_f64().unwrap_or(f64::NAN)).abs() < 0.5
                    }
                    serde_json::Value::String(s) => norm(&p.text) == norm(s),
                    _ => false,
                };
                if ok {
                    Ok(Reply::ok())
                } else {
                    Err(Reply::fail(
                        format!(
                            "{id:?}: expected {value}, probe text={:?} value={} flag={}",
                            p.text, p.value, p.flag
                        ),
                        true,
                    ))
                }
            }
            Step::AssertAnnounced { text } => {
                let said = day_core::conformance::announcements();
                if said.iter().any(|s| norm(s) == norm(&text)) {
                    Ok(Reply::ok())
                } else {
                    Err(Reply::fail(
                        format!("{text:?} was not announced (announced: {said:?})"),
                        true,
                    ))
                }
            }
            Step::AssertOpenedUrl { url } => {
                let opened = day_core::conformance::opened_urls();
                if opened.contains(&url) {
                    Ok(Reply::ok())
                } else {
                    Err(Reply::fail(
                        format!("{url:?} was not opened (opened: {opened:?})"),
                        true,
                    ))
                }
            }
            Step::AssertFrame {
                id,
                width,
                height,
                x,
                y,
                relative_to,
                tolerance,
            } => {
                let tol = tolerance.unwrap_or(1.0);
                let node = find(&id)?;
                let day = with_tree(|t| t.node_frame(node))
                    .ok_or_else(|| Reply::fail(format!("{id:?} has no frame"), true))?;
                let native = with_tree(|t| t.read_native(node)).and_then(|n| n.frame);
                let (base_day, base_native) = match &relative_to {
                    Some(other) => {
                        let o = find(other)?;
                        let f = with_tree(|t| t.node_frame(o))
                            .ok_or_else(|| Reply::fail(format!("{other:?} has no frame"), true))?;
                        let n = with_tree(|t| t.read_native(o)).and_then(|n| n.frame);
                        (f.origin, n.map(|r| r.origin))
                    }
                    None => (day_spec::Point::ZERO, Some(day_spec::Point::ZERO)),
                };
                let mut fails = Vec::new();
                let mut check = |source: &str, f: day_spec::Rect, base: day_spec::Point| {
                    let got = [
                        ("width", f.size.width, width),
                        ("height", f.size.height, height),
                        ("x", f.origin.x - base.x, x),
                        ("y", f.origin.y - base.y, y),
                    ];
                    for (name, value, want) in got {
                        if let Some(w) = want
                            && (value - w).abs() > tol
                        {
                            fails.push(format!("{source} {name} {value:.1} ≠ {w}"));
                        }
                    }
                };
                check("Day", day, base_day);
                let unread = match (native, base_native) {
                    (Some(f), Some(base)) => {
                        check("native", f, base);
                        false
                    }
                    _ => true,
                };
                if !fails.is_empty() {
                    return Err(Reply::fail(format!("{id:?}: {}", fails.join("; ")), true));
                }
                Ok(Reply {
                    data: unread.then(|| serde_json::json!({ "unread": ["frame"] })),
                    ..Reply::ok()
                })
            }
            Step::SamplePixel {
                id,
                x,
                y,
                color,
                tolerance,
            } => {
                let want = parse_hex_color(&color).ok_or_else(|| {
                    Reply::fail(format!("sample_pixel: {color:?} is not #rrggbb"), false)
                })?;
                if day_core::capability(day_spec::Cap::Snapshot) == day_spec::Support::Unsupported {
                    return Ok(Reply {
                        data: Some(serde_json::json!({ "unread": ["pixel"] })),
                        ..Reply::ok()
                    });
                }
                day_reactive::flush_sync();
                if !with_tree(|t| t.ui_idle()) {
                    return Err(Reply::fail("ui transitions still settling", true));
                }
                hosts_settled()?;
                let readiness = with_tree(|t| t.prepare_snapshot(None, revision))
                    .map_err(|e| Reply::fail(format!("sample_pixel readiness: {e}"), false))?;
                if readiness == day_spec::capture::Readiness::Pending {
                    return Err(Reply {
                        capture_pending: true,
                        ..Reply::fail("waiting for a render checkpoint", true)
                    });
                }
                let node = find(&id)?;
                let frame = with_tree(|t| t.node_frame(node))
                    .ok_or_else(|| Reply::fail(format!("{id:?} has no frame"), true))?;
                let window = with_tree(|t| t.node_frame(t.root_node()))
                    .ok_or_else(|| Reply::fail("the window has no frame", true))?;
                let bytes = with_tree(|t| t.snapshot())
                    .map_err(|e| Reply::fail(format!("sample_pixel capture: {e}"), true))?;
                let origin = with_tree(|t| t.snapshot_origin());
                // A capture this reader cannot read (the mock's placeholder bytes) is a gap
                // to record, like a toolkit with no capture, not a wrong color.
                let Ok(img) = png::decode(&bytes) else {
                    return Ok(Reply {
                        data: Some(serde_json::json!({ "unread": ["pixel"] })),
                        ..Reply::ok()
                    });
                };
                // The capture is the window's content at the screen's scale. Where the toolkit
                // says where Day's root sits in it (Android's edge-to-edge content, with bars
                // above and below), that is the offset, and the scale comes from the screen
                // width the capture spans. Otherwise the capture is measured across Day's own
                // width, and rows beyond Day's content are window area above it (AppKit's
                // full-size content view under a transparent title bar).
                let (scale, left, above) = match origin {
                    Some(o) => (
                        img.width as f64 / (window.size.width + 2.0 * o.x).max(1.0),
                        o.x,
                        o.y,
                    ),
                    None => {
                        let scale = img.width as f64 / window.size.width.max(1.0);
                        let above = (img.height as f64 / scale - window.size.height).max(0.0);
                        (scale, 0.0, above)
                    }
                };
                let px = ((left + frame.origin.x - window.origin.x + x * frame.size.width) * scale)
                    .floor()
                    .max(0.0) as usize;
                let py = ((above + frame.origin.y - window.origin.y + y * frame.size.height)
                    * scale)
                    .floor()
                    .max(0.0) as usize;
                let got = img.pixel(px, py).ok_or_else(|| {
                    Reply::fail(
                        format!("{id:?}: ({px}, {py}) is outside the capture"),
                        false,
                    )
                })?;
                let tol = tolerance.unwrap_or(64);
                let near = (0..3).all(|i| got[i].abs_diff(want[i]) <= tol);
                if near {
                    Ok(Reply::ok())
                } else {
                    Err(Reply::fail(
                        format!(
                            "{id:?} at ({x}, {y}): #{:02x}{:02x}{:02x} ≠ {color}",
                            got[0], got[1], got[2]
                        ),
                        true,
                    ))
                }
            }
            Step::AssertNative {
                id,
                text,
                number,
                checked,
                enabled,
                visible,
            } => {
                let node = find(&id)?;
                let native = with_tree(|t| t.read_native(node)).unwrap_or_default();
                if let Some(want) = enabled
                    && probe(&id)?.enabled != want
                {
                    return Err(Reply::fail(
                        format!("{id:?}: Day has enabled={}, expected {want}", !want),
                        true,
                    ));
                }
                let mut unread = Vec::new();
                let mut fails = Vec::new();
                let mut check = |field: &str,
                                 got: Option<String>,
                                 want: Option<String>,
                                 eq: bool| match (got, want) {
                    (_, None) => {}
                    (None, Some(_)) => unread.push(field.to_owned()),
                    (Some(g), Some(w)) if !eq => {
                        fails.push(format!("native {field} {g} ≠ expected {w}"))
                    }
                    _ => {}
                };
                let text_eq =
                    matches!((&native.text, &text), (Some(g), Some(w)) if norm(g) == norm(w));
                check(
                    "text",
                    native.text.as_ref().map(|t| format!("{t:?}")),
                    text.as_ref().map(|t| format!("{t:?}")),
                    text_eq,
                );
                let number_eq = matches!((native.number, number), (Some(g), Some(w)) if (g - w).abs() <= 1e-3 * w.abs().max(1.0));
                check(
                    "number",
                    native.number.map(|n| n.to_string()),
                    number.map(|n| n.to_string()),
                    number_eq,
                );
                check(
                    "checked",
                    native.checked.map(|b| b.to_string()),
                    checked.map(|b| b.to_string()),
                    native.checked == checked,
                );
                check(
                    "enabled",
                    native.enabled.map(|b| b.to_string()),
                    enabled.map(|b| b.to_string()),
                    native.enabled == enabled,
                );
                check(
                    "visible",
                    native.visible.map(|b| b.to_string()),
                    visible.map(|b| b.to_string()),
                    native.visible == visible,
                );
                if !fails.is_empty() {
                    return Err(Reply::fail(format!("{id:?}: {}", fails.join("; ")), true));
                }
                Ok(Reply {
                    data: (!unread.is_empty()).then(|| serde_json::json!({ "unread": unread })),
                    ..Reply::ok()
                })
            }
            Step::ScrollTo { id, edge, x, y } => {
                let node = find(&id)?;
                let target = match (edge.as_deref(), x, y) {
                    (Some("top"), _, _) => day_core::ScrollTarget::Top,
                    (Some("bottom"), _, _) => day_core::ScrollTarget::Bottom,
                    (Some("leading"), _, _) => day_core::ScrollTarget::Leading,
                    (Some("trailing"), _, _) => day_core::ScrollTarget::Trailing,
                    (Some(other), _, _) => {
                        return Err(Reply::fail(
                            format!(
                                "scroll_to: unknown edge {other:?} (top|bottom|leading|trailing)"
                            ),
                            false,
                        ));
                    }
                    (None, None, None) => {
                        // Reveal the element in its nearest enclosing scroll.
                        let ok = with_tree(|t| t.scroll_reveal(node, false));
                        if !ok {
                            return Err(Reply::fail(
                                format!("scroll_to: {id:?} has no enclosing scroll"),
                                true,
                            ));
                        }
                        day_reactive::flush_sync();
                        return Ok(Reply::ok());
                    }
                    (None, x, y) => day_core::ScrollTarget::Offset(day_spec::Point::new(
                        x.unwrap_or(0.0),
                        y.unwrap_or(0.0),
                    )),
                };
                let ok = with_tree(|t| t.scroll_to_target(node, &target, false));
                if !ok {
                    return Err(Reply::fail(
                        format!("scroll_to: {id:?} does not support this scroll target"),
                        true,
                    ));
                }
                day_reactive::flush_sync();
                Ok(Reply::ok())
            }
            Step::Focus { id, focused } => {
                let node = find(&id)?;
                with_tree(|t| t.focus_node(node, focused.unwrap_or(true)));
                day_reactive::flush_sync();
                Ok(Reply::ok())
            }
            Step::AssertFocused { id, focused } => {
                let want = focused.unwrap_or(true);
                let got = probe(&id)?.focused;
                if got == want {
                    Ok(Reply::ok())
                } else {
                    Err(Reply::fail(
                        format!("{id:?}: expected focused={want}, found focused={got}"),
                        true,
                    ))
                }
            }
            Step::CloseWindow { window } => {
                let handle = match &window {
                    Some(key) => day_core::window_by_key(key),
                    None => day_core::initial_window(),
                };
                if let Some(handle) = handle {
                    handle.close();
                }
                day_reactive::flush_sync();
                Ok(Reply::ok())
            }
            Step::Screenshot {
                window, in_process, ..
            } => {
                day_reactive::flush_sync();
                // Wait (retryable, bounded by the step timeout) for native transitions to
                // settle so the capture never shows a half-dismissed dialog or mid-push page.
                if !with_tree(|t| t.ui_idle()) {
                    return Err(Reply::fail("ui transitions still settling", true));
                }
                hosts_settled()?;
                let root = match window.as_deref() {
                    Some(key) => Some(
                        day_core::windows::window_root_by_key(key)
                            .ok_or_else(|| Reply::fail(format!("no window {key:?}"), true))?,
                    ),
                    None => None,
                };
                let readiness = with_tree(|t| t.prepare_snapshot(root, revision))
                    .map_err(|e| Reply::fail(format!("screenshot readiness: {e}"), false))?;
                if readiness == day_spec::capture::Readiness::Pending {
                    return Err(Reply {
                        capture_pending: true,
                        ..Reply::fail("waiting for screenshot render checkpoint", true)
                    });
                }
                let capture_revision =
                    (readiness == day_spec::capture::Readiness::Ready).then_some(revision);
                if !in_process {
                    return Ok(Reply {
                        capture_revision,
                        ..Reply::ok()
                    });
                }
                let png = match window.as_deref() {
                    Some(key) => match day_core::windows::window_root_by_key(key) {
                        Some(root) => with_tree(|t| t.snapshot_of(root)),
                        // Retryable: the window may still be opening (a Pending native
                        // creation, or the opening tap's turn not yet drained).
                        None => return Err(Reply::fail(format!("no window {key:?}"), true)),
                    },
                    None => with_tree(|t| t.snapshot()),
                };
                match png {
                    Ok(bytes) => {
                        SNAPSHOT_MISSES.store(0, Ordering::Relaxed);
                        SNAPSHOT_WORKS.store(true, Ordering::Relaxed);
                        Ok(Reply {
                            ok: true,
                            png_base64: Some(b64encode(&bytes)),
                            capture_revision: Some(revision),
                            ..Default::default()
                        })
                    }
                    // A backend also fails a snapshot it cannot take YET: a GTK window has no
                    // render node until its first frame, and a large window (the 1280x800
                    // capture size) is still laying out when a script's opening `screenshot`
                    // arrives. Answering "unsupported" there dropped a run's first capture, so
                    // the miss is retryable, a bounded number of times. A backend that has
                    // never produced a snapshot pays that wait once and is then believed.
                    Err(_)
                        if (SNAPSHOT_WORKS.load(Ordering::Relaxed)
                            || !SNAPSHOT_NEVER.load(Ordering::Relaxed))
                            && SNAPSHOT_MISSES.fetch_add(1, Ordering::Relaxed)
                                < SNAPSHOT_RETRIES =>
                    {
                        Err(Reply::fail("the window has nothing to capture yet", true))
                    }
                    Err(_) => {
                        SNAPSHOT_MISSES.store(0, Ordering::Relaxed);
                        if !SNAPSHOT_WORKS.load(Ordering::Relaxed) {
                            SNAPSHOT_NEVER.store(true, Ordering::Relaxed);
                        }
                        Ok(Reply {
                            ok: true,
                            screenshot_unsupported: true,
                            ..Default::default()
                        })
                    }
                }
            }
            Step::Pause { secs } => {
                // Pausing the main thread would freeze the UI; the runner sleeps instead.
                let _ = secs;
                Ok(Reply::ok())
            }
            Step::ExpectExit { within } => {
                // Runner-side (day-cli watches for the connection to drop); the engine only reaches
                // this arm if the step was somehow delivered; treat it as a no-op success.
                let _ = within;
                Ok(Reply::ok())
            }
            Step::SizeClass { width, height } => {
                if width == "auto" {
                    day_core::restore_reported_size_class();
                    day_reactive::flush_sync();
                    return Ok(Reply::ok());
                }
                let width = parse_width_class(&width).ok_or_else(|| {
                    Reply::fail(
                        format!(
                            "size_class: unknown width {width:?} \
                             (auto|compact|medium|expanded|large|extra-large)"
                        ),
                        false,
                    )
                })?;
                let height = match height.as_deref() {
                    None => day_spec::HeightClass::Expanded,
                    Some(h) => parse_height_class(h).ok_or_else(|| {
                        Reply::fail(
                            format!("size_class: unknown height {h:?} (compact|medium|expanded)"),
                            false,
                        )
                    })?,
                };
                day_core::override_size_class(day_spec::SizeClass { width, height });
                // Settle the re-present before the next step looks: the class write schedules a
                // binding, and the backend's re-home runs inside it.
                day_reactive::flush_sync();
                Ok(Reply::ok())
            }
            Step::Resize {
                width,
                height,
                restore,
            } => {
                // The runner has already asked the platform to resize; this half waits for the
                // app to have seen it. Everything downstream (the re-present, a piece rebuilding
                // off `size_class()`) rides the report, so acknowledging before it landed would
                // hand the next step the old layout.
                if !with_tree(|t| t.ui_idle()) {
                    return Err(Reply::fail("ui transitions still settling", true));
                }
                // Real geometry ends a class an earlier `size_class:` step forced.
                day_core::restore_reported_size_class();
                day_reactive::flush_sync();
                let (Some(w), Some(h)) = (width, height) else {
                    // `resize: auto`, or a resize with no dimensions to check against: the
                    // runner restored the device's own geometry and there is nothing to assert.
                    let _ = restore;
                    return Ok(Reply::ok());
                };
                // Compared as a width class, and only that.
                //
                // Two reasons, both learned from the first run of this step. What reaches day-core
                // is the safe-area-inset content size, not the window's: a window resized to 900dp
                // tall reports about 830 once the status bar, the navigation bar and the app bar
                // are taken out, so asserting the height class fails a resize that was letter
                // perfect. And width is what the step exists to control: every re-presentation
                // decision reads `SizeClass::width` (`prefers_split`, the Tabs/Rail/Split ladder),
                // while height enters into none of them. Top and bottom chrome is also exactly
                // where the insets are, so height is the axis the content size distorts most.
                let want = day_spec::SizeClass::from_size(w, h).width;
                let have = day_core::size_class();
                if have.map(|c| c.width) == Some(want) {
                    Ok(Reply::ok())
                } else {
                    // Retryable: a platform resize is animated, and the report lands when it ends.
                    Err(Reply::fail(
                        format!(
                            "resize to {w}x{h} wants width {want:?}, window reports {have:?} \
                             (a width within a few points of a breakpoint can fall the other \
                             side of it once safe-area insets come out — aim for mid-bucket)"
                        ),
                        true,
                    ))
                }
            }
            Step::OpenUrl { url } => {
                day_core::request_open_url(&url);
                Ok(Reply::ok())
            }
            Step::DeepLink { url } => {
                day_reactive::flush_sync();
                let route = day_spec::route_of_url(&url);
                if day_core::navigate(&route) {
                    day_reactive::flush_sync();
                    Ok(Reply::ok())
                } else {
                    // Retryable: the nav host may not have mounted yet.
                    Err(Reply::fail(format!("no route for {url:?}"), true))
                }
            }
            Step::Navigate { route } => {
                day_reactive::flush_sync();
                if day_core::navigate(&route) {
                    day_reactive::flush_sync();
                    Ok(Reply::ok())
                } else {
                    // Retryable: the nav host may not have mounted yet.
                    Err(Reply::fail(format!("no route {route:?}"), true))
                }
            }
            Step::NavBack { native } => {
                // `native`: the platform's own back affordance, so the backend's user-back
                // path (the bar's `shouldPop`, the pop, the report to Day) is what runs. The
                // pop animates and Day hears of it on completion, so nothing is flushed here;
                // the next `assert_route` waits for it like any assertion.
                // A native press must not race the transition before it: pressed during a
                // push still animating, the bar has nothing to pop yet, and a wide window
                // would then pass this step as "nothing was pushed" (below). Retryable, like
                // `screenshot`'s own settle.
                if native && !with_tree(|t| t.ui_idle()) {
                    return Err(Reply::fail("ui transitions still settling", true));
                }
                let popped = if native {
                    with_tree(|t| t.native_back())
                } else {
                    day_core::nav_back()
                };
                if popped {
                    if !native {
                        day_reactive::flush_sync();
                    }
                    Ok(Reply::ok())
                } else if day_core::size_class().is_some_and(|c| c.prefers_split()) {
                    // Nothing to pop, and nothing should be: a window past the compact width keeps
                    // the detail beside the list instead of pushing it (docs/size-classes.md), so
                    // the script is already where `nav_back` would have taken it.
                    //
                    // Without this, one walkthrough could not describe both form factors of the
                    // same target. The step was gated `only_on: [uikit, material]`, a toolkit condition,
                    // which silently meant "phone" until ios-uikit started running on an iPad,
                    // where the presentation is expanded exactly like a desktop's. The toolkit was
                    // never the thing that decided; the width class is.
                    //
                    // Still a failure while compact, which is where a missing pop is a regression
                    // and where the guard in the scaffold's walkthrough does its job. Tolerating
                    // it everywhere would have made this step unable to fail.
                    Ok(Reply::ok())
                } else {
                    Err(Reply::fail("nothing to pop", true))
                }
            }
            Step::AssertRoute { route } => {
                let current = day_core::current_route();
                if current.as_deref() == Some(route.as_str()) {
                    Ok(Reply::ok())
                } else {
                    Err(Reply::fail(
                        format!("expected route {route:?}, current {current:?}"),
                        true,
                    ))
                }
            }
            Step::DialogMode { mode } => {
                let mode = match mode {
                    DialogMode::Native => day_core::PresentationMode::Native,
                    DialogMode::Scripted => day_core::PresentationMode::Scripted,
                };
                day_core::set_presentation_mode(mode).map_err(|why| Reply::fail(why, false))?;
                Ok(Reply::ok())
            }
            Step::AssertNotPresented => {
                if let Some((_, spec)) = day_core::pending_presentation() {
                    Err(Reply::fail(
                        format!("unanswered presentation: {:?}", spec.title()),
                        true,
                    ))
                } else {
                    Ok(Reply::ok())
                }
            }
            Step::AssertPresented { title } => match day_core::pending_presentation() {
                Some((_, spec)) => {
                    let actual = norm(spec.title());
                    match title {
                        Some(want) if norm(&want) != actual => Err(Reply::fail(
                            format!("modal title {actual:?} != expected {want:?}"),
                            true,
                        )),
                        _ => Ok(Reply::ok()),
                    }
                }
                None => Err(Reply::fail("no modal presented", true)),
            },
            Step::Respond {
                button,
                text,
                path,
                dismiss,
            } => {
                let Some((req, _)) = day_core::pending_presentation() else {
                    return Err(Reply::fail("no modal to respond to", true));
                };
                let result = if dismiss {
                    PresentResult::Dismissed
                } else if let Some(t) = text {
                    PresentResult::Text(t)
                } else if let Some(p) = path {
                    // Relative paths resolve against the app-writable temp dir so a scripted
                    // open/save round-trip works on desktop, iOS, and Android alike.
                    let pb = std::path::PathBuf::from(&p);
                    let full = if pb.is_absolute() {
                        pb
                    } else {
                        day_core::app_temp_dir().join(pb)
                    };
                    PresentResult::Files(vec![full.to_string_lossy().into_owned()])
                } else if let Some(i) = button {
                    PresentResult::Button(i)
                } else {
                    PresentResult::Dismissed
                };
                day_core::respond_presentation(req, result);
                day_reactive::flush_sync();
                Ok(Reply::ok())
            }
            Step::Tests => Ok(Reply {
                data: Some(conformance::listing().map_err(|e| Reply::fail(e, false))?),
                ..Reply::ok()
            }),
            Step::RunTests {
                filter,
                shots,
                case_timeout_secs,
                ..
            } => conformance::run_tests(&filter, shots, case_timeout_secs),
            Step::A11yAudit { id } => {
                let rows = with_tree(|t| t.a11y_nodes());
                let rows: Vec<_> = match &id {
                    Some(want) => rows.into_iter().filter(|(nid, ..)| nid == want).collect(),
                    None => rows,
                };
                if let Some(want) = &id
                    && rows.is_empty()
                {
                    return Err(Reply::fail(
                        format!("a11y_audit: no element {want:?}"),
                        true,
                    ));
                }
                let mut fails = Vec::new();
                for (nid, _kind, expected, actual) in &rows {
                    audit_a11y_node(nid, expected, actual, &mut fails);
                }
                if !fails.is_empty() {
                    return Err(Reply::fail(
                        format!("a11y_audit: {}", fails.join("; ")),
                        false,
                    ));
                }
                Ok(Reply::ok())
            }
        }
    })();
    let mut reply = result.unwrap_or_else(|r| r);
    if reply.ok
        && !absent_optional_action
        && let (Some(class), Some(id)) = (evidence_class, evidence_id)
        && let Ok(catalog) = id_catalog()
        && let Ok(d) = catalog.resolve(&id)
    {
        reply.id_evidence = Box::new([day_script_protocol::IdEvidence {
            family: d.family.clone(),
            class,
        }]);
    }
    reply.fast_animations = Some(day_core::testing::fast_animations());
    reply
}

/// Compare readable, shown native accessibility nodes. Hidden navigation panes may retain
/// widgets whose platform accessibility nodes omit their metadata until shown again.
fn audit_a11y_node(
    nid: &str,
    expected: &day_spec::A11yProps,
    actual: &day_spec::NativeSnapshot,
    fails: &mut Vec<String>,
) {
    if !actual.found || actual.visible == Some(false) {
        return;
    }
    if actual.identifier.as_deref() != Some(nid) {
        fails.push(format!(
            "{nid}: native identifier {:?} ≠ {nid:?}",
            actual.identifier
        ));
    }
    // Role: audit only explicit (user-set) roles, the canvas/custom cases where
    // Day itself applies a role. Native controls own their roles (Day's job
    // is to not break them, §13), and those vary per platform, so we don't diff
    // the kind-default. Compare only when the native role also maps to a known Role.
    if expected.role != day_spec::Role::None
        && actual.role != day_spec::Role::None
        && !role_eq(expected.role, actual.role)
    {
        fails.push(format!(
            "{nid}: role {:?} ≠ expected {:?}",
            actual.role, expected.role
        ));
    }
    if let Some(lbl) = &expected.label
        && actual.label.as_deref() != Some(lbl.as_str())
    {
        fails.push(format!(
            "{nid}: label {:?} ≠ expected {lbl:?}",
            actual.label
        ));
    }
    if let Some(val) = &expected.value
        && actual.value.as_deref() != Some(val.as_str())
    {
        fails.push(format!(
            "{nid}: value {:?} ≠ expected {val:?}",
            actual.value
        ));
    }
}

/// Two roles match for audit purposes; `Heading` levels are ignored (the native role carries
/// no level).
fn role_eq(a: day_spec::Role, b: day_spec::Role) -> bool {
    use day_spec::Role::Heading;
    matches!((a, b), (Heading(_), Heading(_))) || a == b
}

// ---------------------------------------------------------------------------
// Minimal base64 (no dependency; screenshots cross as one JSON line)
// ---------------------------------------------------------------------------

const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

pub fn b64encode(data: &[u8]) -> String {
    let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
    for chunk in data.chunks(3) {
        let b = [
            chunk[0],
            *chunk.get(1).unwrap_or(&0),
            *chunk.get(2).unwrap_or(&0),
        ];
        let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | b[2] as u32;
        out.push(B64[(n >> 18) as usize & 63] as char);
        out.push(B64[(n >> 12) as usize & 63] as char);
        out.push(if chunk.len() > 1 {
            B64[(n >> 6) as usize & 63] as char
        } else {
            '='
        });
        out.push(if chunk.len() > 2 {
            B64[n as usize & 63] as char
        } else {
            '='
        });
    }
    out
}

pub fn b64decode(s: &str) -> Vec<u8> {
    let val = |c: u8| B64.iter().position(|&x| x == c).unwrap_or(0) as u32;
    let bytes: Vec<u8> = s.bytes().filter(|&c| c != b'\n' && c != b'\r').collect();
    let mut out = Vec::with_capacity(bytes.len() / 4 * 3);
    for chunk in bytes.chunks(4) {
        if chunk.len() < 4 {
            break;
        }
        let pad = chunk.iter().filter(|&&c| c == b'=').count();
        let n = (val(chunk[0]) << 18)
            | (val(chunk[1]) << 12)
            | (val(if chunk[2] == b'=' { b'A' } else { chunk[2] }) << 6)
            | val(if chunk[3] == b'=' { b'A' } else { chunk[3] });
        out.push((n >> 16) as u8);
        if pad < 2 {
            out.push((n >> 8) as u8);
        }
        if pad < 1 {
            out.push(n as u8);
        }
    }
    out
}

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

    #[test]
    fn a11y_audit_checks_metadata_when_visible_or_visibility_is_unknown() {
        // Synthetic snapshots model an Android list parked behind a compact detail pane.
        let expected = day_spec::A11yProps {
            label: Some("Fixture list".into()),
            ..Default::default()
        };
        let mut actual = day_spec::NativeSnapshot {
            found: true,
            identifier: Some("fixture-list".into()),
            visible: Some(false),
            ..Default::default()
        };
        let mut fails = Vec::new();
        audit_a11y_node("fixture-list", &expected, &actual, &mut fails);
        assert!(
            fails.is_empty(),
            "hidden panes need not expose their labels"
        );

        for visible in [Some(true), None] {
            actual.visible = visible;
            fails.clear();
            audit_a11y_node("fixture-list", &expected, &actual, &mut fails);
            assert_eq!(
                fails.len(),
                1,
                "missing labels must still fail: {visible:?}"
            );
            assert!(fails[0].contains("label None"));
        }

        actual.visible = Some(true);
        actual.label = expected.label.clone();
        fails.clear();
        audit_a11y_node("fixture-list", &expected, &actual, &mut fails);
        assert!(
            fails.is_empty(),
            "the list exposes its label when shown again"
        );

        actual.label = None;
        actual.found = false;
        audit_a11y_node("fixture-list", &expected, &actual, &mut fails);
        assert!(
            fails.is_empty(),
            "unreadable accessibility nodes remain unsupported"
        );
    }

    #[test]
    fn dialog_steps_hold_requests_until_an_explicit_response() {
        use day_spec::present::{PresentResult, PresentSpec};
        use std::future::Future;
        use std::task::{Context, Poll, Waker};
        assert!(serde_json::from_str::<Step>(r#"{"op":"dialog_mode","mode":"typo"}"#).is_err());
        let mode: Step = serde_json::from_str(r#"{"op":"dialog_mode","mode":"scripted"}"#).unwrap();
        assert!(exec(mode, 0).ok);
        assert!(exec(Step::AssertNotPresented, 0).ok);
        // No tree is installed: neither presenting nor answering may call a toolkit.
        let mut future = Box::pin(day_core::present(PresentSpec::OpenFile {
            title: "Choose file".into(),
            filters: vec![],
            multiple: false,
        }));
        let mut cx = Context::from_waker(Waker::noop());
        assert!(future.as_mut().poll(&mut cx).is_pending());
        assert!(
            exec(
                Step::AssertPresented {
                    title: Some("Choose file".into())
                },
                0
            )
            .ok
        );
        assert!(!exec(Step::AssertNotPresented, 0).ok);
        let refused = exec(
            Step::DialogMode {
                mode: DialogMode::Native,
            },
            0,
        );
        assert!(!refused.ok && !refused.retryable);
        assert!(
            exec(
                Step::Respond {
                    button: None,
                    text: None,
                    path: None,
                    dismiss: true
                },
                0
            )
            .ok
        );
        assert_eq!(
            future.as_mut().poll(&mut cx),
            Poll::Ready(PresentResult::Dismissed)
        );
        assert!(exec(Step::AssertNotPresented, 0).ok);
        assert!(
            exec(
                Step::DialogMode {
                    mode: DialogMode::Native
                },
                0
            )
            .ok
        );
    }

    #[test]
    fn optional_tap_only_skips_absent_elements_after_transitions_settle() {
        use day_pieces::prelude::*;
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        day_core::uninstall_tree();
        let enabled = Signal::new(false);
        let presses = Signal::new(0);
        let (mock, probe) = day_mock::MockToolkit::new();
        day_core::launch_with(mock, day_spec::WindowOptions::default(), move || {
            button("Remove fixture")
                .enabled(move || enabled.get())
                .action(move || presses.update(|n| *n += 1))
                .id(day_core::id!(remove_fixture))
                .height(50.)
                .grow_w()
                .any()
        });
        let tap = |id, optional| {
            exec(
                serde_json::from_value(serde_json::json!({
                    "op": "tap", "id": id, "if_present": optional
                }))
                .unwrap(),
                1,
            )
        };
        assert!(!tap("missing", false).ok);
        let absent = tap("missing", true);
        assert!(absent.ok);
        assert!(absent.id_evidence.is_empty());
        probe.state.borrow_mut().ui_busy = true;
        assert!(!tap("missing", true).ok);
        probe.state.borrow_mut().ui_busy = false;
        let disabled = tap("remove_fixture", true);
        assert!(!disabled.ok && disabled.retryable);
        assert_eq!(presses.get(), 0);
        enabled.set(true);
        id_catalog().expect("the compiled test fixture registry is valid");
        let present = tap("remove_fixture", true);
        assert!(present.ok);
        assert_eq!(present.id_evidence.len(), 1);
        assert_eq!(present.id_evidence[0].family, "remove_fixture");
        assert_eq!(
            present.id_evidence[0].class,
            day_script_protocol::EvidenceClass::Interaction
        );
        assert_eq!(presses.get(), 1);
        day_core::uninstall_tree();
    }

    #[test]
    fn tap_waits_for_navigation_and_enabled_state_before_dispatching_once() {
        use day_pieces::prelude::*;
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        day_core::uninstall_tree();
        let enabled = Signal::new(false);
        let presses = Signal::new(0);
        let (mock, probe) = day_mock::MockToolkit::new();
        day_core::launch_with(mock, day_spec::WindowOptions::default(), move || {
            button("Fixture download")
                .enabled(move || enabled.get())
                .action(move || presses.update(|n| *n += 1))
                .id(day_core::id!(fixture_download))
                .height(50.)
                .grow_w()
                .any()
        });
        let tap = || {
            exec(
                serde_json::from_value(serde_json::json!({
                    "op": "tap", "id": "fixture_download"
                }))
                .unwrap(),
                1,
            )
        };
        let reply = tap();
        assert!(!reply.ok && reply.retryable);
        assert!(reply.error.unwrap().contains("disabled"));
        assert_eq!(presses.get(), 0);
        enabled.set(true);
        probe.state.borrow_mut().ui_busy = true;
        assert!(!tap().ok);
        assert!(!exec(Step::WaitIdle, 1).ok);
        assert_eq!(presses.get(), 0);
        probe.state.borrow_mut().ui_busy = false;
        assert!(exec(Step::WaitIdle, 1).ok);
        assert!(tap().ok);
        assert_eq!(presses.get(), 1);
        day_core::uninstall_tree();
    }

    #[test]
    fn capture_acknowledgments_are_optional_and_pending_stays_internal() {
        let old: Reply = serde_json::from_str(r#"{"ok":true}"#).unwrap();
        assert_eq!(old.capture_revision, None);
        assert_eq!(old.fast_animations, None);
        let reply = Reply {
            capture_revision: Some(73),
            fast_animations: Some(true),
            capture_pending: true,
            ..Reply::ok()
        };
        let json = serde_json::to_value(reply).unwrap();
        assert_eq!(json["capture_revision"], 73);
        assert!(json.get("capture_pending").is_none());
        let decoded: Reply = serde_json::from_value(json).unwrap();
        assert_eq!(decoded.capture_revision, Some(73));
        assert_eq!(decoded.fast_animations, Some(true));
    }

    /// Serialize the env mutation below (`set_var` is unsafe under concurrency in edition 2024).
    static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// The budget that decides whether a busy CI runner fails a walkthrough. One
    /// `main thread did not respond` was enough to fail an otherwise perfect 407-step run, so the
    /// default is generous, the environment can raise it, and a step that asks for longer gets it.
    #[test]
    fn the_main_thread_budget_is_generous_overridable_and_never_below_the_step() {
        let five = Duration::from_secs(5);
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        // SAFETY: the guard above serializes every mutation of this variable in this crate.
        unsafe { std::env::remove_var("DAY_SCRIPT_MAIN_TIMEOUT_SECS") };
        assert_eq!(
            main_thread_budget(five),
            Duration::from_secs_f64(DEFAULT_MAIN_TIMEOUT_SECS)
        );
        // A step declaring a longer wait is saying the app may legitimately take that long.
        assert_eq!(
            main_thread_budget(Duration::from_secs(120)),
            Duration::from_secs(120)
        );
        unsafe { std::env::set_var("DAY_SCRIPT_MAIN_TIMEOUT_SECS", "90") };
        assert_eq!(main_thread_budget(five), Duration::from_secs(90));
        // Nonsense is ignored rather than producing a zero budget that fails every step.
        for bad in ["0", "-3", "abc", ""] {
            unsafe { std::env::set_var("DAY_SCRIPT_MAIN_TIMEOUT_SECS", bad) };
            assert_eq!(
                main_thread_budget(five),
                Duration::from_secs_f64(DEFAULT_MAIN_TIMEOUT_SECS),
                "{bad:?} should fall back to the default"
            );
        }
        unsafe { std::env::remove_var("DAY_SCRIPT_MAIN_TIMEOUT_SECS") };
    }

    /// A download finishing or an upload's receipt can take far longer than the shared wait, and
    /// a step's `timeout_secs` is how a script says so. An `assert_text` that dropped the field
    /// failed after five seconds while its script promised two minutes.
    #[test]
    fn assert_text_honors_its_own_timeout() {
        let step = |json: &str| serde_json::from_str::<Step>(json).expect("step");
        let slow = step(r#"{"op":"assert_text","id":"state","text":"done","timeout_secs":120}"#);
        assert_eq!(slow.wait_budget_secs(), 120.0);
        let plain = step(r#"{"op":"assert_text","id":"state","text":"done"}"#);
        assert_eq!(plain.wait_budget_secs(), DEFAULT_TIMEOUT_SECS);
        let waiting = step(r#"{"op":"wait_for","id":"state","timeout_secs":30}"#);
        assert_eq!(waiting.wait_budget_secs(), 30.0);
    }

    /// A cold WebView2 engine can take longer than five seconds. The serialized step's
    /// budget must reach the engine poller, matching the CLI's socket timeout budget.
    #[test]
    fn web_eval_honors_its_own_timeout() {
        for (timeout, expected) in [
            (None, DEFAULT_TIMEOUT_SECS),
            (Some(30.0), 30.0),
            (Some(0.0), DEFAULT_TIMEOUT_SECS),
            (Some(-1.0), DEFAULT_TIMEOUT_SECS),
        ] {
            let step: Step = serde_json::from_value(serde_json::json!({
                "op": "web_eval", "id": "page", "script": "document.title",
                "timeout_secs": timeout,
            }))
            .expect("web_eval step");
            assert_eq!(step.wait_budget_secs(), expected);
        }
    }

    /// `menu: { id: … }` is the address that survives a label change (which is exactly what a
    /// checked item does to itself on every state flip), and it never falls back to the label,
    /// so a step naming an id that is not there fails instead of hitting a lookalike.
    #[test]
    fn menu_id_addresses_an_item_whose_label_moves() {
        use day_spec::MenuItem as MI;
        let model = |mark: &str| {
            vec![MI::Submenu {
                label: "View".into(),
                role: None,
                items: vec![
                    MI::Action {
                        id: Some("view-grid".into()),
                        action: 42,
                        label: format!("{mark}Grid"),
                        shortcut: None,
                        enabled: true,
                        checked: Some(mark == "\u{2713} "),
                        role: None,
                        icon: None,
                    },
                    MI::Action {
                        id: None,
                        action: 7,
                        label: "Grid".into(),
                        shortcut: None,
                        enabled: true,
                        checked: None,
                        role: None,
                        icon: None,
                    },
                ],
            }]
        };
        let by_id = |items: &[MI]| {
            find_menu_actions(items, "", None, Some("view-grid"), &[])
                .into_iter()
                .map(|(a, _, _)| a)
                .collect::<Vec<_>>()
        };
        // Same id on either side of the flip, though the label is a different string each time.
        assert_eq!(by_id(&model("\u{2713} ")), vec![42]);
        assert_eq!(by_id(&model("    ")), vec![42]);
        // The unmarked spelling matches the other item by label, which is the ambiguity an id
        // exists to avoid.
        assert_eq!(
            find_menu_actions(&model("    "), "Grid", None, None, &[])
                .into_iter()
                .map(|(a, _, _)| a)
                .collect::<Vec<_>>(),
            vec![7]
        );
        // An id that is not in the model matches nothing: never the same-named item by label.
        assert!(
            find_menu_actions(&model("    "), "Grid", None, Some("view-ruler"), &[]).is_empty()
        );
    }
}