waterui-cli 0.4.1

Cross-platform tooling for WaterUI applications
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
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
use std::{
    collections::HashMap,
    path::PathBuf,
    time::{Duration, Instant},
};

use eyre::{Context as _, bail, eyre};
use jiff::Timestamp;
use semver::Version;
use serde::Deserialize;
use smol::{
    Timer,
    channel::Sender,
    io::{AsyncBufReadExt, BufReader},
    process::Stdio,
    spawn,
    stream::StreamExt,
};
use tracing::{debug as trace_debug, info, warn};

use std::path::Path;

use crate::{
    apple::{physical::ApplePhysicalDevice, platform::apple_deployment_target},
    debug,
    device::{
        ApplicationExit, Artifact, Device, DeviceEvent, FailToRun, Local, LogLevel, Running,
        format_panic_message,
    },
    platform::TargetPlatform,
    project::Project,
    toolchain::Host,
    utils::parse_semver_version,
};

use smol::channel::Receiver;

/// Panic information extracted from log stream.
#[derive(Debug, Clone)]
struct PanicInfo {
    /// The panic message payload
    payload: String,
    /// The source location where the panic occurred
    location: Option<String>,
}

async fn install_simulator_artifact(
    host: &Host,
    udid: &str,
    artifact_path: &Path,
) -> Result<(), FailToRun> {
    let install_output = host
        .command("xcrun")
        .args(["simctl", "install", udid])
        .arg(artifact_path)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .await
        .map_err(|error| FailToRun::Install(eyre!("Failed to install app: {error}")))?;
    if install_output.status.success() {
        return Ok(());
    }

    Err(FailToRun::Install(eyre!(
        "Failed to install app:\n{}\n{}",
        String::from_utf8_lossy(&install_output.stdout).trim(),
        String::from_utf8_lossy(&install_output.stderr).trim(),
    )))
}

fn simulator_process_name(artifact: &Artifact) -> Result<String, FailToRun> {
    artifact
        .path()
        .file_stem()
        .ok_or_else(|| {
            FailToRun::Run(eyre!(
                "Artifact path has no filename: {}",
                artifact.path().display()
            ))
        })?
        .to_str()
        .ok_or_else(|| {
            FailToRun::Run(eyre!(
                "Artifact filename is not valid UTF-8: {}",
                artifact.path().display()
            ))
        })
        .map(std::string::ToString::to_string)
}

fn simulator_env_vars(options: &crate::device::RunOptions) -> Vec<(String, String)> {
    options
        .env_vars()
        .map(|(key, value)| (key.to_string(), value.to_string()))
        .collect()
}

async fn launch_simulator_app(
    host: &Host,
    udid: &str,
    bundle_id: &str,
    env_vars: &[(String, String)],
) -> Result<u32, FailToRun> {
    let mut launch = host.command("xcrun");
    launch
        .arg("simctl")
        .arg("launch")
        .arg("--terminate-running-process")
        .arg(udid)
        .arg(bundle_id);

    for (key, value) in env_vars {
        launch.env(format!("SIMCTL_CHILD_{key}"), value);
    }

    let launch_output = launch
        .output()
        .await
        .map_err(|error| FailToRun::Launch(eyre!("Failed to launch app: {error}")))?;
    if !launch_output.status.success() {
        return Err(FailToRun::Launch(eyre!(
            "Failed to launch app:\n{}\n{}",
            String::from_utf8_lossy(&launch_output.stdout).trim(),
            String::from_utf8_lossy(&launch_output.stderr).trim(),
        )));
    }

    parse_simctl_launch_pid(&String::from_utf8_lossy(&launch_output.stdout)).ok_or_else(|| {
        FailToRun::Launch(eyre!(
            "Failed to parse PID from simctl launch output: {}",
            String::from_utf8_lossy(&launch_output.stdout).trim()
        ))
    })
}

fn spawn_simulator_termination(host: &Host, udid: String, bundle_id: String) {
    let host = host.clone();
    let spawn_result = std::thread::Builder::new()
        .name("waterui-simctl-terminate".to_string())
        .spawn(move || {
            match host
                .std_command("xcrun")
                .args(["simctl", "terminate", &udid, &bundle_id])
                .output()
            {
                Ok(output) if output.status.success() => {}
                Ok(output) => {
                    tracing::error!(
                        "Failed to terminate app on simulator: status={}, stdout={}, stderr={}",
                        output.status,
                        String::from_utf8_lossy(&output.stdout).trim(),
                        String::from_utf8_lossy(&output.stderr).trim()
                    );
                }
                Err(error) => {
                    tracing::error!("Failed to terminate app on simulator: {error}");
                }
            }
        });

    if let Err(error) = spawn_result {
        tracing::error!("Failed to spawn simulator termination thread: {error}");
    }
}

struct SimulatorExitContext {
    device_name: String,
    device_identifier: String,
    bundle_id: String,
    process_name: String,
    pid: u32,
    start_time: Timestamp,
    start_instant: Instant,
}

fn spawn_simulator_exit_monitor(
    host: &Host,
    sender: Sender<DeviceEvent>,
    panic_rx: Receiver<PanicInfo>,
    context: SimulatorExitContext,
) {
    let host = host.clone();
    spawn(async move {
        wait_for_pid_exit(&host, context.pid).await;

        if let Ok(info) = panic_rx.try_recv() {
            let _ = sender.try_send(DeviceEvent::Crashed(format_panic_message(
                &info.payload,
                info.location.as_deref(),
            )));
            return;
        }

        if let Some(report) = poll_for_crash_report(&host, &context, Duration::from_secs(10)).await
        {
            let _ = sender.try_send(DeviceEvent::Crashed(report.to_string()));
            return;
        }

        if let Some(panic_msg) = fetch_recent_panic_logs(
            &host,
            &context.device_identifier,
            context.start_instant,
            Some(context.pid),
        )
        .await
        {
            let _ = sender.try_send(DeviceEvent::Crashed(panic_msg));
            return;
        }

        let _ = sender.try_send(DeviceEvent::Exited(ApplicationExit::user_closed()));
    })
    .detach();
}

/// Start streaming logs from a `WaterUI` app.
///
/// This uses `log stream` with a predicate to filter logs.
/// - By default, filters by the `WaterUI` subsystem ("dev.waterui").
/// - If `native_logs` is true, filters by process ID instead to capture all native output.
///
/// Returns a receiver for panic info that fires if a panic is detected, and
/// the `log stream` process. It is spawned with `kill_on_drop` and the reader
/// task only holds its stdout, so the caller retains the handle in its
/// [`Running`] to end the stream with the run instead of leaving it behind.
fn start_log_stream(
    host: &Host,
    sender: Sender<DeviceEvent>,
    log_level: Option<LogLevel>,
    pid: u32,
    native_logs: bool,
    udid: &str,
) -> eyre::Result<(Receiver<PanicInfo>, smol::process::Child)> {
    // Bounded channel with capacity 1 acts as oneshot - only first panic is captured
    let (panic_tx, panic_rx) = smol::channel::bounded::<PanicInfo>(1);

    // Always stream at default level to capture errors/faults, even if user didn't request logs
    let stream_level = log_level.map_or("default", |l| l.to_apple_level());

    // Build predicate: use processID for native logs, subsystem for WaterUI-only logs
    let predicate = if native_logs {
        format!("processID == {pid}")
    } else {
        format!("processID == {pid} AND subsystem == \"dev.waterui\"")
    };

    // The stream runs inside the simulator: the host logd records nothing for
    // sim processes on these systems, so a host-side `log stream` sees zero
    // entries while `simctl spawn <udid> log stream` sees them all.
    let mut log_cmd = host.command("xcrun");
    log_cmd
        .args(["simctl", "spawn", udid, "log", "stream"])
        .arg("--predicate")
        .arg(&predicate)
        .arg("--level")
        .arg(stream_level)
        .arg("--style")
        .arg("compact")
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .kill_on_drop(true);

    let mut log_child = log_cmd
        .spawn()
        .map_err(|error| eyre!("Failed to start simulator log stream: {error}"))?;
    let stdout = log_child
        .stdout
        .take()
        .expect("stdout is piped for the simulator log stream");

    // `log stream` only forwards entries written after it attaches to logd, and
    // a fast first paint routinely beats the attach — the launch marker (and a
    // fast crash's panic payload) would be permanently lost. `log show` reads
    // the persisted store, so replay the recent window once shortly after the
    // stream starts; consumers take the first matching marker, so a line that
    // also arrives through the stream is harmless.
    replay_log_history(
        host.clone(),
        udid.to_string(),
        predicate,
        sender.clone(),
        panic_tx.clone(),
        log_level,
    );

    spawn(async move {
        let mut lines = BufReader::new(stdout).lines();
        while let Some(Ok(line)) = lines.next().await {
            // Skip header lines from `log stream`
            if line.starts_with("Filtering") || line.starts_with("Timestamp") {
                continue;
            }

            // Extract panic info from log line if present (only first panic via try_send)
            if line.contains("panic.payload=")
                && let Some(info) = extract_panic_info_from_log(&line)
            {
                let _ = panic_tx.try_send(info);
            }

            // Only send log events to display if user requested logs
            if log_level.is_some()
                && sender
                    .try_send(DeviceEvent::Log {
                        level: compact_log_level(&line),
                        message: line,
                    })
                    .is_err()
            {
                break;
            }
        }
    })
    .detach();

    Ok((panic_rx, log_child))
}

/// Parse log level from `log`'s compact format: "timestamp Ty Process..." where
/// Ty is F (fault), E (error), W (warning), I (info), or D (debug). Fault is
/// Apple's highest severity - used by the panic handler.
fn compact_log_level(line: &str) -> tracing::Level {
    if line.contains(" F ") || line.contains(" E ") {
        tracing::Level::ERROR
    } else if line.contains(" W ") {
        tracing::Level::WARN
    } else if line.contains(" D ") {
        tracing::Level::DEBUG
    } else {
        tracing::Level::INFO
    }
}

/// Forward `log show` output for the recent window into the same event path as
/// the live stream, a few seconds after the stream starts. Reads the persisted
/// store, so it recovers entries emitted before the stream attached to logd.
fn replay_log_history(
    host: Host,
    udid: String,
    predicate: String,
    sender: Sender<DeviceEvent>,
    panic_tx: Sender<PanicInfo>,
    log_level: Option<LogLevel>,
) {
    spawn(async move {
        Timer::after(Duration::from_secs(4)).await;
        let Ok(output) = host
            .command("xcrun")
            .args(["simctl", "spawn", &udid, "log", "show"])
            .args(["--last", "2m", "--predicate", &predicate])
            .args(["--style", "compact"])
            .output()
            .await
        else {
            return;
        };
        for line in String::from_utf8_lossy(&output.stdout).lines() {
            if line.starts_with("Filtering") || line.starts_with("Timestamp") {
                continue;
            }
            if line.contains("panic.payload=")
                && let Some(info) = extract_panic_info_from_log(line)
            {
                let _ = panic_tx.try_send(info);
            }
            if log_level.is_some() {
                let _ = sender.try_send(DeviceEvent::Log {
                    level: compact_log_level(line),
                    message: line.to_string(),
                });
            }
        }
    })
    .detach();
}

/// Extract panic information from a log line containing panic.payload and panic.location fields.
fn extract_panic_info_from_log(line: &str) -> Option<PanicInfo> {
    let mut payload = None;
    let mut location = None;

    // Extract panic.payload="..."
    if let Some(start) = line.find("panic.payload=\"") {
        let start = start + 15;
        if let Some(end) = line[start..].find('"') {
            payload = Some(line[start..start + end].to_string());
        }
    }

    // Extract panic.location="..."
    if let Some(start) = line.find("panic.location=\"") {
        let start = start + 16;
        if let Some(end) = line[start..].find('"') {
            location = Some(line[start..start + end].to_string());
        }
    }

    payload.map(|p| PanicInfo {
        payload: p,
        location,
    })
}

/// Fetch recent panic logs from the unified logging system.
///
/// This uses `log show` to retrieve logs from the last few seconds that contain panic info.
/// Returns the panic message if found, along with location and payload.
async fn fetch_recent_panic_logs(
    host: &Host,
    udid: &str,
    started_at: Instant,
    pid: Option<u32>,
) -> Option<String> {
    let last = started_at.elapsed() + Duration::from_secs(2);
    let last_arg = format!("{}s", last.as_secs().max(5));

    let predicate = pid.map_or_else(|| "subsystem == \"dev.waterui\" AND eventMessage CONTAINS \"panic\"".to_string(), |pid| format!(
            "processID == {pid} AND subsystem == \"dev.waterui\" AND eventMessage CONTAINS \"panic\""
        ));

    // Same simulator-side domain as the live stream: the host logd does not
    // record sim app entries, so `log show` must run inside the device.
    let output = host
        .output(
            "xcrun",
            [
                "simctl",
                "spawn",
                udid,
                "log",
                "show",
                "--predicate",
                predicate.as_str(),
                "--style",
                "compact",
                "--last",
                last_arg.as_str(),
            ],
        )
        .await
        .ok()?;

    let stdout = String::from_utf8(output.stdout).ok()?;

    // Parse the log output to extract panic information
    for line in stdout.lines() {
        // Skip header lines
        if line.starts_with("Filtering") || line.starts_with("Timestamp") || line.is_empty() {
            continue;
        }

        // Extract panic.payload and panic.location from structured log fields
        // Format: ... panic.location="path:line:col" ... panic.payload="message"
        let mut location = None;
        let mut payload = None;

        if let Some(loc_start) = line.find("panic.location=\"") {
            let start = loc_start + 16;
            if let Some(end) = line[start..].find('"') {
                location = Some(&line[start..start + end]);
            }
        }

        if let Some(pay_start) = line.find("panic.payload=\"") {
            let start = pay_start + 15;
            if let Some(end) = line[start..].find('"') {
                payload = Some(&line[start..start + end]);
            }
        }

        if payload.is_some() || location.is_some() {
            let mut msg = String::from("Panic:");
            if let Some(p) = payload {
                msg = format!("{msg} {p}");
            }
            if let Some(l) = location {
                msg = format!("{msg}\n  at {l}");
            }
            return Some(msg);
        }
    }

    None
}

async fn poll_for_crash_report(
    host: &Host,
    context: &SimulatorExitContext,
    timeout: Duration,
) -> Option<debug::CrashReport> {
    trace_debug!(
        "Polling for crash report: bundle_id={}, process_name={}, pid={:?}, timeout={:?}",
        context.bundle_id,
        context.process_name,
        context.pid,
        timeout
    );

    let deadline = Instant::now() + timeout;
    let mut poll_count = 0;
    loop {
        poll_count += 1;
        if let Some(report) = debug::find_macos_ips_crash_report_since(
            host,
            &context.device_name,
            &context.device_identifier,
            &context.bundle_id,
            &context.process_name,
            Some(context.pid),
            context.start_time,
        )
        .await
        {
            trace_debug!(
                "Found crash report after {} polls: {}",
                poll_count,
                report.summary()
            );
            return Some(report);
        }

        if Instant::now() >= deadline {
            trace_debug!(
                "No crash report found after {} polls within {:?}",
                poll_count,
                timeout
            );
            return None;
        }

        Timer::after(Duration::from_millis(250)).await;
    }
}

fn parse_simctl_launch_pid(stdout: &str) -> Option<u32> {
    for line in stdout.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }

        if let Some((_, pid_part)) = line.rsplit_once(':')
            && let Ok(pid) = pid_part.trim().parse::<u32>()
        {
            return Some(pid);
        }

        if let Ok(pid) = line.parse::<u32>() {
            return Some(pid);
        }
    }
    None
}

async fn is_pid_alive(host: &Host, pid: u32) -> bool {
    host.command("kill")
        .arg("-0")
        .arg(pid.to_string())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .await
        .is_ok_and(|s| s.success())
}

async fn wait_for_pid_exit(host: &Host, pid: u32) {
    while is_pid_alive(host, pid).await {
        Timer::after(Duration::from_millis(200)).await;
    }
}

/// Represents an Apple device available to the CLI.
#[derive(Debug)]
pub enum AppleDevice {
    /// An Apple Simulator device
    Simulator(Box<AppleSimulator>),

    /// A paired physical iOS device reachable over USB or the LAN.
    Physical(ApplePhysicalDevice),

    /// The current physical `macOS` device
    ///
    /// Apple do not provide macOS simulator, so this represents the current physical machine.
    /// Uses the shared `Local` device which handles both `.app` bundles and binaries.
    Current(Local),
}

impl Device for AppleDevice {
    fn name(&self) -> &str {
        match self {
            Self::Simulator(simulator) => simulator.name(),
            Self::Physical(device) => device.name(),
            Self::Current(mac_os) => mac_os.name(),
        }
    }

    async fn launch(&self, host: &Host) -> eyre::Result<()> {
        match self {
            Self::Simulator(simulator) => simulator.launch(host).await,
            Self::Physical(device) => device.launch(host).await,
            Self::Current(_) => {
                // No need to launch anything for MacOS physical device
                // This is the current machine
                Ok(())
            }
        }
    }

    async fn run(
        &self,
        host: &Host,
        artifact: Artifact,
        options: crate::device::RunOptions,
    ) -> Result<crate::device::Running, crate::device::FailToRun> {
        match self {
            Self::Simulator(simulator) => simulator.run(host, artifact, options).await,
            Self::Physical(device) => device.run(host, artifact, options).await,
            Self::Current(mac_os) => mac_os.run(host, artifact, options).await,
        }
    }

    async fn scan(host: &Host) -> eyre::Result<Vec<Self>> {
        // Aggregate all available Apple devices: simulators + physical + local
        let mut devices = Vec::new();

        // Add available simulators
        let simulators = AppleSimulator::scan(host).await?;
        for sim in simulators {
            devices.push(Self::Simulator(Box::new(sim)));
        }

        // Add paired physical devices; a devicectl failure is non-fatal —
        // the simulator list is still useful on its own.
        match ApplePhysicalDevice::scan(host).await {
            Ok(physical) => devices.extend(physical.into_iter().map(Self::Physical)),
            Err(error) => warn!("devicectl device scan failed: {error:#}"),
        }

        // Add local machine
        devices.push(Self::Current(Local));

        Ok(devices)
    }
}

/// Represents an Apple Simulator device
///
/// Fields are deserialized from `xcrun simctl list devices --json` output
#[derive(Debug, Deserialize, Clone)]
pub struct AppleSimulator {
    /// Path to the simulator data directory
    #[serde(rename = "dataPath")]
    pub data_path: PathBuf,

    /// Size of the simulator data directory in bytes
    #[serde(rename = "dataPathSize")]
    pub data_path_size: Option<u64>,

    /// Path to the simulator log directory
    #[serde(rename = "logPath")]
    pub log_path: PathBuf,

    /// Size of the simulator log directory in bytes
    #[serde(rename = "logPathSize")]
    pub log_path_size: Option<u64>,

    /// Unique device identifier
    ///
    /// Note: not `uuid` but `udid`!
    pub udid: String,

    /// Indicates if the simulator is available
    #[serde(rename = "isAvailable")]
    pub is_available: bool,

    /// Device type identifier
    #[serde(rename = "deviceTypeIdentifier")]
    pub device_type_identifier: String,

    /// Current state of the simulator (e.g., Shutdown, Booted)
    pub state: String,
    /// Name of the simulator device
    pub name: String,

    /// Timestamp of the last boot time
    #[serde(rename = "lastBootedAt")]
    pub last_booted_at: Option<String>,

    /// Runtime identifier key from `simctl` (e.g. `com.apple.CoreSimulator.SimRuntime.iOS-26-2`).
    ///
    /// This is not part of the simulator device object itself; it comes from the map key in
    /// `xcrun simctl list --json`.
    #[serde(skip)]
    pub runtime_identifier: Option<String>,

    /// Version of the runtime this simulator runs (e.g. iOS 26.5 -> `26.5.0`).
    ///
    /// Like [`Self::runtime_identifier`], this is attached by `scan()` from the
    /// `runtimes` list of `xcrun simctl list --json`, not deserialized from the
    /// device object. `None` when `simctl` reports no usable version for the
    /// runtime — such a simulator can never satisfy a deployment target.
    #[serde(skip)]
    pub runtime_version: Option<Version>,
}

impl Device for AppleSimulator {
    fn name(&self) -> &str {
        &self.name
    }

    /// Launch the Apple simulator (boot it)
    async fn launch(&self, host: &Host) -> eyre::Result<()> {
        // Only boot if not already booted
        if self.state != "Booted" {
            host.run("xcrun", ["simctl", "boot", self.udid.as_str()])
                .await?;
        }
        Ok(())
    }

    /// Run an artifact on the Apple simulator
    ///
    /// Please launch the device before calling this method
    async fn run(
        &self,
        host: &Host,
        artifact: Artifact,
        options: crate::device::RunOptions,
    ) -> Result<crate::device::Running, crate::device::FailToRun> {
        info!("Installing app on apple simulator {}", self.name);
        install_simulator_artifact(host, &self.udid, artifact.path()).await?;

        info!("Launching app on apple simulator {}", self.name);

        let start_time = Timestamp::now();
        let start_instant = Instant::now();
        let bundle_id = artifact.bundle_id().to_string();
        let process_name = simulator_process_name(&artifact)?;
        let log_level = options.log_level();
        let native_logs = options.native_logs();
        let env_vars = simulator_env_vars(&options);
        let pid = launch_simulator_app(host, &self.udid, &bundle_id, &env_vars).await?;

        // Create a Running instance - termination will use simctl terminate
        let host_for_termination = host.clone();
        let udid = self.udid.clone();
        let bundle_id_for_termination = bundle_id.clone();
        let (mut running, sender) = Running::new(move || {
            spawn_simulator_termination(&host_for_termination, udid, bundle_id_for_termination);
        });

        // Start log streaming and get panic info receiver
        // Uses WaterUI subsystem predicate by default, or processID if native_logs is enabled
        let (panic_rx, log_child) = start_log_stream(
            host,
            sender.clone(),
            log_level,
            pid,
            native_logs,
            &self.udid,
        )
        .map_err(FailToRun::Launch)?;
        running.retain(log_child);

        // Monitor the actual app process and classify crash vs normal exit.
        spawn_simulator_exit_monitor(
            host,
            sender,
            panic_rx,
            SimulatorExitContext {
                device_name: self.name.clone(),
                device_identifier: self.udid.clone(),
                bundle_id,
                process_name,
                pid,
                start_time,
                start_instant,
            },
        );

        Ok(running)
    }

    async fn scan(host: &Host) -> eyre::Result<Vec<Self>> {
        #[derive(Deserialize)]
        struct Runtime {
            identifier: String,
            version: Option<String>,
        }

        #[derive(Deserialize)]
        struct Root {
            devices: HashMap<String, Vec<AppleSimulator>>,
            runtimes: Vec<Runtime>,
        }

        let content = host.run("xcrun", ["simctl", "list", "--json"]).await?;

        let root = serde_json::from_str::<Root>(&content)?;

        let mut runtime_versions = HashMap::with_capacity(root.runtimes.len());
        for runtime in root.runtimes {
            let Some(version) = runtime.version.as_deref() else {
                warn!("simctl runtime {} reports no version", runtime.identifier);
                continue;
            };
            match parse_semver_version(version) {
                Ok(version) => {
                    runtime_versions.insert(runtime.identifier, version);
                }
                Err(error) => {
                    warn!("Ignoring simctl runtime {}: {error}", runtime.identifier);
                }
            }
        }

        let mut simulators = Vec::new();
        for (runtime_identifier, sims) in root.devices {
            for mut sim in sims {
                sim.runtime_version = runtime_versions.get(&runtime_identifier).cloned();
                sim.runtime_identifier = Some(runtime_identifier.clone());
                simulators.push(sim);
            }
        }

        Ok(simulators)
    }
}

impl AppleSimulator {
    /// Scan iOS simulators only.
    ///
    /// # Errors
    /// Returns an error if `simctl` cannot be queried for available simulators.
    pub async fn scan_ios(host: &Host) -> eyre::Result<Vec<Self>> {
        let ios_filter = |s: &Self| {
            s.is_available
                && s.runtime_identifier
                    .as_deref()
                    .is_some_and(|r| r.contains("SimRuntime.iOS-"))
        };

        let simulators = Self::scan(host).await?;
        let mut ios_sims: Vec<Self> = simulators.into_iter().filter(ios_filter).collect();
        let mut healthy: Vec<Self> = ios_sims
            .iter()
            .filter(|s| s.data_path.exists())
            .cloned()
            .collect();
        if !healthy.is_empty() {
            return Ok(healthy);
        }

        if ios_sims.is_empty() {
            return Ok(Vec::new());
        }

        warn!(
            "No healthy iOS simulators found (missing data paths). Attempting automatic simulator repair."
        );

        // Best-effort cleanup first: remove stale entries from unavailable runtimes.
        if let Err(error) = host.run("xcrun", ["simctl", "delete", "unavailable"]).await {
            warn!("Failed to delete unavailable simulators: {error}");
        }

        // Re-scan after cleanup.
        ios_sims = Self::scan(host)
            .await?
            .into_iter()
            .filter(ios_filter)
            .collect();
        healthy = ios_sims
            .iter()
            .filter(|s| s.data_path.exists())
            .cloned()
            .collect();
        if !healthy.is_empty() {
            return Ok(healthy);
        }

        // If still broken, create a fresh simulator from a template.
        if let Some(template) = ios_sims
            .iter()
            .find(|s| s.device_type_identifier.contains("iPhone"))
            .or_else(|| ios_sims.first())
            .cloned()
            && let Some(runtime) = template.runtime_identifier.as_deref()
        {
            let generated_name = format!("{} (WaterUI)", template.name);
            match host
                .run(
                    "xcrun",
                    [
                        "simctl",
                        "create",
                        &generated_name,
                        &template.device_type_identifier,
                        runtime,
                    ],
                )
                .await
            {
                Ok(udid) => {
                    info!(
                        "Created replacement iOS simulator: {} ({})",
                        generated_name,
                        udid.trim()
                    );
                }
                Err(error) => {
                    warn!("Failed to create replacement iOS simulator: {error}");
                }
            }
        }

        // Final re-scan: return only healthy simulators.
        Ok(Self::scan(host)
            .await?
            .into_iter()
            .filter(ios_filter)
            .filter(|s| s.data_path.exists())
            .collect())
    }

    /// Whether this simulator's runtime can run an app that requires `deployment_target`.
    ///
    /// A simulator `simctl` reported no runtime version for is treated as
    /// incapable: selection must never pick a runtime it cannot prove satisfies
    /// the app's deployment target.
    #[must_use]
    pub fn supports_deployment_target(&self, deployment_target: &Version) -> bool {
        self.runtime_version
            .as_ref()
            .is_some_and(|runtime| runtime >= deployment_target)
    }

    /// Select the iOS simulator to run `project`'s app on.
    ///
    /// Reads the app's `IPHONEOS_DEPLOYMENT_TARGET` from the project and
    /// considers only simulators whose runtime satisfies it, so an app is never
    /// built for minutes only to be rejected by `simctl install`.
    ///
    /// `device` is the `--device` query: a UDID, or a device name. A matched
    /// simulator whose runtime is below the target is rejected; a name matching
    /// several qualifying simulators is an error listing the candidates. With
    /// `None`, the first booted qualifying simulator wins, else the first
    /// qualifying one.
    ///
    /// # Errors
    /// Returns an error when the deployment target cannot be read from the
    /// project, when `simctl` cannot be queried, when a `device` query matches
    /// nothing or only simulators below the target or several qualifying ones,
    /// or when no simulator satisfies the target.
    pub async fn select_ios(
        host: &Host,
        project: &Project,
        device: Option<&str>,
    ) -> eyre::Result<Self> {
        let (_, target) = apple_deployment_target(project, TargetPlatform::IOSSimulator).await?;
        let deployment_target = parse_semver_version(&target).wrap_err_with(|| {
            format!("Failed to parse the project's IPHONEOS_DEPLOYMENT_TARGET `{target}`")
        })?;
        let simulators = Self::scan_ios(host).await?;
        Self::select(&simulators, &deployment_target, device)
    }

    /// Select a simulator from `simulators` able to run an app that requires
    /// `deployment_target`.
    fn select(
        simulators: &[Self],
        deployment_target: &Version,
        device: Option<&str>,
    ) -> eyre::Result<Self> {
        if let Some(query) = device {
            return Self::select_matching(simulators, deployment_target, query);
        }

        simulators
            .iter()
            .filter(|sim| sim.supports_deployment_target(deployment_target))
            .min_by_key(|sim| usize::from(sim.state != "Booted"))
            .cloned()
            .ok_or_else(|| no_qualifying_simulator_error(simulators, deployment_target))
    }

    /// Resolve an explicit `--device` query — a UDID or a device name — against
    /// `simulators`, honoring `deployment_target`.
    fn select_matching(
        simulators: &[Self],
        deployment_target: &Version,
        query: &str,
    ) -> eyre::Result<Self> {
        let matches: Vec<&Self> = simulators
            .iter()
            .filter(|sim| sim.udid == query || sim.name == query)
            .collect();
        if matches.is_empty() {
            bail!("Device not found: {query}");
        }

        let qualifying: Vec<&Self> = matches
            .iter()
            .copied()
            .filter(|sim| sim.supports_deployment_target(deployment_target))
            .collect();
        match qualifying.as_slice() {
            [sim] => Ok((*sim).clone()),
            [] => Err(unqualified_simulator_error(
                &matches,
                deployment_target,
                query,
            )),
            candidates => Err(ambiguous_simulator_error(
                candidates,
                deployment_target,
                query,
            )),
        }
    }

    /// `iOS <version>` when `simctl` reported one, else the raw runtime identifier.
    fn runtime_label(&self) -> String {
        self.runtime_version.as_ref().map_or_else(
            || {
                self.runtime_identifier
                    .clone()
                    .unwrap_or_else(|| String::from("an unknown runtime"))
            },
            |version| format!("iOS {version}"),
        )
    }
}

/// One line per simulator: `name (udid) — iOS version`.
fn simulator_candidates<'a>(simulators: impl IntoIterator<Item = &'a AppleSimulator>) -> String {
    use std::fmt::Write as _;
    simulators.into_iter().fold(String::new(), |mut out, sim| {
        write!(
            out,
            "\n  {} ({}) — {}",
            sim.name,
            sim.udid,
            sim.runtime_label()
        )
        .expect("writing to a String cannot fail");
        out
    })
}

/// Error for an explicit `--device` query whose matches all run a runtime below
/// `deployment_target`.
fn unqualified_simulator_error(
    matches: &[&AppleSimulator],
    deployment_target: &Version,
    query: &str,
) -> eyre::Report {
    if let [sim] = matches {
        return eyre!(
            "Simulator \"{}\" ({}) runs {}, but this app requires iOS {deployment_target} (IPHONEOS_DEPLOYMENT_TARGET)",
            sim.name,
            sim.udid,
            sim.runtime_label(),
        );
    }
    eyre!(
        "Device \"{query}\" matches {} simulators, but none can run this app, which requires iOS {deployment_target} (IPHONEOS_DEPLOYMENT_TARGET):{}",
        matches.len(),
        simulator_candidates(matches.iter().copied()),
    )
}

/// Error for a `--device` name matching several simulators that all satisfy
/// `deployment_target`: picking silently would ignore which device the user meant.
fn ambiguous_simulator_error(
    candidates: &[&AppleSimulator],
    deployment_target: &Version,
    query: &str,
) -> eyre::Report {
    eyre!(
        "Device \"{query}\" matches {} simulators that can run this app (iOS {deployment_target} or newer); select one by UDID:{}",
        candidates.len(),
        simulator_candidates(candidates.iter().copied()),
    )
}

/// Error for automatic selection when nothing in `simulators` satisfies
/// `deployment_target`.
fn no_qualifying_simulator_error(
    simulators: &[AppleSimulator],
    deployment_target: &Version,
) -> eyre::Report {
    if simulators.is_empty() {
        return eyre!("No iOS simulators available. Create one in Xcode.");
    }
    eyre!(
        "No iOS simulator can run this app: it requires iOS {deployment_target} (IPHONEOS_DEPLOYMENT_TARGET). Available simulators:{}",
        simulator_candidates(simulators.iter()),
    )
}

/// Capture a screenshot from an iOS simulator.
///
/// Uses `xcrun simctl io <udid> screenshot <output_path>` to capture
/// the current screen of the simulator.
///
/// # Errors
///
/// Returns an error if the screenshot command fails or the simulator
/// is not available.
pub async fn screenshot(host: &Host, udid: &str, output: &Path) -> eyre::Result<()> {
    host.run(
        "xcrun",
        [
            "simctl",
            "io",
            udid,
            "screenshot",
            output
                .to_str()
                .ok_or_else(|| eyre!("Invalid output path"))?,
        ],
    )
    .await?;
    Ok(())
}

/// Capture a screenshot from an iOS simulator and return the raw PNG bytes.
///
/// This is used for the diff workflow where we need in-memory screenshots.
///
/// # Errors
///
/// Returns an error if the screenshot command fails or the simulator is not available.
pub async fn screenshot_bytes(host: &Host, udid: &str) -> eyre::Result<Vec<u8>> {
    // Use "-" to output to stdout
    let output = host
        .output("xcrun", ["simctl", "io", udid, "screenshot", "-"])
        .await?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        eyre::bail!("Failed to capture screenshot: {}", stderr.trim());
    }

    Ok(output.stdout)
}

/// Check if IDB (iOS Development Bridge) is installed.
///
/// IDB is required for gesture automation on iOS simulators.
async fn check_idb_installed(host: &Host) -> eyre::Result<()> {
    if host.which("idb").await.is_err() {
        eyre::bail!(
            "IDB (iOS Development Bridge) is not installed.\n\n\
            Gesture commands require IDB for iOS simulator automation.\n\n\
            To install IDB:\n\
            \x20 brew tap facebook/fb && brew install idb-companion\n\
            \x20 pipx install fb-idb --python python3.12\n\n\
            For more information: https://fbidb.io/"
        );
    }

    Ok(())
}

/// Perform a tap gesture on an iOS simulator at the specified coordinates.
///
/// Uses IDB (iOS Development Bridge) to send touch events to the simulator.
///
/// # Arguments
///
/// * `udid` - The simulator's unique device identifier
/// * `x` - X coordinate within the simulator screen
/// * `y` - Y coordinate within the simulator screen
///
/// # Errors
///
/// Returns an error if IDB is not installed or the tap fails.
pub async fn tap(host: &Host, udid: &str, x: u32, y: u32) -> eyre::Result<()> {
    check_idb_installed(host).await?;

    let output = host
        .output(
            "idb",
            ["ui", "tap", "--udid", udid, &x.to_string(), &y.to_string()],
        )
        .await?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        eyre::bail!("Failed to tap: {}", stderr.trim());
    }

    Ok(())
}

/// Perform a swipe gesture on an iOS simulator.
///
/// Uses IDB (iOS Development Bridge) to send swipe events to the simulator.
///
/// # Arguments
///
/// * `udid` - The simulator's unique device identifier
/// * `from` - Starting coordinates (x, y)
/// * `to` - Ending coordinates (x, y)
/// * `duration_ms` - Duration of the swipe in milliseconds (optional)
///
/// # Errors
///
/// Returns an error if IDB is not installed or the swipe fails.
pub async fn swipe(
    host: &Host,
    udid: &str,
    from: (u32, u32),
    to: (u32, u32),
    duration_ms: Option<u32>,
) -> eyre::Result<()> {
    check_idb_installed(host).await?;

    let mut args = vec![
        "ui".to_string(),
        "swipe".to_string(),
        "--udid".to_string(),
        udid.to_string(),
        from.0.to_string(),
        from.1.to_string(),
        to.0.to_string(),
        to.1.to_string(),
    ];

    if let Some(duration) = duration_ms {
        // IDB uses duration in seconds as a float
        let duration_sec = f64::from(duration) / 1000.0;
        args.push("--duration".to_string());
        args.push(format!("{duration_sec:.2}"));
    }

    let output = host.output("idb", args).await?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        eyre::bail!("Failed to swipe: {}", stderr.trim());
    }

    Ok(())
}

/// Input text on an iOS simulator.
///
/// Uses IDB (iOS Development Bridge) to send text input to the simulator.
///
/// # Errors
///
/// Returns an error if IDB is not installed or the text input fails.
pub async fn text(host: &Host, udid: &str, input: &str) -> eyre::Result<()> {
    check_idb_installed(host).await?;

    let output = host
        .output("idb", ["ui", "text", "--udid", udid, input])
        .await?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        eyre::bail!("Failed to input text: {}", stderr.trim());
    }

    Ok(())
}

/// Describe UI elements on the screen.
///
/// Uses IDB to get accessibility information about all UI elements.
/// Returns JSON string with element details (frame, label, type, etc.).
///
/// # Errors
///
/// Returns an error if IDB is not installed or the command fails.
pub async fn describe(host: &Host, udid: &str) -> eyre::Result<String> {
    check_idb_installed(host).await?;

    let output = host
        .output("idb", ["ui", "describe-all", "--udid", udid, "--json"])
        .await?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        eyre::bail!("Failed to describe UI: {}", stderr.trim());
    }

    let json = String::from_utf8_lossy(&output.stdout).to_string();
    Ok(json)
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use semver::Version;

    use super::{AppleSimulator, parse_simctl_launch_pid};
    use crate::utils::parse_semver_version;

    fn ios_simulator(name: &str, udid: &str, state: &str, runtime: &str) -> AppleSimulator {
        AppleSimulator {
            data_path: PathBuf::new(),
            data_path_size: None,
            log_path: PathBuf::new(),
            log_path_size: None,
            udid: udid.to_string(),
            is_available: true,
            device_type_identifier: "com.apple.CoreSimulator.SimDeviceType.iPhone-16-Pro"
                .to_string(),
            state: state.to_string(),
            name: name.to_string(),
            last_booted_at: None,
            runtime_identifier: Some(format!(
                "com.apple.CoreSimulator.SimRuntime.iOS-{}",
                runtime.replace('.', "-")
            )),
            runtime_version: Some(
                parse_semver_version(runtime).expect("test runtime version should parse"),
            ),
        }
    }

    fn target(version: &str) -> Version {
        parse_semver_version(version).expect("test target should parse")
    }

    #[test]
    fn parses_simctl_launch_pid_from_bundle_prefix() {
        let stdout = "com.example.app: 12345\n";
        assert_eq!(parse_simctl_launch_pid(stdout), Some(12345));
    }

    #[test]
    fn parses_simctl_launch_pid_from_plain_pid() {
        let stdout = "12345\n";
        assert_eq!(parse_simctl_launch_pid(stdout), Some(12345));
    }

    #[test]
    fn returns_none_when_no_pid_present() {
        let stdout = "com.example.app: not-a-pid\n";
        assert_eq!(parse_simctl_launch_pid(stdout), None);
    }

    #[test]
    fn simulator_below_target_does_not_qualify() {
        let sim = ios_simulator("iPhone 16 Pro", "UDID-18", "Booted", "18.5");
        assert!(!sim.supports_deployment_target(&target("26.0")));
        assert!(sim.supports_deployment_target(&target("18.5")));
        assert!(sim.supports_deployment_target(&target("17.0")));
    }

    #[test]
    fn simulator_without_runtime_version_never_qualifies() {
        let mut sim = ios_simulator("iPhone 16 Pro", "UDID-X", "Booted", "18.5");
        sim.runtime_version = None;
        assert!(!sim.supports_deployment_target(&target("1.0")));
    }

    #[test]
    fn automatic_selection_prefers_booted_qualifying_simulator() {
        let sims = vec![
            ios_simulator("iPhone 16 Pro", "UDID-18-BOOTED", "Booted", "18.5"),
            ios_simulator("iPhone 16 Pro", "UDID-26-BOOTED", "Booted", "26.5"),
            ios_simulator("iPhone 16 Pro", "UDID-26-SHUTDOWN", "Shutdown", "26.5"),
        ];
        let selected = AppleSimulator::select(&sims, &target("26.0"), None)
            .expect("a qualifying booted simulator exists");
        assert_eq!(selected.udid, "UDID-26-BOOTED");
    }

    #[test]
    fn automatic_selection_falls_back_to_shutdown_qualifying_simulator() {
        let sims = vec![
            ios_simulator("iPhone 16 Pro", "UDID-18-BOOTED", "Booted", "18.5"),
            ios_simulator("iPhone 16 Pro", "UDID-26-SHUTDOWN", "Shutdown", "26.5"),
        ];
        let selected = AppleSimulator::select(&sims, &target("26.0"), None)
            .expect("a qualifying simulator exists");
        assert_eq!(selected.udid, "UDID-26-SHUTDOWN");
    }

    #[test]
    fn automatic_selection_names_target_when_nothing_qualifies() {
        let sims = vec![ios_simulator("iPhone 16 Pro", "UDID-18", "Booted", "18.5")];
        let error = AppleSimulator::select(&sims, &target("26.0"), None).unwrap_err();
        let message = error.to_string();
        assert!(message.contains("26.0.0"), "{message}");
        assert!(message.contains("UDID-18"), "{message}");
    }

    #[test]
    fn explicit_device_below_target_is_rejected() {
        let sims = vec![ios_simulator("iPhone 16 Pro", "UDID-18", "Booted", "18.5")];
        let error = AppleSimulator::select(&sims, &target("26.0"), Some("UDID-18")).unwrap_err();
        let message = error.to_string();
        assert!(message.contains("iPhone 16 Pro"), "{message}");
        assert!(message.contains("UDID-18"), "{message}");
        assert!(message.contains("18.5"), "{message}");
        assert!(message.contains("26.0.0"), "{message}");
    }

    #[test]
    fn explicit_name_selects_the_qualifying_simulator() {
        // Two same-named simulators on different runtimes: only the one
        // satisfying the target is a usable pick.
        let sims = vec![
            ios_simulator("iPhone 16 Pro", "UDID-18", "Booted", "18.5"),
            ios_simulator("iPhone 16 Pro", "UDID-26", "Shutdown", "26.5"),
        ];
        let selected = AppleSimulator::select(&sims, &target("26.0"), Some("iPhone 16 Pro"))
            .expect("exactly one match qualifies");
        assert_eq!(selected.udid, "UDID-26");
    }

    #[test]
    fn explicit_name_matching_several_qualifying_simulators_is_ambiguous() {
        let sims = vec![
            ios_simulator("iPhone 16 Pro", "UDID-26-A", "Booted", "26.5"),
            ios_simulator("iPhone 16 Pro", "UDID-26-B", "Shutdown", "26.5"),
        ];
        let error =
            AppleSimulator::select(&sims, &target("26.0"), Some("iPhone 16 Pro")).unwrap_err();
        let message = error.to_string();
        assert!(message.contains("UDID-26-A"), "{message}");
        assert!(message.contains("UDID-26-B"), "{message}");
    }

    #[test]
    fn explicit_device_not_found() {
        let sims = vec![ios_simulator("iPhone 16 Pro", "UDID-26", "Booted", "26.5")];
        let error = AppleSimulator::select(&sims, &target("26.0"), Some("iPhone 17")).unwrap_err();
        assert!(error.to_string().contains("iPhone 17"));
    }
}