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
//! Entering teleop control mode for dev mode

use super::registry::NodeRegistry;
use crate::dev::termination::ScreenOutcome;
use crate::types::ProjectConfig;
use crate::ui::{LogBuffer, TeleopUi};
use anyhow::Result;
use mecha10_core::context::split_base_and_custom;
use std::collections::HashMap;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;

/// Whether a teleop node's PID is tracked in `registry`, under either its scoped
/// (`@mecha10/teleop`) or unscoped key.
fn teleop_already_running(registry: &NodeRegistry) -> bool {
    registry
        .pids()
        .keys()
        .any(|name| super::strip_node_scope(name) == "teleop")
}

/// Resolve the active `dev`/`production` environment section of the project's own `teleop`
/// node config (if any) and merge it via the real [`split_base_and_custom`] split - mirrors
/// `handlers/dev/ops/models.rs::parse_node_config`'s environment-aware resolution, so this
/// reads the same shape every node config is actually written in (`controller`,
/// `status_rate_hz`, etc. nested inside `"dev"`/`"production"`, node-specific fields under a
/// nested `custom` key promoted to the top level by `split_base_and_custom`).
///
/// Tries each config candidate, in `node_config_candidates`'s canonical tier order, falling
/// through to the next candidate only when a candidate's file is missing, unreadable, not
/// valid JSON, or has no matching environment section/fails the base/custom split. A
/// candidate whose file exists and resolves cleanly is used as-is - even if it simply has
/// nothing relevant set (e.g. no `controller`) - rather than falling through to the next
/// tier just because nothing matched, which is the bug this replaces: the earlier code bailed
/// out with an empty result after the very first candidate unconditionally, so a later tier's
/// config (e.g. the project's own override) was never even consulted.
fn resolve_teleop_custom_config() -> Option<serde_json::Value> {
    let profile = std::env::var("MECHA10_ENVIRONMENT").unwrap_or_else(|_| "dev".to_string());
    let env_key = match profile.as_str() {
        "production" | "prod" => "production",
        _ => "dev",
    };

    for candidate in crate::paths::config::node_config_candidates("teleop") {
        let Ok(content) = std::fs::read_to_string(&candidate) else {
            continue;
        };
        let Ok(value) = serde_json::from_str::<serde_json::Value>(&content) else {
            continue;
        };
        let Some(obj) = value.as_object() else {
            continue;
        };
        let Some(section) = obj.get(env_key) else {
            continue;
        };
        let Ok(merged) = split_base_and_custom(section) else {
            continue;
        };
        return Some(merged);
    }

    None
}

/// Read the project's own `teleop` node config (if any) and resolve the `joint_names` this
/// instance is configured for - empty for drivetrain mode (the default) or if no config exists.
fn resolve_teleop_joint_names() -> Vec<String> {
    let Some(merged) = resolve_teleop_custom_config() else {
        return Vec::new();
    };

    merged
        .get("controller")
        .filter(|c| c.get("type").and_then(|t| t.as_str()) == Some("actuator"))
        .and_then(|c| c.get("joint_names"))
        .and_then(|n| n.as_array())
        .map(|names| names.iter().filter_map(|n| n.as_str().map(str::to_string)).collect())
        .unwrap_or_default()
}

/// Read the project's own `teleop` node config (if any) and resolve its `custom.key_bindings`
/// map (a key-name -> action-name remap for the TUI's controls) - empty if absent/malformed,
/// which preserves today's hardcoded w/s/a/d/arrows behavior.
fn resolve_teleop_key_bindings() -> HashMap<String, String> {
    let Some(merged) = resolve_teleop_custom_config() else {
        return HashMap::new();
    };

    merged
        .get("key_bindings")
        .and_then(|v| v.as_object())
        .map(|obj| {
            obj.iter()
                .filter_map(|(k, v)| v.as_str().map(|s| (k.to_lowercase(), s.to_string())))
                .collect()
        })
        .unwrap_or_default()
}

/// Enter teleop mode. `spawn_failure`, if present, is the `(node_name, error)` pair from a
/// just-attempted lifecycle mode change that tried and failed to start teleop, so the right
/// error can be surfaced instead of a generic "not running" message.
pub async fn enter_teleop_mode(
    config: &ProjectConfig,
    registry: &NodeRegistry,
    redis_url: &str,
    running: &Arc<AtomicBool>,
    log_buffer: &LogBuffer,
    spawn_failure: Option<&(String, String)>,
) -> Result<ScreenOutcome> {
    let has_teleop = config.nodes.contains("teleop");
    let teleop_running = teleop_already_running(registry);

    if !has_teleop {
        println!("\n⚠️  Teleop node not found in project");
        println!();
        println!("To add teleop to your project:");
        println!("  mecha10 add teleop");
        println!();
        println!("The teleop coordination node manages multiple");
        println!("control sources with priority arbitration.");
        println!();
        log_buffer.push("TELEOP: Teleop node not found in project (run `mecha10 add teleop`)".to_string());
        return Ok(ScreenOutcome::ReturnToParent);
    } else if !teleop_running {
        if let Some((_, err)) = spawn_failure {
            println!("\n⚠️  Teleop node failed to start");
            println!();
            println!("It's configured in mecha10.json and mecha10 just tried to start it");
            println!("as part of this mode change, but the spawn failed:");
            println!();
            println!("  {}", err);
            println!();
            println!("Run 'mecha10 dev teleop' directly to see the full startup output.");
            println!();
            log_buffer.push(format!("TELEOP: teleop failed to start during mode change: {}", err));
        } else {
            println!("\n⚠️  Teleop node not running");
            println!();
            println!("Start the teleop node by adding it to dev nodes:");
            println!("  mecha10 dev teleop");
            println!();
            log_buffer.push("TELEOP: Teleop node not running (run `mecha10 dev teleop`)".to_string());
        }
        return Ok(ScreenOutcome::ReturnToParent);
    }

    println!("\n🎮 Entering teleop control mode...\n");

    let dashboard_url = config.environments.dashboard_url();
    let mut teleop_ui = TeleopUi::new(
        redis_url.to_string(),
        log_buffer.clone(),
        dashboard_url,
        config.actuator.locomotion.max_linear_vel,
        config.actuator.locomotion.max_angular_vel,
        resolve_teleop_joint_names(),
        resolve_teleop_key_bindings(),
    );

    match teleop_ui.run_with_interrupt(running.clone()).await {
        Ok(outcome) => {
            println!("\n✅ Exited teleop mode\n");
            Ok(outcome)
        }
        Err(e) => {
            eprintln!("\n❌ Teleop UI error: {}\n", e);
            Ok(ScreenOutcome::ReturnToParent)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::project::{NodesConfig, ProjectConfig, RobotConfig};
    use std::collections::HashMap as StdHashMap;
    use std::sync::atomic::AtomicBool;

    fn project_config_with_nodes(node_names: &[&str]) -> ProjectConfig {
        let mut nodes = StdHashMap::new();
        for name in node_names {
            nodes.insert(format!("@mecha10/{}", name), "0.1.0".to_string());
        }

        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(nodes),
            targets: Default::default(),
            behaviors: None,
            docker: Default::default(),
            environments: Default::default(),
            actuator: Default::default(),
        }
    }

    #[tokio::test]
    async fn not_configured_reports_add_teleop_regardless_of_spawn_failure() {
        let config = project_config_with_nodes(&["camera"]);
        let registry = NodeRegistry::new();
        let log_buffer = LogBuffer::new(100);
        let running = Arc::new(AtomicBool::new(true));

        enter_teleop_mode(&config, &registry, "redis://localhost", &running, &log_buffer, None)
            .await
            .unwrap();

        let logs = log_buffer.get_all();
        assert!(
            logs.iter().any(|l| l.contains("not found in project")),
            "expected a 'not found in project' log entry, got: {logs:?}"
        );
    }

    #[tokio::test]
    async fn configured_but_not_running_without_spawn_failure_suggests_dev_teleop() {
        let config = project_config_with_nodes(&["teleop"]);
        let registry = NodeRegistry::new();
        let log_buffer = LogBuffer::new(100);
        let running = Arc::new(AtomicBool::new(true));

        enter_teleop_mode(&config, &registry, "redis://localhost", &running, &log_buffer, None)
            .await
            .unwrap();

        let logs = log_buffer.get_all();
        assert!(
            logs.iter().any(|l| l.contains("Teleop node not running")),
            "expected a plain 'not running' log entry, got: {logs:?}"
        );
        assert!(
            !logs.iter().any(|l| l.contains("failed to start during mode change")),
            "should not claim a spawn failure when none occurred, got: {logs:?}"
        );
    }

    #[test]
    fn running_under_scoped_pid_key_is_detected_as_running() {
        let mut registry = NodeRegistry::new();
        registry.mark_started("@mecha10/teleop", 12345);

        assert!(
            teleop_already_running(&registry),
            "a teleop pid tracked under the scoped '@mecha10/teleop' key should be recognized as running"
        );
    }

    #[test]
    fn no_tracked_pid_is_not_detected_as_running() {
        let registry = NodeRegistry::new();

        assert!(
            !teleop_already_running(&registry),
            "a registry with no teleop pid tracked should not be recognized as running"
        );
    }

    #[tokio::test]
    async fn configured_but_not_running_with_spawn_failure_surfaces_the_real_error() {
        let config = project_config_with_nodes(&["teleop"]);
        let registry = NodeRegistry::new();
        let log_buffer = LogBuffer::new(100);
        let running = Arc::new(AtomicBool::new(true));
        let spawn_failure = ("teleop".to_string(), "binary download failed: HTTP 404".to_string());

        enter_teleop_mode(
            &config,
            &registry,
            "redis://localhost",
            &running,
            &log_buffer,
            Some(&spawn_failure),
        )
        .await
        .unwrap();

        let logs = log_buffer.get_all();
        assert!(
            logs.iter()
                .any(|l| l.contains("failed to start during mode change") && l.contains("HTTP 404")),
            "expected the actual spawn error to be surfaced, got: {logs:?}"
        );
        assert!(
            !logs.iter().any(|l| l.contains("Teleop node not running (run")),
            "should not show the generic 'not running' message when the real cause is known, got: {logs:?}"
        );
    }

    /// Covers `resolve_teleop_joint_names`/`resolve_teleop_key_bindings` against a real
    /// `teleop` `config.json` on disk, written at whichever of `node_config_candidates`'s 2
    /// tiers the test asks for - these helpers resolve relative paths against the process cwd,
    /// so each test chdirs into a scratch project dir for the duration of the call.
    mod config_resolution {
        use super::super::*;
        use serial_test::serial;
        use std::fs;

        /// Writes `content` at the project-tier `configs/nodes/teleop/config.json` path (one of
        /// `node_config_candidates("teleop")`'s 2 entries) under `project_dir`.
        fn write_project_tier_config(project_dir: &std::path::Path, content: &str) {
            let node_dir = project_dir.join("configs").join("nodes").join("teleop");
            fs::create_dir_all(&node_dir).unwrap();
            fs::write(node_dir.join("config.json"), content).unwrap();
        }

        /// Runs `f` with the process cwd pointed at a fresh scratch project directory,
        /// restoring the original cwd afterward even if `f` panics.
        fn with_scratch_project_dir<T>(f: impl FnOnce(&std::path::Path) -> T) -> T {
            let original_dir = std::env::current_dir().unwrap();
            let project = tempfile::tempdir().unwrap();

            std::env::set_current_dir(project.path()).unwrap();
            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(project.path())));
            std::env::set_current_dir(original_dir).unwrap();

            match result {
                Ok(value) => value,
                Err(payload) => std::panic::resume_unwind(payload),
            }
        }

        #[test]
        #[serial]
        fn joint_names_resolve_from_the_realistic_env_nested_shape() {
            with_scratch_project_dir(|project_dir| {
                write_project_tier_config(
                    project_dir,
                    r#"{"dev": {"controller": {"type": "actuator", "joint_names": ["pan", "tilt"]}}}"#,
                );

                assert_eq!(
                    resolve_teleop_joint_names(),
                    vec!["pan".to_string(), "tilt".to_string()]
                );
            });
        }

        #[test]
        #[serial]
        fn flat_top_level_controller_does_not_falsely_match() {
            with_scratch_project_dir(|project_dir| {
                // The old, buggy assumption: `controller` at the raw file's top level rather
                // than nested inside an environment ("dev"/"production") block. There is no
                // "dev" key here at all, so this must resolve to empty, not to ["pan", "tilt"].
                write_project_tier_config(
                    project_dir,
                    r#"{"controller": {"type": "actuator", "joint_names": ["pan", "tilt"]}}"#,
                );

                assert_eq!(
                    resolve_teleop_joint_names(),
                    Vec::<String>::new(),
                    "a flat top-level controller must not be read as if it were the active environment section"
                );
            });
        }

        #[test]
        #[serial]
        fn drivetrain_mode_resolves_to_no_joint_names() {
            with_scratch_project_dir(|project_dir| {
                write_project_tier_config(project_dir, r#"{"dev": {"controller": {"type": "drivetrain"}}}"#);

                assert_eq!(resolve_teleop_joint_names(), Vec::<String>::new());
            });
        }

        #[test]
        #[serial]
        fn absent_controller_resolves_to_no_joint_names() {
            with_scratch_project_dir(|project_dir| {
                write_project_tier_config(project_dir, r#"{"dev": {}}"#);

                assert_eq!(resolve_teleop_joint_names(), Vec::<String>::new());
            });
        }

        #[test]
        #[serial]
        fn no_config_file_at_all_resolves_to_no_joint_names() {
            with_scratch_project_dir(|_project_dir| {
                assert_eq!(resolve_teleop_joint_names(), Vec::<String>::new());
            });
        }

        #[test]
        #[serial]
        fn key_bindings_resolve_from_custom_when_configured() {
            with_scratch_project_dir(|project_dir| {
                write_project_tier_config(
                    project_dir,
                    r#"{"dev": {"custom": {"key_bindings": {"j": "tilt-", "k": "tilt+"}}}}"#,
                );

                let bindings = resolve_teleop_key_bindings();
                assert_eq!(bindings.get("j").map(String::as_str), Some("tilt-"));
                assert_eq!(bindings.get("k").map(String::as_str), Some("tilt+"));
                assert_eq!(bindings.len(), 2);
            });
        }

        #[test]
        #[serial]
        fn key_bindings_default_to_empty_when_absent() {
            with_scratch_project_dir(|project_dir| {
                write_project_tier_config(
                    project_dir,
                    r#"{"dev": {"controller": {"type": "actuator", "joint_names": ["pan"]}}}"#,
                );

                assert!(resolve_teleop_key_bindings().is_empty());
            });
        }
    }
}