nativeview-cli 0.1.0-rc.1

Developer CLI (`nv`) for Native View Engine: dev hot-reload, builds, pairing, SDK management, app scaffolding, and docs.
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
//! iOS Simulator host shell builder, `.app` bundle packager, and `xcrun simctl` launcher.
//!
//! Layout emitted under `<out_dir>/<Executable>.app`:
//! - `<Executable>`      (real arm64 iOS Simulator Mach-O shell binary, chmod 0755)
//! - `libnv_app.dylib`  (app cdylib with `@executable_path/libnv_app.dylib`, omitted for `--pair-only`)
//! - `Info.plist`        (generated from `nativeview.toml`, linted via `plutil -lint`)
//!
//! Signed bottom-up with ad-hoc `codesign` via [`super::macos_bundle::sign_apple_bundle`].

use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use nativeview_cli::manifest::{ManifestAppInfo, NvManifest};

use super::macos_bundle::{run_checked, set_mode, sign_apple_bundle};
use crate::build::host_cache::{
    cmake_build_args, cmake_build_type, expected_cmake_generator, has_ninja_on_path,
    locate_cmake_shell_binary, modules_cache_key, push_apple_clang_pins, reset_stale_cmake_cache,
};
use crate::cargo_env::{build_artifact, AppContext, ArtifactKind, BuildArtifactSpec, NvSdkRoot};

pub(crate) const IOS_SIM_RUST_TARGET: &str = "aarch64-apple-ios-sim";
pub(crate) const IOS_SIM_CMAKE_TARGET: &str = "nv_ios_shell";

/// Resolved paths inside a packaged iOS Simulator `.app` bundle.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct IosSimBundleOutput {
    pub app_bundle: PathBuf,
    pub executable_path: PathBuf,
    pub dylib_path: Option<PathBuf>,
    pub plist_path: PathBuf,
    pub bundle_id: String,
}

/// Resolved iOS Simulator device entry parsed from `xcrun simctl list devices available -j`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SimDevice {
    pub udid: String,
    pub name: String,
    pub state: String,
    pub runtime: String,
}

/// GUI launcher strategy preserving Xcode 27 `Simulator.app` -> `DeviceHub.app` fallback.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum SimulatorGuiApp {
    SimulatorApp(PathBuf),
    DeviceHubApp(PathBuf),
    OpenByName,
}

/// Shared iOS Simulator host CMake build directory:
/// `<target_dir>/nv-hosts/ios-sim-shell-<profile>-ios<min_ios>-<modules_key>/`.
pub(crate) fn ios_sim_host_cache_dir(
    target_dir: &Path,
    release: bool,
    min_ios: &str,
    modules: &[String],
) -> PathBuf {
    let profile = if release { "release" } else { "debug" };
    let key = modules_cache_key(modules);
    target_dir.join("nv-hosts").join(format!("ios-sim-shell-{profile}-ios{min_ios}-{key}"))
}

pub(crate) fn ios_cargo_env(sdkroot: Option<&str>, min_ios: &str) -> BTreeMap<String, String> {
    let mut env = BTreeMap::new();
    if let Some(root) = sdkroot
        && !root.trim().is_empty()
    {
        env.insert("SDKROOT".to_owned(), root.trim().to_owned());
    }
    env.insert("IPHONEOS_DEPLOYMENT_TARGET".to_owned(), min_ios.to_owned());
    env
}

/// Cargo spec to prebuild `libnv_runtime.a` for an iOS Rust target triple.
pub(crate) fn ios_runtime_staticlib_spec(
    sdk_root: &Path,
    target_dir: &Path,
    rust_triple: &str,
    release: bool,
    sdkroot: Option<&str>,
    min_ios: &str,
) -> BuildArtifactSpec {
    BuildArtifactSpec {
        manifest_path: Some(sdk_root.join("Cargo.toml")),
        working_dir: sdk_root.to_path_buf(),
        package: "nativeview-runtime".to_owned(),
        package_id: String::new(),
        artifact_name: "nv_runtime".to_owned(),
        kind: ArtifactKind::Staticlib,
        crate_type_override: Some("staticlib"),
        target_triple: Some(rust_triple.to_owned()),
        no_default_features: false,
        features: Vec::new(),
        release,
        locked: sdk_root.join("Cargo.lock").is_file(),
        target_dir: Some(target_dir.to_path_buf()),
        env: ios_cargo_env(sdkroot, min_ios),
        expected_suffix: ".a".to_owned(),
    }
}

/// Cargo spec to prebuild `libnv_runtime.a` for `aarch64-apple-ios-sim`.
pub(crate) fn ios_sim_runtime_spec(
    sdk_root: &Path,
    target_dir: &Path,
    release: bool,
    sdkroot: Option<&str>,
    min_ios: &str,
) -> BuildArtifactSpec {
    ios_runtime_staticlib_spec(sdk_root, target_dir, IOS_SIM_RUST_TARGET, release, sdkroot, min_ios)
}

/// Cargo spec to cross-compile the app's `cdylib` for `aarch64-apple-ios-sim`.
pub(crate) fn ios_sim_app_cdylib_spec(
    app: &AppContext,
    release: bool,
    sdkroot: Option<&str>,
    min_ios: &str,
) -> BuildArtifactSpec {
    BuildArtifactSpec {
        manifest_path: Some(app.manifest_path.clone()),
        working_dir: app.manifest_dir.clone(),
        package: app.package_name.clone(),
        package_id: app.package_id.clone(),
        artifact_name: app.lib_name.clone(),
        kind: ArtifactKind::Cdylib,
        crate_type_override: None,
        target_triple: Some(IOS_SIM_RUST_TARGET.to_owned()),
        no_default_features: false,
        features: Vec::new(),
        release,
        locked: app.has_lockfile,
        target_dir: Some(app.target_directory.clone()),
        env: ios_cargo_env(sdkroot, min_ios),
        expected_suffix: ".dylib".to_owned(),
    }
}

/// Deterministic CMake configure args for `hosts/ios-shell` targeting `iphonesimulator` arm64.
pub(crate) fn ios_sim_cmake_configure_args(
    source_dir: &Path,
    build_dir: &Path,
    release: bool,
    modules: &[String],
    prebuilt_runtime_lib: &Path,
    min_ios: &str,
    use_ninja: bool,
) -> Vec<String> {
    let mut args = vec![
        "-S".to_owned(),
        source_dir.display().to_string(),
        "-B".to_owned(),
        build_dir.display().to_string(),
    ];
    if use_ninja {
        args.push("-G".to_owned());
        args.push("Ninja".to_owned());
    }
    args.push("-DCMAKE_SYSTEM_NAME=iOS".to_owned());
    args.push("-DCMAKE_OSX_SYSROOT=iphonesimulator".to_owned());
    args.push("-DCMAKE_OSX_ARCHITECTURES=arm64".to_owned());
    args.push(format!("-DCMAKE_OSX_DEPLOYMENT_TARGET={min_ios}"));
    args.push(format!("-DCMAKE_BUILD_TYPE={}", cmake_build_type(release)));
    args.push("-DNV_SKIP_CODEGEN=ON".to_owned());
    args.push(format!("-DNV_RUNTIME_PREBUILT_LIB={}", prebuilt_runtime_lib.display()));
    args.push("-DNV_HOST_SANITIZE=OFF".to_owned());
    args.push(format!("-DNV_MODULES={}", modules.join(";")));
    push_apple_clang_pins(&mut args);
    args
}

use nativeview_abi::contains_ignore_ascii_case;

fn parse_ios_runtime_version(runtime: &str) -> (u32, u32, u32) {
    let Some(pos) = runtime.find("iOS-") else {
        return (0, 0, 0);
    };
    let mut nums = runtime[pos + 4..]
        .split('-')
        .take_while(|seg| !seg.is_empty() && seg.bytes().all(|b| b.is_ascii_digit()))
        .filter_map(|seg| seg.parse::<u32>().ok());
    (nums.next().unwrap_or(0), nums.next().unwrap_or(0), nums.next().unwrap_or(0))
}

/// Parses `xcrun simctl list devices available -j` JSON and picks a target iOS Simulator device.
///
/// Precedence:
/// - With `query`: exact UDID or name match, then ASCII case-insensitive substring on name; among
///   matches, prefers `Booted` then newest numeric iOS runtime.
/// - Without `query`: newest `Booted` iPhone -> newest `Booted` iOS device (e.g. iPad) ->
///   newest available iPhone -> newest available iOS device.
pub(crate) fn select_simulator_device(
    devices_json: &str,
    query: Option<&str>,
) -> Result<SimDevice, String> {
    let parsed: serde_json::Value = serde_json::from_str(devices_json)
        .map_err(|e| format!("failed to parse `xcrun simctl list` JSON: {e}"))?;
    let map = parsed
        .get("devices")
        .and_then(serde_json::Value::as_object)
        .ok_or_else(|| "`xcrun simctl list` JSON missing `devices` map".to_owned())?;

    let mut candidates: Vec<SimDevice> = Vec::new();
    for (runtime, list) in map {
        if !runtime.contains("iOS") {
            continue;
        }
        let Some(arr) = list.as_array() else {
            continue;
        };
        for dev in arr {
            if !dev.get("isAvailable").and_then(serde_json::Value::as_bool).unwrap_or(false) {
                continue;
            }
            let Some(udid) = dev.get("udid").and_then(serde_json::Value::as_str) else {
                continue;
            };
            let Some(name) = dev.get("name").and_then(serde_json::Value::as_str) else {
                continue;
            };
            let state = dev
                .get("state")
                .and_then(serde_json::Value::as_str)
                .unwrap_or("Shutdown");
            candidates.push(SimDevice {
                udid: udid.to_owned(),
                name: name.to_owned(),
                state: state.to_owned(),
                runtime: runtime.clone(),
            });
        }
    }

    if candidates.is_empty() {
        return Err("no available iOS Simulator devices found (check Xcode Simulator runtimes)".to_owned());
    }
    candidates.sort_by(|a, b| {
        parse_ios_runtime_version(&a.runtime)
            .cmp(&parse_ios_runtime_version(&b.runtime))
            .then_with(|| a.runtime.cmp(&b.runtime))
            .then_with(|| a.name.cmp(&b.name))
    });

    if let Some(raw) = query.map(str::trim).filter(|s| !s.is_empty()) {
        let exact: Vec<&SimDevice> =
            candidates.iter().filter(|d| d.udid == raw || d.name == raw).collect();
        let matches: Vec<&SimDevice> = if !exact.is_empty() {
            exact
        } else {
            candidates.iter().filter(|d| contains_ignore_ascii_case(&d.name, raw)).collect()
        };
        if let Some(booted) = matches.iter().rev().find(|d| d.state == "Booted") {
            return Ok((*booted).clone());
        }
        if let Some(newest) = matches.last() {
            return Ok((*newest).clone());
        }
        return Err(format!("no available iOS Simulator matching '{raw}'"));
    }

    if let Some(booted_iphone) =
        candidates.iter().rev().find(|d| d.state == "Booted" && d.name.contains("iPhone"))
    {
        return Ok(booted_iphone.clone());
    }
    if let Some(booted_any) = candidates.iter().rev().find(|d| d.state == "Booted") {
        return Ok(booted_any.clone());
    }
    if let Some(newest_iphone) = candidates.iter().rev().find(|d| d.name.contains("iPhone")) {
        return Ok(newest_iphone.clone());
    }
    Ok(candidates[candidates.len() - 1].clone())
}

/// Resolves the Simulator GUI app path, preserving the Xcode 27 `Simulator.app` -> `DeviceHub.app`
/// fallback documented in `docs/UPSTREAM.md`.
pub(crate) fn resolve_simulator_gui_app(dev_dir: Option<&Path>) -> SimulatorGuiApp {
    if let Some(dir) = dev_dir {
        let sim_app = dir.join("Applications").join("Simulator.app");
        if sim_app.is_dir() {
            return SimulatorGuiApp::SimulatorApp(sim_app);
        }
        if let Some(parent) = dir.parent() {
            let hub_app = parent.join("Applications").join("DeviceHub.app");
            if hub_app.is_dir() {
                return SimulatorGuiApp::DeviceHubApp(hub_app);
            }
        }
    }
    SimulatorGuiApp::OpenByName
}

fn ensure_ios_sim_target_installed() -> Result<(), String> {
    let out = Command::new("rustup")
        .args(["target", "list", "--installed"])
        .output()
        .map_err(|e| format!("failed to run `rustup target list --installed`: {e}"))?;
    if !out.status.success() {
        return Err(format!(
            "`rustup target list --installed` failed with {}",
            out.status
        ));
    }
    let stdout = String::from_utf8_lossy(&out.stdout);
    if !stdout.lines().any(|l| l.trim() == IOS_SIM_RUST_TARGET) {
        return Err(format!(
            "Rust target '{IOS_SIM_RUST_TARGET}' is not installed. Run: rustup target add {IOS_SIM_RUST_TARGET}"
        ));
    }
    Ok(())
}

pub(crate) fn resolve_apple_sdk(sdk_name: &str) -> Result<String, String> {
    let out = Command::new("xcrun")
        .args(["--sdk", sdk_name, "--show-sdk-path"])
        .output()
        .map_err(|e| format!("failed to run `xcrun --sdk {sdk_name} --show-sdk-path`: {e}"))?;
    if !out.status.success() {
        let stderr = String::from_utf8_lossy(&out.stderr);
        return Err(format!(
            "Apple SDK '{sdk_name}' not available (`xcrun --sdk {sdk_name} --show-sdk-path` failed): {}",
            stderr.trim()
        ));
    }
    let path = String::from_utf8_lossy(&out.stdout).trim().to_owned();
    if path.is_empty() {
        return Err(format!("`xcrun --sdk {sdk_name} --show-sdk-path` returned an empty path"));
    }
    Ok(path)
}

fn resolve_iphonesimulator_sdkroot() -> Result<String, String> {
    resolve_apple_sdk("iphonesimulator")
}

fn ensure_ios_sim_host_shell(
    sdk_root: &NvSdkRoot,
    target_dir: &Path,
    release: bool,
    modules: &[String],
    min_ios: &str,
    sdkroot: &str,
) -> Result<PathBuf, String> {
    let source_dir = sdk_root.path().join("hosts").join("ios-shell");
    if !source_dir.join("CMakeLists.txt").is_file() {
        return Err(format!("missing iOS shell CMakeLists.txt at '{}'", source_dir.display()));
    }

    println!("==> Ensuring generated ABI headers...");
    crate::codegen::ensure_sdk_abi_headers(sdk_root)?;

    let runtime_lib = if sdk_root.is_packaged_sdk() {
        let xcf = crate::cargo_env::sdk::resolve_prebuilt_xcframework(sdk_root)?
            .ok_or_else(|| "packaged SDK missing NvRuntime.xcframework".to_owned())?;
        let sim_lib = xcf.join("ios-arm64_x86_64-simulator/libnv_runtime.a");
        if sim_lib.is_file() {
            sim_lib
        } else {
            return Err(format!(
                "prebuilt NvRuntime.xcframework at '{}' missing ios-arm64_x86_64-simulator/libnv_runtime.a",
                xcf.display()
            ));
        }
    } else {
        println!("==> Prebuilding nativeview-runtime staticlib ({IOS_SIM_RUST_TARGET})...");
        let rt_spec = ios_sim_runtime_spec(sdk_root.path(), target_dir, release, Some(sdkroot), min_ios);
        build_artifact(&rt_spec)?
    };

    let build_dir = ios_sim_host_cache_dir(target_dir, release, min_ios, modules);
    let use_ninja = has_ninja_on_path();
    reset_stale_cmake_cache(&build_dir, &source_dir, expected_cmake_generator(use_ninja))?;

    let cfg_args = ios_sim_cmake_configure_args(
        &source_dir,
        &build_dir,
        release,
        modules,
        &runtime_lib,
        min_ios,
        use_ninja,
    );
    println!(
        "==> Configuring '{IOS_SIM_CMAKE_TARGET}' (modules={}, min_ios={min_ios})...",
        modules_cache_key(modules)
    );
    let cfg_status = Command::new("cmake")
        .args(&cfg_args)
        .status()
        .map_err(|e| format!("failed to run `cmake` configure: {e}"))?;
    if !cfg_status.success() {
        return Err(format!(
            "`cmake` configure for '{IOS_SIM_CMAKE_TARGET}' failed with {cfg_status}"
        ));
    }

    println!("==> Building '{IOS_SIM_CMAKE_TARGET}'...");
    let build_args = cmake_build_args(&build_dir, IOS_SIM_CMAKE_TARGET, release, false);
    let build_status = Command::new("cmake")
        .args(&build_args)
        .status()
        .map_err(|e| format!("failed to run `cmake --build`: {e}"))?;
    if !build_status.success() {
        return Err(format!(
            "`cmake --build` for '{IOS_SIM_CMAKE_TARGET}' failed with {build_status}"
        ));
    }

    locate_cmake_shell_binary(&build_dir, IOS_SIM_CMAKE_TARGET, release, "").ok_or_else(|| {
        format!(
            "CMake build succeeded but '{IOS_SIM_CMAKE_TARGET}' was not found under '{}'",
            build_dir.display()
        )
    })
}

/// Packages `shell_binary` and optional `app_dylib` into a signed iOS Simulator `<Executable>.app`.
pub(crate) fn package_ios_sim_app_bundle(
    out_dir: &Path,
    manifest: &NvManifest,
    info: &ManifestAppInfo,
    shell_binary: &Path,
    app_dylib: Option<&Path>,
) -> Result<IosSimBundleOutput, String> {
    let executable = manifest.resolved_executable(info);
    let bundle_id = manifest.resolved_id(info);
    let app_bundle = out_dir.join(format!("{executable}.app"));

    if app_bundle.exists() {
        fs::remove_dir_all(&app_bundle).map_err(|e| {
            format!("failed to clean previous bundle '{}': {e}", app_bundle.display())
        })?;
    }
    fs::create_dir_all(&app_bundle)
        .map_err(|e| format!("failed to create '{}': {e}", app_bundle.display()))?;

    let executable_path = app_bundle.join(&executable);
    fs::copy(shell_binary, &executable_path).map_err(|e| {
        format!(
            "failed to copy iOS shell binary '{}' -> '{}': {e}",
            shell_binary.display(),
            executable_path.display()
        )
    })?;
    set_mode(&executable_path, 0o755)?;

    let dylib_path = match app_dylib {
        Some(src) => {
            let dest = app_bundle.join("libnv_app.dylib");
            fs::copy(src, &dest).map_err(|e| {
                format!("failed to copy app dylib '{}' -> '{}': {e}", src.display(), dest.display())
            })?;
            set_mode(&dest, 0o755)?;
            run_checked(
                "install_name_tool",
                &[
                    "-id".to_owned(),
                    "@executable_path/libnv_app.dylib".to_owned(),
                    dest.display().to_string(),
                ],
            )?;
            Some(dest)
        }
        None => None,
    };

    let plist_path = app_bundle.join("Info.plist");
    let plist_xml = manifest.emit_ios_sim_info_plist(info);
    fs::write(&plist_path, plist_xml)
        .map_err(|e| format!("failed to write '{}': {e}", plist_path.display()))?;
    run_checked("plutil", &["-lint".to_owned(), plist_path.display().to_string()])?;

    let ent_xml = manifest.emit_ios_entitlements_plist();
    sign_apple_bundle(
        out_dir,
        &app_bundle,
        &executable,
        &bundle_id,
        dylib_path.as_deref(),
        ent_xml.as_deref(),
    )?;

    Ok(IosSimBundleOutput { app_bundle, executable_path, dylib_path, plist_path, bundle_id })
}

/// Full end-to-end iOS Simulator build: prebuilds runtime + app cdylib (unless `pair_only`),
/// builds cached `hosts/ios-shell`, and packages + signs `<Executable>.app`.
pub(crate) fn build_ios_sim_app(
    app: &AppContext,
    sdk_root: &NvSdkRoot,
    manifest: &NvManifest,
    out_dir: &Path,
    release: bool,
    pair_only: bool,
) -> Result<IosSimBundleOutput, String> {
    ensure_ios_sim_target_installed()?;
    let sdkroot = resolve_iphonesimulator_sdkroot()?;
    let min_ios = manifest.apple.min_ios.as_str();

    let dylib = if pair_only {
        println!("==> Skipping app cdylib cross-compile (--pair-only).");
        None
    } else {
        println!("==> Building app cdylib '{}' ({IOS_SIM_RUST_TARGET})...", app.package_name);
        let spec = ios_sim_app_cdylib_spec(app, release, Some(&sdkroot), min_ios);
        Some(build_artifact(&spec)?)
    };

    let shell_bin = ensure_ios_sim_host_shell(
        sdk_root,
        &app.target_directory,
        release,
        &app.host_modules,
        min_ios,
        &sdkroot,
    )?;
    let info = app.manifest_app_info();
    println!("==> Packaging iOS Simulator .app bundle...");
    package_ios_sim_app_bundle(out_dir, manifest, &info, &shell_bin, dylib.as_deref())
}

/// Resolves an iOS Simulator device, boots it, optionally opens Simulator/DeviceHub GUI,
/// installs the `.app` bundle, and launches it via `xcrun simctl`.
pub(crate) fn launch_ios_sim_app(
    app_bundle: &Path,
    bundle_id: &str,
    device_query: Option<&str>,
    headless: bool,
    pair_uri: Option<&str>,
    shell_args: &[String],
) -> Result<(), String> {
    let list_out = Command::new("xcrun")
        .args(["simctl", "list", "devices", "available", "-j"])
        .output()
        .map_err(|e| format!("failed to run `xcrun simctl list`: {e}"))?;
    if !list_out.status.success() {
        let stderr = String::from_utf8_lossy(&list_out.stderr);
        return Err(format!("`xcrun simctl list` failed: {}", stderr.trim()));
    }
    let json = String::from_utf8_lossy(&list_out.stdout);
    let device = select_simulator_device(&json, device_query)?;
    println!("==> Simulator: {} ({}, state={})", device.name, device.udid, device.state);

    if device.state == "Shutdown" {
        run_checked("xcrun", &["simctl".to_owned(), "boot".to_owned(), device.udid.clone()])?;
    }
    run_checked(
        "xcrun",
        &["simctl".to_owned(), "bootstatus".to_owned(), device.udid.clone(), "-b".to_owned()],
    )?;

    if !headless {
        let dev_dir = Command::new("xcode-select")
            .arg("-p")
            .output()
            .ok()
            .filter(|o| o.status.success())
            .map(|o| PathBuf::from(String::from_utf8_lossy(&o.stdout).trim()));
        match resolve_simulator_gui_app(dev_dir.as_deref()) {
            SimulatorGuiApp::SimulatorApp(path) => {
                let _ = Command::new("open")
                    .arg(&path)
                    .args(["--args", "-CurrentDeviceUDID", &device.udid])
                    .status();
            }
            SimulatorGuiApp::DeviceHubApp(path) => {
                let _ = Command::new("open").arg(&path).status();
            }
            SimulatorGuiApp::OpenByName => {
                let ok = Command::new("open")
                    .args(["-a", "Simulator", "--args", "-CurrentDeviceUDID", &device.udid])
                    .status()
                    .map(|s| s.success())
                    .unwrap_or(false);
                if !ok {
                    println!(
                        "note: Simulator GUI app not found; continuing install/launch on booted device {}",
                        device.udid
                    );
                }
            }
        }
    }

    let _ = Command::new("xcrun")
        .args(["simctl", "terminate", &device.udid, bundle_id])
        .output();
    println!("==> Installing {}...", app_bundle.display());
    run_checked(
        "xcrun",
        &[
            "simctl".to_owned(),
            "install".to_owned(),
            device.udid.clone(),
            app_bundle.display().to_string(),
        ],
    )?;

    println!("==> Launching {bundle_id} on {}...", device.name);
    let mut launch = Command::new("xcrun");
    launch.args(["simctl", "launch", &device.udid, bundle_id]).args(shell_args);
    if let Some(uri) = pair_uri {
        launch.env("SIMCTL_CHILD_NV_PAIR_CONNECT", uri);
    }
    let status = launch
        .status()
        .map_err(|e| format!("failed to run `xcrun simctl launch`: {e}"))?;
    if !status.success() {
        return Err(format!("`xcrun simctl launch` failed with {status}"));
    }
    Ok(())
}