autumn-web 0.7.0

An opinionated, convention-over-configuration web framework for Rust
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
//! Locating a usable Chromium/Chrome binary on the host.
//!
//! Shared by the `system_test` harness (which launches the browser it finds;
//! feature `system-tests`, so this always-compiled module cannot link to it)
//! and `autumn doctor` (which only reports on it).
//! Both used to carry their own copy of this logic and drifted — a fix in one
//! left the other reporting the opposite answer on the same machine — so the
//! resolution order, the version probe, and its platform quirks live here
//! once.
//!
//! Deliberately **not** behind the `system-tests` feature: `autumn doctor`
//! must be able to tell you whether system tests would work without pulling
//! `chromiumoxide` (and a headless browser stack) into the CLI.
//!
//! # Resolution order
//!
//! 1. `AUTUMN_CHROMIUM` environment variable (full binary path)
//! 2. `PLAYWRIGHT_BROWSERS_PATH` — scans `<path>/chromium-*/…`
//! 3. `PATH`-based lookup (`chrome`, `google-chrome`, `chromium`, …)
//! 4. Well-known per-platform install locations

use std::fmt;
use std::path::{Path, PathBuf};

/// Version string reported for a browser binary that exists and is usable but
/// cannot tell us its version — see [`probe_version`].
pub const UNKNOWN_VERSION: &str = "version unavailable";

// ── BrowserCheck ───────────────────────────────────────────────────────────

/// Result of probing the host for a usable Chromium binary.
///
/// Returned by [`BrowserCheck::run`] and shown by `autumn doctor`.
#[derive(Debug, Clone)]
pub enum BrowserCheck {
    /// A usable binary was found at `path` with the reported `version` string.
    Found {
        /// Absolute path to the Chromium binary.
        path: PathBuf,
        /// Version string reported by `--version` (e.g. `"Chromium 122.0.6261.111"`),
        /// or [`UNKNOWN_VERSION`] when the platform cannot report one.
        version: String,
    },
    /// No usable binary could be found; `searched_paths` lists every path that
    /// was probed so the user knows what to add.
    NotFound {
        /// Every path that was checked and did not yield a working binary.
        searched_paths: Vec<PathBuf>,
    },
}

impl BrowserCheck {
    /// Probe the host for a Chromium binary using the documented resolution
    /// order and return the result.
    #[must_use]
    pub fn run() -> Self {
        let candidates = browser_candidates();
        let mut searched = Vec::new();
        for path in &candidates {
            if let Some(version) = probe_version(path) {
                return Self::Found {
                    path: path.clone(),
                    version,
                };
            }
            searched.push(path.clone());
        }
        Self::NotFound {
            searched_paths: searched,
        }
    }

    /// `true` when a browser was found.
    #[must_use]
    pub const fn is_found(&self) -> bool {
        matches!(self, Self::Found { .. })
    }
}

impl fmt::Display for BrowserCheck {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Found { path, version } => {
                write!(f, "Chromium found: {} ({})", path.display(), version)
            }
            Self::NotFound { searched_paths } => {
                write!(
                    f,
                    "Chromium not found. Searched:\n{}",
                    searched_paths
                        .iter()
                        .map(|p| format!("  {}", p.display()))
                        .collect::<Vec<_>>()
                        .join("\n")
                )?;
                write!(
                    f,
                    "\n\nTo install on Ubuntu/Debian: apt-get install chromium-browser\n\
                     Or set the AUTUMN_CHROMIUM environment variable to the full binary path."
                )
            }
        }
    }
}

// ── Candidate discovery ────────────────────────────────────────────────────

/// Binary names to look for on `PATH`, in preference order.
const PATH_BINARY_NAMES: &[&str] = &[
    "chrome",
    "google-chrome",
    "google-chrome-stable",
    "chromium",
    "chromium-browser",
];

/// All paths to probe for a Chromium binary, in resolution order.
#[must_use]
pub fn browser_candidates() -> Vec<PathBuf> {
    let mut candidates: Vec<PathBuf> = Vec::new();

    // 1. Explicit override.
    if let Ok(p) = std::env::var("AUTUMN_CHROMIUM") {
        candidates.push(PathBuf::from(p));
    }

    // 2. Playwright browsers directory.
    if let Ok(base) = std::env::var("PLAYWRIGHT_BROWSERS_PATH") {
        let base = PathBuf::from(base);
        if let Ok(entries) = std::fs::read_dir(&base) {
            let mut pw_paths: Vec<PathBuf> = entries
                .flatten()
                .filter(|e| e.file_name().to_string_lossy().starts_with("chromium-"))
                .map(|e| {
                    if cfg!(target_os = "macos") {
                        e.path()
                            .join("chrome-mac")
                            .join("Chromium.app")
                            .join("Contents")
                            .join("MacOS")
                            .join("Chromium")
                    } else if cfg!(target_os = "windows") {
                        e.path().join("chrome-win").join("chrome.exe")
                    } else {
                        e.path().join("chrome-linux").join("chrome")
                    }
                })
                .collect();
            pw_paths.sort();
            pw_paths.reverse(); // highest revision first
            candidates.extend(pw_paths);
        }
    }

    // 3. PATH-based lookup — covers CI setups like browser-actions/setup-chrome
    //    that install a `chrome` or `google-chrome` binary on PATH rather than
    //    at a well-known fixed location.
    candidates.extend(path_candidates(std::env::var_os("PATH").as_deref()));

    // 4. Well-known system paths.
    candidates.extend(well_known_paths());

    // A duplicate can only waste a probe and clutter the searched-paths list
    // in the not-found error (duplicate PATH entries are common).
    let mut seen = std::collections::HashSet::new();
    candidates.retain(|p| seen.insert(p.clone()));

    candidates
}

/// Every `PATH` directory holding one of [`PATH_BINARY_NAMES`], in `PATH`
/// order, for each name in preference order.
///
/// Returns **all** matches rather than the first per name. Existence is not
/// usability — [`probe_version`] is what decides — so a stale or
/// non-executable `chrome` early in `PATH` must not mask a working one a CI
/// setup action installed later. The extra entries cost one stat each.
///
/// Takes `PATH` as an argument rather than reading the environment so it is
/// testable without mutating process-wide state (which this crate forbids:
/// `unsafe_code = "forbid"`).
fn path_candidates(path_var: Option<&std::ffi::OsStr>) -> Vec<PathBuf> {
    let Some(path_var) = path_var else {
        return Vec::new();
    };

    let mut found = Vec::new();
    for name in PATH_BINARY_NAMES {
        // `Path::is_file` stats the literal path and does *not* apply
        // Windows' PATHEXT resolution, so a bare `chrome` never matches
        // `chrome.exe`. Ask for the name Windows actually stores on disk.
        let file_name = if cfg!(target_os = "windows") {
            format!("{name}.exe")
        } else {
            (*name).to_owned()
        };
        found.extend(
            std::env::split_paths(path_var)
                .map(|dir| dir.join(&file_name))
                .filter(|p| p.is_file()),
        );
    }
    found
}

/// Per-platform install locations, checked after `PATH`.
fn well_known_paths() -> Vec<PathBuf> {
    if cfg!(target_os = "windows") {
        // Chrome installs under `%ProgramFiles%` / `%ProgramFiles(x86)%` for a
        // machine-wide install and `%LOCALAPPDATA%` for the (very common)
        // per-user one. Read the variables rather than hard-coding `C:\` —
        // the system drive is not always `C:`, and the 32-bit variable name
        // contains parentheses, so it must be fetched by name.
        ["ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"]
            .iter()
            .filter_map(std::env::var_os)
            .flat_map(|base| {
                let base = PathBuf::from(base);
                ["Google\\Chrome", "Google\\Chrome Beta", "Chromium"]
                    .iter()
                    .map(move |vendor| base.join(vendor).join("Application").join("chrome.exe"))
            })
            .collect()
    } else {
        [
            "/usr/bin/chromium-browser",
            "/usr/bin/chromium",
            "/usr/bin/google-chrome",
            "/usr/bin/google-chrome-stable",
            "/snap/bin/chromium",
            "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
            "/Applications/Chromium.app/Contents/MacOS/Chromium",
        ]
        .iter()
        .map(PathBuf::from)
        .collect()
    }
}

/// Return the first candidate that exists and probes successfully.
#[must_use]
pub fn find_chromium() -> Option<PathBuf> {
    browser_candidates()
        .into_iter()
        .find(|path| probe_version(path).is_some())
}

// ── Version probe ──────────────────────────────────────────────────────────

/// Outcome of asking a candidate binary for its version.
#[derive(Debug, PartialEq, Eq)]
enum VersionProbe {
    /// The process ran and exited successfully; payload is its raw stdout
    /// (which may legitimately be empty for a launcher shim that prints
    /// elsewhere).
    Ran(String),
    /// The process could not be spawned, or exited non-zero. The candidate is
    /// not usable.
    Failed,
    /// The probe was deliberately not executed, but the file is a plausible
    /// browser binary. See [`run_version_probe`] for why Windows takes this
    /// path.
    Skipped,
}

/// Arguments for the `--version` probe.
///
/// The private `--user-data-dir` keeps the probe from touching the user's real
/// profile: launching Chrome against a profile another instance already holds
/// makes the new process rendezvous with the running one instead of answering
/// us (#1456). `--version` exits before profile setup on POSIX, so this is
/// belt-and-braces there rather than load-bearing — but it costs nothing and
/// covers wrapper scripts that do reach profile startup.
fn version_probe_args(user_data_dir: &Path) -> Vec<String> {
    vec![
        "--version".to_owned(),
        format!("--user-data-dir={}", user_data_dir.display()),
    ]
}

/// A throwaway profile directory for a single probe.
fn unique_probe_dir() -> PathBuf {
    static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    std::env::temp_dir().join(format!("autumn-browser-probe-{}-{n}", std::process::id()))
}

/// `true` when `path` names something that plausibly *is* a Chrome/Chromium
/// binary, judged from the filename alone.
///
/// The Windows branch accepts a candidate without running it, so this is the
/// only filter standing between a stale or mistyped `AUTUMN_CHROMIUM` and it
/// **ending discovery**: it is the first candidate, so accepting it stops
/// `find_chromium` from ever reaching a real Chrome further down the list, and
/// turns a clear `BrowserNotFound` (which prints every searched path and the
/// remediation hint) into an opaque failure later, inside `Browser::launch`.
///
/// Requiring `.exe` alone is not enough — every discovery source *except* the
/// env override already constrains the filename (`chrome.exe` under the
/// well-known install roots and the Playwright layout, the `PATH_BINARY_NAMES`
/// on `PATH`), so the override is the one place an arbitrary path can enter.
/// Matching on `chrom` keeps the real-world variants that people legitimately
/// point at — `chrome.exe`, `chromium.exe`, `chrome-headless-shell.exe`,
/// `google-chrome.exe` — while rejecting a wrong turn like `notepad.exe`.
fn looks_like_a_browser_binary(path: &Path) -> bool {
    let has_exe_extension = path
        .extension()
        .is_some_and(|ext| ext.eq_ignore_ascii_case("exe"));

    let named_like_chrome = path
        .file_stem()
        .and_then(|stem| stem.to_str())
        .is_some_and(|stem| stem.to_ascii_lowercase().contains("chrom"));

    has_exe_extension && named_like_chrome
}

/// Ask `path` for its version, or decide not to ask.
///
/// **Windows never executes the candidate.** `chrome.exe` is a GUI-subsystem
/// binary: it writes nothing to the parent console, and `--version` is not an
/// early-exit switch there, so running it proceeds into real browser startup —
/// which is how the original report saw exit code 21 (the running instance
/// being notified) rather than a version string. Handing it a private profile
/// would remove that abort only to replace it with something worse: a real
/// browser window, and a [`std::process::Command::output`] call that blocks
/// until every child process closes its stdout handle. File existence is the
/// strongest signal available on Windows, and it is the one the issue's own
/// suggested fix names.
fn run_version_probe(path: &Path) -> VersionProbe {
    if !path.is_file() {
        return VersionProbe::Failed;
    }

    if cfg!(target_os = "windows") {
        return if looks_like_a_browser_binary(path) {
            VersionProbe::Skipped
        } else {
            VersionProbe::Failed
        };
    }

    let probe_profile = unique_probe_dir();
    let output = std::process::Command::new(path)
        .args(version_probe_args(&probe_profile))
        .output();
    // `--version` should not create the directory, but Chrome variants differ;
    // clean up unconditionally and ignore failure.
    let _ = std::fs::remove_dir_all(&probe_profile);

    match output {
        Ok(o) if o.status.success() => {
            VersionProbe::Ran(String::from_utf8_lossy(&o.stdout).into_owned())
        }
        _ => VersionProbe::Failed,
    }
}

/// Turn a probe outcome into the reported version.
///
/// Split from [`run_version_probe`] so the platform-dependent decisions are
/// unit-testable on every host — a `#[cfg(windows)]` branch would be dead,
/// unexercised code on the Linux CI runner.
fn version_from_probe(probe: &VersionProbe) -> Option<String> {
    match probe {
        VersionProbe::Ran(stdout) => {
            let trimmed = stdout.trim();
            // Exiting 0 is the usability signal; the text is a bonus. A
            // launcher shim that prints its version to stderr (or nothing at
            // all) is still a browser we can drive.
            Some(if trimmed.is_empty() {
                UNKNOWN_VERSION.to_owned()
            } else {
                trimmed.to_owned()
            })
        }
        VersionProbe::Skipped => Some(UNKNOWN_VERSION.to_owned()),
        VersionProbe::Failed => None,
    }
}

/// Probe `path` for a browser version.
///
/// Returns `None` when the candidate is not a usable browser binary, and
/// [`UNKNOWN_VERSION`] when it is usable but cannot report a version.
///
/// On Linux and macOS "usable" means `<path> --version` ran and exited 0
/// (against a throwaway `--user-data-dir`, so it can never rendezvous with a
/// Chrome holding the real profile); empty output is still accepted, since a
/// launcher shim may print elsewhere.
///
/// On **Windows** the candidate is never executed: `chrome.exe` is a
/// GUI-subsystem binary that writes nothing to the parent console, and
/// `--version` is not an early-exit switch there, so running it starts a real
/// browser instead of answering (#1456). An existing file with an `.exe`
/// extension is accepted on that evidence alone.
#[must_use]
pub fn probe_version(path: &Path) -> Option<String> {
    version_from_probe(&run_version_probe(path))
}

// ── Tests ──────────────────────────────────────────────────────────────────

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

    #[test]
    fn browser_check_not_found_message_has_hints() {
        let check = BrowserCheck::NotFound {
            searched_paths: vec![PathBuf::from("/no/such/path")],
        };
        let msg = check.to_string();
        assert!(msg.contains("apt-get") || msg.contains("AUTUMN_CHROMIUM"));
    }

    #[test]
    fn browser_candidates_includes_common_paths() {
        let candidates = browser_candidates();
        let as_strings: Vec<_> = candidates
            .iter()
            .map(|p| p.to_string_lossy().into_owned())
            .collect();
        assert!(
            as_strings
                .iter()
                .any(|s| s.contains("chromium") || s.contains("chrome")),
            "should have at least one chrome path; got {as_strings:?}"
        );
    }

    #[test]
    fn path_scan_keeps_every_match_not_just_the_first() {
        // A stale, non-executable `chrome` early in PATH must not mask a
        // working one installed later (e.g. by a CI setup action): existence
        // is not usability, and `probe_version` — not this scan — is what
        // decides. Both must survive into the candidate list, in PATH order.
        let base = std::env::temp_dir().join(format!(
            "autumn-path-scan-{}-{}",
            std::process::id(),
            line!()
        ));
        let stale = base.join("stale");
        let good = base.join("good");
        std::fs::create_dir_all(&stale).unwrap();
        std::fs::create_dir_all(&good).unwrap();
        let binary = if cfg!(target_os = "windows") {
            "chrome.exe"
        } else {
            "chrome"
        };
        std::fs::write(stale.join(binary), b"stale").unwrap();
        std::fs::write(good.join(binary), b"good").unwrap();

        let joined = std::env::join_paths([&stale, &good]).unwrap();
        let found = path_candidates(Some(joined.as_os_str()));

        assert_eq!(
            found,
            vec![stale.join(binary), good.join(binary)],
            "both PATH hits must be candidates, in PATH order"
        );

        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn path_scan_without_a_path_variable_is_empty() {
        assert!(path_candidates(None).is_empty());
    }

    #[test]
    fn candidates_are_deduplicated() {
        let candidates = browser_candidates();
        let mut seen = std::collections::HashSet::new();
        for path in &candidates {
            assert!(
                seen.insert(path.clone()),
                "duplicate candidate {path:?} wastes a probe and clutters the \
                 searched-paths list in the not-found error"
            );
        }
    }

    #[test]
    fn well_known_paths_target_the_host_platform() {
        // #1456: the well-known list was Linux + macOS only, so a Windows host
        // with a stock Chrome install reached no candidate at all and the
        // version-probe fix downstream of it could never help.
        let paths: Vec<String> = well_known_paths()
            .iter()
            .map(|p| p.to_string_lossy().into_owned())
            .collect();
        assert!(!paths.is_empty(), "every platform needs candidates");
        if cfg!(target_os = "windows") {
            assert!(
                paths.iter().all(|p| p.ends_with("chrome.exe")),
                "Windows candidates must name the real on-disk binary; got {paths:?}"
            );
            assert!(
                paths.iter().any(|p| p.contains("Application")),
                "Windows Chrome lives in <base>\\...\\Application\\chrome.exe; got {paths:?}"
            );
        } else {
            assert!(
                paths.iter().any(|p| p.starts_with('/')),
                "POSIX candidates must be absolute; got {paths:?}"
            );
        }
    }

    #[test]
    fn version_probe_isolates_the_profile_directory() {
        let dir = PathBuf::from("/tmp/probe-profile");
        let args = version_probe_args(&dir);

        assert!(
            args.iter().any(|a| a == "--version"),
            "the probe must still ask for the version; got {args:?}"
        );
        let user_data_dir: Vec<_> = args
            .iter()
            .filter(|a| a.starts_with("--user-data-dir="))
            .collect();
        assert_eq!(
            user_data_dir.len(),
            1,
            "the probe must pass exactly one --user-data-dir so it never \
             rendezvouses with a Chrome already holding the real profile; \
             got {args:?}"
        );
        assert!(
            user_data_dir[0].contains("probe-profile"),
            "--user-data-dir must point at the supplied private directory; got {args:?}"
        );
    }

    #[test]
    fn probe_dirs_are_never_reused() {
        assert_ne!(
            unique_probe_dir(),
            unique_probe_dir(),
            "two probes must not share a directory, or one's cleanup deletes \
             the other's profile mid-probe"
        );
    }

    #[test]
    fn version_from_probe_prefers_reported_version() {
        assert_eq!(
            version_from_probe(&VersionProbe::Ran("Chromium 122.0.6261.111\n".to_owned())),
            Some("Chromium 122.0.6261.111".to_owned()),
            "reported version must be used verbatim (trimmed)"
        );
    }

    #[test]
    fn version_from_probe_accepts_a_binary_that_exits_zero_without_output() {
        // A launcher shim may print its version to stderr or not at all.
        // Exiting 0 is the usability signal, and rejecting these would have
        // regressed hosts that worked before #1456.
        for stdout in ["", "   \r\n"] {
            assert_eq!(
                version_from_probe(&VersionProbe::Ran(stdout.to_owned())),
                Some(UNKNOWN_VERSION.to_owned()),
                "stdout {stdout:?} exited 0, so the binary is usable"
            );
        }
    }

    #[test]
    fn version_from_probe_skipped_resolves_without_running_anything() {
        // The Windows path: chrome.exe exists but must not be executed.
        assert_eq!(
            version_from_probe(&VersionProbe::Skipped),
            Some(UNKNOWN_VERSION.to_owned()),
            "an existing Windows chrome.exe must resolve as found, not as \
             BrowserNotFound"
        );
    }

    #[test]
    fn version_from_probe_rejects_a_failed_probe() {
        // Spawn failure or a non-zero exit means the candidate is unusable.
        // It must keep failing so the search falls through to the next
        // candidate and, if none work, the caller still gets the
        // searched-paths error with its remediation hint.
        assert_eq!(
            version_from_probe(&VersionProbe::Failed),
            None,
            "a broken binary must not be papered over"
        );
    }

    #[cfg(not(target_os = "windows"))]
    #[test]
    fn the_probe_actually_passes_its_arguments_to_the_process() {
        // The pure functions above cover the decisions; this covers the
        // wiring. `echo` prints back whatever argv it received, so a
        // successful probe whose "version" is our own flags proves both
        // `--version` and the isolating `--user-data-dir` reached the child.
        let echo = ["/bin/echo", "/usr/bin/echo"]
            .into_iter()
            .map(Path::new)
            .find(|p| p.is_file());
        let Some(echo) = echo else {
            return; // no `echo` on this host; nothing to assert against
        };

        let reported = probe_version(echo).expect("echo exits 0, so it is 'usable'");
        assert!(
            reported.contains("--version"),
            "the probe must ask for the version; echo saw {reported:?}"
        );
        assert!(
            reported.contains("--user-data-dir="),
            "the probe must isolate the profile so a running Chrome cannot \
             abort it; echo saw {reported:?}"
        );
    }

    #[cfg(not(target_os = "windows"))]
    #[test]
    fn a_non_zero_exit_is_not_a_browser() {
        // `false` exists on every POSIX host and exits 1.
        let Some(falsy) = ["/bin/false", "/usr/bin/false"]
            .into_iter()
            .map(Path::new)
            .find(|p| p.is_file())
        else {
            return;
        };
        assert_eq!(
            probe_version(falsy),
            None,
            "a binary that exits non-zero must not be accepted as a browser"
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn windows_accepts_an_existing_exe_without_running_it() {
        // A file that exists and is named like Chrome must resolve without
        // being executed — running the candidate is exactly what #1456 says
        // not to do on Windows. The file's *contents* are irrelevant here,
        // which is the point: we never launch it.
        let dir = std::env::temp_dir().join("autumn-browser-detect-test");
        std::fs::create_dir_all(&dir).expect("create temp dir");
        let fake_chrome = dir.join("chrome.exe");
        std::fs::write(&fake_chrome, b"not really chrome").expect("write fake binary");

        assert_eq!(
            probe_version(&fake_chrome),
            Some(UNKNOWN_VERSION.to_owned()),
            "an existing chrome.exe must resolve as found, not BrowserNotFound"
        );

        // Same directory, same existence, wrong program: must NOT end
        // discovery (see `looks_like_a_browser_binary`).
        let not_chrome = dir.join("notepad.exe");
        std::fs::write(&not_chrome, b"not a browser").expect("write decoy");
        assert_eq!(probe_version(&not_chrome), None);

        assert_eq!(
            probe_version(Path::new(r"C:\definitely\not\here\chrome.exe")),
            None,
            "a path that does not exist is still not a browser"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn missing_files_never_probe() {
        assert_eq!(
            run_version_probe(Path::new("/definitely/not/a/browser/chrome")),
            VersionProbe::Failed
        );
        assert_eq!(
            probe_version(Path::new("/definitely/not/a/browser/chrome")),
            None
        );
    }

    #[test]
    fn windows_candidates_must_look_like_a_browser() {
        for real in [
            r"C:\Program Files\Google\Chrome\Application\chrome.exe",
            r"C:\Users\me\AppData\Local\Chromium\Application\chrome.exe",
            "chrome.EXE",   // case-insensitive extension
            "CHROMIUM.exe", // case-insensitive name
            "chrome-headless-shell.exe",
            "google-chrome.exe",
        ] {
            assert!(
                looks_like_a_browser_binary(Path::new(real)),
                "{real:?} is a browser people legitimately point AUTUMN_CHROMIUM at"
            );
        }

        for not_a_browser in [
            // Right extension, wrong program. Accepting this would end
            // discovery at a stale/mistyped override and hide an installed
            // Chrome further down the candidate list.
            "notepad.exe",
            r"C:\Windows\System32\cmd.exe",
            // Right name, not an executable.
            "chrome.lnk",
            "chrome",
            "README.md",
        ] {
            assert!(
                !looks_like_a_browser_binary(Path::new(not_a_browser)),
                "{not_a_browser:?} must not end discovery — a wrong override has \
                 to fall through to the real candidates, and failing that yield \
                 BrowserNotFound with its searched-paths list"
            );
        }
    }
}