nsh-cli 0.6.1

The nsh command line tool: build, package and run apps.
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
//! `nsh test --target`: the apps tests open run on a real platform's
//! development host instead of a headless engine. Each `open` builds the
//! entry, starts a dev server of its own in a test session
//! (`DevServer::test_session`) serving that build, and starts the host on
//! it; the host's test agent (`nsh_testing::agent`) takes the test's steps
//! at the views the selectors name, with the platform's own input. The
//! host goes when the test closes the app. The web's host is a page in a
//! headless browser, whose agent runs in this process (`test_web.rs`).

use std::{
    path::Path,
    process::{Child, Command, Stdio},
    sync::Arc,
    time::{Duration, Instant},
};

use nsh_dev::{
    AppInfo, ClientEvent, DevServer,
    protocol::{LogLevel, WS_PATH},
};
use nsh_testing::{Host, HostOptions, StartHost};

use crate::{build, run::Target, ui};

/// How long a host may take to start and connect.
const CONNECT: Duration = Duration::from_secs(60);

/// Starts the apps tests open on `target`'s host; `browser` is the one
/// `--target web` runs them in (else the one found on this machine); `fps`
/// has the host log its performance monitor's readings; `device` is the iOS
/// simulator (name or UDID); `display` (one-based) is the display the
/// macOS and GPUI hosts open their windows on (by default a secondary one
/// when there is one: [`opens_on_a_display`]); `foreground` lets the apps of the
/// hosts that run them in the background ([`runs_in_background`]) become the
/// active app.
pub(crate) fn starter(
    target: Target,
    browser: Option<&Path>,
    work: &Path,
    fps: bool,
    device: Option<&str>,
    display: Option<usize>,
    foreground: bool,
) -> anyhow::Result<StartHost> {
    if browser.is_some() && target != Target::Web {
        anyhow::bail!("--browser goes with --target web");
    }
    if fps
        && !matches!(
            target,
            Target::Linux | Target::Macos | Target::Windows | Target::Ios
        )
    {
        anyhow::bail!("--fps goes with --target linux, macos, windows or ios");
    }
    if device.is_some() && target != Target::Ios {
        anyhow::bail!("--device goes with --target ios");
    }
    if display.is_some() && !opens_on_a_display(target) {
        anyhow::bail!("{DISPLAY_TARGETS}");
    }
    if foreground && !runs_in_background(target) {
        anyhow::bail!("{FOREGROUND_TARGETS}");
    }
    match target {
        Target::Web => return crate::test_web::starter(browser),
        Target::Ios => return crate::test_ios::starter(work, fps, device),
        Target::Android => return crate::test_android::starter(work),
        _ => {}
    }
    if !matches!(
        target,
        Target::Macos | Target::Linux | Target::Windows | Target::Gpui | Target::Tui
    ) {
        anyhow::bail!(
            "nsh test --target takes macos, linux, windows, gpui, tui, web, ios or android"
        );
    }
    // Built (in a checkout) or found once, before the first test.
    let host = crate::runtime::test_host(target.platform())?;
    Ok(Arc::new(move |entry: &Path, options: &HostOptions| {
        start(target, &host, entry, options, fps, display, foreground)
            .map(|h| Box::new(h) as Box<dyn Host>)
    }))
}

/// Whether `target`'s host runs a test's apps in the background (its
/// `--background`) unless `nsh test --foreground`: they never become the
/// active app, so the keyboard stays with the app the user types in, and
/// the agent's input goes to their windows directly.
pub(crate) fn runs_in_background(target: Target) -> bool {
    matches!(
        target,
        Target::Macos | Target::Windows | Target::Gpui | Target::Linux
    )
}

/// Whether `target`'s host opens a test's windows on the display `nsh test
/// --display` names, else a secondary one when there is one (its
/// `--display`), at the size the test asks for on a smaller one too (its
/// `--keep-window-size`): a test run keeps off the screen in use.
pub(crate) fn opens_on_a_display(target: Target) -> bool {
    matches!(target, Target::Macos | Target::Gpui)
}

/// The error `--display` gives with any other target.
pub(crate) const DISPLAY_TARGETS: &str = "--display goes with --target macos or gpui";

/// The error `--foreground` gives with any other target.
pub(crate) const FOREGROUND_TARGETS: &str =
    "--foreground goes with --target macos, windows, gpui or linux";

/// What `target`'s host honors of `open`'s options, which `open` checks
/// them against: the platform the apps run on there, and whether the host
/// opens them at the size `open` gives (a desktop's window, a browser's
/// page) or they fill a device's screen.
pub(crate) fn host_target(target: Target) -> nsh_testing::HostTarget {
    use nsh_testing::Platform;
    // This machine's desktop: the GPUI and terminal hosts'.
    let desktop = if cfg!(target_os = "macos") {
        Platform::Macos
    } else if cfg!(windows) {
        Platform::Windows
    } else {
        Platform::Linux
    };
    let (name, platform, sized) = match target {
        Target::Ios | Target::Catalyst => ("ios", Platform::Ios, false),
        Target::Android => ("android", Platform::Android, false),
        Target::Macos => ("macos", Platform::Macos, true),
        Target::Windows => ("windows", Platform::Windows, true),
        Target::Linux => ("linux", Platform::Linux, true),
        Target::Web => ("web", Platform::Web, true),
        Target::Gpui => ("gpui", desktop, true),
        // The terminal reports this machine's OS, in the terminal idiom.
        Target::Tui => ("tui", desktop, true),
    };
    let mut host = nsh_testing::HostTarget::default();
    host.name = name.to_owned();
    host.platform = platform;
    host.sized = sized;
    host
}

/// A host running one app for a test.
struct TestHost {
    server: DevServer,
    child: Child,
    /// The app's data directory, fresh for it and removed after it.
    data: std::path::PathBuf,
}

impl Host for TestHost {
    fn step(
        &self,
        step: nsh_dev::protocol::TestStep,
        timeout: Duration,
    ) -> Result<serde_json::Value, String> {
        self.server.step(step, timeout)
    }
}

impl Drop for TestHost {
    fn drop(&mut self) {
        // It quits after the test's `Quit`; a host that does not goes.
        let deadline = Instant::now() + Duration::from_secs(3);
        while Instant::now() < deadline {
            if let Ok(Some(_)) = self.child.try_wait() {
                return;
            }
            std::thread::sleep(Duration::from_millis(20));
        }
        let _ = self.child.kill();
        let _ = self.child.wait();
        let _ = std::fs::remove_dir_all(&self.data);
    }
}

/// Builds `entry`, serves it in a test session and starts `host` on it.
fn start(
    target: Target,
    host: &Path,
    entry: &Path,
    options: &HostOptions,
    fps: bool,
    display: Option<usize>,
    foreground: bool,
) -> Result<TestHost, String> {
    let server = serve(entry, options)?;
    let entry = resolve(entry)?;
    if matches!(
        target,
        Target::Macos | Target::Linux | Target::Windows | Target::Gpui
    ) {
        crate::package::note_hidden_main_window(&entry);
    }
    let dir = entry.parent().unwrap_or(Path::new("."));
    let url = format!("ws://{}{WS_PATH}", server.local_addr());
    // A fresh data directory: what the app keeps (its storage) starts empty
    // in every test, as headless runs' does.
    let data = fresh_data_dir()?;
    let mut command = Command::new(host);
    command
        .env("NSH_DEV_APP_DIR", dir)
        .args(["--dev-server", &url])
        .arg("--data-dir")
        .arg(&data)
        .stdin(Stdio::null());
    if target == Target::Tui {
        command.arg("--headless");
        command.arg("--log-file").arg(data.join("host.log"));
        let config = crate::package::read_config(&entry).map_err(|e| e.to_string())?;
        if let Some(cells) = config.tui.points_per_cell {
            crate::run::parse_points_per_cell(&cells)?;
            command.args(["--points-per-cell", &cells]);
        }
    }
    if fps {
        command.arg("--fps");
    }
    if target == Target::Windows {
        // The window and its notifications show the app's name and icon.
        command.args(crate::windows::host_args(&entry, &dir.join(".nsh")));
    }
    if target == Target::Macos {
        // A window AppKit restored from an earlier run would not be this one.
        command.args(["-ApplePersistenceIgnoreState", "YES"]);
        // As the app runs (`--background` takes precedence): a menu bar app
        // run `--foreground` has no Dock icon either. As `nsh run` does, a
        // test runs as a regular app when `nsh.json` does not read (the
        // keys only packages use are checked there too).
        let config = crate::package::read_config(&entry).unwrap_or_default();
        command.args(config.macos_host_args());
    }
    if opens_on_a_display(target) {
        // Off the main screen, which the user works on: the display
        // `--display` names, else a secondary one when there is one (the
        // host knows the screens).
        let display = display.map_or_else(|| "secondary".to_owned(), |n| n.to_string());
        command.args(["--display", &display]);
        // At the size the test opens the app at, on a display smaller than
        // it too: the window would be fitted to the screen (AppKit shrinks
        // it as it shows it), and the app would lay out in less room than
        // the test expects.
        command.arg("--keep-window-size");
    }
    // Never the active app: the keyboard stays with the app the user types
    // in, and the agent's input goes to the window directly.
    if runs_in_background(target) && !foreground {
        command.arg("--background");
    }
    if target == Target::Gpui && cfg!(target_os = "linux") && std::env::var_os("DISPLAY").is_some()
    {
        // Screenshots read the window from the X server: under X11
        // (Xwayland on a Wayland desktop).
        command.env_remove("WAYLAND_DISPLAY");
    }
    if let Some(size) = options.size {
        command.args([
            "--window-size",
            &format!("{}x{}", size.width.0, size.height.0),
        ]);
    }
    let (mut child, output) =
        ui::quiet(&mut command).map_err(|e| format!("cannot start {}: {e}", host.display()))?;
    let deadline = Instant::now() + CONNECT;
    while !server.has_tester() {
        if let Ok(Some(status)) = child.try_wait() {
            return Err(format!(
                "the host exited with {status} before it connected{}",
                indented(&output.text())
            ));
        }
        if Instant::now() >= deadline {
            let _ = child.kill();
            return Err(format!(
                "the host did not connect in {} s{}",
                CONNECT.as_secs(),
                indented(&output.text())
            ));
        }
        std::thread::sleep(Duration::from_millis(20));
    }
    Ok(TestHost {
        server,
        child,
        data,
    })
}

/// The entry `open` names (a file, or an app's directory: its entry, or
/// for an app of Rust only its `nsh.json`).
fn resolve(entry: &Path) -> Result<std::path::PathBuf, String> {
    crate::entry::resolve(entry).map_err(|e| format!("{e:#}"))
}

/// A dev server in a test session serving `entry`'s build, as `nsh run`
/// serves it (the app's assets, its log lines shown as `nsh run` shows
/// them); for an app of Rust only, the host's own root, which its
/// development host is built with.
pub(crate) fn serve(entry: &Path, options: &HostOptions) -> Result<DevServer, String> {
    let entry = &resolve(entry)?;
    let root = crate::rust_app::is_root(entry);
    let built = if root {
        None
    } else {
        Some(build::compile(entry, false).map_err(|e| e.plain)?)
    };
    // The media files a literal `asset:/` URL names, from where the build
    // named the imported ones: the app's directory, as a package has them.
    let dir = built
        .as_ref()
        .and_then(|built| built.asset_root.clone())
        .unwrap_or_else(|| entry.parent().unwrap_or(Path::new(".")).to_path_buf());
    let trace = options.trace.clone();
    let server = DevServer::start(
        "127.0.0.1:0".parse().expect("an address"),
        nsh_js::BYTECODE_VERSION,
        Some(dir),
        move |event| match event {
            // The app's log lines, as `nsh run` shows them (a traced app's
            // commit timings among them); the host's own coming and going
            // is the test's business.
            ClientEvent::Log(log) => {
                let level = match log.level {
                    LogLevel::Error => log::Level::Error,
                    LogLevel::Warn => log::Level::Warn,
                    LogLevel::Info => log::Level::Info,
                    LogLevel::Debug => log::Level::Debug,
                    LogLevel::Trace => log::Level::Trace,
                };
                crate::logger::forward(level, &log.target, &log.message);
            }
            ClientEvent::Trace { items } => {
                if let Some(trace) = &trace {
                    trace(items);
                }
            }
            _ => {}
        },
    )
    .map_err(|e| format!("cannot start a dev server: {e}"))?;
    server.serve_files(build::crate_assets().map(|a| (a.path, a.source)));
    server.test_session();
    // What the app starts with and what answers its requests: the test's.
    server.set_test_storage(options.storage.clone());
    server.set_test_trace(options.trace.is_some());
    server.set_test_environment(options.environment.clone());
    if let Some(network) = &options.network {
        server.set_test_network(network.clone());
    }
    let Some(built) = built else {
        server.publish_root();
        return Ok(server);
    };
    server.serve_files(
        built
            .assets
            .iter()
            .map(|a| (a.path.clone(), a.source.clone())),
    );
    let capabilities = built.capabilities_json();
    server.publish(
        built.bytecode,
        built.code,
        built.source_map,
        AppInfo {
            capabilities,
            id: crate::package::app_id(entry).ok(),
            window: crate::package::window_json(entry),
        },
        None,
        built.ui_sets,
    );
    Ok(server)
}

/// A data directory of its own for an app a test opens: what the app
/// keeps (its storage) starts empty in every test, as headless runs' does.
pub(crate) fn fresh_data_dir() -> Result<std::path::PathBuf, String> {
    let data = std::env::temp_dir().join(format!(
        "nsh-test-{}-{}",
        std::process::id(),
        NEXT_APP.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
    ));
    std::fs::create_dir_all(&data).map_err(|e| format!("cannot make {}: {e}", data.display()))?;
    Ok(data)
}

/// The apps started so far: each gets a data directory of its own.
static NEXT_APP: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

/// `text` (the host's output) on lines of its own, if there is any.
pub(crate) fn indented(text: &str) -> String {
    if text.trim().is_empty() {
        String::new()
    } else {
        format!(":\n{}", text.trim_end())
    }
}

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

    /// `--foreground` goes with the hosts that run apps in the background:
    /// the other targets refuse it before anything is built or started.
    #[test]
    fn foreground_is_for_the_hosts_that_run_in_the_background() {
        for target in [Target::Tui, Target::Web, Target::Ios, Target::Android] {
            assert!(!runs_in_background(target), "{target:?}");
            let err = starter(target, None, Path::new("."), false, None, None, true).err();
            assert_eq!(
                err.map(|e| e.to_string()).as_deref(),
                Some(FOREGROUND_TARGETS),
                "{target:?}"
            );
        }
        for target in [Target::Macos, Target::Windows, Target::Gpui, Target::Linux] {
            assert!(runs_in_background(target), "{target:?}");
        }
    }

    /// `--display` goes with the hosts that place windows on a display: the
    /// other targets refuse it before anything is built or started.
    #[test]
    fn display_is_for_the_hosts_that_place_windows() {
        for target in [
            Target::Linux,
            Target::Windows,
            Target::Tui,
            Target::Web,
            Target::Ios,
            Target::Android,
        ] {
            assert!(!opens_on_a_display(target), "{target:?}");
            let err = starter(target, None, Path::new("."), false, None, Some(2), false).err();
            assert_eq!(
                err.map(|e| e.to_string()).as_deref(),
                Some(DISPLAY_TARGETS),
                "{target:?}"
            );
        }
        for target in [Target::Macos, Target::Gpui] {
            assert!(opens_on_a_display(target), "{target:?}");
        }
    }

    /// `--device` names an iOS simulator: the other targets refuse it before
    /// anything is built or started.
    #[test]
    fn device_is_for_the_ios_host_only() {
        for target in [
            Target::Macos,
            Target::Linux,
            Target::Windows,
            Target::Gpui,
            Target::Tui,
            Target::Web,
            Target::Android,
        ] {
            let err = starter(
                target,
                None,
                Path::new("."),
                false,
                Some("iPhone 16"),
                None,
                false,
            )
            .err();
            assert_eq!(
                err.map(|e| e.to_string()).as_deref(),
                Some("--device goes with --target ios"),
                "{target:?}"
            );
        }
    }
}