mecha10-cli 0.8.0

Mecha10 CLI tool
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
//! Teleop UI with ratatui TUI and logs sidebar
//!
//! 3-panel interface: teleop controls/status, real-time logs sidebar, footer links.

use crate::dev::termination::{classify_key, ScreenOutcome, TerminationIntent};
use crate::ui::LogBuffer;
use anyhow::Result;
use crossterm::{
    event::{
        Event, EventStream, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, KeyboardEnhancementFlags,
        PopKeyboardEnhancementFlags, PushKeyboardEnhancementFlags,
    },
    execute,
    terminal::{
        disable_raw_mode, enable_raw_mode, supports_keyboard_enhancement, EnterAlternateScreen, LeaveAlternateScreen,
    },
};
use futures_util::StreamExt;
use mecha10_core::context::Context;
use mecha10_core::prelude::now_micros;
use mecha10_core::teleop::TeleopInput;
use mecha10_core::topics::Topic;
use ratatui::{
    backend::CrosstermBackend,
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, List, ListItem, Paragraph},
    Frame, Terminal,
};
use std::collections::HashMap;
use std::io::stdout;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

use crate::ui::tui_layout::{draw_dashboard_footer, SidebarTui};

const TELEOP_CMD: Topic<TeleopInput> = Topic::new("/teleop/cmd");

const HELD_WINDOW: Duration = Duration::from_millis(300);

const REPUBLISH_INTERVAL: Duration = Duration::from_millis(75);

/// Per-keypress position nudge for actuator-mode joint control, in radians.
const JOINT_STEP_RAD: f32 = 0.05;

#[derive(Debug, Clone, Copy)]
struct HeldKeyTracker {
    last_event: Option<Instant>,
    window: Duration,
}

impl HeldKeyTracker {
    fn new(window: Duration) -> Self {
        Self {
            last_event: None,
            window,
        }
    }

    /// Record a fresh KeyDown at `now` - refreshes the held window.
    fn mark_pressed_at(&mut self, now: Instant) {
        self.last_event = Some(now);
    }

    /// True if a KeyDown refreshed the window within `window` of `now`.
    fn is_held_at(&self, now: Instant) -> bool {
        self.last_event.is_some_and(|t| now.duration_since(t) < self.window)
    }

    /// Explicitly stop considering any key held (e.g. Stop/Space/X pressed,
    /// or emergency stop engaged) - stops future re-publishing immediately
    /// rather than waiting for the window to expire.
    fn clear(&mut self) {
        self.last_event = None;
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MovementKeyAction {
    Activate,
    Release,
}

/// Classify a movement key's `KeyEventKind` into an action to take.
fn classify_movement_key(kind: KeyEventKind) -> MovementKeyAction {
    match kind {
        KeyEventKind::Release => MovementKeyAction::Release,
        KeyEventKind::Press | KeyEventKind::Repeat => MovementKeyAction::Activate,
    }
}

/// The canonical string key `TeleopUi::key_bindings` is keyed by for a given `KeyEvent` - a
/// lowercased single character for `KeyCode::Char`, or `"up"`/`"down"`/`"left"`/`"right"` for
/// the arrow keys. `None` for any other key (e.g. function keys), which simply can never match
/// a configured binding.
fn teleop_key_binding_key(key: &KeyEvent) -> Option<String> {
    match key.code {
        KeyCode::Char(c) => Some(c.to_ascii_lowercase().to_string()),
        KeyCode::Up => Some("up".to_string()),
        KeyCode::Down => Some("down".to_string()),
        KeyCode::Left => Some("left".to_string()),
        KeyCode::Right => Some("right".to_string()),
        _ => None,
    }
}

pub struct TeleopUi {
    redis_url: String,
    log_buffer: LogBuffer,
    max_linear_vel: f32,
    max_angular_vel: f32,
    priority: u8,
    current_linear: f32,
    current_angular: f32,
    command_count: u64,
    last_command: Option<Instant>,
    scroll_offset: usize,
    should_quit: bool,
    dashboard_url: String,
    held_tracker: HeldKeyTracker,
    /// This instance's configured actuator joint names, resolved once at construction from the
    /// project's own `teleop` node config - empty means drivetrain mode (see `is_actuator_mode`).
    joint_names: Vec<String>,
    /// Parallel to `joint_names` - the locally-tracked target position (radians) for each
    /// joint, nudged by `JOINT_STEP_RAD` per keypress and republished unmodified, mirroring how
    /// `current_linear`/`current_angular` work for drivetrain mode.
    joint_positions: Vec<f32>,
    /// Index into `joint_names`/`joint_positions` that Up/Down currently nudge.
    selected_joint: usize,
    /// Project-configured key -> action-name remap (`teleop` node config's
    /// `custom.key_bindings`), resolved once at construction. Keys are lowercased single
    /// characters or one of `"up"`/`"down"`/`"left"`/`"right"` for the arrow keys - see
    /// `teleop_key_binding_key` for the canonical key string a pressed `KeyEvent` maps to. Empty (the
    /// default for any project that doesn't configure this) means every key handler falls back
    /// to today's hardcoded w/s/a/d/arrows behavior unchanged.
    key_bindings: HashMap<String, String>,
}

impl TeleopUi {
    /// Create a new teleop UI
    pub fn new(
        redis_url: String,
        log_buffer: LogBuffer,
        dashboard_url: String,
        max_linear_vel: f32,
        max_angular_vel: f32,
        joint_names: Vec<String>,
        key_bindings: HashMap<String, String>,
    ) -> Self {
        let joint_positions = vec![0.0; joint_names.len()];
        Self {
            redis_url,
            log_buffer,
            max_linear_vel,
            max_angular_vel,
            priority: 50,
            current_linear: 0.0,
            current_angular: 0.0,
            command_count: 0,
            last_command: None,
            scroll_offset: 0,
            should_quit: false,
            dashboard_url,
            held_tracker: HeldKeyTracker::new(HELD_WINDOW),
            joint_names,
            joint_positions,
            selected_joint: 0,
            key_bindings,
        }
    }

    /// Whether this instance is driving a named set of joints (position control) rather than a
    /// drivetrain (velocity control) - resolved once from whether any `joint_names` were found,
    /// not from a live `/teleop/status` round trip.
    fn is_actuator_mode(&self) -> bool {
        !self.joint_names.is_empty()
    }

    /// The configured action name (e.g. `"forward"`, `"tilt-"`) for `key`, if any - looks up
    /// `key`'s canonical binding-key string (`teleop_key_binding_key`) in `self.key_bindings`.
    /// `None` whenever no `key_bindings` are configured at all (the default), or `key` simply
    /// has no configured binding - either way the caller should fall back to its hardcoded
    /// physical-key behavior.
    fn bound_action(&self, key: &KeyEvent) -> Option<String> {
        teleop_key_binding_key(key).and_then(|k| self.key_bindings.get(&k).cloned())
    }

    /// Nudge the named joint's target position by `delta` radians, by looking it up in
    /// `joint_names` directly - unlike `nudge_selected_joint`, this doesn't go through
    /// `selected_joint`, since a configured key binding names its joint explicitly. A no-op if
    /// `name` isn't one of this instance's configured joints.
    fn nudge_joint_by_name(&mut self, name: &str, delta: f32) {
        if let Some(index) = self.joint_names.iter().position(|n| n == name) {
            if let Some(position) = self.joint_positions.get_mut(index) {
                *position += delta;
            }
        }
    }

    /// Run the teleop UI with interrupt support. Returns a `ScreenOutcome` telling the caller
    /// whether the screen just backed out or the whole session should quit.
    pub async fn run_with_interrupt(&mut self, running: Arc<AtomicBool>) -> Result<ScreenOutcome> {
        std::env::set_var("REDIS_URL", &self.redis_url);

        let ctx = Context::new("cli_teleop_tui").await?;

        enable_raw_mode()?;
        let mut stdout = stdout();
        execute!(stdout, EnterAlternateScreen)?;

        let keyboard_enhancement_enabled = supports_keyboard_enhancement().unwrap_or(false);
        if keyboard_enhancement_enabled {
            execute!(
                stdout,
                PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::REPORT_EVENT_TYPES)
            )?;
        }

        let backend = CrosstermBackend::new(stdout);
        let mut terminal = Terminal::new(backend)?;

        let outcome_result = self.event_loop(&mut terminal, &ctx, &running).await;

        self.send_stop(&ctx).await?;

        if keyboard_enhancement_enabled {
            execute!(terminal.backend_mut(), PopKeyboardEnhancementFlags)?;
        }
        disable_raw_mode()?;
        execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
        terminal.show_cursor()?;

        outcome_result
    }

    /// Main event loop
    ///
    /// Combines an async terminal event stream with a fixed-interval re-publish timer via
    /// `tokio::select!`, so held movement keys keep feeding the teleop node's timeout clock.
    async fn event_loop(
        &mut self,
        terminal: &mut Terminal<CrosstermBackend<std::io::Stdout>>,
        ctx: &Context,
        running: &Arc<AtomicBool>,
    ) -> Result<ScreenOutcome> {
        let mut events = EventStream::new();
        let mut republish_ticker = tokio::time::interval(REPUBLISH_INTERVAL);
        republish_ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);

        let mut outcome = ScreenOutcome::ReturnToParent;

        loop {
            if !running.load(Ordering::SeqCst) {
                outcome = ScreenOutcome::QuitAll;
                break;
            }
            if self.should_quit {
                break;
            }

            terminal.draw(|f| self.draw(f))?;

            tokio::select! {
                maybe_event = events.next() => {
                    match maybe_event {
                        Some(Ok(Event::Key(key))) => {
                            match self.handle_key(key, ctx).await? {
                                ScreenOutcome::Continue => {}
                                terminal_outcome => {
                                    outcome = terminal_outcome;
                                    self.should_quit = true;
                                }
                            }
                        }
                        Some(Ok(_)) => {}
                        Some(Err(err)) => return Err(err.into()),
                        None => {
                            self.should_quit = true;
                        }
                    }
                }

                _ = republish_ticker.tick() => {
                    self.republish_if_held(ctx).await?;
                }
            }
        }

        Ok(outcome)
    }

    /// Re-publish the last commanded `TeleopInput` if a movement key is still considered held
    /// (see `HeldKeyTracker`), keeping the teleop node's `command_timeout_ms` clock fed.
    async fn republish_if_held(&mut self, ctx: &Context) -> Result<()> {
        if self.held_tracker.is_held_at(Instant::now()) {
            if self.is_actuator_mode() {
                self.send_joint_positions(ctx).await?;
            } else {
                self.send_velocity(ctx).await?;
            }
        }

        Ok(())
    }

    /// Draw teleop controls panel
    fn draw_teleop_panel(&self, f: &mut Frame, area: ratatui::layout::Rect) {
        let text = if self.is_actuator_mode() {
            self.actuator_panel_lines()
        } else {
            self.drivetrain_panel_lines()
        };

        let paragraph = Paragraph::new(text).block(
            Block::default()
                .borders(Borders::ALL)
                .title(" Teleop Controls ")
                .border_style(Style::default().fg(Color::Cyan)),
        );

        f.render_widget(paragraph, area);
    }

    fn drivetrain_panel_lines(&self) -> Vec<Line<'static>> {
        let status_color = if self.current_linear == 0.0 && self.current_angular == 0.0 {
            Color::Gray
        } else {
            Color::Green
        };

        vec![
            Line::from(vec![Span::styled(
                "🎮 TELEOPERATION CONTROL",
                Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD),
            )]),
            Line::from(""),
            Line::from("Controls:"),
            Line::from("  ↑ / W       Forward"),
            Line::from("  ↓ / S       Backward"),
            Line::from("  ← / A       Turn Left"),
            Line::from("  → / D       Turn Right"),
            Line::from("  SPACE       Stop"),
            Line::from("  E           Emergency Stop"),
            Line::from(""),
            Line::from("Navigation:"),
            Line::from("  j/k         Scroll logs (or PgUp/PgDn)"),
            Line::from(""),
            Line::from(vec![Span::styled(
                "  Q / ESC / X Exit",
                Style::default().fg(Color::Yellow),
            )]),
            Line::from(""),
            Line::from("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"),
            Line::from(""),
            Line::from(vec![Span::styled(
                "Status:",
                Style::default().add_modifier(Modifier::BOLD),
            )]),
            Line::from(vec![
                Span::raw("  Linear:  "),
                Span::styled(format!("{:.2}", self.current_linear), Style::default().fg(status_color)),
                Span::raw(" m/s"),
            ]),
            Line::from(vec![
                Span::raw("  Angular: "),
                Span::styled(
                    format!("{:.2}", self.current_angular),
                    Style::default().fg(status_color),
                ),
                Span::raw(" rad/s"),
            ]),
            Line::from(""),
            Line::from(vec![
                Span::raw("  Commands: "),
                Span::styled(self.command_count.to_string(), Style::default().fg(Color::Cyan)),
            ]),
        ]
    }

    fn actuator_panel_lines(&self) -> Vec<Line<'static>> {
        let mut text = vec![
            Line::from(vec![Span::styled(
                "🎮 TELEOPERATION CONTROL (actuator)",
                Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD),
            )]),
            Line::from(""),
            Line::from("Controls:"),
            Line::from("  ↑ / W       Nudge selected joint +"),
            Line::from("  ↓ / S       Nudge selected joint -"),
            Line::from("  ← / A, → / D  Select joint"),
            Line::from("  E           Emergency Stop"),
            Line::from(""),
            Line::from("Navigation:"),
            Line::from("  j/k         Scroll logs (or PgUp/PgDn)"),
            Line::from(""),
            Line::from(vec![Span::styled(
                "  Q / ESC / X Exit",
                Style::default().fg(Color::Yellow),
            )]),
            Line::from(""),
            Line::from("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"),
            Line::from(""),
            Line::from(vec![Span::styled(
                "Joints:",
                Style::default().add_modifier(Modifier::BOLD),
            )]),
        ];

        for (i, name) in self.joint_names.iter().enumerate() {
            let position = self.joint_positions.get(i).copied().unwrap_or(0.0);
            let is_selected = i == self.selected_joint;
            let marker = if is_selected { "▶ " } else { "  " };
            let color = if is_selected { Color::Green } else { Color::White };
            text.push(Line::from(vec![
                Span::raw(marker),
                Span::styled(name.clone(), Style::default().fg(color)),
                Span::raw(": "),
                Span::styled(format!("{:.2} rad", position), Style::default().fg(color)),
            ]));
        }

        text.push(Line::from(""));
        text.push(Line::from(vec![
            Span::raw("  Commands: "),
            Span::styled(self.command_count.to_string(), Style::default().fg(Color::Cyan)),
        ]));

        text
    }

    /// Draw logs sidebar with mode changes, node status, and general logs
    fn draw_logs_panel(&self, f: &mut Frame, area: ratatui::layout::Rect) {
        let logs = self.log_buffer.get_all();

        let items: Vec<ListItem> = logs
            .iter()
            .skip(self.scroll_offset)
            .map(|log| {
                let (style, icon) = if log.contains("ERROR") {
                    (Style::default().fg(Color::Red).add_modifier(Modifier::BOLD), "❌")
                } else if log.contains("WARN") {
                    (Style::default().fg(Color::Yellow), "⚠️ ")
                } else if log.contains("MODE:") {
                    (Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD), "⚡")
                } else if log.contains("STARTED") || log.contains("✅") {
                    (Style::default().fg(Color::Green), "✅")
                } else if log.contains("STOPPED") || log.contains("🛑") {
                    (Style::default().fg(Color::Red), "🛑")
                } else if log.contains("INFO") {
                    (Style::default().fg(Color::Green), "ℹ️ ")
                } else if log.contains("DEBUG") {
                    (Style::default().fg(Color::Blue), "🔍")
                } else {
                    (Style::default().fg(Color::White), "  ")
                };

                let formatted_log = format!("{} {}", icon, log);
                ListItem::new(formatted_log).style(style)
            })
            .collect();

        let title = if logs.is_empty() {
            " System Logs (waiting...) ".to_string()
        } else {
            format!(" System Logs ({}) ", logs.len())
        };

        let list = List::new(items).block(
            Block::default()
                .borders(Borders::ALL)
                .title(title)
                .border_style(Style::default().fg(Color::Yellow)),
        );

        f.render_widget(list, area);
    }

    /// Handle keyboard input
    ///
    /// Termination-shaped keys (bare `q`/`Esc`/`x` -> `StopCurrent`, Ctrl+C/Ctrl+X -> `QuitAll`)
    /// are classified uniformly via the shared `classify_key` before this screen's own handling.
    async fn handle_key(&mut self, key: KeyEvent, ctx: &Context) -> Result<ScreenOutcome> {
        if let Some(intent) = classify_key(&key) {
            return Ok(match intent {
                TerminationIntent::StopCurrent => ScreenOutcome::ReturnToParent,
                TerminationIntent::QuitAll => ScreenOutcome::QuitAll,
            });
        }

        if self.is_actuator_mode() {
            return self.handle_actuator_key(key, ctx).await;
        }

        if let Some(action) = self.bound_action(&key) {
            return self.handle_drivetrain_action(&action, key, ctx).await;
        }

        match key.code {
            KeyCode::PageUp | KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.scroll_offset = self.scroll_offset.saturating_sub(10);
            }
            KeyCode::PageDown | KeyCode::Char('d') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                let logs = self.log_buffer.get_all();
                self.scroll_offset = (self.scroll_offset + 10).min(logs.len().saturating_sub(1));
            }

            KeyCode::Char('k') if key.modifiers.is_empty() => {
                self.scroll_offset = self.scroll_offset.saturating_sub(1);
            }
            KeyCode::Char('j') if key.modifiers.is_empty() => {
                let logs = self.log_buffer.get_all();
                self.scroll_offset = (self.scroll_offset + 1).min(logs.len().saturating_sub(1));
            }

            KeyCode::Char('w') | KeyCode::Up if key.modifiers.is_empty() || key.code == KeyCode::Up => {
                match classify_movement_key(key.kind) {
                    MovementKeyAction::Activate => {
                        self.current_linear = self.max_linear_vel;
                        self.current_angular = 0.0;
                        self.held_tracker.mark_pressed_at(Instant::now());
                    }
                    MovementKeyAction::Release => {
                        self.current_linear = 0.0;
                        self.current_angular = 0.0;
                        self.held_tracker.clear();
                    }
                }
                self.send_velocity(ctx).await?;
            }
            KeyCode::Char('s') | KeyCode::Down if key.modifiers.is_empty() || key.code == KeyCode::Down => {
                match classify_movement_key(key.kind) {
                    MovementKeyAction::Activate => {
                        self.current_linear = -self.max_linear_vel;
                        self.current_angular = 0.0;
                        self.held_tracker.mark_pressed_at(Instant::now());
                    }
                    MovementKeyAction::Release => {
                        self.current_linear = 0.0;
                        self.current_angular = 0.0;
                        self.held_tracker.clear();
                    }
                }
                self.send_velocity(ctx).await?;
            }
            KeyCode::Char('a') | KeyCode::Left if key.modifiers.is_empty() || key.code == KeyCode::Left => {
                match classify_movement_key(key.kind) {
                    MovementKeyAction::Activate => {
                        self.current_linear = 0.0;
                        self.current_angular = self.max_angular_vel;
                        self.held_tracker.mark_pressed_at(Instant::now());
                    }
                    MovementKeyAction::Release => {
                        self.current_linear = 0.0;
                        self.current_angular = 0.0;
                        self.held_tracker.clear();
                    }
                }
                self.send_velocity(ctx).await?;
            }
            KeyCode::Char('d') | KeyCode::Right if key.modifiers.is_empty() || key.code == KeyCode::Right => {
                match classify_movement_key(key.kind) {
                    MovementKeyAction::Activate => {
                        self.current_linear = 0.0;
                        self.current_angular = -self.max_angular_vel;
                        self.held_tracker.mark_pressed_at(Instant::now());
                    }
                    MovementKeyAction::Release => {
                        self.current_linear = 0.0;
                        self.current_angular = 0.0;
                        self.held_tracker.clear();
                    }
                }
                self.send_velocity(ctx).await?;
            }

            KeyCode::Char(' ') if key.modifiers.is_empty() => {
                self.current_linear = 0.0;
                self.current_angular = 0.0;
                self.held_tracker.clear();
                self.send_velocity(ctx).await?;
            }

            KeyCode::Char('e') if key.modifiers.is_empty() => {
                self.held_tracker.clear();
                self.send_emergency_stop(ctx).await?;
            }

            _ => {}
        }

        Ok(ScreenOutcome::Continue)
    }

    /// Drivetrain-mode dispatch by configured action name (`self.key_bindings`'s value for the
    /// pressed key), rather than by the physical key that was pressed - the configured-binding
    /// counterpart to `handle_key`'s hardcoded w/s/a/d/arrows match arms, which this mirrors
    /// exactly for each action.
    async fn handle_drivetrain_action(&mut self, action: &str, key: KeyEvent, ctx: &Context) -> Result<ScreenOutcome> {
        match action {
            "forward" => {
                match classify_movement_key(key.kind) {
                    MovementKeyAction::Activate => {
                        self.current_linear = self.max_linear_vel;
                        self.current_angular = 0.0;
                        self.held_tracker.mark_pressed_at(Instant::now());
                    }
                    MovementKeyAction::Release => {
                        self.current_linear = 0.0;
                        self.current_angular = 0.0;
                        self.held_tracker.clear();
                    }
                }
                self.send_velocity(ctx).await?;
            }
            "backward" => {
                match classify_movement_key(key.kind) {
                    MovementKeyAction::Activate => {
                        self.current_linear = -self.max_linear_vel;
                        self.current_angular = 0.0;
                        self.held_tracker.mark_pressed_at(Instant::now());
                    }
                    MovementKeyAction::Release => {
                        self.current_linear = 0.0;
                        self.current_angular = 0.0;
                        self.held_tracker.clear();
                    }
                }
                self.send_velocity(ctx).await?;
            }
            "left" => {
                match classify_movement_key(key.kind) {
                    MovementKeyAction::Activate => {
                        self.current_linear = 0.0;
                        self.current_angular = self.max_angular_vel;
                        self.held_tracker.mark_pressed_at(Instant::now());
                    }
                    MovementKeyAction::Release => {
                        self.current_linear = 0.0;
                        self.current_angular = 0.0;
                        self.held_tracker.clear();
                    }
                }
                self.send_velocity(ctx).await?;
            }
            "right" => {
                match classify_movement_key(key.kind) {
                    MovementKeyAction::Activate => {
                        self.current_linear = 0.0;
                        self.current_angular = -self.max_angular_vel;
                        self.held_tracker.mark_pressed_at(Instant::now());
                    }
                    MovementKeyAction::Release => {
                        self.current_linear = 0.0;
                        self.current_angular = 0.0;
                        self.held_tracker.clear();
                    }
                }
                self.send_velocity(ctx).await?;
            }
            "stop" => {
                self.current_linear = 0.0;
                self.current_angular = 0.0;
                self.held_tracker.clear();
                self.send_velocity(ctx).await?;
            }
            "estop" => {
                self.held_tracker.clear();
                self.send_emergency_stop(ctx).await?;
            }
            _ => {}
        }

        Ok(ScreenOutcome::Continue)
    }

    /// Actuator-mode key handling - mirrors `handle_key`'s scroll/exit handling, but Up/Down
    /// nudge the selected joint's target position and Left/Right select which joint is nudged.
    async fn handle_actuator_key(&mut self, key: KeyEvent, ctx: &Context) -> Result<ScreenOutcome> {
        if let Some(action) = self.bound_action(&key) {
            return self.handle_actuator_action(&action, key, ctx).await;
        }

        match key.code {
            KeyCode::PageUp | KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.scroll_offset = self.scroll_offset.saturating_sub(10);
            }
            KeyCode::PageDown | KeyCode::Char('d') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                let logs = self.log_buffer.get_all();
                self.scroll_offset = (self.scroll_offset + 10).min(logs.len().saturating_sub(1));
            }
            KeyCode::Char('k') if key.modifiers.is_empty() => {
                self.scroll_offset = self.scroll_offset.saturating_sub(1);
            }
            KeyCode::Char('j') if key.modifiers.is_empty() => {
                let logs = self.log_buffer.get_all();
                self.scroll_offset = (self.scroll_offset + 1).min(logs.len().saturating_sub(1));
            }

            KeyCode::Char('w') | KeyCode::Up if key.modifiers.is_empty() || key.code == KeyCode::Up => {
                if classify_movement_key(key.kind) == MovementKeyAction::Activate {
                    self.nudge_selected_joint(JOINT_STEP_RAD);
                    self.held_tracker.mark_pressed_at(Instant::now());
                    self.send_joint_positions(ctx).await?;
                } else {
                    self.held_tracker.clear();
                }
            }
            KeyCode::Char('s') | KeyCode::Down if key.modifiers.is_empty() || key.code == KeyCode::Down => {
                if classify_movement_key(key.kind) == MovementKeyAction::Activate {
                    self.nudge_selected_joint(-JOINT_STEP_RAD);
                    self.held_tracker.mark_pressed_at(Instant::now());
                    self.send_joint_positions(ctx).await?;
                } else {
                    self.held_tracker.clear();
                }
            }
            KeyCode::Char('a') | KeyCode::Left if key.modifiers.is_empty() || key.code == KeyCode::Left => {
                if classify_movement_key(key.kind) == MovementKeyAction::Activate && !self.joint_names.is_empty() {
                    self.selected_joint = (self.selected_joint + self.joint_names.len() - 1) % self.joint_names.len();
                }
            }
            KeyCode::Char('d') | KeyCode::Right if key.modifiers.is_empty() || key.code == KeyCode::Right => {
                if classify_movement_key(key.kind) == MovementKeyAction::Activate && !self.joint_names.is_empty() {
                    self.selected_joint = (self.selected_joint + 1) % self.joint_names.len();
                }
            }

            KeyCode::Char(' ') if key.modifiers.is_empty() => {
                self.held_tracker.clear();
            }

            KeyCode::Char('e') if key.modifiers.is_empty() => {
                self.held_tracker.clear();
                self.send_emergency_stop(ctx).await?;
            }

            _ => {}
        }

        Ok(ScreenOutcome::Continue)
    }

    /// Actuator-mode dispatch by configured action name - the configured-binding counterpart
    /// to `handle_actuator_key`'s hardcoded Up/Down/Left/Right match arms. `"<joint_name>+"`/
    /// `"<joint_name>-"` nudge that specific named joint directly (via `nudge_joint_by_name`,
    /// not whichever joint happens to be `selected_joint`) by +/-`JOINT_STEP_RAD`.
    async fn handle_actuator_action(&mut self, action: &str, key: KeyEvent, ctx: &Context) -> Result<ScreenOutcome> {
        match action {
            "select-next" => {
                if classify_movement_key(key.kind) == MovementKeyAction::Activate && !self.joint_names.is_empty() {
                    self.selected_joint = (self.selected_joint + 1) % self.joint_names.len();
                }
            }
            "select-previous" => {
                if classify_movement_key(key.kind) == MovementKeyAction::Activate && !self.joint_names.is_empty() {
                    self.selected_joint = (self.selected_joint + self.joint_names.len() - 1) % self.joint_names.len();
                }
            }
            "estop" => {
                self.held_tracker.clear();
                self.send_emergency_stop(ctx).await?;
            }
            _ if action.ends_with('+') => {
                let joint_name = &action[..action.len() - 1];
                if classify_movement_key(key.kind) == MovementKeyAction::Activate {
                    self.nudge_joint_by_name(joint_name, JOINT_STEP_RAD);
                    self.held_tracker.mark_pressed_at(Instant::now());
                    self.send_joint_positions(ctx).await?;
                } else {
                    self.held_tracker.clear();
                }
            }
            _ if action.ends_with('-') => {
                let joint_name = &action[..action.len() - 1];
                if classify_movement_key(key.kind) == MovementKeyAction::Activate {
                    self.nudge_joint_by_name(joint_name, -JOINT_STEP_RAD);
                    self.held_tracker.mark_pressed_at(Instant::now());
                    self.send_joint_positions(ctx).await?;
                } else {
                    self.held_tracker.clear();
                }
            }
            _ => {}
        }

        Ok(ScreenOutcome::Continue)
    }

    /// Clamp-free nudge of `self.joint_positions[self.selected_joint]` by `delta` radians - the
    /// teleop node itself clamps to `mecha10_core::config::joint_limits` when publishing, so
    /// this UI doesn't need to know per-joint limits to stay safe.
    fn nudge_selected_joint(&mut self, delta: f32) {
        if let Some(position) = self.joint_positions.get_mut(self.selected_joint) {
            *position += delta;
        }
    }

    /// Publish the current `joint_positions` for all `joint_names` as an actuator `TeleopInput`.
    async fn send_joint_positions(&mut self, ctx: &Context) -> Result<()> {
        let input = TeleopInput::new_actuator(
            "cli_tui",
            self.joint_names.clone(),
            self.joint_positions.clone(),
            now_micros(),
        )
        .with_priority(self.priority);

        ctx.publish_to(TELEOP_CMD, &input).await?;
        self.last_command = Some(Instant::now());
        self.command_count += 1;

        Ok(())
    }

    /// Send velocity command
    async fn send_velocity(&mut self, ctx: &Context) -> Result<()> {
        let input = TeleopInput::new("cli_tui", self.current_linear, self.current_angular, now_micros())
            .with_priority(self.priority);

        ctx.publish_to(TELEOP_CMD, &input).await?;
        self.last_command = Some(Instant::now());
        self.command_count += 1;

        Ok(())
    }

    /// Send stop command - a no-op in actuator mode (no velocity to zero; holding the last
    /// commanded joint position on exit is the correct behavior, same as a timeout safety-stop).
    async fn send_stop(&mut self, ctx: &Context) -> Result<()> {
        if self.is_actuator_mode() {
            return Ok(());
        }

        let input = TeleopInput::new("cli_tui", 0.0, 0.0, now_micros()).with_priority(self.priority);

        ctx.publish_to(TELEOP_CMD, &input).await?;
        Ok(())
    }

    /// Send emergency stop
    async fn send_emergency_stop(&mut self, ctx: &Context) -> Result<()> {
        let input = TeleopInput::emergency_stop("cli_tui", now_micros());

        ctx.publish_to(TELEOP_CMD, &input).await?;
        self.current_linear = 0.0;
        self.current_angular = 0.0;
        self.last_command = Some(Instant::now());
        self.command_count += 1;

        Ok(())
    }
}

impl SidebarTui for TeleopUi {
    fn draw_main(&mut self, f: &mut Frame, area: ratatui::layout::Rect) {
        self.draw_teleop_panel(f, area);
    }

    fn draw_sidebar(&self, f: &mut Frame, area: ratatui::layout::Rect) {
        self.draw_logs_panel(f, area);
    }

    fn draw_footer(&self, f: &mut Frame, area: ratatui::layout::Rect) {
        draw_dashboard_footer(f, area, &self.dashboard_url, "Q/ESC");
    }
}

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

    /// Sanity check that REPUBLISH_INTERVAL is fast enough relative to HELD_WINDOW and a
    /// typical `command_timeout_ms` to keep the node's timeout clock fed while a key is held.
    #[test]
    fn constants_are_tuned_safely_relative_to_each_other() {
        assert!(
            REPUBLISH_INTERVAL * 2 < HELD_WINDOW,
            "REPUBLISH_INTERVAL should fire multiple times within a single HELD_WINDOW"
        );
        assert!(
            REPUBLISH_INTERVAL < Duration::from_millis(100),
            "REPUBLISH_INTERVAL should be safely faster than a typical 200ms command_timeout_ms"
        );
    }

    #[test]
    fn fresh_tracker_is_not_held() {
        let tracker = HeldKeyTracker::new(HELD_WINDOW);
        assert!(!tracker.is_held_at(Instant::now()));
    }

    #[test]
    fn single_press_stays_held_until_window_expires_with_no_further_events() {
        let mut tracker = HeldKeyTracker::new(HELD_WINDOW);
        let t0 = Instant::now();
        tracker.mark_pressed_at(t0);

        assert!(tracker.is_held_at(t0), "should be held immediately after press");
        assert!(
            tracker.is_held_at(t0 + Duration::from_millis(50)),
            "should still be held well within the window"
        );
        assert!(
            tracker.is_held_at(t0 + HELD_WINDOW - Duration::from_millis(1)),
            "should still be held just under the window boundary"
        );
        assert!(
            !tracker.is_held_at(t0 + HELD_WINDOW),
            "should no longer be held once the window has fully elapsed"
        );
        assert!(
            !tracker.is_held_at(t0 + HELD_WINDOW + Duration::from_millis(500)),
            "should stay not-held indefinitely after the window elapses (doesn't spin forever)"
        );
    }

    #[test]
    fn repeated_presses_keep_refreshing_the_held_window() {
        let mut tracker = HeldKeyTracker::new(HELD_WINDOW);
        let t0 = Instant::now();

        let mut t = t0;
        for _ in 0..10 {
            tracker.mark_pressed_at(t);
            assert!(tracker.is_held_at(t));
            t += Duration::from_millis(100);
        }
        assert!(tracker.is_held_at(t - Duration::from_millis(1)));
    }

    #[test]
    fn clear_stops_being_held_immediately() {
        let mut tracker = HeldKeyTracker::new(HELD_WINDOW);
        let t0 = Instant::now();
        tracker.mark_pressed_at(t0);
        assert!(tracker.is_held_at(t0));

        tracker.clear();

        assert!(
            !tracker.is_held_at(t0),
            "clearing should stop 'held' immediately, even though the window hasn't elapsed"
        );
        assert!(!tracker.is_held_at(t0 + Duration::from_millis(1)));
    }

    #[test]
    fn press_activates_a_movement_key() {
        assert_eq!(classify_movement_key(KeyEventKind::Press), MovementKeyAction::Activate);
    }

    #[test]
    fn repeat_activates_a_movement_key_exactly_like_press() {
        assert_eq!(classify_movement_key(KeyEventKind::Repeat), MovementKeyAction::Activate);
    }

    #[test]
    fn release_stops_a_movement_key_immediately() {
        assert_eq!(classify_movement_key(KeyEventKind::Release), MovementKeyAction::Release);
    }

    /// Simulates handling a movement key's `KeyEventKind` against the same state fields
    /// `handle_key` mutates, without needing a live Redis `Context`.
    fn apply_movement_key(
        action: MovementKeyAction,
        activate_linear: f32,
        activate_angular: f32,
        current_linear: &mut f32,
        current_angular: &mut f32,
        held_tracker: &mut HeldKeyTracker,
        now: Instant,
    ) {
        match action {
            MovementKeyAction::Activate => {
                *current_linear = activate_linear;
                *current_angular = activate_angular;
                held_tracker.mark_pressed_at(now);
            }
            MovementKeyAction::Release => {
                *current_linear = 0.0;
                *current_angular = 0.0;
                held_tracker.clear();
            }
        }
    }

    #[test]
    fn release_event_zeroes_velocity_and_clears_held_tracker_regardless_of_window_remaining() {
        let mut current_linear = 0.7_f32;
        let mut current_angular = 0.0_f32;
        let mut held_tracker = HeldKeyTracker::new(HELD_WINDOW);
        let t0 = Instant::now();
        held_tracker.mark_pressed_at(t0);
        assert!(held_tracker.is_held_at(t0), "sanity: key is held right after press");

        let t_release = t0 + Duration::from_millis(10);
        apply_movement_key(
            classify_movement_key(KeyEventKind::Release),
            0.7,
            0.0,
            &mut current_linear,
            &mut current_angular,
            &mut held_tracker,
            t_release,
        );

        assert_eq!(current_linear, 0.0, "Release must zero linear velocity immediately");
        assert_eq!(current_angular, 0.0, "Release must zero angular velocity immediately");
        assert!(
            !held_tracker.is_held_at(t_release),
            "Release must clear the held tracker immediately, not wait out HELD_WINDOW"
        );
    }

    #[test]
    fn press_and_repeat_events_activate_velocity_and_refresh_held_window_unchanged() {
        let mut current_linear = 0.0_f32;
        let mut current_angular = 0.0_f32;
        let mut held_tracker = HeldKeyTracker::new(HELD_WINDOW);
        let t0 = Instant::now();

        for kind in [KeyEventKind::Press, KeyEventKind::Repeat] {
            apply_movement_key(
                classify_movement_key(kind),
                0.5,
                0.0,
                &mut current_linear,
                &mut current_angular,
                &mut held_tracker,
                t0,
            );
            assert_eq!(current_linear, 0.5, "{kind:?} must activate the key's velocity");
            assert_eq!(current_angular, 0.0);
            assert!(held_tracker.is_held_at(t0), "{kind:?} must mark the key as held");
        }
    }

    #[test]
    fn stop_current_intent_maps_to_return_to_parent() {
        let intent = classify_key(&KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE))
            .expect("bare x must classify as a termination intent");
        let outcome = match intent {
            TerminationIntent::StopCurrent => ScreenOutcome::ReturnToParent,
            TerminationIntent::QuitAll => ScreenOutcome::QuitAll,
        };
        assert_eq!(outcome, ScreenOutcome::ReturnToParent);
    }

    #[test]
    fn quit_all_intent_maps_to_quit_all() {
        let intent = classify_key(&KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL))
            .expect("Ctrl+C must classify as a termination intent");
        let outcome = match intent {
            TerminationIntent::StopCurrent => ScreenOutcome::ReturnToParent,
            TerminationIntent::QuitAll => ScreenOutcome::QuitAll,
        };
        assert_eq!(outcome, ScreenOutcome::QuitAll);
    }

    #[test]
    fn space_is_never_classified_as_a_termination_key() {
        let key = KeyEvent::new(KeyCode::Char(' '), KeyModifiers::NONE);
        assert_eq!(classify_key(&key), None);
    }

    fn test_teleop_ui(joint_names: Vec<String>, key_bindings: HashMap<String, String>) -> TeleopUi {
        TeleopUi::new(
            "redis://localhost".to_string(),
            LogBuffer::new(10),
            "http://localhost".to_string(),
            1.0,
            1.0,
            joint_names,
            key_bindings,
        )
    }

    #[test]
    fn char_keys_bind_to_their_lowercased_char() {
        let key = KeyEvent::new(KeyCode::Char('J'), KeyModifiers::NONE);
        assert_eq!(teleop_key_binding_key(&key), Some("j".to_string()));
    }

    #[test]
    fn arrow_keys_bind_to_their_direction_name() {
        assert_eq!(
            teleop_key_binding_key(&KeyEvent::new(KeyCode::Up, KeyModifiers::NONE)),
            Some("up".to_string())
        );
        assert_eq!(
            teleop_key_binding_key(&KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)),
            Some("down".to_string())
        );
        assert_eq!(
            teleop_key_binding_key(&KeyEvent::new(KeyCode::Left, KeyModifiers::NONE)),
            Some("left".to_string())
        );
        assert_eq!(
            teleop_key_binding_key(&KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)),
            Some("right".to_string())
        );
    }

    #[test]
    fn empty_key_bindings_resolve_no_bound_action_preserving_default_wsad_behavior() {
        let ui = test_teleop_ui(vec!["pan".to_string(), "tilt".to_string()], HashMap::new());

        for key in [
            KeyEvent::new(KeyCode::Char('w'), KeyModifiers::NONE),
            KeyEvent::new(KeyCode::Char('s'), KeyModifiers::NONE),
            KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE),
            KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE),
            KeyEvent::new(KeyCode::Up, KeyModifiers::NONE),
        ] {
            assert_eq!(
                ui.bound_action(&key),
                None,
                "with no key_bindings configured, {key:?} must fall back to hardcoded behavior"
            );
        }
    }

    #[test]
    fn configured_binding_resolves_to_its_action_name() {
        let mut key_bindings = HashMap::new();
        key_bindings.insert("j".to_string(), "tilt-".to_string());

        let ui = test_teleop_ui(vec!["pan".to_string(), "tilt".to_string()], key_bindings);

        let key = KeyEvent::new(KeyCode::Char('j'), KeyModifiers::NONE);
        assert_eq!(ui.bound_action(&key), Some("tilt-".to_string()));
    }

    #[test]
    fn configured_binding_nudges_the_named_joint_directly_not_the_selected_one() {
        let mut key_bindings = HashMap::new();
        key_bindings.insert("j".to_string(), "tilt-".to_string());

        let mut ui = test_teleop_ui(vec!["pan".to_string(), "tilt".to_string()], key_bindings);
        // `selected_joint` defaults to index 0 ("pan") - the binding names "tilt" directly, so
        // the nudge must land on "tilt" (index 1) regardless of what's currently selected.
        assert_eq!(ui.selected_joint, 0);

        let key = KeyEvent::new(KeyCode::Char('j'), KeyModifiers::NONE);
        let action = ui.bound_action(&key).expect("binding must resolve");
        assert_eq!(action, "tilt-");

        let joint_name = action.strip_suffix('-').expect("action must be a '-' nudge");
        ui.nudge_joint_by_name(joint_name, -JOINT_STEP_RAD);

        assert_eq!(ui.joint_positions[0], 0.0, "unselected/unbound 'pan' must be untouched");
        assert_eq!(
            ui.joint_positions[1], -JOINT_STEP_RAD,
            "'tilt' must be nudged by the configured binding"
        );
    }

    #[test]
    fn nudge_joint_by_name_is_a_no_op_for_an_unknown_joint() {
        let mut ui = test_teleop_ui(vec!["pan".to_string()], HashMap::new());
        ui.nudge_joint_by_name("nonexistent", JOINT_STEP_RAD);
        assert_eq!(ui.joint_positions, vec![0.0]);
    }
}