day-mock 0.7.4

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
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! day-mock: the headless toolkit (DESIGN.md §3.2, §21.2 M0–M1).
//!
//! Records every toolkit call into a compact op log (golden-diffable), performs deterministic
//! measurement (8pt/char × 16pt line labels, fixed control sizes), and lets tests inject
//! native events through the real sink. The op log is the contract for the fine-grained
//! guarantees: "exactly one op per state change" and "bounded measure calls" are assertions
//! over this log.

use std::any::Any;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;

use day_spec::props::*;
use day_spec::*;

// --- the opt-in native behavior: list and tree viewports, cover reports ----------------------
//
// A native list binds the rows it shows into cells by itself: on attach, after a reload, and
// around a row it is asked to scroll to. Unit tests drive that by hand through
// `MockProbe::list_bind`; the conformance harness has no test in the loop to do it, so it turns
// this on (`MockProbe::set_list_viewport`) and the mock binds a window of rows itself.
//
// The binding cannot happen where the list learns of a change: that is inside a Toolkit duty,
// with Day's tree borrowed, and day-core skips a bind it cannot reach the tree for. So a change
// marks the viewport dirty, and the next `post_delayed` (a `sleep`, which the runner's retry
// loop reaches with the tree free) binds it.

/// An event a native toolkit raises by itself, with the sink to raise it through.
type NativeEvent = (Rc<dyn Fn(NodeId, Event)>, NodeId, Event);
/// A viewport's rows in display order, given the disclosed rows.
type VisibleRows = Rc<dyn Fn(&std::collections::HashSet<u64>) -> Vec<u64>>;

thread_local! {
    /// Rows a list shows at once; 0 = off (the default: unit tests bind by hand).
    static VIEWPORT_ROWS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
    static VIEWPORTS: RefCell<HashMap<u64, Viewport>> = RefCell::new(HashMap::new());
    /// Each bound viewport cell's row height, as the source reported it after the bind and
    /// `ListPatch::RowSizeInvalidated` corrected it since: the cells stack by these heights,
    /// which is where `read_native` finds a row's content in the window.
    static CELL_HEIGHTS: RefCell<HashMap<u64, f64>> = RefCell::new(HashMap::new());
    /// Events a native toolkit would raise by itself (a cover's size and its dismissal), held
    /// like the viewport binds until the tree is free, with the sink to raise them through.
    static NATIVE_EVENTS: RefCell<Vec<NativeEvent>> = RefCell::new(Vec::new());
    /// The primary window's size, which a presented cover fills.
    static MOCK_WINDOW: std::cell::Cell<Size> = const { std::cell::Cell::new(Size::new(0.0, 0.0)) };
}

struct Viewport {
    /// The rows in display order, given the tree's disclosed rows: a list's indices, a tree's
    /// tokens.
    visible: VisibleRows,
    bind_row: Rc<dyn Fn(u64, RawHandle)>,
    recycle: Rc<dyn Fn(RawHandle)>,
    /// The bound row's height (`ListSource::cell_height`); a tree's rows report none.
    cell_height: Option<Rc<dyn Fn(RawHandle) -> f64>>,
    /// A tree's disclosed rows, as `TreePatch::Expand` set them.
    expanded: std::collections::HashSet<u64>,
    /// The first row shown.
    start: usize,
    /// Scroll to the end on the next bind.
    to_end: bool,
    /// Cells bound by the last bind.
    bound: usize,
    dirty: bool,
}

/// The physical cell `slot` of list `host`: stable per list and slot, clear of widget handles.
fn viewport_cell(host: u64, slot: usize) -> RawHandle {
    ((1u64 << 40) + host * 4096 + slot as u64) as RawHandle
}

/// The list and slot a viewport cell belongs to: [`viewport_cell`] inverted.
fn viewport_slot(cell: u64) -> Option<(u64, usize)> {
    let offset = cell.checked_sub(1u64 << 40)?;
    Some((offset / 4096, (offset % 4096) as usize))
}

/// How far down its list viewport cell `cell` sits: the heights of the cells above it.
fn viewport_cell_top(cell: u64) -> f64 {
    let Some((host, slot)) = viewport_slot(cell) else {
        return 0.0;
    };
    CELL_HEIGHTS.with(|h| {
        let h = h.borrow();
        (0..slot)
            .map(|s| {
                h.get(&(viewport_cell(host, s) as u64))
                    .copied()
                    .unwrap_or(0.0)
            })
            .sum()
    })
}

/// Widget `id`'s frame in the window, as `NativeSnapshot::frame` is defined: its own frame
/// moved by each ancestor's origin, and a list row's content by where its cell sits in the list.
fn window_frame(s: &MockState, id: u64) -> Rect {
    let Some(w) = s.widgets.get(&id) else {
        return Rect::default();
    };
    let mut frame = w.frame;
    let mut current = id;
    // Bounded: a malformed test tree must not hang the probe.
    for _ in 0..4096 {
        let next = match s.widgets.get(&current) {
            Some(w) if w.kind == kinds::LIST_CELL => viewport_slot(current).map(|(host, _)| {
                frame.origin.y += viewport_cell_top(current);
                host
            }),
            _ => s
                .widgets
                .iter()
                .find(|(_, p)| p.children.contains(&current))
                .map(|(k, _)| *k),
        };
        let Some(parent) = next else {
            break;
        };
        if let Some(p) = s.widgets.get(&parent) {
            frame.origin.x += p.frame.origin.x;
            frame.origin.y += p.frame.origin.y;
        }
        current = parent;
    }
    frame
}

fn viewport_touch(host: u64, f: impl FnOnce(&mut Viewport)) {
    VIEWPORTS.with(|v| {
        if let Some(port) = v.borrow_mut().get_mut(&host) {
            f(port);
            port.dirty = true;
        }
    });
}

/// Bind every dirty viewport's rows, outside any borrow of the registry.
fn viewport_flush() {
    let rows = VIEWPORT_ROWS.with(|r| r.get());
    if rows == 0 {
        return;
    }
    let events = NATIVE_EVENTS.with(|q| std::mem::take(&mut *q.borrow_mut()));
    for (sink, node, event) in events {
        sink(node, event);
    }
    let dirty: Vec<u64> = VIEWPORTS.with(|v| {
        v.borrow()
            .iter()
            .filter(|(_, p)| p.dirty)
            .map(|(h, _)| *h)
            .collect()
    });
    for host in dirty {
        let Some((visible, bind_row, recycle, cell_height, expanded, start, to_end, bound)) =
            VIEWPORTS.with(|v| {
                let mut v = v.borrow_mut();
                let p = v.get_mut(&host)?;
                p.dirty = false;
                Some((
                    p.visible.clone(),
                    p.bind_row.clone(),
                    p.recycle.clone(),
                    p.cell_height.clone(),
                    p.expanded.clone(),
                    p.start,
                    p.to_end,
                    p.bound,
                ))
            })
        else {
            continue;
        };
        let rows_now = visible(&expanded);
        let total = rows_now.len();
        let start = if to_end {
            total.saturating_sub(rows)
        } else {
            start.min(total.saturating_sub(rows))
        };
        let count = rows.min(total - start.min(total));
        for slot in 0..count {
            let cell = viewport_cell(host, slot);
            bind_row(rows_now[start + slot], cell);
            // A native list sizes the row once it is bound, from the height Day laid it at.
            if let Some(height) = &cell_height {
                let laid = height(cell);
                CELL_HEIGHTS.with(|h| h.borrow_mut().insert(cell as u64, laid));
            }
        }
        // Cells past a shrunk source go back to the pool, as a native list's would.
        for slot in count..bound {
            recycle(viewport_cell(host, slot));
        }
        VIEWPORTS.with(|v| {
            if let Some(p) = v.borrow_mut().get_mut(&host) {
                p.start = start;
                p.to_end = false;
                p.bound = count;
            }
        });
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct MockHandle(pub u64);

#[derive(Default, Debug, Clone)]
pub struct MockWidget {
    pub kind: &'static str,
    pub node: u64,
    pub text: String,
    pub placeholder: String,
    /// A text field's last requested selection (`TextFieldPatch::Select`), in characters,
    /// probe-visible for tests. The mock has no focus to gate it on, so it keeps every request.
    pub selection: Option<day_spec::props::TextSelection>,
    pub value: f64,
    pub flag: bool,
    /// A cover presented as a half sheet (`CoverProps::half`): its present reports half the
    /// window's height, as the native sheet would.
    pub half: bool,
    pub enabled: bool,
    /// A button's selected state (`ButtonProps::selected`), probe-visible for tests.
    pub selected: bool,
    /// `text_area` attributes (probe-visible for tests): editable/read-only, selectable, spell-check.
    pub editable: bool,
    pub selectable: bool,
    pub spellcheck: bool,
    /// The last text entry traits applied to this widget (docs/textfield.md), probe-visible
    /// for tests; `None` until a field asks for anything but the defaults.
    pub input_traits: Option<day_spec::InputTraits>,
    /// The last `.cursor()` applied to this widget (probe-visible for tests), `None` until set.
    pub cursor: Option<day_spec::Cursor>,
    pub children: Vec<u64>,
    pub frame: Rect,
    pub a11y: A11yProps,
    pub scroll_content: Size,
    /// The scroll offset after the last `scroll_to` (docs/scroll.md), computed with the same
    /// minimal-reveal clamp every real backend applies (probe-visible for tests).
    pub scroll_offset: Point,
    pub ops: Vec<DrawOp>,
    /// Surface style from a `background`/`corner_radius` decorator (probe-visible for tests).
    pub background: Option<Color>,
    pub corner_radius: f64,
    pub clips: bool,
    /// Semantic theme-adaptive surface (a form section card), probe-visible for tests.
    pub surface_role: Option<day_spec::SurfaceRole>,
    /// A label's resolved font spec (probe-visible so tests can assert e.g. `Font::Custom` flow).
    pub font: Option<day_spec::FontSpec>,
    /// A label's styled spans (docs/text-runs.md). Probe-visible so a test can assert that the
    /// second word is bold, which no screenshot comparison can state and no `assert_text` can
    /// see, since the plain text is identical either way.
    pub runs: Vec<day_spec::TextRun>,
    /// Last focus state driven through the `focus` duty (docs/focus.md), probe-visible.
    pub focused: bool,
    /// Last opacity applied via `set_opacity` (§8.4); `None` until touched (probe-visible).
    pub opacity: Option<f64>,
    /// Last transform applied via `set_transform` (§8.4), probe-visible.
    pub transform: Option<day_spec::Transform>,
    /// The most recent animation intent seen on any duty for this widget (`update`/`set_frame`/
    /// `set_opacity`/`set_transform`). Lets tests assert `with_animation` threaded the intent.
    pub last_anim: Option<AnimSpec>,
    /// A nav host's current presentation (docs/size-classes.md), probe-visible so a test can
    /// assert which of the four a morph landed on. `flag` carries only split-ness, which cannot
    /// tell `Tabs` from `Rail` from `Stack`; both are kept because the older tests read `flag`.
    pub presentation: Option<day_spec::props::NavPresentation>,
    /// The resident detail page index a `NavPatch::Select` last chose (docs/navigation.md).
    /// `None` until the host is asked to select one, which only happens in a presentation whose
    /// rows are chrome; a stacked host pushes and pops instead.
    pub selected_page: Option<usize>,
    /// Pages a nav host holds above its root (`NavPatch::Pushed` less `Popped`), what the
    /// mock's [`Toolkit::native_back`] pops first.
    pub nav_depth: usize,
    /// A nav host's back guard (`NavPatch::GuardTop`): the native back asks Day instead of
    /// popping.
    pub nav_guarded: bool,
}

/// A secondary window opened through the `open_window` duty (docs/windows.md),
/// probe-visible for the `open_window` tests.
#[derive(Clone, Debug)]
pub struct MockWindow {
    /// The content-container widget handle.
    pub handle: u64,
    /// The window root's spec-boundary id (events emit to it).
    pub node: NodeId,
    pub title: String,
    pub size: Size,
    /// `"normal"` | `"preferences"`.
    pub kind: String,
    /// The tabbing the window was opened with (docs/windows.md).
    pub tabbing: day_spec::WindowTabbing,
    pub open: bool,
    pub focused: bool,
    /// The content size the window was fitted to (`WindowOptions::size_to_fit`), or `None` if it
    /// kept the size it was opened at. Probe-visible so a test can assert that a preferences
    /// panel shrank to its rows rather than keeping the caller's ceiling.
    pub fit_size: Option<Size>,
}

#[derive(Default)]
pub struct MockState {
    /// Optional synthetic palette for appearance-reactivity tests.
    pub system_colors: Option<[day_spec::Color; 5]>,
    /// Simulate native navigation that has not settled yet in engine tests.
    pub ui_busy: bool,
    next: u64,
    pub widgets: HashMap<u64, MockWidget>,
    pub log: Vec<String>,
    /// Held as an `Rc` rather than the `Box` day-spec hands over, so it can be CALLED without
    /// being taken out.
    ///
    /// Taking it out is what a `Box<dyn Fn>` forces, and it is a trap: the whole dispatch of one
    /// event (pump, handler, action, any completion a Toolkit duty raises along the way)
    /// happens inside that window, so a second event raised during the first found no sink and
    /// vanished. An image decode completing inside a button's action is exactly that shape
    /// (docs/images.md).
    pub sink: Option<Rc<dyn Fn(NodeId, Event)>>,
    /// Decoded images by id (docs/images.md): what `image_info` answers and `release_image`
    /// forgets, so a test can assert both that a decode landed and that dropping the handle
    /// released it.
    pub bitmaps: HashMap<u64, day_spec::BitmapInfo>,
    /// (kind, proposal) measure-call counter for the M1 bounded-measure tests.
    pub measure_calls: usize,
    /// What `scroll_bar_inset` answers (docs/scroll.md): 0, overlay bars, unless a test plays a
    /// backend whose classic bar takes room from the viewport.
    pub scroll_bar_inset: f64,
    /// Recycling-list row-pull sources, keyed by list host handle (docs/list.md). A test drives
    /// the "viewport" through [`MockProbe::list_bind`], simulating what a native list would do.
    pub list_sources: HashMap<u64, ListSource>,
    /// Hierarchical-tree row-pull sources, keyed by tree host handle (docs/tree.md). A test
    /// drives the "native tree" through the `MockProbe::tree_*` probes.
    pub tree_sources: HashMap<u64, day_spec::TreeSource>,
    /// Exercise the shared composed tree/section implementation instead of native pulls.
    pub emulated_trees: bool,
    /// The app menu as last applied (docs/menus.md): item titles, probe-visible.
    pub app_menu: Vec<String>,
    /// The Dock menu as last applied (docs/menus.md "Dock menu"): item titles.
    pub dock_menu: Vec<String>,
    /// The widgets marked as window drag regions (docs/window-chrome.md), by handle.
    pub drag_regions: std::collections::HashSet<u64>,
    /// The status items as last applied (docs/status-item.md).
    pub status_items: Vec<day_spec::StatusItemSpec>,
    /// The Dock or taskbar progress as last applied.
    pub app_progress: day_spec::AppProgress,
    /// Whether the Dock icon is shown (`None` until the app asks).
    pub dock_visible: Option<bool>,
    /// Whether day-core asked the platform to keep running with no window.
    pub keep_running: bool,
    /// The run-time launcher shortcuts as last applied.
    pub launcher_shortcuts: Vec<day_spec::LauncherShortcut>,
    /// Every `apply_window` change, oldest first, keyed by content-container handle
    /// (docs/windows.md "Window properties").
    pub window_changes: Vec<(u64, day_spec::WindowChange)>,
    /// Each window's display state as the mock platform holds it, keyed by handle.
    pub window_states: HashMap<u64, day_spec::WindowState>,
    /// Hold `WindowChange::State` requests instead of completing them, so a test can model a
    /// platform that declines one (a browser refusing fullscreen outside a gesture).
    pub decline_window_states: bool,
    /// Every window-toolbar edit, in order (docs/toolbars.md). A test reads these to hold
    /// day-core to touching only the items that changed.
    pub toolbar_edits: Vec<Vec<day_spec::ToolbarOp>>,
    /// The bar those edits and the patches produced, the way a backend keeps it.
    pub toolbar: day_spec::ToolbarMirror,
    /// `Cap::ToolbarSearch` answers `Unsupported`: a phone's bar, a row of actions with no room
    /// for a field (docs/search.md).
    pub no_toolbar_search: bool,
    /// `edit_toolbar` declines every edit, as a window with no bar to edit yet does.
    pub decline_toolbar_edits: bool,
    /// Every targeted toolbar patch, in order.
    pub toolbar_patches: Vec<day_spec::ToolbarPatch>,
    /// Context menus by widget handle (docs/menus.md): item titles per handle.
    pub context_menus: HashMap<u64, Vec<String>>,
    /// Summon-time menus, callable after releasing the probe's state borrow.
    pub context_menu_providers: HashMap<u64, day_spec::ContextMenuFn>,
    /// Menu buttons' providers by button handle (`set_button_menu`, docs/menus.md "Menu
    /// buttons"), callable after releasing the probe's state borrow, as a press would.
    pub button_menus: HashMap<u64, day_spec::ContextMenuFn>,
    /// Every share chooser presented, with the handle of the control it pointed at, if any
    /// (docs/sharing.md).
    pub shares: Vec<(day_spec::share::ShareSpec, Option<u64>)>,
    /// Whether day-core armed the system back for the app's handlers
    /// (`Toolkit::set_system_back`, docs/navigation.md "Handling the system Back").
    pub system_back: bool,
    /// Secondary windows (docs/windows.md), in open order, probe-visible.
    pub windows: Vec<MockWindow>,
    /// `open_window` answers `Unsupported` (the cover-fallback test harness).
    pub no_multi_window: bool,
    /// Delay native close confirmation until `MockProbe::close_window_natively` is called.
    pub defer_window_close: bool,
    /// Enable the OS window-tab contract for lifecycle tests.
    pub native_window_tabs: bool,
    /// Realize `kinds::LIST_ITEM` natively (`Cap::ListItem` answers `Native`), so a test sees
    /// the item's props and patches; off, the `list_item` piece composes.
    pub native_list_items: bool,
    /// Native tab groups in display order; tests can simulate an OS reorder or detach.
    pub window_tab_groups: Vec<Vec<NodeId>>,
    /// Every `announce` in order, as `(text, urgent)` (docs/accessibility.md), probe-visible.
    pub announcements: Vec<(String, bool)>,
    /// What `reduce_motion` answers (docs/accessibility.md): the user's system setting as
    /// the mock models it. A test flips it and calls `day_core::note_motion_changed`, as a
    /// backend's observer would.
    pub reduce_motion: bool,
    /// Model a toolkit whose secure field is a different native class (AppKit, WinUI):
    /// `set_input_traits` answers a secure flip with a replacement widget under a new handle
    /// (docs/textfield.md). Off by default: most toolkits flip a property.
    pub secure_class_swap: bool,
    /// `Cap::NavSplit` answers `Native`: the harness for split and re-presenting nav hosts
    /// (docs/size-classes.md). Off by default, so the mock keeps modeling a phone.
    pub nav_split: bool,
    /// `Cap::NavTabs` answers `Unsupported`: the harness for the degradation path, where an
    /// `Automatic` nav host falls back to the sidebar resolver (docs/navigation.md). Inverted
    /// like `no_multi_window` because the capability is on by default: a phone has a tab bar,
    /// so a mock that models a phone must have one too, or the default resolution is a fiction.
    pub no_nav_tabs: bool,
    /// Preserve native navigation while content lists remain draggable, as on UIKit.
    pub no_nav_reorder: bool,
    /// `Cap::NavReorder` answers `Native`: the sidebar drags its own rows, as on AppKit, so a
    /// reordering nav keeps its `day.nav_menu` and marks the movable rows. Off, the mock
    /// answers `Emulated` and the nav stands a reorderable list in.
    pub native_nav_reorder: bool,
    /// `Cap::NavTabsAdaptive` answers `Unsupported`: the harness for a desktop idiom, where a
    /// narrow window collapses to a stack instead of growing a tab bar. Also inverted: the mock
    /// models a phone by default, and a phone adapts.
    pub desktop_idiom: bool,
    /// What `Cap::NavContentList` answers (docs/navigation.md): `Unsupported` by default (the
    /// composed path); a test opts into `Native` (persistent pane) or `Emulated` (merges into
    /// the stack) with [`MockProbe::set_nav_content_list`]. Read during the build.
    pub nav_content_list: Support,
    /// `open_window` answers `Pending` (the async-completion test harness); the test
    /// finishes the open through [`MockProbe::complete_window`].
    pub pending_windows: bool,
    /// Parked `Pending` opens: (node, title, kind).
    pub pending_opens: Vec<(NodeId, String, String)>,
    /// Formatters for patch types the mock does not know; see [`MockProbe::describe_patch`].
    #[allow(clippy::type_complexity)]
    pub describers: Vec<Box<dyn Fn(&dyn Any) -> Option<String>>>,
}

impl MockState {
    fn log(&mut self, s: String) {
        self.log.push(s);
    }
}

/// The mock backend. Cloneable observer half: construct with [`MockToolkit::new`] and keep the
/// returned [`MockProbe`] to inspect state after day-core takes ownership of the toolkit.
pub struct MockToolkit {
    pub state: Rc<RefCell<MockState>>,
}

#[derive(Clone)]
pub struct MockProbe {
    pub state: Rc<RefCell<MockState>>,
}

impl MockToolkit {
    pub fn new() -> (Self, MockProbe) {
        // A fresh mock starts with the viewport off and no lists from an earlier one.
        VIEWPORT_ROWS.with(|r| r.set(0));
        VIEWPORTS.with(|v| v.borrow_mut().clear());
        NATIVE_EVENTS.with(|q| q.borrow_mut().clear());
        // Posts run on the calling thread here (see `Platform::post`), so a wake from a pool
        // thread would have no loop to land on: blocking jobs run inline, like the web's.
        day_async::set_blocking_inline(true);
        let state = Rc::new(RefCell::new(MockState::default()));
        (
            MockToolkit {
                state: state.clone(),
            },
            MockProbe { state },
        )
    }
}

impl MockProbe {
    pub fn log(&self) -> Vec<String> {
        self.state.borrow().log.clone()
    }
    pub fn clear_log(&self) {
        let mut s = self.state.borrow_mut();
        s.log.clear();
        s.measure_calls = 0;
    }
    pub fn measure_calls(&self) -> usize {
        self.state.borrow().measure_calls
    }
    /// Teach the op log to name a patch type the mock doesn't know.
    ///
    /// A standalone piece (docs/extending.md) defines its patch enum in its own crate, so the
    /// `update` duty sees `&dyn Any` and logs `update <kind> #n ?`. Install a describer and the
    /// log carries the variant instead, which is what makes "this write patched attributes and
    /// did not replace the document" an assertion a test can make:
    ///
    /// ```ignore
    /// probe.describe_patch::<EditorPatch>(|p| format!("{p:?}"));
    /// ```
    ///
    /// Describers are tried in the order installed; the first that matches the type wins.
    pub fn describe_patch<T: 'static>(&self, f: impl Fn(&T) -> String + 'static) {
        self.state
            .borrow_mut()
            .describers
            .push(Box::new(move |any| any.downcast_ref::<T>().map(&f)));
    }
    /// Ops excluding measures (mutation ops only).
    pub fn mutations(&self) -> Vec<String> {
        self.state
            .borrow()
            .log
            .iter()
            .filter(|l| !l.starts_with("measure"))
            .cloned()
            .collect()
    }
    pub fn widget(&self, h: MockHandle) -> MockWidget {
        self.state
            .borrow()
            .widgets
            .get(&h.0)
            .cloned()
            .unwrap_or_default()
    }
    pub fn find_by_kind(&self, kind: &str) -> Vec<(MockHandle, MockWidget)> {
        let mut v: Vec<_> = self
            .state
            .borrow()
            .widgets
            .iter()
            .filter(|(_, w)| w.kind == kind)
            .map(|(k, w)| (MockHandle(*k), w.clone()))
            .collect();
        v.sort_by_key(|(h, _)| h.0);
        v
    }
    /// Report a simulated viewport without synchronously entering application code.
    pub fn list_first_visible(&self, host: MockHandle, index: usize) {
        let callback = self
            .state
            .borrow()
            .list_sources
            .get(&host.0)
            .and_then(|source| source.first_visible.clone());
        if let Some(callback) = callback {
            callback(index);
        }
    }

    /// Row count a `LIST` host would query from its data-source.
    pub fn list_len(&self, host: MockHandle) -> usize {
        let f = self
            .state
            .borrow()
            .list_sources
            .get(&host.0)
            .map(|s| s.len.clone());
        f.map(|f| f()).unwrap_or(0)
    }

    /// Simulate the native list binding row `index` into a physical `cell`: Day builds the row
    /// the first time a cell is used and rebinds (slot-write) when it is recycled. Drives the real
    /// day-core driver, so tests exercise the whole recycling path. (The source Rc is cloned out
    /// before the call so the re-entrant `with_tree`/toolkit work holds no MockState borrow.)
    pub fn list_bind(&self, host: MockHandle, index: usize, cell: MockHandle) {
        let f = self
            .state
            .borrow()
            .list_sources
            .get(&host.0)
            .map(|s| s.bind_row.clone());
        if let Some(f) = f {
            f(index, cell.0 as RawHandle);
        }
    }

    /// Simulate an emulated-pin host binding display row `index` into its pinned-header `cell`
    /// (`ListSource::bind_pinned`, docs/list.md "Sections").
    pub fn list_bind_pinned(&self, host: MockHandle, index: usize, cell: MockHandle) {
        let f = self
            .state
            .borrow()
            .list_sources
            .get(&host.0)
            .map(|s| s.bind_pinned.clone());
        if let Some(f) = f {
            f(index, cell.0 as RawHandle);
        }
    }

    /// Simulate the native list pooling a physical `cell` that scrolled out of view, the
    /// `onViewRecycled` / prepare-for-reuse moment. Day parks the cell subtree's ids so the
    /// hidden row stops answering lookups; the next [`Self::list_bind`] of that cell restores
    /// them (docs/list.md).
    /// Have the mock do by itself what a native toolkit does without being asked, for harnesses
    /// with no test in the loop to drive it (the conformance runner): lists and trees bind a
    /// window of `viewport_rows` rows (on attach, after a reload, around a scrolled-to row), and
    /// a presented cover reports its size and, once dismissed, that it is hidden. 0 turns it off,
    /// the default, where unit tests drive [`Self::list_bind`] and the cover events by hand.
    pub fn set_native_behavior(&self, viewport_rows: usize) {
        VIEWPORT_ROWS.with(|r| r.set(viewport_rows));
    }

    pub fn list_recycle(&self, host: MockHandle, cell: MockHandle) {
        let f = self
            .state
            .borrow()
            .list_sources
            .get(&host.0)
            .map(|s| s.recycle.clone());
        if let Some(f) = f {
            f(cell.0 as RawHandle);
        }
    }

    /// Simulate the native list discarding a physical `cell` for good, the factory-teardown /
    /// cell-dealloc moment: Day disposes the row it built there, so its ids are gone rather
    /// than parked and the next [`Self::list_bind`] of the same handle builds afresh
    /// (docs/list.md).
    pub fn list_release(&self, host: MockHandle, cell: MockHandle) {
        let f = self
            .state
            .borrow()
            .list_sources
            .get(&host.0)
            .map(|s| s.release.clone());
        if let Some(f) = f {
            f(cell.0 as RawHandle);
        }
    }

    /// Consult the list's reorder guard the way a native validate hook would: the accepted
    /// target index, or -1 when the guard denies. `i64::MIN` when the list is not reorderable
    /// (no `.reorderable()`).
    pub fn list_can_move(&self, host: MockHandle, from: usize, to: usize) -> i64 {
        let f = self
            .state
            .borrow()
            .list_sources
            .get(&host.0)
            .and_then(|s| s.reorder.as_ref().map(|r| r.can_move.clone()));
        f.map(|f| f(from, to)).unwrap_or(i64::MIN)
    }

    /// Consult the list's delete guard the way a native swipe would before offering its action:
    /// `Some(true)` to offer, `Some(false)` when the guard protects the row, `None` when the
    /// list is not deletable (no `.deletable()`).
    pub fn list_can_delete(&self, host: MockHandle, index: usize) -> Option<bool> {
        let f = self
            .state
            .borrow()
            .list_sources
            .get(&host.0)
            .and_then(|s| s.delete.as_ref().map(|d| d.can_delete.clone()));
        f.map(|f| f(index))
    }

    /// Simulate a native swipe-to-delete: consult the guard, commit on accept (shortening Day's
    /// snapshot and deferring the app's `on_delete`, exactly as a native backend would). Returns
    /// whether the delete committed.
    pub fn list_delete(&self, host: MockHandle, index: usize) -> bool {
        let d = self
            .state
            .borrow()
            .list_sources
            .get(&host.0)
            .and_then(|s| s.delete.clone());
        let Some(d) = d else {
            self.state
                .borrow_mut()
                .log(format!("list delete unsupported {index}"));
            return false;
        };
        if !(d.can_delete)(index) {
            self.state
                .borrow_mut()
                .log(format!("list delete denied {index}"));
            return false;
        }
        (d.delete_row)(index);
        true
    }

    /// Pull a row's swipe-action offer the way a native gesture would as the row starts to
    /// slide (docs/list.md): `Some(actions)`, possibly empty, when the list is swipeable,
    /// `None` when it is not (no `.swipe_leading()`/`.swipe_trailing()`).
    pub fn list_swipe_actions(
        &self,
        host: MockHandle,
        index: usize,
        edge: SwipeEdge,
    ) -> Option<Vec<ListSwipeAction>> {
        let f = self
            .state
            .borrow()
            .list_sources
            .get(&host.0)
            .and_then(|s| s.swipe.as_ref().map(|sw| sw.actions_at.clone()));
        f.map(|f| f(index, edge))
    }

    /// Simulate a native swipe activation: pull the offer and press button `action` (an index
    /// into it), committing through the source's `perform`, which defers the app's handler to
    /// the event drain, exactly as a native backend would. Returns whether an action was
    /// activated.
    pub fn list_swipe(
        &self,
        host: MockHandle,
        index: usize,
        edge: SwipeEdge,
        action: usize,
    ) -> bool {
        let sw = self
            .state
            .borrow()
            .list_sources
            .get(&host.0)
            .and_then(|s| s.swipe.clone());
        let Some(sw) = sw else {
            self.state
                .borrow_mut()
                .log(format!("list swipe unsupported {index}"));
            return false;
        };
        if (sw.actions_at)(index, edge).len() <= action {
            self.state
                .borrow_mut()
                .log(format!("list swipe no action {index}"));
            return false;
        }
        (sw.perform)(index, edge, action);
        true
    }

    /// Simulate a native drop: consult the guard, commit on accept (rotating Day's snapshot and
    /// deferring the app's `on_reorder`, exactly as a native backend would). Returns whether the
    /// move committed. (Reorder Rcs are cloned out before the call, like [`Self::list_bind`].)
    pub fn list_move(&self, host: MockHandle, from: usize, to: usize) -> bool {
        let r = self
            .state
            .borrow()
            .list_sources
            .get(&host.0)
            .and_then(|s| s.reorder.clone());
        let Some(r) = r else {
            self.state
                .borrow_mut()
                .log(format!("list move unsupported {from}->{to}"));
            return false;
        };
        let accepted = (r.can_move)(from, to);
        if accepted < 0 {
            self.state
                .borrow_mut()
                .log(format!("list move denied {from}->{to}"));
            return false;
        }
        (r.move_row)(from, accepted as usize);
        self.state
            .borrow_mut()
            .log(format!("list move {from}->{accepted}"));
        true
    }

    /// The tree's direct children of `parent` (`None` = the root level), as tokens, read
    /// straight from the injected `TreeSource` (docs/tree.md).
    pub fn tree_children(&self, host: MockHandle, parent: Option<u64>) -> Vec<u64> {
        let fns = self
            .state
            .borrow()
            .tree_sources
            .get(&host.0)
            .map(|s| (s.children_len.clone(), s.child_token.clone()));
        let Some((len, tok)) = fns else {
            return Vec::new();
        };
        (0..len(parent)).map(|i| tok(parent, i)).collect()
    }

    /// Whether this token can hold children (draws a disclosure), per the injected source.
    pub fn tree_expandable(&self, host: MockHandle, token: u64) -> bool {
        let f = self
            .state
            .borrow()
            .tree_sources
            .get(&host.0)
            .map(|s| s.expandable.clone());
        f.map(|f| f(token)).unwrap_or(false)
    }

    /// The row's type-ahead string, per the injected source.
    pub fn tree_type_text(&self, host: MockHandle, token: u64) -> String {
        let f = self
            .state
            .borrow()
            .tree_sources
            .get(&host.0)
            .map(|s| s.type_select_text.clone());
        f.map(|f| f(token)).unwrap_or_default()
    }

    /// Simulate the native tree binding `token`'s row into a physical `cell`: build on first
    /// use, rebind (slot-write) on recycle, exactly like [`Self::list_bind`]. (The source Rc
    /// is cloned out before the call so the re-entrant work holds no MockState borrow.)
    pub fn tree_bind(&self, host: MockHandle, token: u64, cell: MockHandle) {
        let f = self
            .state
            .borrow()
            .tree_sources
            .get(&host.0)
            .map(|s| s.bind_row.clone());
        if let Some(f) = f {
            f(token, cell.0 as RawHandle);
        }
    }

    /// Consult the tree's move guard the way a native drag-validate hook would. `None` when
    /// the tree is not movable (no `.movable()`).
    pub fn tree_can_move(
        &self,
        host: MockHandle,
        token: u64,
        parent: Option<u64>,
        index: Option<usize>,
    ) -> Option<day_spec::MoveVerdict> {
        let f = self
            .state
            .borrow()
            .tree_sources
            .get(&host.0)
            .and_then(|s| s.moves.as_ref().map(|m| m.can_move.clone()));
        f.map(|f| f(token, parent, index))
    }

    /// Simulate a native tree drop: consult the guard, commit on accept (deferring the app's
    /// `on_move`, exactly as a native backend would). Returns whether the move committed.
    pub fn tree_move(
        &self,
        host: MockHandle,
        token: u64,
        parent: Option<u64>,
        index: Option<usize>,
    ) -> bool {
        let m = self
            .state
            .borrow()
            .tree_sources
            .get(&host.0)
            .and_then(|s| s.moves.clone());
        let Some(m) = m else {
            self.state
                .borrow_mut()
                .log(format!("tree move unsupported {token}"));
            return false;
        };
        if (m.can_move)(token, parent, index) == day_spec::MoveVerdict::Deny {
            self.state
                .borrow_mut()
                .log(format!("tree move denied {token}"));
            return false;
        }
        (m.move_node)(token, parent, index);
        self.state
            .borrow_mut()
            .log(format!("tree move {token} -> {parent:?}@{index:?}"));
        true
    }

    /// Inject a native event through the real sink (as the toolkit trampoline would).
    pub fn emit(&self, node: NodeId, event: Event) {
        let sink = self.state.borrow().sink.clone();
        match sink {
            Some(sink) => sink(node, event),
            None => panic!("day-mock: no event sink installed"),
        }
    }

    /// Press the menu button with handle `button` as a toolkit does (docs/menus.md "Menu
    /// buttons"): ask its provider, then answer the items the toolkit would show, or `None`
    /// when the menu is empty or the provider removed the button
    /// ([`day_spec::resolve_button_menu`]). The state borrow is released while app code runs.
    pub fn press_menu_button(&self, button: u64) -> Option<Vec<day_spec::MenuItem>> {
        let provider = self.state.borrow().button_menus.get(&button).cloned()?;
        day_spec::resolve_button_menu(&provider, || {
            self.state.borrow().button_menus.contains_key(&button)
        })
    }

    /// The share choosers presented so far, oldest first, with the anchor's handle.
    pub fn shares(&self) -> Vec<(day_spec::share::ShareSpec, Option<u64>)> {
        self.state.borrow().shares.clone()
    }

    /// Whether day-core has the system back armed for the app's handlers (docs/navigation.md
    /// "Handling the system Back").
    pub fn system_back_armed(&self) -> bool {
        self.state.borrow().system_back
    }

    /// Choose app action `index` in the last share chooser, as a person tapping it would: the
    /// choice arrives as the action's `Event::MenuAction`. False if there is no such action.
    pub fn choose_share_action(&self, index: usize) -> bool {
        let id = self
            .state
            .borrow()
            .shares
            .last()
            .and_then(|(spec, _)| spec.actions.get(index))
            .map(|a| a.id);
        match id {
            Some(id) => {
                self.emit(day_spec::WINDOW_NODE, day_spec::Event::MenuAction(id));
                true
            }
            None => false,
        }
    }

    // --- secondary windows (docs/windows.md) -------------------------------------------

    /// Make `Cap::ToolbarSearch` answer `Unsupported`, as a phone's action bar does.
    pub fn set_no_toolbar_search(&self, v: bool) {
        self.state.borrow_mut().no_toolbar_search = v;
    }

    /// Realize list items natively (see `MockState::native_list_items`).
    pub fn set_native_list_items(&self, v: bool) {
        self.state.borrow_mut().native_list_items = v;
    }

    /// Make the toolkit decline (or accept again) toolbar edits.
    pub fn set_decline_toolbar_edits(&self, v: bool) {
        self.state.borrow_mut().decline_toolbar_edits = v;
    }

    /// Every window-toolbar edit applied so far, oldest first.
    pub fn toolbar_edits(&self) -> Vec<Vec<day_spec::ToolbarOp>> {
        self.state.borrow().toolbar_edits.clone()
    }

    /// The window toolbar as the backend holds it now: every edit and patch applied.
    pub fn toolbar_items(&self) -> Vec<day_spec::ToolbarItem> {
        self.state.borrow().toolbar.items().to_vec()
    }

    /// Every targeted toolbar patch applied so far, oldest first.
    pub fn toolbar_patches(&self) -> Vec<day_spec::ToolbarPatch> {
        self.state.borrow().toolbar_patches.clone()
    }

    /// The secondary windows opened so far (closed ones stay listed with `open: false`).
    pub fn windows(&self) -> Vec<MockWindow> {
        self.state.borrow().windows.clone()
    }

    /// The Dock menu's item titles as last installed (docs/menus.md "Dock menu").
    pub fn dock_menu(&self) -> Vec<String> {
        self.state.borrow().dock_menu.clone()
    }

    /// Every `apply_window` change so far, oldest first, keyed by content-container handle.
    pub fn window_changes(&self) -> Vec<(u64, day_spec::WindowChange)> {
        self.state.borrow().window_changes.clone()
    }

    /// The status items as last applied.
    pub fn status_items(&self) -> Vec<day_spec::StatusItemSpec> {
        self.state.borrow().status_items.clone()
    }

    /// Whether day-core last asked the platform to keep running with no window.
    pub fn keep_running(&self) -> bool {
        self.state.borrow().keep_running
    }

    /// Whether the widget at `handle` is a window drag region.
    pub fn is_drag_region(&self, handle: u64) -> bool {
        self.state.borrow().drag_regions.contains(&handle)
    }

    /// Make the mock platform record `WindowChange::State` requests without completing them.
    pub fn set_decline_window_states(&self, v: bool) {
        self.state.borrow_mut().decline_window_states = v;
    }

    /// Model the user flipping the system's reduce-motion setting (docs/accessibility.md). The
    /// test then calls `day_core::note_motion_changed()`, which is the backend observer's job.
    pub fn set_reduce_motion(&self, v: bool) {
        self.state.borrow_mut().reduce_motion = v;
    }

    /// Make a secure flip rebuild the text field under a new handle, the harness for the
    /// toolkits whose secure field is its own native class (docs/textfield.md).
    pub fn set_secure_class_swap(&self, v: bool) {
        self.state.borrow_mut().secure_class_swap = v;
    }

    /// Make `open_window` answer `Unsupported`, the cover-fallback test harness.
    pub fn set_no_multi_window(&self, v: bool) {
        self.state.borrow_mut().no_multi_window = v;
    }

    /// Make `Cap::NavSplit` answer `Native`, the harness for a nav host that presents as split
    /// panes and re-presents on a size-class change (docs/size-classes.md). Unlike the window
    /// toggles this is read during the build, so set it before launching.
    pub fn set_nav_split(&self, v: bool) {
        self.state.borrow_mut().nav_split = v;
    }

    /// Retain native navigation despite a reordering declaration, independently of lists.
    pub fn set_no_nav_reorder(&self, v: bool) {
        self.state.borrow_mut().no_nav_reorder = v;
    }

    /// Answer `Cap::NavReorder` as `Native`: the sidebar drags its own rows.
    pub fn set_native_nav_reorder(&self, v: bool) {
        self.state.borrow_mut().native_nav_reorder = v;
    }

    /// Make `Cap::NavTabs` answer `Unsupported`, modeling a toolkit without tab chrome.
    pub fn set_no_nav_tabs(&self, v: bool) {
        self.state.borrow_mut().no_nav_tabs = v;
    }

    /// Model a desktop toolkit: `Cap::NavTabs` stays on (a pinned tab bar still draws) but
    /// `Cap::NavTabsAdaptive` answers `Unsupported`, so an `Automatic` nav host collapses a
    /// narrow window to a stack rather than growing a tab bar (docs/navigation.md). Read during
    /// the build, so set it before launching.
    pub fn set_desktop_idiom(&self, v: bool) {
        self.state.borrow_mut().desktop_idiom = v;
    }

    /// What `Cap::NavContentList` answers (docs/navigation.md): the content-list pane
    /// harness. `Native` = persistent pane, `Emulated` = merges into the collapsed stack,
    /// `Unsupported` (the default) = the nav host composes. Read during the build.
    pub fn set_nav_content_list(&self, v: day_spec::Support) {
        self.state.borrow_mut().nav_content_list = v;
    }

    /// Make `open_window` answer `Pending`, the async-completion test harness. Finish an
    /// open with [`Self::complete_window`] + `day_core::finish_window_open`.
    pub fn set_pending_windows(&self, v: bool) {
        self.state.borrow_mut().pending_windows = v;
    }

    /// Materialize the parked `Pending` open for `node`: registers the content-container
    /// widget + window record (as the native side finishing creation would) and returns
    /// the raw handle to pass to `day_core::finish_window_open`. `None` = no such pending
    /// open.
    pub fn complete_window(&self, node: NodeId, size: Size) -> Option<day_spec::RawHandle> {
        let mut s = self.state.borrow_mut();
        let i = s.pending_opens.iter().position(|(n, _, _)| *n == node)?;
        let (node, title, kind) = s.pending_opens.remove(i);
        s.next += 1;
        let h = s.next;
        s.widgets.insert(
            h,
            MockWidget {
                kind: kinds::CONTAINER,
                node: node.0,
                enabled: true,
                ..Default::default()
            },
        );
        s.windows.push(MockWindow {
            handle: h,
            node,
            title,
            size,
            kind,
            tabbing: day_spec::WindowTabbing::Automatic,
            open: true,
            focused: false,
            fit_size: None,
        });
        s.log(format!("window_ready #{h} {}", fmt_size(size)));
        Some(h as day_spec::RawHandle)
    }

    /// Resize a secondary window (as a native drag would): updates the record and reports
    /// `WindowResized` to the window's root.
    pub fn resize_window(&self, node: NodeId, size: Size) {
        {
            let mut s = self.state.borrow_mut();
            if let Some(w) = s.windows.iter_mut().find(|w| w.node == node) {
                w.size = size;
            }
        }
        self.emit(node, Event::WindowResized(size));
    }

    /// Model a native dismissal animation: retain the window until the test confirms it
    /// with [`Self::close_window_natively`].
    pub fn set_defer_window_close(&self, defer: bool) {
        self.state.borrow_mut().defer_window_close = defer;
    }

    /// Close a secondary window from the native side (the title-bar path): marks it closed
    /// and reports `WindowClosed` to the window's root.
    pub fn close_window_natively(&self, node: NodeId) {
        {
            let mut s = self.state.borrow_mut();
            if let Some(w) = s.windows.iter_mut().find(|w| w.node == node) {
                w.open = false;
            }
        }
        self.emit(node, Event::WindowClosed);
    }

    /// The current op-log length; pair with [`Self::log_since`] to scope assertions.
    pub fn log_len(&self) -> usize {
        self.state.borrow().log.len()
    }

    /// The op-log entries recorded after `mark` (from [`Self::log_len`]).
    pub fn log_since(&self, mark: usize) -> Vec<String> {
        self.state.borrow().log[mark..].to_vec()
    }
}

fn fmt_size(s: Size) -> String {
    format!("{}x{}", s.width, s.height)
}
fn fmt_rect(r: Rect) -> String {
    format!(
        "({},{} {}x{})",
        r.origin.x, r.origin.y, r.size.width, r.size.height
    )
}

/// Deterministic text metrics: 8pt per char, 16pt line height, greedy wrap.
/// The mock's line box: one line of text is this tall, whatever it says.
pub const MOCK_LINE_H: f64 = 16.0;

/// The synthetic pixel size every mock decode reports (docs/images.md): deterministic, so a
/// test can predict the frame an `image(bytes)` measures to, exactly like the synthetic text
/// metrics above.
pub const MOCK_IMAGE_W: f64 = 64.0;
pub const MOCK_IMAGE_H: f64 = 48.0;
/// What the mock claims it can encode: the two formats every real backend also manages, so a
/// test that asserts a WebP refusal exercises the same path a desktop backend takes.
pub const MOCK_ENCODE_FORMATS: [day_spec::ImageFormat; 2] =
    [day_spec::ImageFormat::Png, day_spec::ImageFormat::Jpeg];

/// How the probe spells an image source in the log and in `WidgetProbe::text`: the name for a
/// staged asset, `bytes:<len>` for a buffer, `bitmap:<id>` for a shared decode.
fn describe_image_source(source: &day_spec::ImageSource) -> String {
    match source {
        day_spec::ImageSource::Named(name) => name.clone(),
        day_spec::ImageSource::Bytes(b) => format!("bytes:{}", b.len()),
        day_spec::ImageSource::Decoded(id) => format!("bitmap:{}", id.0),
    }
}

pub fn text_size(text: &str, proposal: Proposal, wraps: bool, scale: f64) -> Size {
    let needed = 8.0 * scale * text.chars().count() as f64;
    let line = MOCK_LINE_H * scale;
    match (proposal.width, wraps) {
        (Some(w), true) if needed > w && w > 0.0 => {
            let lines = (needed / w).ceil();
            Size::new(w, line * lines)
        }
        _ => Size::new(needed, line),
    }
}

/// A semantic style's size against `Body`, the mock's 8 × 16 cell: Apple's default point sizes
/// (Body 17), so a large-title row measures taller than a caption row the way it does natively.
/// `Body` and `Headline` stay exactly 1.0, the size every older mock expectation assumes.
pub fn font_scale(style: Font) -> f64 {
    let points = match style {
        Font::LargeTitle => 34.0,
        Font::Title => 28.0,
        Font::Title2 => 22.0,
        Font::Title3 => 20.0,
        Font::Headline | Font::Body => 17.0,
        Font::Subheadline => 15.0,
        Font::Callout => 16.0,
        Font::Footnote => 13.0,
        Font::Caption => 12.0,
        Font::Caption2 => 11.0,
        Font::System(pt) | Font::Custom(_, pt) => pt,
    };
    points / 17.0
}

impl MockToolkit {
    /// Raise a completion through the installed sink (docs/images.md).
    ///
    /// Clones the `Rc` rather than taking the sink, so a completion raised while another event
    /// is being dispatched still reaches day-core. A missing sink is logged, not swallowed: a
    /// dropped completion leaves a future parked forever, which reads as a hang rather than a
    /// failure.
    fn raise(&self, event: Event) {
        let sink = self.state.borrow().sink.clone();
        match sink {
            Some(sink) => sink(NodeId(0), event),
            None => self
                .state
                .borrow_mut()
                .log(format!("dropped {event:?}: no event sink installed")),
        }
    }
}

impl Toolkit for MockToolkit {
    fn system_color(&mut self, role: day_spec::SystemColor) -> day_spec::Color {
        let colors = self.state.borrow().system_colors;
        colors
            .map(|colors| colors[role as usize])
            .unwrap_or_else(|| role.fallback(self.dark_mode()))
    }

    type Handle = MockHandle;

    fn capability(&self, cap: Cap) -> Support {
        match cap {
            Cap::Snapshot => Support::Native,
            // With native behavior on (the conformance harness), the mock stands in for a
            // toolkit with a toolbar and dialogs: it records the toolbar edits and the
            // presentations, and answers `dismiss`. Off, unit tests keep the toolbar-less
            // placement they assert (an `Automatic` search stays inline).
            Cap::Toolbar | Cap::Dialogs if VIEWPORT_ROWS.with(|r| r.get()) > 0 => Support::Native,
            // Native-behavior mode binds its bounded viewport pool to new rows on scroll.
            Cap::ListRecycling if VIEWPORT_ROWS.with(|r| r.get()) > 0 => Support::Native,
            // Records every toolbar edit and patch, search item included (probe-visible). The
            // mock still has no `Cap::Toolbar`, so an `Automatic` search stays inline.
            Cap::ToolbarSearch => {
                if self.state.borrow().no_toolbar_search {
                    Support::Unsupported
                } else {
                    Support::Native
                }
            }
            // The mock decodes by reading magic numbers and encodes a matching signature
            // (docs/images.md): no pixels, but the whole request → completion → release path a
            // test needs. `Cap::ImageProperties` stays Unsupported in the default arm: the
            // mock reads no metadata, and pretending otherwise would let a test pass against a
            // capability no backend answers this way.
            Cap::ImageDecode | Cap::ImageEncode => Support::Native,
            // A rendered bitmap is a synthetic entry in the same table a decode fills, so app
            // logic around export (menus, save flows) runs headless. PDF stays Unsupported, the
            // answer three real toolkits give, so the disabled path is the one a test sees.
            Cap::CanvasBitmap => Support::Native,
            // Records the shape per widget (probe-visible), so a test can assert it.
            Cap::Cursor => Support::Native,
            // Records every window change and Dock menu and completes state requests the way a
            // platform reports them (`apply_window` below), so the two-way state signal and the
            // menu lowering are testable headless.
            // OS window tabs follow the test's own switch (`MockState::native_window_tabs`),
            // so a case that `requires` them is skipped unless a test turned them on.
            Cap::ListItem => {
                if self.state.borrow().native_list_items {
                    Support::Native
                } else {
                    Support::Unsupported
                }
            }
            Cap::WindowTabbing => {
                if self.state.borrow().native_window_tabs {
                    Support::Native
                } else {
                    Support::Unsupported
                }
            }
            Cap::WindowStates
            | Cap::WindowFullscreen
            | Cap::ContentProtection
            | Cap::DockMenu
            | Cap::DragRegion
            | Cap::StatusItem
            | Cap::AppProgress
            | Cap::DockVisibility
            | Cap::Monitors
            | Cap::DynamicShortcuts
            | Cap::WindowGeometry
            | Cap::WindowPosition
            | Cap::WindowLevel
            | Cap::WindowAppearance
            | Cap::RequestAttention => Support::Native,
            // A fixed two-family list (`font_families` below), composed, not read.
            Cap::FontList => Support::Emulated,
            Cap::Announce => Support::Native,
            Cap::ReduceMotion => Support::Native,
            // The mock answers `first_baseline` from its synthetic metrics (see below).
            Cap::BaselineAlignment => Support::Native,
            // The mock records the text-area attributes (probe-visible), so it "supports" all three.
            Cap::TextEditable | Cap::TextSelectable | Cap::TextSpellCheck => Support::Native,
            // Styled runs land in `WidgetProbe::runs`, which is what a test asserts on
            // (docs/text-runs.md). Activating a link is not modeled (nothing in the mock
            // hit-tests text), so `Cap::TextLinks` stays Unsupported in the default arm; a test
            // that wants the rail emits `Event::LinkActivated` itself.
            Cap::TextRuns => Support::Native,
            // The mock "runs" backend-executed animation by recording the intent (probe-visible).
            Cap::Animation => Support::Native,
            // Covers "present" by recording the patch (probe-visible); tests emit the
            // FrameChanged size report themselves, as the native surface would.
            Cap::Cover => Support::Native,
            // The status bar "hides" by recording the duty call (probe-visible).
            Cap::StatusBarHidden => Support::Native,
            // The probe drives the whole reorder sequence, guard then commit (`list_can_move`/
            // `list_move`).
            Cap::ListReorder => Support::Native,
            Cap::NavReorder => {
                let s = self.state.borrow();
                if s.no_nav_reorder {
                    Support::Unsupported
                } else if s.native_nav_reorder {
                    Support::Native
                } else {
                    Support::Emulated
                }
            }
            // The probe drives every tree duty (`tree_children`/`tree_bind`/`tree_move`).
            Cap::Tree | Cap::TreeSections if self.state.borrow().emulated_trees => {
                Support::Emulated
            }
            Cap::Tree | Cap::TreeSections | Cap::TreeMove => Support::Native,
            // Off by default: the mock models a phone, so a nav host stacks unless a test opts in.
            // A mock that can split can also re-present: it records the patch, which is exactly
            // what the morph tests assert against.
            Cap::NavSplit | Cap::NavRepresent => {
                if self.state.borrow().nav_split {
                    Support::Native
                } else {
                    Support::Unsupported
                }
            }
            // Unsupported by default (the composed path); a test opts into the pane shapes
            // (docs/navigation.md) with [`MockProbe::set_nav_content_list`].
            Cap::NavContentList => self.state.borrow().nav_content_list,
            // On by default (docs/navigation.md): the mock models a phone, and a phone has a tab
            // bar. A test opts out to exercise the degradation path, where `Automatic` falls back
            // to the sidebar resolver.
            Cap::NavTabs => {
                if self.state.borrow().no_nav_tabs {
                    Support::Unsupported
                } else {
                    Support::Native
                }
            }
            // Separate from `NavTabs`: a desktop draws a pinned tab bar but never adapts into one.
            Cap::NavTabsAdaptive => {
                let st = self.state.borrow();
                if st.no_nav_tabs || st.desktop_idiom {
                    Support::Unsupported
                } else {
                    Support::Native
                }
            }
            // Real (recorded) windows unless the test opted into the cover-fallback tier.
            Cap::MultiWindow => {
                if self.state.borrow().no_multi_window {
                    Support::Unsupported
                } else {
                    Support::Native
                }
            }
            _ => Support::Unsupported,
        }
    }

    fn realize(&mut self, kind: PieceKind, props: &dyn Any, id: NodeId) -> MockHandle {
        let mut s = self.state.borrow_mut();
        s.next += 1;
        let h = s.next;
        let mut w = MockWidget {
            kind,
            node: id.0,
            enabled: true,
            ..Default::default()
        };
        let mut detail = String::new();
        if let Some(p) = props.downcast_ref::<CoverProps>() {
            w.half = p.half;
            detail = format!(" sheet={} half={}", p.sheet, p.half);
        } else if let Some(p) = props.downcast_ref::<ListItemProps>() {
            w.text = p.title.clone();
            w.flag = p.checked;
            detail = format!(
                " title={:?} subtitle={:?} detail={:?} icon={:?} checked={}",
                p.title, p.subtitle, p.detail, p.icon, p.checked
            );
        } else if let Some(p) = props.downcast_ref::<LabelProps>() {
            w.text = p.text.clone();
            w.flag = p.wraps;
            w.font = Some(p.font);
            w.runs = p.runs.clone();
            detail = format!(" text={:?}", p.text);
        } else if let Some(p) = props.downcast_ref::<ButtonProps>() {
            w.text = p.title.clone();
            w.enabled = p.enabled;
            w.selected = p.selected;
            detail = format!(" title={:?}", p.title);
        } else if let Some(p) = props.downcast_ref::<ToggleProps>() {
            w.flag = p.on;
            w.enabled = p.enabled;
        } else if let Some(p) = props.downcast_ref::<SliderProps>() {
            w.value = p.value;
            w.enabled = p.enabled;
        } else if let Some(p) = props.downcast_ref::<TextFieldProps>() {
            w.text = p.text.clone();
            w.placeholder = p.placeholder.clone();
            w.enabled = p.enabled;
        } else if let Some(p) = props.downcast_ref::<CanvasProps>() {
            w.ops = p.ops.clone();
        } else if let Some(p) = props.downcast_ref::<ContainerProps>() {
            w.background = p.background;
            w.corner_radius = p.corner_radius;
            w.clips = p.clips;
            w.surface_role = p.role;
            if p.background.is_some() || p.corner_radius > 0.0 || p.clips {
                detail = format!(
                    " bg={:?} radius={} clips={}",
                    p.background, p.corner_radius, p.clips
                );
            }
        } else if let Some(p) = props.downcast_ref::<ImageProps>() {
            // The probe records which pixels were asked for, so a test can assert that a name
            // resolved, that bytes arrived, or that two nodes share one decode (docs/images.md).
            w.text = describe_image_source(&p.source);
            // Image probes expose template mode for artwork/glyph regression tests.
            w.flag = p.template;
            detail = format!(" source={}", w.text);
        } else if let Some(p) = props.downcast_ref::<ProgressProps>() {
            // `flag` records indeterminate-ness; `value` the determinate fraction.
            w.flag = p.value.is_none();
            w.value = p.value.unwrap_or(0.0);
            detail = format!(" value={:?}", p.value);
        } else if let Some(p) = props.downcast_ref::<NavProps>() {
            w.text = p.title.clone();
            w.flag = p.presentation.is_split();
            w.presentation = Some(p.presentation);
            // The content-list pane's realize-time state, so a test can see the shape the host
            // was built with; the pane's initial visibility is settled here, not by a patch.
            detail = match p.list_width {
                Some(w) => format!(
                    " title={:?} presentation={:?} list_width={w} list_visible={}",
                    p.title, p.presentation, p.list_visible
                ),
                None => format!(" title={:?} presentation={:?}", p.title, p.presentation),
            };
        } else if let Some(p) = props.downcast_ref::<NavPageProps>() {
            w.text = p.title.clone();
            // The page's pane, not the presentation drawing it: a nav host's list page reads
            // `sidebar` whether the host is split or stacked (docs/size-classes.md).
            w.flag = p.pane == day_spec::props::Pane::Sidebar;
            detail = format!(" title={:?} pane={:?}", p.title, p.pane);
        } else if let Some(p) = props.downcast_ref::<NavMenuProps>() {
            w.text = p.items.join("|");
            w.value = p.selected.map(|i| i as f64).unwrap_or(-1.0);
            detail = format!(
                " items={:?} selected={:?} movable={:?}",
                p.items, p.selected, p.movable
            );
            // Only a regrouping sidebar carries these, so other logs read as they always have.
            if p.regroup {
                detail.push_str(&format!(" regroup sorted={:?}", p.sorted));
            }
        } else if let Some(p) = props.downcast_ref::<PickerProps>() {
            w.text = p.options.join("|");
            w.value = p.selected as f64;
            w.enabled = p.enabled;
            detail = format!(" options={:?} selected={}", p.options, p.selected);
        } else if let Some(p) = props.downcast_ref::<TextAreaProps>() {
            w.text = p.text.clone();
            w.placeholder = p.placeholder.clone();
            w.editable = p.editable;
            w.selectable = p.selectable;
            w.spellcheck = p.spellcheck;
            detail = format!(
                " lines={}..{} editable={} selectable={} spellcheck={}",
                p.min_lines, p.max_lines, p.editable, p.selectable, p.spellcheck
            );
        }
        s.log(format!("realize {kind} #{h}{detail}"));
        s.widgets.insert(h, w);
        MockHandle(h)
    }

    fn update(
        &mut self,
        h: &MockHandle,
        kind: PieceKind,
        patch: &dyn Any,
        anim: Option<&AnimSpec>,
    ) {
        let mut s = self.state.borrow_mut();
        // Ask the installed describers first; the borrow has to end before `widgets` is taken
        // mutably below.
        let described = s.describers.iter().find_map(|d| d(patch));
        let detail;
        // A cover shown or hidden, for the native-behavior mode to report (see `NATIVE_EVENTS`).
        // (node, shown, half)
        let mut cover_shown: Option<(u64, bool, bool)> = None;
        {
            let w = s.widgets.get_mut(&h.0).expect("update on unknown widget");
            if anim.is_some() {
                w.last_anim = anim.copied();
            }
            detail = if let Some(p) = patch.downcast_ref::<ImagePatch>() {
                match p {
                    // The probe's `text` is which pixels the view draws, so a test can assert a
                    // source swap landed in the same view (docs/images.md).
                    ImagePatch::Source(s) => {
                        w.text = describe_image_source(s);
                        format!("source={}", w.text)
                    }
                    ImagePatch::Tint(c) => format!("tint={c:?}"),
                }
            } else if let Some(p) = patch.downcast_ref::<LabelPatch>() {
                match p {
                    LabelPatch::Text(t) => {
                        w.text = t.clone();
                        format!("text={t:?}")
                    }
                    LabelPatch::Color(_) => "color".into(),
                    LabelPatch::Font(f) => {
                        w.font = Some(*f);
                        "font".into()
                    }
                    LabelPatch::Runs(text, runs) => {
                        w.text = text.clone();
                        w.runs = runs.clone();
                        format!("runs={}", runs.len())
                    }
                }
            } else if let Some(p) = patch.downcast_ref::<ButtonPatch>() {
                match p {
                    ButtonPatch::Content(c) => {
                        w.text = c.title.clone();
                        format!("content={c:?}")
                    }
                    ButtonPatch::Title(t) => {
                        w.text = t.clone();
                        format!("title={t:?}")
                    }
                    ButtonPatch::Enabled(e) => {
                        w.enabled = *e;
                        format!("enabled={e}")
                    }
                    ButtonPatch::Selected(on) => {
                        w.selected = *on;
                        format!("selected={on}")
                    }
                    // Recorded so a walkthrough can see a reactive tint change, but the mock
                    // has no pixels to apply it to.
                    ButtonPatch::Style(s) => format!("style={s:?}"),
                }
            } else if let Some(p) = patch.downcast_ref::<TogglePatch>() {
                match p {
                    TogglePatch::On(v) => {
                        w.flag = *v;
                        format!("on={v}")
                    }
                    TogglePatch::Enabled(e) => {
                        w.enabled = *e;
                        format!("enabled={e}")
                    }
                }
            } else if let Some(p) = patch.downcast_ref::<SliderPatch>() {
                match p {
                    SliderPatch::Value(v) => {
                        w.value = *v;
                        format!("value={v}")
                    }
                    SliderPatch::Enabled(e) => {
                        w.enabled = *e;
                        format!("enabled={e}")
                    }
                }
            } else if let Some(p) = patch.downcast_ref::<TextFieldPatch>() {
                match p {
                    TextFieldPatch::Text { text, from_native } => {
                        if !*from_native {
                            w.text = text.clone();
                        }
                        format!("text={text:?} from_native={from_native}")
                    }
                    TextFieldPatch::Placeholder(t) => {
                        w.placeholder = t.clone();
                        format!("placeholder={t:?}")
                    }
                    TextFieldPatch::Enabled(e) => {
                        w.enabled = *e;
                        format!("enabled={e}")
                    }
                    TextFieldPatch::Select(r) => {
                        let r = r.clamped(&w.text);
                        w.selection = Some(r);
                        format!("select={}..{}", r.start, r.end)
                    }
                }
            } else if let Some(p) = patch.downcast_ref::<CanvasProps>() {
                w.ops = p.ops.clone();
                format!("canvas ops={}", w.ops.len())
            } else if let Some(ProgressPatch::Value(v)) = patch.downcast_ref::<ProgressPatch>() {
                w.flag = v.is_none();
                w.value = v.unwrap_or(0.0);
                format!("value={v:?}")
            } else if let Some(pp) = patch.downcast_ref::<PickerPatch>() {
                let Some(w) = s.widgets.get_mut(&h.0) else {
                    return;
                };
                match pp {
                    PickerPatch::Selected(i) => {
                        w.value = *i as f64;
                        format!("picker.selected {i}")
                    }
                    PickerPatch::Options(opts) => {
                        w.text = opts.join("|");
                        format!("picker.options {opts:?}")
                    }
                    PickerPatch::Enabled(e) => {
                        w.enabled = *e;
                        format!("picker.enabled {e}")
                    }
                }
            } else if let Some(tp) = patch.downcast_ref::<TextAreaPatch>() {
                if let Some(w) = s.widgets.get_mut(&h.0) {
                    match tp {
                        TextAreaPatch::SetText(t) => w.text = t.clone(),
                        TextAreaPatch::SetEditable(v) => w.editable = *v,
                        TextAreaPatch::SetSelectable(v) => w.selectable = *v,
                        TextAreaPatch::SetSpellCheck(v) => w.spellcheck = *v,
                    }
                }
                format!("textarea.patch {tp:?}")
            } else if let Some(p) = patch.downcast_ref::<ListItemPatch>() {
                match p {
                    ListItemPatch::Title(t) => w.text = t.clone(),
                    ListItemPatch::Checked(on) => w.flag = *on,
                    _ => {}
                }
                format!("list_item {p:?}")
            } else if let Some(p) = patch.downcast_ref::<NavMenuPatch>() {
                match p {
                    NavMenuPatch::IconProgress(values) => format!("menu icon_progress={values:?}"),
                    NavMenuPatch::Selected(sel) => {
                        w.value = sel.map(|i| i as f64).unwrap_or(-1.0);
                        format!("menu selected={sel:?}")
                    }
                    // Data-driven rows: `text` mirrors the joined labels for tests to assert.
                    NavMenuPatch::Items {
                        items,
                        selected,
                        badges,
                        rows_changed,
                        movable,
                        sorted,
                        ..
                    } => {
                        w.text = items.join("|");
                        w.value = selected.map(|i| i as f64).unwrap_or(-1.0);
                        let mut line = format!(
                            "menu items={items:?} selected={selected:?} badges={badges:?} \
                             rows_changed={rows_changed:?} movable={movable:?}"
                        );
                        if !sorted.is_empty() {
                            line.push_str(&format!(" sorted={sorted:?}"));
                        }
                        line
                    }
                }
            } else if let Some(p) = patch.downcast_ref::<NavPatch>() {
                match p {
                    NavPatch::Pushed { title, .. } => {
                        w.text = title.clone();
                        w.nav_depth += 1;
                        format!("nav pushed title={title:?}")
                    }
                    NavPatch::Popped => {
                        w.nav_depth = w.nav_depth.saturating_sub(1);
                        "nav popped".into()
                    }
                    NavPatch::Title(t) => {
                        w.text = t.clone();
                        format!("nav title={t:?}")
                    }
                    // Probe-visible: tests assert the armed flag round-trips.
                    NavPatch::GuardTop(on) => {
                        w.flag = *on;
                        w.nav_guarded = *on;
                        format!("nav guard={on}")
                    }
                    // The host's presentation after a size-class change. `flag` tracks it the
                    // same way the initial `NavProps` did, so a walkthrough asserting the morph
                    // reads one field either side of it; `presentation` carries which of the
                    // four it actually is, which `flag` cannot say.
                    NavPatch::Presentation(p) => {
                        w.flag = p.is_split();
                        w.presentation = Some(*p);
                        format!("nav presentation={p:?}")
                    }
                    // Resident-page switch (docs/navigation.md). A stacked host never receives
                    // this (it gets `Pushed`/`Popped` instead), so recording it unconditionally
                    // is also what lets a test prove the pieces layer sent the right one.
                    NavPatch::Select(i) => {
                        w.selected_page = Some(*i);
                        w.value = *i as f64;
                        format!("nav select={i}")
                    }
                    // Content-list pane visibility / stack membership (docs/navigation.md).
                    // Logged only: mock answers `Cap::NavContentList` Unsupported, so the pieces
                    // layer composes and these arrive solely in tests that force the cap.
                    NavPatch::ListVisible(v) => format!("nav list visible={v}"),
                    NavPatch::Reorder(order) => format!("nav reorder {order:?}"),
                    NavPatch::ListInStack(v) => format!("nav list in-stack={v}"),
                }
            } else if let Some(p) = patch.downcast_ref::<CoverPatch>() {
                // `flag` records presented-ness (probe-visible). Tests emit the FrameChanged
                // size report and the `CoverHidden` event, as the native surface would.
                match p {
                    CoverPatch::Present {
                        background,
                        dismiss_disabled,
                    } => {
                        w.flag = true;
                        w.background = *background;
                        cover_shown = Some((w.node, true, w.half));
                        format!(
                            "cover present bg={background:?} dismiss_disabled={dismiss_disabled}"
                        )
                    }
                    CoverPatch::DismissDisabled(d) => format!("cover dismiss_disabled={d}"),
                    CoverPatch::Dismiss => {
                        w.flag = false;
                        cover_shown = Some((w.node, false, w.half));
                        "cover dismiss".into()
                    }
                }
            } else if let Some(ContainerPatch::Background(c)) =
                patch.downcast_ref::<ContainerPatch>()
            {
                w.background = *c;
                format!("bg={c:?}")
            } else if let Some(p) = patch.downcast_ref::<ListPatch>() {
                match p {
                    ListPatch::Reload => {
                        viewport_touch(h.0, |_| {});
                        "list reload".into()
                    }
                    ListPatch::Splice(deltas) => {
                        viewport_touch(h.0, |_| {});
                        format!("list splice {deltas:?}")
                    }
                    ListPatch::RowSizeInvalidated { cell, height } => {
                        CELL_HEIGHTS.with(|h| h.borrow_mut().insert(*cell as u64, *height));
                        format!("list row-size-invalidated {height}")
                    }
                    ListPatch::ScrollToEnd => {
                        // Record that the host was asked to follow its last row (probe-visible).
                        w.flag = true;
                        viewport_touch(h.0, |p| p.to_end = true);
                        "list scroll-to-end".into()
                    }
                    ListPatch::ScrollToRow(row) => {
                        let rows = VIEWPORT_ROWS.with(|r| r.get());
                        viewport_touch(h.0, |p| p.start = row.saturating_sub(rows / 2));
                        format!("list scroll-to-row {row}")
                    }
                    ListPatch::Selected(rows) => format!("list selected {rows:?}"),
                    ListPatch::Editing(on) => format!("list editing {on}"),
                }
            } else if let Some(p) = patch.downcast_ref::<TreePatch>() {
                match p {
                    TreePatch::Reload => {
                        viewport_touch(h.0, |_| {});
                        "tree reload".into()
                    }
                    TreePatch::Expand(tok, on) => {
                        let (tok, on) = (*tok, *on);
                        viewport_touch(h.0, |p| {
                            if on {
                                p.expanded.insert(tok);
                            } else {
                                p.expanded.remove(&tok);
                            }
                        });
                        format!("tree expand {tok} {on}")
                    }
                    TreePatch::Selected(toks) => format!("tree selected {toks:?}"),
                    TreePatch::Reveal(tok) => format!("tree reveal {tok}"),
                }
            } else {
                described.unwrap_or_else(|| "?".into())
            };
        }
        s.log(format!("update {kind} #{} {detail}", h.0));
        // What a native cover reports by itself: the size it gave the content, and that the
        // hide transition finished.
        if let (Some((node, shown, half)), Some(sink)) = (cover_shown, s.sink.clone())
            && VIEWPORT_ROWS.with(|r| r.get()) > 0
        {
            let event = if shown {
                // A half sheet is the bottom half of the window (docs/cover.md).
                let mut size = MOCK_WINDOW.with(|w| w.get());
                if half {
                    size.height = (size.height * 0.5).floor();
                }
                Event::FrameChanged(size)
            } else {
                Event::CoverHidden
            };
            NATIVE_EVENTS.with(|q| q.borrow_mut().push((sink, NodeId(node), event)));
        }
    }

    fn release(&mut self, h: MockHandle) {
        VIEWPORTS.with(|v| v.borrow_mut().remove(&h.0));
        let mut s = self.state.borrow_mut();
        s.widgets.remove(&h.0);
        s.context_menu_providers.remove(&h.0);
        s.button_menus.remove(&h.0);
        s.log(format!("release #{}", h.0));
    }

    fn insert(&mut self, parent: &MockHandle, child: &MockHandle, index: usize) {
        let mut s = self.state.borrow_mut();
        {
            let p = s
                .widgets
                .get_mut(&parent.0)
                .expect("insert into unknown parent");
            let idx = index.min(p.children.len());
            p.children.insert(idx, child.0);
        }
        s.log(format!(
            "insert #{} into #{} at {}",
            child.0, parent.0, index
        ));
    }

    fn remove(&mut self, parent: &MockHandle, child: &MockHandle) {
        let mut s = self.state.borrow_mut();
        {
            let p = s
                .widgets
                .get_mut(&parent.0)
                .expect("remove from unknown parent");
            p.children.retain(|&c| c != child.0);
        }
        s.log(format!("remove #{} from #{}", child.0, parent.0));
    }

    fn move_child(&mut self, parent: &MockHandle, child: &MockHandle, to: usize) {
        let mut s = self.state.borrow_mut();
        {
            let p = s
                .widgets
                .get_mut(&parent.0)
                .expect("move in unknown parent");
            p.children.retain(|&c| c != child.0);
            let idx = to.min(p.children.len());
            p.children.insert(idx, child.0);
        }
        s.log(format!("move #{} in #{} to {}", child.0, parent.0, to));
    }

    fn measure(&mut self, h: &MockHandle, kind: PieceKind, p: Proposal) -> Size {
        let mut s = self.state.borrow_mut();
        s.measure_calls += 1;
        let w = s.widgets.get(&h.0).cloned().unwrap_or_default();
        let size = match kind {
            kinds::LABEL => {
                let scale = w.font.map_or(1.0, |f| font_scale(f.style));
                let s = text_size(&w.text, p, w.flag, scale);
                Size::new(s.width.min(p.width.unwrap_or(s.width)), s.height)
            }
            kinds::BUTTON => {
                let t = text_size(&w.text, Proposal::UNCONSTRAINED, false, 1.0);
                Size::new(t.width + 16.0, 24.0)
            }
            kinds::TOGGLE => Size::new(51.0, 31.0),
            kinds::SLIDER => Size::new(p.width.unwrap_or(200.0), 24.0),
            kinds::TEXT_FIELD => Size::new(p.width.unwrap_or(200.0), 24.0),
            kinds::DIVIDER => Size::new(p.width.unwrap_or(0.0), 1.0),
            kinds::IMAGE => Size::new(32.0, 32.0),
            kinds::LIST_ITEM => Size::new(p.width.unwrap_or(200.0), 24.0),
            // Indeterminate spinner is a fixed square; determinate bar fills width.
            kinds::PROGRESS if w.flag => Size::new(20.0, 20.0),
            kinds::PROGRESS => Size::new(p.width.unwrap_or(200.0), 4.0),
            _ => Size::new(p.width.unwrap_or(10.0), p.height.unwrap_or(10.0)),
        };
        s.log(format!(
            "measure {kind} #{} {:?} -> {}",
            h.0,
            p.cache_key(),
            fmt_size(size)
        ));
        size
    }

    /// A synthetic first baseline (docs/baseline.md), modeling the one fact that matters for
    /// the layout math: text sits at different heights inside different widgets. The mock's
    /// line box is 16pt with a 12pt ascent, and a widget that frames its text (a field, a
    /// button) insets it, so a label beside a text field must drop by exactly that inset for
    /// the two to share a line. Widgets with no text report `None`.
    fn first_baseline(&mut self, h: &MockHandle, kind: PieceKind, size: Size) -> Option<f64> {
        const ASCENT: f64 = 12.0;
        let framed_inset = |box_h: f64| (box_h - MOCK_LINE_H) / 2.0 + ASCENT;
        let s = self.state.borrow();
        let w = s.widgets.get(&h.0).cloned().unwrap_or_default();
        match kind {
            kinds::LABEL => (!w.text.is_empty() || size.height > 0.0).then_some(ASCENT),
            kinds::BUTTON | kinds::TEXT_FIELD | kinds::TEXT_AREA => Some(framed_inset(size.height)),
            // No text, so no baseline; these are the children that keep centering.
            _ => None,
        }
    }

    fn set_frame(&mut self, h: &MockHandle, frame: Rect, anim: Option<&AnimSpec>) {
        let mut s = self.state.borrow_mut();
        if let Some(w) = s.widgets.get_mut(&h.0) {
            w.frame = frame;
            if anim.is_some() {
                w.last_anim = anim.copied();
            }
        }
        let a = if anim.is_some() { " animated" } else { "" };
        s.log(format!("set_frame #{} {}{}", h.0, fmt_rect(frame), a));
    }

    fn set_opacity(&mut self, h: &MockHandle, opacity: f64, anim: Option<&AnimSpec>) {
        let mut s = self.state.borrow_mut();
        if let Some(w) = s.widgets.get_mut(&h.0) {
            w.opacity = Some(opacity);
            if anim.is_some() {
                w.last_anim = anim.copied();
            }
        }
        let a = if anim.is_some() { " animated" } else { "" };
        s.log(format!("set_opacity #{} {:.3}{}", h.0, opacity, a));
    }

    fn set_transform(
        &mut self,
        h: &MockHandle,
        t: day_spec::Transform,
        _size: day_spec::Size,
        anim: Option<&AnimSpec>,
    ) {
        let mut s = self.state.borrow_mut();
        if let Some(w) = s.widgets.get_mut(&h.0) {
            w.transform = Some(t);
            if anim.is_some() {
                w.last_anim = anim.copied();
            }
        }
        let a = if anim.is_some() { " animated" } else { "" };
        s.log(format!(
            "set_transform #{} tx={:.1},ty={:.1},sx={:.2},sy={:.2},rot={:.1}{}",
            h.0, t.tx, t.ty, t.sx, t.sy, t.rotate_deg, a
        ));
    }

    fn set_selectable(&mut self, h: &MockHandle, selectable: bool) -> Option<MockHandle> {
        let mut s = self.state.borrow_mut();
        if let Some(w) = s.widgets.get_mut(&h.0) {
            w.selectable = selectable;
        }
        s.log(format!("set_selectable #{} {}", h.0, selectable));
        None
    }

    fn set_input_traits(
        &mut self,
        h: &MockHandle,
        traits: &day_spec::InputTraits,
    ) -> Option<MockHandle> {
        let mut s = self.state.borrow_mut();
        s.log(format!(
            "set_input_traits #{} secure={} read_only={} purpose={:?} submit={:?} max={:?}",
            h.0,
            traits.secure,
            traits.read_only,
            traits.purpose,
            traits.submit_label,
            traits.max_length
        ));
        let was_secure = s
            .widgets
            .get(&h.0)
            .and_then(|w| w.input_traits.as_ref())
            .is_some_and(|t| t.secure);
        if s.secure_class_swap && was_secure != traits.secure {
            // The class-swap toolkits: a new widget carries the old one's state and takes its
            // place among the parent's children; the old handle is gone.
            let mut w = s.widgets.remove(&h.0)?;
            w.input_traits = Some(traits.clone());
            s.next += 1;
            let new = s.next;
            for parent in s.widgets.values_mut() {
                for child in parent.children.iter_mut().filter(|c| **c == h.0) {
                    *child = new;
                }
            }
            s.widgets.insert(new, w);
            s.log(format!("swap #{} for #{}", h.0, new));
            return Some(MockHandle(new));
        }
        if let Some(w) = s.widgets.get_mut(&h.0) {
            w.input_traits = Some(traits.clone());
        }
        None
    }

    fn set_cursor(&mut self, h: &MockHandle, cursor: day_spec::Cursor) {
        let mut s = self.state.borrow_mut();
        if let Some(w) = s.widgets.get_mut(&h.0) {
            w.cursor = Some(cursor.clone());
        }
        s.log(format!("set_cursor #{} {}", h.0, cursor.css_name()));
    }

    fn scroll_bar_inset(&mut self, _h: &MockHandle, _vertical: bool) -> f64 {
        self.state.borrow().scroll_bar_inset
    }

    fn set_scroll_content(&mut self, h: &MockHandle, content: Size) {
        let mut s = self.state.borrow_mut();
        if let Some(w) = s.widgets.get_mut(&h.0) {
            w.scroll_content = content;
        }
        s.log(format!("set_scroll_content #{} {}", h.0, fmt_size(content)));
    }

    fn scroll_to(&mut self, h: &MockHandle, target: Rect, _animated: bool) {
        let mut s = self.state.borrow_mut();
        if let Some(w) = s.widgets.get_mut(&h.0) {
            // Minimal scroll that makes `target` (content space) visible, clamped to range.
            let (vw, vh) = (w.frame.size.width, w.frame.size.height);
            let (cw, ch) = (w.scroll_content.width, w.scroll_content.height);
            let clamp = |cur: f64, lo: f64, hi_edge: f64, view: f64, content: f64| -> f64 {
                let mut o = cur;
                if hi_edge > o + view {
                    o = hi_edge - view;
                }
                if lo < o {
                    o = lo;
                }
                o.clamp(0.0, (content - view).max(0.0))
            };
            let o = w.scroll_offset;
            w.scroll_offset = Point::new(
                clamp(
                    o.x,
                    target.origin.x,
                    target.origin.x + target.size.width,
                    vw,
                    cw,
                ),
                clamp(
                    o.y,
                    target.origin.y,
                    target.origin.y + target.size.height,
                    vh,
                    ch,
                ),
            );
        }
        s.log(format!("scroll_to #{} {}", h.0, fmt_rect(target)));
    }

    fn scroll_offset(&mut self, h: &MockHandle) -> Point {
        self.state
            .borrow()
            .widgets
            .get(&h.0)
            .map(|w| w.scroll_offset)
            .unwrap_or(Point::ZERO)
    }

    fn enable_gesture(&mut self, h: &MockHandle, _node: NodeId, kind: GestureKind) {
        self.state
            .borrow_mut()
            .log(format!("enable_gesture #{} {:?}", h.0, kind));
    }

    fn focus(&mut self, h: &MockHandle, node: NodeId, focused: bool) {
        let sink = {
            let mut st = self.state.borrow_mut();
            st.log(format!("focus #{} {}", h.0, focused));
            if let Some(w) = st.widgets.get_mut(&h.0) {
                w.focused = focused;
            }
            st.sink.clone()
        };
        // A native toolkit reports the focus it was given back as an event, which is what
        // day-core's probe mirrors (docs/focus.md); the mock does the same, after the borrow.
        if let Some(sink) = sink {
            sink(node, Event::FocusChanged(focused));
        }
    }

    fn set_event_sink(&mut self, sink: EventSink) {
        self.state.borrow_mut().sink = Some(Rc::from(sink));
    }

    fn attach_tree(&mut self, host: &MockHandle, source: day_spec::TreeSource) {
        if VIEWPORT_ROWS.with(|r| r.get()) > 0 {
            let (children_len, child_token) =
                (source.children_len.clone(), source.child_token.clone());
            // Depth first, into the disclosed rows only: the order a native tree shows.
            let visible = move |open: &std::collections::HashSet<u64>| {
                let mut out = Vec::new();
                fn walk(
                    parent: Option<u64>,
                    open: &std::collections::HashSet<u64>,
                    len: &dyn Fn(Option<u64>) -> usize,
                    tok: &dyn Fn(Option<u64>, usize) -> u64,
                    out: &mut Vec<u64>,
                ) {
                    for i in 0..len(parent) {
                        let t = tok(parent, i);
                        out.push(t);
                        if open.contains(&t) {
                            walk(Some(t), open, len, tok, out);
                        }
                    }
                }
                walk(None, open, &*children_len, &*child_token, &mut out);
                out
            };
            VIEWPORTS.with(|v| {
                v.borrow_mut().insert(
                    host.0,
                    Viewport {
                        visible: Rc::new(visible),
                        bind_row: source.bind_row.clone(),
                        recycle: source.recycle.clone(),
                        cell_height: None,
                        expanded: Default::default(),
                        start: 0,
                        to_end: false,
                        bound: 0,
                        dirty: true,
                    },
                )
            });
        }
        let mut s = self.state.borrow_mut();
        s.tree_sources.insert(host.0, source);
        s.log(format!("attach_tree #{}", host.0));
    }

    fn attach_list(&mut self, host: &MockHandle, source: ListSource) {
        if VIEWPORT_ROWS.with(|r| r.get()) > 0 {
            VIEWPORTS.with(|v| {
                v.borrow_mut().insert(
                    host.0,
                    Viewport {
                        visible: {
                            let len = source.len.clone();
                            Rc::new(move |_| (0..len() as u64).collect())
                        },
                        bind_row: {
                            let bind = source.bind_row.clone();
                            Rc::new(move |row, cell| bind(row as usize, cell))
                        },
                        recycle: source.recycle.clone(),
                        cell_height: Some(source.cell_height.clone()),
                        expanded: Default::default(),
                        start: 0,
                        to_end: false,
                        bound: 0,
                        dirty: true,
                    },
                )
            });
        }
        let mut s = self.state.borrow_mut();
        s.list_sources.insert(host.0, source);
        s.log(format!("attach_list #{}", host.0));
    }

    fn adopt(&mut self, raw: RawHandle) -> MockHandle {
        // A recycling list's cell: register a container widget so row content can attach to it.
        let h = raw as u64;
        let mut s = self.state.borrow_mut();
        s.widgets.entry(h).or_insert_with(|| MockWidget {
            kind: kinds::LIST_CELL,
            node: h,
            enabled: true,
            ..Default::default()
        });
        MockHandle(h)
    }

    fn reduce_motion(&mut self) -> bool {
        self.state.borrow().reduce_motion
    }

    fn announce(&mut self, text: &str, urgent: bool) {
        let mut s = self.state.borrow_mut();
        s.announcements.push((text.to_string(), urgent));
        s.log(format!("announce {text:?} urgent={urgent}"));
    }

    fn set_a11y(&mut self, h: &MockHandle, a11y: &A11yProps) {
        let mut s = self.state.borrow_mut();
        if let Some(w) = s.widgets.get_mut(&h.0) {
            w.a11y = a11y.clone();
        }
        s.log(format!("a11y #{} id={:?}", h.0, a11y.identifier));
    }

    // --- raster images (docs/images.md) --------------------------------------------------
    //
    // The mock "decodes" without pixels: it reads the format from the magic numbers and invents
    // a size, which is what a test needs to assert against. Undecodable bytes answer
    // `ImageError::Decode`, so the failure path is exercised too.

    fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]) {
        let format = day_spec::ImageFormat::sniff(bytes);
        let mut s = self.state.borrow_mut();
        s.log(format!(
            "decode_image #{} {} bytes {:?}",
            id.0,
            bytes.len(),
            format
        ));
        let event = match format {
            Some(format) => {
                let info = day_spec::BitmapInfo {
                    // A deterministic synthetic size a test can predict, in the same spirit as
                    // the mock's synthetic text metrics.
                    pixels: Size::new(MOCK_IMAGE_W, MOCK_IMAGE_H),
                    scale: 1.0,
                    format: Some(format),
                    has_alpha: format == day_spec::ImageFormat::Png,
                };
                s.bitmaps.insert(id.0, info);
                Event::ImageDecoded {
                    req,
                    result: Ok(info),
                }
            }
            None => Event::ImageDecoded {
                req,
                result: Err(day_spec::ImageError::Decode),
            },
        };
        drop(s);
        self.raise(event);
    }

    fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo> {
        self.state.borrow().bitmaps.get(&id.0).copied()
    }

    fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec) {
        let mut s = self.state.borrow_mut();
        s.log(format!("encode_image #{} {:?}", id.0, spec.format));
        let known = s.bitmaps.contains_key(&id.0);
        let result = if !known {
            Err(day_spec::ImageError::Gone)
        } else if !MOCK_ENCODE_FORMATS.contains(&spec.format) {
            Err(day_spec::ImageError::Encode)
        } else {
            // A recognizable stand-in, not real pixels: the format's magic number, so a test
            // can assert what came back round-trips through `ImageFormat::sniff`.
            Ok(match spec.format {
                day_spec::ImageFormat::Jpeg => vec![0xff, 0xd8, 0xff, 0xe0],
                _ => vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a],
            })
        };
        drop(s);
        self.raise(Event::ImageEncoded { req, result });
    }

    fn encode_formats(&mut self) -> Vec<day_spec::ImageFormat> {
        MOCK_ENCODE_FORMATS.to_vec()
    }

    fn release_image(&mut self, id: day_spec::BitmapId) {
        let mut s = self.state.borrow_mut();
        s.bitmaps.remove(&id.0);
        s.log(format!("release_image #{}", id.0));
    }

    /// No pixels, like a decode: the bitmap's facts are the size and scale asked for, which is
    /// what a test asserts against, and it joins the table `encode_image` reads.
    fn render_bitmap(
        &mut self,
        req: u64,
        id: day_spec::BitmapId,
        ops: &[DrawOp],
        size: Size,
        scale: f64,
    ) {
        let (w, h) = day_spec::export_pixels(size, scale);
        let info = day_spec::BitmapInfo {
            pixels: Size::new(f64::from(w), f64::from(h)),
            scale,
            format: None,
            has_alpha: true,
        };
        let mut s = self.state.borrow_mut();
        s.log(format!(
            "render_bitmap #{} {} ops {} @{scale}",
            id.0,
            ops.len(),
            fmt_size(size)
        ));
        s.bitmaps.insert(id.0, info);
        drop(s);
        self.raise(Event::BitmapRendered {
            req,
            result: Ok(info),
        });
    }

    fn replay(&mut self, h: &MockHandle, ops: &[DrawOp], size: Size) {
        let mut s = self.state.borrow_mut();
        if let Some(w) = s.widgets.get_mut(&h.0) {
            w.ops = ops.to_vec();
        }
        s.log(format!(
            "replay #{} {} ops in {}",
            h.0,
            ops.len(),
            fmt_size(size)
        ));
    }

    /// A deterministic list a test can assert on: "Day Sans" in four faces and "Day Mono" in one.
    fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo> {
        self.state.borrow_mut().log("font_families".to_string());
        let face = |name: &str, weight: day_spec::FontWeight, italic: bool| day_spec::FontFace {
            name: name.to_string(),
            weight,
            italic,
        };
        use day_spec::FontWeight::{Bold, Regular};
        vec![
            day_spec::FontFamilyInfo {
                family: "Day Sans".to_string(),
                faces: vec![
                    face("Regular", Regular, false),
                    face("Bold", Bold, false),
                    face("Italic", Regular, true),
                    face("Bold Italic", Bold, true),
                ],
            },
            day_spec::FontFamilyInfo {
                family: "Day Mono".to_string(),
                faces: vec![face("Regular", Regular, false)],
            },
        ]
    }

    /// The same formula as `TextMetrics::approximate`, so a test can predict a frame.
    fn measure_text(
        &mut self,
        text: &str,
        size: f64,
        _font: &day_spec::CanvasFont,
    ) -> Option<day_spec::TextMetrics> {
        self.state
            .borrow_mut()
            .log(format!("measure_text {text:?} {size}"));
        Some(day_spec::TextMetrics::approximate(text, size))
    }

    fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
        Ok(vec![0x89, b'P', b'N', b'G'])
    }

    fn fit_window(&mut self, host: &MockHandle, size: Size) {
        let mut st = self.state.borrow_mut();
        if let Some(w) = st.windows.iter_mut().find(|w| w.handle == host.0) {
            w.fit_size = Some(size);
            w.size = size;
        }
        st.log(format!("fit_window {} {size:?}", host.0));
    }

    fn native_window_tabs(&self) -> bool {
        self.state.borrow().native_window_tabs
    }
    fn native_document_tabs(&self) -> bool {
        true
    }
    fn group_windows(&mut self, hosts: &[MockHandle]) {
        let mut state = self.state.borrow_mut();
        let ids: Vec<_> = hosts
            .iter()
            .filter_map(|h| {
                state
                    .windows
                    .iter()
                    .find(|w| w.handle == h.0 && w.open)
                    .map(|w| w.node)
            })
            .collect();
        for group in &mut state.window_tab_groups {
            group.retain(|id| !ids.contains(id));
        }
        state.window_tab_groups.retain(|group| !group.is_empty());
        if !ids.is_empty() {
            state.window_tab_groups.push(ids);
        }
        state.log(format!("group_windows {hosts:?}"));
    }
    fn window_tab_order(&self, host: &MockHandle) -> Vec<NodeId> {
        let state = self.state.borrow();
        let Some(window) = state.windows.iter().find(|w| w.handle == host.0 && w.open) else {
            return Vec::new();
        };
        state
            .window_tab_groups
            .iter()
            .find(|group| group.contains(&window.node))
            .map(|group| {
                group
                    .iter()
                    .copied()
                    .filter(|id| state.windows.iter().any(|w| w.node == *id && w.open))
                    .collect()
            })
            .unwrap_or_default()
    }
    fn open_window(
        &mut self,
        id: NodeId,
        options: &day_spec::WindowOptions,
        kind: day_spec::WindowKind,
    ) -> day_spec::WindowOpenReply<MockHandle> {
        let kind_s = match kind {
            day_spec::WindowKind::Normal => "normal",
            day_spec::WindowKind::Preferences => "preferences",
            day_spec::WindowKind::About => "about",
        };
        let mut s = self.state.borrow_mut();
        if s.no_multi_window {
            s.log(format!("open_window unsupported kind={kind_s}"));
            return day_spec::WindowOpenReply::Unsupported;
        }
        if s.pending_windows {
            s.log(format!("open_window pending {:?} kind={kind_s}", id.0));
            s.pending_opens
                .push((id, options.title.clone(), kind_s.into()));
            return day_spec::WindowOpenReply::Pending;
        }
        s.next += 1;
        let h = s.next;
        s.widgets.insert(
            h,
            MockWidget {
                kind: kinds::CONTAINER,
                node: id.0,
                enabled: true,
                ..Default::default()
            },
        );
        s.windows.push(MockWindow {
            handle: h,
            node: id,
            title: options.title.clone(),
            size: options.size,
            kind: kind_s.into(),
            tabbing: options.tabbing.clone(),
            open: true,
            focused: false,
            fit_size: None,
        });
        s.log(format!(
            "open_window #{h} {:?} {} kind={kind_s}",
            options.title,
            fmt_size(options.size)
        ));
        day_spec::WindowOpenReply::Open(MockHandle(h))
    }

    fn quit_app(&mut self) {
        // Recorded rather than acted on: a test asserts the close policy reached the platform
        // exit, and the harness has no process to end (docs/windows.md).
        self.state.borrow_mut().log("quit_app".to_string());
    }

    fn close_window(&mut self, host: &MockHandle) {
        // Model the native round-trip: mark closed, then confirm through the sink with
        // `WindowClosed`; day-core tears down when the (queued) event drains.
        let mut s = self.state.borrow_mut();
        let Some(w) = s.windows.iter_mut().find(|w| w.handle == host.0 && w.open) else {
            return;
        };
        let node = w.node;
        s.log(format!("close_window #{}", host.0));
        if s.defer_window_close {
            return;
        }
        s.windows.iter_mut().find(|w| w.node == node).unwrap().open = false;
        let sink = s.sink.clone();
        drop(s);
        if let Some(sink) = sink {
            sink(node, Event::WindowClosed);
        }
    }

    fn focus_window(&mut self, host: &MockHandle) {
        let mut s = self.state.borrow_mut();
        let Some(node) = s
            .windows
            .iter()
            .find(|w| w.handle == host.0 && w.open)
            .map(|w| w.node)
        else {
            return;
        };
        let prev = s.windows.iter().find(|w| w.focused).map(|w| w.node);
        for w in s.windows.iter_mut() {
            w.focused = w.handle == host.0;
        }
        s.log(format!("focus_window #{}", host.0));
        let sink = s.sink.clone();
        drop(s);
        if let Some(sink) = sink {
            if let Some(p) = prev
                && p != node
            {
                sink(p, Event::WindowFocused(false));
            }
            sink(node, Event::WindowFocused(true));
        }
    }

    fn set_window_title(&mut self, host: &MockHandle, title: &str) {
        let mut s = self.state.borrow_mut();
        if let Some(w) = s.windows.iter_mut().find(|w| w.handle == host.0) {
            w.title = title.to_string();
        }
        s.log(format!("set_window_title #{} {title:?}", host.0));
    }

    fn snapshot_window_of(&mut self, host: &MockHandle) -> Result<Vec<u8>, String> {
        // Distinguishable from the primary snapshot so the dayscript `window:` routing is
        // assertable.
        Ok(vec![0x89, b'P', b'N', b'G', host.0 as u8])
    }

    fn present(&mut self, req: u64, spec: &day_spec::present::PresentSpec) {
        // No native UI; day-core's `PENDING` registry holds the spec. Log for op-log asserts;
        // tests answer via day_core::respond_presentation / pending_presentation.
        self.state
            .borrow_mut()
            .log(format!("present req={req} title={:?}", spec.title()));
    }

    fn dismiss(&mut self, req: u64) {
        self.state.borrow_mut().log(format!("dismiss req={req}"));
    }

    fn share_support(&self) -> day_spec::Support {
        day_spec::Support::Native
    }

    fn share(&mut self, spec: &day_spec::share::ShareSpec, anchor: Option<&Self::Handle>) -> bool {
        // No chooser to show; record it so a test can read the request and choose an action
        // (`MockProbe::choose_share_action`).
        let anchor = anchor.map(|h| h.0);
        self.state.borrow_mut().shares.push((spec.clone(), anchor));
        true
    }

    fn open_url(&mut self, url: &str) {
        // No browser to launch; record it so op-log assertions can verify a `link` fired.
        self.state.borrow_mut().log(format!("open_url {url}"));
    }

    fn defer_system_gestures(&mut self, edges: day_spec::Edges) {
        // No system gestures to defer; record the union (docs/cover.md) for op-log asserts.
        self.state
            .borrow_mut()
            .log(format!("defer_system_gestures edges={:#06b}", edges.0));
    }

    fn set_status_bar_hidden(&mut self, hidden: bool) {
        // No status bar; record the union (docs/cover.md) for op-log asserts.
        self.state
            .borrow_mut()
            .log(format!("set_status_bar_hidden {hidden}"));
    }

    // The remaining duties, implemented observably so mock stays a complete conformance probe
    // (a duty a piece exercises must never vanish into a trait default here).

    fn edit_toolbar(&mut self, _h: &MockHandle, ops: &[day_spec::ToolbarOp]) -> bool {
        let mut s = self.state.borrow_mut();
        if s.decline_toolbar_edits {
            return false;
        }
        for op in ops {
            s.toolbar.apply(op);
        }
        s.toolbar_edits.push(ops.to_vec());
        s.log(format!("edit_toolbar [{} ops]", ops.len()));
        true
    }

    fn update_toolbar(&mut self, _h: &MockHandle, patch: &day_spec::ToolbarPatch) {
        let mut s = self.state.borrow_mut();
        s.toolbar.patch(patch);
        s.toolbar_patches.push(patch.clone());
    }

    fn set_app_menu(&mut self, items: &[day_spec::MenuItem]) {
        let mut s = self.state.borrow_mut();
        s.app_menu = items.iter().map(menu_title).collect();
        s.log(format!("set_app_menu [{} items]", items.len()));
    }

    fn set_status_items(&mut self, items: &[day_spec::StatusItemSpec]) {
        let mut s = self.state.borrow_mut();
        s.status_items = items.to_vec();
        s.log(format!("set_status_items [{} items]", items.len()));
    }

    fn set_app_progress(&mut self, progress: day_spec::AppProgress) {
        let mut s = self.state.borrow_mut();
        s.app_progress = progress;
        s.log(format!("set_app_progress {progress:?}"));
    }

    fn set_dock_visible(&mut self, visible: bool) {
        let mut s = self.state.borrow_mut();
        s.dock_visible = Some(visible);
        s.log(format!("set_dock_visible {visible}"));
    }

    fn set_keep_running(&mut self, keep: bool) {
        let mut s = self.state.borrow_mut();
        s.keep_running = keep;
        s.log(format!("set_keep_running {keep}"));
    }

    fn monitors(&self) -> Vec<day_spec::Monitor> {
        // One fixed display, so placement arithmetic is testable headless.
        let frame = day_spec::Rect::new(0.0, 0.0, 1440.0, 900.0);
        vec![day_spec::Monitor {
            id: "mock-0".into(),
            name: "Mock Display".into(),
            frame,
            work_area: day_spec::Rect::new(0.0, 25.0, 1440.0, 875.0),
            scale: 2.0,
            primary: true,
        }]
    }

    fn window_frame(&self, host: &MockHandle) -> Option<day_spec::Rect> {
        // The last `Frame` change applied to this window, as a platform would report it back.
        let s = self.state.borrow();
        s.window_changes.iter().rev().find_map(|(h, c)| match c {
            day_spec::WindowChange::Frame {
                origin: Some(o),
                size: Some(z),
            } if *h == host.0 => Some(day_spec::Rect::new(o.x, o.y, z.width, z.height)),
            _ => None,
        })
    }

    fn set_launcher_shortcuts(&mut self, shortcuts: &[day_spec::LauncherShortcut]) {
        let mut s = self.state.borrow_mut();
        s.launcher_shortcuts = shortcuts.to_vec();
        s.log(format!(
            "set_launcher_shortcuts [{} items]",
            shortcuts.len()
        ));
    }

    fn set_drag_region(&mut self, h: &MockHandle, drag: bool) {
        let mut s = self.state.borrow_mut();
        if drag {
            s.drag_regions.insert(h.0);
        } else {
            s.drag_regions.remove(&h.0);
        }
        s.log(format!("set_drag_region #{} {drag}", h.0));
    }

    fn set_dock_menu(&mut self, items: &[day_spec::MenuItem]) {
        let mut s = self.state.borrow_mut();
        s.dock_menu = items.iter().map(menu_title).collect();
        s.log(format!("set_dock_menu [{} items]", items.len()));
    }

    fn apply_window(&mut self, host: &MockHandle, change: &day_spec::WindowChange) {
        // Model the platform: record the request, and for a state change complete it and report
        // the outcome the way a real window does, through `WindowStateChanged` on the window's
        // own node (the primary's goes to `WINDOW_NODE`, as AppKit's does).
        let mut s = self.state.borrow_mut();
        s.log(format!("apply_window #{} {change:?}", host.0));
        s.window_changes.push((host.0, change.clone()));
        let day_spec::WindowChange::State(state) = change else {
            return;
        };
        if s.decline_window_states {
            return;
        }
        s.window_states.insert(host.0, *state);
        let node = s
            .windows
            .iter()
            .find(|w| w.handle == host.0)
            .map(|w| w.node)
            .unwrap_or(day_spec::WINDOW_NODE);
        let sink = s.sink.clone();
        drop(s);
        if let Some(sink) = sink {
            sink(node, Event::WindowStateChanged(*state));
        }
    }

    fn set_context_menu(&mut self, h: &MockHandle, _node: NodeId, items: &[day_spec::MenuItem]) {
        let mut s = self.state.borrow_mut();
        if items.is_empty() {
            s.context_menus.remove(&h.0);
        } else {
            s.context_menus
                .insert(h.0, items.iter().map(menu_title).collect());
        }
        s.log(format!("set_context_menu #{} [{} items]", h.0, items.len()));
    }

    fn set_context_menu_fn(&mut self, h: &MockHandle, _node: NodeId, f: day_spec::ContextMenuFn) {
        self.state
            .borrow_mut()
            .context_menu_providers
            .insert(h.0, f);
    }

    fn set_button_menu(&mut self, h: &MockHandle, _node: NodeId, f: day_spec::ContextMenuFn) {
        let mut s = self.state.borrow_mut();
        s.button_menus.insert(h.0, f);
        s.log(format!("set_button_menu #{}", h.0));
    }

    fn supports_lifecycle(&self, _phase: day_spec::Lifecycle) -> bool {
        // Headless CI stands in for every platform: claim the full lifecycle so tests can
        // exercise mobile-only phases (day-core synthesizes delivery).
        true
    }

    fn read_native(&self, h: &MockHandle) -> day_spec::NativeSnapshot {
        // Echo what the setters recorded, so `a11y_audit` and `assert_native` diff cleanly
        // against expectations: the mock's "native" state is its widget record.
        let s = self.state.borrow();
        let Some(w) = s.widgets.get(&h.0) else {
            return day_spec::NativeSnapshot::default();
        };
        let kind = w.kind;
        let texty = matches!(
            kind,
            "day.label" | "day.button" | "day.text_field" | "day.text_area"
        );
        // A picker shows its selected option; the mock keeps the options `|`-joined.
        let picked = (kind == "day.picker")
            .then(|| w.text.split('|').nth(w.value as usize).map(str::to_owned))
            .flatten();
        day_spec::NativeSnapshot {
            found: true,
            role: w.a11y.role,
            label: w.a11y.label.clone(),
            value: w.a11y.value.clone(),
            identifier: w.a11y.identifier.clone(),
            text: texty.then(|| w.text.clone()).or(picked),
            number: matches!(kind, "day.slider" | "day.progress").then_some(w.value),
            // A toggle's state, or a button's selected state.
            checked: match kind {
                "day.toggle" => Some(w.flag),
                "day.button" => Some(w.selected),
                _ => None,
            },
            enabled: Some(w.enabled),
            visible: None,
            frame: Some(window_frame(&s, h.0)),
        }
    }

    fn set_system_back(&mut self, armed: bool) {
        let mut s = self.state.borrow_mut();
        s.system_back = armed;
        s.log(format!("system_back armed={armed}"));
    }

    /// Android's back dispatcher, in its order: the topmost presented cover's callback, then a
    /// nav host with a page above its root (asking Day when guarded, else popping natively and
    /// reporting it), then the app's own system-back callback while day-core arms it. With
    /// none of them, the press would leave the app: `false`.
    fn native_back(&mut self) -> bool {
        let target = {
            let mut s = self.state.borrow_mut();
            let Some(sink) = s.sink.clone() else {
                return false;
            };
            let cover = s
                .widgets
                .values()
                .filter(|w| w.kind == kinds::COVER && w.flag)
                .map(|w| w.node)
                .max();
            let host = s
                .widgets
                .iter()
                .filter(|(_, w)| w.nav_depth > 0)
                .max_by_key(|(_, w)| w.node)
                .map(|(h, _)| *h);
            let target = if let Some(node) = cover {
                Some((
                    NodeId(node),
                    Event::NavBack {
                        already_popped: false,
                    },
                ))
            } else if let Some(h) = host {
                let w = s.widgets.get_mut(&h).expect("host just found");
                let guarded = w.nav_guarded;
                if !guarded {
                    w.nav_depth -= 1;
                }
                Some((
                    NodeId(w.node),
                    Event::NavBack {
                        already_popped: !guarded,
                    },
                ))
            } else if s.system_back {
                Some((
                    day_spec::WINDOW_NODE,
                    Event::NavBack {
                        already_popped: false,
                    },
                ))
            } else {
                None
            };
            if let Some((node, _)) = &target {
                s.log(format!("native_back -> {node:?}"));
            }
            target.map(|(node, ev)| (sink, node, ev))
        };
        match target {
            Some((sink, node, ev)) => {
                sink(node, ev);
                true
            }
            None => false,
        }
    }

    fn ui_idle(&mut self) -> bool {
        // No native transitions exist; idle is immediate, but log the poll so scripted runs
        // can assert dayscript's settle path touched it.
        self.state.borrow_mut().log("ui_idle".into());
        !self.state.borrow().ui_busy
    }

    fn on_suspend(&mut self) {
        self.state.borrow_mut().log("on_suspend".into());
    }

    fn on_resume(&mut self) {
        self.state.borrow_mut().log("on_resume".into());
    }

    fn on_memory_warning(&mut self) {
        self.state.borrow_mut().log("on_memory_warning".into());
    }
}

/// A menu item's display title (submenus render as their title; separators as "—").
fn menu_title(item: &day_spec::MenuItem) -> String {
    match item {
        day_spec::MenuItem::Action { label, .. } => label.clone(),
        day_spec::MenuItem::Submenu { label, .. } => label.clone(),
        day_spec::MenuItem::Separator => "—".into(),
    }
}

impl Platform for MockToolkit {
    const TARGET: &'static str = "mock-mock";
    const TOOLKIT: &'static str = "mock";
    // The host owns the loop: `run` hands back at once, and DidExit is its last callback.
    const RUN_ENDS_APP: bool = false;

    fn run(mut self, options: WindowOptions, ready: Box<dyn FnOnce(Self, MockHandle, Size)>) {
        // No native loop: create the root container, hand off, return. Tests drive via
        // MockProbe::emit + day_reactive::flush_sync.
        let root = self.realize(kinds::CONTAINER, &ContainerProps::default(), NodeId(0));
        MOCK_WINDOW.with(|w| w.set(options.size));
        ready(self, root, options.size);
    }

    fn post(f: Box<dyn FnOnce() + Send>) {
        // No loop to defer to: run immediately (tests are synchronous).
        f();
    }

    fn post_delayed(_ms: u32, f: Box<dyn FnOnce() + Send>) {
        // A sleep is where the opt-in list viewport binds (see `viewport_flush`).
        viewport_flush();
        // The default rides a helper thread home, which has no tree or task table: a sleep in
        // a synchronous test is over the moment it starts, on this thread.
        f();
    }
}