nsh-cli 0.5.0

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
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
use std::{
    fs,
    path::{Path, PathBuf},
    process::{Command, Stdio},
};

use anyhow::{Context as _, bail};
use nsh_core::js::HostLimits;
use serde::Deserialize;

use crate::{dev::DevSession, runtime::Platform, ui};

const APP_NAME: &str = "NshDev";
pub(crate) const BUNDLE_ID: &str = "com.longbridge.nsh.host";

/// Where `nsh dev` and `nsh run` run the app.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub(crate) enum Target {
    /// The Mac Catalyst development host (an iPhone-sized window).
    Catalyst,
    /// The development host in an iOS simulator.
    Ios,
    /// The development host on an Android device or emulator.
    Android,
    /// The Linux (GTK) development host, in a window on this machine.
    Linux,
    /// The macOS (AppKit) development host, in a window on this machine.
    Macos,
    /// The Windows development host, in a window on this machine.
    Windows,
    /// The web development host, in the browser (the dev server serves its
    /// page).
    Web,
    /// The GPUI development host, in a window on this machine (macOS,
    /// Windows or Linux): the app as GPUI apps that embed it show it.
    Gpui,
    /// The development host in this terminal.
    Tui,
}

impl Target {
    /// Whether the dev server listens on every interface for this target,
    /// or on loopback only. Phones open the web page at the LAN address
    /// and a device's host may be on the network; a desktop window, the
    /// terminal and Catalyst connect on this machine.
    pub(crate) fn uses_network(self) -> bool {
        matches!(self, Target::Ios | Target::Android | Target::Web)
    }

    /// The default: this system’s native desktop host (AppKit on macOS,
    /// GTK on Linux, Win32 on Windows; the browser elsewhere).
    pub(crate) fn native() -> Target {
        if cfg!(target_os = "macos") {
            Target::Macos
        } else if cfg!(target_os = "linux") {
            Target::Linux
        } else if cfg!(windows) {
            Target::Windows
        } else {
            Target::Web
        }
    }

    pub(crate) fn platform(self) -> crate::runtime::Platform {
        match self {
            Target::Catalyst => crate::runtime::Platform::MacCatalyst,
            Target::Linux => crate::runtime::Platform::Linux,
            Target::Macos => crate::runtime::Platform::MacOs,
            Target::Windows => crate::runtime::Platform::Windows,
            Target::Gpui => crate::runtime::Platform::Gpui,
            Target::Tui => crate::runtime::Platform::Tui,
            Target::Ios | Target::Android | Target::Web => {
                crate::runtime::Platform::IphoneSimulator
            }
        }
    }
}

/// How the development host runs the app and what it shows besides it.
#[derive(Debug, Clone)]
pub(crate) struct HostFlags {
    /// The VM limits an embedding app would set (`--limits`); `None`: none,
    /// as an app on its own.
    pub(crate) limits: Option<HostLimits>,
    /// Log per-commit timings.
    pub(crate) trace: bool,
    /// The selected host's performance monitor.
    pub(crate) fps: bool,
    /// Terminal Cell dimensions, overriding nsh.json.
    pub(crate) points_per_cell: Option<String>,
}

/// The host window's own options: the desktop hosts take the size
/// ([`HostWindow::check`]), the macOS host the name and the display too.
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct HostWindow<'a> {
    /// The app's name in the host (the menu bar, the window title).
    pub(crate) name: Option<&'a str>,
    /// The window's initial size, `WxH` in points.
    pub(crate) size: Option<&'a str>,
    /// The display the window opens on, from 1 (the primary display).
    pub(crate) display: Option<usize>,
}

impl HostWindow<'_> {
    /// Refuses the options `target`'s host does not take. An app of Rust
    /// only (`rust_root`) runs in its runner on macOS, Linux and Windows;
    /// GPUI has no runner (it is the backend for embedding in GPUI apps),
    /// so such an app does not run there at all.
    fn check(&self, target: Target, rust_root: bool) -> anyhow::Result<()> {
        if rust_root && target == Target::Gpui {
            bail!(
                "a Rust app runs on this OS's own backend (--target macos, linux or windows); \
                 GPUI apps embed its root with AppView"
            );
        }
        let desktop = matches!(
            target,
            Target::Macos | Target::Linux | Target::Windows | Target::Gpui
        );
        if self.name.is_some() && (target != Target::Macos || rust_root) {
            bail!(
                "--name needs --target macos and a TSX entry (the other hosts do not take it yet)"
            );
        }
        if self.display.is_some() && (target != Target::Macos || rust_root) {
            bail!(
                "--display needs --target macos and a TSX entry (the other hosts do not take it yet)"
            );
        }
        if self.size.is_some() && (!desktop || rust_root) {
            bail!(
                "--window-size needs a desktop host (--target macos, linux, windows or gpui) and a TSX entry"
            );
        }
        Ok(())
    }

    /// The arguments of the size and the display, for a desktop host.
    fn args(&self) -> Vec<String> {
        let mut args = Vec::new();
        if let Some(size) = self.size {
            // `WxH` in points; the host opens the window at this size.
            args.extend(["--window-size".to_owned(), size.to_owned()]);
        }
        if let Some(display) = self.display {
            // One-based, as the host counts them.
            args.extend(["--display".to_owned(), display.to_string()]);
        }
        args
    }
}

/// Starts a dev session and runs the app in a development host, which
/// loads bundles from the dev server and reloads on change.
pub(crate) fn run(
    entry: &Path,
    listen: crate::dev::Listen,
    release: bool,
    flags: HostFlags,
    target: Target,
    device: Option<&str>,
    window: HostWindow<'_>,
) -> anyhow::Result<()> {
    let HostFlags {
        limits,
        trace,
        fps,
        points_per_cell,
    } = flags;
    if points_per_cell.is_some() && target != Target::Tui {
        bail!("--points-per-cell needs --target tui");
    }
    if fps
        && !matches!(
            target,
            Target::Macos | Target::Linux | Target::Ios | Target::Windows | Target::Tui
        )
    {
        bail!(
            "--fps needs --target macos, linux, windows, ios or tui (the other hosts have no performance monitor yet)"
        );
    }
    window.check(target, crate::rust_app::is_root(entry))?;
    if matches!(
        target,
        Target::Macos | Target::Linux | Target::Windows | Target::Gpui
    ) {
        crate::package::note_hidden_main_window(entry);
    }
    if release {
        // The app's crates and NSH's in the host, optimized as in a
        // package: a debug host measures debug code.
        crate::rust_app::set_release_hosts();
    }
    let work = dunce::canonicalize(entry)?
        .parent()
        .context("entry has no directory")?
        .join(".nsh");
    if target == Target::Tui {
        return run_tui(
            entry,
            listen,
            release,
            HostFlags {
                limits,
                trace,
                fps,
                points_per_cell,
            },
            &work,
        );
    }
    if crate::rust_app::is_root(entry) {
        return run_rust_app(entry, listen, target, device, &work);
    }
    if target == Target::Android {
        return run_android(entry, listen, release, limits, &work, trace);
    }
    if target == Target::Web {
        return run_web(entry, listen, release, limits);
    }
    // The host a previous session left running would connect to this one
    // until it is replaced.
    let udid = match target {
        Target::Ios => {
            let udid = simulator(device)?;
            let _ = simctl(&["terminate", &udid, BUNDLE_ID]);
            Some(udid)
        }
        Target::Catalyst
        | Target::Android
        | Target::Linux
        | Target::Macos
        | Target::Windows
        | Target::Web
        | Target::Gpui
        | Target::Tui => None,
    };
    // The host it starts connects by itself: no addresses to show.
    let session = DevSession::start(entry, listen, release, limits)?;
    let host = crate::runtime::file(target.platform(), false)?;
    let mut args = vec!["--dev-server".to_owned(), session.local_url()];
    if trace {
        args.push("--trace".to_owned());
    }
    if fps {
        args.push("--fps".to_owned());
    }
    match target {
        Target::Catalyst => {
            let app = package_catalyst(&work, &host)?;
            let exe = app.join("Contents/MacOS/nsh-ios-host");
            // Its own output (AppKit's notes) is kept for when it fails.
            let mut command = Command::new(&exe);
            command.env("NSH_DEV_APP_DIR", work.parent().expect("source directory"));
            command
                .args(&args)
                // A host that crashed must not ask to reopen its windows
                // next time (a modal dialog that blocks the window).
                .args(["-ApplePersistenceIgnoreState", "YES"]);
            run_local(&session, &mut command, "the Mac Catalyst host")
        }
        // Run in place: unlike Catalyst's, the GTK host needs no app
        // bundle around it.
        Target::Linux => {
            let mut command = Command::new(&host);
            command.env("NSH_DEV_APP_DIR", work.parent().expect("source directory"));
            command
                .args(&args)
                .args(["--app-id", &crate::package::app_id(entry)?])
                .args(window.args());
            let schemes = crate::package::read_config(entry)?.schemes;
            if !schemes.is_empty() {
                command.args(["--schemes", &schemes.join(",")]);
            }
            run_local(&session, &mut command, "the Linux host")
        }
        // In place too: the AppKit host makes itself a regular app (menu
        // bar, Dock icon) without an app bundle around it, or the menu bar
        // app `nsh.json` `macos.activationPolicy` says, from the start.
        Target::Macos => {
            // The menu bar and the window show the app's name; `--name`
            // overrides it (a host run for one of the app's windows can
            // name itself).
            let entry = entry.canonicalize()?;
            let config = crate::package::read_config(&entry).unwrap_or_default();
            let (app_name, id) = crate::package::name_and_id(&entry, &config);
            let name = window.name.unwrap_or(&app_name);
            let mut command = Command::new(&host);
            command.env("NSH_DEV_APP_DIR", work.parent().expect("source directory"));
            command
                .args(&args)
                .args(["--name", name, "--app-id", &id])
                .args(["-ApplePersistenceIgnoreState", "YES"])
                .args(config.macos.host_args())
                .args(window.args());
            run_local(&session, &mut command, "the macOS host")
        }
        Target::Windows => {
            let mut command = Command::new(&host);
            command.env("NSH_DEV_APP_DIR", work.parent().expect("source directory"));
            command
                .args(&args)
                .args(["--app-id", &crate::package::app_id(entry)?])
                .args(crate::windows::host_args(entry, &work))
                .args(window.args());
            run_local(&session, &mut command, "the Windows host")
        }
        // In place on every OS: GPUI makes the process a regular app (on
        // macOS too) without an app bundle around it.
        Target::Gpui => {
            let mut command = Command::new(&host);
            command.env("NSH_DEV_APP_DIR", work.parent().expect("source directory"));
            command
                .args(&args)
                .args(["--app-id", &crate::package::app_id(entry)?])
                .args(window.args());
            run_local(&session, &mut command, "the GPUI host")
        }
        Target::Ios => {
            let app = package_ios(&work, &host)?;
            let udid = udid.expect("the simulator is picked before the session");
            let step = ui::Step::start("installing the development host in the simulator");
            simctl(&["install", &udid, &app.to_string_lossy()])?;
            step.finish();
            let mut launch = vec!["launch", "--terminate-running-process", &udid, BUNDLE_ID];
            launch.extend(args.iter().map(String::as_str));
            let env = simctl_app_env(&crate::package::read_config(entry)?);
            let step = ui::Step::start("launching the development host");
            simctl_with_env(&launch, &env)?;
            step.finish();
            // The simulator shares the Mac's network: 127.0.0.1 is the dev
            // server, so a host left running would join the next session
            // of any app: Ctrl-C stops it too.
            let stoppable = ui::Stoppable::new();
            let result = session.watch(|| Ok(false));
            let _ = simctl(&["terminate", &udid, BUNDLE_ID]);
            drop(stoppable);
            result
        }
        Target::Android | Target::Web | Target::Tui => unreachable!("handled above"),
    }
}

/// Starts a dev session that serves the web host and prints its address;
/// every browser that opens the page (on this machine or, at the LAN
/// address, on a phone) runs the app until the session ends. The browser
/// is the user's to open: a session that starts again (the app's Rust code
/// changed) finds its page still open, and it reloads by itself.
fn run_web(
    entry: &Path,
    listen: crate::dev::Listen,
    release: bool,
    limits: Option<HostLimits>,
) -> anyhow::Result<()> {
    // Built first in a checkout: the session serves the runtime it finds.
    crate::runtime::web(crate::runtime::WebKind::Dev, true)?.context("no web runtime")?;
    let session = DevSession::start(entry, listen, release, limits)?;
    session.print_web_url();
    session.watch(|| Ok(false))
}

/// Runs a Rust app (`nsh.json` `"root"`): its own runner, with no JS
/// runtime, mounts its root. Desktops run the debug runner in place (its
/// output in this terminal), Catalyst in an app bundle, the iOS simulator
/// and Android a package of it, the web the dev server's page. A change to
/// the app's Rust code ends the command with [`crate::rust_app::Restart`]:
/// `nsh` builds it again and runs it anew.
fn run_rust_app(
    entry: &Path,
    listen: crate::dev::Listen,
    target: Target,
    device: Option<&str>,
    work: &Path,
) -> anyhow::Result<()> {
    let app =
        crate::rust_app::current().context("nsh.json: \"root\" needs \"rust\", the app's crate")?;
    let entry = dunce::canonicalize(entry)?;
    let config = crate::package::read_config(&entry)?;
    let (name, id) = crate::package::name_and_id(&entry, &config);
    let built = crate::build::rust_root();
    // The package's `nsh` directory for the runners that run in place:
    // the crates' assets and the window's name, id, appearance and
    // activation policy.
    let resources = |dir: &Path| -> anyhow::Result<()> {
        if dir.exists() {
            fs::remove_dir_all(dir)?;
        }
        for asset in &built.assets {
            let dest = dir.join("assets").join(&asset.path);
            fs::create_dir_all(dest.parent().context("asset dir")?)?;
            fs::copy(&asset.source, &dest).with_context(|| format!("copy {}", asset.path))?;
        }
        fs::create_dir_all(dir)?;
        let mut info = serde_json::json!({ "name": name, "id": id });
        if let Some(appearance) = &config.appearance {
            info["appearance"] = appearance.as_str().into();
        }
        // A menu bar app on macOS (the other runners leave it).
        config.macos.add_to_app_json(&mut info);
        config.add_file_types_to_app_json(&mut info);
        // The main window's launch options, as a package's `app.json`.
        if let Some(window) = &config.window {
            info["window"] = window.clone();
        }
        fs::write(dir.join("app.json"), info.to_string())?;
        Ok(())
    };
    let run = work.join("rust");
    match target {
        Target::Linux | Target::Macos | Target::Windows => {
            let runner = crate::runtime::file(target.platform(), false)?;
            let dir = run.join("run/nsh");
            resources(&dir)?;
            let mut command = Command::new(&runner);
            command.env("NSH_APP_DIR", &dir);
            if cfg!(target_os = "macos") {
                // A runner that crashed must not ask to reopen its windows.
                command.args(["-ApplePersistenceIgnoreState", "YES"]);
            }
            ui::done(format!(
                "running {name} ({})",
                ui::dim("Rust, no JS runtime")
            ));
            run_rust_local(&app, &mut command)
        }
        Target::Catalyst => {
            let runner = crate::runtime::file(Platform::MacCatalyst, false)?;
            let bundle = package_catalyst(&run.join("catalyst"), &runner)?;
            let macos = bundle.join("Contents/MacOS");
            // The iOS runner looks next to itself.
            resources(&macos.join("nsh"))?;
            let mut command = Command::new(macos.join("nsh-ios-host"));
            command
                .env("NSH_DEVELOPMENT", "1")
                .args(["-ApplePersistenceIgnoreState", "YES"]);
            ui::done(format!(
                "running {name} ({})",
                ui::dim("Rust, no JS runtime")
            ));
            run_rust_local(&app, &mut command)
        }
        Target::Ios => {
            let udid = simulator(device)?;
            let env = simctl_app_env(&config);
            let out = run.join("ios");
            package_for_run(
                &entry,
                crate::package::PackageTarget::IosSimulator,
                &out,
                config,
                &[],
            )?;
            let bundle = out.join(format!("{name}.app"));
            let step = ui::Step::start(format!("installing {id} in the simulator"));
            simctl(&["install", &udid, &bundle.to_string_lossy()])?;
            step.finish();
            // Its output (the app's logs) in this terminal while it runs.
            let mut command = Command::new("xcrun");
            command
                .args([
                    "simctl",
                    "launch",
                    "--console-pty",
                    "--terminate-running-process",
                ])
                .args([&udid, &id])
                .envs(env)
                .env("SIMCTL_CHILD_NSH_DEVELOPMENT", "1");
            let result = run_rust_local(&app, &mut command);
            let _ = simctl(&["terminate", &udid, &id]);
            result
        }
        Target::Android => {
            use crate::android;
            let sdk = android::Sdk::find()?;
            let serial = android::device(&sdk)?;
            let out = run.join("android");
            // The device's ABI alone: each one is a build of the app's crate.
            let abi = android::device_abis(&sdk, &serial)?
                .into_iter()
                .find(|abi| android::ABIS.contains(&abi.as_str()))
                .with_context(|| format!("{serial} runs none of {}", android::ABIS.join(", ")))?;
            package_for_run(
                &entry,
                crate::package::PackageTarget::Android,
                &out,
                config,
                std::slice::from_ref(&abi),
            )?;
            let apk = out.join(format!("{name}.apk"));
            let step = ui::Step::start(format!("installing {id} on {serial}"));
            android::adb(&sdk, &serial, &["install", "-r", &apk.to_string_lossy()])?;
            android::adb(
                &sdk,
                &serial,
                &[
                    "shell",
                    "am",
                    "start",
                    "-S",
                    "-n",
                    &format!("{id}/com.longbridge.nsh.AppActivity"),
                ],
            )?;
            step.done(format!("launched {id} on {serial}"));
            let _stoppable = ui::Stoppable::new();
            let result = app.watch(|| Ok(false));
            let _ = android::adb(&sdk, &serial, &["shell", "am", "force-stop", &id]);
            result
        }
        Target::Web => {
            crate::runtime::web(crate::runtime::WebKind::Dev, true)?.context("no web runtime")?;
            let session = DevSession::start(&entry, listen, false, None)?;
            session.print_web_url();
            session.watch(|| Ok(false))
        }
        Target::Gpui | Target::Tui => unreachable!("handled before Rust runner selection"),
    }
}

/// Packages the Rust app at `entry` for `target` into `out` (as `nsh
/// package` does), for `nsh run` to install; Android: for `abis`.
fn package_for_run(
    entry: &Path,
    target: crate::package::PackageTarget,
    out: &Path,
    config: crate::package::AppConfig,
    abis: &[String],
) -> anyhow::Result<()> {
    crate::package::package(crate::package::PackageOptions {
        entry,
        target,
        out,
        config,
        sign: None,
        profile: None,
        keystore: None,
        abis,
        format: crate::android::Format::Apk,
        arch: None,
        run: false,
        asset_url: None,
    })
}

/// Runs `command` (a Rust app's runner, its output in this terminal) until
/// it ends or the app's Rust code changes.
fn run_rust_local(app: &crate::rust_app::RustApp, command: &mut Command) -> anyhow::Result<()> {
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt as _;
        command.creation_flags(windows_sys::Win32::System::Threading::CREATE_NEW_PROCESS_GROUP);
    }
    let mut child = command
        .stdin(Stdio::null())
        .spawn()
        .with_context(|| format!("launch {}", command.get_program().to_string_lossy()))?;
    #[cfg(windows)]
    let _job = KillOnClose::assign(&child);
    let stoppable = ui::Stoppable::new();
    let result = app.watch(|| match child.try_wait()? {
        Some(status) if status.success() => Ok(true),
        Some(status) => bail!("the app exited with {status}"),
        None => Ok(false),
    });
    let _ = child.kill();
    let _ = child.wait();
    drop(stoppable);
    result
}

/// Checks the terminal scale at the CLI/configuration boundary.
pub(crate) fn parse_points_per_cell(value: &str) -> Result<String, String> {
    let valid = value.split_once('x').is_some_and(|(width, height)| {
        [width, height]
            .into_iter()
            .all(|part| part.parse::<f32>().is_ok_and(|n| n.is_finite() && n > 0.0))
    });
    if !valid {
        return Err("points per Cell must be WIDTHxHEIGHT with finite, positive dimensions".into());
    }
    Ok(value.to_owned())
}

fn run_tui(
    entry: &Path,
    listen: crate::dev::Listen,
    release: bool,
    flags: HostFlags,
    work: &Path,
) -> anyhow::Result<()> {
    let HostFlags {
        limits,
        trace,
        fps,
        points_per_cell,
    } = flags;
    let config = crate::package::read_config(entry)?;
    let cells = points_per_cell
        .as_deref()
        .or(config.tui.points_per_cell.as_deref())
        .unwrap_or("8x16");
    parse_points_per_cell(cells).map_err(anyhow::Error::msg)?;
    fs::create_dir_all(work)?;
    let path = work.join("tui.log");
    let building = ui::Step::start(format!("building {}", ui::path(entry)));
    let session = DevSession::start(entry, listen, release, limits)?;
    building.finish();
    // A Rust root also uses the development host, which receives the Root event.
    let host = crate::runtime::test_host(Platform::Tui)?;
    // Preparation stays visible until the host takes over the terminal. From
    // here, diagnostics belong in the panel so they cannot overwrite its UI.
    let _terminal_logs = ui::LogFile::open(&path)?;
    let diagnostics = fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&path)?;
    let mut command = Command::new(host);
    command
        .env("NSH_DEV_APP_DIR", work.parent().context("app directory")?)
        .args([
            "--dev-server",
            &session.local_url(),
            "--points-per-cell",
            cells,
        ])
        .arg("--log-file")
        .arg(&path)
        .stdin(Stdio::inherit())
        .stdout(Stdio::inherit())
        .stderr(diagnostics);
    if fps {
        command.arg("--fps");
    }
    if trace {
        command.arg("--trace");
    }
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt as _;
        command.creation_flags(windows_sys::Win32::System::Threading::CREATE_NEW_PROCESS_GROUP);
    }
    let _stoppable = ui::Stoppable::new();
    let mut child = command
        .spawn()
        .context("launch the terminal development host")?;
    #[cfg(windows)]
    let _job = KillOnClose::assign(&child);
    let result = session.watch(|| match child.try_wait()? {
        Some(status) if status.success() => Ok(true),
        Some(status) => bail!(
            "the terminal host exited with {status}; see {}",
            path.display()
        ),
        None => Ok(false),
    });
    if !matches!(child.try_wait(), Ok(Some(_))) {
        // Let the host leave raw mode and the alternate screen before ending it.
        #[cfg(unix)]
        // SAFETY: this is the live child owned by this invocation.
        unsafe {
            libc::kill(child.id() as libc::pid_t, libc::SIGTERM);
        }
        #[cfg(windows)]
        // SAFETY: the child was started in its own console process group.
        unsafe {
            windows_sys::Win32::System::Console::GenerateConsoleCtrlEvent(
                windows_sys::Win32::System::Console::CTRL_BREAK_EVENT,
                child.id(),
            );
        }
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
        while matches!(child.try_wait(), Ok(None)) && std::time::Instant::now() < deadline {
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        if !matches!(child.try_wait(), Ok(Some(_))) {
            let _ = child.kill();
        }
    }
    let _ = child.wait();
    result
}

/// Runs `command`, a host in a window on this machine, until its window
/// closes or the session ends; `what` names it when it fails.
fn run_local(session: &DevSession, command: &mut Command, what: &str) -> anyhow::Result<()> {
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt as _;
        // Out of the console's Ctrl-C: this command stops the host itself,
        // so that a stop is not taken for the host failing.
        command.creation_flags(windows_sys::Win32::System::Threading::CREATE_NEW_PROCESS_GROUP);
    }
    // Its own output is kept for when it fails.
    let (mut child, output) = ui::quiet(command)
        .with_context(|| format!("launch {}", command.get_program().to_string_lossy()))?;
    // Windows ends a child with its parent only in a job: the host goes
    // with this command however it ends (closed console, killed).
    #[cfg(windows)]
    let _job = KillOnClose::assign(&child);
    // A host left running would open a second window next time: Ctrl-C and
    // SIGTERM close it too.
    let stoppable = ui::Stoppable::new();
    let result = session.watch(|| match child.try_wait()? {
        Some(status) if status.success() => Ok(true),
        Some(status) => Err(ui::failure(
            format!("{what} exited with {status}"),
            output.text(),
        )),
        None => Ok(false),
    });
    let _ = child.kill();
    let _ = child.wait();
    drop(stoppable);
    result
}

/// A job object that ends its processes when it closes: when dropped, or
/// with this process, however it ends.
#[cfg(windows)]
pub(crate) struct KillOnClose(windows_sys::Win32::Foundation::HANDLE);

#[cfg(windows)]
impl KillOnClose {
    /// Puts `child` in a new such job; `None` (the child then outlives a
    /// killed parent, as without it) if Windows refuses.
    pub(crate) fn assign(child: &std::process::Child) -> Option<KillOnClose> {
        use std::os::windows::io::AsRawHandle as _;

        use windows_sys::Win32::System::JobObjects::{
            AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
            JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation,
            SetInformationJobObject,
        };

        // SAFETY: an unnamed job with default security; the handle is
        // owned by the returned value, which closes it.
        let job = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
        if job.is_null() {
            return None;
        }
        let job = KillOnClose(job);
        // SAFETY: zeroed is a valid "no limits" value of this plain C
        // structure.
        let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { std::mem::zeroed() };
        info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
        // SAFETY: `info` is the structure the information class names, with
        // its size; `child`'s handle is open while it is borrowed.
        let ok = unsafe {
            SetInformationJobObject(
                job.0,
                JobObjectExtendedLimitInformation,
                (&raw const info).cast(),
                std::mem::size_of_val(&info) as u32,
            ) != 0
                && AssignProcessToJobObject(job.0, child.as_raw_handle()) != 0
        };
        ok.then_some(job)
    }
}

#[cfg(windows)]
impl Drop for KillOnClose {
    fn drop(&mut self) {
        // SAFETY: the job handle this value owns, closed once.
        unsafe { windows_sys::Win32::Foundation::CloseHandle(self.0) };
    }
}

/// Starts a dev session, builds and installs the Android dev host (when
/// it changed), forwards the dev server port to the device and starts the
/// host.
fn run_android(
    entry: &Path,
    listen: crate::dev::Listen,
    release: bool,
    limits: Option<HostLimits>,
    work: &Path,
    trace: bool,
) -> anyhow::Result<()> {
    use crate::android;
    let sdk = android::Sdk::find()?;
    let serial = android::device(&sdk)?;
    // As on iOS: the host of a previous session must not connect first.
    let _ = android::adb(&sdk, &serial, &["shell", "am", "force-stop", BUNDLE_ID]);
    let session = DevSession::start(entry, listen, release, limits)?;
    install_android_host(&sdk, &serial, work, &crate::runtime::android(true, &[])?)?;
    // The device reaches the dev server on its own 127.0.0.1, until the
    // run ends.
    let _reverse = android::Reverse::add(&sdk, &serial, session.port())?;
    let url = session.local_url();
    let mut start = vec![
        "shell",
        "am",
        "start",
        "-S",
        "-n",
        "com.longbridge.nsh.host/com.longbridge.nsh.DevActivity",
        "--es",
        "url",
        &url,
    ];
    if trace {
        start.extend(["--ez", "trace", "true"]);
    }
    let env = android_app_env(&crate::package::read_config(entry)?);
    start.extend(env.iter().map(String::as_str));
    let step = ui::Step::start("launching the development host");
    android::adb(&sdk, &serial, &start)?;
    step.finish();
    let result = session.watch(|| Ok(false));
    let _ = android::adb(&sdk, &serial, &["shell", "am", "force-stop", BUNDLE_ID]);
    result
}

/// Builds the Android development host (when its runtime changed) into
/// `work` and installs it on device `serial` (when the device does not have
/// this build).
pub(crate) fn install_android_host(
    sdk: &crate::android::Sdk,
    serial: &str,
    work: &Path,
    runtime: &Path,
) -> anyhow::Result<()> {
    use crate::android::{self, Apk, Signing};
    let apk_path = work.join("android/NshDev.apk");
    fs::create_dir_all(apk_path.parent().context("apk dir")?)?;
    let stamp = work.join("android/runtime.stamp");
    // Every app's development host is the same package: another app's run
    // (an app with its own Rust crate has its own runtime) or another
    // device replaces what this app installed. The device's install time
    // tells whether the host there is still the one this app installed.
    let installed = work.join("android/installed");
    let version = runtime_version(runtime)?;
    let built =
        apk_path.exists() && fs::read_to_string(&stamp).ok().as_deref() == Some(version.as_str());
    if !built {
        let step = ui::Step::start("building the Android development host");
        android::build_apk(
            sdk,
            &Apk {
                package: BUNDLE_ID,
                label: APP_NAME,
                version_name: "0.1.0",
                version_code: 1,
                target_sdk: android::DEFAULT_TARGET_SDK,
                activity: "com.longbridge.nsh.DevActivity",
                dev: true,
                cleartext: true,
                notifications: true,
                // The host runs any app: its pages may capture media.
                microphone: true,
                camera: true,
                schemes: &[],
                rust: false,
                dark: false,
                runtime,
                abis: &[],
                icon: None,
                assets: Vec::new(),
                signing: Signing::Debug,
            },
            &apk_path,
        )?;
        step.done("built the Android development host");
        // Until it is installed, no device has this build.
        let _ = fs::remove_file(&installed);
        fs::write(&stamp, &version)?;
    }
    let on_device =
        |sdk: &android::Sdk| installed_host(sdk, serial).map(|time| format!("{serial} {time}"));
    let current = fs::read_to_string(&installed).ok();
    if current.is_none() || current != on_device(sdk) {
        let step = ui::Step::start(format!("installing it on {serial}"));
        android::adb(
            sdk,
            serial,
            &["install", "-r", "-t", &apk_path.to_string_lossy()],
        )?;
        step.done(format!(
            "installed the Android development host on {serial}"
        ));
        match on_device(sdk) {
            Some(record) => fs::write(&installed, record)?,
            None => {
                let _ = fs::remove_file(&installed);
            }
        }
    }
    Ok(())
}

/// When the development host on device `serial` was installed or last
/// updated (`dumpsys package`), if it is there.
fn installed_host(sdk: &crate::android::Sdk, serial: &str) -> Option<String> {
    let text =
        crate::android::adb(sdk, serial, &["shell", "dumpsys", "package", BUNDLE_ID]).ok()?;
    text.lines()
        .find_map(|line| line.trim().strip_prefix("lastUpdateTime="))
        .map(str::to_owned)
}

/// Identifies a runtime build: the sizes and times of its files.
fn runtime_version(runtime: &Path) -> anyhow::Result<String> {
    let mut parts = Vec::new();
    let mut files = vec![runtime.join("classes.dex")];
    for entry in fs::read_dir(runtime.join("lib"))? {
        files.push(entry?.path().join("libnsh.so"));
    }
    for file in files {
        if let Ok(meta) = fs::metadata(&file) {
            let modified = meta
                .modified()?
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0);
            parts.push(format!("{}:{}:{modified}", file.display(), meta.len()));
        }
    }
    Ok(parts.join("\n"))
}

/// Creates (or refreshes) `<work>/NshDev.app` around the host binary.
fn package_catalyst(work: &Path, host: &Path) -> anyhow::Result<PathBuf> {
    let app = work.join(format!("{APP_NAME}.app"));
    let contents = app.join("Contents");
    let macos = contents.join("MacOS");
    fs::create_dir_all(&macos)?;
    fs::write(contents.join("Info.plist"), info_plist(Target::Catalyst))?;
    install_binary(host, &macos.join("nsh-ios-host"))?;
    Ok(app)
}

/// Creates (or refreshes) `<work>/ios/NshDev.app`, a flat iOS app bundle,
/// signed ad hoc (the simulator requires a signature).
pub(crate) fn package_ios(work: &Path, host: &Path) -> anyhow::Result<PathBuf> {
    let app = work.join("ios").join(format!("{APP_NAME}.app"));
    fs::create_dir_all(&app)?;
    fs::write(app.join("Info.plist"), info_plist(Target::Ios))?;
    if install_binary(host, &app.join("nsh-ios-host"))? || !app.join("_CodeSignature").exists() {
        let status = Command::new("codesign")
            .args(["--force", "--sign", "-", "--timestamp=none"])
            .arg(&app)
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .context("run codesign")?;
        if !status.success() {
            bail!("codesign failed for {}", app.display());
        }
    }
    Ok(app)
}

/// Copies the host binary if it changed. Returns true if it did.
fn install_binary(host: &Path, dest: &Path) -> anyhow::Result<bool> {
    if !is_stale(host, dest)? {
        return Ok(false);
    }
    // Copy then rename: overwriting in place would modify the file a
    // running host (another session) maps, and the kernel kills processes
    // whose code no longer matches its cached signature.
    let tmp = dest.with_extension("tmp");
    fs::copy(host, &tmp).with_context(|| format!("copy {}", host.display()))?;
    fs::rename(&tmp, dest)?;
    Ok(true)
}

fn is_stale(src: &Path, dest: &Path) -> anyhow::Result<bool> {
    let Ok(dest_meta) = fs::metadata(dest) else {
        return Ok(true);
    };
    let src_meta = fs::metadata(src)?;
    Ok(src_meta.len() != dest_meta.len() || src_meta.modified()? > dest_meta.modified()?)
}

pub(crate) fn simctl(args: &[&str]) -> anyhow::Result<String> {
    simctl_with_env(args, &[])
}

/// [`simctl`] with variables in its environment: `launch` passes those
/// named `SIMCTL_CHILD_<name>` to the app as `<name>` ([`simctl_app_env`]).
pub(crate) fn simctl_with_env(
    args: &[&str],
    env: &[(String, std::ffi::OsString)],
) -> anyhow::Result<String> {
    let output = Command::new("xcrun")
        .arg("simctl")
        .args(args)
        .envs(env.iter().map(|(name, value)| (name, value)))
        .output()
        .context("run xcrun simctl (is Xcode installed?)")?;
    if !output.status.success() {
        bail!(
            "simctl {} failed: {}",
            args.first().unwrap_or(&""),
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}

/// The variables of this environment that the app's `nsh.json` declares in
/// `capabilities.process.env`, named for `xcrun simctl launch`, which
/// passes the app only its caller's `SIMCTL_CHILD_<name>` variables: the
/// app in the simulator reads them in `process.env` as the desktops' hosts,
/// the CLI's children, do. Only declared names, never the whole
/// environment: the declaration is what the app may read.
pub(crate) fn simctl_app_env(
    config: &crate::package::AppConfig,
) -> Vec<(String, std::ffi::OsString)> {
    simctl_child_env(&declared_env(config), |name| std::env::var_os(name))
}

/// The variable names the app's `nsh.json` declares in
/// `capabilities.process.env`: the only ones a development host is given
/// from this environment.
fn declared_env(config: &crate::package::AppConfig) -> Vec<String> {
    config
        .capabilities
        .as_ref()
        .and_then(|c| nsh_core::access::Capabilities::from_json_lenient(c).ok())
        .map(|(caps, _)| caps.process.env)
        .unwrap_or_default()
}

/// What the simulator sets for each app it launches: its container's paths
/// and the simulated runtime's. The app reads the simulator's values; the
/// Mac's would point it outside its container.
const SIMULATOR_ENV: [&str; 4] = ["HOME", "CFFIXED_USER_HOME", "TMPDIR", "PATH"];

/// [`simctl_app_env`] over the environment `var` reads. Each name is looked
/// up as the OS matches names, as the runtime's `process.env` does
/// (exactly on macOS, where the simulator runs).
fn simctl_child_env(
    declared: &[String],
    var: impl Fn(&str) -> Option<std::ffi::OsString>,
) -> Vec<(String, std::ffi::OsString)> {
    let mut env: Vec<(String, std::ffi::OsString)> = Vec::new();
    for name in declared {
        let child = format!("SIMCTL_CHILD_{name}");
        let simulators = SIMULATOR_ENV.contains(&name.as_str())
            || name.starts_with("DYLD_")
            || name.starts_with("SIMULATOR_");
        if simulators || env.iter().any(|(n, _)| *n == child) {
            continue;
        }
        if let Some(value) = var(name) {
            env.push((child, value));
        }
    }
    env
}

/// The variables of this environment that the app's `nsh.json` declares in
/// `capabilities.process.env`, as `adb shell am start` arguments for the
/// Android development host: `am start` starts the app in a process the
/// system makes, so each one goes as a string extra `nsh.env.<name>`, which
/// `DevActivity` sets in its process's environment before the app starts.
/// The app reads them in `process.env` as the desktops' hosts, the CLI's
/// children, do.
pub(crate) fn android_app_env(config: &crate::package::AppConfig) -> Vec<String> {
    android_env_extras(&declared_env(config), |name| std::env::var_os(name))
}

/// What Android sets for each app process: its paths and the runtime's
/// (`PATH`, `ANDROID_ROOT`, `BOOTCLASSPATH`, ...). The app reads the
/// device's values; the computer's would point it at files the device does
/// not have.
fn android_system_env(name: &str) -> bool {
    ["PATH", "HOME", "TMPDIR", "EXTERNAL_STORAGE"].contains(&name)
        || name.starts_with("LD_")
        || name.starts_with("ANDROID_")
        || name.ends_with("CLASSPATH")
}

/// [`android_app_env`] over the environment `var` reads: `--es
/// nsh.env.<name> <value>` for each declared name with a value, once. Only
/// names of letters, digits and `_` (the extra's key is a word of the
/// command line) and UTF-8 values (an extra is a Java string) go.
fn android_env_extras(
    declared: &[String],
    var: impl Fn(&str) -> Option<std::ffi::OsString>,
) -> Vec<String> {
    let mut extras = Vec::new();
    let mut passed: Vec<&str> = Vec::new();
    for name in declared {
        let plain =
            !name.is_empty() && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_');
        if !plain || android_system_env(name) || passed.contains(&name.as_str()) {
            continue;
        }
        let Some(value) = var(name).and_then(|v| v.into_string().ok()) else {
            continue;
        };
        passed.push(name);
        extras.extend([
            "--es".to_owned(),
            format!("nsh.env.{name}"),
            shell_quote(&value),
        ]);
    }
    extras
}

/// `text` as one word of a POSIX shell's command line: `adb shell` joins its
/// arguments into a line the device's shell parses again.
fn shell_quote(text: &str) -> String {
    format!("'{}'", text.replace('\'', r"'\''"))
}

#[derive(Deserialize)]
struct DeviceList {
    devices: std::collections::BTreeMap<String, Vec<Device>>,
}

#[derive(Deserialize)]
struct Device {
    udid: String,
    name: String,
    state: String,
    #[serde(rename = "isAvailable", default)]
    available: bool,
}

/// Picks a simulator (`wanted` by name or UDID; else a booted one; else the
/// newest iPhone), boots it and shows the Simulator app.
pub(crate) fn simulator(wanted: Option<&str>) -> anyhow::Result<String> {
    let list: DeviceList =
        serde_json::from_str(&simctl(&["list", "devices", "available", "--json"])?)?;
    // Runtimes sort by version within a platform; newest last.
    let mut devices: Vec<&Device> = list
        .devices
        .iter()
        .filter(|(runtime, _)| runtime.contains("SimRuntime.iOS"))
        .flat_map(|(_, devices)| devices)
        .filter(|d| d.available)
        .collect();
    devices.reverse();
    let device = match wanted {
        Some(w) => devices
            .iter()
            .find(|d| d.udid == w || d.name == w)
            .with_context(|| format!("no available simulator named {w}"))?,
        None => devices
            .iter()
            .find(|d| d.state == "Booted")
            .or_else(|| {
                devices
                    .iter()
                    .find(|d| d.name.starts_with("iPhone") && d.name.contains("Pro"))
            })
            .or_else(|| devices.iter().find(|d| d.name.starts_with("iPhone")))
            .context(
                "no iOS simulator available: install one with `xcodebuild -downloadPlatform iOS`",
            )?,
    };
    let booting =
        (device.state != "Booted").then(|| ui::Step::start(format!("booting {}", device.name)));
    if booting.is_some() {
        simctl(&["boot", &device.udid])?;
    }
    // Apps launched before the boot completes are sent to the background
    // when SpringBoard comes up.
    simctl(&["bootstatus", &device.udid, "-b"])?;
    if let Some(step) = booting {
        step.done(format!("booted {}", device.name));
    }
    show_simulators();
    Ok(device.udid.clone())
}

/// Brings up the simulators' window: Simulator.app, or DeviceHub.app in
/// Xcode versions that replaced it.
fn show_simulators() {
    let quiet = |cmd: &mut Command| {
        cmd.stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .is_ok_and(|s| s.success())
    };
    if quiet(Command::new("open").args(["-b", "com.apple.iphonesimulator"])) {
        return;
    }
    let developer = Command::new("xcode-select").arg("-p").output();
    if let Ok(out) = developer {
        let developer = String::from_utf8_lossy(&out.stdout);
        let hub = Path::new(developer.trim()).join("../Applications/DeviceHub.app");
        if hub.exists() && quiet(Command::new("open").arg(&hub)) {
            return;
        }
    }
    ui::warn("no Simulator or DeviceHub app found: the simulator runs without a window");
}

fn info_plist(target: Target) -> String {
    let platform = match target {
        // 6 = Mac idiom ("Optimize for Mac"): 1:1 points instead of the 77%
        // iPad scaling.
        Target::Catalyst => {
            "<key>UIDeviceFamily</key><array><integer>6</integer></array>\n    \
             <key>LSMinimumSystemVersion</key><string>11.0</string>"
        }
        // A launch screen entry opts into the full screen (no letterboxing).
        Target::Ios
        | Target::Android
        | Target::Linux
        | Target::Macos
        | Target::Windows
        | Target::Web
        | Target::Gpui
        | Target::Tui => {
            "<key>UIDeviceFamily</key><array><integer>1</integer><integer>2</integer></array>\n    \
             <key>MinimumOSVersion</key><string>15.0</string>\n    \
             <key>CFBundleSupportedPlatforms</key><array><string>iPhoneSimulator</string></array>\n    \
             <key>UILaunchScreen</key><dict/>\n    \
             <key>CADisableMinimumFrameDurationOnPhone</key><true/>\n    \
             <key>NSAppTransportSecurity</key><dict><key>NSAllowsLocalNetworking</key><true/></dict>"
        }
    };
    // The host runs any app: it may recognize speech and its pages may
    // capture media.
    let usage = crate::package::USAGE_DESCRIPTIONS
        .iter()
        .copied()
        .chain([crate::package::WEB_MEDIA_USAGE_DESCRIPTIONS[1]].map(|(_, key, text)| (key, text)))
        .map(|(key, text)| format!("<key>{key}</key><string>{text}</string>"))
        .collect::<Vec<_>>()
        .join("\n    ");
    format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleExecutable</key><string>nsh-ios-host</string>
    <key>CFBundleIdentifier</key><string>{BUNDLE_ID}</string>
    <key>CFBundleName</key><string>{APP_NAME}</string>
    <key>CFBundlePackageType</key><string>APPL</string>
    <key>CFBundleShortVersionString</key><string>0.1.0</string>
    <key>CFBundleVersion</key><string>1</string>
    <key>UIApplicationSupportsMultipleScenes</key><false/>
    {usage}
    {platform}
</dict>
</plist>
"#
    )
}

#[cfg(test)]
mod tests {
    use clap::ValueEnum as _;

    use super::{
        HostWindow, Target, android_app_env, android_env_extras, shell_quote, simctl_app_env,
        simctl_child_env,
    };

    /// The simulator's app gets the declared variables this environment
    /// has, prefixed for simctl, each once; undeclared ones stay behind,
    /// and so do those the simulator sets for its apps (`HOME`).
    #[test]
    fn simctl_passes_only_declared_variables() {
        let vars = |name: &str| {
            ["NSH_GALLERY_DEMO", "API_TOKEN", "HOME", "DYLD_LIBRARY_PATH"]
                .contains(&name)
                .then(|| format!("{name} value").into())
        };
        let declared = [
            "NSH_GALLERY_DEMO",
            "NSH_GALLERY_SECTION",
            "NSH_GALLERY_DEMO",
            "API_TOKEN",
            "HOME",
            "DYLD_LIBRARY_PATH",
        ]
        .map(String::from);
        assert_eq!(
            simctl_child_env(&declared, vars),
            [
                (
                    "SIMCTL_CHILD_NSH_GALLERY_DEMO".to_owned(),
                    "NSH_GALLERY_DEMO value".into()
                ),
                (
                    "SIMCTL_CHILD_API_TOKEN".to_owned(),
                    "API_TOKEN value".into()
                ),
            ]
        );
        assert!(simctl_child_env(&[], vars).is_empty());
    }

    /// An app without a declaration of `process.env`, or none at all, gets
    /// nothing from this environment; one that declares a name gets it
    /// (`cargo test` sets `CARGO_PKG_NAME`).
    #[test]
    fn simctl_passes_nothing_undeclared() {
        let config = |json: &str| {
            let mut config = crate::package::AppConfig::default();
            config.capabilities = Some(serde_json::from_str(json).unwrap());
            config
        };
        assert!(simctl_app_env(&crate::package::AppConfig::default()).is_empty());
        assert!(simctl_app_env(&config(r#"{ "clipboard": true }"#)).is_empty());
        assert_eq!(
            simctl_app_env(&config(r#"{ "process": { "env": ["CARGO_PKG_NAME"] } }"#))
                .into_iter()
                .map(|(name, _)| name)
                .collect::<Vec<_>>(),
            ["SIMCTL_CHILD_CARGO_PKG_NAME"]
        );
    }

    /// The Android host gets the declared variables this environment has,
    /// each once, as string extras with quoted values; undeclared ones stay
    /// behind, and so do those Android sets for its apps, names that are
    /// not plain and values that are not UTF-8.
    #[test]
    fn android_passes_only_declared_variables() {
        let vars = |name: &str| -> Option<std::ffi::OsString> {
            match name {
                "NSH_GALLERY_DEMO" => Some("accordion".into()),
                "API_TOKEN" => Some("it's $HOME".into()),
                "EMPTY" => Some("".into()),
                #[cfg(unix)]
                "BINARY" => Some(
                    <std::ffi::OsStr as std::os::unix::ffi::OsStrExt>::from_bytes(b"\xff").into(),
                ),
                "PATH" | "HOME" | "TMPDIR" | "LD_PRELOAD" | "ANDROID_ROOT" | "BOOTCLASSPATH"
                | "EXTERNAL_STORAGE" | "A-B" | "A B" => Some("system".into()),
                _ => None,
            }
        };
        let declared = [
            "NSH_GALLERY_DEMO",
            "NSH_GALLERY_SECTION",
            "NSH_GALLERY_DEMO",
            "API_TOKEN",
            "EMPTY",
            "BINARY",
            "PATH",
            "HOME",
            "TMPDIR",
            "LD_PRELOAD",
            "ANDROID_ROOT",
            "BOOTCLASSPATH",
            "EXTERNAL_STORAGE",
            "A-B",
            "A B",
            "",
        ]
        .map(String::from);
        assert_eq!(
            android_env_extras(&declared, vars),
            [
                "--es",
                "nsh.env.NSH_GALLERY_DEMO",
                "'accordion'",
                "--es",
                "nsh.env.API_TOKEN",
                r"'it'\''s $HOME'",
                "--es",
                "nsh.env.EMPTY",
                "''",
            ]
        );
        assert!(android_env_extras(&[], vars).is_empty());
    }

    /// An app without a declaration of `process.env` gets nothing on
    /// Android either; one that declares a name gets it (`cargo test` sets
    /// `CARGO_PKG_NAME`).
    #[test]
    fn android_passes_nothing_undeclared() {
        let mut config = crate::package::AppConfig::default();
        assert!(android_app_env(&config).is_empty());
        config.capabilities = Some(serde_json::json!({ "process": { "env": ["CARGO_PKG_NAME"] } }));
        assert_eq!(
            android_app_env(&config),
            ["--es", "nsh.env.CARGO_PKG_NAME", "'nsh-cli'"]
        );
    }

    /// A value is one word for the device's shell, whatever it holds.
    #[test]
    fn shell_quote_keeps_one_word() {
        assert_eq!(shell_quote(""), "''");
        assert_eq!(shell_quote("a b"), "'a b'");
        assert_eq!(shell_quote(r#"$HOME `x` "q""#), r#"'$HOME `x` "q"'"#);
        assert_eq!(shell_quote("it's"), r"'it'\''s'");
        assert_eq!(shell_quote("''"), r"''\'''\'''");
    }

    /// Only phones and browsers that may be on the network get a dev
    /// server listening on every interface; hosts on this machine get
    /// loopback.
    #[test]
    fn only_targets_that_may_be_other_machines_listen_on_the_network() {
        let network: Vec<_> = Target::value_variants()
            .iter()
            .filter(|target| target.uses_network())
            .copied()
            .collect();
        assert_eq!(network, [Target::Ios, Target::Android, Target::Web]);
    }

    /// `--window-size` reaches every desktop host; GPUI runs no app of
    /// Rust only.
    #[test]
    fn the_desktop_hosts_take_a_size() {
        for target in [Target::Macos, Target::Linux, Target::Windows] {
            assert!(
                HostWindow::default().check(target, true).is_ok(),
                "Rust app, {target:?}"
            );
        }
        assert!(HostWindow::default().check(Target::Gpui, true).is_err());
        let sized = HostWindow {
            size: Some("700x500"),
            ..HostWindow::default()
        };
        for target in [Target::Macos, Target::Linux, Target::Windows, Target::Gpui] {
            assert!(sized.check(target, false).is_ok(), "{target:?}");
        }
        for target in [Target::Catalyst, Target::Ios, Target::Android, Target::Web] {
            assert!(sized.check(target, false).is_err(), "{target:?}");
        }
        assert_eq!(sized.args(), ["--window-size", "700x500"]);
        let named = HostWindow {
            name: Some("Orders"),
            ..HostWindow::default()
        };
        assert!(named.check(Target::Macos, false).is_ok());
        assert!(named.check(Target::Linux, false).is_err());
    }

    /// `--display` reaches the macOS host only, for a TSX entry.
    #[test]
    fn the_macos_host_takes_a_display() {
        let placed = HostWindow {
            display: Some(2),
            ..HostWindow::default()
        };
        assert!(placed.check(Target::Macos, false).is_ok());
        assert!(placed.check(Target::Macos, true).is_err());
        for target in [Target::Linux, Target::Windows, Target::Gpui, Target::Ios] {
            assert!(placed.check(target, false).is_err(), "{target:?}");
        }
        assert_eq!(placed.args(), ["--display", "2"]);
    }

    /// The desktop hosts get each app's own id, so each keeps its own data.
    #[test]
    fn hosts_get_the_apps_id() {
        let dir = std::env::temp_dir().join(format!("nsh-run-app-id-{}", std::process::id()));
        let (named, unnamed) = (dir.join("named"), dir.join("Notes"));
        for app in [&named, &unnamed] {
            std::fs::create_dir_all(app).unwrap();
            std::fs::write(app.join("App.tsx"), "").unwrap();
        }
        std::fs::write(named.join("nsh.json"), r#"{ "id": "com.acme.orders" }"#).unwrap();
        assert_eq!(
            crate::package::app_id(&named.join("App.tsx")).unwrap(),
            "com.acme.orders"
        );
        assert_eq!(
            crate::package::app_id(&unnamed.join("App.tsx")).unwrap(),
            "com.example.notes"
        );
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn gpui_is_a_target_with_its_own_host() {
        let target = Target::from_str("gpui", false).unwrap();
        assert_eq!(target, Target::Gpui);
        assert_eq!(target.platform().binary(false), "nsh-gpui-host");
    }
}