mecha10-cli 0.8.0

Mecha10 CLI tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! 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. Prefers the current keypress's own fresh result,
/// falling back to `last_known_failures`.
fn resolve_teleop_failure(
    start_failures: Vec<(String, String)>,
    last_known_failures: &HashMap<String, String>,
) -> Option<(String, String)> {
    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()))
        })
}

#[derive(Debug, PartialEq, Eq)]
enum SimulationKeyAction {
    NoLifecycleConfig,
    ModeNotConfigured,
    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". Returns `None` when there's no lifecycle config, or "dev" isn't one of
/// the lifecycle's available modes.
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` is a no-op here, `QuitAll` propagates the
/// quit request to the outer dev-mode loop's shared `running` flag.
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<()> {
    disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
    terminal.show_cursor()?;

    print!("\x1B[2J\x1B[1;1H");
    stdout().flush()?;
    println!("╔════════════════════════════════════════════════════════════╗");
    println!("║              SWITCHING TO SIMULATION MODE                  ║");
    println!("╚════════════════════════════════════════════════════════════╝");
    println!();

    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?;
            state.node_registry.record_failures(&start_failures);
            let teleop_failure = resolve_teleop_failure(start_failures, state.node_registry.last_known_failures());

            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 => {
                    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' target configured in targets");
            state
                .log_buffer
                .push("MODE: No 'simulation' target in targets".to_string());
        }
        SimulationKeyAction::NoLifecycleConfig => {
            println!("❌ Target configuration is required. Please add a 'targets' section to mecha10.json");
            state.log_buffer.push("MODE: No targets config found".to_string());
        }
    }

    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<()> {
    disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
    terminal.show_cursor()?;

    print!("\x1B[2J\x1B[1;1H");
    stdout().flush()?;
    println!("╔════════════════════════════════════════════════════════════╗");
    println!("║                 SWITCHING TO TELEOP MODE                   ║");
    println!("╚════════════════════════════════════════════════════════════╝");
    println!();

    if let Some(ref mut lifecycle_mgr) = state.lifecycle {
        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());

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

    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<()> {
    disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
    terminal.show_cursor()?;

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

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

    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() {
        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() {
        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() {
        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::{NodesConfig, ProjectConfig, RobotConfig, TargetEntry, TargetsConfig};
    use std::collections::HashMap as StdHashMap;

    /// Build a minimal `ProjectConfig` with the given `targets` section, mirroring
    /// `teleop.rs`'s own `project_config_with_nodes` test helper.
    fn project_config_with_targets(targets: TargetsConfig) -> ProjectConfig {
        ProjectConfig {
            name: "test".to_string(),
            version: "0.1.0".to_string(),
            template_version: None,
            robot: RobotConfig {
                id: "test".to_string(),
                name: "test".to_string(),
                platform: None,
                description: None,
            },
            simulation: None,
            nodes: NodesConfig(StdHashMap::new()),
            targets,
            behaviors: None,
            docker: Default::default(),
            environments: Default::default(),
            actuator: Default::default(),
        }
    }

    /// Build a `TargetsConfig` where each of the given (valid) target keys is present with an
    /// empty node list - `mode_names` must be a subset of `"dev"`/`"simulation"`/`"robot"`/
    /// `"remote"`/`"rl"`.
    fn targets_config(mode_names: &[&str]) -> TargetsConfig {
        let has = |name: &str| mode_names.contains(&name);
        let entry = || Some(TargetEntry::default());

        TargetsConfig {
            dev: if has("dev") { entry() } else { None },
            simulation: if has("simulation") { entry() } else { None },
            robot: if has("robot") { entry() } else { None },
            remote: if has("remote") { entry() } else { None },
            rl: if has("rl") { entry() } else { None },
        }
    }

    fn lifecycle_manager(mode_names: &[&str]) -> CliLifecycleManager {
        let config = project_config_with_targets(targets_config(mode_names));
        CliLifecycleManager::from_project_config(&config).expect("targets section is present")
    }

    #[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() {
        let lifecycle_mgr = lifecycle_manager(&["dev", "robot"]);

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

    #[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() {
        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()));
    }

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