mecha10-cli 0.7.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
//! Teleop UI with ratatui TUI and logs sidebar
//!
//! Provides a 3-panel interface:
//! - Main area: Teleop controls and status
//! - Sidebar: Real-time system logs
//! - Footer: Quick links to dashboard and docs

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::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. Pure,
/// dependency-free function (no `Context`/`TeleopUi` access) so it can be
/// unit tested directly, unlike `handle_key` which requires a live Redis
/// `Context`.
fn classify_movement_key(kind: KeyEventKind) -> MovementKeyAction {
    match kind {
        KeyEventKind::Release => MovementKeyAction::Release,
        KeyEventKind::Press | KeyEventKind::Repeat => MovementKeyAction::Activate,
    }
}

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,
}

impl TeleopUi {
    /// Create a new teleop UI
    ///
    /// # Arguments
    ///
    /// * `redis_url` - Redis connection URL
    /// * `log_buffer` - Shared log buffer for collecting logs
    /// * `dashboard_url` - Dashboard URL to display in footer (derived from mecha10.json)
    /// * `max_linear_vel` - Per-keypress linear velocity target, in m/s. Callers read this from
    ///   the project's single `actuator.locomotion` config (`ProjectConfig::actuator`
    ///   directly, not `mecha10_core::config::locomotion_limits()` - that reads env vars
    ///   `inject_locomotion_limits_env` only ever sets on *spawned child* node processes, never
    ///   on this CLI process's own environment, so a call to it from in-process code like this
    ///   TUI always silently falls back to the compiled defaults regardless of `mecha10.json`)
    ///   so the UI's commanded velocity matches what the teleop node itself enforces.
    /// * `max_angular_vel` - Per-keypress angular velocity target, in rad/s. Same source as
    ///   `max_linear_vel`.
    /// * `joint_names` - This project's `teleop` node's configured actuator joint names (empty
    ///   for drivetrain mode, the default) - see `resolve_teleop_joint_names` in
    ///   `ops/teleop.rs::enter_teleop_mode`, this screen's only caller.
    pub fn new(
        redis_url: String,
        log_buffer: LogBuffer,
        dashboard_url: String,
        max_linear_vel: f32,
        max_angular_vel: f32,
        joint_names: Vec<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,
        }
    }

    /// 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()
    }

    /// Run the teleop UI with interrupt support. Returns a `ScreenOutcome` telling the caller
    /// what happened - whether the screen just backed out (`ReturnToParent`, e.g. `q`/Esc/bare
    /// `x`) or the whole `mecha10 dev` session should quit (`QuitAll`, e.g. Ctrl+C). See
    /// `crate::dev::termination` module docs for why this screen reports intent rather than
    /// mutating the outer loop's shutdown flag itself.
    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!`, rather than only ever polling
    /// for terminal input. This is what lets the UI proactively keep the
    /// teleop node's `command_timeout_ms` clock fed while a movement key is
    /// held, independent of whether/when the terminal forwards auto-repeat
    /// KeyDown events - see `HeldKeyTracker` and `REPUBLISH_INTERVAL`.
    ///
    /// Returns the `ScreenOutcome` that ended the loop: an external quit request (`running`
    /// flipping to `false`, e.g. Ctrl+C caught elsewhere in the process) always reports
    /// `QuitAll`, since the whole session is tearing down regardless of what this screen was
    /// doing. A `handle_key`-reported outcome (`ReturnToParent`/`QuitAll`) is used verbatim. The
    /// terminal event stream closing (e.g. stdin EOF) reports `ReturnToParent`, matching this
    /// screen's pre-existing behavior of just backing out rather than tearing down the session.
    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`). Called on every
    /// `REPUBLISH_INTERVAL` tick regardless of terminal events, so the
    /// teleop node's `command_timeout_ms` clock keeps getting fed for as
    /// long as the key is genuinely held - even on terminals that never
    /// forward a second terminal event at all.
    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 any of this screen's own
    /// key handling below - see `crate::dev::termination` module docs. This is the fix for the
    /// reported bug: `x` inside teleop used to mean "zero velocity, stay put" (a leftover
    /// combined `Space`/`x` Stop match arm), a different meaning than the same physical key at
    /// the outer dev-mode menu ("stop the simulation"). Now both mean the same
    /// `TerminationIntent`, and the caller (`ops/teleop.rs::enter_teleop_mode`) decides what
    /// "stop" actually does for the specific entry point this screen was reached through. `Space`
    /// deliberately does NOT go through `classify_key` - it stays a distinct, non-terminating
    /// "zero velocity, stay in teleop" safety control, not a termination concept.
    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;
        }

        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)
    }

    /// Actuator-mode key handling - mirrors `handle_key`'s scroll/exit handling, but Up/Down
    /// nudge the selected joint's target position (`JOINT_STEP_RAD`) instead of setting a
    /// drivetrain velocity, and Left/Right select which joint is being nudged rather than
    /// turning. Split out from `handle_key` (which dispatches here first) purely to keep that
    /// function from growing two full sets of movement-key arms.
    async fn handle_actuator_key(&mut self, key: KeyEvent, ctx: &Context) -> Result<ScreenOutcome> {
        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)
    }

    /// 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 on the tuned constants: the re-publish cadence must be
    /// comfortably faster than the held window (so several re-publishes fit
    /// inside a single held window) and the held window itself must be
    /// larger than a typical `command_timeout_ms` (200ms default, commonly
    /// 100-500ms), so that as long as a key is "held" the node's timeout
    /// clock is kept fed well before it can expire.
    #[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` end-to-end against
    /// the same state fields `handle_key` mutates (`current_linear`,
    /// `current_angular`, `held_tracker`), without needing a live Redis
    /// `Context` - mirrors the `Activate`/`Release` match arms in
    /// `handle_key`'s movement branches.
    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);
    }
}