mecha10-cli 0.6.3

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
//! 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::{main_and_sidebar_layout, render_footer_hints, standard_tui_layout};

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

/// How long a movement key is considered "held" after its most recent
/// KeyDown/Press event, with no further terminal events required. This is a
/// **fallback** liveness window for terminals that do not support (or where
/// we failed to enable) the Kitty keyboard enhancement protocol's
/// `REPORT_EVENT_TYPES` flag - see `supports_keyboard_enhancement` in
/// `run_with_interrupt`. On terminals where that protocol is active, real
/// `KeyEventKind::Release` events stop a movement key immediately (see
/// `classify_movement_key`) and this window is never relied upon. On
/// terminals without it, crossterm only ever reports `KeyEventKind::Press`,
/// so release can only be *inferred* by this window silently expiring:
/// each fresh KeyDown simply refreshes it, and it naturally expires if no
/// further KeyDown arrives.
///
/// This is intentionally larger than any reasonable
/// `TeleopConfig::command_timeout_ms` (default 200ms, commonly 100-500ms) so
/// that as long as this window says "held", the CLI keeps re-publishing
/// fast enough to keep the node's timeout clock fed - see
/// `REPUBLISH_INTERVAL` below.
const HELD_WINDOW: Duration = Duration::from_millis(300);

/// How often to proactively re-publish the last commanded `TeleopInput`
/// while a movement key is considered held (see `HELD_WINDOW`). This must be
/// safely faster than any reasonable `command_timeout_ms` so the teleop
/// node's safety-stop timeout never fires while a key is genuinely held,
/// regardless of whether the terminal forwards auto-repeat KeyDown events at
/// all, and regardless of the terminal/OS's initial auto-repeat delay
/// (commonly 250-660ms, often longer than `command_timeout_ms` itself).
const REPUBLISH_INTERVAL: Duration = Duration::from_millis(75);

/// Tracks whether a movement key is currently considered "held", decoupled
/// entirely from terminal auto-repeat timing/KeyUp events. A key is "held"
/// for as long as `now` is within `window` of the most recent `mark_pressed`
/// call; each fresh KeyDown pushes the deadline back out. This is pure,
/// clock-injectable state so it can be unit tested without waiting on a real
/// terminal or real wall-clock sleeps.
#[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;
    }
}

/// What a movement key's (W/A/S/D or arrow) terminal event should do. Only
/// consulted for the four movement keys - all other keys (stop/e-stop/
/// scroll/quit) ignore `KeyEventKind` entirely and keep acting only on
/// their existing match arms, unaffected by this enum.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MovementKeyAction {
    /// Apply the key's velocity. Covers both a fresh `Press` and a
    /// terminal/OS auto-repeat `Repeat` event - identical to the
    /// pre-existing behavior. On terminals where the Kitty keyboard
    /// enhancement protocol isn't supported/enabled, crossterm reports
    /// every movement key event as `Press`, so this is the only variant
    /// those terminals will ever produce, and the `HELD_WINDOW` fallback
    /// keeps working exactly as before.
    Activate,
    /// A real key-release event. Only ever reported when the Kitty
    /// keyboard enhancement protocol's `REPORT_EVENT_TYPES` flag was
    /// successfully pushed (see `run_with_interrupt`) - zero velocity
    /// immediately instead of waiting for `HELD_WINDOW` to silently
    /// expire, restoring the instant stop-on-release behavior.
    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,
    }
}

/// Teleop UI with TUI interface
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,
    /// Explicit local "is a movement key currently held" state, decoupled
    /// from terminal auto-repeat timing - see `HeldKeyTracker`.
    held_tracker: HeldKeyTracker,
}

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. Should be resolved
    ///   from the project's teleop node `TeleopConfig` (`configs/nodes/@mecha10/teleop/config.json`)
    ///   so the UI's commanded velocity matches what the teleop node itself is configured to
    ///   accept - falling back to the teleop node's own default (0.5) when unset.
    /// * `max_angular_vel` - Per-keypress angular velocity target, in rad/s. Same resolution
    ///   rules as `max_linear_vel`, falling back to the teleop node's own default (1.0).
    pub fn new(
        redis_url: String,
        log_buffer: LogBuffer,
        dashboard_url: String,
        max_linear_vel: f32,
        max_angular_vel: f32,
    ) -> Self {
        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),
        }
    }

    /// 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> {
        // Set REDIS_URL env var for Context creation
        std::env::set_var("REDIS_URL", &self.redis_url);

        // Create Redis context
        let ctx = Context::new("cli_teleop_tui").await?;

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

        // Enable the Kitty keyboard enhancement protocol's REPORT_EVENT_TYPES
        // flag where the terminal supports it, so we get real Press/Repeat/
        // Release `KeyEventKind`s instead of only ever seeing Press - lets
        // movement keys stop instantly on release (see
        // `classify_movement_key`) instead of relying solely on the
        // `HELD_WINDOW` heuristic. Terminals without support leave
        // `supports_keyboard_enhancement` false, so this is a no-op there and
        // the `HELD_WINDOW` fallback keeps working exactly as before (see
        // LAB-1954).
        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)?;

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

        // Send stop command on exit
        self.send_stop(&ctx).await?;

        // Cleanup terminal - this is the single cleanup point regardless of
        // whether `event_loop` returned Ok or Err (see `result` above), so
        // the keyboard enhancement flags are always popped if they were
        // pushed, never leaving the terminal stuck in enhanced mode.
        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 {
            // An external quit request always wins and means the whole session is tearing
            // down, not just this screen backing out.
            if !running.load(Ordering::SeqCst) {
                outcome = ScreenOutcome::QuitAll;
                break;
            }
            if self.should_quit {
                break;
            }

            // Draw UI
            terminal.draw(|f| self.draw(f))?;

            tokio::select! {
                // Terminal input - handled as soon as it arrives, no polling delay
                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()),
                        // Terminal event stream closed (e.g. stdin EOF) - back out of this
                        // screen, matching pre-existing behavior (`outcome` already defaults
                        // to `ReturnToParent` above).
                        None => {
                            self.should_quit = true;
                        }
                    }
                }

                // Fixed-interval tick, independent of terminal events - drives
                // the proactive re-publish while a movement key is held.
                _ = 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()) {
            self.send_velocity(ctx).await?;
        }

        Ok(())
    }

    /// Draw the UI with 3-panel layout: main area, logs sidebar, footer
    fn draw(&mut self, f: &mut Frame) {
        // Split terminal vertically: content area + footer
        let (content_area, footer_area) = standard_tui_layout(f.area());

        // Split main content horizontally: teleop controls + logs sidebar
        let (main_area, sidebar_area) = main_and_sidebar_layout(content_area);

        // Draw panels
        self.draw_teleop_panel(f, main_area);
        self.draw_logs_panel(f, sidebar_area);
        self.draw_footer(f, footer_area);
    }

    /// Draw teleop controls panel
    fn draw_teleop_panel(&self, f: &mut Frame, area: ratatui::layout::Rect) {
        let status_color = if self.current_linear == 0.0 && self.current_angular == 0.0 {
            Color::Gray
        } else {
            Color::Green
        };

        let text = 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)),
            ]),
        ];

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

    /// 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_logs();

        // Convert logs to list items with color coding and icons
        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);
    }

    /// Draw footer with links to dashboard and documentation
    fn draw_footer(&self, f: &mut Frame, area: ratatui::layout::Rect) {
        render_footer_hints(
            f,
            area,
            &[
                ("Dashboard", &self.dashboard_url, Color::Cyan),
                ("Docs", "https://mecha10.dev", Color::Yellow),
                ("Q/ESC", "Exit", Color::Red),
            ],
        );
    }

    /// 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,
            });
        }

        match key.code {
            // Scroll logs with modifiers (check before movement controls)
            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_logs();
                self.scroll_offset = (self.scroll_offset + 10).min(logs.len().saturating_sub(1));
            }

            // Scroll logs single-line (j/k) - check before other char matches
            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_logs();
                self.scroll_offset = (self.scroll_offset + 1).min(logs.len().saturating_sub(1));
            }

            // Movement controls (only when no modifiers)
            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?;
            }

            // Stop (Space only - bare 'x' is now a termination key, handled by `classify_key`
            // above; see `handle_key`'s docs).
            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?;
            }

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

            _ => {}
        }

        Ok(ScreenOutcome::Continue)
    }

    /// 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
    async fn send_stop(&mut self, ctx: &Context) -> Result<()> {
        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(())
    }
}

#[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() {
        // Simulates a single KeyDown followed by total terminal silence
        // (e.g. a terminal that never forwards auto-repeat events at all).
        // The tracker should report "held" for the full window, purely from
        // simulated elapsed time - no further terminal events required.
        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() {
        // Simulates a terminal that DOES forward auto-repeat KeyDown events:
        // each fresh press should push the deadline back out, so "held"
        // stays true across a long sequence as long as presses keep coming
        // faster than the 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); // refreshed well before the 300ms window lapses
        }
        assert!(tracker.is_held_at(t - Duration::from_millis(1)));
    }

    #[test]
    fn clear_stops_being_held_immediately() {
        // Simulates releasing/pausing key input via an explicit Stop (Space/X)
        // - re-publishing must stop right away rather than waiting out the
        // rest of the window.
        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)));
    }

    // -- classify_movement_key: real Press/Repeat/Release detection --------

    #[test]
    fn press_activates_a_movement_key() {
        // Existing behavior, must be unchanged: a fresh KeyDown activates
        // the key's velocity and refreshes the held window.
        assert_eq!(classify_movement_key(KeyEventKind::Press), MovementKeyAction::Activate);
    }

    #[test]
    fn repeat_activates_a_movement_key_exactly_like_press() {
        // Terminal/OS auto-repeat events must behave exactly like a fresh
        // Press (this is what LAB-1954's HELD_WINDOW fallback still relies
        // on for terminals without the enhancement protocol, where every
        // event - including true repeats - arrives as Press anyway).
        assert_eq!(classify_movement_key(KeyEventKind::Repeat), MovementKeyAction::Activate);
    }

    #[test]
    fn release_stops_a_movement_key_immediately() {
        // The regression fix: a real Release event (only ever reported once
        // the Kitty keyboard enhancement protocol is enabled) must zero
        // velocity immediately, regardless of how much of HELD_WINDOW would
        // otherwise remain.
        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");

        // Well within HELD_WINDOW - the old heuristic-only behavior would
        // have kept moving for up to HELD_WINDOW - 1ms more here.
        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");
        }
    }

    // -- classify_key usage from this screen's perspective ---------------------------------
    //
    // `classify_key` itself (bare q/Esc/x -> StopCurrent, Ctrl+C/Ctrl+X -> QuitAll, Space ->
    // None) is unit tested directly in `crate::dev::termination`; the regression test for the
    // reported bug (bare 'x' now classifies as StopCurrent, not the old zero-velocity behavior)
    // lives there too. This just sanity-checks the two outcomes `handle_key` maps `classify_key`
    // results onto.

    #[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() {
        // Space stays a distinct, non-terminating "zero velocity, stay in teleop" safety
        // control - it must never be routed through classify_key's Stop/QuitAll handling.
        let key = KeyEvent::new(KeyCode::Char(' '), KeyModifiers::NONE);
        assert_eq!(classify_key(&key), None);
    }
}