fret-diag-protocol 0.1.0

Diagnostics protocol types for Fret (bundles, events, and capture metadata).
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
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
//! Stable, serializable protocol types for Fret diagnostics and scripted UI automation.
//!
//! The diagnostics pipeline intentionally uses explicit schema versions (e.g. `*V1`, `*V2`) so
//! tooling can evolve without breaking older bundles/scripts.
//!
//! Most users interact with this crate indirectly via `fretboard diag` and the JSON artifacts in
//! `tools/diag-scripts/`.

use serde::{Deserialize, Serialize};

pub mod builder;

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Envelope message for diagnostics/devtools transports.
///
/// Transports (e.g. WebSockets) send a `type` discriminator and a free-form JSON `payload`.
/// Higher-level tooling is responsible for validating the schema version and payload structure.
pub struct DiagTransportMessageV1 {
    pub schema_version: u32,
    pub r#type: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub request_id: Option<u64>,
    #[serde(default)]
    pub payload: serde_json::Value,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Hello message sent by a client when attaching to a devtools server.
pub struct DevtoolsHelloV1 {
    pub client_kind: String,
    pub client_version: String,
    #[serde(default)]
    pub capabilities: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Acknowledgement message returned by the devtools server after receiving [`DevtoolsHelloV1`].
pub struct DevtoolsHelloAckV1 {
    pub server_version: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub server_capabilities: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DevtoolsSessionDescriptorV1 {
    pub session_id: String,
    pub client_kind: String,
    pub client_version: String,
    #[serde(default)]
    pub capabilities: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DevtoolsSessionListV1 {
    pub sessions: Vec<DevtoolsSessionDescriptorV1>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DevtoolsSessionAddedV1 {
    pub session: DevtoolsSessionDescriptorV1,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DevtoolsSessionRemovedV1 {
    pub session_id: String,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UiScriptMetaV1 {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub required_capabilities: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub target_hints: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum UiImeEventV1 {
    Enabled,
    Disabled,
    Commit {
        text: String,
    },
    /// IME preedit update.
    ///
    /// `cursor_bytes` is a byte-indexed range in the preedit string (begin, end).
    /// When `None`, the cursor should be hidden.
    Preedit {
        text: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        cursor_bytes: Option<(u32, u32)>,
    },
    /// Delete text surrounding the cursor or selection.
    ///
    /// Offsets are expressed in UTF-8 bytes.
    DeleteSurrounding {
        before_bytes: u32,
        after_bytes: u32,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Scripted UI interaction plan (schema v1).
///
/// Used by `fretboard diag` to drive automated UI actions and assertions.
pub struct UiActionScriptV1 {
    pub schema_version: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<UiScriptMetaV1>,
    pub steps: Vec<UiActionStepV1>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum UiActionStepV1 {
    Click {
        target: UiSelectorV1,
        #[serde(default)]
        button: UiMouseButtonV1,
        #[serde(
            default = "default_click_count",
            skip_serializing_if = "is_default_click_count"
        )]
        click_count: u8,
    },
    ResetDiagnostics,
    MovePointer {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        target: UiSelectorV1,
    },
    DragPointer {
        target: UiSelectorV1,
        #[serde(default)]
        button: UiMouseButtonV1,
        delta_x: f32,
        delta_y: f32,
        #[serde(default = "default_drag_steps")]
        steps: u32,
    },
    Wheel {
        target: UiSelectorV1,
        #[serde(default)]
        delta_x: f32,
        #[serde(default)]
        delta_y: f32,
    },
    PressKey {
        key: String,
        #[serde(default)]
        modifiers: UiKeyModifiersV1,
        #[serde(default)]
        repeat: bool,
    },
    TypeText {
        text: String,
    },
    WaitFrames {
        n: u32,
    },
    WaitUntil {
        predicate: UiPredicateV1,
        timeout_frames: u32,
    },
    Assert {
        predicate: UiPredicateV1,
    },
    CaptureBundle {
        label: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        max_snapshots: Option<u32>,
    },
    CaptureScreenshot {
        label: Option<String>,
        #[serde(default = "default_capture_screenshot_timeout_frames")]
        timeout_frames: u32,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Scripted UI interaction plan (schema v2).
///
/// This is the preferred schema for new scripts and generators.
pub struct UiActionScriptV2 {
    pub schema_version: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<UiScriptMetaV1>,
    pub steps: Vec<UiActionStepV2>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FilesystemCapabilitiesHintsV1 {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub allow_script_schema_v1: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub write_bundle_schema2: Option<bool>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FilesystemCapabilitiesV1 {
    pub schema_version: u32,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub capabilities: Vec<String>,
    /// Optional runner identity for auditability (additive; tooling must treat as hints).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub runner_kind: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub runner_version: Option<String>,
    /// Optional schema/config hints for tooling and triage (additive).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hints: Option<FilesystemCapabilitiesHintsV1>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UiDiagnosticsConfigPathsV1 {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trigger_path: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ready_path: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exit_path: Option<String>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub screenshot_request_path: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub screenshot_trigger_path: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub screenshot_result_path: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub screenshot_result_trigger_path: Option<String>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub script_path: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub script_trigger_path: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub script_result_path: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub script_result_trigger_path: Option<String>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pick_trigger_path: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pick_result_path: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pick_result_trigger_path: Option<String>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub inspect_path: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub inspect_trigger_path: Option<String>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UiDiagnosticsConfigFileV1 {
    pub schema_version: u32,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub out_dir: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub paths: Option<UiDiagnosticsConfigPathsV1>,

    /// Whether the diagnostics runtime should accept script schema v1 inputs.
    ///
    /// When `None`, the runtime uses its default policy (currently: allow in manual flows; tooling
    /// typically writes an explicit `false` for launched runs).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub allow_script_schema_v1: Option<bool>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub script_keepalive: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub script_auto_dump: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pick_auto_dump: Option<bool>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_events: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_snapshots: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub script_dump_max_snapshots: Option<u32>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capture_semantics: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_semantics_nodes: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub semantics_test_ids_only: Option<bool>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub screenshots_enabled: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub screenshot_on_dump: Option<bool>,

    /// Whether the diagnostics runtime should write the large raw bundle artifact (`bundle.json`)
    /// during dumps.
    ///
    /// Tooling typically sets this to `false` for launched runs so default artifacts stay
    /// small-by-default (manifest + sidecars + optional compact bundle view).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub write_bundle_json: Option<bool>,
    /// Whether the diagnostics runtime should write the compact bundle view (`bundle.schema2.json`)
    /// alongside sidecars during dumps.
    ///
    /// This is intended for schema2-first + AI/sidecar-first workflows to avoid requiring tooling
    /// to parse large raw bundles just to produce a portable artifact.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub write_bundle_schema2: Option<bool>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub redact_text: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_debug_string_bytes: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_gating_trace_entries: Option<u32>,

    /// When enabled, ignore external pointer input events (mouse/touch/pen) while a diagnostics
    /// script is running.
    ///
    /// This is intended to keep scripted runs deterministic when a user accidentally moves or
    /// clicks the real mouse during playback (especially for cross-window docking/tear-off).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub isolate_external_pointer_input_while_script_running: Option<bool>,

    /// When enabled, ignore external keyboard/text/IME events while a diagnostics script is
    /// running.
    ///
    /// This is intended to keep scripted runs deterministic when a user accidentally types while
    /// playback is in progress (especially when scripts are asserting shortcut routing or text
    /// input outcomes).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub isolate_external_keyboard_input_while_script_running: Option<bool>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub frame_clock_fixed_delta_ms: Option<u64>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub devtools_embed_bundle: Option<bool>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct UiPaddingInsetsV1 {
    pub left_px: f32,
    pub top_px: f32,
    pub right_px: f32,
    pub bottom_px: f32,
}

impl UiPaddingInsetsV1 {
    pub fn uniform(padding_px: f32) -> Self {
        let p = padding_px.max(0.0);
        Self {
            left_px: p,
            top_px: p,
            right_px: p,
            bottom_px: p,
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum UiWindowTargetV1 {
    /// Target the window currently driving the script step.
    Current,
    /// Target the first window observed by the diagnostics runtime.
    FirstSeen,
    /// Target the first observed window that is not the current window.
    FirstSeenOther,
    /// Target the most recently observed window.
    LastSeen,
    /// Target the most recently observed window that is not the current window.
    LastSeenOther,
    /// Target a specific window by its FFI handle/id as reported in bundles and script results.
    WindowFfi { window: u64 },
}

#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum UiInsetsOverrideV1 {
    #[default]
    NoChange,
    Clear,
    Set {
        insets_px: UiPaddingInsetsV1,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum UiIncomingOpenInjectItemV1 {
    /// Diagnostics-only UTF-8 file payload.
    ///
    /// This is intended for CI fixtures and does not model binary files or platform handles.
    FileUtf8 {
        name: String,
        text: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        media_type: Option<String>,
    },
    Text {
        text: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        media_type: Option<String>,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UiClipboardWriteResultV1 {
    Success,
    Failure,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UiClipboardAccessErrorKindV1 {
    Unavailable,
    PermissionDenied,
    UserActivationRequired,
    Unsupported,
    BackendError,
    Unknown,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum UiActionStepV2 {
    // v1-compatible steps
    Click {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pointer_kind: Option<UiPointerKindV1>,
        target: UiSelectorV1,
        #[serde(default)]
        button: UiMouseButtonV1,
        #[serde(
            default = "default_click_count",
            skip_serializing_if = "is_default_click_count"
        )]
        click_count: u8,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        modifiers: Option<UiKeyModifiersV1>,
    },
    /// A high-level “tap” gesture (touch-first) resolved via semantics selectors.
    ///
    /// This is intended for mobile-style interaction policies where "click" is an imprecise term.
    /// Runtime injection still maps to unified pointer events with `PointerType::Touch` by default.
    Tap {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        /// Optional override; when omitted, defaults to `touch`.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pointer_kind: Option<UiPointerKindV1>,
        target: UiSelectorV1,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        modifiers: Option<UiKeyModifiersV1>,
    },
    /// A high-level “long press” gesture (touch-first) resolved via semantics selectors.
    ///
    /// Runtime injection emits a `pointer_down`, holds until `duration_ms` elapses, then emits
    /// `pointer_up` with `is_click=false`.
    LongPress {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        /// Optional override; when omitted, defaults to `touch`.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pointer_kind: Option<UiPointerKindV1>,
        target: UiSelectorV1,
        #[serde(
            default = "default_long_press_duration_ms",
            skip_serializing_if = "is_default_long_press_duration_ms"
        )]
        duration_ms: u64,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        modifiers: Option<UiKeyModifiersV1>,
    },
    /// A high-level “swipe” gesture (touch-first) resolved via semantics selectors.
    ///
    /// Runtime injection emits a `pointer_down` at the target's center, then a sequence of
    /// `pointer_move` events to the end position, then a `pointer_up` with `is_click=false`.
    Swipe {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        /// Optional override; when omitted, defaults to `touch`.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pointer_kind: Option<UiPointerKindV1>,
        target: UiSelectorV1,
        delta_x: f32,
        delta_y: f32,
        #[serde(
            default = "default_drag_steps",
            skip_serializing_if = "is_default_drag_steps"
        )]
        steps: u32,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        modifiers: Option<UiKeyModifiersV1>,
    },
    /// A pinch/zoom gesture emitted at the target's center.
    ///
    /// `delta` is positive for zoom in and negative for zoom out (matches `PointerEvent::PinchGesture`).
    Pinch {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        /// Optional override; when omitted, defaults to `touch`.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pointer_kind: Option<UiPointerKindV1>,
        target: UiSelectorV1,
        /// Total delta across all steps.
        delta: f32,
        #[serde(
            default = "default_drag_steps",
            skip_serializing_if = "is_default_drag_steps"
        )]
        steps: u32,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        modifiers: Option<UiKeyModifiersV1>,
    },
    ResetDiagnostics,
    /// Set a “base reference” for subsequent selector-driven steps.
    ///
    /// When a base reference is set, the runtime may scope later selector resolution to the
    /// base node's subtree (window-local) until [`UiActionStepV2::ClearBaseRef`] is executed.
    ///
    /// This is an ergonomics feature (ImGui `SetRef(...)`-style outcome) intended to reduce
    /// repetition and diff noise in long scripts.
    SetBaseRef {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        target: UiSelectorV1,
    },
    /// Clear the active base reference, restoring global selector resolution.
    ClearBaseRef,
    /// Semantically activate a target using the runtime accessibility action surface.
    ///
    /// This bypasses pointer hit-testing and is primarily intended for diagnosis: it helps
    /// distinguish "semantics can activate" from "pointer cannot hit the target".
    Activate {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        target: UiSelectorV1,
    },
    /// Move accessibility focus to a target without invoking it.
    ///
    /// This is intended for diagnosis and parity checks where you want to distinguish
    /// focusability from pointer hit-testing and activation behavior.
    Focus {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        target: UiSelectorV1,
    },
    MovePointer {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pointer_kind: Option<UiPointerKindV1>,
        target: UiSelectorV1,
    },
    /// Move the pointer to a target and issue a pointer down, keeping the session active across
    /// subsequent steps (until `pointer_up`).
    ///
    /// This is intended for scripted "drag + key" flows (e.g. press Escape while dragging).
    PointerDown {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pointer_kind: Option<UiPointerKindV1>,
        target: UiSelectorV1,
        #[serde(default)]
        button: UiMouseButtonV1,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        modifiers: Option<UiKeyModifiersV1>,
    },
    DragPointer {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pointer_kind: Option<UiPointerKindV1>,
        target: UiSelectorV1,
        #[serde(default)]
        button: UiMouseButtonV1,
        #[serde(default = "default_true")]
        clamp_to_window_bounds: bool,
        delta_x: f32,
        delta_y: f32,
        #[serde(default = "default_drag_steps")]
        steps: u32,
    },
    /// Move the pointer while a `pointer_down` session is active.
    ///
    /// This emits `PointerEvent::Move` with pressed buttons and also mirrors internal drag routing
    /// by emitting `InternalDrag::Over` events (safe unless a cross-window internal-drag session is
    /// active).
    PointerMove {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pointer_kind: Option<UiPointerKindV1>,
        delta_x: f32,
        delta_y: f32,
        #[serde(default = "default_drag_steps")]
        steps: u32,
    },
    /// Release an active `pointer_down` session.
    ///
    /// This emits `PointerEvent::Up` and mirrors internal drag routing by emitting
    /// `InternalDrag::Drop`.
    PointerUp {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pointer_kind: Option<UiPointerKindV1>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        button: Option<UiMouseButtonV1>,
    },
    /// Cancel an active `pointer_down` session.
    ///
    /// This emits `Event::PointerCancel` and mirrors internal drag routing by emitting
    /// `InternalDrag::Cancel`.
    PointerCancel {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pointer_kind: Option<UiPointerKindV1>,
    },
    MovePointerSweep {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pointer_kind: Option<UiPointerKindV1>,
        target: UiSelectorV1,
        delta_x: f32,
        delta_y: f32,
        #[serde(default = "default_drag_steps")]
        steps: u32,
        #[serde(default = "default_move_frames_per_step")]
        frames_per_step: u32,
    },
    Wheel {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pointer_kind: Option<UiPointerKindV1>,
        target: UiSelectorV1,
        #[serde(default)]
        delta_x: f32,
        #[serde(default)]
        delta_y: f32,
    },
    /// Inject a burst of wheel events in a single frame via the native runner (best-effort).
    ///
    /// Unlike [`UiActionStepV2::Wheel`], which injects a single `pointer.wheel` event directly into
    /// the UI event stream, this step is intended to exercise runner-level wheel coalescing by
    /// synthesizing multiple raw wheel inputs in the same frame.
    ///
    /// Requires capability `diag.wheel_burst_inject`.
    WheelBurst {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pointer_kind: Option<UiPointerKindV1>,
        target: UiSelectorV1,
        #[serde(default)]
        delta_x: f32,
        #[serde(default)]
        delta_y: f32,
        #[serde(
            default = "default_wheel_burst_count",
            skip_serializing_if = "is_default_wheel_burst_count"
        )]
        count: u32,
    },
    PressKey {
        key: String,
        #[serde(default)]
        modifiers: UiKeyModifiersV1,
        #[serde(default)]
        repeat: bool,
    },
    PressShortcut {
        shortcut: String,
        #[serde(default)]
        repeat: bool,
    },
    TypeText {
        text: String,
    },
    /// Inject an IME event into the focused text surface.
    ///
    /// This is intended for deterministic regression scripts that need to exercise text/IME
    /// composition without depending on platform IME integrations.
    Ime {
        event: UiImeEventV1,
    },
    WaitFrames {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        n: u32,
    },
    /// Wait for a fixed duration (in milliseconds).
    ///
    /// This is intended as a last-resort stabilization step when no semantic predicate exists.
    /// Prefer `wait_until` for deterministic gates.
    WaitMs {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        n_ms: u32,
    },
    WaitUntil {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        predicate: UiPredicateV1,
        #[serde(default = "default_action_timeout_frames")]
        timeout_frames: u32,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        timeout_ms: Option<u32>,
    },
    /// Wait until the shortcut routing diagnostics trace contains an entry matching `query`.
    ///
    /// This is intended for deterministic scripts that need to assert keyboard routing outcomes
    /// (e.g. reserved-for-IME) without depending on screenshots or ad-hoc logs.
    WaitShortcutRoutingTrace {
        query: UiShortcutRoutingTraceQueryV1,
        #[serde(default = "default_action_timeout_frames")]
        timeout_frames: u32,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        timeout_ms: Option<u32>,
    },
    /// Wait until the command dispatch trace contains an entry matching `query`.
    ///
    /// This is intended to gate action-first convergence work: pointer triggers, keymap shortcuts,
    /// and command palette/menus should all produce explainable dispatch outcomes.
    WaitCommandDispatchTrace {
        query: UiCommandDispatchTraceQueryV1,
        #[serde(default = "default_action_timeout_frames")]
        timeout_frames: u32,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        timeout_ms: Option<u32>,
    },
    /// Wait until the overlay placement trace contains an entry matching `query`.
    ///
    /// This is intended for overlay-driven components (Select/Combobox/Menus) where correctness
    /// depends on collision/flip/shift behavior and we want failures to be explainable without
    /// relying on screenshots.
    WaitOverlayPlacementTrace {
        query: UiOverlayPlacementTraceQueryV1,
        #[serde(default = "default_action_timeout_frames")]
        timeout_frames: u32,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        timeout_ms: Option<u32>,
    },
    Assert {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        predicate: UiPredicateV1,
    },
    CaptureBundle {
        label: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        max_snapshots: Option<u32>,
    },
    CaptureScreenshot {
        label: Option<String>,
        #[serde(default = "default_capture_screenshot_timeout_frames")]
        timeout_frames: u32,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        timeout_ms: Option<u32>,
    },
    /// Capture a layout sidecar (native-only, best-effort).
    ///
    /// This is intended to make layout regressions explainable via a bundle-scoped sidecar file
    /// (e.g. `layout.taffy.v1.json`) rather than ad-hoc debug UI in demos.
    ///
    /// Tooling should treat missing sidecars as warnings, not failures.
    CaptureLayoutSidecar {
        /// Optional label used to name the bundle directory for this capture step.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        label: Option<String>,
        /// Optional debug label filter for selecting a subtree root before dumping.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        root_label_filter: Option<String>,
    },

    // v2 intent-level steps
    /// Click a target only after its bounds have remained stable for `stable_frames`.
    ///
    /// This is useful for virtualized lists where a target's measured bounds can jump
    /// across frames (e.g. estimate -> measured), causing clicks to land at stale
    /// positions when using a single-frame snapshot.
    ClickStable {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pointer_kind: Option<UiPointerKindV1>,
        target: UiSelectorV1,
        #[serde(default)]
        button: UiMouseButtonV1,
        #[serde(
            default = "default_click_count",
            skip_serializing_if = "is_default_click_count"
        )]
        click_count: u8,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        modifiers: Option<UiKeyModifiersV1>,
        #[serde(default = "default_click_stable_frames")]
        stable_frames: u32,
        #[serde(default = "default_click_stable_max_move_px")]
        max_move_px: f32,
        #[serde(default = "default_action_timeout_frames")]
        timeout_frames: u32,
    },
    /// Click an interactive span (by `tag`) inside a `SelectableText` target after its computed
    /// span bounds remain stable for `stable_frames`.
    ///
    /// This is intended for rich text surfaces where the clickable region is smaller than the
    /// semantics node bounds (e.g. link spans inside a paragraph), and where clicking the center
    /// of the node can miss the span.
    ClickSelectableTextSpanStable {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pointer_kind: Option<UiPointerKindV1>,
        target: UiSelectorV1,
        tag: String,
        #[serde(default)]
        button: UiMouseButtonV1,
        #[serde(
            default = "default_click_count",
            skip_serializing_if = "is_default_click_count"
        )]
        click_count: u8,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        modifiers: Option<UiKeyModifiersV1>,
        #[serde(default = "default_click_stable_frames")]
        stable_frames: u32,
        #[serde(default = "default_click_stable_max_move_px")]
        max_move_px: f32,
        #[serde(default = "default_action_timeout_frames")]
        timeout_frames: u32,
    },
    /// Wait until a target's semantics bounds have remained stable for `stable_frames`.
    ///
    /// This is useful for overlays/virtualized surfaces where measured bounds can jump across
    /// frames (estimate -> measured, placement flip/shift, scroll settle), and you want a
    /// deterministic “ready” point without relying on wall-clock sleeps.
    WaitBoundsStable {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        target: UiSelectorV1,
        #[serde(default = "default_bounds_stable_frames")]
        stable_frames: u32,
        #[serde(default = "default_bounds_stable_max_move_px")]
        max_move_px: f32,
        #[serde(default = "default_action_timeout_frames")]
        timeout_frames: u32,
    },
    /// Wait until a target's structured semantics scroll field has remained stable for
    /// `stable_frames`.
    ///
    /// This is intended for scrollable surfaces whose content extent converges across a few
    /// post-layout frames (for example after switching tabs or appending content at the bottom).
    WaitSemanticsScrollStable {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        target: UiSelectorV1,
        field: UiSemanticsScrollFieldV1,
        #[serde(default = "default_semantics_scroll_stable_frames")]
        stable_frames: u32,
        #[serde(default = "default_semantics_scroll_stable_max_delta")]
        max_delta: f64,
        #[serde(default = "default_action_timeout_frames")]
        timeout_frames: u32,
    },
    EnsureVisible {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        target: UiSelectorV1,
        #[serde(default)]
        within_window: bool,
        #[serde(default)]
        padding_px: f32,
        #[serde(default = "default_action_timeout_frames")]
        timeout_frames: u32,
    },
    ScrollIntoView {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pointer_kind: Option<UiPointerKindV1>,
        container: UiSelectorV1,
        target: UiSelectorV1,
        #[serde(default)]
        delta_x: f32,
        #[serde(default = "default_scroll_delta_y")]
        delta_y: f32,
        #[serde(default)]
        require_fully_within_container: bool,
        #[serde(default)]
        require_fully_within_window: bool,
        #[serde(default)]
        padding_px: f32,
        #[serde(default)]
        padding_insets_px: Option<UiPaddingInsetsV1>,
        #[serde(default = "default_action_timeout_frames")]
        timeout_frames: u32,
    },
    TypeTextInto {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pointer_kind: Option<UiPointerKindV1>,
        target: UiSelectorV1,
        text: String,
        #[serde(default)]
        clear_before_type: bool,
        #[serde(default = "default_action_timeout_frames")]
        timeout_frames: u32,
    },
    /// Set the full text value of a target text surface via the accessibility SetValue path.
    ///
    /// Unlike [`UiActionStepV2::TypeTextInto`], this step does not depend on click-to-focus
    /// behavior. It resolves the target from semantics, requests focus for that node, selects the
    /// current text, then dispatches a single text input payload with `text`.
    ///
    /// Notes:
    ///
    /// - Intended for diagnostics gates that need stable text entry across policy-layer widgets.
    /// - Targets should expose `actions.set_value=true`; disabled targets fail the step.
    SetTextValue {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        target: UiSelectorV1,
        text: String,
        #[serde(default = "default_action_timeout_frames")]
        timeout_frames: u32,
    },
    /// Paste `text` into a target text surface by:
    ///
    /// 1) clicking the target to focus it,
    /// 2) setting the OS clipboard text (best-effort),
    /// 3) issuing the platform "paste" shortcut (`Primary+V`).
    ///
    /// This is intentionally higher-level than `set_clipboard_text + press_shortcut` so scripts
    /// can gate paste-specific code paths with less boilerplate.
    ///
    /// Notes:
    ///
    /// - The clipboard write is best-effort and runner/platform dependent.
    /// - `clear_before_paste` uses `SetTextSelection { anchor=0, focus=u32::MAX }` (not `Ctrl+A`).
    PasteTextInto {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pointer_kind: Option<UiPointerKindV1>,
        target: UiSelectorV1,
        text: String,
        #[serde(default)]
        clear_before_paste: bool,
        #[serde(default = "default_action_timeout_frames")]
        timeout_frames: u32,
    },
    MenuSelect {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pointer_kind: Option<UiPointerKindV1>,
        menu: UiSelectorV1,
        item: UiSelectorV1,
        #[serde(default = "default_action_timeout_frames")]
        timeout_frames: u32,
    },
    MenuSelectPath {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pointer_kind: Option<UiPointerKindV1>,
        path: Vec<UiSelectorV1>,
        #[serde(default = "default_action_timeout_frames")]
        timeout_frames: u32,
    },
    DragTo {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pointer_kind: Option<UiPointerKindV1>,
        from: UiSelectorV1,
        to: UiSelectorV1,
        #[serde(default)]
        button: UiMouseButtonV1,
        #[serde(default = "default_drag_steps")]
        steps: u32,
        #[serde(default = "default_action_timeout_frames")]
        timeout_frames: u32,
    },
    SetSliderValue {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pointer_kind: Option<UiPointerKindV1>,
        target: UiSelectorV1,
        value: f32,
        #[serde(default = "default_slider_min")]
        min: f32,
        #[serde(default = "default_slider_max")]
        max: f32,
        #[serde(default = "default_slider_epsilon")]
        epsilon: f32,
        #[serde(default = "default_action_timeout_frames")]
        timeout_frames: u32,
        #[serde(default = "default_drag_steps")]
        drag_steps: u32,
    },
    SetWindowInnerSize {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        width_px: f32,
        height_px: f32,
    },
    /// Best-effort request to update OS window style facets at runtime (patch semantics).
    ///
    /// This is intended for diagnostics-only repros and regression gates for utility window
    /// postures (frameless/transparent/materials/hit-test policies).
    ///
    /// Capability-gated behind `diag.window_style_patch_v1`.
    ///
    /// Note: as of 2026-03-04 this capability is Windows-only in the default in-tree runner.
    /// Supported patch fields in the default runner are currently limited to:
    /// - `z_level`
    /// - `background_material`
    /// - `hit_test`
    /// - `opacity_alpha_u8`
    SetWindowStyle {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        style: UiWindowStylePatchV1,
    },
    SetWindowInsets {
        #[serde(default)]
        safe_area_insets: UiInsetsOverrideV1,
        #[serde(default)]
        occlusion_insets: UiInsetsOverrideV1,
    },
    /// Diagnostics-only clipboard override to simulate clipboard read denial/unavailability.
    ///
    /// This is intended to gate “paste request fails gracefully” behavior under mobile privacy
    /// constraints without requiring a real mobile runner.
    SetClipboardForceUnavailable {
        enabled: bool,
    },
    /// Set the OS clipboard text payload (best-effort).
    ///
    /// This is intended to make "paste" flows deterministic in scripted diagnostics by ensuring
    /// the clipboard contents are known.
    ///
    /// Requires capability `diag.clipboard_text`.
    SetClipboardText {
        text: String,
    },
    /// Wait until a clipboard write completion matching `outcome` is observed.
    ///
    /// This is intended for gating explicit copy-button success/failure without inferring from
    /// clipboard contents alone.
    ///
    /// When `outcome = "failure"`, callers may additionally match on `error_kind` and/or a
    /// substring of the structured error message.
    WaitClipboardWriteResult {
        outcome: UiClipboardWriteResultV1,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        error_kind: Option<UiClipboardAccessErrorKindV1>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        message_contains: Option<String>,
        #[serde(default = "default_action_timeout_frames")]
        timeout_frames: u32,
    },
    /// Assert a clipboard write completion matches `outcome`.
    ///
    /// If a preceding `wait_clipboard_write_result` step already captured a completion, this step
    /// asserts against that cached result. Otherwise it waits for a new completion up to
    /// `timeout_frames`, which keeps the step usable as a single-shot gate after clicking a copy
    /// button.
    ///
    /// When `outcome = "failure"`, callers may additionally match on `error_kind` and/or a
    /// substring of the structured error message.
    AssertClipboardWriteResult {
        outcome: UiClipboardWriteResultV1,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        error_kind: Option<UiClipboardAccessErrorKindV1>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        message_contains: Option<String>,
        #[serde(default = "default_action_timeout_frames")]
        timeout_frames: u32,
    },
    /// Assert that the OS clipboard text payload equals `text` (best-effort).
    ///
    /// This is intended to make clipboard-driven regression scripts explainable without relying
    /// on screenshots.
    ///
    /// Requires capability `diag.clipboard_text`.
    AssertClipboardText {
        text: String,
        #[serde(default = "default_action_timeout_frames")]
        timeout_frames: u32,
    },
    /// In-app inspector helper: open help, search for `query`, lock the best match, and request
    /// copying the best selector JSON to the OS clipboard.
    ///
    /// This is intended to gate that the in-app inspector UX is still functional under
    /// tool-launched scripted runs (`fretboard diag run/suite --launch`) without relying on
    /// keyboard shortcut injection.
    ///
    /// Behavior notes:
    ///
    /// - Matching prefers `test_id`, then `label` when text redaction is disabled.
    /// - The runtime may keep the help overlay open after the step.
    InspectHelpLockBestMatchAndCopySelector {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        query: String,
        #[serde(default = "default_action_timeout_frames")]
        timeout_frames: u32,
    },
    /// In-app inspector helper: open help, ensure the semantics tree panel is visible, select the
    /// best match for `query` in the tree, lock it, and copy the best selector JSON to the OS
    /// clipboard.
    ///
    /// This is intended to gate that the help-mode tree browser remains functional under
    /// tool-launched scripted runs (`fretboard diag run/suite --launch`) without relying on
    /// keyboard shortcut injection.
    InspectHelpTreeLockBestMatchAndCopySelector {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        query: String,
        #[serde(default = "default_action_timeout_frames")]
        timeout_frames: u32,
    },
    /// Diagnostics-only incoming-open injection (best-effort).
    ///
    /// This simulates “open in…” / share-target flows by injecting an `IncomingOpenRequest` event.
    InjectIncomingOpen {
        items: Vec<UiIncomingOpenInjectItemV1>,
    },
    /// Set the OS window outer position (screen-space logical pixels).
    ///
    /// This is intended for deterministically arranging windows in scripted repros and for
    /// best-effort placement restoration (ADR 0017).
    SetWindowOuterPosition {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        x_px: f32,
        y_px: f32,
    },
    /// Set a runner-level cursor screen position override (screen-space physical pixels).
    ///
    /// Desktop runners may use this during scripted diagnostics to drive hover routing that is
    /// normally owned by OS cursor events (e.g. cross-window docking).
    ///
    /// Requires capability `diag.cursor_screen_pos_override`.
    SetCursorScreenPos {
        x_px: f32,
        y_px: f32,
    },
    /// Set a runner-level cursor screen position override using window-local client coordinates.
    ///
    /// This is intended for cross-window scripted diagnostics where the runner must synthesize a
    /// global cursor location from window-local input.
    ///
    /// Coordinates are in window-client **physical pixels**.
    ///
    /// Requires capability `diag.cursor_screen_pos_override`.
    SetCursorInWindow {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        x_px: f32,
        y_px: f32,
    },
    /// Set a runner-level cursor screen position override using window-local client coordinates.
    ///
    /// This is identical to `set_cursor_in_window`, except the coordinates are in window-client
    /// **logical pixels** (pre-DPI scale). The runner converts to physical pixels using the
    /// current window scale factor.
    ///
    /// Prefer this for deterministic scripts that already express geometry in logical pixels.
    ///
    /// Requires capability `diag.cursor_screen_pos_override`.
    SetCursorInWindowLogical {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        x_px: f32,
        y_px: f32,
    },
    /// Set a runner-level mouse button state override.
    ///
    /// This is intended for scripted diagnostics that need to exercise runner-level fallback
    /// behavior that depends on OS button state (e.g. "release outside all windows" poll-up
    /// paths) without requiring real OS input.
    ///
    /// Desktop runners may choose to apply this only while certain interactions are active
    /// (e.g. cross-window dock drags).
    SetMouseButtons {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        left: Option<bool>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        right: Option<bool>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        middle: Option<bool>,
    },
    RaiseWindow {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
    },
    /// Drag with pointer down across frames until `predicate` passes, or timeout.
    ///
    /// This is intended for runner-owned cross-window routing: scripts can keep a drag session
    /// active while polling diagnostics predicates that are only updated between frames.
    DragPointerUntil {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<UiWindowTargetV1>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pointer_kind: Option<UiPointerKindV1>,
        target: UiSelectorV1,
        #[serde(default)]
        button: UiMouseButtonV1,
        #[serde(default = "default_true")]
        release_on_success: bool,
        delta_x: f32,
        delta_y: f32,
        #[serde(default = "default_drag_steps")]
        steps: u32,
        predicate: UiPredicateV1,
        #[serde(default = "default_action_timeout_frames")]
        timeout_frames: u32,
    },
}

impl From<UiActionStepV1> for UiActionStepV2 {
    fn from(value: UiActionStepV1) -> Self {
        match value {
            UiActionStepV1::Click {
                target,
                button,
                click_count,
            } => Self::Click {
                window: None,
                pointer_kind: None,
                target,
                button,
                click_count,
                modifiers: None,
            },
            UiActionStepV1::ResetDiagnostics => Self::ResetDiagnostics,
            UiActionStepV1::MovePointer { window, target } => Self::MovePointer {
                window,
                pointer_kind: None,
                target,
            },
            UiActionStepV1::DragPointer {
                target,
                button,
                delta_x,
                delta_y,
                steps,
            } => Self::DragPointer {
                window: None,
                pointer_kind: None,
                target,
                button,
                clamp_to_window_bounds: true,
                delta_x,
                delta_y,
                steps,
            },
            UiActionStepV1::Wheel {
                target,
                delta_x,
                delta_y,
            } => Self::Wheel {
                window: None,
                pointer_kind: None,
                target,
                delta_x,
                delta_y,
            },
            UiActionStepV1::PressKey {
                key,
                modifiers,
                repeat,
            } => Self::PressKey {
                key,
                modifiers,
                repeat,
            },
            UiActionStepV1::TypeText { text } => Self::TypeText { text },
            UiActionStepV1::WaitFrames { n } => Self::WaitFrames { window: None, n },
            UiActionStepV1::WaitUntil {
                predicate,
                timeout_frames,
            } => Self::WaitUntil {
                window: None,
                predicate,
                timeout_frames,
                timeout_ms: None,
            },
            UiActionStepV1::Assert { predicate } => Self::Assert {
                window: None,
                predicate,
            },
            UiActionStepV1::CaptureBundle {
                label,
                max_snapshots,
            } => Self::CaptureBundle {
                label,
                max_snapshots,
            },
            UiActionStepV1::CaptureScreenshot {
                label,
                timeout_frames,
            } => Self::CaptureScreenshot {
                label,
                timeout_frames,
                timeout_ms: None,
            },
        }
    }
}

fn default_drag_steps() -> u32 {
    8
}

fn is_default_drag_steps(v: &u32) -> bool {
    *v == default_drag_steps()
}

fn default_wheel_burst_count() -> u32 {
    8
}

fn is_default_wheel_burst_count(v: &u32) -> bool {
    *v == default_wheel_burst_count()
}

fn default_move_frames_per_step() -> u32 {
    1
}

fn default_click_count() -> u8 {
    1
}

fn is_default_click_count(v: &u8) -> bool {
    *v == 1
}

fn default_long_press_duration_ms() -> u64 {
    500
}

fn is_default_long_press_duration_ms(v: &u64) -> bool {
    *v == 500
}

fn default_click_stable_frames() -> u32 {
    2
}

fn default_click_stable_max_move_px() -> f32 {
    1.0
}

fn default_bounds_stable_frames() -> u32 {
    2
}

fn default_bounds_stable_max_move_px() -> f32 {
    1.0
}

fn default_semantics_scroll_stable_frames() -> u32 {
    2
}

fn default_semantics_scroll_stable_max_delta() -> f64 {
    1.0
}

fn default_capture_screenshot_timeout_frames() -> u32 {
    300
}

fn default_action_timeout_frames() -> u32 {
    180
}

fn default_true() -> bool {
    true
}

fn default_scroll_delta_y() -> f32 {
    -120.0
}

fn default_slider_min() -> f32 {
    0.0
}

fn default_slider_max() -> f32 {
    100.0
}

fn default_slider_epsilon() -> f32 {
    0.5
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UiMouseButtonV1 {
    #[default]
    Left,
    Right,
    Middle,
}

impl UiMouseButtonV1 {
    pub fn from_button(button: fret_core::MouseButton) -> Self {
        match button {
            fret_core::MouseButton::Left => Self::Left,
            fret_core::MouseButton::Right => Self::Right,
            fret_core::MouseButton::Middle => Self::Middle,
            fret_core::MouseButton::Back
            | fret_core::MouseButton::Forward
            | fret_core::MouseButton::Other(_) => Self::Left,
        }
    }
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UiPointerKindV1 {
    #[default]
    Mouse,
    Touch,
    Pen,
}

#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize)]
pub struct UiKeyModifiersV1 {
    #[serde(default)]
    pub shift: bool,
    #[serde(default)]
    pub ctrl: bool,
    #[serde(default)]
    pub alt: bool,
    #[serde(default)]
    pub meta: bool,
}

impl UiKeyModifiersV1 {
    pub fn from_modifiers(modifiers: fret_core::Modifiers) -> Self {
        Self {
            shift: modifiers.shift,
            ctrl: modifiers.ctrl,
            alt: modifiers.alt,
            meta: modifiers.meta,
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UiWindowDecorationsRequestV1 {
    System,
    None,
    Server,
    Client,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UiTaskbarVisibilityV1 {
    Show,
    Hide,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UiActivationPolicyV1 {
    Activates,
    NonActivating,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UiWindowZLevelV1 {
    Normal,
    AlwaysOnTop,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UiWindowHitTestRequestV1 {
    Normal,
    PassthroughAll,
    PassthroughRegions,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UiWindowAppearanceV1 {
    Opaque,
    CompositedNoBackdrop,
    CompositedBackdrop,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UiWindowBackgroundMaterialRequestV1 {
    None,
    SystemDefault,
    Mica,
    Acrylic,
    Vibrancy,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UiWindowStyleMatchV1 {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub decorations: Option<UiWindowDecorationsRequestV1>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resizable: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub transparent: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub visual_transparent: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub appearance: Option<UiWindowAppearanceV1>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub taskbar: Option<UiTaskbarVisibilityV1>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub activation: Option<UiActivationPolicyV1>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub z_level: Option<UiWindowZLevelV1>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hit_test: Option<UiWindowHitTestRequestV1>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hit_test_regions_fingerprint64: Option<u64>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UiWindowStylePatchV1 {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub taskbar: Option<UiTaskbarVisibilityV1>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub activation: Option<UiActivationPolicyV1>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub z_level: Option<UiWindowZLevelV1>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub decorations: Option<UiWindowDecorationsRequestV1>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resizable: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub transparent: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub background_material: Option<UiWindowBackgroundMaterialRequestV1>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hit_test: Option<UiWindowHitTestPatchV1>,
    /// Global window opacity hint (0..=255), best-effort.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub opacity_alpha_u8: Option<u8>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum UiWindowHitTestPatchV1 {
    Normal,
    PassthroughAll,
    PassthroughRegions {
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        regions: Vec<UiWindowHitTestRegionV1>,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum UiWindowHitTestRegionV1 {
    Rect {
        x: f32,
        y: f32,
        width: f32,
        height: f32,
    },
    RRect {
        x: f32,
        y: f32,
        width: f32,
        height: f32,
        radius: f32,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum UiPredicateV1 {
    Exists {
        target: UiSelectorV1,
    },
    NotExists {
        target: UiSelectorV1,
    },
    /// True when `target` resolves to a node that is a descendant of (or equal to) `scope`.
    ///
    /// This is primarily used to disambiguate selectors when multiple similar widgets exist in a
    /// window (and to keep scripts resilient under overlay/root splits).
    ExistsUnder {
        scope: UiSelectorV1,
        target: UiSelectorV1,
    },
    /// True when `scope` exists and `target` does *not* exist under it.
    ///
    /// Note: if `scope` does not exist, this predicate returns false.
    NotExistsUnder {
        scope: UiSelectorV1,
        target: UiSelectorV1,
    },
    /// True when the currently focused semantics node equals `target` and is a descendant of
    /// (or equal to) `scope`.
    ///
    /// This is a convenience predicate for focus-trap / focus-restore assertions:
    /// - "focus stays within this dialog root"
    /// - "after open, focus moves to the dialog's close button"
    FocusedDescendantIs {
        scope: UiSelectorV1,
        target: UiSelectorV1,
    },
    FocusIs {
        target: UiSelectorV1,
    },
    RoleIs {
        target: UiSelectorV1,
        role: String,
    },
    /// True when the target exists and its semantics `label` contains `text` as a substring.
    LabelContains {
        target: UiSelectorV1,
        text: String,
    },
    /// True when the target exists and its semantics `label` length (UTF-8 bytes) matches `len_bytes`.
    ///
    /// This is intended to remain stable under diagnostics text redaction, where labels may be
    /// replaced with placeholders like `<redacted len=123>`.
    LabelLenIs {
        target: UiSelectorV1,
        len_bytes: u32,
    },
    /// True when the target exists and its semantics `label` length (UTF-8 bytes) is at least `min_len_bytes`.
    LabelLenGe {
        target: UiSelectorV1,
        min_len_bytes: u32,
    },
    /// True when the target exists and its semantics `value` contains `text` as a substring.
    ValueContains {
        target: UiSelectorV1,
        text: String,
    },
    /// True when the target exists and its semantics `value` equals `text`.
    ///
    /// Caution: some widgets use locale-dependent `value` strings; prefer structured predicates
    /// (`SemanticsNumericApproxEq`, `SemanticsScrollApproxEq`, ...) when available.
    ValueEquals {
        target: UiSelectorV1,
        text: String,
    },
    /// True when the target exists and its semantics `value` length (UTF-8 bytes) matches `len_bytes`.
    ///
    /// This is intended to remain stable under diagnostics text redaction, where values may be
    /// replaced with placeholders like `<redacted len=123>`.
    ValueLenIs {
        target: UiSelectorV1,
        len_bytes: u32,
    },
    /// True when the target exists and its semantics `value` length (UTF-8 bytes) is at least `min_len_bytes`.
    ValueLenGe {
        target: UiSelectorV1,
        min_len_bytes: u32,
    },
    /// True when the target exists and its semantics `pos_in_set` equals `pos_in_set`.
    PosInSetIs {
        target: UiSelectorV1,
        pos_in_set: u32,
    },
    /// True when the target exists and its semantics `set_size` equals `set_size`.
    SetSizeIs {
        target: UiSelectorV1,
        set_size: u32,
    },
    CheckedIs {
        target: UiSelectorV1,
        checked: bool,
    },
    SelectedIs {
        target: UiSelectorV1,
        selected: bool,
    },
    /// True when the target exists and its structured semantics numeric field is approximately
    /// equal to the specified value.
    ///
    /// This is intended for range controls (slider/progress-like semantics) which should prefer
    /// `SemanticsNode.extra.numeric.*` over locale-dependent `value` strings.
    SemanticsNumericApproxEq {
        target: UiSelectorV1,
        field: UiSemanticsNumericFieldV1,
        value: f64,
        #[serde(default)]
        eps: f64,
    },
    /// True when the target exists and its structured semantics scroll field is present and finite.
    ///
    /// This is a lightweight gate to ensure `SemanticsNode.extra.scroll.*` is emitted for scroll
    /// containers.
    SemanticsScrollIsFinite {
        target: UiSelectorV1,
        field: UiSemanticsScrollFieldV1,
    },
    /// True when the target exists and its structured semantics scroll field is approximately
    /// equal to the specified value.
    SemanticsScrollApproxEq {
        target: UiSelectorV1,
        field: UiSemanticsScrollFieldV1,
        value: f64,
        #[serde(default)]
        eps: f64,
    },
    /// True when the target exists and its structured semantics scroll field is not approximately
    /// equal to the specified value.
    SemanticsScrollNotApproxEq {
        target: UiSelectorV1,
        field: UiSemanticsScrollFieldV1,
        value: f64,
        #[serde(default)]
        eps: f64,
    },
    /// True when the target exists and its semantics reports whether it currently has an IME
    /// composition range.
    ///
    /// Notes:
    /// - This checks whether `SemanticsNode.text_composition` is `Some(_)`.
    /// - Some platforms/widgets may omit composition ranges even while composing; treat this
    ///   predicate as best-effort and gate it behind appropriate suites.
    TextCompositionIs {
        target: UiSelectorV1,
        composing: bool,
    },
    /// True when the diagnostics runtime has a window-level IME cursor area snapshot.
    ///
    /// Notes:
    /// - This reads `WindowTextInputSnapshot.ime_cursor_area`.
    /// - Coordinates are window logical pixels.
    ImeCursorAreaIsSome {
        is_some: bool,
    },
    /// True when the window-level IME cursor area snapshot is within the current window bounds.
    ///
    /// This is a coarse regression gate for IME geometry bugs (caret/candidate window
    /// teleportation, negative coordinates, far-offscreen rects).
    ImeCursorAreaWithinWindow {
        #[serde(default)]
        padding_px: f32,
        /// Optional per-edge padding (added on top of `padding_px`).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        padding_insets_px: Option<UiPaddingInsetsV1>,
        #[serde(default)]
        eps_px: f32,
    },
    /// True when the window-level IME cursor area snapshot has at least the specified size.
    ///
    /// This can catch "zero rect" bugs where the IME caret geometry is missing meaningful size.
    ImeCursorAreaMinSize {
        #[serde(default)]
        min_w_px: f32,
        #[serde(default)]
        min_h_px: f32,
        #[serde(default)]
        eps_px: f32,
    },
    /// True when the diagnostics runtime has a window-level IME surrounding text excerpt.
    ///
    /// Notes:
    /// - This reads `WindowTextInputSnapshot.surrounding_text`.
    /// - Offsets are UTF-8 byte offsets within the excerpt and should be on char boundaries.
    ImeSurroundingTextIsSome {
        is_some: bool,
    },
    /// True when the window-level IME surrounding text excerpt is present and internally valid.
    ///
    /// This is a coarse regression gate for platform text-input interop (winit `ImeSurroundingText`
    /// constraints: max bytes, offsets within range, char boundaries).
    ImeSurroundingTextValid,
    CheckedIsNone {
        target: UiSelectorV1,
    },
    /// True when the current active item is the specified `item`.
    ///
    /// This supports both common semantics models:
    ///
    /// - Composite widgets that retain focus on a container and express the highlighted row via
    ///   `active_descendant` (DOM-style `aria-activedescendant`).
    /// - Widgets that use roving focus (the focused node itself is the active item).
    ActiveItemIs {
        /// Container node (e.g. listbox). Used when the widget uses `active_descendant`.
        container: UiSelectorV1,
        /// The expected active item (highlighted option / row).
        item: UiSelectorV1,
    },
    /// True when there is no active item (neither roving focus nor `active_descendant`).
    ///
    /// This is primarily intended for combobox/listbox recipes that should not implicitly
    /// highlight the first option on open unless `auto_highlight` is enabled.
    ActiveItemIsNone {
        /// Container node used for composite focus + `active_descendant` models (typically the
        /// focused input or listbox root).
        container: UiSelectorV1,
    },
    BarrierRoots {
        #[serde(default)]
        barrier_root: UiOptionalRootStateV1,
        #[serde(default)]
        focus_barrier_root: UiOptionalRootStateV1,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        require_equal: Option<bool>,
    },
    RenderTextMissingGlyphsIs {
        missing_glyphs: u64,
    },
    /// Ensures that when the renderer reports missing/tofu glyphs for the current frame, a
    /// renderer-owned font fallback trace has been captured and is non-empty.
    ///
    /// This predicate is meant to keep "tofu regressions" debuggable: if missing glyphs happen,
    /// the diagnostics bundle should contain an audit trail of the selected families.
    RenderTextFontTraceCapturedWhenMissingGlyphs,
    /// True when the runner-owned `TextFontStackKey` has not changed for `stable_frames`
    /// consecutive frames.
    ///
    /// This is primarily used to keep perf suites from including one-time system font catalog
    /// rescans (which bump `TextFontStackKey` and can trigger large relayouts) inside a measured
    /// window.
    TextFontStackKeyStable {
        stable_frames: u32,
    },
    /// True when the runner-owned `FontCatalog` has been populated with at least one family.
    ///
    /// On desktop, the runner may seed an empty catalog at startup and populate it asynchronously
    /// via the system font rescan pipeline. This predicate lets scripts wait for that one-time
    /// async work to complete before entering a measured window.
    FontCatalogPopulated,
    /// True when the runner-owned system font rescan pipeline is idle (no work in flight and no
    /// pending restart).
    ///
    /// Desktop runners may perform a one-time async system font rescan at startup. Applying the
    /// result can bump `TextFontStackKey` and trigger large relayouts; this predicate lets perf
    /// suites wait for that one-time work to complete before entering a measured window.
    SystemFontRescanIdle,
    /// True when `debug.resource_loading.asset_load.missing_bundle_asset_requests >= min`.
    ///
    /// This is intended for negative-path diagnostics scripts that deliberately trigger missing
    /// bundle assets and want a structured gate instead of grepping logs.
    AssetLoadMissingBundleAssetRequestsGe {
        min: u64,
    },
    /// True when `debug.resource_loading.asset_load.stale_manifest_requests >= min`.
    ///
    /// This is intended for native/package-dev file-backed manifest lanes where the logical
    /// bundle/key mapping still exists but the manifest-backed file path has gone stale.
    AssetLoadStaleManifestRequestsGe {
        min: u64,
    },
    /// True when `debug.resource_loading.asset_load.unsupported_file_requests >= min`.
    ///
    /// This is intended to gate portable capability degradations where file locators must stay
    /// unsupported on targets like wasm.
    AssetLoadUnsupportedFileRequestsGe {
        min: u64,
    },
    /// True when `debug.resource_loading.asset_load.unsupported_url_requests >= min`.
    AssetLoadUnsupportedUrlRequestsGe {
        min: u64,
    },
    /// True when
    /// `debug.resource_loading.asset_load.external_reference_unavailable_requests >= min`.
    ///
    /// This is intended for byte-only asset surfaces that should not silently claim an external
    /// reference exists.
    AssetLoadExternalReferenceUnavailableRequestsGe {
        min: u64,
    },
    /// True when `debug.resource_loading.asset_load.revision_change_requests >= min`.
    ///
    /// This is intended for hot-reload / invalidation flows where we want to observe that a
    /// locator revision actually changed across snapshots.
    AssetLoadRevisionChangeRequestsGe {
        min: u64,
    },
    /// True when `debug.resource_loading.asset_load.recent[*].outcome_kind` contains
    /// `outcome_kind`.
    ///
    /// Supported values currently mirror the debug snapshot surface:
    /// - `resolved`
    /// - `missing`
    /// - `stale_manifest`
    /// - `unsupported_locator_kind`
    /// - `external_reference_unavailable`
    /// - `resolver_unavailable`
    /// - `access_denied`
    /// - `message`
    AssetLoadRecentOutcomeSeen {
        outcome_kind: String,
    },
    /// True when `debug.resource_loading.asset_load.recent[*].revision_transition` contains
    /// `transition`.
    ///
    /// Supported values currently mirror the debug snapshot surface:
    /// - `initial`
    /// - `stable`
    /// - `changed`
    AssetLoadRecentRevisionTransitionSeen {
        transition: String,
    },
    /// True when `debug.resource_loading.font_environment.bundled_baseline_source == source`.
    ///
    /// Supported values currently mirror the debug snapshot surface:
    /// - `none`
    /// - `bundled_profile`
    BundledFontBaselineSourceIs {
        source: String,
    },
    /// True when `debug.resource_loading.font_environment.renderer_font_environment_revision >= min`.
    RendererFontEnvironmentRevisionGe {
        min: u64,
    },
    /// True when `debug.resource_loading.font_environment.renderer_font_sources[*].source_lane`
    /// contains `lane`.
    ///
    /// Supported values currently mirror the debug snapshot surface:
    /// - `bundled_startup`
    /// - `asset_request`
    RendererFontSourceLaneSeen {
        lane: String,
    },
    /// True when `debug.resource_loading.font_environment.renderer_font_sources[*].asset_key`
    /// contains `asset_key`.
    RendererFontSourceAssetKeySeen {
        asset_key: String,
    },
    /// True when `debug.resource_loading.svg_text_bridge.selection_misses.len() >= min`.
    SvgTextBridgeSelectionMissesGe {
        min: u64,
    },
    /// True when `debug.resource_loading.svg_text_bridge.missing_glyphs.len() >= min`.
    SvgTextBridgeMissingGlyphsGe {
        min: u64,
    },
    /// True when `debug.resource_loading.svg_text_bridge` reports a clean bridge result.
    ///
    /// A clean result means there were no font-selection misses and no missing glyph records.
    SvgTextBridgeDiagnosticsCleanIs {
        clean: bool,
    },
    /// True when `debug.resource_loading.svg_text_bridge.fallback_records[*]` contains the given
    /// `(from_family, to_family)` pair.
    SvgTextBridgeFallbackSeen {
        from_family: String,
        to_family: String,
    },
    /// True when `debug.resource_loading.asset_reload.epoch >= min`.
    ///
    /// This is intended for hot-reload / invalidation flows that want to observe the shared
    /// runtime-global reload epoch directly instead of inferring it indirectly from asset-load
    /// revision transitions.
    AssetReloadEpochGe {
        min: u64,
    },
    /// True when `debug.resource_loading.asset_reload.configured_backend == backend`.
    ///
    /// Supported values currently mirror the debug snapshot surface:
    /// - `poll_metadata`
    /// - `native_watcher`
    AssetReloadConfiguredBackendIs {
        backend: String,
    },
    /// True when `debug.resource_loading.asset_reload.active_backend == backend`.
    ///
    /// Supported values currently mirror the debug snapshot surface:
    /// - `poll_metadata`
    /// - `native_watcher`
    AssetReloadActiveBackendIs {
        backend: String,
    },
    /// True when `debug.resource_loading.asset_reload.fallback_reason == reason`.
    ///
    /// Supported values currently mirror the debug snapshot surface:
    /// - `watcher_install_failed`
    AssetReloadFallbackReasonIs {
        reason: String,
    },
    /// True when the runner has observed an OS accessibility activation request for the current
    /// window.
    ///
    /// This is intended to gate “AccessKit ↔ OS AX is actually live” rather than only asserting
    /// that the app has an internal semantics tree.
    RunnerAccessibilityActivated,
    VisibleInWindow {
        target: UiSelectorV1,
    },
    BoundsWithinWindow {
        target: UiSelectorV1,
        #[serde(default)]
        padding_px: f32,
        /// Optional per-edge padding (added on top of `padding_px`).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        padding_insets_px: Option<UiPaddingInsetsV1>,
        #[serde(default)]
        eps_px: f32,
    },
    /// True when the runtime-published IME cursor area for the focused text input is fully within
    /// the window bounds (minus the specified padding).
    ///
    /// This is intended as a stable regression gate for keyboard-avoidance policies: after
    /// occlusion insets change, the focused caret/cursor area should remain inside the visible
    /// rect derived from safe-area + occlusion.
    TextInputImeCursorAreaWithinWindow {
        #[serde(default)]
        padding_px: f32,
        /// Optional per-edge padding (added on top of `padding_px`).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        padding_insets_px: Option<UiPaddingInsetsV1>,
        #[serde(default)]
        eps_px: f32,
    },
    BoundsMinSize {
        target: UiSelectorV1,
        #[serde(default)]
        min_w_px: f32,
        #[serde(default)]
        min_h_px: f32,
        #[serde(default)]
        eps_px: f32,
    },
    BoundsMaxSize {
        target: UiSelectorV1,
        #[serde(default)]
        max_w_px: f32,
        #[serde(default)]
        max_h_px: f32,
        #[serde(default)]
        eps_px: f32,
    },
    /// True when both targets exist and their bounds match within `eps_px`.
    ///
    /// This is primarily used to gate “hit box vs visual chrome” regressions where a pressable
    /// can stretch but an inner chrome surface must continue to fill the same box.
    BoundsApproxEqual {
        a: UiSelectorV1,
        b: UiSelectorV1,
        #[serde(default)]
        eps_px: f32,
    },
    /// True when both targets exist and their bounds centers match within `eps_px`.
    ///
    /// This is primarily used to gate “stretched hit box + centered fixed chrome” contracts where
    /// the interactive surface can grow via flex/grid/min touch target, but the inner visual chrome
    /// remains fixed-size and centered.
    BoundsCenterApproxEqual {
        a: UiSelectorV1,
        b: UiSelectorV1,
        #[serde(default)]
        eps_px: f32,
    },
    BoundsNonOverlapping {
        a: UiSelectorV1,
        b: UiSelectorV1,
        #[serde(default)]
        eps_px: f32,
    },
    BoundsOverlapping {
        a: UiSelectorV1,
        b: UiSelectorV1,
        #[serde(default)]
        eps_px: f32,
    },
    BoundsOverlappingX {
        a: UiSelectorV1,
        b: UiSelectorV1,
        #[serde(default)]
        eps_px: f32,
    },
    BoundsOverlappingY {
        a: UiSelectorV1,
        b: UiSelectorV1,
        #[serde(default)]
        eps_px: f32,
    },
    /// True when the diagnostics event ring contains an event whose recorded kind equals `kind`.
    ///
    /// This is intentionally a coarse predicate: it is meant to gate “a platform completion was
    /// delivered” without requiring a dedicated predicate per event type.
    EventKindSeen {
        event_kind: String,
    },
    /// True when the app snapshot field addressed by JSON Pointer `pointer` equals `value`.
    ///
    /// This predicate reads the best-effort `app_snapshot` payload published by the app into
    /// diagnostics snapshots. The pointer uses RFC 6901 JSON Pointer syntax (for example:
    /// `/shell/settings_open` or `/shell/last_action`).
    ///
    /// If the app does not publish an `app_snapshot`, or the pointer does not resolve to a value,
    /// this predicate evaluates to false.
    AppSnapshotFieldEquals {
        pointer: String,
        value: serde_json::Value,
    },
    /// True when the diagnostics runtime has observed at least `n` windows.
    ///
    /// This is intended for multi-window scripted repros (tear-off, auxiliary windows).
    KnownWindowCountGe {
        n: u32,
    },
    /// True when the diagnostics runtime has observed exactly `n` windows.
    ///
    /// This is useful for degradation gates where creating additional windows must be prevented
    /// (e.g. Wayland-safe docking tear-off degradation).
    KnownWindowCountIs {
        n: u32,
    },
    /// True when the latest diagnostics snapshot includes platform capability information and it
    /// reports `ui.window_hover_detection == quality`.
    ///
    /// Supported qualities:
    /// - `none`
    /// - `best_effort`
    /// - `reliable`
    PlatformUiWindowHoverDetectionIs {
        quality: String,
    },
    /// True when the platform-level "receiver window at cursor" probe reports that the active
    /// cursor position would be routed to `window` (best-effort).
    ///
    /// This predicate is intended to gate runner-level hit-test passthrough behavior (e.g.
    /// `WM_NCHITTEST` on Win32) without relying on pixel screenshots.
    ///
    /// Capability-gated behind `diag.platform_window_receiver_at_cursor_v1`.
    PlatformWindowReceiverAtCursorIs {
        window: UiWindowTargetV1,
    },
    /// True when the effective (clamped) OS window style for `window` matches the provided facets.
    ///
    /// This predicate is capability-gated and intended for non-pixel regression gates for utility
    /// windows (frameless/transparent/always-on-top posture).
    WindowStyleEffectiveIs {
        window: UiWindowTargetV1,
        style: UiWindowStyleMatchV1,
    },
    /// True when the effective (clamped) OS window background material for `window` matches `material`.
    ///
    /// This predicate is capability-gated and intended to gate deterministic degradation paths
    /// when OS materials are unsupported.
    WindowBackgroundMaterialEffectiveIs {
        window: UiWindowTargetV1,
        material: UiWindowBackgroundMaterialRequestV1,
    },
    /// True when the latest docking diagnostics report an active dock drag whose `current_window`
    /// matches `window`.
    DockDragCurrentWindowIs {
        window: UiWindowTargetV1,
    },
    /// True when the latest diagnostics report an active dock drag whose drag kind matches `kind`.
    ///
    /// Supported kinds:
    /// - `dock_panel`
    /// - `dock_tabs`
    DockDragKindIs {
        drag_kind: String,
    },
    /// True when the latest docking diagnostics report an active dock drag whose runner-owned
    /// moving window matches `window`.
    ///
    /// This is intended for ImGui-style multi-window docking where a torn-off window follows the
    /// cursor while dragging.
    DockDragMovingWindowIs {
        window: UiWindowTargetV1,
    },
    /// True when the latest docking diagnostics report an active dock drag whose
    /// "window under moving window" matches `window`.
    ///
    /// This allows scripts to gate "peek-behind" selection paths without reinterpreting
    /// `dock_drag_current_window_is` (which remains the runner's primary hover/drop routing
    /// target).
    DockDragWindowUnderMovingWindowIs {
        window: UiWindowTargetV1,
    },
    /// True when the latest docking diagnostics report an active dock drag session.
    DockDragActiveIs {
        active: bool,
    },
    /// True when the latest docking diagnostics report that the shell-local dock payload ghost is
    /// visible in the evaluated window.
    ///
    /// This is intended to gate shell choreography: once a real `moving_window` takes ownership
    /// of drag feedback, the in-window payload ghost should no longer paint.
    DockDragPayloadGhostVisibleIs {
        visible: bool,
    },
    /// True when the latest docking diagnostics report a dock drag session with an ImGui-style
    /// "transparent payload" applied to the moving window (e.g. reduced opacity and/or
    /// click-through hit-test passthrough while the dock-floating window follows the cursor).
    DockDragTransparentPayloadAppliedIs {
        applied: bool,
    },
    /// True when the latest docking diagnostics report that the runner successfully applied
    /// click-through hit-test passthrough for the moving window during transparent payload.
    DockDragTransparentPayloadHitTestPassthroughAppliedIs {
        applied: bool,
    },
    /// True when the latest docking diagnostics report a dock drag session whose hovered-window
    /// selection source matches `source`.
    ///
    /// This is primarily intended to gate multi-window docking hand-feel regressions: on
    /// platforms that claim `ui.window_hover_detection=reliable`, we want to ensure the runner is
    /// using an OS-backed "window under cursor" provider rather than a heuristic fallback.
    ///
    /// Supported sources:
    /// - `platform`: any OS-backed platform hover provider
    /// - `platform_win32`
    /// - `platform_macos`
    /// - `latched`
    /// - `heuristic`: any heuristic fallback
    /// - `heuristic_z_order`
    /// - `heuristic_rects`
    /// - `unknown`
    DockDragWindowUnderCursorSourceIs {
        source: String,
    },
    /// True when the latest docking diagnostics report a dock drag session whose
    /// "window under moving window" selection source matches `source`.
    ///
    /// Supported sources:
    /// - `platform`: any OS-backed platform hover provider
    /// - `platform_win32`
    /// - `platform_macos`
    /// - `latched`
    /// - `heuristic`: any heuristic fallback
    /// - `heuristic_z_order`
    /// - `heuristic_rects`
    /// - `unknown`
    DockDragWindowUnderMovingWindowSourceIs {
        source: String,
    },
    /// True when the latest docking diagnostics report an active in-window floating drag session.
    ///
    /// This is intended to gate "floating window" hand-feel regressions without relying on pixels.
    DockFloatingDragActiveIs {
        active: bool,
    },
    /// True when the current docking drop preview kind matches `kind`.
    ///
    /// This predicate reads the window-local `DockDropResolveDiagnostics` snapshot published into
    /// `WindowInteractionDiagnosticsStore` by policy-heavy ecosystem crates (e.g. docking).
    ///
    /// Supported kinds:
    /// - `wrap_binary`
    /// - `insert_into_split`
    DockDropPreviewKindIs {
        preview_kind: String,
    },
    /// True when the current docking drop resolve source matches `source`.
    ///
    /// This predicate reads the window-local `DockDropResolveDiagnostics` snapshot published into
    /// `WindowInteractionDiagnosticsStore` by policy-heavy ecosystem crates (e.g. docking).
    ///
    /// Supported sources:
    /// - `invert_docking`
    /// - `outside_window`
    /// - `float_zone`
    /// - `layout_bounds_miss`
    /// - `latched_previous_hover`
    /// - `tab_bar`
    /// - `floating_title_bar`
    /// - `outer_hint_rect`
    /// - `inner_hint_rect`
    /// - `none`
    DockDropResolveSourceIs {
        source: String,
    },
    /// True when the current docking drop resolve has (or does not have) a resolved target.
    ///
    /// This is useful for policy-gated no-drop zones: scripts can assert that the pointer is over
    /// a *candidate* region (via `dock_drop_resolve_source_is`) while `resolved` stays `None`.
    DockDropResolvedIsSome {
        some: bool,
    },
    /// True when the current docking drop resolve has a resolved target whose `zone` matches
    /// `zone`.
    ///
    /// Supported zones:
    /// - `center`
    /// - `left`
    /// - `right`
    /// - `top`
    /// - `bottom`
    DockDropResolvedZoneIs {
        zone: String,
    },
    /// True when the current docking drop resolve has a resolved target whose `insert_index`
    /// matches `index`.
    ///
    /// This is intended to gate "drop at end" semantics (e.g. `index == tab_count`) without
    /// relying on pixels.
    DockDropResolvedInsertIndexIs {
        index: u32,
    },
    /// True when the latest docking diagnostics report whether the active tab strip is overflowed.
    ///
    /// This predicate reads the best-effort `tab_strip_active_visibility` snapshot recorded by
    /// docking into `WindowInteractionDiagnosticsStore`.
    DockTabStripActiveOverflowIs {
        overflow: bool,
    },
    /// True when the latest docking diagnostics report whether the active tab is visible at the
    /// current tab scroll position.
    ///
    /// This predicate is intended to gate the editor-grade invariant:
    /// "selecting a tab (including via overflow menu) must scroll it into view".
    DockTabStripActiveVisibleIs {
        visible: bool,
    },
    /// True when the latest docking diagnostics report `tab_strip_active_visibility.scroll >= px`.
    ///
    /// This predicate is intended to gate edge auto-scroll during tab drags in overflowed tab
    /// strips, without relying on pixels.
    DockTabStripActiveScrollPxGe {
        px: f32,
    },
    /// True when the latest docking diagnostics report `tab_strip_active_visibility.scroll <= px`.
    ///
    /// This is primarily intended to assert the initial scroll state in scripted regressions.
    DockTabStripActiveScrollPxLe {
        px: f32,
    },
    /// True when the latest workspace diagnostics report whether the active tab strip is overflowed.
    ///
    /// This predicate reads the best-effort `workspace_interaction.tab_strip_active_visibility`
    /// snapshot recorded into `WindowInteractionDiagnosticsStore`.
    WorkspaceTabStripActiveOverflowIs {
        overflow: bool,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pane_id: Option<String>,
    },
    /// True when the latest workspace diagnostics report whether the active tab is visible at the
    /// current tab scroll position.
    ///
    /// This predicate is intended to gate the editor-grade invariant:
    /// "selecting a tab (including via overflow menu) must scroll it into view".
    WorkspaceTabStripActiveVisibleIs {
        visible: bool,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pane_id: Option<String>,
    },
    /// True when the latest workspace diagnostics report `tab_strip_active_visibility.scroll_x >= px`.
    ///
    /// This predicate reads the best-effort `workspace_interaction.tab_strip_active_visibility`
    /// snapshot recorded into `WindowInteractionDiagnosticsStore`.
    WorkspaceTabStripActiveScrollPxGe {
        px: f32,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pane_id: Option<String>,
    },
    /// True when the latest workspace diagnostics report `tab_strip_active_visibility.scroll_x <= px`.
    ///
    /// This predicate reads the best-effort `workspace_interaction.tab_strip_active_visibility`
    /// snapshot recorded into `WindowInteractionDiagnosticsStore`.
    WorkspaceTabStripActiveScrollPxLe {
        px: f32,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pane_id: Option<String>,
    },
    /// True when the latest workspace diagnostics report an active tab strip drag session.
    ///
    /// This predicate reads the best-effort `workspace_interaction.tab_strip_drag` snapshot
    /// recorded into `WindowInteractionDiagnosticsStore`.
    WorkspaceTabStripDragActiveIs {
        active: bool,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pane_id: Option<String>,
    },
    /// True when the latest workspace diagnostics report whether a tab strip drag session is armed
    /// (i.e. tracking a pointer that may become a drag on move threshold).
    ///
    /// This predicate reads the best-effort `workspace_interaction.tab_strip_drag` snapshot
    /// recorded into `WindowInteractionDiagnosticsStore`.
    WorkspaceTabStripDragArmedIs {
        armed: bool,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pane_id: Option<String>,
    },
    /// True when the latest dock graph stats snapshot reports a canonical-form layout.
    DockGraphCanonicalIs {
        canonical: bool,
    },
    /// True when the latest dock graph stats snapshot reports nested same-axis split children.
    DockGraphHasNestedSameAxisSplitsIs {
        has_nested: bool,
    },
    /// True when the latest dock graph stats snapshot reports `node_count <= max`.
    ///
    /// This is intended for scripted regression gates that want to ensure repeated dock operations
    /// do not accidentally allocate unbounded structure (e.g. legacy "wrap" behavior that deepens
    /// the split tree).
    DockGraphNodeCountLe {
        max: u32,
    },
    /// True when the latest dock graph stats snapshot reports `max_split_depth <= max`.
    DockGraphMaxSplitDepthLe {
        max: u32,
    },
    /// True when the latest dock graph signature snapshot matches `signature`.
    ///
    /// This signature is intended to be stable across runs and platforms:
    /// - it does not include split fractions (pointer-driven and DPI-sensitive),
    /// - it does not include floating window rects (platform-dependent).
    DockGraphSignatureIs {
        signature: String,
    },
    /// True when the latest dock graph signature snapshot contains `needle` as a substring.
    ///
    /// This is useful for large layouts where asserting the entire signature string would be too
    /// verbose.
    DockGraphSignatureContains {
        needle: String,
    },
    /// True when the latest dock graph signature snapshot does **not** contain `needle` as a
    /// substring.
    DockGraphSignatureNotContains {
        needle: String,
    },
    /// True when the latest dock graph signature fingerprint matches `fingerprint64`.
    DockGraphSignatureFingerprint64Is {
        fingerprint64: u64,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UiSemanticsNumericFieldV1 {
    Value,
    Min,
    Max,
    Step,
    Jump,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UiSemanticsScrollFieldV1 {
    X,
    XMin,
    XMax,
    Y,
    YMin,
    YMax,
}

#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UiOptionalRootStateV1 {
    #[default]
    Any,
    None,
    Some,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum UiSelectorV1 {
    RoleAndName {
        role: String,
        name: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        root_z_index: Option<u32>,
    },
    RoleAndPath {
        role: String,
        name: String,
        ancestors: Vec<UiRoleAndNameV1>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        root_z_index: Option<u32>,
    },
    TestId {
        id: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        root_z_index: Option<u32>,
    },
    GlobalElementId {
        element: u64,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        root_z_index: Option<u32>,
    },
    NodeId {
        node: u64,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        root_z_index: Option<u32>,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiRoleAndNameV1 {
    pub role: String,
    pub name: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiSemanticsNodeGetV1 {
    pub schema_version: u32,
    pub window: u64,
    pub node_id: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiSemanticsNodeGetAckV1 {
    pub schema_version: u32,
    pub status: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    pub window: u64,
    pub node_id: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub semantics_fingerprint: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub node: Option<serde_json::Value>,
    #[serde(default)]
    pub children: Vec<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub captured_unix_ms: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiHitTestExplainV1 {
    pub schema_version: u32,
    pub window: u64,
    pub target: UiSelectorV1,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiHitTestExplainAckV1 {
    pub schema_version: u32,
    pub status: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    pub window: u64,
    pub target: UiSelectorV1,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub semantics_fingerprint: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hittable: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hit_test: Option<UiHitTestTraceEntryV1>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub captured_unix_ms: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiInspectConfigV1 {
    pub schema_version: u32,
    pub enabled: bool,
    #[serde(default = "serde_default_true")]
    pub consume_clicks: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DevtoolsBundleDumpV1 {
    pub schema_version: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
    /// Optional per-dump cap on how many snapshots are included in the exported bundle.
    ///
    /// When omitted, the runtime uses its configured dump cap (typically
    /// `FRET_DIAG_SCRIPT_DUMP_MAX_SNAPSHOTS` for script-driven dumps, and
    /// `FRET_DIAG_MAX_SNAPSHOTS` for manual dumps).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_snapshots: Option<u32>,
}

/// Request that the app exits as soon as possible.
///
/// This is intended for transport-neutral "exit after run" behavior in CI / scripted automation
/// flows where relying on large timeouts is undesirable.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DevtoolsAppExitRequestV1 {
    pub schema_version: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    /// Optional delay before triggering exit, expressed in wall-clock milliseconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub delay_ms: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DevtoolsBundleDumpedV1 {
    pub schema_version: u32,
    pub exported_unix_ms: u64,
    pub out_dir: String,
    pub dir: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bundle: Option<serde_json::Value>,
    /// Optional chunked representation of the embedded bundle JSON.
    ///
    /// When present, the runtime may send multiple `bundle.dumped` messages (same `exported_unix_ms`
    /// + `dir`) each carrying one chunk. Tooling should reassemble chunks in order to reconstruct
    ///   the full JSON payload.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bundle_json_chunk: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bundle_json_chunk_index: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bundle_json_chunk_count: Option<u32>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DevtoolsScreenshotRequestV1 {
    pub schema_version: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
    #[serde(default = "default_capture_screenshot_timeout_frames")]
    pub timeout_frames: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub window: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DevtoolsScreenshotResultV1 {
    pub schema_version: u32,
    pub status: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    pub request_id: String,
    pub window: u64,
    pub bundle_dir_name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub screenshots_dir: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub entry: Option<serde_json::Value>,
}

/// GPU screenshot request written by the in-app diagnostics runtime, consumed by desktop runners.
///
/// This is the transport between:
///
/// - `ecosystem/fret-bootstrap` (writer; script steps + DevTools WS bridge), and
/// - `crates/fret-launch` (reader; runner-owned GPU readback + PNG encoding).
///
/// Keeping this schema in `fret-diag-protocol` avoids "forked" JSON parsing logic across crates.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiagScreenshotRequestV1 {
    pub schema_version: u32,
    pub out_dir: String,
    pub bundle_dir_name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub request_id: Option<String>,
    #[serde(default)]
    pub windows: Vec<DiagScreenshotWindowRequestV1>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiagScreenshotWindowRequestV1 {
    pub window: u64,
    pub tick_id: u64,
    pub frame_id: u64,
    #[serde(default = "serde_default_one_f64")]
    pub scale_factor: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiagScreenshotResultFileV1 {
    #[serde(default = "default_diag_screenshot_schema_version")]
    pub schema_version: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub updated_unix_ms: Option<u64>,
    #[serde(default)]
    pub completed: Vec<DiagScreenshotResultEntryV1>,
}

impl Default for DiagScreenshotResultFileV1 {
    fn default() -> Self {
        Self {
            schema_version: default_diag_screenshot_schema_version(),
            updated_unix_ms: None,
            completed: Vec::new(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiagScreenshotResultEntryV1 {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub request_id: Option<String>,
    pub bundle_dir_name: String,
    pub window: u64,
    pub tick_id: u64,
    pub frame_id: u64,
    pub scale_factor: f32,
    pub file: String,
    pub width_px: u32,
    pub height_px: u32,
    pub completed_unix_ms: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiArtifactStatsV1 {
    pub schema_version: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bundle_json_bytes: Option<u64>,
    #[serde(default)]
    pub window_count: u64,
    #[serde(default)]
    pub event_count: u64,
    #[serde(default)]
    pub snapshot_count: u64,
    #[serde(default)]
    pub max_snapshots: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dump_max_snapshots: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiScriptResultV1 {
    pub schema_version: u32,
    pub run_id: u64,
    pub updated_unix_ms: u64,
    pub window: Option<u64>,
    pub stage: UiScriptStageV1,
    pub step_index: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason_code: Option<String>,
    pub reason: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub evidence: Option<UiScriptEvidenceV1>,
    pub last_bundle_dir: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_bundle_artifact: Option<UiArtifactStatsV1>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UiScriptEvidenceV1 {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub event_log: Vec<UiScriptEventLogEntryV1>,
    #[serde(default, skip_serializing_if = "is_zero_u64")]
    pub event_log_dropped: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capabilities_check: Option<UiCapabilitiesCheckV1>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub selector_resolution_trace: Vec<UiSelectorResolutionTraceEntryV1>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub hit_test_trace: Vec<UiHitTestTraceEntryV1>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub click_stable_trace: Vec<UiClickStableTraceEntryV1>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub bounds_stable_trace: Vec<UiBoundsStableTraceEntryV1>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub focus_trace: Vec<UiFocusTraceEntryV1>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub shortcut_routing_trace: Vec<UiShortcutRoutingTraceEntryV1>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub command_dispatch_trace: Vec<UiCommandDispatchTraceEntryV1>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub overlay_placement_trace: Vec<UiOverlayPlacementTraceEntryV1>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub web_ime_trace: Vec<UiWebImeTraceEntryV1>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub ime_event_trace: Vec<UiImeEventTraceEntryV1>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiCapabilitiesCheckV1 {
    pub schema_version: u32,
    pub source: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub required: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub available: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub missing: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiScriptEventLogEntryV1 {
    pub unix_ms: u64,
    pub kind: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub step_index: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bundle_dir: Option<String>,
    /// When available, identifies the window that observed/emitted this event.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub window: Option<u64>,
    /// When available, the app tick id at the time of the event.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tick_id: Option<u64>,
    /// When available, the app frame id at the time of the event.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub frame_id: Option<u64>,
    /// Optional per-window snapshot sequence hint (may be resolved by tooling from `bundle.index.json`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub window_snapshot_seq: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiSelectorResolutionTraceEntryV1 {
    pub step_index: u32,
    pub selector: UiSelectorV1,
    #[serde(default)]
    pub match_count: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub chosen_node_id: Option<u64>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub candidates: Vec<UiSelectorResolutionCandidateV1>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiSelectorResolutionCandidateV1 {
    pub node_id: u64,
    pub role: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub test_id: Option<String>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct UiPointV1 {
    pub x_px: f32,
    pub y_px: f32,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct UiRectV1 {
    pub x_px: f32,
    pub y_px: f32,
    pub w_px: f32,
    pub h_px: f32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiHitTestTraceEntryV1 {
    pub step_index: u32,
    pub selector: UiSelectorV1,
    pub position: UiPointV1,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub intended_node_id: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub intended_test_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub intended_bounds: Option<UiRectV1>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hit_node_id: Option<u64>,
    /// Debug-only path from the root to `hit_node_id` (inclusive).
    ///
    /// Treat node ids as in-run references only; they are not stable across runs.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub hit_node_path: Vec<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hit_semantics_node_id: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hit_semantics_test_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub includes_intended: Option<bool>,
    /// Best-effort: whether the hit-test path contains the intended node id.
    ///
    /// Useful for diagnosing “clicked the right region but an overlay/capture blocked delivery”.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hit_path_contains_intended: Option<bool>,
    /// Best-effort attribution for why the intended target did not receive injected input.
    ///
    /// This is a convenience field intended for triage tools and AI. Prefer inspecting the raw
    /// evidence fields when debugging novel cases.
    ///
    /// Stable strings (start small; expand only when evidence becomes more actionable):
    /// - `modal_barrier` (a modal barrier is active)
    /// - `focus_barrier` (a focus barrier is active)
    /// - `pointer_capture` (pointer capture is active)
    /// - `pointer_occlusion` (pointer occlusion blocks underlay input)
    /// - `no_hit` (hit-test produced no node)
    /// - `miss` (hit-test landed on a different node)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub blocking_reason: Option<String>,
    /// Best-effort in-run root reference associated with `blocking_reason` (when applicable).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub blocking_root: Option<u64>,
    /// Best-effort layer id associated with `blocking_reason` (when applicable).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub blocking_layer_id: Option<u64>,
    /// Best-effort human-readable explanation for `blocking_reason`.
    ///
    /// This is intended for fast triage and AI; treat it as a hint rather than a contract.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub routing_explain: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub barrier_root: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub focus_barrier_root: Option<u64>,
    /// The input arbitration snapshot at the time this trace entry was recorded.
    ///
    /// These fields are primarily useful for explaining why injected input did not reach the
    /// underlay (pointer occlusion/capture/focus barriers).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pointer_occlusion: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pointer_occlusion_layer_id: Option<u64>,
    /// Best-effort pointer occlusion owner (in-run references only).
    ///
    /// When `pointer_occlusion_layer_id` is present, these fields attempt to resolve the layer
    /// root to a semantics node for easier triage.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pointer_occlusion_node_id: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pointer_occlusion_test_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pointer_occlusion_role: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pointer_occlusion_bounds: Option<UiRectV1>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pointer_capture_active: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pointer_capture_layer_id: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pointer_capture_multiple_layers: Option<bool>,
    /// Best-effort pointer capture owner (in-run references only).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pointer_capture_node_id: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pointer_capture_test_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pointer_capture_role: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pointer_capture_bounds: Option<UiRectV1>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pointer_capture_element: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pointer_capture_element_path: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub scope_roots: Vec<UiHitTestScopeRootEvidenceV1>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiClickStableTraceEntryV1 {
    pub step_index: u32,
    pub stable_required: u32,
    pub stable_count: u32,
    pub moved_px: f32,
    pub max_move_px: f32,
    pub remaining_frames: u32,
    pub hit_test: UiHitTestTraceEntryV1,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiBoundsStableTraceEntryV1 {
    pub step_index: u32,
    pub selector: UiSelectorV1,
    pub stable_required: u32,
    pub stable_count: u32,
    pub moved_px: f32,
    pub max_move_px: f32,
    pub remaining_frames: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bounds: Option<UiRectV1>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiHitTestScopeRootEvidenceV1 {
    pub kind: String,
    pub root: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub layer_id: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pointer_occlusion: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub blocks_underlay_input: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hit_testable: Option<bool>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiFocusTraceEntryV1 {
    pub step_index: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason_code: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub text_input_snapshot: Option<UiTextInputSnapshotV1>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expected_node_id: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expected_test_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub modal_barrier_root: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub focus_barrier_root: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pointer_occlusion: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pointer_occlusion_layer_id: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pointer_capture_active: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pointer_capture_layer_id: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pointer_capture_multiple_layers: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub focused_element: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub focused_element_path: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub focused_node_id: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub focused_test_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub focused_role: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub matches_expected: Option<bool>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiTextInputSnapshotV1 {
    #[serde(default)]
    pub focus_is_text_input: bool,
    #[serde(default)]
    pub is_composing: bool,
    #[serde(default)]
    pub text_len_utf16: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub selection_utf16: Option<(u32, u32)>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub marked_utf16: Option<(u32, u32)>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ime_cursor_area: Option<UiRectV1>,
    /// Optional IME surrounding text excerpt metadata (bytes).
    ///
    /// This is derived from `WindowTextInputSnapshot.surrounding_text` and is intended for
    /// lightweight debugging without embedding potentially sensitive text contents in bundles.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ime_surrounding_text_len_bytes: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ime_surrounding_cursor_bytes: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ime_surrounding_anchor_bytes: Option<u32>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiShortcutRoutingTraceEntryV1 {
    pub step_index: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
    #[serde(default)]
    pub frame_id: u64,
    pub phase: String,
    #[serde(default)]
    pub deferred: bool,
    #[serde(default)]
    pub focus_is_text_input: bool,
    #[serde(default)]
    pub ime_composing: bool,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub key_contexts: Vec<String>,
    pub key: String,
    pub modifiers: UiKeyModifiersV1,
    pub repeat: bool,
    pub outcome: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub command_enabled: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pending_sequence_len: Option<u32>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UiOverlayPlacementTraceKindV1 {
    AnchoredPanel,
    PlacedRect,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct UiShortcutRoutingTraceQueryV1 {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub phase: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub outcome: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub key: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ime_composing: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub focus_is_text_input: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub key_context: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiCommandDispatchTraceEntryV1 {
    pub step_index: u32,
    pub frame_id: u64,
    pub command: String,
    pub handled: bool,
    /// Best-effort handler scope classification (ADR 0307).
    ///
    /// Expected values: `"widget"`, `"window"`, `"app"`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub handled_by_scope: Option<String>,
    /// Whether the command was handled by a runner/driver integration layer (not by a UI element).
    #[serde(default)]
    pub handled_by_driver: bool,
    #[serde(default)]
    pub stopped: bool,
    #[serde(default)]
    pub source_kind: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_element: Option<u64>,
    /// Best-effort stable selector attribution for pointer-triggered dispatch.
    ///
    /// This is intended to help scripted diagnostics answer:
    /// “which `test_id` caused this command to dispatch?”
    ///
    /// Notes:
    /// - This is a best-effort hint (additive). Tooling should fall back to correlating
    ///   `source_element` with the semantics snapshot if needed.
    /// - When available, this is usually populated from the hit-test trace recorded for the
    ///   injected pointer step.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_test_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub handled_by_element: Option<u64>,
    /// Best-effort stable selector attribution for the first widget that handled the command.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub handled_by_test_id: Option<String>,
    #[serde(default)]
    pub started_from_focus: bool,
    #[serde(default)]
    pub used_default_root_fallback: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct UiCommandDispatchTraceQueryV1 {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_kind: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_test_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub handled: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub handled_by_scope: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub handled_by_driver: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub handled_by_test_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub started_from_focus: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub used_default_root_fallback: Option<bool>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UiLayoutDirectionV1 {
    Ltr,
    Rtl,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UiOverlaySideV1 {
    Top,
    Bottom,
    Left,
    Right,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UiOverlayAlignV1 {
    Start,
    Center,
    End,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UiOverlayStickyModeV1 {
    Partial,
    Always,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct UiEdgesV1 {
    pub top_px: f32,
    pub right_px: f32,
    pub bottom_px: f32,
    pub left_px: f32,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct UiSizeV1 {
    pub w_px: f32,
    pub h_px: f32,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct UiOverlayOffsetV1 {
    pub main_axis_px: f32,
    pub cross_axis_px: f32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub alignment_axis_px: Option<f32>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct UiOverlayShiftV1 {
    pub main_axis: bool,
    pub cross_axis: bool,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct UiOverlayArrowLayoutV1 {
    pub side: UiOverlaySideV1,
    pub offset_px: f32,
    pub alignment_offset_px: f32,
    pub center_offset_px: f32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum UiOverlayPlacementTraceEntryV1 {
    AnchoredPanel {
        step_index: u32,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        note: Option<String>,
        #[serde(default)]
        frame_id: u64,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        overlay_root_name: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        anchor_element: Option<u64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        anchor_test_id: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        content_element: Option<u64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        content_test_id: Option<String>,

        outer_input: UiRectV1,
        outer_collision: UiRectV1,
        anchor: UiRectV1,
        desired: UiSizeV1,
        side_offset_px: f32,
        preferred_side: UiOverlaySideV1,
        align: UiOverlayAlignV1,
        direction: UiLayoutDirectionV1,
        sticky: UiOverlayStickyModeV1,
        offset: UiOverlayOffsetV1,
        shift: UiOverlayShiftV1,
        collision_padding: UiEdgesV1,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        collision_boundary: Option<UiRectV1>,
        gap_px: f32,

        preferred_rect: UiRectV1,
        flipped_rect: UiRectV1,
        #[serde(default)]
        preferred_fits_without_main_clamp: bool,
        #[serde(default)]
        flipped_fits_without_main_clamp: bool,
        #[serde(default)]
        preferred_available_main_px: f32,
        #[serde(default)]
        flipped_available_main_px: f32,
        chosen_side: UiOverlaySideV1,
        chosen_rect: UiRectV1,
        rect_after_shift: UiRectV1,
        shift_delta: UiPointV1,
        final_rect: UiRectV1,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        arrow: Option<UiOverlayArrowLayoutV1>,
    },
    PlacedRect {
        step_index: u32,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        note: Option<String>,
        #[serde(default)]
        frame_id: u64,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        overlay_root_name: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        anchor_element: Option<u64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        anchor_test_id: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        content_element: Option<u64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        content_test_id: Option<String>,
        outer: UiRectV1,
        anchor: UiRectV1,
        placed: UiRectV1,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        side: Option<UiOverlaySideV1>,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct UiOverlayPlacementTraceQueryV1 {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kind: Option<UiOverlayPlacementTraceKindV1>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub overlay_root_name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub anchor_test_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub content_test_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub preferred_side: Option<UiOverlaySideV1>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub chosen_side: Option<UiOverlaySideV1>,
    /// For `kind=anchored_panel`, whether the solver flipped away from `preferred_side`.
    /// Equivalent to `chosen_side != preferred_side` when both are available.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub flipped: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub align: Option<UiOverlayAlignV1>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sticky: Option<UiOverlayStickyModeV1>,
}

/// Debug-only snapshot for the wasm textarea IME bridge (ADR 0180).
///
/// This is intended for diagnostics evidence and is not a normative contract surface.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiWebImeTraceEntryV1 {
    pub step_index: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,

    #[serde(default)]
    pub enabled: bool,
    #[serde(default)]
    pub composing: bool,
    #[serde(default)]
    pub suppress_next_input: bool,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub textarea_has_focus: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub active_element_tag: Option<String>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub position_mode: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mount_kind: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub device_pixel_ratio: Option<f64>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub textarea_selection_start_utf16: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub textarea_selection_end_utf16: Option<u32>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_cursor_area: Option<UiRectV1>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_cursor_anchor_px: Option<(f32, f32)>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_input_type: Option<String>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_preedit_len: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_preedit_cursor_utf16: Option<(u32, u32)>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_commit_len: Option<u32>,

    #[serde(default)]
    pub beforeinput_seen: u64,
    #[serde(default)]
    pub input_seen: u64,
    #[serde(default)]
    pub suppressed_input_seen: u64,
    #[serde(default)]
    pub composition_start_seen: u64,
    #[serde(default)]
    pub composition_update_seen: u64,
    #[serde(default)]
    pub composition_end_seen: u64,
    #[serde(default)]
    pub cursor_area_set_seen: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiImeEventTraceEntryV1 {
    pub step_index: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
    pub kind: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub preedit_len: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub preedit_cursor: Option<(u32, u32)>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub commit_len: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub delete_surrounding: Option<(u32, u32)>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UiScriptStageV1 {
    Queued,
    Running,
    Passed,
    Failed,
}

fn serde_default_true() -> bool {
    true
}

fn serde_default_one_f64() -> f64 {
    1.0
}

fn default_diag_screenshot_schema_version() -> u32 {
    1
}

fn is_zero_u64(v: &u64) -> bool {
    *v == 0
}

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

    #[test]
    fn devtools_app_exit_request_serializes_minimally() {
        let value = serde_json::to_value(DevtoolsAppExitRequestV1 {
            schema_version: 1,
            reason: None,
            delay_ms: None,
        })
        .unwrap();
        assert_eq!(value, serde_json::json!({ "schema_version": 1 }));
    }

    #[test]
    fn predicate_runner_accessibility_activated_serializes_and_deserializes() {
        let value = serde_json::to_value(UiPredicateV1::RunnerAccessibilityActivated).unwrap();
        assert_eq!(
            value,
            serde_json::json!({ "kind": "runner_accessibility_activated" })
        );

        let roundtrip: UiPredicateV1 = serde_json::from_value(value).unwrap();
        assert!(matches!(
            roundtrip,
            UiPredicateV1::RunnerAccessibilityActivated
        ));
    }

    #[test]
    fn predicate_app_snapshot_field_equals_serializes_minimally() {
        let value = serde_json::to_value(UiPredicateV1::AppSnapshotFieldEquals {
            pointer: "/shell/settings_open".to_string(),
            value: serde_json::json!(true),
        })
        .unwrap();

        assert_eq!(
            value,
            serde_json::json!({
                "kind": "app_snapshot_field_equals",
                "pointer": "/shell/settings_open",
                "value": true,
            })
        );

        let roundtrip: UiPredicateV1 = serde_json::from_value(value).unwrap();
        assert!(matches!(
            roundtrip,
            UiPredicateV1::AppSnapshotFieldEquals { .. }
        ));
    }

    #[test]
    fn predicate_bounds_approx_equal_serializes_and_deserializes() {
        let value = serde_json::to_value(UiPredicateV1::BoundsApproxEqual {
            a: UiSelectorV1::TestId {
                id: "a".to_string(),
                root_z_index: None,
            },
            b: UiSelectorV1::TestId {
                id: "b".to_string(),
                root_z_index: None,
            },
            eps_px: 1.0,
        })
        .unwrap();

        assert_eq!(
            value,
            serde_json::json!({
                "kind": "bounds_approx_equal",
                "a": { "kind": "test_id", "id": "a" },
                "b": { "kind": "test_id", "id": "b" },
                "eps_px": 1.0
            })
        );

        let roundtrip: UiPredicateV1 = serde_json::from_value(value).unwrap();
        assert!(matches!(roundtrip, UiPredicateV1::BoundsApproxEqual { .. }));
    }

    #[test]
    fn predicate_bounds_center_approx_equal_serializes_and_deserializes() {
        let value = serde_json::to_value(UiPredicateV1::BoundsCenterApproxEqual {
            a: UiSelectorV1::TestId {
                id: "a".to_string(),
                root_z_index: None,
            },
            b: UiSelectorV1::TestId {
                id: "b".to_string(),
                root_z_index: None,
            },
            eps_px: 1.0,
        })
        .unwrap();

        assert_eq!(
            value,
            serde_json::json!({
                "kind": "bounds_center_approx_equal",
                "a": { "kind": "test_id", "id": "a" },
                "b": { "kind": "test_id", "id": "b" },
                "eps_px": 1.0
            })
        );

        let roundtrip: UiPredicateV1 = serde_json::from_value(value).unwrap();
        assert!(matches!(
            roundtrip,
            UiPredicateV1::BoundsCenterApproxEqual { .. }
        ));
    }

    #[test]
    fn predicate_exists_under_serializes_minimally() {
        let value = serde_json::to_value(UiPredicateV1::ExistsUnder {
            scope: UiSelectorV1::TestId {
                id: "scope".to_string(),
                root_z_index: None,
            },
            target: UiSelectorV1::TestId {
                id: "target".to_string(),
                root_z_index: None,
            },
        })
        .unwrap();

        assert_eq!(
            value,
            serde_json::json!({
                "kind": "exists_under",
                "scope": { "kind": "test_id", "id": "scope" },
                "target": { "kind": "test_id", "id": "target" },
            })
        );

        let roundtrip: UiPredicateV1 = serde_json::from_value(value).unwrap();
        assert!(matches!(roundtrip, UiPredicateV1::ExistsUnder { .. }));
    }

    #[test]
    fn predicate_value_equals_serializes_minimally() {
        let value = serde_json::to_value(UiPredicateV1::ValueEquals {
            target: UiSelectorV1::TestId {
                id: "name".to_string(),
                root_z_index: None,
            },
            text: "Alice".to_string(),
        })
        .unwrap();

        assert_eq!(
            value,
            serde_json::json!({
                "kind": "value_equals",
                "target": { "kind": "test_id", "id": "name" },
                "text": "Alice",
            })
        );

        let roundtrip: UiPredicateV1 = serde_json::from_value(value).unwrap();
        assert!(matches!(roundtrip, UiPredicateV1::ValueEquals { .. }));
    }

    #[test]
    fn predicate_focused_descendant_is_serializes_minimally() {
        let value = serde_json::to_value(UiPredicateV1::FocusedDescendantIs {
            scope: UiSelectorV1::TestId {
                id: "dialog".to_string(),
                root_z_index: None,
            },
            target: UiSelectorV1::TestId {
                id: "close".to_string(),
                root_z_index: None,
            },
        })
        .unwrap();

        assert_eq!(
            value,
            serde_json::json!({
                "kind": "focused_descendant_is",
                "scope": { "kind": "test_id", "id": "dialog" },
                "target": { "kind": "test_id", "id": "close" },
            })
        );

        let roundtrip: UiPredicateV1 = serde_json::from_value(value).unwrap();
        assert!(matches!(
            roundtrip,
            UiPredicateV1::FocusedDescendantIs { .. }
        ));
    }

    #[test]
    fn predicate_dock_tab_strip_scroll_predicates_serialize_and_deserialize() {
        let value =
            serde_json::to_value(UiPredicateV1::DockTabStripActiveScrollPxGe { px: 12.0 }).unwrap();
        assert_eq!(
            value,
            serde_json::json!({
                "kind": "dock_tab_strip_active_scroll_px_ge",
                "px": 12.0
            })
        );
        let roundtrip: UiPredicateV1 = serde_json::from_value(value).unwrap();
        assert!(matches!(
            roundtrip,
            UiPredicateV1::DockTabStripActiveScrollPxGe { .. }
        ));

        let value =
            serde_json::to_value(UiPredicateV1::DockTabStripActiveScrollPxLe { px: 0.0 }).unwrap();
        assert_eq!(
            value,
            serde_json::json!({
                "kind": "dock_tab_strip_active_scroll_px_le",
                "px": 0.0
            })
        );
        let roundtrip: UiPredicateV1 = serde_json::from_value(value).unwrap();
        assert!(matches!(
            roundtrip,
            UiPredicateV1::DockTabStripActiveScrollPxLe { .. }
        ));
    }

    #[test]
    fn predicate_workspace_tab_strip_scroll_predicates_serialize_and_deserialize() {
        let value = serde_json::to_value(UiPredicateV1::WorkspaceTabStripActiveScrollPxGe {
            px: 12.0,
            pane_id: None,
        })
        .unwrap();
        assert_eq!(
            value,
            serde_json::json!({
                "kind": "workspace_tab_strip_active_scroll_px_ge",
                "px": 12.0
            })
        );
        let roundtrip: UiPredicateV1 = serde_json::from_value(value).unwrap();
        assert!(matches!(
            roundtrip,
            UiPredicateV1::WorkspaceTabStripActiveScrollPxGe { .. }
        ));

        let value = serde_json::to_value(UiPredicateV1::WorkspaceTabStripActiveScrollPxLe {
            px: 0.0,
            pane_id: Some("pane-a".to_string()),
        })
        .unwrap();
        assert_eq!(
            value,
            serde_json::json!({
                "kind": "workspace_tab_strip_active_scroll_px_le",
                "px": 0.0,
                "pane_id": "pane-a",
            })
        );
        let roundtrip: UiPredicateV1 = serde_json::from_value(value).unwrap();
        assert!(matches!(
            roundtrip,
            UiPredicateV1::WorkspaceTabStripActiveScrollPxLe { .. }
        ));
    }

    #[test]
    fn diag_screenshot_request_round_trips_and_defaults_scale_factor() {
        let json = serde_json::json!({
            "schema_version": 1,
            "out_dir": "target/fret-diag",
            "bundle_dir_name": "1700000-bundle",
            "request_id": "req-1",
            "windows": [{
                "window": 123,
                "tick_id": 1,
                "frame_id": 2
            }]
        });
        let parsed: DiagScreenshotRequestV1 = serde_json::from_value(json).unwrap();
        assert_eq!(parsed.schema_version, 1);
        assert_eq!(parsed.windows.len(), 1);
        assert_eq!(parsed.windows[0].scale_factor, 1.0);

        let value = serde_json::to_value(parsed).unwrap();
        assert_eq!(value["schema_version"].as_u64(), Some(1));
    }

    #[test]
    fn diag_screenshot_result_defaults_schema_version_to_1() {
        let value = serde_json::json!({
            "updated_unix_ms": 1700000,
            "completed": [],
        });
        let parsed: DiagScreenshotResultFileV1 = serde_json::from_value(value).unwrap();
        assert_eq!(parsed.schema_version, 1);
        assert_eq!(DiagScreenshotResultFileV1::default().schema_version, 1);
    }

    #[test]
    fn click_step_pointer_kind_round_trips_and_omits_none() {
        let step = UiActionStepV2::Click {
            window: None,
            pointer_kind: None,
            target: UiSelectorV1::TestId {
                id: "a".to_string(),
                root_z_index: None,
            },
            button: UiMouseButtonV1::Left,
            click_count: 1,
            modifiers: None,
        };
        let value = serde_json::to_value(step.clone()).unwrap();
        assert_eq!(
            value,
            serde_json::json!({
              "type": "click",
              "target": {"kind":"test_id","id":"a"},
              "button": "left"
            })
        );

        let parsed: UiActionStepV2 = serde_json::from_value(serde_json::json!({
          "type": "click",
          "pointer_kind": "touch",
          "target": {"kind":"test_id","id":"a"},
          "button": "left",
          "click_count": 1
        }))
        .unwrap();
        assert!(matches!(
            parsed,
            UiActionStepV2::Click {
                pointer_kind: Some(UiPointerKindV1::Touch),
                ..
            }
        ));
    }

    #[test]
    fn tap_step_pointer_kind_round_trips_and_omits_none() {
        let step = UiActionStepV2::Tap {
            window: None,
            pointer_kind: None,
            target: UiSelectorV1::TestId {
                id: "a".to_string(),
                root_z_index: None,
            },
            modifiers: None,
        };
        let value = serde_json::to_value(step.clone()).unwrap();
        assert_eq!(
            value,
            serde_json::json!({
              "type": "tap",
              "target": {"kind":"test_id","id":"a"}
            })
        );

        let parsed: UiActionStepV2 = serde_json::from_value(serde_json::json!({
          "type": "tap",
          "pointer_kind": "pen",
          "target": {"kind":"test_id","id":"a"}
        }))
        .unwrap();
        assert!(matches!(
            parsed,
            UiActionStepV2::Tap {
                pointer_kind: Some(UiPointerKindV1::Pen),
                ..
            }
        ));
    }

    #[test]
    fn long_press_step_round_trips_and_omits_defaults() {
        let step = UiActionStepV2::LongPress {
            window: None,
            pointer_kind: None,
            target: UiSelectorV1::TestId {
                id: "a".to_string(),
                root_z_index: None,
            },
            duration_ms: default_long_press_duration_ms(),
            modifiers: None,
        };
        let value = serde_json::to_value(step.clone()).unwrap();
        assert_eq!(
            value,
            serde_json::json!({
              "type": "long_press",
              "target": {"kind":"test_id","id":"a"}
            })
        );

        let parsed: UiActionStepV2 = serde_json::from_value(serde_json::json!({
          "type": "long_press",
          "pointer_kind": "pen",
          "target": {"kind":"test_id","id":"a"},
          "duration_ms": 125
        }))
        .unwrap();
        assert!(matches!(
            parsed,
            UiActionStepV2::LongPress {
                pointer_kind: Some(UiPointerKindV1::Pen),
                duration_ms: 125,
                ..
            }
        ));
    }

    #[test]
    fn swipe_step_round_trips_and_omits_defaults() {
        let step = UiActionStepV2::Swipe {
            window: None,
            pointer_kind: None,
            target: UiSelectorV1::TestId {
                id: "a".to_string(),
                root_z_index: None,
            },
            delta_x: 12.0,
            delta_y: -8.0,
            steps: default_drag_steps(),
            modifiers: None,
        };
        let value = serde_json::to_value(step.clone()).unwrap();
        assert_eq!(
            value,
            serde_json::json!({
              "type": "swipe",
              "target": {"kind":"test_id","id":"a"},
              "delta_x": 12.0,
              "delta_y": -8.0
            })
        );

        let parsed: UiActionStepV2 = serde_json::from_value(serde_json::json!({
          "type": "swipe",
          "pointer_kind": "pen",
          "target": {"kind":"test_id","id":"a"},
          "delta_x": 1.0,
          "delta_y": 2.0,
          "steps": 3
        }))
        .unwrap();
        assert!(matches!(
            parsed,
            UiActionStepV2::Swipe {
                pointer_kind: Some(UiPointerKindV1::Pen),
                steps: 3,
                ..
            }
        ));
    }

    #[test]
    fn step_activate_deserializes_with_defaults() {
        let value = serde_json::json!({
            "type": "activate",
            "target": { "kind": "test_id", "id": "trigger" }
        });

        let step: UiActionStepV2 = serde_json::from_value(value).unwrap();
        match step {
            UiActionStepV2::Activate { window, target } => {
                assert!(window.is_none());
                assert!(matches!(target, UiSelectorV1::TestId { .. }));
            }
            _ => panic!("expected activate"),
        }
    }

    #[test]
    fn step_focus_deserializes_with_defaults() {
        let value = serde_json::json!({
            "type": "focus",
            "target": { "kind": "test_id", "id": "trigger" }
        });

        let step: UiActionStepV2 = serde_json::from_value(value).unwrap();
        match step {
            UiActionStepV2::Focus { window, target } => {
                assert!(window.is_none());
                assert!(matches!(target, UiSelectorV1::TestId { .. }));
            }
            _ => panic!("expected focus"),
        }
    }

    #[test]
    fn hit_test_explain_request_round_trips() {
        let value = serde_json::json!({
            "schema_version": 1,
            "window": 7,
            "target": { "kind": "test_id", "id": "trigger" }
        });
        let req: UiHitTestExplainV1 = serde_json::from_value(value.clone()).unwrap();
        assert_eq!(req.window, 7);
        assert_eq!(serde_json::to_value(req).unwrap(), value);
    }

    #[test]
    fn step_paste_text_into_deserializes_with_defaults() {
        let value = serde_json::json!({
            "type": "paste_text_into",
            "target": { "kind": "test_id", "id": "field" },
            "text": "Hello"
        });

        let step: UiActionStepV2 = serde_json::from_value(value).unwrap();
        match step {
            UiActionStepV2::PasteTextInto {
                window,
                pointer_kind,
                target,
                text,
                clear_before_paste,
                timeout_frames,
            } => {
                assert!(window.is_none());
                assert!(pointer_kind.is_none());
                assert!(matches!(target, UiSelectorV1::TestId { .. }));
                assert_eq!(text, "Hello");
                assert!(!clear_before_paste);
                assert_eq!(timeout_frames, default_action_timeout_frames());
            }
            _ => panic!("expected paste_text_into"),
        }
    }

    #[test]
    fn step_set_text_value_deserializes_with_defaults() {
        let value = serde_json::json!({
            "type": "set_text_value",
            "target": { "kind": "test_id", "id": "field" },
            "text": "#112233"
        });

        let step: UiActionStepV2 = serde_json::from_value(value).unwrap();
        match step {
            UiActionStepV2::SetTextValue {
                window,
                target,
                text,
                timeout_frames,
            } => {
                assert!(window.is_none());
                assert!(matches!(target, UiSelectorV1::TestId { .. }));
                assert_eq!(text, "#112233");
                assert_eq!(timeout_frames, default_action_timeout_frames());
            }
            _ => panic!("expected set_text_value"),
        }
    }

    #[test]
    fn step_wait_clipboard_write_result_deserializes_with_defaults() {
        let value = serde_json::json!({
            "type": "wait_clipboard_write_result",
            "outcome": "success"
        });

        let step: UiActionStepV2 = serde_json::from_value(value).unwrap();
        match step {
            UiActionStepV2::WaitClipboardWriteResult {
                outcome,
                error_kind,
                message_contains,
                timeout_frames,
            } => {
                assert_eq!(outcome, UiClipboardWriteResultV1::Success);
                assert!(error_kind.is_none());
                assert!(message_contains.is_none());
                assert_eq!(timeout_frames, default_action_timeout_frames());
            }
            _ => panic!("expected wait_clipboard_write_result"),
        }
    }

    #[test]
    fn step_assert_clipboard_write_result_deserializes_with_failure_details() {
        let value = serde_json::json!({
            "type": "assert_clipboard_write_result",
            "outcome": "failure",
            "error_kind": "unavailable",
            "message_contains": "forced clipboard unavailable",
            "timeout_frames": 90
        });

        let step: UiActionStepV2 = serde_json::from_value(value).unwrap();
        match step {
            UiActionStepV2::AssertClipboardWriteResult {
                outcome,
                error_kind,
                message_contains,
                timeout_frames,
            } => {
                assert_eq!(outcome, UiClipboardWriteResultV1::Failure);
                assert_eq!(error_kind, Some(UiClipboardAccessErrorKindV1::Unavailable));
                assert_eq!(
                    message_contains.as_deref(),
                    Some("forced clipboard unavailable")
                );
                assert_eq!(timeout_frames, 90);
            }
            _ => panic!("expected assert_clipboard_write_result"),
        }
    }

    #[test]
    fn step_inspect_help_lock_best_match_and_copy_selector_deserializes_with_defaults() {
        let value = serde_json::json!({
            "type": "inspect_help_lock_best_match_and_copy_selector",
            "query": "ui-gallery-nav-search"
        });

        let step: UiActionStepV2 = serde_json::from_value(value).unwrap();
        match step {
            UiActionStepV2::InspectHelpLockBestMatchAndCopySelector {
                window,
                query,
                timeout_frames,
            } => {
                assert!(window.is_none());
                assert_eq!(query, "ui-gallery-nav-search");
                assert_eq!(timeout_frames, default_action_timeout_frames());
            }
            _ => panic!("expected inspect_help_lock_best_match_and_copy_selector"),
        }
    }

    #[test]
    fn step_inspect_help_tree_lock_best_match_and_copy_selector_deserializes_with_defaults() {
        let value = serde_json::json!({
            "type": "inspect_help_tree_lock_best_match_and_copy_selector",
            "query": "ui-gallery-nav-search"
        });

        let step: UiActionStepV2 = serde_json::from_value(value).unwrap();
        match step {
            UiActionStepV2::InspectHelpTreeLockBestMatchAndCopySelector {
                window,
                query,
                timeout_frames,
            } => {
                assert!(window.is_none());
                assert_eq!(query, "ui-gallery-nav-search");
                assert_eq!(timeout_frames, default_action_timeout_frames());
            }
            _ => panic!("expected inspect_help_tree_lock_best_match_and_copy_selector"),
        }
    }

    #[test]
    fn step_wait_until_deserializes_with_default_timeout_frames() {
        let value = serde_json::json!({
            "type": "wait_until",
            "predicate": {
                "kind": "exists",
                "target": { "kind": "test_id", "id": "ui-gallery-nav-search" }
            }
        });

        let step: UiActionStepV2 = serde_json::from_value(value).unwrap();
        match step {
            UiActionStepV2::WaitUntil {
                window,
                predicate,
                timeout_frames,
                timeout_ms,
            } => {
                assert!(window.is_none());
                assert!(
                    matches!(predicate, UiPredicateV1::Exists { .. }),
                    "expected exists predicate"
                );
                assert_eq!(timeout_frames, default_action_timeout_frames());
                assert!(timeout_ms.is_none());
            }
            _ => panic!("expected wait_until"),
        }
    }

    #[test]
    fn step_wait_semantics_scroll_stable_deserializes_with_defaults() {
        let value = serde_json::json!({
            "type": "wait_semantics_scroll_stable",
            "target": { "kind": "test_id", "id": "ui-gallery-content-viewport" },
            "field": "y_max"
        });

        let step: UiActionStepV2 = serde_json::from_value(value).unwrap();
        match step {
            UiActionStepV2::WaitSemanticsScrollStable {
                window,
                target,
                field,
                stable_frames,
                max_delta,
                timeout_frames,
            } => {
                assert!(window.is_none());
                assert!(matches!(target, UiSelectorV1::TestId { .. }));
                assert_eq!(field, UiSemanticsScrollFieldV1::YMax);
                assert_eq!(stable_frames, default_semantics_scroll_stable_frames());
                assert_eq!(max_delta, default_semantics_scroll_stable_max_delta());
                assert_eq!(timeout_frames, default_action_timeout_frames());
            }
            _ => panic!("expected wait_semantics_scroll_stable"),
        }
    }
}