waterui-cli 0.1.3

A modern UI framework for Rust
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
use color_eyre::eyre::{self, eyre};
use smol::process::Command;
use tracing::error;

use std::process::Stdio;

use crate::{
    android::{platform::AndroidPlatform, toolchain::AndroidSdk},
    device::{Artifact, Device, DeviceEvent, FailToRun, LogLevel, RunOptions, Running},
    utils::{parse_whitespace_separated_u32s, run_command, run_command_output},
};

/// Represents an Android device (physical or emulator).
#[derive(Debug)]
pub struct AndroidDevice {
    identifier: String,
    /// Primary ABI of the device (e.g., "arm64-v8a", "`x86_64`")
    abi: String,
}

impl AndroidDevice {
    /// Create a new Android device with the given identifier and ABI.
    #[must_use]
    pub const fn new(identifier: String, abi: String) -> Self {
        Self { identifier, abi }
    }

    /// Get the device identifier.
    #[must_use]
    pub fn identifier(&self) -> &str {
        &self.identifier
    }

    /// Get the device's primary ABI.
    #[must_use]
    pub fn abi(&self) -> &str {
        &self.abi
    }
}

impl Device for AndroidDevice {
    type Platform = AndroidPlatform;

    async fn launch(&self) -> eyre::Result<()> {
        let adb = AndroidSdk::adb_path()
            .ok_or_else(|| eyre::eyre!("Android SDK not found or adb not installed"))?;
        run_command(
            adb.to_str().unwrap(),
            ["-s", &self.identifier, "wait-for-device"],
        )
        .await?;
        Ok(())
    }

    fn platform(&self) -> Self::Platform {
        AndroidPlatform::from_abi(&self.abi)
    }

    async fn run(&self, artifact: Artifact, options: RunOptions) -> Result<Running, FailToRun> {
        run_on_android(&self.identifier, artifact, options).await
    }
}

/// Shared implementation for running an app on any Android device.
///
/// This handles:
/// - Passing environment variables as intent extras
/// - Uninstalling previous version (to avoid storage issues)
/// - Installing the APK
/// - Launching the app
/// - Monitoring process state
/// - Streaming logs
#[allow(clippy::too_many_lines)]
async fn run_on_android(
    device_id: &str,
    artifact: Artifact,
    options: RunOptions,
) -> Result<Running, FailToRun> {
    let adb = AndroidSdk::adb_path()
        .ok_or_else(|| FailToRun::Run(eyre!("Android SDK not found or adb not installed")))?;
    let adb_str = adb.to_str().unwrap();

    let env_vars: Vec<(String, String)> = options
        .env_vars()
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .collect();

    // If hot reload is using localhost, set up adb reverse so the device can connect back
    // to the host's hot reload server (listening on 127.0.0.1:<port>).
    let reverse_port = env_vars
        .iter()
        .find(|(k, _)| k == "WATERUI_HOT_RELOAD_PORT")
        .and_then(|(_, v)| v.parse::<u16>().ok())
        .zip(
            env_vars
                .iter()
                .find(|(k, _)| k == "WATERUI_HOT_RELOAD_HOST")
                .map(|(_, v)| v.as_str()),
        )
        .and_then(|(port, host)| {
            if host == "127.0.0.1" || host == "localhost" {
                Some(port)
            } else {
                None
            }
        });

    if let Some(port) = reverse_port {
        let spec = format!("tcp:{port}");
        let output = Command::new(adb_str)
            .args(["-s", device_id, "reverse", &spec, &spec])
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output()
            .await;

        match output {
            Ok(output) if output.status.success() => {}
            Ok(output) => {
                tracing::warn!(
                    "Failed to set up adb reverse for hot reload ({}): stdout='{}' stderr='{}'",
                    spec,
                    String::from_utf8_lossy(&output.stdout).trim(),
                    String::from_utf8_lossy(&output.stderr).trim()
                );
            }
            Err(e) => {
                tracing::warn!("Failed to set up adb reverse for hot reload ({spec}): {e}");
            }
        }
    }

    // Install the APK on the device with -r flag to replace existing installation
    // This handles both cases: fresh install and reinstall over existing app
    run_command(
        adb_str,
        [
            "-s",
            device_id,
            "install",
            "-r",
            artifact.path().to_str().unwrap(),
        ],
    )
    .await
    .map_err(|e| FailToRun::Install(eyre!("Failed to install APK: {e}")))?;

    // Launch the app (pass env vars as intent extras).
    //
    // We use the "waterui.env.<KEY>" namespace to avoid collisions.
    // MainActivity reads these extras and calls Os.setenv() before loading native libraries.
    let mut start_args = vec![
        "-s".to_string(),
        device_id.to_string(),
        "shell".to_string(),
        "am".to_string(),
        "start".to_string(),
        "-S".to_string(), // force-stop target app before starting (ensures env takes effect)
        "-n".to_string(),
        format!("{}/.MainActivity", artifact.bundle_id()),
    ];

    for (key, value) in &env_vars {
        start_args.push("--es".to_string());
        start_args.push(format!("waterui.env.{key}"));
        start_args.push(value.clone());
    }

    let output = Command::new(adb_str)
        .args(&start_args)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .await
        .map_err(|e| FailToRun::Launch(eyre!("Failed to launch app: {e}")))?;

    if !output.status.success() {
        return Err(FailToRun::Launch(eyre!(
            "Failed to launch app:\n{}\n{}",
            String::from_utf8_lossy(&output.stdout).trim(),
            String::from_utf8_lossy(&output.stderr).trim(),
        )));
    }

    // Wait for the process to start and get its PID
    let pid = wait_for_app_pid(adb_str, device_id, artifact.bundle_id()).await?;

    let adb_for_kill = adb.clone();
    let identifier_for_kill = device_id.to_string();
    let identifier_for_monitor = device_id.to_string();
    let bundle_id_for_kill = artifact.bundle_id().to_string();
    let bundle_id_for_monitor = artifact.bundle_id().to_string();
    let log_level = options.log_level();
    let reverse_port_for_drop = reverse_port;

    let (running, sender) = Running::new(move || {
        // Use std::process::Command for synchronous execution in Drop context
        let result = std::process::Command::new(&adb_for_kill)
            .args([
                "-s",
                &identifier_for_kill,
                "shell",
                "am",
                "force-stop",
                &bundle_id_for_kill,
            ])
            .output();

        match result {
            Ok(output) => {
                tracing::debug!(
                    "Force-stop command executed: status={}, stdout={}, stderr={}",
                    output.status,
                    String::from_utf8_lossy(&output.stdout),
                    String::from_utf8_lossy(&output.stderr)
                );
            }
            Err(e) => {
                error!("Failed to stop app {}: {}", bundle_id_for_kill, e);
            }
        }

        if let Some(port) = reverse_port_for_drop {
            let spec = format!("tcp:{port}");
            let _ = std::process::Command::new(&adb_for_kill)
                .args(["-s", &identifier_for_kill, "reverse", "--remove", &spec])
                .output();
        }
    });

    // Spawn a background task to monitor the process
    let adb_for_monitor = adb.clone();
    let sender_for_monitor = sender.clone();
    smol::spawn(async move {
        monitor_android_process(
            adb_for_monitor,
            &identifier_for_monitor,
            &bundle_id_for_monitor,
            pid,
            sender_for_monitor,
        )
        .await;
    })
    .detach();

    // Spawn a background task to stream logs if log_level is set
    if let Some(level) = log_level {
        let adb_for_logs = adb;
        let identifier_for_logs = device_id.to_string();
        smol::spawn(async move {
            stream_android_logs(adb_for_logs, &identifier_for_logs, pid, level, sender).await;
        })
        .detach();
    }

    Ok(running)
}

/// Wait for an app to start and return its PID.
async fn wait_for_app_pid(
    adb_str: &str,
    device_id: &str,
    bundle_id: &str,
) -> Result<u32, FailToRun> {
    for _ in 0..10 {
        smol::Timer::after(std::time::Duration::from_millis(200)).await;
        if let Ok(output) =
            run_command(adb_str, ["-s", device_id, "shell", "pidof", bundle_id]).await
        {
            if let Some(pid) = parse_whitespace_separated_u32s(&output).into_iter().next() {
                return Ok(pid);
            }
        }
    }

    // App likely crashed on startup - fetch logcat for crash info
    let crash_info = run_command(
        adb_str,
        [
            "-s",
            device_id,
            "logcat",
            "-d",
            "-t",
            "100",
            "-s",
            "AndroidRuntime:E",
            "DEBUG:*",
            "WaterUI:*",
        ],
    )
    .await
    .unwrap_or_default();

    let mut error_msg = format!("App {bundle_id} crashed on startup (process not found).\n\n");

    if !crash_info.trim().is_empty() {
        error_msg.push_str("=== Crash Log ===\n");
        error_msg.push_str(&crash_info);
    }

    Err(FailToRun::Launch(eyre!("{}", error_msg)))
}

/// Find the running emulator's device identifier.
async fn find_emulator_identifier() -> Result<String, FailToRun> {
    let adb = AndroidSdk::adb_path()
        .ok_or_else(|| FailToRun::Run(eyre!("Android SDK not found or adb not installed")))?;

    let output = run_command(adb.to_str().unwrap(), ["devices"])
        .await
        .map_err(|e| FailToRun::Run(eyre!("Failed to list devices: {e}")))?;

    output
        .lines()
        .skip(1)
        .find_map(|line| {
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() >= 2 && parts[0].starts_with("emulator-") && parts[1] == "device" {
                Some(parts[0].to_string())
            } else {
                None
            }
        })
        .ok_or_else(|| FailToRun::Run(eyre!("Emulator not running")))
}

/// Monitor an Android process and send events when it crashes or exits.
async fn monitor_android_process(
    adb: std::path::PathBuf,
    device_id: &str,
    bundle_id: &str,
    pid: u32,
    sender: smol::channel::Sender<DeviceEvent>,
) {
    let adb_str = adb.to_str().unwrap_or_default();

    // Check process status periodically
    loop {
        smol::Timer::after(std::time::Duration::from_secs(1)).await;

        // Check if process is still running using pidof
        // Note: We use pidof instead of kill -0 because kill -0 returns "Operation not permitted"
        // when the shell user doesn't have permission to send signals to the app process
        let result = run_command(adb_str, ["-s", device_id, "shell", "pidof", bundle_id]).await;

        // Check if the process with the same PID is still running
        let still_running = result
            .as_ref()
            .ok()
            .map(|output| parse_whitespace_separated_u32s(output))
            .is_some_and(|pids| pids.contains(&pid));

        if !still_running {
            // Give crash reporting a brief moment to flush logs.
            smol::Timer::after(std::time::Duration::from_millis(500)).await;

            // Try to fetch logs for this PID (best signal for distinguishing crash vs normal exit).
            let pid_arg = format!("--pid={pid}");
            let pid_log_args = vec![
                "-s".to_string(),
                device_id.to_string(),
                "logcat".to_string(),
                "-v".to_string(),
                "threadtime".to_string(),
                "-d".to_string(),
                "-t".to_string(),
                "200".to_string(),
                pid_arg,
                "*:V".to_string(),
            ];
            let pid_log = run_command_output(adb_str, pid_log_args.iter().map(String::as_str))
                .await
                .ok()
                .filter(|o| o.status.success())
                .map(|o| String::from_utf8_lossy(&o.stdout).to_string())
                .unwrap_or_default();

            // Fallback for older logcat versions that don't support --pid.
            let fallback_log = if pid_log.trim().is_empty() {
                let fallback_args = vec![
                    "-s".to_string(),
                    device_id.to_string(),
                    "logcat".to_string(),
                    "-v".to_string(),
                    "threadtime".to_string(),
                    "-d".to_string(),
                    "-t".to_string(),
                    "200".to_string(),
                    "-s".to_string(),
                    "AndroidRuntime:E".to_string(),
                    "DEBUG:*".to_string(),
                    "libc:F".to_string(),
                ];
                run_command_output(adb_str, fallback_args.iter().map(String::as_str))
                    .await
                    .ok()
                    .filter(|o| o.status.success())
                    .map(|o| String::from_utf8_lossy(&o.stdout).to_string())
                    .unwrap_or_default()
            } else {
                String::new()
            };

            let pid_filtered = !pid_log.trim().is_empty();
            let log_for_detection = if pid_filtered {
                pid_log.as_str()
            } else {
                fallback_log.as_str()
            };

            if android_log_looks_like_crash(log_for_detection, bundle_id, pid, pid_filtered) {
                let crash_log = if pid_log.trim().is_empty() {
                    fallback_log
                } else {
                    pid_log
                };

                let error_msg = if crash_log.trim().is_empty() {
                    format!("Process {bundle_id} crashed.")
                } else {
                    format!("Process {bundle_id} crashed.\n\n=== Crash Log ===\n{crash_log}")
                };

                let _ = sender.send(DeviceEvent::Crashed(error_msg)).await;
            } else {
                let _ = sender.send(DeviceEvent::Exited).await;
            }
            break;
        }
    }
}

fn log_mentions_pid(log: &str, pid: u32) -> bool {
    let pid_str = pid.to_string();
    let pid_lower = format!("pid: {pid}");
    let pid_upper = format!("PID: {pid}");

    log.lines().any(|line| {
        line.split_whitespace().any(|part| part == pid_str)
            || line.contains(&pid_lower)
            || line.contains(&pid_upper)
    })
}

fn android_log_looks_like_crash(log: &str, bundle_id: &str, pid: u32, pid_filtered: bool) -> bool {
    if log.trim().is_empty() {
        return false;
    }

    // When we don't have a PID-filtered dump (older logcat), ensure we don't accidentally pick up
    // crashes from unrelated processes.
    let relevant = pid_filtered || log.contains(bundle_id) || log_mentions_pid(log, pid);
    if !relevant {
        return false;
    }

    // Common Java crash markers (AndroidRuntime).
    if log.contains("FATAL EXCEPTION") {
        return true;
    }

    // Common native crash markers (tombstone / debuggerd / libc).
    if log.contains("Fatal signal") {
        return true;
    }
    if log.contains("SIGSEGV")
        || log.contains("SIGABRT")
        || log.contains("SIGBUS")
        || log.contains("SIGILL")
        || log.contains("SIGFPE")
    {
        return true;
    }
    if log.contains("Abort message:") || log.contains("backtrace:") {
        return true;
    }

    // If we only have a global log fallback (no --pid), make sure it actually mentions this app
    // and includes an error marker to avoid false positives from unrelated processes.
    if !log.contains(bundle_id) {
        return false;
    }

    // Heuristic: treat AndroidRuntime errors for this process as crash.
    log.contains("AndroidRuntime")
        && (log.contains("E AndroidRuntime") || log.contains("Exception"))
}

/// Stream logs from an Android process using logcat.
async fn stream_android_logs(
    adb: std::path::PathBuf,
    device_id: &str,
    pid: u32,
    level: LogLevel,
    sender: smol::channel::Sender<DeviceEvent>,
) {
    use futures::StreamExt;
    use futures::io::{AsyncBufReadExt, BufReader};
    use smol::process::Command;

    let priority = level.to_android_priority();

    // Build logcat command with PID filter and minimum priority
    // Format: `adb -s <device> logcat --pid=<pid> *:<priority>`
    let pid_arg = format!("--pid={pid}");
    let mut cmd = Command::new(&adb);
    cmd.args(["-s", device_id, "logcat", "-v", "threadtime"])
        .arg(pid_arg)
        .arg(format!("*:{priority}"))
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null());

    let mut child = match cmd.spawn() {
        Ok(c) => c,
        Err(e) => {
            tracing::warn!("Failed to spawn logcat: {e}");
            return;
        }
    };

    let Some(stdout) = child.stdout.take() else {
        return;
    };

    let reader = BufReader::new(stdout);
    let mut lines = reader.lines();

    // Parse logcat output and send as DeviceEvent::Log
    // Logcat format: "MM-DD HH:MM:SS.mmm  PID  TID LEVEL TAG: message"
    while let Some(result) = lines.next().await {
        let Ok(line) = result else { break };

        let (parsed_level, message) = parse_logcat_line(&line);

        let _ = sender
            .send(DeviceEvent::Log {
                level: parsed_level,
                message,
            })
            .await;
    }

    // Clean up child process
    let _ = child.kill();
}

/// Parsed logcat line with level, tag, and message.
struct LogcatParsed {
    level: tracing::Level,
    tag: String,
    message: String,
}

/// Parse a logcat line into level, tag, and message.
/// Logcat threadtime format: "MM-DD HH:MM:SS.mmm  PID  TID LEVEL TAG: message"
fn parse_logcat_line(line: &str) -> (tracing::Level, String) {
    // Try to parse the structured format
    if let Some(parsed) = try_parse_logcat(line) {
        let formatted = format!("[{}] {}", parsed.tag, parsed.message);
        return (parsed.level, formatted);
    }

    // Fallback: return raw line with default level
    (tracing::Level::INFO, line.to_string())
}

/// Try to parse a logcat line. Returns None if parsing fails.
fn try_parse_logcat(line: &str) -> Option<LogcatParsed> {
    // Logcat threadtime format: "MM-DD HH:MM:SS.mmm  PID  TID LEVEL TAG: message"
    // Example: "12-10 23:04:40.190 28184 28184 D WaterUI : Touch..."

    // Split by whitespace, but we need to be careful about the message part
    let parts: Vec<&str> = line.splitn(7, char::is_whitespace).collect();

    // We need at least: date, time, pid, tid, level, tag, message
    if parts.len() < 6 {
        return None;
    }

    // Find the level character (should be single char: V, D, I, W, E, F)
    let mut level_idx = None;
    for (i, part) in parts.iter().enumerate() {
        if part.len() == 1 {
            let c = part.chars().next()?;
            if matches!(c, 'V' | 'D' | 'I' | 'W' | 'E' | 'F') {
                level_idx = Some(i);
                break;
            }
        }
    }

    let level_idx = level_idx?;
    if level_idx + 1 >= parts.len() {
        return None;
    }

    let level = match parts[level_idx] {
        "E" | "F" => tracing::Level::ERROR,
        "W" => tracing::Level::WARN,
        "D" => tracing::Level::DEBUG,
        "V" => tracing::Level::TRACE,
        _ => tracing::Level::INFO,
    };

    // The rest after level is "TAG: message" or "TAG     : message"
    // Find the position of the level character in the original line (after timestamp)
    // Skip past timestamp "MM-DD HH:MM:SS.mmm" which is about 18 chars
    let level_char = parts[level_idx].chars().next()?;
    let search_start = 18.min(line.len());
    let level_pos = line[search_start..]
        .find(level_char)
        .map(|p| p + search_start)?;

    let after_level = line.get(level_pos + 1..)?.trim_start();

    // Split by ": " to get tag and message
    after_level.find(": ").map_or_else(
        || {
            Some(LogcatParsed {
                level,
                tag: "unknown".to_string(),
                message: after_level.to_string(),
            })
        },
        |colon_pos| {
            let tag = after_level[..colon_pos].trim();
            let message = after_level[colon_pos + 2..].to_string();
            Some(LogcatParsed {
                level,
                tag: tag.to_string(),
                message,
            })
        },
    )
}

/// Android emulator (AVD) that needs to be launched.
///
/// Unlike `AndroidDevice` which represents an already-connected device,
/// `AndroidEmulator` represents an AVD that will be launched when `launch()` is called.
#[derive(Debug)]
pub struct AndroidEmulator {
    /// AVD name.
    avd_name: String,
}

impl AndroidEmulator {
    /// Create a new Android emulator with the given AVD name.
    #[must_use]
    pub const fn new(avd_name: String) -> Self {
        Self { avd_name }
    }

    /// Get the AVD name.
    #[must_use]
    pub fn avd_name(&self) -> &str {
        &self.avd_name
    }
}

impl Device for AndroidEmulator {
    type Platform = AndroidPlatform;

    async fn launch(&self) -> eyre::Result<()> {
        let emulator_path =
            AndroidSdk::emulator_path().ok_or_else(|| eyre::eyre!("Android emulator not found"))?;

        // Start the emulator process (don't wait for it here, we'll poll for readiness)
        Command::new(&emulator_path)
            .arg("-avd")
            .arg(&self.avd_name)
            .arg("-no-snapshot-load")
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .spawn()?;

        // Wait for the emulator to boot by polling adb devices
        let adb_path =
            AndroidSdk::adb_path().ok_or_else(|| eyre::eyre!("Android adb not found"))?;

        let start = std::time::Instant::now();
        let timeout = std::time::Duration::from_secs(120);

        loop {
            if start.elapsed() > timeout {
                eyre::bail!("Emulator launch timed out after 120 seconds");
            }

            // Check for booted emulator via adb
            if let Ok(output) = Command::new(&adb_path).arg("devices").output().await {
                if let Ok(stdout) = String::from_utf8(output.stdout) {
                    for line in stdout.lines().skip(1) {
                        let parts: Vec<&str> = line.split_whitespace().collect();
                        if parts.len() >= 2
                            && parts[0].starts_with("emulator-")
                            && parts[1] == "device"
                        {
                            // Emulator is ready
                            return Ok(());
                        }
                    }
                }
            }

            smol::Timer::after(std::time::Duration::from_secs(2)).await;
        }
    }

    fn platform(&self) -> Self::Platform {
        // Default to arm64 for emulators - most common architecture
        AndroidPlatform::arm64()
    }

    async fn run(&self, artifact: Artifact, options: RunOptions) -> Result<Running, FailToRun> {
        let identifier = find_emulator_identifier().await?;
        run_on_android(&identifier, artifact, options).await
    }
}

#[cfg(test)]
mod tests {
    use super::{android_log_looks_like_crash, log_mentions_pid};

    #[test]
    fn detects_pid_mentions_in_threadtime_lines() {
        let log = "12-10 23:04:40.190 28184 28184 F libc    : Fatal signal 11 (SIGSEGV)\n";
        assert!(log_mentions_pid(log, 28184));
        assert!(!log_mentions_pid(log, 12345));
    }

    #[test]
    fn avoids_false_positive_from_unrelated_fatal_signal_in_global_dump() {
        let unrelated = "12-10 23:04:40.190 999 999 F libc    : Fatal signal 11 (SIGSEGV)\n";
        assert!(!android_log_looks_like_crash(
            unrelated,
            "com.example.app",
            28184,
            false
        ));
    }

    #[test]
    fn detects_native_crash_when_pid_is_mentioned() {
        let log = "I DEBUG : Fatal signal 11 (SIGSEGV), code 1, fault addr 0x0 in tid 1 (main) pid: 28184\n";
        assert!(android_log_looks_like_crash(
            log,
            "com.example.app",
            28184,
            false
        ));
    }

    #[test]
    fn detects_java_crash_for_app() {
        let log = "E AndroidRuntime: FATAL EXCEPTION: main\nE AndroidRuntime: Process: com.example.app, PID: 28184\n";
        assert!(android_log_looks_like_crash(
            log,
            "com.example.app",
            28184,
            false
        ));
    }
}