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
//! Key handlers for the interactive dev mode TUI (simulation/teleop toggles)

use super::{InteractiveModeConfig, InteractiveModeState};
use crate::context::CliContext;
use crate::dev::lifecycle_adapter::CliLifecycleManager;
use crate::dev::termination::ScreenOutcome;
use crate::handlers::dev::ops::lifecycle::handle_mode_change;
use crate::handlers::dev::ops::teleop::enter_teleop_mode;
use crate::ui::DevModeTui;
use anyhow::Result;
use crossterm::execute;
use crossterm::terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen};
use ratatui::backend::CrosstermBackend;
use ratatui::Terminal;
use std::collections::HashMap;
use std::io::{stdout, Stdout, Write};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

type DevTerminal = Terminal<CrosstermBackend<Stdout>>;

/// Figure out what spawn failure (if any) to show for `teleop` after a
/// keypress that may or may not have just run a lifecycle mode change.
///
/// `start_failures` is the current keypress's own fresh result (empty if no
/// mode change ran, or the target mode wasn't configured). It always wins
/// when it mentions `teleop` — it's the freshest information available.
/// Otherwise falls back to `last_known_failures`, which persists across
/// keypresses and is the only place a startup-time failure (or a failure
/// from an earlier keypress that a later mode change never re-attempted)
/// survives to.
fn resolve_teleop_failure(
    start_failures: Vec<(String, String)>,
    last_known_failures: &HashMap<String, String>,
) -> Option<(String, String)> {
    // Both maps are keyed by the full scoped node identifier (e.g.
    // `@mecha10/teleop`), exactly as `spawn_nodes_by_name` records it — not
    // the bare `"teleop"` string. Strip the scope before comparing. See
    // `super::super::strip_node_scope`.
    start_failures
        .into_iter()
        .find(|(name, _)| super::super::strip_node_scope(name) == "teleop")
        .or_else(|| {
            last_known_failures
                .iter()
                .find(|(name, _)| super::super::strip_node_scope(name) == "teleop")
                .map(|(name, err)| (name.clone(), err.clone()))
        })
}

/// What handling the 's' key should do, based on whether `lifecycle` is configured at all and,
/// if so, whether it defines a "simulation" mode.
#[derive(Debug, PartialEq, Eq)]
enum SimulationKeyAction {
    /// No `lifecycle` section in mecha10.json at all — nothing to switch to.
    NoLifecycleConfig,
    /// `lifecycle` is configured, but none of its modes is named "simulation".
    ModeNotConfigured,
    /// `lifecycle` is configured and a "simulation" mode is available — proceed with the mode
    /// change + teleop hand-off.
    SwitchToSimulation,
}

/// Decide what the 's' key should do for the current lifecycle state. Pure/side-effect-free so
/// it can be unit-tested against mocked lifecycle configs rather than a live terminal/process.
fn resolve_simulation_key_action(lifecycle: Option<&CliLifecycleManager>) -> SimulationKeyAction {
    match lifecycle {
        None => SimulationKeyAction::NoLifecycleConfig,
        Some(lifecycle_mgr) if lifecycle_mgr.available_modes().contains(&"simulation") => {
            SimulationKeyAction::SwitchToSimulation
        }
        Some(_) => SimulationKeyAction::ModeNotConfigured,
    }
}

/// Which mode `handle_stop_simulation_key` ('x') should switch back to, if any.
///
/// Always targets "dev" — there's no more `lifecycle.default_mode` to read (removed in
/// LAB-2040). Returns `None` when there's no lifecycle config, or "dev" isn't one of the
/// lifecycle's available modes — in both cases the keypress is a no-op beyond the TUI banner,
/// since there's nothing valid to switch to. Pure/side-effect-free so it can be unit-tested
/// against mocked lifecycle configs rather than a live terminal/process.
fn resolve_stop_simulation_target(lifecycle: Option<&CliLifecycleManager>) -> Option<String> {
    const TARGET_MODE: &str = "dev";
    let lifecycle_mgr = lifecycle?;

    lifecycle_mgr
        .available_modes()
        .contains(&TARGET_MODE)
        .then(|| TARGET_MODE.to_string())
}

/// Apply a teleop screen's `ScreenOutcome` when it was entered standalone (via `'t'`, not as
/// part of a simulation hand-off): `ReturnToParent` just closes the screen — no mode change, and
/// `refresh_status` beneath both `enter_teleop_mode` call sites in `handle_teleop_key` handles
/// the UI redraw already, so it's a no-op here. `QuitAll` propagates the quit request to the
/// outer dev-mode loop's shared `running` flag, whose own `if !running.load() { break }` handles
/// full session teardown - mirrors how `handle_simulation_key` handles the same outcome for the
/// `'s'` entry point (see that function's `ScreenOutcome::ReturnToParent` arm for why *that* case
/// differs: simulation hand-off needs an extra stop-and-return-to-dev step this entry point
/// doesn't).
fn apply_standalone_teleop_outcome(outcome: ScreenOutcome, running: &Arc<AtomicBool>) {
    if outcome == ScreenOutcome::QuitAll {
        running.store(false, Ordering::SeqCst);
    }
}

/// Refresh the TUI's status line from the current lifecycle mode + running pids
fn refresh_status(state: &InteractiveModeState, dev_tui: &mut DevModeTui) {
    let current_mode = state
        .lifecycle
        .as_ref()
        .map(|l| l.current_mode().to_string())
        .unwrap_or_else(|| "startup".to_string());
    let running_nodes: Vec<String> = state.node_registry.running_node_names();
    dev_tui.update_status(current_mode, running_nodes);
}

/// Handle the 's' key: switch to simulation mode and enter keyboard control
#[allow(clippy::too_many_arguments)]
pub(super) async fn handle_simulation_key(
    ctx: &mut CliContext,
    config: &InteractiveModeConfig<'_>,
    state: &mut InteractiveModeState,
    terminal: &mut DevTerminal,
    dev_tui: &mut DevModeTui,
    redis_url: &str,
    running: &Arc<AtomicBool>,
) -> Result<()> {
    // Exit TUI temporarily
    disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
    terminal.show_cursor()?;

    // Clear screen and show header for simulation mode
    print!("\x1B[2J\x1B[1;1H"); // Clear screen and move cursor to top
    stdout().flush()?;
    println!("╔════════════════════════════════════════════════════════════╗");
    println!("║              SWITCHING TO SIMULATION MODE                  ║");
    println!("╚════════════════════════════════════════════════════════════╝");
    println!();

    // Switch to simulation mode
    match resolve_simulation_key_action(state.lifecycle.as_ref()) {
        SimulationKeyAction::SwitchToSimulation => {
            let lifecycle_mgr = state
                .lifecycle
                .as_mut()
                .expect("SwitchToSimulation is only returned when lifecycle is configured");
            let start_failures = handle_mode_change(
                ctx,
                lifecycle_mgr,
                "simulation",
                &mut state.node_registry,
                config.project_name,
                config.project_config,
                config.nodes_to_run,
                Some(&state.log_buffer),
            )
            .await?;
            // Persist this attempt's failures (if any) beyond this call, and
            // clear stale entries for anything that's now running — a later
            // keypress may need this even if `teleop` wasn't touched by this
            // specific mode change (e.g. it's not part of `simulation`'s own
            // node list because it was expected to still be running from
            // whatever mode started it).
            state.node_registry.record_failures(&start_failures);
            let teleop_failure = resolve_teleop_failure(start_failures, state.node_registry.last_known_failures());

            // Sim nodes (simulator) are up — reuse the teleop keyboard-capture UI so
            // the user can immediately drive the robot in the running MuJoCo sim.
            let outcome = enter_teleop_mode(
                config.project_config,
                &state.node_registry,
                redis_url,
                running,
                &state.log_buffer,
                teleop_failure.as_ref(),
            )
            .await?;

            match outcome {
                ScreenOutcome::ReturnToParent => {
                    // Entered teleop via 's' (simulation hand-off): backing out of the teleop
                    // screen (bare 'q'/Esc/'x' — see `crate::dev::termination`) means "stop the
                    // simulation and return to dev mode", not just "close the screen". This is
                    // the direct fix for the reported bug: pressing 's' then 'x' now reaches
                    // here instead of silently zeroing teleop's velocity and doing nothing else.
                    // Reuses `handle_stop_simulation_key`'s mode-change sequence verbatim, which
                    // already re-enters the TUI and refreshes status — return early rather than
                    // falling through to this function's own "re-enter TUI" tail below.
                    handle_stop_simulation_key(ctx, config, state, terminal, dev_tui).await?;
                    return Ok(());
                }
                ScreenOutcome::QuitAll => {
                    running.store(false, Ordering::SeqCst);
                }
                ScreenOutcome::Continue => {}
            }
        }
        SimulationKeyAction::ModeNotConfigured => {
            println!("⚠️  No 'simulation' mode configured in lifecycle");
            state
                .log_buffer
                .push("MODE: No 'simulation' mode in lifecycle config".to_string());
        }
        SimulationKeyAction::NoLifecycleConfig => {
            println!("❌ Lifecycle configuration is required. Please add a 'lifecycle' section to mecha10.json");
            state.log_buffer.push("MODE: No lifecycle config found".to_string());
        }
    }

    // Re-enter TUI
    enable_raw_mode()?;
    execute!(terminal.backend_mut(), EnterAlternateScreen)?;
    terminal.clear()?;

    refresh_status(state, dev_tui);

    Ok(())
}

/// Handle the 't' key: switch to teleop mode and enter the teleop UI
#[allow(clippy::too_many_arguments)]
pub(super) async fn handle_teleop_key(
    ctx: &mut CliContext,
    config: &InteractiveModeConfig<'_>,
    state: &mut InteractiveModeState,
    terminal: &mut DevTerminal,
    dev_tui: &mut DevModeTui,
    redis_url: &str,
    running: &Arc<AtomicBool>,
) -> Result<()> {
    // Exit TUI temporarily
    disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
    terminal.show_cursor()?;

    // Clear screen and show header for teleop mode
    print!("\x1B[2J\x1B[1;1H"); // Clear screen and move cursor to top
    stdout().flush()?;
    println!("╔════════════════════════════════════════════════════════════╗");
    println!("║                 SWITCHING TO TELEOP MODE                   ║");
    println!("╚════════════════════════════════════════════════════════════╝");
    println!();

    // Switch to teleop mode
    if let Some(ref mut lifecycle_mgr) = state.lifecycle {
        // Try to switch to teleop mode
        if lifecycle_mgr.available_modes().contains(&"teleop") {
            let start_failures = handle_mode_change(
                ctx,
                lifecycle_mgr,
                "teleop",
                &mut state.node_registry,
                config.project_name,
                config.project_config,
                config.nodes_to_run,
                Some(&state.log_buffer),
            )
            .await?;
            state.node_registry.record_failures(&start_failures);
            let teleop_failure = resolve_teleop_failure(start_failures, state.node_registry.last_known_failures());

            // After switching mode, enter teleop UI
            let outcome = enter_teleop_mode(
                config.project_config,
                &state.node_registry,
                redis_url,
                running,
                &state.log_buffer,
                teleop_failure.as_ref(),
            )
            .await?;
            apply_standalone_teleop_outcome(outcome, running);
        } else {
            // Fallback to direct teleop UI if mode not configured. No mode
            // change ran, but a previously known startup failure for teleop
            // (e.g. it's configured and part of the fixed node set, not
            // behind any lifecycle mode) is still the more useful message.
            // Same scoped-key concern as `resolve_teleop_failure`:
            // `last_known_failures` is keyed by the full scoped identifier
            // (e.g. `@mecha10/teleop`), not the bare short name.
            let teleop_failure = state
                .node_registry
                .last_known_failures()
                .iter()
                .find(|(name, _)| super::super::strip_node_scope(name) == "teleop")
                .map(|(name, err)| (name.clone(), err.clone()));
            let outcome = enter_teleop_mode(
                config.project_config,
                &state.node_registry,
                redis_url,
                running,
                &state.log_buffer,
                teleop_failure.as_ref(),
            )
            .await?;
            apply_standalone_teleop_outcome(outcome, running);
        }
    } else {
        println!("❌ Lifecycle configuration is required. Please add a 'lifecycle' section to mecha10.json");
    }

    // Re-enter TUI
    enable_raw_mode()?;
    execute!(terminal.backend_mut(), EnterAlternateScreen)?;
    terminal.clear()?;

    refresh_status(state, dev_tui);

    Ok(())
}

/// Handle the 'x' key: stop simulation mode and switch back to the default mode
///
/// Caller is responsible for checking that the current mode is `simulation`
/// before calling this.
pub(super) async fn handle_stop_simulation_key(
    ctx: &mut CliContext,
    config: &InteractiveModeConfig<'_>,
    state: &mut InteractiveModeState,
    terminal: &mut DevTerminal,
    dev_tui: &mut DevModeTui,
) -> Result<()> {
    // Exit TUI temporarily
    disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
    terminal.show_cursor()?;

    // Clear screen and show header
    print!("\x1B[2J\x1B[1;1H");
    stdout().flush()?;
    println!("╔════════════════════════════════════════════════════════════╗");
    println!("║               STOPPING SIMULATION MODE                     ║");
    println!("╚════════════════════════════════════════════════════════════╝");
    println!();

    state.log_buffer.push("MODE: Stopping simulation mode...".to_string());

    // Switch back to default mode
    if let Some(target_mode) = resolve_stop_simulation_target(state.lifecycle.as_ref()) {
        let lifecycle_mgr = state
            .lifecycle
            .as_mut()
            .expect("resolve_stop_simulation_target only returns Some when lifecycle is configured");
        let start_failures = handle_mode_change(
            ctx,
            lifecycle_mgr,
            &target_mode,
            &mut state.node_registry,
            config.project_name,
            config.project_config,
            config.nodes_to_run,
            Some(&state.log_buffer),
        )
        .await?;
        state.node_registry.record_failures(&start_failures);
    }

    // Re-enter TUI
    enable_raw_mode()?;
    execute!(terminal.backend_mut(), EnterAlternateScreen)?;
    terminal.clear()?;

    refresh_status(state, dev_tui);

    Ok(())
}

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

    #[test]
    fn prefers_this_keypress_own_fresh_failure() {
        // `start_failures`/`last_known_failures` are keyed by the full
        // scoped node identifier production code actually uses (e.g.
        // `@mecha10/teleop`), never the bare `"teleop"` string — see
        // `spawn_nodes_by_name`.
        let start_failures = vec![("@mecha10/teleop".to_string(), "fresh error".to_string())];
        let mut last_known_failures = HashMap::new();
        last_known_failures.insert("@mecha10/teleop".to_string(), "stale error".to_string());

        let resolved = resolve_teleop_failure(start_failures, &last_known_failures);

        assert_eq!(
            resolved,
            Some(("@mecha10/teleop".to_string(), "fresh error".to_string()))
        );
    }

    #[test]
    fn falls_back_to_last_known_failure_when_this_keypress_did_not_touch_teleop() {
        // e.g. teleop failed at `DevSession` startup and the mode this
        // keypress switched to doesn't list teleop in its own node set (it
        // was expected to still be running from whatever mode started it),
        // so `handle_mode_change` never attempted it again this time.
        let start_failures = vec![("@mecha10/simulator".to_string(), "unrelated failure".to_string())];
        let mut last_known_failures = HashMap::new();
        last_known_failures.insert(
            "@mecha10/teleop".to_string(),
            "binary download failed: HTTP 404".to_string(),
        );

        let resolved = resolve_teleop_failure(start_failures, &last_known_failures);

        assert_eq!(
            resolved,
            Some((
                "@mecha10/teleop".to_string(),
                "binary download failed: HTTP 404".to_string()
            ))
        );
    }

    #[test]
    fn none_when_neither_this_keypress_nor_history_has_a_teleop_failure() {
        let resolved = resolve_teleop_failure(Vec::new(), &HashMap::new());

        assert_eq!(resolved, None);
    }

    #[test]
    fn matches_scoped_key_against_bare_teleop_lookup_in_start_failures() {
        // Regression test for LAB-1883: previously this compared the scoped
        // key directly against the bare `"teleop"` string and never
        // matched, so a genuine teleop spawn failure was silently dropped.
        let start_failures = vec![("@mecha10/teleop".to_string(), "binary download failed".to_string())];

        let resolved = resolve_teleop_failure(start_failures, &HashMap::new());

        assert_eq!(
            resolved,
            Some(("@mecha10/teleop".to_string(), "binary download failed".to_string()))
        );
    }
}

#[cfg(test)]
mod simulation_key_branch_tests {
    use super::*;
    use crate::types::project::{LifecycleConfig, ModeConfig, NodesConfig, ProjectConfig, RobotConfig};
    use std::collections::HashMap as StdHashMap;

    /// Build a minimal `ProjectConfig` with an optional `lifecycle` section, mirroring
    /// `teleop.rs`'s own `project_config_with_nodes` test helper.
    fn project_config_with_lifecycle(lifecycle: Option<LifecycleConfig>) -> ProjectConfig {
        ProjectConfig {
            name: "test".to_string(),
            version: "0.1.0".to_string(),
            robot: RobotConfig {
                id: "test".to_string(),
                platform: None,
                description: None,
            },
            lifecycle,
            simulation: None,
            nodes: NodesConfig(StdHashMap::new()),
            targets: None,
            behaviors: None,
            services: Default::default(),
            docker: Default::default(),
            environments: Default::default(),
        }
    }

    fn lifecycle_config(mode_names: &[&str]) -> LifecycleConfig {
        let mut modes = StdHashMap::new();
        for name in mode_names {
            modes.insert(name.to_string(), ModeConfig { nodes: Vec::new() });
        }
        LifecycleConfig { modes }
    }

    fn lifecycle_manager(mode_names: &[&str]) -> CliLifecycleManager {
        let config = project_config_with_lifecycle(Some(lifecycle_config(mode_names)));
        CliLifecycleManager::from_project_config(&config).expect("lifecycle section is present")
    }

    // --- resolve_simulation_key_action ('s' key) ---

    #[test]
    fn simulation_key_reports_missing_lifecycle_config_when_none_configured() {
        let action = resolve_simulation_key_action(None);

        assert_eq!(action, SimulationKeyAction::NoLifecycleConfig);
    }

    #[test]
    fn simulation_key_reports_mode_not_configured_when_simulation_mode_absent() {
        // Lifecycle is configured, but "simulation" isn't one of its modes — e.g. only "dev" and
        // "teleop" are defined.
        let lifecycle_mgr = lifecycle_manager(&["dev", "teleop"]);

        let action = resolve_simulation_key_action(Some(&lifecycle_mgr));

        assert_eq!(action, SimulationKeyAction::ModeNotConfigured);
    }

    #[test]
    fn simulation_key_switches_when_simulation_mode_is_available() {
        let lifecycle_mgr = lifecycle_manager(&["dev", "simulation"]);

        let action = resolve_simulation_key_action(Some(&lifecycle_mgr));

        assert_eq!(action, SimulationKeyAction::SwitchToSimulation);
    }

    // --- resolve_stop_simulation_target ('x' key) ---
    //
    // Always targets "dev" (LAB-2040 removed `lifecycle.default_mode`, so there's no
    // project-configurable default to read anymore).

    #[test]
    fn stop_simulation_key_is_a_no_op_when_no_lifecycle_config() {
        let target = resolve_stop_simulation_target(None);

        assert_eq!(target, None, "nothing to switch back to without a lifecycle config");
    }

    #[test]
    fn stop_simulation_key_is_a_no_op_when_dev_not_available() {
        // "dev" was never defined as one of the lifecycle's modes — e.g. a misconfigured
        // mecha10.json (this would already be rejected at `mecha10 dev` startup, but
        // `resolve_stop_simulation_target` stays defensive here regardless).
        let lifecycle_mgr = lifecycle_manager(&["simulation"]);

        let target = resolve_stop_simulation_target(Some(&lifecycle_mgr));

        assert_eq!(target, None);
    }

    #[test]
    fn stop_simulation_key_targets_dev() {
        let lifecycle_mgr = lifecycle_manager(&["dev", "simulation"]);

        let target = resolve_stop_simulation_target(Some(&lifecycle_mgr));

        assert_eq!(target, Some("dev".to_string()));
    }

    // --- apply_standalone_teleop_outcome (teleop entered via 't') ---

    #[test]
    fn standalone_teleop_return_to_parent_does_not_touch_running_flag() {
        let running = Arc::new(AtomicBool::new(true));

        apply_standalone_teleop_outcome(ScreenOutcome::ReturnToParent, &running);

        assert!(
            running.load(Ordering::SeqCst),
            "backing out of standalone teleop must not quit `mecha10 dev`"
        );
    }

    #[test]
    fn standalone_teleop_quit_all_clears_running_flag() {
        let running = Arc::new(AtomicBool::new(true));

        apply_standalone_teleop_outcome(ScreenOutcome::QuitAll, &running);

        assert!(
            !running.load(Ordering::SeqCst),
            "Ctrl+C inside standalone teleop must propagate to the outer dev-mode loop's quit flag"
        );
    }

    #[test]
    fn standalone_teleop_continue_does_not_touch_running_flag() {
        let running = Arc::new(AtomicBool::new(true));

        apply_standalone_teleop_outcome(ScreenOutcome::Continue, &running);

        assert!(running.load(Ordering::SeqCst));
    }
}