teksilo-automation 0.9.4

GUI-free runtime-introspection & automation toolkit for Teksilo apps (semantic tree + AT-action driving over serde DTOs).
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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! Toolkit unit tests, all driven through [`execute`]. Every test that
//! snapshots the tree validates the produced `TreeUpdate` with the real
//! `accesskit_consumer`, exactly as teksilo-core's own AT tests do.

use teksilo_canvas::SizeProposal;
use teksilo_core::WidgetTree;
use teksilo_core::accesskit;
use teksilo_core::binding::BindingLevel;
use teksilo_core::build_context::BuildContext;
use teksilo_core::event::{EventResponse, Key, WidgetEvent};
use teksilo_core::gesture::TapEvent;
use teksilo_core::signal::Signal;
use teksilo_core::widget::{LayoutContext, LayoutResponse, Widget, WidgetPlacement};
use teksilo_core::widget_builder::HandlerSet;
use teksilo_core::widget_id::WidgetId;

use crate::dto::*;
use crate::executor::execute;
use crate::recording_ops::RecordingWindowOps;

// ---------------------------------------------------------------------------
// A configurable probe widget — the unit-test fixture. The toolkit depends
// only on teksilo-core, so it can't reach `teksilo-widgets`; this minimal
// widget exercises every path: role/label/value round-trip, reactive
// (AccessibilityOnly) bindings, AT actions (Click / SetValue), live
// regions, typed text, taps, and an optional window-opening action.
// ---------------------------------------------------------------------------

/// Held modifiers as `ctrl+shift`, or `none`. One formatter, so a press and a
/// scroll cannot describe the same modifiers two different ways.
fn mods_tag(modifiers: &teksilo_core::event::Modifiers) -> String {
    let mut out = String::new();
    for (on, tag) in [
        (modifiers.ctrl(), "ctrl"),
        (modifiers.shift(), "shift"),
        (modifiers.alt(), "alt"),
        (modifiers.super_key(), "meta"),
    ] {
        if on {
            if !out.is_empty() {
                out.push('+');
            }
            out.push_str(tag);
        }
    }
    if out.is_empty() {
        out.push_str("none");
    }
    out
}

struct Probe {
    role: accesskit::Role,
    label: Signal<String>,
    value: Option<Signal<String>>,
    live: Option<accesskit::Live>,
    focusable: bool,
    accept_set_value: bool,
    opens_window: bool,
    tristate_mixed: bool,
    /// Attach a `.context_menu(..)` factory that mounts a `Role::Menu` child
    /// labelled "context-menu" — the fixture for right-click / ShowContextMenu.
    has_context_menu: bool,
    /// When true, also advertise + explicitly handle `Action::ShowContextMenu`
    /// (bumping `clicks`) so a test can prove the widget's own handler wins over
    /// the factory fallback.
    handles_show_context_menu: bool,
    clicks: Signal<u64>,
    taps: Signal<u64>,
    typed: Signal<String>,
    /// Each received KeyDown, tagged `named:<Display>` or `char:<c>` so a test
    /// can tell `Key::S` (a named variant) from `Key::Character('s')`.
    received: Signal<Vec<String>>,
    /// Each received `Scroll`, as `<dx>,<dy>,<mods>` — so a test can prove the
    /// modifiers a caller asked for actually reached the widget, and not just
    /// the delta.
    scrolls: Signal<Vec<String>>,
    /// The modifiers on each `PointerDown`, same formatting as `scrolls`, for
    /// the same reason: a Ctrl-click is its own gesture and a probe that cannot
    /// prove the Ctrl arrived is asserting against a plain click.
    presses: Signal<Vec<String>>,
}

impl std::fmt::Debug for Probe {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Probe").field("role", &self.role).finish()
    }
}

/// The window an `opens_window()` probe asks for, whichever route reached it.
fn probe_child_window() -> teksilo_core::window::WindowConfig {
    teksilo_core::window::WindowConfig::new()
        .title("probe child")
        .id("probe-child")
        .size(200, 100)
}

impl Probe {
    fn new(role: accesskit::Role, label: &str) -> Self {
        Self {
            role,
            label: Signal::new(label.to_string()),
            value: None,
            live: None,
            focusable: true,
            accept_set_value: false,
            opens_window: false,
            tristate_mixed: false,
            has_context_menu: false,
            handles_show_context_menu: false,
            clicks: Signal::new(0),
            taps: Signal::new(0),
            typed: Signal::new(String::new()),
            received: Signal::new(Vec::new()),
            scrolls: Signal::new(Vec::new()),
            presses: Signal::new(Vec::new()),
        }
    }
    fn value(mut self, v: Signal<String>) -> Self {
        self.value = Some(v);
        self.accept_set_value = true;
        self
    }
    fn live(mut self, l: accesskit::Live) -> Self {
        self.live = Some(l);
        self
    }
    fn opens_window(mut self) -> Self {
        self.opens_window = true;
        self
    }
    /// Emit `Toggled::Mixed` (tristate / indeterminate).
    fn mixed(mut self) -> Self {
        self.tristate_mixed = true;
        self
    }
    /// Attach a context-menu factory (see [`Probe::has_context_menu`]).
    fn with_context_menu(mut self) -> Self {
        self.has_context_menu = true;
        self
    }
    /// Advertise + explicitly handle `Action::ShowContextMenu` in the widget's
    /// own handler (see [`Probe::handles_show_context_menu`]).
    fn handling_show_context_menu(mut self) -> Self {
        self.handles_show_context_menu = true;
        self
    }
}

impl Widget for Probe {
    fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
        let self_id = ctx.self_id();
        {
            let registry = ctx.binding_registry();
            self.label
                .bind_to(self_id, registry, BindingLevel::AccessibilityOnly);
            if let Some(v) = &self.value {
                v.bind_to(self_id, registry, BindingLevel::AccessibilityOnly);
            }
        }

        let clicks = self.clicks.clone();
        let value_sig = self.value.clone();
        let accept_set = self.accept_set_value;
        let opens_window = self.opens_window;
        // The same "this command opens a window" behaviour, reachable through
        // the two *synthetic input* routes as well as the AT action — that is
        // what proves the executor keeps its real `WindowOps` on every path and
        // not just the AT one (see `executor`'s "Synthetic input" section).
        let opens_on_tap = self.opens_window;
        let opens_on_key = self.opens_window;
        let handles_show = self.handles_show_context_menu;
        let taps = self.taps.clone();
        let typed = self.typed.clone();
        let received = self.received.clone();
        let scrolls = self.scrolls.clone();
        let presses = self.presses.clone();

        let mut handlers = HandlerSet::new();
        if self.focusable {
            handlers = handlers.focusable(true);
        }
        handlers = handlers
            .on_access_action_request(move |action, _node, data, ctx| match action {
                accesskit::Action::Click => {
                    clicks.set(clicks.get() + 1);
                    if opens_window {
                        ctx.open_window(probe_child_window());
                    }
                    EventResponse::Handled
                }
                accesskit::Action::SetValue if accept_set => {
                    if let Some(accesskit::ActionData::Value(s)) = data
                        && let Some(v) = &value_sig
                    {
                        v.set(s.to_string());
                    }
                    EventResponse::Handled
                }
                accesskit::Action::ShowContextMenu if handles_show => {
                    // Prove the widget's own handler wins over the factory
                    // fallback: bump `clicks` and claim the action.
                    clicks.set(clicks.get() + 1);
                    EventResponse::Handled
                }
                _ => EventResponse::Ignored,
            })
            .on_tap(move |_e: &TapEvent, ctx| {
                taps.set(taps.get() + 1);
                if opens_on_tap {
                    ctx.open_window(probe_child_window());
                }
            })
            .on_key(move |event, ctx| {
                if let WidgetEvent::KeyDown { key, .. } = event {
                    if opens_on_key {
                        ctx.open_window(probe_child_window());
                    }
                    let mut log = received.get();
                    log.push(match key {
                        Key::Character(c) => format!("char:{c}"),
                        other => format!("named:{other}"),
                    });
                    received.set(log);
                    if let Key::Character(ch) = key {
                        let mut s = typed.get();
                        s.push(*ch);
                        typed.set(s);
                    }
                    return EventResponse::Handled;
                }
                EventResponse::Ignored
            })
            .on_pointer_event(move |event, _ctx| {
                if let WidgetEvent::PointerDown { modifiers, .. } = event {
                    let mut log = presses.get();
                    log.push(mods_tag(modifiers));
                    presses.set(log);
                }
                EventResponse::Ignored
            })
            .on_scroll(move |event, _ctx| {
                if let WidgetEvent::Scroll { delta, modifiers } = event {
                    let (dx, dy) = match delta {
                        teksilo_core::event::ScrollDelta::Pixels { x, y }
                        | teksilo_core::event::ScrollDelta::Lines { x, y } => (*x, *y),
                    };
                    let mods = mods_tag(modifiers);
                    let mut log = scrolls.get();
                    log.push(format!("{dx},{dy},{mods}"));
                    scrolls.set(log);
                    return EventResponse::Handled;
                }
                EventResponse::Ignored
            });
        if self.has_context_menu {
            handlers = handlers.context_menu(|_pos, _ctx| {
                Some(Box::new(Probe::new(accesskit::Role::Menu, "context-menu")) as Box<dyn Widget>)
            });
        }
        ctx.apply_self_handlers(handlers);
        Vec::new()
    }

    fn layout_response(&self, proposal: SizeProposal, _ctx: &LayoutContext) -> LayoutResponse {
        proposal.resolve(120.0, 30.0).into()
    }

    fn accessibility(&self, builder: &mut teksilo_core::AccessNodeBuilder) {
        builder.set_role(self.role);
        builder.set_name(self.label.get());
        if let Some(v) = &self.value {
            builder.set_value(v.get());
        }
        if let Some(live) = self.live {
            builder.set_live(live);
        }
        if self.tristate_mixed {
            builder.inner_mut().set_toggled(accesskit::Toggled::Mixed);
        }
        builder.add_action(accesskit::Action::Focus);
        builder.add_action(accesskit::Action::Click);
        if self.accept_set_value {
            builder.add_action(accesskit::Action::SetValue);
        }
        if self.handles_show_context_menu {
            builder.add_action(accesskit::Action::ShowContextMenu);
        }
    }
}

/// A minimal presentational container: holds one child, emits NO AT role (so
/// the accessibility walk prunes it), but is a real arena widget with bounds.
/// Used to prove `layout_tree` sees what the AT tree doesn't.
#[derive(Debug)]
struct Container {
    pending: Option<Box<dyn Widget>>,
    child_id: Option<WidgetId>,
}

impl Container {
    fn new(child: impl Widget + 'static) -> Self {
        Self {
            pending: Some(Box::new(child)),
            child_id: None,
        }
    }
}

impl Widget for Container {
    fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
        if let Some(child) = self.pending.take() {
            self.child_id = Some(ctx.add_boxed(child));
        }
        self.child_id.into_iter().collect()
    }
    fn layout_response(&self, proposal: SizeProposal, _ctx: &LayoutContext) -> LayoutResponse {
        proposal.resolve(200.0, 100.0).into()
    }
    fn place_children(
        &self,
        bounds: teksilo_canvas::Rect,
        _proposal: SizeProposal,
        children: &mut [WidgetPlacement],
        _ctx: &LayoutContext,
    ) {
        for child in children.iter_mut() {
            child.origin = bounds.origin();
            child.size = bounds.size();
        }
    }
    fn children(&self) -> Vec<WidgetId> {
        self.child_id.into_iter().collect()
    }
    // No `accessibility` override → bare presentational node, pruned from the AT tree.
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn node_ref(id: WidgetId) -> NodeRef {
    teksilo_core::accessibility::widget_id_to_node_id(id).0
}

/// Validate a fresh `TreeUpdate` with the real AccessKit consumer — the
/// same conformance gate teksilo-core's own AT tests use.
fn assert_valid(tree: &mut WidgetTree) {
    let update = tree.sync_accessibility();
    let _consumer = accesskit_consumer::Tree::new(update, false);
}

fn laid_out(probe: Probe) -> (WidgetTree, WidgetId) {
    let mut tree = WidgetTree::new();
    let id = tree.add(probe);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    (tree, id)
}

fn default_settle() -> SettleSpec {
    SettleSpec::default()
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[test]
fn snapshot_round_trips_role_and_label() {
    let (mut tree, id) = laid_out(Probe::new(accesskit::Role::Button, "Save"));
    assert_valid(&mut tree);
    let mut ops = RecordingWindowOps::new();
    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::SnapshotTree { max_depth: None },
        &default_settle(),
    );
    let AutomationReply::Ok { data } = reply else {
        panic!("expected ok, got {reply:?}");
    };
    let nodes = data["nodes"].as_array().unwrap();
    let probe = nodes
        .iter()
        .find(|n| n["id"].as_u64() == Some(node_ref(id)))
        .expect("probe node present");
    assert_eq!(probe["role"], "Button");
    assert_eq!(probe["label"], "Save");
    assert!(
        probe["actions"]
            .as_array()
            .unwrap()
            .iter()
            .any(|a| a == "click")
    );
}

#[test]
fn read_node_returns_semantic_node() {
    let (mut tree, id) = laid_out(Probe::new(accesskit::Role::Button, "Open"));
    let mut ops = RecordingWindowOps::new();
    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::ReadNode { node: node_ref(id) },
        &default_settle(),
    );
    let AutomationReply::Ok { data } = reply else {
        panic!("{reply:?}");
    };
    let sn: SemanticNode = serde_json::from_value(data).unwrap();
    assert_eq!(sn.role, "Button");
    assert_eq!(sn.label.as_deref(), Some("Open"));
}

#[test]
fn read_missing_node_is_not_found() {
    let (mut tree, _id) = laid_out(Probe::new(accesskit::Role::Button, "X"));
    let mut ops = RecordingWindowOps::new();
    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::ReadNode { node: 999_999 },
        &default_settle(),
    );
    assert!(matches!(reply, AutomationReply::Err { code, .. } if code == codes::NOT_FOUND));
}

#[test]
fn layout_tree_includes_widgets_the_at_tree_prunes() {
    // A presentational Container wrapping a Button: the Container has no AT
    // role (pruned from the AT tree) but is a real arena widget.
    let mut tree = WidgetTree::new();
    let _root = tree.add(Container::new(Probe::new(accesskit::Role::Button, "Inner")));
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let mut ops = RecordingWindowOps::new();

    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::LayoutTree {
            max_depth: None,
            include_debug: false,
        },
        &default_settle(),
    );
    let AutomationReply::Ok { data } = reply else {
        panic!("{reply:?}");
    };
    let nodes: Vec<LayoutNode> = serde_json::from_value(data["nodes"].clone()).unwrap();
    let types: Vec<&str> = nodes.iter().map(|n| n.type_name.as_str()).collect();
    assert!(
        types.iter().any(|t| t.contains("Container")),
        "the presentational Container is in the layout tree: {types:?}"
    );
    assert!(
        types.iter().any(|t| t.contains("Probe")),
        "the Button is too: {types:?}"
    );
    // Every node carries real bounds (the Container is 400x300 — the root fills
    // the proposal — and is active).
    let container = nodes
        .iter()
        .find(|n| n.type_name.contains("Container"))
        .unwrap();
    assert!(container.active);
    assert!(container.bounds.width > 0.0 && container.bounds.height > 0.0);
    assert!(
        !container.children.is_empty(),
        "Container has the Button as a child"
    );

    // Contrast: the Container is absent from the AT snapshot (no role).
    let at = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::SnapshotTree { max_depth: None },
        &default_settle(),
    );
    let AutomationReply::Ok { data: at } = at else {
        panic!();
    };
    let at_roles: Vec<&str> = at["nodes"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|n| n["role"].as_str())
        .collect();
    assert!(at_roles.contains(&"Button"), "Button is in the AT tree");
}

#[test]
fn inspect_node_returns_type_bounds_and_debug() {
    let (mut tree, id) = laid_out(Probe::new(accesskit::Role::Button, "Inspect"));
    let mut ops = RecordingWindowOps::new();
    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::InspectNode { node: node_ref(id) },
        &default_settle(),
    );
    let AutomationReply::Ok { data } = reply else {
        panic!("{reply:?}");
    };
    let ln: LayoutNode = serde_json::from_value(data).unwrap();
    assert_eq!(ln.id, node_ref(id));
    assert!(ln.type_name.contains("Probe"), "type: {}", ln.type_name);
    assert!(ln.active);
    // The Debug repr (the inspector's Properties data) is present.
    assert!(ln.debug.as_deref().unwrap_or("").contains("Probe"));

    // A made-up id resolves to nothing.
    let missing = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::InspectNode { node: 7 },
        &default_settle(),
    );
    assert!(matches!(missing, AutomationReply::Err { code, .. } if code == codes::NOT_FOUND));
}

#[test]
fn find_node_by_role_and_label() {
    let (mut tree, id) = laid_out(Probe::new(accesskit::Role::Button, "Find Me"));
    let mut ops = RecordingWindowOps::new();
    for op in [
        AutomationOp::FindNode {
            role: Some("Button".into()),
            label: None,
        },
        AutomationOp::FindNode {
            role: None,
            label: Some("Find Me".into()),
        },
        AutomationOp::FindNode {
            role: Some("button".into()), // case-insensitive
            label: Some("Find Me".into()),
        },
    ] {
        let reply = execute(&mut tree, &mut ops, &op, &default_settle());
        let AutomationReply::Ok { data } = reply else {
            panic!("{op:?} -> err");
        };
        assert_eq!(data["node"].as_u64(), Some(node_ref(id)), "for {op:?}");
    }
}

#[test]
fn find_node_no_match_is_null() {
    let (mut tree, _id) = laid_out(Probe::new(accesskit::Role::Button, "X"));
    let mut ops = RecordingWindowOps::new();
    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::FindNode {
            role: Some("Slider".into()),
            label: None,
        },
        &default_settle(),
    );
    let AutomationReply::Ok { data } = reply else {
        panic!("{reply:?}");
    };
    assert!(data["node"].is_null());
}

#[test]
fn assert_node_role_pass_and_fail() {
    let (mut tree, id) = laid_out(Probe::new(accesskit::Role::Button, "B"));
    let mut ops = RecordingWindowOps::new();
    let pass = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::AssertNode {
            node: node_ref(id),
            assertion: Assertion::RoleEquals {
                value: "Button".into(),
            },
        },
        &default_settle(),
    );
    let AutomationReply::Ok { data } = pass else {
        panic!();
    };
    let res: AssertionResult = serde_json::from_value(data).unwrap();
    assert!(res.passed);

    let fail = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::AssertNode {
            node: node_ref(id),
            assertion: Assertion::RoleEquals {
                value: "Slider".into(),
            },
        },
        &default_settle(),
    );
    // A false assertion is a failure, not a successful report of one. The
    // detail survives into the message, because "role is 'Button', expected
    // 'Slider'" is the whole value of the failure.
    let AutomationReply::Err { code, message } = fail else {
        panic!("a false assertion must be an Err, got {fail:?}");
    };
    assert_eq!(code, codes::ASSERTION_FAILED);
    assert!(
        message.contains("Button") && message.contains("Slider"),
        "the message must carry actual and expected: {message}"
    );
}

/// The distinction the error code exists for. "The button is not focused" and
/// "there is no such button" are different bugs, and a caller that sees one
/// message for both chases the wrong one.
#[test]
fn a_missing_node_is_not_found_rather_than_a_failed_assertion() {
    let (mut tree, _id) = laid_out(Probe::new(accesskit::Role::Button, "B"));
    let mut ops = RecordingWindowOps::new();
    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::AssertNode {
            node: 12345,
            assertion: Assertion::RoleEquals {
                value: "Button".into(),
            },
        },
        &default_settle(),
    );
    let AutomationReply::Err { code, .. } = reply else {
        panic!("{reply:?}");
    };
    assert_eq!(
        code,
        codes::NOT_FOUND,
        "asserting a property of a node that does not exist is a bad node \
         reference, not a property mismatch"
    );
}

#[test]
fn assert_exists_on_missing_node_fails_gracefully() {
    let (mut tree, _id) = laid_out(Probe::new(accesskit::Role::Button, "B"));
    let mut ops = RecordingWindowOps::new();
    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::AssertNode {
            node: 12345,
            assertion: Assertion::Exists,
        },
        &default_settle(),
    );
    // Asking whether something exists and being told it does not is an answer,
    // so this is a failed assertion rather than a bad node reference.
    let AutomationReply::Err { code, .. } = reply else {
        panic!("{reply:?}");
    };
    assert_eq!(code, codes::ASSERTION_FAILED);
}

#[test]
fn invoke_click_fires_handler() {
    let probe = Probe::new(accesskit::Role::Button, "Click");
    let clicks = probe.clicks.clone();
    let (mut tree, id) = laid_out(probe);
    let mut ops = RecordingWindowOps::new();
    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::InvokeAction {
            node: node_ref(id),
            action: "click".into(),
        },
        &default_settle(),
    );
    assert!(reply.is_ok(), "{reply:?}");
    assert_eq!(clicks.get(), 1);
}

#[test]
fn invoke_unknown_action_is_unknown_name() {
    let (mut tree, id) = laid_out(Probe::new(accesskit::Role::Button, "B"));
    let mut ops = RecordingWindowOps::new();
    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::InvokeAction {
            node: node_ref(id),
            action: "frobnicate".into(),
        },
        &default_settle(),
    );
    assert!(matches!(reply, AutomationReply::Err { code, .. } if code == codes::UNKNOWN_NAME));
}

#[test]
fn invoke_on_missing_node_is_not_found() {
    let (mut tree, _id) = laid_out(Probe::new(accesskit::Role::Button, "B"));
    let mut ops = RecordingWindowOps::new();
    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::InvokeAction {
            node: 424242,
            action: "click".into(),
        },
        &default_settle(),
    );
    assert!(matches!(reply, AutomationReply::Err { code, .. } if code == codes::NOT_FOUND));
}

#[test]
fn set_value_updates_and_resnapshots() {
    let value = Signal::new("before".to_string());
    let probe = Probe::new(accesskit::Role::TextInput, "Field").value(value.clone());
    let (mut tree, id) = laid_out(probe);
    let mut ops = RecordingWindowOps::new();
    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::SetValue {
            node: node_ref(id),
            value: "after".into(),
        },
        &default_settle(),
    );
    assert!(reply.is_ok(), "{reply:?}");
    assert_eq!(value.get(), "after");

    // Re-snapshot reflects the new value.
    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::ReadNode { node: node_ref(id) },
        &default_settle(),
    );
    let AutomationReply::Ok { data } = reply else {
        panic!();
    };
    let sn: SemanticNode = serde_json::from_value(data).unwrap();
    assert_eq!(sn.value.as_deref(), Some("after"));
}

#[test]
fn focus_then_type_text_routes_to_target() {
    let probe = Probe::new(accesskit::Role::TextInput, "Field");
    let typed = probe.typed.clone();
    let (mut tree, id) = laid_out(probe);
    let mut ops = RecordingWindowOps::new();
    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::TypeText {
            node: node_ref(id),
            text: "hi".into(),
        },
        &default_settle(),
    );
    assert!(reply.is_ok(), "{reply:?}");
    assert_eq!(typed.get(), "hi");
}

/// **A misspelled argument is refused, not quietly reinterpreted.**
///
/// serde's default is to ignore a field it does not recognise and take the
/// `#[serde(default)]` for the one that was meant. On `InjectPointer` that
/// default is `Click`, so `{"x":.., "y":.., "kind":"move"}` -- `kind` where
/// `action` was meant -- asked to hover and clicked instead, on every control
/// it pointed at. It toggled real settings in a real config while a probe
/// reported nothing wrong, because from serde's side nothing was.
#[test]
fn an_unknown_argument_is_refused_rather_than_defaulted() {
    let good = serde_json::json!({
        "InjectPointer": { "x": 1.0, "y": 2.0, "action": "move" }
    });
    let parsed: AutomationOp = serde_json::from_value(good).expect("a well-formed op parses");
    assert!(matches!(
        parsed,
        AutomationOp::InjectPointer {
            action: PointerAction::Move,
            ..
        }
    ));

    let typo = serde_json::json!({
        "InjectPointer": { "x": 1.0, "y": 2.0, "kind": "move" }
    });
    let err = serde_json::from_value::<AutomationOp>(typo)
        .expect_err("a field nobody declared must not be silently dropped");
    assert!(
        err.to_string().contains("kind"),
        "and the error must name the offending field, got: {err}"
    );
}

/// A double-click is one op, because two `Click` ops cannot be one: the round
/// trip and the settle between them are longer than the recogniser's window.
#[test]
fn inject_pointer_double_click_is_seen_as_a_double_tap() {
    let probe = Probe::new(accesskit::Role::Button, "Tappable");
    let taps = probe.taps.clone();
    let (mut tree, id) = laid_out(probe);
    let bounds = tree.bounds(id);
    let mut ops = RecordingWindowOps::new();
    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::InjectPointer {
            x: bounds.x + bounds.width * 0.5,
            y: bounds.y + bounds.height * 0.5,
            action: PointerAction::DoubleClick,
            button: PointerButtonDto::Primary,
            ctrl: false,
            shift: false,
            alt: false,
            meta: false,
            command: false,
        },
        &default_settle(),
    );
    assert!(reply.is_ok(), "double click ok: {reply:?}");
    assert_eq!(
        taps.get(),
        2,
        "both presses must reach the widget, back to back"
    );
}

/// Modifiers reach the synthesised press. Ctrl-click to extend a selection is
/// its own gesture, and the corkboard probe spent its life passing an
/// undeclared `modifiers` field that serde dropped on the floor -- asserting
/// against a plain click while believing it held Ctrl.
#[test]
fn inject_pointer_carries_its_modifiers() {
    let probe = Probe::new(accesskit::Role::Button, "Tappable");
    let presses = probe.presses.clone();
    let (mut tree, id) = laid_out(probe);
    let bounds = tree.bounds(id);
    let mut ops = RecordingWindowOps::new();
    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::InjectPointer {
            x: bounds.x + bounds.width * 0.5,
            y: bounds.y + bounds.height * 0.5,
            action: PointerAction::Click,
            button: PointerButtonDto::Primary,
            ctrl: true,
            shift: false,
            alt: false,
            meta: false,
            command: false,
        },
        &default_settle(),
    );
    assert!(reply.is_ok(), "ctrl-click ok: {reply:?}");
    assert_eq!(
        presses.get(),
        vec!["ctrl".to_string()],
        "the press must carry Ctrl"
    );
}

#[test]
fn inject_pointer_click_taps_widget() {
    let probe = Probe::new(accesskit::Role::Button, "Tappable");
    let taps = probe.taps.clone();
    let (mut tree, id) = laid_out(probe);
    let bounds = tree.bounds(id);
    let (cx, cy) = (
        bounds.x + bounds.width * 0.5,
        bounds.y + bounds.height * 0.5,
    );
    let mut ops = RecordingWindowOps::new();
    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::InjectPointer {
            x: cx,
            y: cy,
            action: PointerAction::Click,
            button: PointerButtonDto::Primary,
            ctrl: false,
            shift: false,
            alt: false,
            meta: false,
            command: false,
        },
        &default_settle(),
    );
    assert!(reply.is_ok(), "{reply:?}");
    assert_eq!(taps.get(), 1);
}

#[test]
fn inject_key_letter_maps_to_named_variant() {
    // Regression: a single ASCII letter must become `Key::S` (named), not
    // `Key::Character('s')`, or it would never fire a letter shortcut.
    let probe = Probe::new(accesskit::Role::Button, "B");
    let received = probe.received.clone();
    let (mut tree, id) = laid_out(probe);
    tree.focus(id);
    let mut ops = RecordingWindowOps::new();

    let mk = |key: &str| AutomationOp::InjectKey {
        key: key.into(),
        ctrl: false,
        shift: false,
        alt: false,
        meta: false,
        command: false,
    };
    execute(&mut tree, &mut ops, &mk("s"), &default_settle());
    execute(&mut tree, &mut ops, &mk("/"), &default_settle());

    let log = received.get();
    assert!(
        log.contains(&"named:S".to_string()),
        "letter → Key::S, got {log:?}"
    );
    assert!(
        log.contains(&"char:/".to_string()),
        "non-letter → Character, got {log:?}"
    );
}

#[test]
fn assert_toggled_false_fails_on_mixed() {
    // Regression: `Toggled { value: false }` must FAIL on a tristate/Mixed
    // node, not silently pass by collapsing Mixed into false.
    let (mut tree, id) = laid_out(Probe::new(accesskit::Role::CheckBox, "cb").mixed());
    let mut ops = RecordingWindowOps::new();
    for value in [false, true] {
        let reply = execute(
            &mut tree,
            &mut ops,
            &AutomationOp::AssertNode {
                node: node_ref(id),
                assertion: Assertion::Toggled { value },
            },
            &default_settle(),
        );
        let AutomationReply::Err { code, message } = reply else {
            panic!("Mixed must not satisfy Toggled {{ value: {value} }}: {reply:?}");
        };
        assert_eq!(code, codes::ASSERTION_FAILED);
        assert!(
            message.contains("mixed"),
            "the message must name the tristate state: {message}"
        );
    }
}

/// A modifier-held wheel is a *different gesture* from a plain one, and
/// `WidgetEvent::Scroll` carries modifiers precisely so an app can tell them
/// apart (Ctrl-wheel-to-zoom is the motivating case named in its own doc).
/// The op hardcoded `Modifiers::NONE`, so it was the one input the bridge could
/// describe but not perform: a probe could confirm that a plain wheel scrolls
/// and never that Ctrl+wheel zooms.
#[test]
fn scroll_carries_the_modifiers_it_was_given() {
    let probe = Probe::new(accesskit::Role::GenericContainer, "S");
    let scrolls = probe.scrolls.clone();
    let (mut tree, id) = laid_out(probe);
    let mut ops = RecordingWindowOps::new();
    let node = node_ref(id);

    let mk = |ctrl, shift, alt, meta| AutomationOp::Scroll {
        node,
        dx: 0.0,
        dy: -48.0,
        ctrl,
        shift,
        alt,
        meta,
        command: false,
    };
    execute(
        &mut tree,
        &mut ops,
        &mk(true, false, false, false),
        &default_settle(),
    );
    execute(
        &mut tree,
        &mut ops,
        &mk(false, true, false, false),
        &default_settle(),
    );
    execute(
        &mut tree,
        &mut ops,
        &mk(false, false, true, true),
        &default_settle(),
    );

    let log = scrolls.get();
    assert_eq!(
        log,
        vec![
            "0,-48,ctrl".to_string(),
            "0,-48,shift".to_string(),
            "0,-48,alt+meta".to_string(),
        ],
        "each modifier must reach the widget as asked, got {log:?}"
    );
}

/// `command` is the platform's *primary accelerator*, `ctrl` is literal Control,
/// and the two are only the same key off macOS.
///
/// This is the difference between a cross-platform agent script and one that
/// silently does nothing: a Teksilo shortcut declared `Ctrl+S` resolves to the
/// Command chord on macOS, so a probe sending literal Control there matches no
/// binding — and reports success, because the key really was injected. Asserting
/// against `Modifiers::COMMAND` rather than a hardcoded `ctrl` keeps this test
/// meaningful on all three platforms: it is the same constant the shortcut
/// registry resolves declarations through.
#[test]
fn command_modifier_is_the_platform_accelerator_and_ctrl_stays_literal() {
    let probe = Probe::new(accesskit::Role::GenericContainer, "S");
    let scrolls = probe.scrolls.clone();
    let (mut tree, id) = laid_out(probe);
    let mut ops = RecordingWindowOps::new();
    let node = node_ref(id);

    let mk = |ctrl, command| AutomationOp::Scroll {
        node,
        dx: 0.0,
        dy: -1.0,
        ctrl,
        shift: false,
        alt: false,
        meta: false,
        command,
    };
    execute(&mut tree, &mut ops, &mk(false, true), &default_settle());
    execute(&mut tree, &mut ops, &mk(true, false), &default_settle());

    let log = scrolls.get();
    // What the accelerator spells on *this* host, taken from the same constant
    // the rest of the framework resolves `Ctrl`-declared shortcuts through.
    let accel = if teksilo_core::event::Modifiers::COMMAND
        .contains(teksilo_core::event::Modifiers::SUPER)
    {
        "meta"
    } else {
        "ctrl"
    };
    assert_eq!(
        log,
        vec![format!("0,-1,{accel}"), "0,-1,ctrl".to_string()],
        "command must resolve to the platform accelerator and ctrl stay literal, got {log:?}"
    );
}

/// Omitting `command` leaves every existing probe unchanged — it is
/// `#[serde(default)]`, so an op authored before it existed still deserializes.
#[test]
fn command_defaults_to_off_and_is_optional_on_the_wire() {
    // The externally-tagged wire form, with `command` simply absent.
    let json = r#"{"InjectKey":{"key":"s","ctrl":true}}"#;
    let op: AutomationOp = serde_json::from_str(json).expect("legacy op still parses");
    let AutomationOp::InjectKey { ctrl, command, .. } = op else {
        panic!("expected inject_key");
    };
    assert!(ctrl, "ctrl round-trips");
    assert!(!command, "command defaults to false when absent");
}

/// The default stays a bare wheel, so every existing probe keeps working
/// unchanged — the fields are `#[serde(default)]` for exactly this.
#[test]
fn scroll_without_modifiers_is_still_a_plain_wheel() {
    let probe = Probe::new(accesskit::Role::GenericContainer, "S");
    let scrolls = probe.scrolls.clone();
    let (mut tree, id) = laid_out(probe);
    let mut ops = RecordingWindowOps::new();
    let node = node_ref(id);

    execute(
        &mut tree,
        &mut ops,
        &AutomationOp::Scroll {
            node,
            dx: 0.0,
            dy: 120.0,
            ctrl: false,
            shift: false,
            alt: false,
            meta: false,
            command: false,
        },
        &default_settle(),
    );

    assert_eq!(scrolls.get(), vec!["0,120,none".to_string()]);
}

#[test]
fn inject_key_unknown_is_unknown_name() {
    let (mut tree, _id) = laid_out(Probe::new(accesskit::Role::Button, "B"));
    let mut ops = RecordingWindowOps::new();
    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::InjectKey {
            key: "NopeKey".into(),
            ctrl: false,
            shift: false,
            alt: false,
            meta: false,
            command: false,
        },
        &default_settle(),
    );
    assert!(matches!(reply, AutomationReply::Err { code, .. } if code == codes::UNKNOWN_NAME));
}

#[test]
fn settle_terminates_on_static_tree() {
    let (mut tree, _id) = laid_out(Probe::new(accesskit::Role::Button, "B"));
    let mut ops = RecordingWindowOps::new();
    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::Settle,
        &default_settle(),
    );
    assert!(reply.is_ok(), "settle should not time out on a static tree");
}

#[test]
fn pull_announcements_captures_changes_and_dedups() {
    let label = Signal::new("Ready".to_string());
    let probe = Probe::new(accesskit::Role::Label, "Ready").live(accesskit::Live::Polite);
    // Reuse the probe's own label signal so we can mutate the announced text.
    let probe = Probe {
        label: label.clone(),
        ..probe
    };
    let (mut tree, _id) = laid_out(probe);
    let mut ops = RecordingWindowOps::new();

    // Prime: drain whatever the first sync produced.
    let _ = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::PullAnnouncements { since_seq: 0 },
        &default_settle(),
    );
    let baseline = pull(&mut tree, &mut ops, 0)
        .last()
        .map(|a| a.seq)
        .unwrap_or(0);

    // Change the announced text → one new announcement.
    label.set("Saved".to_string());
    let _ = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::Settle,
        &default_settle(),
    );
    let after_first = pull(&mut tree, &mut ops, baseline);
    assert_eq!(after_first.len(), 1, "one announcement after a change");
    assert_eq!(after_first[0].text, "Saved");
    let seq1 = after_first[0].seq;

    // No change → no new announcement (dedup).
    label.set("Saved".to_string());
    let _ = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::Settle,
        &default_settle(),
    );
    assert!(
        pull(&mut tree, &mut ops, seq1).is_empty(),
        "identical text must not re-announce"
    );

    // New change → another announcement.
    label.set("Closed".to_string());
    let _ = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::Settle,
        &default_settle(),
    );
    let after_second = pull(&mut tree, &mut ops, seq1);
    assert_eq!(after_second.len(), 1);
    assert_eq!(after_second[0].text, "Closed");
    let seq2 = after_second[0].seq;

    // Regression: clearing the live region then re-setting the SAME text must
    // re-announce (the cleared state must not leave a stale dedup entry).
    label.set(String::new());
    let _ = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::Settle,
        &default_settle(),
    );
    assert!(
        pull(&mut tree, &mut ops, seq2).is_empty(),
        "empty text does not announce"
    );
    label.set("Closed".to_string());
    let _ = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::Settle,
        &default_settle(),
    );
    let after_reappear = pull(&mut tree, &mut ops, seq2);
    assert_eq!(
        after_reappear.len(),
        1,
        "same text after a clear re-announces"
    );
    assert_eq!(after_reappear[0].text, "Closed");
}

fn pull(tree: &mut WidgetTree, ops: &mut RecordingWindowOps, since: u64) -> Vec<AnnouncementDto> {
    let reply = execute(
        tree,
        ops,
        &AutomationOp::PullAnnouncements { since_seq: since },
        &default_settle(),
    );
    let AutomationReply::Ok { data } = reply else {
        panic!("{reply:?}");
    };
    serde_json::from_value(data).unwrap()
}

#[test]
fn wait_for_condition_succeeds_and_times_out() {
    let (mut tree, id) = laid_out(Probe::new(accesskit::Role::Button, "Wait"));
    let mut ops = RecordingWindowOps::new();

    // Already-true condition resolves immediately.
    let ok = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::WaitForCondition {
            condition: WaitCondition::NodeExists {
                role: Some("Button".into()),
                label: None,
            },
        },
        &SettleSpec {
            settle_timeout_ms: 200,
            ..Default::default()
        },
    );
    assert!(ok.is_ok(), "{ok:?}");

    // Impossible condition times out.
    let timeout = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::WaitForCondition {
            condition: WaitCondition::NodeValue {
                node: node_ref(id),
                expected: "never".into(),
            },
        },
        &SettleSpec {
            settle_timeout_ms: 80,
            ..Default::default()
        },
    );
    assert!(matches!(timeout, AutomationReply::Err { code, .. } if code == codes::WAIT_TIMEOUT));
}

#[test]
fn recording_window_ops_captures_open_without_panic() {
    let probe = Probe::new(accesskit::Role::Button, "New Window").opens_window();
    let (mut tree, id) = laid_out(probe);
    let mut ops = RecordingWindowOps::new();
    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::InvokeAction {
            node: node_ref(id),
            action: "click".into(),
        },
        &default_settle(),
    );
    assert!(reply.is_ok(), "{reply:?}");
    assert_eq!(
        ops.opened.len(),
        1,
        "open_window must be recorded, not panic"
    );
    assert_eq!(ops.opened[0].title, "probe child");
    assert_eq!(ops.opened[0].string_id.as_deref(), Some("probe-child"));
}

// ---------------------------------------------------------------------------
// Synthetic input must carry the caller's `WindowOps`
// ---------------------------------------------------------------------------
//
// The regression: `InjectPointer`/`InjectKey`/`TypeText`/`DragNode` went through
// `WidgetTree`'s test API, which dispatches with a `NoopWindowOps` — whose
// `open_window` *panics*. Against a live app the executor is handed the real
// ops and threw them away, so an injected click or keystroke on any command
// that opens a window killed the whole application. The AT-action path above
// never had the bug; these two are its synthetic-input counterparts.
//
// `RecordingWindowOps` is what makes the failure legible here: with the bug, the
// panic came from `NoopWindowOps` deep inside the tree; without it, the request
// lands in `ops.opened` where it can be asserted.

#[test]
fn an_injected_click_reaches_the_callers_window_ops() {
    let probe = Probe::new(accesskit::Role::Button, "New Window").opens_window();
    let (mut tree, id) = laid_out(probe);
    let bounds = tree.bounds(id);
    let mut ops = RecordingWindowOps::new();

    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::InjectPointer {
            x: bounds.center().x,
            y: bounds.center().y,
            action: PointerAction::Click,
            button: Default::default(),
            ctrl: false,
            shift: false,
            alt: false,
            meta: false,
            command: false,
        },
        &default_settle(),
    );

    assert!(reply.is_ok(), "{reply:?}");
    assert_eq!(
        ops.opened.len(),
        1,
        "a synthetic click must reach the caller's WindowOps, not a NoopWindowOps"
    );
    assert_eq!(ops.opened[0].string_id.as_deref(), Some("probe-child"));
}

#[test]
fn an_injected_key_reaches_the_callers_window_ops() {
    // `Probe` is focusable by default, which key routing needs.
    let probe = Probe::new(accesskit::Role::Button, "New Window").opens_window();
    let (mut tree, id) = laid_out(probe);
    let mut ops = RecordingWindowOps::new();
    // Key events route by focus, so focus the probe first — through the
    // executor, so this exercises the real op sequence a probe script uses.
    let focused = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::FocusNode { node: node_ref(id) },
        &default_settle(),
    );
    assert!(focused.is_ok(), "{focused:?}");

    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::InjectKey {
            key: "n".into(),
            ctrl: true,
            shift: true,
            alt: false,
            meta: false,
            command: false,
        },
        &default_settle(),
    );

    assert!(reply.is_ok(), "{reply:?}");
    assert_eq!(
        ops.opened.len(),
        1,
        "an injected keystroke must reach the caller's WindowOps, not a NoopWindowOps"
    );
    assert_eq!(ops.opened[0].string_id.as_deref(), Some("probe-child"));
}

#[test]
fn list_live_regions_finds_polite_node() {
    let probe = Probe::new(accesskit::Role::Label, "Status").live(accesskit::Live::Polite);
    let (mut tree, id) = laid_out(probe);
    let mut ops = RecordingWindowOps::new();
    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::ListLiveRegions,
        &default_settle(),
    );
    let AutomationReply::Ok { data } = reply else {
        panic!("{reply:?}");
    };
    let regions: Vec<SemanticNode> = serde_json::from_value(data).unwrap();
    assert!(regions.iter().any(|n| n.id == node_ref(id)));
    assert_eq!(regions[0].live.as_deref(), Some("polite"));
}

#[test]
fn get_overlays_empty_on_plain_tree() {
    let (mut tree, _id) = laid_out(Probe::new(accesskit::Role::Button, "B"));
    let mut ops = RecordingWindowOps::new();
    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::GetOverlays,
        &default_settle(),
    );
    let AutomationReply::Ok { data } = reply else {
        panic!("{reply:?}");
    };
    assert_eq!(data["count"].as_u64(), Some(0));
}

#[test]
fn list_windows_and_screenshot_defer_to_host() {
    let (mut tree, _id) = laid_out(Probe::new(accesskit::Role::Button, "B"));
    let mut ops = RecordingWindowOps::new();
    for op in [
        AutomationOp::ListWindows,
        AutomationOp::Screenshot { node: None },
    ] {
        let reply = execute(&mut tree, &mut ops, &op, &default_settle());
        assert!(
            matches!(reply, AutomationReply::Err { ref code, .. } if code == codes::HOST_REQUIRED),
            "{op:?} -> {reply:?}"
        );
    }
}

#[test]
fn dto_round_trips_through_json() {
    // The socket protocol depends on every op + reply round-tripping.
    let req = AutomationRequest {
        window_id: Some(7),
        op: AutomationOp::SetValue {
            node: 42,
            value: "x".into(),
        },
        settle: SettleSpec::default(),
    };
    let json = serde_json::to_string(&req).unwrap();
    let back: AutomationRequest = serde_json::from_str(&json).unwrap();
    assert_eq!(back.window_id, Some(7));
    assert_eq!(back.op, req.op);

    let reply = AutomationReply::ok(serde_json::json!({"k": 1}));
    let s = serde_json::to_string(&reply).unwrap();
    let back: AutomationReply = serde_json::from_str(&s).unwrap();
    assert_eq!(back, reply);
}

// ---------------------------------------------------------------------------
// Right-click / context menus
// ---------------------------------------------------------------------------

/// Run `GetOverlays` and return the active-overlay count.
fn overlay_count(tree: &mut WidgetTree, ops: &mut RecordingWindowOps) -> u64 {
    let reply = execute(tree, ops, &AutomationOp::GetOverlays, &default_settle());
    let AutomationReply::Ok { data } = reply else {
        panic!("get_overlays: {reply:?}");
    };
    data["count"].as_u64().expect("count field")
}

#[test]
fn right_click_opens_the_context_menu_factory() {
    let (mut tree, id) = laid_out(Probe::new(accesskit::Role::Button, "Row").with_context_menu());
    let mut ops = RecordingWindowOps::new();

    assert_eq!(overlay_count(&mut tree, &mut ops), 0, "no overlay before");

    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::RightClick { node: node_ref(id) },
        &default_settle(),
    );
    assert!(reply.is_ok(), "right_click ok: {reply:?}");

    assert_eq!(
        overlay_count(&mut tree, &mut ops),
        1,
        "context menu overlay opened by right_click"
    );
    assert_valid(&mut tree);

    // The mounted menu is visible in the AT snapshot.
    let found = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::FindNode {
            role: Some("Menu".into()),
            label: None,
        },
        &default_settle(),
    );
    let AutomationReply::Ok { data } = found else {
        panic!("{found:?}");
    };
    assert!(data["node"].as_u64().is_some(), "menu node found: {data}");
}

#[test]
fn right_click_on_missing_node_is_not_found() {
    let (mut tree, _id) = laid_out(Probe::new(accesskit::Role::Button, "Row").with_context_menu());
    let mut ops = RecordingWindowOps::new();
    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::RightClick { node: 999_999 },
        &default_settle(),
    );
    assert!(
        matches!(reply, AutomationReply::Err { ref code, .. } if code == codes::NOT_FOUND),
        "expected NOT_FOUND, got {reply:?}"
    );
}

#[test]
fn show_context_menu_action_opens_the_factory_menu() {
    // The framework a11y route: `invoke_action(node, "show_context_menu")` on a
    // widget that wires its menu via `.context_menu(..)` (and does NOT handle the
    // AT action itself) now opens the menu — it used to be a silent no-op.
    let (mut tree, id) = laid_out(Probe::new(accesskit::Role::Button, "Row").with_context_menu());
    let mut ops = RecordingWindowOps::new();

    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::InvokeAction {
            node: node_ref(id),
            action: "show_context_menu".into(),
        },
        &default_settle(),
    );
    assert!(reply.is_ok(), "invoke show_context_menu ok: {reply:?}");
    assert_eq!(
        overlay_count(&mut tree, &mut ops),
        1,
        "show_context_menu AT action opened the factory menu"
    );
}

#[test]
fn show_context_menu_prefers_the_widgets_own_handler() {
    // A widget that explicitly handles `Action::ShowContextMenu` wins over the
    // factory fallback: its handler fires and NO factory overlay is mounted.
    let probe = Probe::new(accesskit::Role::Button, "Row")
        .with_context_menu()
        .handling_show_context_menu();
    let clicks = probe.clicks.clone();
    let mut tree = WidgetTree::new();
    let id = tree.add(probe);
    tree.layout(SizeProposal::exact(400.0, 300.0));
    let mut ops = RecordingWindowOps::new();

    let reply = execute(
        &mut tree,
        &mut ops,
        &AutomationOp::InvokeAction {
            node: node_ref(id),
            action: "show_context_menu".into(),
        },
        &default_settle(),
    );
    assert!(reply.is_ok(), "{reply:?}");
    assert_eq!(clicks.get(), 1, "the widget's own handler fired");
    assert_eq!(
        overlay_count(&mut tree, &mut ops),
        0,
        "handler consumed the action — factory fallback skipped"
    );
}

#[test]
fn tool_catalog_has_27_entries() {
    assert_eq!(crate::mcp_schema::TOOL_COUNT, 27);
    // Names are unique.
    let mut names: Vec<&str> = crate::mcp_schema::TOOL_CATALOG
        .iter()
        .map(|t| t.name)
        .collect();
    names.sort_unstable();
    let unique = {
        let mut n = names.clone();
        n.dedup();
        n.len()
    };
    assert_eq!(unique, names.len(), "tool names must be unique");
}