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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! The single core function that performs every automation operation
//! against a live [`WidgetTree`].
//!
//! ```text
//! execute(tree: &mut WidgetTree, ops: &mut dyn WindowOps,
//!         op: &AutomationOp, settle: &SettleSpec) -> AutomationReply
//! ```
//!
//! `WidgetTree` is `Rc/RefCell`-based and therefore `!Send`, so it lives on
//! exactly one thread; the async / socket layers marshal `Send` DTOs to it
//! and call this. Two ops can't be served here — `ListWindows` (needs the
//! window manager) and `Screenshot` (needs a GPU / platform window). Both
//! return [`codes::HOST_REQUIRED`]; the headless tree-thread and the live
//! bridge intercept them with the extra context they alone hold.

use std::time::{Duration, Instant};

use teksilo_canvas::{Point, Rect};
use teksilo_core::WidgetTree;
use teksilo_core::accesskit;
use teksilo_core::event::{Key, Modifiers, ScrollDelta, WidgetEvent};
use teksilo_core::widget_id::WidgetId;
use teksilo_core::window::WindowOps;

use crate::dto::{
    AnnouncementDto, Assertion, AssertionResult, AutomationOp, AutomationReply, NodeBounds,
    NodeRef, SemanticNode, SettleSpec, ShortcutInfo, WaitCondition, codes,
};

/// Perform one automation operation. See the module docs.
pub fn execute(
    tree: &mut WidgetTree,
    ops: &mut dyn WindowOps,
    op: &AutomationOp,
    settle: &SettleSpec,
) -> AutomationReply {
    match op {
        // ---- Query ----
        AutomationOp::SnapshotTree { max_depth } => {
            let update = tree.sync_accessibility();
            AutomationReply::ok(snapshot_json(&update, *max_depth))
        }
        AutomationOp::ReadNode { node } => {
            let update = tree.sync_accessibility();
            match find_node(&update, *node) {
                Some(sn) => AutomationReply::ok_json(&sn),
                None => AutomationReply::err(codes::NOT_FOUND, format!("no node {node}")),
            }
        }
        AutomationOp::LayoutTree {
            max_depth,
            include_debug,
        } => AutomationReply::ok(layout_tree_json(tree, *max_depth, *include_debug)),
        AutomationOp::InspectNode { node } => {
            let nid = accesskit::NodeId(*node);
            if teksilo_core::accessibility::is_synthetic(nid) {
                return AutomationReply::err(
                    codes::NOT_FOUND,
                    "synthetic node has no backing widget — use read_node for its AT detail",
                );
            }
            let widget = teksilo_core::accessibility::node_id_to_widget_id_maybe(nid)
                .filter(|w| tree.widget_type_name(*w).is_some());
            match widget {
                Some(w) => AutomationReply::ok_json(&layout_node(tree, w, true)),
                None => {
                    AutomationReply::err(codes::NOT_FOUND, format!("no widget for node {node}"))
                }
            }
        }
        AutomationOp::FindNode { role, label } => {
            let update = tree.sync_accessibility();
            let found = find_node_ref(&update, role.as_deref(), label.as_deref());
            AutomationReply::ok(serde_json::json!({ "node": found }))
        }
        AutomationOp::AssertNode { node, assertion } => {
            let update = tree.sync_accessibility();
            // A false assertion is a *failure*, not a successful report of one.
            //
            // It used to come back as `Ok(AssertionResult { passed: false })`,
            // which every transport and every caller had to remember to unwrap
            // and check — and a caller that forgot got a green result for a
            // failed assertion, which is the worst possible default for a
            // testing tool. The MCP server carried a bolt-on that re-read its
            // own JSON payload to set `is_error`; the socket bridge and every
            // direct `execute` caller had nothing.
            //
            // Deciding it here means every transport inherits it: rmcp already
            // maps `AutomationReply::Err` to `CallToolResult::error`, so
            // `isError` falls out with no special case.
            match evaluate_assertion(&update, *node, assertion) {
                Ok(result) => AutomationReply::ok_json(&result),
                Err(reply) => reply,
            }
        }
        AutomationOp::ListWindows => AutomationReply::err(
            codes::HOST_REQUIRED,
            "list_windows is served by the host (window manager / headless shim)",
        ),

        // ---- AT-action driving ----
        AutomationOp::InvokeAction { node, action } => {
            let Some(act) = action_from_str(action) else {
                return AutomationReply::err(
                    codes::UNKNOWN_NAME,
                    format!("unknown action '{action}'"),
                );
            };
            dispatch_action_and_settle(tree, ops, settle, *node, act, None)
        }
        AutomationOp::FocusNode { node } => {
            dispatch_action_and_settle(tree, ops, settle, *node, accesskit::Action::Focus, None)
        }
        AutomationOp::SetValue { node, value } => dispatch_action_and_settle(
            tree,
            ops,
            settle,
            *node,
            accesskit::Action::SetValue,
            Some(accesskit::ActionData::Value(value.clone().into_boxed_str())),
        ),
        AutomationOp::Expand { node } => {
            dispatch_action_and_settle(tree, ops, settle, *node, accesskit::Action::Expand, None)
        }
        AutomationOp::Collapse { node } => {
            dispatch_action_and_settle(tree, ops, settle, *node, accesskit::Action::Collapse, None)
        }
        AutomationOp::Scroll {
            node,
            dx,
            dy,
            ctrl,
            shift,
            alt,
            meta,
            command,
        } => {
            let update = tree.sync_accessibility();
            let Some(widget) = resolve_widget(tree, &update, *node) else {
                return AutomationReply::err(codes::NOT_FOUND, format!("no node {node}"));
            };
            let c = center(tree.bounds(widget));
            // Route the wheel: hover the target first (scroll dispatches to
            // the hovered/focused widget), then deliver the delta.
            pointer_move(tree, ops, c);
            tree.dispatch_event_with_ops(
                WidgetEvent::Scroll {
                    delta: ScrollDelta::Pixels { x: *dx, y: *dy },
                    // Carried, not hardcoded to `NONE`: a modifier-held wheel is
                    // a distinct gesture (Ctrl-wheel-to-zoom is why
                    // `WidgetEvent::Scroll` has this field at all), and a probe
                    // that could only send a bare wheel could not reach it.
                    modifiers: modifiers(*ctrl, *shift, *alt, *meta, *command),
                },
                ops,
            );
            finish_settle(tree, ops, settle)
        }

        // ---- Synthetic input ----
        AutomationOp::InjectPointer {
            x,
            y,
            action,
            button,
            ctrl,
            shift,
            alt,
            meta,
            command,
        } => {
            use crate::dto::PointerAction as PA;
            let p = Point::new(*x, *y);
            let btn = button.to_core();
            let m = modifiers(*ctrl, *shift, *alt, *meta, *command);
            match action {
                PA::Move => pointer_move(tree, ops, p),
                PA::Down => pointer_down(tree, ops, p, btn, m),
                PA::Up => pointer_up(tree, ops, p, btn, m),
                PA::Click => {
                    pointer_down(tree, ops, p, btn, m);
                    pointer_up(tree, ops, p, btn, m);
                }
                PA::DoubleClick => {
                    // Both pairs in one op, with no settle between them: a
                    // client sending two `Click` ops cannot make a double-click,
                    // because the round trip between them is longer than the
                    // recogniser's window.
                    pointer_down(tree, ops, p, btn, m);
                    pointer_up(tree, ops, p, btn, m);
                    pointer_down(tree, ops, p, btn, m);
                    pointer_up(tree, ops, p, btn, m);
                }
            }
            finish_settle(tree, ops, settle)
        }
        AutomationOp::RightClick { node } => {
            // Resolve the node's pointer point (prefers its own AT bounds, so a
            // synthetic child — scene item, rich-text run — is right-clicked at
            // its own centre, not its owning widget's), then drive a real
            // Secondary press+release. That runs the same `PointerDown`
            // → `show_context_menu_for` path a user's right-click does, so the
            // widget's `.context_menu(..)` factory opens.
            let update = tree.sync_accessibility();
            let Some(p) = node_point(tree, &update, *node) else {
                return AutomationReply::err(codes::NOT_FOUND, format!("no node {node}"));
            };
            pointer_down(
                tree,
                ops,
                p,
                teksilo_core::PointerButton::Secondary,
                Modifiers::NONE,
            );
            pointer_up(
                tree,
                ops,
                p,
                teksilo_core::PointerButton::Secondary,
                Modifiers::NONE,
            );
            finish_settle(tree, ops, settle)
        }
        AutomationOp::InjectKey {
            key,
            ctrl,
            shift,
            alt,
            meta,
            command,
        } => {
            let Some(k) = key_from_str(key) else {
                return AutomationReply::err(codes::UNKNOWN_NAME, format!("unknown key '{key}'"));
            };
            press_key(
                tree,
                ops,
                k,
                modifiers(*ctrl, *shift, *alt, *meta, *command),
            );
            finish_settle(tree, ops, settle)
        }
        AutomationOp::TypeText { node, text } => {
            let update = tree.sync_accessibility();
            let Some(widget) = resolve_widget(tree, &update, *node) else {
                return AutomationReply::err(codes::NOT_FOUND, format!("no node {node}"));
            };
            // `type_text` routes to the *focused* widget, so focus first.
            tree.focus_ops(widget, ops);
            type_text(tree, ops, text);
            finish_settle(tree, ops, settle)
        }
        AutomationOp::TypeIme {
            node,
            preedit,
            commit,
        } => {
            let update = tree.sync_accessibility();
            let Some(widget) = resolve_widget(tree, &update, *node) else {
                return AutomationReply::err(codes::NOT_FOUND, format!("no node {node}"));
            };
            tree.focus_ops(widget, ops);
            if let Some(text) = preedit {
                tree.dispatch_event_with_ops(
                    WidgetEvent::ImeComposition {
                        text: text.clone(),
                        cursor: None,
                    },
                    ops,
                );
            }
            if let Some(text) = commit {
                tree.dispatch_event_with_ops(WidgetEvent::ImeCommit { text: text.clone() }, ops);
            }
            finish_settle(tree, ops, settle)
        }
        AutomationOp::DragNode {
            node,
            to_node,
            to_x,
            to_y,
        } => {
            let update = tree.sync_accessibility();
            let Some(from) = node_point(tree, &update, *node) else {
                return AutomationReply::err(codes::NOT_FOUND, format!("no node {node}"));
            };
            let to = if let Some(tn) = to_node {
                match node_point(tree, &update, *tn) {
                    Some(p) => p,
                    None => {
                        return AutomationReply::err(codes::NOT_FOUND, format!("no node {tn}"));
                    }
                }
            } else if let (Some(x), Some(y)) = (to_x, to_y) {
                Point::new(*x, *y)
            } else {
                return AutomationReply::err(
                    codes::BAD_ARGUMENT,
                    "drag_node needs to_node or (to_x, to_y)",
                );
            };
            drag(tree, ops, from, to);
            finish_settle(tree, ops, settle)
        }

        // ---- Introspection ----
        AutomationOp::GetOverlays => {
            let overlays = tree.active_overlays();
            let ids: Vec<String> = overlays.iter().map(|o| format!("{o:?}")).collect();
            AutomationReply::ok(serde_json::json!({ "count": overlays.len(), "ids": ids }))
        }
        AutomationOp::GetShortcuts => {
            let list: Vec<ShortcutInfo> = tree
                .shortcut_registry()
                .iter_effective()
                .map(|eff| ShortcutInfo {
                    id: eff.shortcut.id.to_string(),
                    name: Some(eff.shortcut.name.get()).filter(|n| !n.is_empty()),
                    primary: eff.primary.map(format_keystroke),
                    secondary: eff.secondary.map(format_keystroke),
                    enabled: eff.enabled,
                })
                .collect();
            AutomationReply::ok_json(&list)
        }
        AutomationOp::ListLiveRegions => {
            let update = tree.sync_accessibility();
            let focus = update.focus;
            let regions: Vec<SemanticNode> = update
                .nodes
                .iter()
                .filter(|(_, n)| {
                    matches!(
                        n.live(),
                        Some(accesskit::Live::Polite) | Some(accesskit::Live::Assertive)
                    )
                })
                .map(|(id, n)| semantic_node(*id, n, focus))
                .collect();
            AutomationReply::ok_json(&regions)
        }
        AutomationOp::PullAnnouncements { since_seq } => {
            // Re-sync so the latest rebuild's announcements are captured.
            tree.sync_accessibility();
            let list: Vec<AnnouncementDto> = tree
                .announcements_since(*since_seq)
                .into_iter()
                .map(AnnouncementDto::from)
                .collect();
            AutomationReply::ok_json(&list)
        }

        // ---- Time / settle ----
        AutomationOp::AdvanceClock { millis } => {
            tree.advance_time(Duration::from_millis(*millis));
            tree.sync_accessibility();
            AutomationReply::ok_unit()
        }
        AutomationOp::Settle => finish_settle(tree, ops, settle),
        AutomationOp::WaitForCondition { condition } => {
            wait_for_condition(tree, ops, settle, condition)
        }

        // ---- Visual (host-handled) ----
        AutomationOp::Screenshot { .. } => AutomationReply::err(
            codes::HOST_REQUIRED,
            "screenshot pixels are produced by the host (offscreen renderer / platform window)",
        ),
    }
}

// ---------------------------------------------------------------------------
// Synthetic input
// ---------------------------------------------------------------------------
//
// `WidgetTree`'s `test_api` has a ready-made method for each of these
// (`pointer_move`, `press_key`, `drag`, …) and this module used to call them.
// It must not: every one of them goes through
// [`WidgetTree::dispatch_event`](teksilo_core::WidgetTree::dispatch_event), the
// *standalone-tree* variant, which substitutes a `NoopWindowOps` — and
// `NoopWindowOps::open_window` **panics**, by design, because a standalone tree
// has no winit back-end to create a window in.
//
// Against a live app that is the wrong sink and it is not a degraded one: the
// executor is handed the real `WindowOpsImpl` (`teksilo-app`'s `run_in_window`)
// and then threw it away, so an injected click or keystroke on any command that
// opens, enumerates or focuses a window took the whole application down —
// mid-probe, with a panic naming a "standalone WidgetTree" that the automated
// session plainly was not. Found driving a real "New Window" menu command.
//
// The AT-action ops (`invoke_action` and friends) never had the problem: they
// go through `dispatch_action_and_settle`, which passes `ops` down. So did
// `scroll`. These helpers make the synthetic-input ops behave the same way —
// same events, same order, real ops.

fn pointer_move(tree: &mut WidgetTree, ops: &mut dyn WindowOps, position: Point) {
    tree.dispatch_event_with_ops(WidgetEvent::PointerMove { position }, ops);
}

fn pointer_down(
    tree: &mut WidgetTree,
    ops: &mut dyn WindowOps,
    position: Point,
    button: teksilo_core::PointerButton,
    modifiers: Modifiers,
) {
    tree.dispatch_event_with_ops(
        WidgetEvent::PointerDown {
            position,
            button,
            modifiers,
        },
        ops,
    );
}

fn pointer_up(
    tree: &mut WidgetTree,
    ops: &mut dyn WindowOps,
    position: Point,
    button: teksilo_core::PointerButton,
    modifiers: Modifiers,
) {
    tree.dispatch_event_with_ops(
        WidgetEvent::PointerUp {
            position,
            button,
            modifiers,
        },
        ops,
    );
}

/// Press and release one key, carrying the text the platform attaches to it
/// ([`Key::to_text`]) so a driven run matches a hand-driven one.
///
/// It sent `text: None` for every key, which made `inject_key` a *weaker*
/// probe than a real keypress rather than an equivalent one — an Escape that
/// a focused field swallowed came back through this path looking fine.
fn press_key(tree: &mut WidgetTree, ops: &mut dyn WindowOps, key: Key, modifiers: Modifiers) {
    tree.dispatch_event_with_ops(
        WidgetEvent::KeyDown {
            key,
            modifiers,
            text: key.to_text().map(str::to_string),
        },
        ops,
    );
    tree.dispatch_event_with_ops(WidgetEvent::KeyUp { key, modifiers }, ops);
}

/// Type `text` into the focused widget, one `KeyDown` per character — the
/// caller focuses the target first (`focus_ops`). Mirrors `test_api::type_text`,
/// whose `widget` parameter is likewise unused: focus is what routes a key
/// event, not the node the caller named.
fn type_text(tree: &mut WidgetTree, ops: &mut dyn WindowOps, text: &str) {
    for ch in text.chars() {
        tree.dispatch_event_with_ops(
            WidgetEvent::KeyDown {
                key: Key::Character(ch),
                modifiers: Modifiers::NONE,
                text: Some(ch.to_string()),
            },
            ops,
        );
    }
}

fn drag(tree: &mut WidgetTree, ops: &mut dyn WindowOps, from: Point, to: Point) {
    pointer_down(
        tree,
        ops,
        from,
        teksilo_core::PointerButton::Primary,
        Modifiers::NONE,
    );
    pointer_move(tree, ops, to);
    pointer_up(
        tree,
        ops,
        to,
        teksilo_core::PointerButton::Primary,
        Modifiers::NONE,
    );
}

// ---------------------------------------------------------------------------
// Settle
// ---------------------------------------------------------------------------

/// Run the settle described by `settle` and then re-sync the AT tree.
/// Returns `Some(code)` if the wall-clock budget was exceeded (the loop is
/// sim-clock-driven, so it can only overrun on a pathological animation),
/// else `None`.
pub fn run_settle(
    tree: &mut WidgetTree,
    ops: &mut dyn WindowOps,
    settle: &SettleSpec,
) -> Option<&'static str> {
    let deadline = Instant::now() + Duration::from_millis(settle.settle_timeout_ms.max(1));
    if settle.clock_millis > 0 {
        tree.advance_time(Duration::from_millis(settle.clock_millis));
    }
    let mut frames = 0u32;
    let mut timed_out = false;
    while tree.has_active_animations() && frames < settle.max_anim_frames {
        tree.tick_animations(Duration::from_millis(16));
        frames += 1;
        if Instant::now() >= deadline {
            timed_out = true;
            break;
        }
    }
    if settle.layout_after {
        let proposal = tree.last_proposal();
        tree.layout_with_ops(proposal, ops);
    }
    tree.sync_accessibility();
    timed_out.then_some(codes::SETTLE_TIMEOUT)
}

fn finish_settle(
    tree: &mut WidgetTree,
    ops: &mut dyn WindowOps,
    settle: &SettleSpec,
) -> AutomationReply {
    match run_settle(tree, ops, settle) {
        Some(code) => AutomationReply::err(code, "settle exceeded its time budget"),
        None => AutomationReply::ok_unit(),
    }
}

fn dispatch_action_and_settle(
    tree: &mut WidgetTree,
    ops: &mut dyn WindowOps,
    settle: &SettleSpec,
    node: NodeRef,
    action: accesskit::Action,
    data: Option<accesskit::ActionData>,
) -> AutomationReply {
    // Sync first so the synthetic-parent map is fresh AND so we can confirm
    // the node is actually live: `node_id_to_widget_id_maybe` happily decodes
    // any non-synthetic u64 into a `WidgetId`, so presence in the AT tree —
    // not a non-`None` resolution — is the real liveness check.
    let update = tree.sync_accessibility();
    if !node_present(&update, node) {
        return AutomationReply::err(codes::NOT_FOUND, format!("no node {node}"));
    }
    let handled = tree.dispatch_access_action(accesskit::NodeId(node), action, data, ops);
    // Settle regardless: an action that WAS handled must have its effects
    // flushed before we reply, and one that wasn't costs a frame at most.
    let reply = finish_settle(tree, ops, settle);
    if handled || !reply.is_ok() {
        return reply;
    }
    // The node is real but nothing acted on the action. Reporting success here
    // is what made an unsupported action indistinguishable from a working one,
    // so name the actions the node does advertise — that is almost always
    // enough for the caller to fix the call.
    let advertised = find_node(&update, node)
        .map(|sn| sn.actions.join(", "))
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| "none".to_string());
    AutomationReply::err(
        codes::UNHANDLED_ACTION,
        format!(
            "node {node} did not handle '{}'; it advertises: {advertised}",
            action_name(action).unwrap_or("?")
        ),
    )
}

/// One simulated frame at ~60 Hz — how far the wait advances the tree per poll.
const WAIT_FRAME: Duration = Duration::from_millis(16);

/// Poll `condition`, advancing the simulated clock a frame at a time.
///
/// `settle.settle_timeout_ms` is spent as **simulated** time, in whole frames,
/// so the same wait resolves identically on every platform. Bounding it by wall
/// clock — what this used to do — made the outcome depend on the host's timer
/// granularity: each poll slept 1 ms, but a 1 ms sleep costs up to 15.6 ms on
/// Windows, so the same wall budget bought roughly a fifteenth of the frames
/// and a fifteenth of the simulated time. A wait that passed on Linux timed out
/// on Windows, with nothing in the reply to say why.
///
/// Nothing else can move the tree while this runs — the tree is `!Send` and this
/// loop owns the only thread that touches it — so simulated frames are the only
/// thing that can make the predicate true, and sleeping bought no progress at
/// all. Dropping the sleep also removes the reason it was there: the loop is now
/// bounded by a frame count rather than by the timeout, so it finishes in
/// microseconds instead of occupying the thread for the whole budget.
fn wait_for_condition(
    tree: &mut WidgetTree,
    ops: &mut dyn WindowOps,
    settle: &SettleSpec,
    condition: &WaitCondition,
) -> AutomationReply {
    let budget_ms = settle.settle_timeout_ms.max(1);
    let frame_ms = WAIT_FRAME.as_millis() as u64;
    let max_frames = budget_ms.div_ceil(frame_ms);
    // Wall-clock backstop: it exists only so a pathological tree (an unbounded
    // rebuild each frame) cannot spin forever, and must never be what ends an
    // ordinary wait. `budget_ms` is already enormously generous for that job —
    // the frames are pure in-memory work and finish in microseconds — while a
    // larger multiple would break the guarantee the *caller* of this budget is
    // relying on: the live bridge clamps `settle_timeout_ms` to 2 s precisely
    // so no op can freeze the winit main thread for longer (see
    // `clamp_live_settle`), and a 10× backstop quietly turned that into 20 s —
    // past even the bridge's own 15 s reply deadline, so the client would be
    // told the request timed out while the UI stayed frozen.
    let backstop =
        Instant::now() + Duration::from_millis(budget_ms).max(Duration::from_millis(250));

    // `..=` so a budget of one frame still gets an initial check *and* a frame.
    for _ in 0..=max_frames {
        let update = tree.sync_accessibility();
        if condition_met(tree, &update, condition) {
            return AutomationReply::ok_unit();
        }
        if Instant::now() >= backstop {
            break;
        }
        // Drive timed / animated state forward one frame, then re-layout so
        // reactive (AccessibilityOnly) bindings flush before the next sync.
        tree.advance_time(WAIT_FRAME);
        tree.tick_animations(WAIT_FRAME);
        let proposal = tree.last_proposal();
        tree.layout_with_ops(proposal, ops);
    }
    AutomationReply::err(
        codes::WAIT_TIMEOUT,
        "wait_for_condition timed out before the predicate held",
    )
}

fn condition_met(
    tree: &WidgetTree,
    update: &accesskit::TreeUpdate,
    condition: &WaitCondition,
) -> bool {
    match condition {
        WaitCondition::NodeExists { role, label } => {
            find_node_ref(update, role.as_deref(), label.as_deref()).is_some()
        }
        WaitCondition::NodeValue { node, expected } => update
            .nodes
            .iter()
            .find(|(id, _)| id.0 == *node)
            .map(|(_, n)| n.value() == Some(expected.as_str()))
            .unwrap_or(false),
        WaitCondition::NodeGone { node } => !update.nodes.iter().any(|(id, _)| id.0 == *node),
        WaitCondition::AtVersionAtLeast { version } => tree.at_version().get() >= *version,
    }
}

// ---------------------------------------------------------------------------
// Node / tree helpers
// ---------------------------------------------------------------------------

/// Whether `node` is present in the freshly-synced AT tree (the reliable
/// liveness check — see [`dispatch_action_and_settle`]).
fn node_present(update: &accesskit::TreeUpdate, node: NodeRef) -> bool {
    update.nodes.iter().any(|(id, _)| id.0 == node)
}

/// Resolve a *present* [`NodeRef`] to its owning [`WidgetId`] — directly for
/// a widget node, or via the synthetic-parent map for a widget-emitted
/// child. Returns `None` when the node isn't in the live tree.
fn resolve_widget(
    tree: &WidgetTree,
    update: &accesskit::TreeUpdate,
    node: NodeRef,
) -> Option<WidgetId> {
    if !node_present(update, node) {
        return None;
    }
    let nid = accesskit::NodeId(node);
    teksilo_core::accessibility::node_id_to_widget_id_maybe(nid)
        .or_else(|| tree.widget_for_synthetic(nid))
}

fn center(r: Rect) -> Point {
    Point::new(r.x + r.width * 0.5, r.y + r.height * 0.5)
}

/// The pointer point to use when driving a gesture at `node`. Prefers the
/// node's own AT bounds — correct for *synthetic* children (scene items,
/// rich-text runs) whose owning widget may span far more area than the child
/// — and falls back to the owning widget's arena bounds. `None` only when the
/// node is absent from the live tree.
fn node_point(tree: &WidgetTree, update: &accesskit::TreeUpdate, node: NodeRef) -> Option<Point> {
    if let Some((_, n)) = update.nodes.iter().find(|(id, _)| id.0 == node)
        && let Some(r) = n.bounds()
    {
        return Some(Point::new(
            ((r.x0 + r.x1) * 0.5) as f32,
            ((r.y0 + r.y1) * 0.5) as f32,
        ));
    }
    let widget = resolve_widget(tree, update, node)?;
    Some(center(tree.bounds(widget)))
}

/// Build a [`SemanticNode`] from a raw AccessKit node.
fn semantic_node(
    id: accesskit::NodeId,
    node: &accesskit::Node,
    focus: accesskit::NodeId,
) -> SemanticNode {
    let toggled = node.toggled().map(|t| {
        match t {
            accesskit::Toggled::True => "true",
            accesskit::Toggled::False => "false",
            accesskit::Toggled::Mixed => "mixed",
        }
        .to_string()
    });
    let live = match node.live() {
        Some(accesskit::Live::Polite) => Some("polite".to_string()),
        Some(accesskit::Live::Assertive) => Some("assertive".to_string()),
        _ => None,
    };
    let bounds = node.bounds().map(|r| NodeBounds {
        x: r.x0,
        y: r.y0,
        width: r.x1 - r.x0,
        height: r.y1 - r.y0,
    });
    let actions = ADVERTISABLE_ACTIONS
        .iter()
        .filter(|(a, _)| node.supports_action(*a))
        .map(|(_, name)| name.to_string())
        .collect();
    SemanticNode {
        id: id.0,
        role: format!("{:?}", node.role()),
        label: node.label().map(|s| s.to_string()),
        value: node.value().map(|s| s.to_string()),
        description: node.description().map(|s| s.to_string()),
        toggled,
        expanded: node.is_expanded(),
        selected: node.is_selected(),
        level: node.level(),
        disabled: node.is_disabled(),
        focused: id == focus,
        live,
        numeric_value: node.numeric_value(),
        bounds,
        actions,
        children: node.children().iter().map(|c| c.0).collect(),
    }
}

/// Build a [`LayoutNode`](crate::dto::LayoutNode) for one arena widget.
fn layout_node(tree: &WidgetTree, id: WidgetId, include_debug: bool) -> crate::dto::LayoutNode {
    let to_ref = |w: WidgetId| teksilo_core::accessibility::widget_id_to_node_id(w).0;
    let b = tree.bounds(id);
    crate::dto::LayoutNode {
        id: to_ref(id),
        type_name: tree
            .widget_type_name(id)
            .map(|s| s.to_string())
            .unwrap_or_else(|| "?".to_string()),
        bounds: NodeBounds {
            x: b.x as f64,
            y: b.y as f64,
            width: b.width as f64,
            height: b.height as f64,
        },
        active: tree.is_active(id),
        clips_children: tree.widget_clips_children(id),
        parent: tree.parent(id).map(to_ref),
        children: tree.children(id).into_iter().map(to_ref).collect(),
        debug: if include_debug {
            tree.widget_debug_string(id)
        } else {
            None
        },
    }
}

/// Walk the arena widget tree from the roots (BFS, depth-capped), keying every
/// widget by the same `NodeRef` space as the AT tools.
fn layout_tree_json(
    tree: &WidgetTree,
    max_depth: Option<usize>,
    include_debug: bool,
) -> serde_json::Value {
    use std::collections::{HashSet, VecDeque};
    let to_ref = |w: WidgetId| teksilo_core::accessibility::widget_id_to_node_id(w).0;
    let roots = tree.roots();
    let mut out: Vec<crate::dto::LayoutNode> = Vec::new();
    let mut seen: HashSet<WidgetId> = HashSet::new();
    let mut queue: VecDeque<(WidgetId, usize)> = roots.iter().map(|r| (*r, 0usize)).collect();
    while let Some((id, depth)) = queue.pop_front() {
        if !seen.insert(id) {
            continue;
        }
        let descend = max_depth.map(|d| depth < d).unwrap_or(true);
        let mut node = layout_node(tree, id, include_debug);
        if !descend {
            // At the cap: drop child refs so there are no dangling ids.
            node.children.clear();
        }
        out.push(node);
        if descend {
            for c in tree.children(id) {
                queue.push_back((c, depth + 1));
            }
        }
    }
    serde_json::json!({
        "roots": roots.into_iter().map(to_ref).collect::<Vec<_>>(),
        "nodes": out,
    })
}

fn find_node(update: &accesskit::TreeUpdate, node: NodeRef) -> Option<SemanticNode> {
    let focus = update.focus;
    update
        .nodes
        .iter()
        .find(|(id, _)| id.0 == node)
        .map(|(id, n)| semantic_node(*id, n, focus))
}

/// First node (in AT/build order) whose role and/or label match. A `None`
/// filter matches anything; role compares against the role's `Debug` name
/// case-insensitively; label compares for exact equality.
fn find_node_ref(
    update: &accesskit::TreeUpdate,
    role: Option<&str>,
    label: Option<&str>,
) -> Option<NodeRef> {
    update
        .nodes
        .iter()
        .find(|(_, n)| {
            let role_ok = role
                .map(|r| format!("{:?}", n.role()).eq_ignore_ascii_case(r))
                .unwrap_or(true);
            let label_ok = label.map(|l| n.label() == Some(l)).unwrap_or(true);
            role_ok && label_ok
        })
        .map(|(id, _)| id.0)
}

fn snapshot_json(update: &accesskit::TreeUpdate, max_depth: Option<usize>) -> serde_json::Value {
    use std::collections::{HashMap, HashSet, VecDeque};
    let focus = update.focus;
    let map: HashMap<accesskit::NodeId, &accesskit::Node> =
        update.nodes.iter().map(|(id, n)| (*id, n)).collect();
    let root = update.tree.as_ref().map(|t| t.root);
    let mut out: Vec<SemanticNode> = Vec::new();
    match root {
        Some(root) => {
            let mut seen: HashSet<accesskit::NodeId> = HashSet::new();
            let mut queue: VecDeque<(accesskit::NodeId, usize)> = VecDeque::new();
            queue.push_back((root, 0));
            while let Some((nid, depth)) = queue.pop_front() {
                if !seen.insert(nid) {
                    continue;
                }
                if let Some(node) = map.get(&nid) {
                    let descend = max_depth.map(|d| depth < d).unwrap_or(true);
                    let mut sn = semantic_node(nid, node, focus);
                    // At the depth cap the children aren't emitted, so drop the
                    // child refs rather than leave dangling ids pointing at
                    // nodes absent from `nodes`.
                    if !descend {
                        sn.children.clear();
                    }
                    out.push(sn);
                    if descend {
                        for c in node.children() {
                            queue.push_back((*c, depth + 1));
                        }
                    }
                }
            }
        }
        None => {
            for (id, n) in &update.nodes {
                out.push(semantic_node(*id, n, focus));
            }
        }
    }
    serde_json::json!({
        "root": root.map(|r| r.0),
        "focus": focus.0,
        "nodes": out,
    })
}

/// Evaluate an assertion, distinguishing three outcomes rather than two.
///
/// `Ok` is a passing assertion. `Err` is either a genuinely false assertion
/// (`ASSERTION_FAILED`) or a node reference that names nothing
/// (`NOT_FOUND`) — and telling those apart is the point. "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.
///
/// `Assertion::Exists` against a missing node is `ASSERTION_FAILED`, not
/// `NOT_FOUND`: asking whether something exists and being told it does not is
/// an answer, not a lookup error.
fn evaluate_assertion(
    update: &accesskit::TreeUpdate,
    node: NodeRef,
    assertion: &Assertion,
) -> Result<AssertionResult, AutomationReply> {
    let found = update.nodes.iter().find(|(id, _)| id.0 == node);
    let pass = |passed: bool, detail: Option<String>| AssertionResult { passed, detail };
    let Some((id, n)) = found else {
        return Err(if matches!(assertion, Assertion::Exists) {
            AutomationReply::err(
                codes::ASSERTION_FAILED,
                format!("assertion 'exists' failed: node {node} is not in the tree"),
            )
        } else {
            AutomationReply::err(
                codes::NOT_FOUND,
                format!("node {node} is not in the tree, so nothing could be asserted about it"),
            )
        });
    };
    let result = match assertion {
        Assertion::Exists => pass(true, None),
        Assertion::Focused => {
            let ok = id.0 == update.focus.0;
            pass(ok, (!ok).then(|| "node is not focused".to_string()))
        }
        Assertion::RoleEquals { value } => {
            let actual = format!("{:?}", n.role());
            let ok = actual.eq_ignore_ascii_case(value);
            pass(
                ok,
                (!ok).then(|| format!("role is '{actual}', expected '{value}'")),
            )
        }
        Assertion::LabelEquals { value } => {
            let actual = n.label();
            let ok = actual == Some(value.as_str());
            pass(
                ok,
                (!ok).then(|| format!("label is {actual:?}, expected '{value}'")),
            )
        }
        Assertion::LabelContains { value } => {
            let actual = n.label().unwrap_or("");
            let ok = actual.contains(value.as_str());
            pass(
                ok,
                (!ok).then(|| format!("label '{actual}' does not contain '{value}'")),
            )
        }
        Assertion::ValueEquals { value } => {
            let actual = n.value();
            let ok = actual == Some(value.as_str());
            pass(
                ok,
                (!ok).then(|| format!("value is {actual:?}, expected '{value}'")),
            )
        }
        Assertion::Toggled { value } => {
            // A bool assertion must NOT collapse `Mixed` (tristate /
            // indeterminate) into `false`: `Toggled { value: false }` on a
            // partially-checked parent checkbox should FAIL, not silently pass.
            let state = n.toggled();
            let ok = matches!(
                (value, state),
                (true, Some(accesskit::Toggled::True)) | (false, Some(accesskit::Toggled::False))
            );
            let actual = match state {
                Some(accesskit::Toggled::True) => "true",
                Some(accesskit::Toggled::False) => "false",
                Some(accesskit::Toggled::Mixed) => "mixed",
                None => "none",
            };
            pass(
                ok,
                (!ok).then(|| format!("toggled is {actual}, expected {value}")),
            )
        }
        Assertion::Expanded { value } => {
            let actual = n.is_expanded().unwrap_or(false);
            let ok = actual == *value;
            pass(
                ok,
                (!ok).then(|| format!("expanded is {actual}, expected {value}")),
            )
        }
        Assertion::Selected { value } => {
            let actual = n.is_selected().unwrap_or(false);
            let ok = actual == *value;
            pass(
                ok,
                (!ok).then(|| format!("selected is {actual}, expected {value}")),
            )
        }
        Assertion::Disabled { value } => {
            let actual = n.is_disabled();
            let ok = actual == *value;
            pass(
                ok,
                (!ok).then(|| format!("disabled is {actual}, expected {value}")),
            )
        }
    };
    if result.passed {
        Ok(result)
    } else {
        // The detail is the whole value of the failure — "label is None,
        // expected 'Save'" is what tells the caller what to fix. It goes in the
        // message rather than being dropped, and the code says this was a real
        // node whose property did not match.
        Err(AutomationReply::err(
            codes::ASSERTION_FAILED,
            match result.detail {
                Some(detail) => format!("assertion failed on node {node}: {detail}"),
                None => format!("assertion failed on node {node}"),
            },
        ))
    }
}

// ---------------------------------------------------------------------------
// Name <-> enum mapping
// ---------------------------------------------------------------------------

/// Actions surfaced in a `SemanticNode.actions` list, paired with the
/// snake_case name an automation client uses in `invoke_action`.
const ADVERTISABLE_ACTIONS: &[(accesskit::Action, &str)] = &[
    (accesskit::Action::Click, "click"),
    (accesskit::Action::Focus, "focus"),
    (accesskit::Action::Increment, "increment"),
    (accesskit::Action::Decrement, "decrement"),
    (accesskit::Action::Expand, "expand"),
    (accesskit::Action::Collapse, "collapse"),
    (accesskit::Action::SetValue, "set_value"),
    (accesskit::Action::ShowContextMenu, "show_context_menu"),
    (accesskit::Action::ScrollIntoView, "scroll_into_view"),
    (accesskit::Action::ScrollUp, "scroll_up"),
    (accesskit::Action::ScrollDown, "scroll_down"),
    (accesskit::Action::ScrollLeft, "scroll_left"),
    (accesskit::Action::ScrollRight, "scroll_right"),
];

/// The snake_case name for an `accesskit::Action`, for error messages.
fn action_name(action: accesskit::Action) -> Option<&'static str> {
    ADVERTISABLE_ACTIONS
        .iter()
        .find(|(a, _)| *a == action)
        .map(|(_, name)| *name)
}

/// Map an automation action name to an `accesskit::Action`. Accepts the
/// snake_case names plus a few intuitive aliases.
fn action_from_str(s: &str) -> Option<accesskit::Action> {
    use accesskit::Action as A;
    let lower = s.to_ascii_lowercase();
    Some(match lower.as_str() {
        "click" | "default" | "press" | "activate" => A::Click,
        "focus" => A::Focus,
        "blur" => A::Blur,
        "increment" => A::Increment,
        "decrement" => A::Decrement,
        "expand" => A::Expand,
        "collapse" => A::Collapse,
        "set_value" => A::SetValue,
        "show_context_menu" | "context_menu" => A::ShowContextMenu,
        "scroll_into_view" => A::ScrollIntoView,
        "scroll_up" => A::ScrollUp,
        "scroll_down" => A::ScrollDown,
        "scroll_left" => A::ScrollLeft,
        "scroll_right" => A::ScrollRight,
        "show_tooltip" => A::ShowTooltip,
        "hide_tooltip" => A::HideTooltip,
        _ => return None,
    })
}

/// Build a [`Modifiers`] set from the DTO's flags.
///
/// `ctrl` is **literal** Control on every platform; `command` is the platform's
/// primary accelerator — Control on Windows and Linux, Command on macOS.
/// Keeping them apart is what lets one agent script drive all three platforms:
/// a Teksilo shortcut declared as `Ctrl+S` resolves to the Command chord on
/// macOS, so a probe sending literal Control there matches no binding and —
/// worse — reports success, because the key really was injected. See
/// [`Modifiers::COMMAND`].
fn modifiers(ctrl: bool, shift: bool, alt: bool, meta: bool, command: bool) -> Modifiers {
    let mut m = Modifiers::NONE;
    if ctrl {
        m = m | Modifiers::CTRL;
    }
    if command {
        m = m | Modifiers::COMMAND;
    }
    if shift {
        m = m | Modifiers::SHIFT;
    }
    if alt {
        m = m | Modifiers::ALT;
    }
    if meta {
        m = m | Modifiers::SUPER;
    }
    m
}

fn format_keystroke(ks: teksilo_core::shortcut::KeyStroke) -> String {
    // `Modifiers` Display emits a trailing "+", e.g. "Ctrl+"; `Key` Display
    // emits the key name. Together: "Ctrl+S".
    format!("{}{}", ks.modifiers, ks.key)
}

/// Map an automation key name to a [`Key`]. Accepts named keys
/// (case-insensitive), single characters, and ASCII letters.
fn key_from_str(s: &str) -> Option<Key> {
    let lower = s.to_ascii_lowercase();
    let named = match lower.as_str() {
        "space" | " " => Some(Key::Space),
        "enter" | "return" => Some(Key::Enter),
        "escape" | "esc" => Some(Key::Escape),
        "tab" => Some(Key::Tab),
        "backspace" => Some(Key::Backspace),
        "delete" | "del" => Some(Key::Delete),
        "up" | "arrowup" => Some(Key::ArrowUp),
        "down" | "arrowdown" => Some(Key::ArrowDown),
        "left" | "arrowleft" => Some(Key::ArrowLeft),
        "right" | "arrowright" => Some(Key::ArrowRight),
        "home" => Some(Key::Home),
        "end" => Some(Key::End),
        "pageup" => Some(Key::PageUp),
        "pagedown" => Some(Key::PageDown),
        "capslock" => Some(Key::CapsLock),
        "f1" => Some(Key::F1),
        "f2" => Some(Key::F2),
        "f3" => Some(Key::F3),
        "f4" => Some(Key::F4),
        "f5" => Some(Key::F5),
        "f6" => Some(Key::F6),
        "f7" => Some(Key::F7),
        "f8" => Some(Key::F8),
        "f9" => Some(Key::F9),
        "f10" => Some(Key::F10),
        "f11" => Some(Key::F11),
        "f12" => Some(Key::F12),
        _ => None,
    };
    if named.is_some() {
        return named;
    }
    // A single character.
    let mut chars = s.chars();
    match (chars.next(), chars.next()) {
        (Some(ch), None) => {
            // ASCII letters MUST map to the named `Key::A..Key::Z` variants,
            // not `Key::Character`: shortcuts register with `Key::S` etc., and
            // `KeyStroke` equality is by variant, so `inject_key {key:"s",
            // ctrl:true}` would otherwise never fire a `Ctrl+S` shortcut.
            if ch.is_ascii_alphabetic() {
                Some(letter_key(ch.to_ascii_uppercase()))
            } else {
                Some(Key::Character(ch))
            }
        }
        _ => None,
    }
}

/// Map an uppercase ASCII letter to its `Key::A..Key::Z` variant.
fn letter_key(upper: char) -> Key {
    match upper {
        'A' => Key::A,
        'B' => Key::B,
        'C' => Key::C,
        'D' => Key::D,
        'E' => Key::E,
        'F' => Key::F,
        'G' => Key::G,
        'H' => Key::H,
        'I' => Key::I,
        'J' => Key::J,
        'K' => Key::K,
        'L' => Key::L,
        'M' => Key::M,
        'N' => Key::N,
        'O' => Key::O,
        'P' => Key::P,
        'Q' => Key::Q,
        'R' => Key::R,
        'S' => Key::S,
        'T' => Key::T,
        'U' => Key::U,
        'V' => Key::V,
        'W' => Key::W,
        'X' => Key::X,
        'Y' => Key::Y,
        // Only reached for ASCII alphabetic chars, so 'Z' is the last case.
        _ => Key::Z,
    }
}