textual 1.0.0-dev

A reactive TUI framework inspired by the Python Textual library
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
use crate::debug::debug_message;
use crate::keys::KeyEventData;
use crate::keys::format_key_display;
use crate::message::{AsyncTaskRequest, CommandPaletteCommand, Message, MessageEvent};
use crate::node_id::{NodeId, node_id_to_ffi};
use crate::style::{Color, Scalar, Spacing, Tint};
use crate::worker::{CancellationToken, WorkerRequest, WorkerRequestPayload};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use std::collections::HashMap;
use std::time::Duration;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MouseDownEvent {
    pub target: NodeId,
    pub screen_x: u16,
    pub screen_y: u16,
    /// Content-local coordinates (origin at widget content top-left).
    pub x: u16,
    pub y: u16,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MouseUpEvent {
    pub target: Option<NodeId>,
    pub screen_x: u16,
    pub screen_y: u16,
    /// Content-local coordinates (origin at widget content top-left of `target`, if any).
    pub x: u16,
    pub y: u16,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MouseMoveEvent {
    pub target: NodeId,
    pub screen_x: u16,
    pub screen_y: u16,
    /// Content-local coordinates (origin at widget content top-left).
    pub x: u16,
    pub y: u16,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MouseScrollEvent {
    pub target: Option<NodeId>,
    pub screen_x: u16,
    pub screen_y: u16,
    /// Content-local coordinates (origin at widget content top-left of `target`, if any).
    pub x: u16,
    pub y: u16,
    pub delta_x: i32,
    pub delta_y: i32,
    pub modifiers: KeyModifiers,
}

/// Fired when the pointer enters a widget's region.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MouseEnterEvent {
    pub screen_x: u16,
    pub screen_y: u16,
    /// Content-local coordinates.
    pub x: u16,
    pub y: u16,
}

/// Fired when the pointer leaves a widget's region.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MouseLeaveEvent {
    pub screen_x: u16,
    pub screen_y: u16,
    /// Content-local coordinates.
    pub x: u16,
    pub y: u16,
}

/// Fired when a mousedown+mouseup pair hits the same widget (synthesised click).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ClickEvent {
    pub screen_x: u16,
    pub screen_y: u16,
    /// Content-local coordinates.
    pub x: u16,
    pub y: u16,
    /// 0=left, 1=middle, 2=right.
    pub button: u8,
}

/// Fired when the terminal delivers a bracketed-paste payload.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PasteEvent {
    pub text: String,
}

/// Fired when a widget is mounted into the tree.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MountEvent {
    pub node: NodeId,
}

/// Fired when a widget is unmounted from the tree.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UnmountEvent {
    pub node: NodeId,
}

/// Fired once after the first successful render frame.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ReadyEvent;

/// Fired when a widget gains focus.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FocusEvent {
    pub node: NodeId,
}

/// Fired when a widget loses focus.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BlurEvent {
    pub node: NodeId,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AnimationLevel {
    None,
    Basic,
    Full,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AnimationEase {
    None,
    Round,
    Linear,
    InOutCubic,
    OutCubic,
    // Quad
    InQuad,
    OutQuad,
    InOutQuad,
    // Cubic (In only — Out and InOut already exist above)
    InCubic,
    // Quart
    InQuart,
    OutQuart,
    InOutQuart,
    // Quint
    InQuint,
    OutQuint,
    InOutQuint,
    // Expo
    InExpo,
    OutExpo,
    InOutExpo,
    // Circ
    InCirc,
    OutCirc,
    InOutCirc,
    // Back (overshoot)
    InBack,
    OutBack,
    InOutBack,
    // Bounce
    InBounce,
    OutBounce,
    InOutBounce,
    // Elastic
    InElastic,
    OutElastic,
    InOutElastic,
}

#[derive(Debug, Clone, PartialEq)]
pub struct AnimationRequest {
    pub target: NodeId,
    pub attribute: String,
    pub start: f32,
    pub end: f32,
    pub duration: Duration,
    pub delay: Duration,
    pub ease: AnimationEase,
    pub level: AnimationLevel,
}

impl AnimationRequest {
    pub fn new(
        target: NodeId,
        attribute: impl Into<String>,
        start: f32,
        end: f32,
        duration: Duration,
    ) -> Self {
        Self {
            target,
            attribute: attribute.into(),
            start,
            end,
            duration,
            delay: Duration::ZERO,
            ease: AnimationEase::InOutCubic,
            level: AnimationLevel::Full,
        }
    }

    pub fn with_delay(mut self, delay: Duration) -> Self {
        self.delay = delay;
        self
    }

    pub fn with_ease(mut self, ease: AnimationEase) -> Self {
        self.ease = ease;
        self
    }

    pub fn with_level(mut self, level: AnimationLevel) -> Self {
        self.level = level;
        self
    }
}

/// Represents a typed value for CSS property animation.
#[derive(Debug, Clone, PartialEq)]
pub enum StyleValue {
    /// RGBA color value (for `fg`, `bg`).
    Color(Color),
    /// Float value (for `opacity`, `text_opacity` — 0.0–100.0 range).
    Float(f32),
    /// Scalar dimension (for `width`, `height`, `min_width`, etc.).
    Scalar(Scalar),
    /// Four-side spacing (for `margin`, `padding`).
    Spacing(Spacing),
    /// Tint value (for `tint`, `background_tint`).
    Tint(Tint),
}

/// Request to animate a CSS property to a target value on a specific node.
#[derive(Debug, Clone, PartialEq)]
pub struct StyleAnimationRequest {
    pub target: NodeId,
    pub property: String,
    pub from: StyleValue,
    pub to: StyleValue,
    pub duration: Duration,
    pub delay: Duration,
    pub ease: AnimationEase,
    pub level: AnimationLevel,
}

impl StyleAnimationRequest {
    pub fn new(
        target: NodeId,
        property: impl Into<String>,
        from: StyleValue,
        to: StyleValue,
        duration: Duration,
    ) -> Self {
        Self {
            target,
            property: property.into(),
            from,
            to,
            duration,
            delay: Duration::ZERO,
            ease: AnimationEase::InOutCubic,
            level: AnimationLevel::Full,
        }
    }

    pub fn with_delay(mut self, delay: Duration) -> Self {
        self.delay = delay;
        self
    }

    pub fn with_ease(mut self, ease: AnimationEase) -> Self {
        self.ease = ease;
        self
    }

    pub fn with_level(mut self, level: AnimationLevel) -> Self {
        self.level = level;
        self
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct AnimationValueEvent {
    pub target: NodeId,
    pub attribute: String,
    pub value: f32,
    pub done: bool,
}

#[derive(Debug, Clone)]
pub enum Event {
    Key(KeyEventData),
    Action(Action),
    BindingsChanged(Vec<BindingHint>),
    MouseDown(MouseDownEvent),
    MouseUp(MouseUpEvent),
    MouseMove(MouseMoveEvent),
    MouseScroll(MouseScrollEvent),
    Enter(MouseEnterEvent),
    Leave(MouseLeaveEvent),
    Click(ClickEvent),
    Paste(PasteEvent),
    Mount(MountEvent),
    Unmount(UnmountEvent),
    Ready(ReadyEvent),
    Focus(FocusEvent),
    Blur(BlurEvent),
    AnimationValue(AnimationValueEvent),
    AppFocus(bool),
    Tick(u64),
    Resize(u16, u16),
    /// Sent to the widget tree of a screen when it is no longer the active screen
    /// (another screen has been pushed on top).
    ScreenSuspend,
    /// Sent to the widget tree of a screen when it becomes the active screen again
    /// (the screen above was popped).
    ScreenResume,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Action {
    FocusNext,
    FocusPrev,
    HelpQuit,
    CopySelectedText,
    ScrollHome,
    ScrollEnd,
    ScrollUp,
    ScrollDown,
    ScrollPageUp,
    ScrollPageDown,
    ScrollLeft,
    ScrollRight,
    ScrollPageLeft,
    ScrollPageRight,
    Toggle,
    CommandPalette,
}

impl Action {
    pub fn description(self) -> &'static str {
        match self {
            Action::FocusNext => "Focus next",
            Action::FocusPrev => "Focus previous",
            Action::HelpQuit => "Show quit help",
            Action::CopySelectedText => "Copy selected text",
            Action::ScrollHome => "Scroll home",
            Action::ScrollEnd => "Scroll end",
            Action::ScrollUp => "Scroll up",
            Action::ScrollDown => "Scroll down",
            Action::ScrollPageUp => "Page up",
            Action::ScrollPageDown => "Page down",
            Action::ScrollLeft => "Scroll left",
            Action::ScrollRight => "Scroll right",
            Action::ScrollPageLeft => "Page left",
            Action::ScrollPageRight => "Page right",
            Action::Toggle => "Toggle",
            Action::CommandPalette => "Command palette",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct KeyBind {
    pub code: KeyCode,
    pub modifiers: KeyModifiers,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct BindingHint {
    pub key: String,
    pub description: String,
    pub tooltip: Option<String>,
    pub namespace: Option<String>,
    pub show: bool,
    pub key_display: Option<String>,
    pub group: Option<String>,
    pub priority: bool,
    pub system: bool,
    /// Action name from the binding declaration (e.g. `"back"`, `"forward"`).
    /// Used by `check_action` to determine enabled/disabled state.
    pub action: Option<String>,
    /// Parsed action name passed to `check_action`.
    ///
    /// For `BindingDecl::action = "app.push_screen('settings')"`, this stores
    /// `"push_screen"`.
    pub action_name: Option<String>,
    /// Parsed positional parameters passed to `check_action`.
    ///
    /// For `BindingDecl::action = "app.push_screen('settings')"`, this stores
    /// `["settings"]`.
    pub action_parameters: Vec<String>,
    /// Result of `check_action` for this binding:
    /// - `Some(true)` — enabled (default, rendered normally)
    /// - `Some(false)` — hidden (not shown in footer)
    /// - `None` — disabled but visible (rendered dimmed in footer)
    pub enabled: Option<bool>,
}

impl BindingHint {
    pub fn new(key: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            key: key.into(),
            description: description.into(),
            tooltip: None,
            namespace: None,
            show: true,
            key_display: None,
            group: None,
            priority: false,
            system: false,
            action: None,
            action_name: None,
            action_parameters: Vec::new(),
            enabled: Some(true),
        }
    }

    pub fn with_action(mut self, action: impl Into<String>) -> Self {
        let action = action.into();
        self.action = Some(action.clone());
        if let Some(parsed) = crate::action::parse_action(&action) {
            self.action_name = Some(parsed.name);
            self.action_parameters = parsed.arguments;
        } else {
            self.action_name = Some(action);
            self.action_parameters.clear();
        }
        self
    }

    pub fn hidden(mut self, hidden: bool) -> Self {
        self.show = !hidden;
        self
    }

    pub fn with_key_display(mut self, key_display: impl Into<String>) -> Self {
        self.key_display = Some(key_display.into());
        self
    }

    pub fn with_group(mut self, group: impl Into<String>) -> Self {
        self.group = Some(group.into());
        self
    }

    pub fn with_tooltip(mut self, tooltip: impl Into<String>) -> Self {
        self.tooltip = Some(tooltip.into());
        self
    }

    pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
        self.namespace = Some(namespace.into());
        self
    }

    pub fn with_priority(mut self, priority: bool) -> Self {
        self.priority = priority;
        self
    }

    pub fn with_system(mut self, system: bool) -> Self {
        self.system = system;
        self
    }
}

impl KeyBind {
    pub fn new(code: KeyCode, modifiers: KeyModifiers) -> Self {
        Self { code, modifiers }
    }

    pub fn from_event(key: &KeyEventData) -> Self {
        Self {
            code: key.code,
            modifiers: key.modifiers,
        }
    }

    pub fn key_name(&self) -> String {
        KeyEventData::from_crossterm(KeyEvent::new(self.code, self.modifiers)).key
    }

    pub fn display_key(&self) -> String {
        format_key_display(&self.key_name())
    }
}

#[derive(Debug, Default)]
pub struct ActionMap {
    bindings: HashMap<KeyBind, Action>,
}

impl ActionMap {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn bind(&mut self, key: KeyBind, action: Action) {
        self.bindings.insert(key, action);
    }

    pub fn lookup(&self, key: &KeyBind) -> Option<Action> {
        self.bindings.get(key).copied()
    }

    pub fn entries(&self) -> Vec<(KeyBind, Action)> {
        self.bindings
            .iter()
            .map(|(bind, action)| (*bind, *action))
            .collect()
    }
}

#[derive(Debug, Default)]
pub struct EventCtx {
    node_id: NodeId,
    handled: bool,
    repaint_requested: bool,
    invalidation: InvalidationFlags,
    stop_requested: bool,
    messages: Vec<MessageEvent>,
    animation_requests: Vec<AnimationRequest>,
    style_animation_requests: Vec<StyleAnimationRequest>,
    worker_requests: Vec<WorkerRequest>,
    recompose_nodes: Vec<NodeId>,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct InvalidationFlags {
    pub content: bool,
    pub style: bool,
    pub layout: bool,
}

impl InvalidationFlags {
    pub fn content() -> Self {
        Self {
            content: true,
            style: false,
            layout: false,
        }
    }

    pub fn style() -> Self {
        Self {
            content: true,
            style: true,
            layout: false,
        }
    }

    pub fn layout() -> Self {
        Self {
            content: true,
            style: true,
            layout: true,
        }
    }

    pub fn merge(&mut self, other: Self) {
        self.content |= other.content;
        self.style |= other.style;
        self.layout |= other.layout;
    }
}

impl EventCtx {
    /// The arena node ID for the widget currently being dispatched to.
    pub fn node_id(&self) -> NodeId {
        self.node_id
    }

    /// Set the node ID for the current dispatch context.
    pub fn set_node_id(&mut self, id: NodeId) {
        self.node_id = id;
    }

    pub fn handled(&self) -> bool {
        self.handled
    }

    pub fn set_handled(&mut self) {
        self.handled = true;
    }

    /// Request a repaint after this event dispatch finishes.
    ///
    /// This is useful when a widget updates visual state but does not (or should not)
    /// mark the event as handled.
    pub fn request_repaint(&mut self) {
        self.repaint_requested = true;
        self.invalidation.merge(InvalidationFlags::content());
    }

    pub fn repaint_requested(&self) -> bool {
        self.repaint_requested
    }

    pub fn invalidation(&self) -> InvalidationFlags {
        self.invalidation
    }

    /// Request style recomputation (without forcing a full relayout).
    pub fn request_style_invalidation(&mut self) {
        self.repaint_requested = true;
        self.invalidation.merge(InvalidationFlags::style());
    }

    /// Request a layout/style/content invalidation.
    pub fn request_layout_invalidation(&mut self) {
        self.repaint_requested = true;
        self.invalidation.merge(InvalidationFlags::layout());
    }

    /// Request subtree recomposition for the current widget node.
    pub fn request_recompose(&mut self) {
        self.request_recompose_node(self.node_id);
    }

    /// Request subtree recomposition for a specific node.
    pub fn request_recompose_node(&mut self, node_id: NodeId) {
        if !self.recompose_nodes.contains(&node_id) {
            self.recompose_nodes.push(node_id);
        }
        self.request_layout_invalidation();
    }

    /// Request the runtime event loop to stop after current dispatch finishes.
    pub fn request_stop(&mut self) {
        self.stop_requested = true;
    }

    pub fn stop_requested(&self) -> bool {
        self.stop_requested
    }

    pub fn post_message(&mut self, message: Message) {
        debug_message(&format!(
            "[post_message] sender={} payload={message:?}",
            node_id_to_ffi(self.node_id)
        ));
        self.messages.push(MessageEvent {
            sender: self.node_id,
            message,
            control: Some(self.node_id),
        });
    }

    pub fn spawn_async_task(&mut self, task_id: u64, target: NodeId, request: AsyncTaskRequest) {
        self.post_message(Message::AsyncTaskSpawn(crate::message::AsyncTaskSpawn {
            task_id,
            target,
            request,
        }));
    }

    pub fn spawn_async_task_for(&mut self, task_id: u64, request: AsyncTaskRequest) {
        let self_id = self.node_id;
        self.spawn_async_task(task_id, self_id, request);
    }

    pub fn cancel_async_task(&mut self, task_id: u64) {
        self.post_message(Message::AsyncTaskCancel(crate::message::AsyncTaskCancel {
            task_id,
        }));
    }

    pub fn cancel_async_tasks_for(&mut self, target: NodeId) {
        self.post_message(Message::AsyncTaskCancelTarget(
            crate::message::AsyncTaskCancelTarget { target },
        ));
    }

    pub fn schedule_timer(&mut self, timer_id: u64, target: NodeId, delay: Duration) {
        self.post_message(Message::TimerSchedule(crate::message::TimerSchedule {
            timer_id,
            target,
            delay,
        }));
    }

    pub fn schedule_timer_for(&mut self, timer_id: u64, delay: Duration) {
        let self_id = self.node_id;
        self.schedule_timer(timer_id, self_id, delay);
    }

    pub fn cancel_timer(&mut self, timer_id: u64) {
        self.post_message(Message::TimerCancel(crate::message::TimerCancel {
            timer_id,
        }));
    }

    pub fn set_overlay_visible(&mut self, overlay: NodeId, visible: bool) {
        self.post_message(Message::OverlaySetVisible(
            crate::message::OverlaySetVisible { overlay, visible },
        ));
    }

    pub fn show_overlay(&mut self, overlay: NodeId) {
        self.set_overlay_visible(overlay, true);
    }

    pub fn hide_overlay(&mut self, overlay: NodeId) {
        self.set_overlay_visible(overlay, false);
    }

    pub fn toggle_overlay(&mut self, overlay: NodeId) {
        self.post_message(Message::OverlayToggle(crate::message::OverlayToggle {
            overlay,
        }));
    }

    pub fn dismiss_overlay(&mut self, overlay: Option<NodeId>) {
        self.post_message(Message::OverlayDismissRequested(
            crate::message::OverlayDismissRequested { overlay },
        ));
    }

    pub fn open_command_palette(&mut self) {
        self.post_message(Message::CommandPaletteOpened(
            crate::message::CommandPaletteOpened,
        ));
    }

    pub fn close_command_palette(&mut self) {
        self.post_message(Message::CommandPaletteClosed(
            crate::message::CommandPaletteClosed,
        ));
    }

    pub fn set_command_palette_commands(&mut self, commands: Vec<CommandPaletteCommand>) {
        self.post_message(Message::CommandPaletteSetCommands(
            crate::message::CommandPaletteSetCommands { commands },
        ));
    }

    pub fn select_command_palette_command(
        &mut self,
        id: impl Into<String>,
        title: impl Into<String>,
    ) {
        self.post_message(Message::CommandPaletteCommandSelected(
            crate::message::CommandPaletteCommandSelected {
                id: id.into(),
                title: title.into(),
            },
        ));
    }

    pub fn request_animation(&mut self, request: AnimationRequest) {
        debug_message(&format!(
            "[request_animation] target={} attribute={} start={} end={} duration_ms={} delay_ms={} ease={:?} level={:?}",
            node_id_to_ffi(request.target),
            request.attribute,
            request.start,
            request.end,
            request.duration.as_millis(),
            request.delay.as_millis(),
            request.ease,
            request.level
        ));
        self.animation_requests.push(request);
    }

    /// Request a CSS property animation on a specific node.
    pub fn animate_style(
        &mut self,
        target: NodeId,
        property: impl Into<String>,
        from: StyleValue,
        to: StyleValue,
        duration: Duration,
        ease: AnimationEase,
    ) {
        let request =
            StyleAnimationRequest::new(target, property, from, to, duration).with_ease(ease);
        self.request_style_animation(request);
    }

    /// Enqueue a fully-formed style animation request.
    pub fn request_style_animation(&mut self, request: StyleAnimationRequest) {
        debug_message(&format!(
            "[request_style_animation] target={} property={} duration_ms={} ease={:?}",
            node_id_to_ffi(request.target),
            request.property,
            request.duration.as_millis(),
            request.ease
        ));
        self.style_animation_requests.push(request);
    }

    /// Request a background worker to be spawned by the runtime.
    ///
    /// Returns after recording the request — actual spawning happens in the
    /// runtime event loop after dispatch completes.
    pub fn request_worker(&mut self, name: Option<&str>) {
        self.request_worker_with_payload(name, WorkerRequestPayload::default());
    }

    /// Request a background worker with an explicit payload.
    pub fn request_worker_with_payload(
        &mut self,
        name: Option<&str>,
        payload: WorkerRequestPayload,
    ) {
        self.worker_requests.push(WorkerRequest {
            owner: self.node_id,
            exclusive_key: None,
            name: name.map(|s| s.to_string()),
            payload,
        });
    }

    /// Request an exclusive background worker.
    ///
    /// Any existing worker with the same `key` owned by this widget will be
    /// cancelled before the new one starts.
    pub fn request_exclusive_worker(&mut self, key: &str, name: Option<&str>) {
        self.request_exclusive_worker_with_payload(key, name, WorkerRequestPayload::default());
    }

    /// Request an exclusive background worker with an explicit payload.
    pub fn request_exclusive_worker_with_payload(
        &mut self,
        key: &str,
        name: Option<&str>,
        payload: WorkerRequestPayload,
    ) {
        self.worker_requests.push(WorkerRequest {
            owner: self.node_id,
            exclusive_key: Some(key.to_string()),
            name: name.map(|s| s.to_string()),
            payload,
        });
    }

    /// Request a closure-backed background worker.
    pub fn request_worker_task(
        &mut self,
        name: Option<&str>,
        task: impl FnOnce(CancellationToken) -> Result<(), String> + Send + 'static,
    ) {
        self.request_worker_with_payload(name, WorkerRequestPayload::task(task));
    }

    /// Request a closure-backed exclusive background worker.
    pub fn request_exclusive_worker_task(
        &mut self,
        key: &str,
        name: Option<&str>,
        task: impl FnOnce(CancellationToken) -> Result<(), String> + Send + 'static,
    ) {
        self.request_exclusive_worker_with_payload(key, name, WorkerRequestPayload::task(task));
    }

    /// Take pending worker requests (called by runtime after dispatch).
    pub(crate) fn take_worker_requests(&mut self) -> Vec<WorkerRequest> {
        std::mem::take(&mut self.worker_requests)
    }

    pub(crate) fn take_recompose_nodes(&mut self) -> Vec<NodeId> {
        std::mem::take(&mut self.recompose_nodes)
    }

    pub(crate) fn merge_from(&mut self, mut other: EventCtx) {
        if other.handled {
            self.handled = true;
        }
        if other.repaint_requested {
            self.repaint_requested = true;
        }
        self.invalidation.merge(other.invalidation);
        if other.stop_requested {
            self.stop_requested = true;
        }
        self.messages.append(&mut other.messages);
        self.animation_requests
            .append(&mut other.animation_requests);
        self.style_animation_requests
            .append(&mut other.style_animation_requests);
        self.worker_requests.append(&mut other.worker_requests);
        for node_id in other.recompose_nodes.drain(..) {
            if !self.recompose_nodes.contains(&node_id) {
                self.recompose_nodes.push(node_id);
            }
        }
    }

    pub(crate) fn take_messages(&mut self) -> Vec<MessageEvent> {
        std::mem::take(&mut self.messages)
    }

    pub(crate) fn take_animation_requests(&mut self) -> Vec<AnimationRequest> {
        std::mem::take(&mut self.animation_requests)
    }

    /// Animation infrastructure — will be wired when the animation system
    /// drives CSS transition requests through EventCtx.
    #[allow(dead_code)]
    pub(crate) fn take_style_animation_requests(&mut self) -> Vec<StyleAnimationRequest> {
        std::mem::take(&mut self.style_animation_requests)
    }
}

/// Widget-facing context provided by the runtime during event dispatch and rendering.
///
/// **Key design principle:** Widgets do NOT own or store their canonical identity.
/// The arena (`WidgetTree`) owns node identity; widgets receive it through this
/// context when they need it (event handlers, watchers, render).
///
/// `WidgetCtx` wraps an `EventCtx` plus the caller's `NodeId`, so widgets can
/// post messages, request repaints, and query their own identity without owning
/// an identity field.
///
/// # Lifecycle
///
/// The runtime constructs a `WidgetCtx` before each widget callback (event,
/// render, mount, etc.) and reads side-effects out of it afterwards. Widgets
/// never construct one themselves.
///
/// # Migration path
///
/// `WidgetCtx` will gradually replace direct `EventCtx` parameters in widget
/// trait methods as the arena-tree dispatch matures.
#[derive(Debug)]
pub struct WidgetCtx<'a> {
    node_id: NodeId,
    event_ctx: &'a mut EventCtx,
}

impl<'a> WidgetCtx<'a> {
    /// Create a new widget context. Called by the runtime, not by widgets.
    ///
    /// Public API — documented migration path from EventCtx for tree-aware
    /// event handling. Not yet called from the runtime event loop.
    #[allow(dead_code)]
    pub(crate) fn new(node_id: NodeId, event_ctx: &'a mut EventCtx) -> Self {
        Self { node_id, event_ctx }
    }

    /// The arena-assigned identity of this widget.
    #[inline]
    pub fn node_id(&self) -> NodeId {
        self.node_id
    }

    /// Access the underlying `EventCtx` for repaint/stop/invalidation requests.
    #[inline]
    pub fn event_ctx(&self) -> &EventCtx {
        self.event_ctx
    }

    /// Mutable access to the underlying `EventCtx`.
    #[inline]
    pub fn event_ctx_mut(&mut self) -> &mut EventCtx {
        self.event_ctx
    }

    // ── Convenience delegates ──────────────────────────────────────────

    /// Mark the event as handled.
    #[inline]
    pub fn set_handled(&mut self) {
        self.event_ctx.set_handled();
    }

    /// Request a repaint after event dispatch.
    #[inline]
    pub fn request_repaint(&mut self) {
        self.event_ctx.request_repaint();
    }

    /// Request the runtime to stop.
    #[inline]
    pub fn request_stop(&mut self) {
        self.event_ctx.request_stop();
    }

    /// Post a message from this widget (sender = self).
    #[inline]
    pub fn post_message(&mut self, message: Message) {
        self.event_ctx.set_node_id(self.node_id);
        self.event_ctx.post_message(message);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::message::{AsyncTaskRequest, CommandPaletteCommand, Message};
    use crate::node_id::node_id_from_ffi;
    use crate::style::{Color, Scalar, Spacing, Tint};
    use std::time::Duration;

    #[test]
    fn helper_methods_emit_runtime_control_messages() {
        let sender_id = node_id_from_ffi(12);
        let mut ctx = EventCtx::default();
        ctx.set_node_id(sender_id);

        ctx.spawn_async_task_for(
            5,
            AsyncTaskRequest::Sleep {
                duration: Duration::from_millis(10),
                label: "work".to_string(),
            },
        );
        ctx.schedule_timer_for(9, Duration::from_millis(25));
        ctx.cancel_async_task(5);
        ctx.cancel_timer(9);

        let messages = ctx.take_messages();
        assert_eq!(messages.len(), 4);
        assert!(matches!(
            &messages[0].message,
            Message::AsyncTaskSpawn(crate::message::AsyncTaskSpawn {
                task_id,
                target,
                request: AsyncTaskRequest::Sleep { label, .. },
            }) if *task_id == 5 && *target == sender_id && label == "work"
        ));
        assert!(matches!(
            messages[1].message,
            Message::TimerSchedule(crate::message::TimerSchedule {
                timer_id,
                target,
                ..
            }) if timer_id == 9 && target == sender_id
        ));
        assert!(matches!(
            messages[2].message,
            Message::AsyncTaskCancel(crate::message::AsyncTaskCancel { task_id }) if task_id == 5
        ));
        assert!(matches!(
            messages[3].message,
            Message::TimerCancel(crate::message::TimerCancel { timer_id }) if timer_id == 9
        ));
    }

    #[test]
    fn overlay_and_command_palette_helpers_emit_messages() {
        let overlay_id = node_id_from_ffi(77);
        let mut ctx = EventCtx::default();
        ctx.set_node_id(node_id_from_ffi(5));

        ctx.show_overlay(overlay_id);
        ctx.hide_overlay(overlay_id);
        ctx.toggle_overlay(overlay_id);
        ctx.dismiss_overlay(Some(overlay_id));
        ctx.open_command_palette();
        ctx.set_command_palette_commands(vec![CommandPaletteCommand {
            id: "open".to_string(),
            title: "Open".to_string(),
            help: "Open file".to_string(),
        }]);
        ctx.select_command_palette_command("open", "Open");
        ctx.close_command_palette();

        let messages = ctx.take_messages();
        assert_eq!(messages.len(), 8);
        assert!(matches!(
            messages[0].message,
            Message::OverlaySetVisible(crate::message::OverlaySetVisible {
                overlay: target,
                visible: true
            }) if target == overlay_id
        ));
        assert!(matches!(
            messages[1].message,
            Message::OverlaySetVisible(crate::message::OverlaySetVisible {
                overlay: target,
                visible: false
            }) if target == overlay_id
        ));
        assert!(matches!(
            messages[2].message,
            Message::OverlayToggle(crate::message::OverlayToggle { overlay: target }) if target == overlay_id
        ));
        assert!(matches!(
            messages[3].message,
            Message::OverlayDismissRequested(crate::message::OverlayDismissRequested { overlay: Some(target) }) if target == overlay_id
        ));
        assert!(matches!(
            messages[4].message,
            Message::CommandPaletteOpened(_)
        ));
        assert!(matches!(
            &messages[5].message,
            Message::CommandPaletteSetCommands(crate::message::CommandPaletteSetCommands { commands })
                if commands.len() == 1 && commands[0].id == "open"
        ));
        assert!(matches!(
            &messages[6].message,
            Message::CommandPaletteCommandSelected(crate::message::CommandPaletteCommandSelected { id, title }) if id == "open" && title == "Open"
        ));
        assert!(matches!(
            messages[7].message,
            Message::CommandPaletteClosed(_)
        ));
    }

    // ── New event struct construction tests ──────────────────────────

    #[test]
    fn mouse_enter_event_construction() {
        let e = MouseEnterEvent {
            x: 5,
            y: 10,
            screen_x: 20,
            screen_y: 30,
        };
        assert_eq!(e.x, 5);
        assert_eq!(e.y, 10);
        assert_eq!(e.screen_x, 20);
        assert_eq!(e.screen_y, 30);
        let ev = Event::Enter(e);
        assert!(matches!(
            ev,
            Event::Enter(MouseEnterEvent { x: 5, y: 10, .. })
        ));
    }

    #[test]
    fn mouse_leave_event_construction() {
        let e = MouseLeaveEvent {
            x: 1,
            y: 2,
            screen_x: 3,
            screen_y: 4,
        };
        let ev = Event::Leave(e);
        assert!(matches!(
            ev,
            Event::Leave(MouseLeaveEvent {
                x: 1,
                y: 2,
                screen_x: 3,
                screen_y: 4
            })
        ));
    }

    #[test]
    fn click_event_construction() {
        let e = ClickEvent {
            x: 10,
            y: 20,
            screen_x: 50,
            screen_y: 60,
            button: 0,
        };
        assert_eq!(e.button, 0);
        let ev = Event::Click(e);
        assert!(matches!(ev, Event::Click(ClickEvent { button: 0, .. })));
    }

    #[test]
    fn click_event_right_button() {
        let e = ClickEvent {
            x: 0,
            y: 0,
            screen_x: 0,
            screen_y: 0,
            button: 2,
        };
        assert_eq!(e.button, 2);
    }

    #[test]
    fn paste_event_construction() {
        let e = PasteEvent {
            text: "hello world".to_string(),
        };
        assert_eq!(e.text, "hello world");
        let ev = Event::Paste(e);
        assert!(matches!(ev, Event::Paste(PasteEvent { .. })));
    }

    #[test]
    fn paste_event_empty_text() {
        let e = PasteEvent {
            text: String::new(),
        };
        assert!(e.text.is_empty());
    }

    #[test]
    fn mount_event_construction() {
        let id = node_id_from_ffi(42);
        let e = MountEvent { node: id };
        assert_eq!(e.node, id);
        let ev = Event::Mount(e);
        assert!(matches!(ev, Event::Mount(MountEvent { node }) if node == id));
    }

    #[test]
    fn unmount_event_construction() {
        let id = node_id_from_ffi(7);
        let e = UnmountEvent { node: id };
        assert_eq!(e.node, id);
        let ev = Event::Unmount(e);
        assert!(matches!(ev, Event::Unmount(UnmountEvent { node }) if node == id));
    }

    #[test]
    fn ready_event_construction() {
        let e = ReadyEvent;
        let ev = Event::Ready(e);
        assert!(matches!(ev, Event::Ready(ReadyEvent)));
    }

    #[test]
    fn focus_event_construction() {
        let id = node_id_from_ffi(99);
        let e = FocusEvent { node: id };
        assert_eq!(e.node, id);
        let ev = Event::Focus(e);
        assert!(matches!(ev, Event::Focus(FocusEvent { node }) if node == id));
    }

    #[test]
    fn blur_event_construction() {
        let id = node_id_from_ffi(55);
        let e = BlurEvent { node: id };
        assert_eq!(e.node, id);
        let ev = Event::Blur(e);
        assert!(matches!(ev, Event::Blur(BlurEvent { node }) if node == id));
    }

    // ── StyleValue / StyleAnimationRequest tests ─────────────────────

    #[test]
    fn style_value_color_construction() {
        let v = StyleValue::Color(Color::rgb(10, 20, 30));
        assert!(matches!(
            v,
            StyleValue::Color(Color {
                r: 10,
                g: 20,
                b: 30,
                a: 255
            })
        ));
    }

    #[test]
    fn style_value_float_construction() {
        let v = StyleValue::Float(50.0);
        assert!(matches!(v, StyleValue::Float(x) if (x - 50.0).abs() < 0.001));
    }

    #[test]
    fn style_value_scalar_construction() {
        let v = StyleValue::Scalar(Scalar::Cells(42));
        assert!(matches!(v, StyleValue::Scalar(Scalar::Cells(42))));
    }

    #[test]
    fn style_value_spacing_construction() {
        let v = StyleValue::Spacing(Spacing::all(5));
        if let StyleValue::Spacing(s) = v {
            assert_eq!(s.top, 5);
            assert_eq!(s.right, 5);
        } else {
            panic!("expected Spacing");
        }
    }

    #[test]
    fn style_value_tint_construction() {
        let v = StyleValue::Tint(Tint::new(Color::rgb(255, 0, 0), 50));
        if let StyleValue::Tint(t) = v {
            assert_eq!(t.color, Color::rgb(255, 0, 0));
            assert_eq!(t.percent, 50);
        } else {
            panic!("expected Tint");
        }
    }

    #[test]
    fn style_animation_request_builder() {
        let target = node_id_from_ffi(10);
        let req = StyleAnimationRequest::new(
            target,
            "bg",
            StyleValue::Color(Color::rgb(0, 0, 0)),
            StyleValue::Color(Color::rgb(255, 255, 255)),
            Duration::from_millis(300),
        )
        .with_delay(Duration::from_millis(50))
        .with_ease(AnimationEase::Linear)
        .with_level(AnimationLevel::Basic);

        assert_eq!(req.target, target);
        assert_eq!(req.property, "bg");
        assert_eq!(req.duration, Duration::from_millis(300));
        assert_eq!(req.delay, Duration::from_millis(50));
        assert_eq!(req.ease, AnimationEase::Linear);
        assert_eq!(req.level, AnimationLevel::Basic);
    }

    #[test]
    fn event_ctx_animate_style_populates_requests() {
        let target = node_id_from_ffi(20);
        let mut ctx = EventCtx::default();
        ctx.set_node_id(target);

        ctx.animate_style(
            target,
            "opacity",
            StyleValue::Float(0.0),
            StyleValue::Float(100.0),
            Duration::from_millis(500),
            AnimationEase::OutCubic,
        );

        let requests = ctx.take_style_animation_requests();
        assert_eq!(requests.len(), 1);
        assert_eq!(requests[0].property, "opacity");
        assert_eq!(requests[0].ease, AnimationEase::OutCubic);
    }

    #[test]
    fn event_ctx_merge_includes_style_animation_requests() {
        let mut a = EventCtx::default();
        a.set_node_id(node_id_from_ffi(1));
        let mut b = EventCtx::default();
        b.set_node_id(node_id_from_ffi(2));

        let target = node_id_from_ffi(10);
        a.request_style_animation(StyleAnimationRequest::new(
            target,
            "fg",
            StyleValue::Color(Color::rgb(0, 0, 0)),
            StyleValue::Color(Color::rgb(255, 0, 0)),
            Duration::from_millis(200),
        ));
        b.request_style_animation(StyleAnimationRequest::new(
            target,
            "bg",
            StyleValue::Color(Color::rgb(0, 0, 0)),
            StyleValue::Color(Color::rgb(0, 255, 0)),
            Duration::from_millis(300),
        ));

        a.merge_from(b);
        let requests = a.take_style_animation_requests();
        assert_eq!(requests.len(), 2);
        assert_eq!(requests[0].property, "fg");
        assert_eq!(requests[1].property, "bg");
    }

    #[test]
    fn animation_ease_has_all_variants() {
        let variants = [
            AnimationEase::None,
            AnimationEase::Round,
            AnimationEase::Linear,
            AnimationEase::InOutCubic,
            AnimationEase::OutCubic,
            AnimationEase::InQuad,
            AnimationEase::OutQuad,
            AnimationEase::InOutQuad,
            AnimationEase::InCubic,
            AnimationEase::InQuart,
            AnimationEase::OutQuart,
            AnimationEase::InOutQuart,
            AnimationEase::InQuint,
            AnimationEase::OutQuint,
            AnimationEase::InOutQuint,
            AnimationEase::InExpo,
            AnimationEase::OutExpo,
            AnimationEase::InOutExpo,
            AnimationEase::InCirc,
            AnimationEase::OutCirc,
            AnimationEase::InOutCirc,
            AnimationEase::InBack,
            AnimationEase::OutBack,
            AnimationEase::InOutBack,
            AnimationEase::InBounce,
            AnimationEase::OutBounce,
            AnimationEase::InOutBounce,
            AnimationEase::InElastic,
            AnimationEase::OutElastic,
            AnimationEase::InOutElastic,
        ];
        assert_eq!(variants.len(), 30);
    }

    // ── Worker request tests ───────────────────────────────────────────

    #[test]
    fn event_ctx_request_worker() {
        let owner = node_id_from_ffi(10);
        let mut ctx = EventCtx::default();
        ctx.set_node_id(owner);
        ctx.request_worker(Some("bg-fetch"));

        let reqs = ctx.take_worker_requests();
        assert_eq!(reqs.len(), 1);
        assert_eq!(reqs[0].owner, owner);
        assert!(reqs[0].exclusive_key.is_none());
        assert_eq!(reqs[0].name.as_deref(), Some("bg-fetch"));
    }

    #[test]
    fn event_ctx_request_exclusive_worker() {
        let owner = node_id_from_ffi(11);
        let mut ctx = EventCtx::default();
        ctx.set_node_id(owner);
        ctx.request_exclusive_worker("search", Some("search-worker"));

        let reqs = ctx.take_worker_requests();
        assert_eq!(reqs.len(), 1);
        assert_eq!(reqs[0].owner, owner);
        assert_eq!(reqs[0].exclusive_key.as_deref(), Some("search"));
        assert_eq!(reqs[0].name.as_deref(), Some("search-worker"));
    }

    #[test]
    fn event_ctx_request_worker_with_payload() {
        let owner = node_id_from_ffi(12);
        let mut ctx = EventCtx::default();
        ctx.set_node_id(owner);
        ctx.request_worker_with_payload(
            Some("digest"),
            WorkerRequestPayload::ComputeDigest {
                input: "abc".into(),
                rounds: 2,
                delay_per_round_ms: 0,
                fail_with: None,
            },
        );
        let reqs = ctx.take_worker_requests();
        assert_eq!(reqs.len(), 1);
        assert_eq!(reqs[0].owner, owner);
        assert!(matches!(
            reqs[0].payload,
            WorkerRequestPayload::ComputeDigest { rounds: 2, .. }
        ));
    }

    #[test]
    fn event_ctx_request_worker_task_uses_task_payload() {
        let mut ctx = EventCtx::default();
        ctx.set_node_id(node_id_from_ffi(13));
        ctx.request_worker_task(Some("task"), |_token| Ok(()));
        let reqs = ctx.take_worker_requests();
        assert_eq!(reqs.len(), 1);
        assert!(matches!(reqs[0].payload, WorkerRequestPayload::Task(_)));
    }

    #[test]
    fn event_ctx_take_worker_requests_drains() {
        let mut ctx = EventCtx::default();
        ctx.set_node_id(node_id_from_ffi(1));
        ctx.request_worker(None);
        ctx.request_worker(None);

        let reqs = ctx.take_worker_requests();
        assert_eq!(reqs.len(), 2);
        // Second take should be empty.
        let reqs2 = ctx.take_worker_requests();
        assert!(reqs2.is_empty());
    }

    #[test]
    fn event_ctx_merge_includes_worker_requests() {
        let mut a = EventCtx::default();
        a.set_node_id(node_id_from_ffi(1));
        a.request_worker(Some("a"));

        let mut b = EventCtx::default();
        b.set_node_id(node_id_from_ffi(2));
        b.request_worker(Some("b"));

        a.merge_from(b);
        let reqs = a.take_worker_requests();
        assert_eq!(reqs.len(), 2);
        assert_eq!(reqs[0].name.as_deref(), Some("a"));
        assert_eq!(reqs[1].name.as_deref(), Some("b"));
    }

    #[test]
    fn post_message_sets_control_to_sender() {
        let sender_id = node_id_from_ffi(42);
        let mut ctx = EventCtx::default();
        ctx.set_node_id(sender_id);

        ctx.post_message(Message::ClearRequested(crate::message::ClearRequested));

        let messages = ctx.take_messages();
        assert_eq!(messages.len(), 1);
        assert_eq!(messages[0].sender, sender_id);
        assert_eq!(
            messages[0].control,
            Some(sender_id),
            "post_message should set control to Some(sender)"
        );
    }
}