mecha10-cli 4.2.15

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
//! Remote/dashboard build flow (LAB-5442, part of "build via mecha10 dashboard", LAB-2153;
//! extended by LAB-5450 with a GitHub-based source): dispatches a build to mecha10-api by
//! cloning a connected GitHub repo server-side (no CLI-side zip at all), then polls until the
//! dispatched build reaches a terminal state.
//!
//! Split out of `handlers/build.rs` (which already orchestrates the local-compile path) so
//! this entirely different flow - no `cargo build` at all, the project is cross-compiled
//! server-side - doesn't get tangled into that function's control flow.

use crate::commands::{BuildSource, BuildTargetArgs};
use crate::context::CliContext;
use crate::handlers::build::BuildTarget;
use crate::services::build_job_client::{self, BuildJobState, GithubConnection};
use crate::services::credentials::CredentialsService;
use crate::ui::prompts::{self, is_interactive_terminal};
use crate::ui::style;
use anyhow::{Context, Result};
use std::time::Duration;

/// Poll interval for the build-job status endpoint (LAB-5440 decision: "poll every 2-5
/// seconds"). Reused for the GitHub-connect wait loop below.
const POLL_INTERVAL: Duration = Duration::from_secs(3);

/// How many [`POLL_INTERVAL`] ticks to wait silently for a GitHub connection to appear before
/// asking the user whether to keep waiting (roughly a minute) - long enough to cover the
/// browser round trip without looking stuck, short enough that a user who closed the browser
/// tab doesn't hang forever.
const GITHUB_CONNECT_POLL_ROUNDS_BEFORE_PROMPT: u32 = 20;

/// Entry point for `mecha10 build <target> --location dashboard` (or its interactive
/// equivalent): dispatch the build to mecha10-api via a connected GitHub repo - see
/// [`resolve_build_source`] - and poll until it finishes. Builds do not pull models
/// (`crate::jobs::build_jobs`'s module doc comment on the server side) - this flow never
/// touches model-handling logic.
pub async fn build_via_dashboard(ctx: &CliContext, target: BuildTarget, args: &BuildTargetArgs) -> Result<()> {
    println!();
    println!("{}", style::heading("☁️  Building via the mecha10 dashboard"));
    println!("{}", style::separator(47));
    println!();

    let project_config = ctx.load_project_config().await?;
    let control_plane_url = project_config.environments.control_plane_url();
    let robot_id = project_config.robot.id.clone();

    let credentials_service = CredentialsService::new();
    let credentials = mecha10_auth::ensure_authenticated_interactive(&credentials_service)
        .await
        .context("Remote builds require you to be logged in")?;

    let (target_platform, target_arch) = platform_arch_for_target(args.target.as_deref());

    println!("Robot ID:        {}", robot_id);
    println!("Target:          {} ({})", target.display_name(), target.as_str());
    println!("Target platform: {}", target_platform);
    println!("Target arch:     {}", target_arch);
    println!();

    let interactive = is_interactive_terminal() && !args.non_interactive;
    let connection = resolve_build_source(args.source, &control_plane_url, &credentials.api_key, interactive).await?;

    println!(
        "Source:          GitHub ({})",
        connection.repo_full_name.as_deref().unwrap_or("?")
    );
    println!();
    style::step("Creating build job from the connected GitHub repo (no zip, no upload)...");
    let created = build_job_client::create_build_job_from_github(build_job_client::CreateBuildJobFromGithubParams {
        control_plane_url: &control_plane_url,
        robot_id: &robot_id,
        connection_id: &connection.id,
        target_platform: &target_platform,
        target_arch: &target_arch,
        config: None,
        api_key: &credentials.api_key,
    })
    .await
    .context("Failed to create build job from GitHub")?;

    println!("{}", style::success(format!("✅ Build job created: {}", created.id)));
    println!();

    poll_until_terminal(&control_plane_url, &robot_id, &created.id, &credentials.api_key).await
}

/// Decide which connected GitHub repo this dashboard build clones (LAB-5450).
///
/// Decision tree:
/// - Check `GET /api/github/connections`. If one with a repo already selected exists, always
///   use it - this is what makes a connected repo the *default* dashboard behavior, not an
///   opt-in.
/// - No usable connection, `--source github`: the caller explicitly asked for GitHub, so
///   prompt to connect one (interactive only); error out if that's not possible
///   (non-interactive) or the user doesn't finish connecting.
/// - No usable connection, `--source auto` (the default) or unset:
///   - Interactive: offer to connect one now; if the user declines (or doesn't finish),
///     surface a clear error.
///   - Non-interactive (e.g. CI, where there's no browser to complete the install flow): hard
///     error - there is no fallback source left.
async fn resolve_build_source(
    explicit: Option<BuildSource>,
    control_plane_url: &str,
    api_key: &str,
    interactive: bool,
) -> Result<GithubConnection> {
    let connections = build_job_client::list_github_connections(control_plane_url, api_key)
        .await
        .context("Failed to check for a connected GitHub repo")?;
    if let Some(connection) = pick_connected_repo(connections) {
        return Ok(connection);
    }

    if matches!(explicit, Some(BuildSource::Github)) {
        return connect_github_interactively(control_plane_url, api_key, interactive)
            .await?
            .ok_or_else(|| {
                anyhow::anyhow!(
                    "No connected GitHub repo, and --source github was requested. Connect a \
                     repo (this requires an interactive terminal) and try again."
                )
            });
    }

    // `explicit` is `None` or `Some(BuildSource::Auto)` here.
    if !interactive {
        return Err(anyhow::anyhow!(
            "A GitHub connection is required to build via the dashboard. Connecting one \
             requires an interactive terminal."
        ));
    }

    connect_github_interactively(control_plane_url, api_key, interactive)
        .await?
        .ok_or_else(|| {
            anyhow::anyhow!(
                "A GitHub connection is required to build via the dashboard without uploading a \
                 zip."
            )
        })
}

/// The first connection (if any) that already has a repo selected - a connection whose repo
/// hasn't been chosen yet (via the dashboard's `PUT /api/github/connections/{id}`) isn't
/// usable for dispatching a build.
fn pick_connected_repo(connections: Vec<GithubConnection>) -> Option<GithubConnection> {
    connections.into_iter().find(|c| c.repo_full_name.is_some())
}

/// Walk the user through connecting a GitHub repo: print the install URL from
/// `POST /api/github/install/start` for them to open in a browser, then poll
/// `GET /api/github/connections` until a usable one appears, letting them cancel instead of
/// hanging forever if they close the tab. Returns `Ok(None)` (never an error) when the user
/// declines up front or gives up while waiting - the caller decides whether that's a hard
/// error or an acceptable fallback.
async fn connect_github_interactively(
    control_plane_url: &str,
    api_key: &str,
    interactive: bool,
) -> Result<Option<GithubConnection>> {
    if !interactive {
        return Ok(None);
    }

    println!("{}", style::warn("⚠️  No connected GitHub repo found."));
    if !prompts::confirm("Connect a GitHub repo now?", true)? {
        return Ok(None);
    }

    let start = build_job_client::start_github_install(control_plane_url, api_key)
        .await
        .context("Failed to start the GitHub App install flow")?;
    println!();
    println!("Open this URL in a browser to connect your GitHub repo:");
    println!("  {}", start.install_url);
    println!();

    loop {
        style::step("Waiting for the connection to complete...");
        for _ in 0..GITHUB_CONNECT_POLL_ROUNDS_BEFORE_PROMPT {
            let connections = build_job_client::list_github_connections(control_plane_url, api_key)
                .await
                .context("Failed to check GitHub connection status")?;
            if let Some(connection) = pick_connected_repo(connections) {
                println!(
                    "{}",
                    style::success(format!(
                        "✅ Connected: {}",
                        connection.repo_full_name.as_deref().unwrap_or("?")
                    ))
                );
                println!();
                return Ok(Some(connection));
            }
            tokio::time::sleep(POLL_INTERVAL).await;
        }

        if !prompts::confirm("Still waiting for the GitHub connection - keep polling?", true)? {
            return Ok(None);
        }
    }
}

/// Derive `(target_platform, target_arch)` for the build-job sidecar fields from an optional
/// cross-compile target triple (`BuildTargetArgs::target`), falling back to the host
/// platform/arch when building for the host. Matches the vocabulary mecha10-api's
/// `catalog::binaries::types::Binary::platform`/`arch` already use (e.g. `linux`/`aarch64`) -
/// the same vocabulary `handlers/upload.rs::detect_arch` targets for local builds.
fn platform_arch_for_target(target_triple: Option<&str>) -> (String, String) {
    match target_triple {
        Some(triple) => {
            let arch = triple.split('-').next().unwrap_or(triple).to_string();
            let platform = if triple.contains("-linux-") {
                "linux"
            } else if triple.contains("-darwin") {
                "macos"
            } else if triple.contains("-windows-") {
                "windows"
            } else {
                "linux"
            };
            (platform.to_string(), arch)
        }
        None => (host_platform(), std::env::consts::ARCH.to_string()),
    }
}

/// Host OS name in the vocabulary `platform_arch_for_target` uses - `std::env::consts::OS`
/// already returns `"linux"`/`"macos"`/`"windows"`, so this only exists to name the mapping
/// at the call site.
fn host_platform() -> String {
    std::env::consts::OS.to_string()
}

/// Poll `GET .../build-jobs/{id}` on [`POLL_INTERVAL`] until the job reaches a terminal
/// state, printing progress whenever it changes. Returns `Err` on a failed build (surfacing
/// the server's `error_message`) so the CLI's exit code reflects the failure.
async fn poll_until_terminal(control_plane_url: &str, robot_id: &str, id: &str, api_key: &str) -> Result<()> {
    let mut last_reported: Option<String> = None;

    loop {
        let job = build_job_client::get_build_job(control_plane_url, robot_id, id, api_key)
            .await
            .context("Failed to poll build job status")?;

        let status_line = format_status_line(&job);
        if last_reported.as_deref() != Some(status_line.as_str()) {
            println!("Status: {}", status_line);
            last_reported = Some(status_line);
        }

        match job.state {
            BuildJobState::Succeeded => {
                println!();
                println!("{}", style::success("✅ Build succeeded!"));
                println!("The binary is now available in the mecha10 binary registry.");
                println!();
                return Ok(());
            }
            BuildJobState::Failed => {
                println!();
                println!("{}", style::error("❌ Build failed"));
                if let Some(msg) = job.error_message.as_deref() {
                    println!("{}", style::error(msg));
                }
                println!();
                return Err(anyhow::anyhow!(
                    "Remote build failed{}",
                    job.error_message
                        .as_deref()
                        .map(|m| format!(": {m}"))
                        .unwrap_or_default()
                ));
            }
            BuildJobState::Pending | BuildJobState::Running => {
                tokio::time::sleep(POLL_INTERVAL).await;
            }
        }
    }
}

/// Human-readable one-line status for a poll response - `<state>` optionally followed by
/// ` - <progress_message>`. Split out so the "only print when it changes" dedup logic in
/// [`poll_until_terminal`] is comparing a plain string, and so this formatting is
/// unit-testable without a network call.
fn format_status_line(job: &build_job_client::BuildJob) -> String {
    let state_label = match job.state {
        BuildJobState::Pending => "pending",
        BuildJobState::Running => "running",
        BuildJobState::Succeeded => "succeeded",
        BuildJobState::Failed => "failed",
    };

    match job.progress_message.as_deref() {
        Some(message) if !message.is_empty() => format!("{state_label} - {message}"),
        _ => state_label.to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::{Read, Write};

    fn connection(id: &str, repo_full_name: Option<&str>) -> GithubConnection {
        GithubConnection {
            id: id.to_string(),
            repo_full_name: repo_full_name.map(str::to_string),
        }
    }

    #[test]
    fn pick_connected_repo_returns_none_when_list_is_empty() {
        assert!(pick_connected_repo(Vec::new()).is_none());
    }

    #[test]
    fn pick_connected_repo_skips_connections_without_a_repo_selected() {
        let connections = vec![connection("conn-1", None), connection("conn-2", None)];
        assert!(pick_connected_repo(connections).is_none());
    }

    #[test]
    fn pick_connected_repo_returns_the_first_with_a_repo_selected() {
        let connections = vec![
            connection("conn-1", None),
            connection("conn-2", Some("mecha-industries/mecha10")),
        ];
        let picked = pick_connected_repo(connections).unwrap();
        assert_eq!(picked.id, "conn-2");
        assert_eq!(picked.repo_full_name, Some("mecha-industries/mecha10".to_string()));
    }

    /// Minimal fake HTTP server, same pattern as `build_job_client`'s test helper - these
    /// tests only need `GET /api/github/connections` to return a fixed body, never GitHub
    /// install/build-job endpoints, since `resolve_build_source`'s non-interactive branches
    /// never reach those.
    fn start_fake_server(response_body: String) -> String {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();

        std::thread::spawn(move || {
            for stream in listener.incoming() {
                let mut stream = match stream {
                    Ok(s) => s,
                    Err(_) => continue,
                };
                let mut buf = [0u8; 65536];
                let _ = stream.read(&mut buf);
                let header = format!(
                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                    response_body.len()
                );
                let _ = stream.write_all(header.as_bytes());
                let _ = stream.write_all(response_body.as_bytes());
                let _ = stream.flush();
            }
        });

        format!("http://{}", addr)
    }

    #[tokio::test]
    async fn resolve_build_source_uses_github_when_a_connected_repo_exists() {
        let body = serde_json::json!({
            "connections": [{
                "id": "conn-1",
                "installation_id": 1,
                "account_login": "mecha-industries",
                "repo_full_name": "mecha-industries/mecha10",
                "created_at": "2024-01-01T00:00:00Z",
                "updated_at": "2024-01-01T00:00:00Z"
            }],
            "total": 1
        })
        .to_string();
        let url = start_fake_server(body);

        let connection = resolve_build_source(None, &url, "key", false).await.unwrap();
        assert_eq!(connection.repo_full_name, Some("mecha-industries/mecha10".to_string()));
    }

    #[tokio::test]
    async fn resolve_build_source_errors_when_non_interactive_with_no_connection() {
        let url = start_fake_server(serde_json::json!({"connections": [], "total": 0}).to_string());

        let err = resolve_build_source(None, &url, "key", false).await.unwrap_err();
        assert!(err.to_string().contains("GitHub connection is required"));
    }

    #[tokio::test]
    async fn resolve_build_source_errors_when_auto_and_non_interactive_with_no_connection() {
        let url = start_fake_server(serde_json::json!({"connections": [], "total": 0}).to_string());

        let err = resolve_build_source(Some(BuildSource::Auto), &url, "key", false)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("GitHub connection is required"));
    }

    #[tokio::test]
    async fn resolve_build_source_errors_when_source_github_and_non_interactive_with_no_connection() {
        let url = start_fake_server(serde_json::json!({"connections": [], "total": 0}).to_string());

        let err = resolve_build_source(Some(BuildSource::Github), &url, "key", false)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("--source github was requested"));
    }

    #[test]
    fn platform_arch_for_target_falls_back_to_host_when_no_triple_given() {
        let (platform, arch) = platform_arch_for_target(None);
        assert_eq!(platform, std::env::consts::OS);
        assert_eq!(arch, std::env::consts::ARCH);
    }

    #[test]
    fn platform_arch_for_target_parses_a_linux_gnu_triple() {
        let (platform, arch) = platform_arch_for_target(Some("aarch64-unknown-linux-gnu"));
        assert_eq!(platform, "linux");
        assert_eq!(arch, "aarch64");
    }

    #[test]
    fn platform_arch_for_target_parses_a_linux_musl_triple() {
        let (platform, arch) = platform_arch_for_target(Some("x86_64-unknown-linux-musl"));
        assert_eq!(platform, "linux");
        assert_eq!(arch, "x86_64");
    }

    #[test]
    fn platform_arch_for_target_parses_a_darwin_triple() {
        let (platform, arch) = platform_arch_for_target(Some("aarch64-apple-darwin"));
        assert_eq!(platform, "macos");
        assert_eq!(arch, "aarch64");
    }

    fn job(state: BuildJobState, progress: Option<&str>) -> build_job_client::BuildJob {
        build_job_client::BuildJob {
            state,
            error_message: None,
            progress_message: progress.map(str::to_string),
        }
    }

    #[test]
    fn format_status_line_without_progress_message_is_just_the_state() {
        assert_eq!(format_status_line(&job(BuildJobState::Pending, None)), "pending");
    }

    #[test]
    fn format_status_line_appends_a_non_empty_progress_message() {
        assert_eq!(
            format_status_line(&job(BuildJobState::Running, Some("compiling"))),
            "running - compiling"
        );
    }

    #[test]
    fn format_status_line_ignores_an_empty_progress_message() {
        assert_eq!(format_status_line(&job(BuildJobState::Running, Some(""))), "running");
    }
}