Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

76.3 KB
Raw Blame
//! Where bots do computer work: the person's own computer ("local": their installed Chrome with a
//! kwant-only profile, run without a window and streamed into the app unless the person asks for
//! a window, and host shell commands that each need approval) or isolated containers
//! ("vm": the Docker browser and executor). Local is the default on macOS, vm everywhere else.
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::time::Duration;
use crate::doctor::{self, Platform};

/// Settings row holding the person's explicit choice.
pub const SETTING_KEY: &str = "computer_mode";
/// Overrides the platform default (not an explicit saved choice).
pub const MODE_ENV: &str = "KWNT_COMPUTER_MODE";
/// Path to the Chrome/Chromium binary local mode launches, instead of searching for one.
pub const CHROME_PATH_ENV: &str = "KWNT_CHROME_PATH";
/// What vm mode actually runs in containers. The CLI drivers (Claude, Codex, Grok) and their own
/// file and shell tools still run on the host; `cli_agents` joins this list once they move.
pub const VM_ISOLATES: [&str; 2] = ["browser", "kwnt_shell"];

/// What vm mode isolates on this computer. The built-in shell runs in an executor container that
/// needs Docker; with only a browser service (the compose stack, no Docker socket) just the
/// browser is isolated and the built-in shell isn't available.
pub fn vm_isolates(docker: bool) -> &'static [&'static str] {
    if docker {
        &VM_ISOLATES
    } else {
        &VM_ISOLATES[..1]
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ComputerMode {
    Local,
    Vm,
}

impl ComputerMode {
    pub fn parse(value: &str) -> Option<Self> {
        match value.trim().to_ascii_lowercase().as_str() {
            "local" => Some(Self::Local),
            "vm" => Some(Self::Vm),
            _ => None,
        }
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Self::Local => "local",
            Self::Vm => "vm",
        }
    }
}

/// The mode used when the person has not chosen one: a valid env value, else local on macOS
/// (`os` is `std::env::consts::OS`) and vm elsewhere.
pub fn default_mode(os: &str, env: Option<&str>) -> ComputerMode {
    env.and_then(ComputerMode::parse)
        .unwrap_or(if os == "macos" {
            ComputerMode::Local
        } else {
            ComputerMode::Vm
        })
}

/// A valid saved choice wins over the env/platform default.
/// On Windows (0.7.6 beta) it is always local: the isolated vm computer isn't there yet.
pub fn effective_mode(saved: Option<&str>, os: &str, env: Option<&str>) -> ComputerMode {
    if os == "windows" {
        return ComputerMode::Local;
    }
    saved
        .and_then(ComputerMode::parse)
        .unwrap_or_else(|| default_mode(os, env))
}

/// [`effective_mode`] for this process's OS and environment.
pub fn current_mode(saved: Option<&str>) -> ComputerMode {
    effective_mode(
        saved,
        std::env::consts::OS,
        std::env::var(MODE_ENV).ok().as_deref(),
    )
}

const MAC_CHROME_APPS: [&str; 3] = [
    "Google Chrome.app/Contents/MacOS/Google Chrome",
    "Chromium.app/Contents/MacOS/Chromium",
    "Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
];
const CHROME_COMMANDS: [&str; 5] = [
    "google-chrome",
    "google-chrome-stable",
    "chromium",
    "chromium-browser",
    "chrome",
];

/// Finds the browser local mode launches: the override if it names a file, else the macOS app
/// bundles (in `/Applications` and `~/Applications`), else a Chrome/Chromium command on `path`,
/// else a Playwright Chromium, else the Chrome for Testing kwnt downloaded itself (O5).
pub fn find_chrome(
    override_path: Option<&str>,
    os: &str,
    home: Option<&Path>,
    path: Option<&str>,
) -> Option<PathBuf> {
    if let Some(p) = override_path.filter(|p| !p.trim().is_empty()) {
        return Path::new(p).is_file().then(|| PathBuf::from(p));
    }
    if os == "macos" {
        let roots = [
            Some(PathBuf::from("/Applications")),
            home.map(|h| h.join("Applications")),
        ];
        for root in roots.iter().flatten() {
            for app in MAC_CHROME_APPS {
                let candidate = root.join(app);
                if candidate.is_file() {
                    return Some(candidate);
                }
            }
        }
    }
    if os == "windows" {
        if let Some(found) = windows_chrome(&windows_roots()) {
            return Some(found);
        }
    }
    // by name first, then by folder: an installed Google Chrome anywhere on the path wins over a
    // Chromium earlier on it, so sites see the same brand as on everyone else's Chrome
    let on_path = path.and_then(|path| {
        let dirs: Vec<PathBuf> = std::env::split_paths(path).collect();
        CHROME_COMMANDS
            .iter()
            .find_map(|name| dirs.iter().map(|dir| dir.join(name)).find(|candidate| candidate.is_file()))
    });
    on_path
        .or_else(|| playwright_chromium(os, home?))
        .or_else(|| super::chrome_download::downloaded_chrome(os, home?))
}

/// Where Windows installs Chrome: per machine (`Program Files`, both) and per person
/// (`%LOCALAPPDATA%`).
fn windows_roots() -> Vec<PathBuf> {
    ["ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"]
        .iter()
        .filter_map(|var| std::env::var_os(var).map(PathBuf::from))
        .collect()
}

/// The installed Google Chrome under one of `roots`, else a Chromium there.
pub fn windows_chrome(roots: &[PathBuf]) -> Option<PathBuf> {
    const APPS: [&str; 2] = ["Google/Chrome/Application/chrome.exe", "Chromium/Application/chrome.exe"];
    APPS.iter()
        .find_map(|app| roots.iter().map(|root| root.join(app)).find(|candidate| candidate.is_file()))
}

/// The newest Chromium Playwright downloaded into the person's cache (`kwnt setup` puts one there
/// when no Chrome is installed): `~/.cache/ms-playwright` on Linux,
/// `~/Library/Caches/ms-playwright` on a Mac.
pub fn playwright_chromium(os: &str, home: &Path) -> Option<PathBuf> {
    let (cache, inner): (PathBuf, &[&str]) = if os == "macos" {
        (
            home.join("Library/Caches/ms-playwright"),
            &[
                "chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
                "chrome-mac-x64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
                "chrome-mac/Chromium.app/Contents/MacOS/Chromium",
            ],
        )
    } else {
        (home.join(".cache/ms-playwright"), &["chrome-linux64/chrome", "chrome-linux-arm64/chrome", "chrome-linux/chrome"])
    };
    let mut builds: Vec<(u32, PathBuf)> = std::fs::read_dir(cache)
        .ok()?
        .flatten()
        .filter_map(|e| {
            let name = e.file_name().to_string_lossy().to_string();
            let rev = name.strip_prefix("chromium-")?.parse().ok()?;
            Some((rev, e.path()))
        })
        .collect();
    builds.sort_by_key(|b| std::cmp::Reverse(b.0));
    builds
        .iter()
        .flat_map(|(_, dir)| inner.iter().map(move |i| dir.join(i)))
        .find(|c| c.is_file())
}

/// Whether a window can be shown: always on macOS and Windows, on Linux only with an X11 or
/// Wayland display.
pub fn has_display(os: &str, display: Option<&str>, wayland: Option<&str>) -> bool {
    match os {
        "linux" | "freebsd" | "openbsd" | "netbsd" => {
            display.is_some_and(|d| !d.is_empty()) || wayland.is_some_and(|d| !d.is_empty())
        }
        _ => true,
    }
}

/// Why local mode cannot run here, or `None` if it can. No display is needed: local Chrome runs
/// without a window and the app shows it.
pub fn local_unavailable_reason(chrome: Option<&Path>, platform: Platform) -> Option<String> {
    chrome.is_none().then(|| match platform {
        Platform::Docker => format!("kwant runs in a Docker container, which has no Chrome. {}", doctor::chrome_fix(platform)),
        _ => format!("No Chrome or Chromium was found. Install it: {}", doctor::chrome_fix(platform)),
    })
}

/// Why local Chrome cannot be opened as a window here, or `None` if it can.
pub fn window_unavailable_reason(display: bool) -> Option<String> {
    (!display).then(|| "This computer has no screen to show a browser window on (no display).".into())
}

/// The vm computer's reason on Windows (0.7.6 beta: no isolated desktop, Xvfb or rlimits there).
pub const VM_NOT_ON_WINDOWS: &str = "The isolated computer is not available on Windows yet. Bots use this computer.";

/// Why vm mode cannot run here, or `None` if it can. A configured browser service URL is enough
/// for the browser even without Docker.
pub fn vm_unavailable_reason(docker: bool, browser_url_configured: bool, platform: Platform) -> Option<String> {
    if cfg!(windows) {
        return Some(VM_NOT_ON_WINDOWS.into());
    }
    (!docker && !browser_url_configured).then(|| match platform {
        Platform::Docker => format!("No browser service is set for this container. {}", doctor::vm_fix(platform)),
        _ => format!("Docker is not installed or not running. {}", doctor::vm_fix(platform)),
    })
}

/// The local Chrome this process would launch, from the real environment. A Playwright Chromium,
/// or one kwnt downloaded, counts only where its sandbox can start (see [`chrome_sandbox_blocked`]).
pub fn local_chrome_path() -> Option<PathBuf> {
    let home = super::chrome_download::browser_home();
    let found = find_chrome(
        std::env::var(CHROME_PATH_ENV).ok().as_deref(),
        std::env::consts::OS,
        home.as_deref(),
        std::env::var("PATH").ok().as_deref(),
    )?;
    let in_home_cache = home.is_some_and(|h| {
        found.starts_with(h.join(".cache").join("ms-playwright"))
            || found.starts_with(super::chrome_download::cache_root(std::env::consts::OS, &h))
    });
    (!(in_home_cache && chrome_sandbox_blocked())).then_some(found)
}

/// Linux blocks the unprivileged user namespaces Chrome's sandbox needs (Ubuntu 23.10+ AppArmor,
/// or Debian's `unprivileged_userns_clone=0`). Packaged Chrome and Chromium come with a profile
/// or setuid helper that allows it; a Playwright Chromium in the home folder aborts on start.
pub fn chrome_sandbox_blocked() -> bool {
    let read = |p: &str| std::fs::read_to_string(p).map(|s| s.trim().to_string()).ok();
    cfg!(target_os = "linux")
        && (read("/proc/sys/kernel/apparmor_restrict_unprivileged_userns").as_deref() == Some("1")
            || read("/proc/sys/kernel/unprivileged_userns_clone").as_deref() == Some("0"))
}

/// [`local_unavailable_reason`] for this process's environment. Where kwnt can download its own
/// browser (O5), a missing Chrome is no reason: the first bot that needs one gets it.
pub fn local_reason() -> Option<String> {
    let chrome = local_chrome_path();
    if chrome.is_none() && super::chrome_download::ChromeSetup::system().available() {
        return None;
    }
    local_unavailable_reason(chrome.as_deref(), Platform::detect())
}

/// [`window_unavailable_reason`] for this process's environment.
pub fn window_reason() -> Option<String> {
    window_unavailable_reason(has_display(
        std::env::consts::OS,
        std::env::var("DISPLAY").ok().as_deref(),
        std::env::var("WAYLAND_DISPLAY").ok().as_deref(),
    ))
}

/// Reads the debugging port Chrome writes to `DevToolsActivePort` in its profile folder.
pub fn read_devtools_port(profile: &Path) -> Option<u16> {
    let text = std::fs::read_to_string(profile.join("DevToolsActivePort")).ok()?;
    text.lines().next()?.trim().parse().ok().filter(|&p| p > 0)
}

/// Chrome's switch that keeps `navigator.webdriver` false while a debugging port is open. A
/// Chrome feature switch, not a script: the page sees the same browser a person uses.
pub const NOT_AUTOMATED: &str = "--disable-blink-features=AutomationControlled";

/// Whether the browser at `path` is Google Chrome (not Chromium or Chrome for Testing), whose
/// pages name "Google Chrome" among their brands.
pub fn is_google_chrome(path: &Path) -> bool {
    let text = path.to_string_lossy().to_lowercase().replace('\\', "/");
    (text.contains("google chrome") || text.contains("google-chrome") || text.contains("google/chrome/application"))
        && !text.contains("for testing")
}

/// The viewport of windowless local Chrome, matching the vm browser and the in-app viewer.
pub const HEADLESS_WINDOW_SIZE: &str = "1280,800";

/// Chrome's command line for local mode: its own profile, never the person's everyday one, and a
/// debugging port Chrome picks itself (it listens on 127.0.0.1). Without a window (`headless`)
/// unless the person asked to see one.
///
/// Chrome keeps its own user agent: a `--user-agent` flag empties the client hints a real Chrome
/// fills, and Google refuses sign-in on that. The headless token is taken out over DevTools
/// instead, with the browser's own client hints ([`super::identity`]). With a debugging port
/// Chrome says `navigator.webdriver` is true; [`NOT_AUTOMATED`] turns that off. No
/// `--enable-automation`, which adds the "controlled by automated software" bar.
pub fn chrome_args(profile: &Path, headless: bool) -> Vec<String> {
    let mut args = vec![
        format!("--user-data-dir={}", profile.display()),
        "--remote-debugging-port=0".into(),
        "--remote-debugging-address=127.0.0.1".into(),
        "--no-first-run".into(),
        "--no-default-browser-check".into(),
        NOT_AUTOMATED.into(),
    ];
    if headless {
        args.push("--headless=new".into());
        args.push(format!("--window-size={HEADLESS_WINDOW_SIZE}"));
    }
    args.push("about:blank".into());
    args
}

/// The user agent Chrome sends with a window, for the Chrome whose `--version` printed
/// `version_output` ("Google Chrome 131.0.6778.86", "Chromium 154.0.8037.92 built on ..."). Chrome
/// fills it from a fixed template with the major version and a frozen platform, so this is the same
/// string the windowed Chrome on `os` sends. `None` if no version is found.
pub fn headed_user_agent(version_output: &str, os: &str) -> Option<String> {
    let version = version_output
        .split_whitespace()
        .find(|word| word.split('.').count() >= 2 && word.split('.').all(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())))?;
    let major = version.split('.').next()?;
    let platform = match os {
        "macos" => "Macintosh; Intel Mac OS X 10_15_7",
        "windows" => "Windows NT 10.0; Win64; x64",
        _ => "X11; Linux x86_64",
    };
    Some(format!("Mozilla/5.0 ({platform}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{major}.0.0.0 Safari/537.36"))
}

/// [`headed_user_agent`] for the Chrome at `chrome`, from its `--version`. Not on Windows, where
/// `chrome.exe --version` opens the browser instead of printing.
pub fn chrome_user_agent(chrome: &Path) -> Option<String> {
    if cfg!(windows) {
        return None;
    }
    let out = std::process::Command::new(chrome)
        .arg("--version")
        .stdin(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .output()
        .ok()?;
    headed_user_agent(&String::from_utf8_lossy(&out.stdout), std::env::consts::OS)
}

/// [`chrome_user_agent`] for the local Chrome, run off the async workers: a slow `--version` (a
/// snap wrapper takes about a second) would otherwise stall every task on that worker.
pub async fn local_chrome_user_agent() -> Option<String> {
    tokio::task::spawn_blocking(|| local_chrome_path().and_then(|chrome| chrome_user_agent(&chrome)))
        .await
        .ok()
        .flatten()
}

/// A normal Chrome user agent for kwant's plain HTTP requests (`web_fetch`): the local Chrome's,
/// or, without one, a recent Chrome on this platform. Worked out once per process.
pub async fn browser_user_agent() -> &'static str {
    static AGENT: tokio::sync::OnceCell<String> = tokio::sync::OnceCell::const_new();
    AGENT
        .get_or_init(|| async {
            local_chrome_user_agent()
                .await
                .or_else(|| headed_user_agent("Chrome 141.0.0.0", std::env::consts::OS))
                .unwrap_or_default()
        })
        .await
}

/// The file in kwant's Chrome profile that says which form kwant last started it in: "headless"
/// or "window". Written before every start, so it describes the Chrome running there.
const LAUNCH_MODE_FILE: &str = "kwant-launch-mode";

fn record_launch_mode(profile: &Path, headless: bool) -> std::io::Result<()> {
    std::fs::write(profile.join(LAUNCH_MODE_FILE), if headless { "headless" } else { "window" })
}

/// Whether kwant last started the Chrome on `profile` windowless. `None` for a Chrome started by
/// an older kwant, which wrote no such file.
pub fn launched_headless(profile: &Path) -> Option<bool> {
    match std::fs::read_to_string(profile.join(LAUNCH_MODE_FILE)).ok()?.trim() {
        "headless" => Some(true),
        "window" => Some(false),
        _ => None,
    }
}

/// The file kwant writes next to [`LAUNCH_MODE_FILE`] once it starts Chrome as Chrome
/// ([`chrome_args`]: no `--user-agent`, not marked automated). Kwant 0.9.4 and older wrote none.
const LAUNCH_IDENTITY_FILE: &str = "kwant-launch-identity";

fn record_launch_identity(profile: &Path) -> std::io::Result<()> {
    std::fs::write(profile.join(LAUNCH_IDENTITY_FILE), "chrome")
}

/// Whether the windowless Chrome on `profile` was started by an older kwant, with a made-up
/// `--user-agent` and without [`NOT_AUTOMATED`]: sites read it as automated (Google refuses its
/// sign-in), and what kwant sets over DevTools can't undo that, so it has to be started again.
pub fn started_by_older_kwant(profile: &Path) -> bool {
    let line = profile_owner(profile).and_then(command_line);
    is_older_launch(line.as_deref(), profile.join(LAUNCH_IDENTITY_FILE).exists())
}

/// [`started_by_older_kwant`] from the Chrome's command line, else (no command line, as on
/// Windows) from whether kwant left its launch mark. A Chrome kwant starts now always passes, so
/// it is never restarted twice.
pub fn is_older_launch(command_line: Option<&str>, marked: bool) -> bool {
    match command_line {
        Some(line) => {
            let mut args = line.split(' ');
            line.contains(" --user-agent=") || !args.any(|arg| arg == NOT_AUTOMATED)
        }
        None => !marked,
    }
}

/// Whether a running kwant Chrome is windowless: from its command line, else from the form kwant
/// recorded when it started it, else from its user agent (`/json/version` still says
/// "HeadlessChrome" when windowless: the identity kwant gives pages doesn't change it). Its
/// command line comes first, as a Chrome an older kwant started with `--user-agent` reads like a
/// windowed one.
pub fn is_windowless(command_line: Option<&str>, launched_headless: Option<bool>, user_agent: &str) -> bool {
    match (command_line, launched_headless) {
        (Some(line), _) => is_headless_command_line(line),
        (None, Some(recorded)) => recorded,
        (None, None) => is_headless_user_agent(user_agent),
    }
}

/// Whether a running Chrome is windowless, from its `/json/version` user agent. Wrong for a
/// Chrome an older kwant started with `--user-agent` (see [`is_windowless`]).
pub fn is_headless_user_agent(user_agent: &str) -> bool {
    user_agent.contains("HeadlessChrome")
}

/// Whether a Chrome command line (arguments joined by spaces) runs it without a window.
pub fn is_headless_command_line(line: &str) -> bool {
    line.split(' ').any(|arg| arg == "--headless" || arg.starts_with("--headless="))
}

fn client() -> reqwest::Client {
    reqwest::Client::builder()
        .timeout(Duration::from_secs(2))
        .build()
        .unwrap_or_default()
}

/// The user agent of the Chrome answering at `endpoint`, or `None` if nothing answers.
async fn user_agent(endpoint: &str) -> Option<String> {
    let resp = client().get(format!("{endpoint}/json/version")).send().await.ok()?;
    if !resp.status().is_success() {
        return None;
    }
    let version: serde_json::Value = resp.json().await.ok()?;
    Some(version["User-Agent"].as_str().unwrap_or_default().to_string())
}

/// The kwant Chrome running on `profile`: its CDP endpoint and whether it is windowless (see
/// [`is_windowless`]).
pub async fn running_local_chrome(profile: &Path) -> Option<(String, bool)> {
    let port = read_devtools_port(profile)?;
    let endpoint = format!("http://127.0.0.1:{port}");
    let agent = user_agent(&endpoint).await?;
    let line = profile_owner(profile).and_then(command_line);
    Some((endpoint, is_windowless(line.as_deref(), launched_headless(profile), &agent)))
}

/// The live Chrome holding `profile`, from the `SingletonLock` link Chrome keeps in it
/// ("<host>-<pid>"). `None` when no Chrome holds it, or on Windows, which has no such link.
///
/// A Chrome that crashed leaves the link behind, and its pid can later belong to an unrelated
/// program. So the pid only counts while its command line is a Chrome on this profile; trusting
/// the pid alone waited on that program forever and never started Chrome again.
pub fn profile_owner(profile: &Path) -> Option<u32> {
    let pid = lock_pid(profile)?;
    (pid_alive(pid) && command_line(pid).is_some_and(|line| is_chrome_on(&line, profile))).then_some(pid)
}

fn lock_pid(profile: &Path) -> Option<u32> {
    let target = std::fs::read_link(profile.join("SingletonLock")).ok()?;
    target.to_string_lossy().rsplit('-').next()?.parse().ok()
}

/// Whether a process command line (arguments joined by spaces) is a Chrome or Chromium started
/// with `--user-data-dir=<profile>`.
fn is_chrome_on(line: &str, profile: &Path) -> bool {
    let flag = format!("--user-data-dir={}", profile.display());
    let Some(at) = line.find(&flag) else { return false };
    let rest = &line[at + flag.len()..];
    if !(rest.is_empty() || rest.starts_with(' ')) {
        return false; // another profile whose path starts with this one
    }
    // the profile path itself may say "chrome", so look for it in the rest of the line
    format!("{}{rest}", &line[..at]).to_lowercase().contains("chrom")
}

#[cfg(target_os = "linux")]
fn command_line(pid: u32) -> Option<String> {
    let raw = std::fs::read(format!("/proc/{pid}/cmdline")).ok()?;
    let args: Vec<_> = raw.split(|b| *b == 0).filter(|a| !a.is_empty()).map(String::from_utf8_lossy).collect();
    (!args.is_empty()).then(|| args.join(" "))
}

#[cfg(all(unix, not(target_os = "linux")))]
fn command_line(pid: u32) -> Option<String> {
    let out = std::process::Command::new("ps").args(["-ww", "-o", "command=", "-p", &pid.to_string()]).output().ok()?;
    let line = String::from_utf8_lossy(&out.stdout).trim().to_string();
    (out.status.success() && !line.is_empty()).then_some(line)
}

#[cfg(not(unix))]
fn command_line(_pid: u32) -> Option<String> {
    None
}

#[cfg(unix)]
fn pid_alive(pid: u32) -> bool {
    let Ok(pid) = i32::try_from(pid) else { return false };
    if pid <= 0 {
        return false;
    }
    // signal 0 only checks; EPERM means it exists under another user
    let found = unsafe { libc::kill(pid, 0) } == 0;
    found || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
}

#[cfg(not(unix))]
fn pid_alive(_pid: u32) -> bool {
    false
}

/// Waits until the kwant Chrome on `profile` stops answering and its process lets go of the
/// profile (it was asked to close).
pub async fn wait_local_chrome_gone(profile: &Path) -> Result<(), String> {
    for _ in 0..60 {
        if running_local_chrome(profile).await.is_none() && profile_owner(profile).is_none() {
            // Chrome drops its profile lock just after the port closes
            tokio::time::sleep(Duration::from_millis(300)).await;
            return Ok(());
        }
        tokio::time::sleep(Duration::from_millis(250)).await;
    }
    Err("Chrome did not close within 15 seconds.".into())
}

/// How long [`ensure_chrome_with`] waits, and how often it looks.
#[derive(Clone, Copy)]
pub struct LaunchTiming {
    /// For a Chrome that holds the profile but does not answer yet (starting, or busy).
    pub owner: Duration,
    /// For the Chrome just started to open its debugging port.
    pub start: Duration,
    pub step: Duration,
}

impl Default for LaunchTiming {
    fn default() -> Self {
        Self { owner: Duration::from_secs(15), start: Duration::from_secs(20), step: Duration::from_millis(250) }
    }
}

type LaunchLocks = std::sync::Mutex<std::collections::HashMap<PathBuf, std::sync::Arc<tokio::sync::Mutex<()>>>>;

/// One launch at a time per profile in this process. Every caller (the Bot browser panel, its
/// stream, a bot's turn) goes through here, so they wait for the one Chrome instead of each
/// starting their own.
fn launch_lock(profile: &Path) -> std::sync::Arc<tokio::sync::Mutex<()>> {
    static LOCKS: std::sync::LazyLock<LaunchLocks> = std::sync::LazyLock::new(Default::default);
    LOCKS.lock().unwrap_or_else(|e| e.into_inner()).entry(profile.to_path_buf()).or_default().clone()
}

/// The Chrome found holding `profile` that did not answer within the owner wait, and when.
/// `set`: `Some(Some(pid))` records it, `Some(None)` clears it, `None` only reads.
fn unresponsive(profile: &Path, set: Option<Option<u32>>) -> Option<(u32, std::time::Instant)> {
    static STUCK: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<PathBuf, (u32, std::time::Instant)>>> =
        std::sync::LazyLock::new(Default::default);
    let mut stuck = STUCK.lock().unwrap_or_else(|e| e.into_inner());
    match set {
        Some(Some(pid)) => { stuck.insert(profile.to_path_buf(), (pid, std::time::Instant::now())); }
        Some(None) => { stuck.remove(profile); }
        None => {}
    }
    stuck.get(profile).copied()
}

/// The same across kwnt processes sharing a data folder: an advisory lock on a file next to the
/// profile, released when dropped (or when the process dies).
struct FileLock {
    _file: std::fs::File,
}

impl FileLock {
    async fn acquire(profile: &Path) -> Result<Self, String> {
        let path = profile.with_extension("launch.lock");
        if let Some(dir) = path.parent() {
            std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
        }
        let file = std::fs::OpenOptions::new().create(true).truncate(false).write(true).open(&path)
            .map_err(|e| format!("Could not open {}: {e}", path.display()))?;
        #[cfg(unix)]
        {
            use std::os::unix::io::AsRawFd;
            for _ in 0..240 {
                if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 {
                    return Ok(Self { _file: file });
                }
                tokio::time::sleep(Duration::from_millis(250)).await;
            }
            Err("Another kwnt is still starting Chrome on this profile.".into())
        }
        #[cfg(not(unix))]
        Ok(Self { _file: file })
    }
}

/// The kwant Chrome on `profile`, started if none is: its CDP endpoint and whether it is
/// windowless. A running Chrome is reused whatever its form (the caller restarts it if it wants the
/// other one); `headless` only applies to a start.
pub async fn ensure_local_chrome(profile: &Path, headless: bool) -> Result<(String, bool), String> {
    ensure_chrome_with(
        profile,
        || running_local_chrome(profile),
        || launch_local_chrome(profile, headless),
        LaunchTiming::default(),
    )
    .await
}

/// [`ensure_local_chrome`] with the check and the start passed in, so tests can count starts.
///
/// Never starts a second Chrome on a profile a live Chrome holds: on macOS that second start hands
/// its arguments to the running one, which opens one more blank window each time. The stale
/// `DevToolsActivePort` is removed only once no process holds the profile, since removing a live
/// Chrome's port file left every later call unable to find it, so each one started another.
pub async fn ensure_chrome_with<'a, P, PF, S, L>(
    profile: &Path,
    probe: P,
    spawn: S,
    timing: LaunchTiming,
) -> Result<(String, bool), String>
where
    P: Fn() -> PF,
    PF: std::future::Future<Output = Option<(String, bool)>> + 'a,
    S: FnOnce() -> Result<L, String>,
    L: Into<Launched>,
{
    let lock = launch_lock(profile);
    let _in_process = lock.lock().await;
    let _across = FileLock::acquire(profile).await?;
    if let Some(found) = probe().await {
        unresponsive(profile, Some(None));
        return Ok(found);
    }
    if let Some(pid) = profile_owner(profile) {
        // callers queued behind one that already waited the full time for this Chrome look once
        // and give up, instead of each waiting again
        let known_stuck = unresponsive(profile, None).is_some_and(|(p, at)| p == pid && at.elapsed() < timing.owner);
        let deadline = tokio::time::Instant::now() + if known_stuck { Duration::ZERO } else { timing.owner };
        loop {
            if let Some(found) = probe().await {
                unresponsive(profile, Some(None));
                return Ok(found);
            }
            if profile_owner(profile).is_none() {
                break; // it closed: start a fresh one below
            }
            if tokio::time::Instant::now() >= deadline {
                if !known_stuck {
                    unresponsive(profile, Some(Some(pid)));
                }
                return Err(format!(
                    "kwant's Chrome (process {pid}) is open but not answering, so kwant did not start another. \
                     Quit that Chrome (Cmd+Q on a Mac) and try again."
                ));
            }
            tokio::time::sleep(timing.step).await;
        }
    }
    // nothing holds the profile, so a port file or lock left behind points at nothing (a lock
    // naming another program, or an old hostname, would stop the new Chrome from starting)
    let _ = std::fs::remove_file(profile.join("DevToolsActivePort"));
    if lock_pid(profile).is_some() {
        for name in ["SingletonLock", "SingletonSocket", "SingletonCookie"] {
            let _ = std::fs::remove_file(profile.join(name));
        }
    }
    let launched: Launched = spawn()?.into();
    let deadline = tokio::time::Instant::now() + timing.start;
    loop {
        // read before the probe, so a Chrome that opened its port and then closed is not missed
        let exited = launched.exit();
        if let Some(found) = probe().await {
            return Ok(found);
        }
        if let Some(status) = exited {
            // it closed without answering: stop waiting, unless another Chrome took the profile
            // over (then that one is waited for as before)
            if profile_owner(profile).is_none() {
                return Err(launched.closed_message(&status));
            }
        }
        if tokio::time::Instant::now() >= deadline {
            return Err("Chrome started but did not open its debugging port in time.".into());
        }
        tokio::time::sleep(timing.step).await;
    }
}

/// The file in kwant's Chrome profile that Chrome's stderr goes to: emptied at each start, kept
/// under [`STDERR_CAP`] while kwnt runs, and read only once that Chrome has closed. Not a pipe:
/// Chrome outlives kwnt, and its next write to a pipe whose reader is gone would fail (EPIPE).
pub const STDERR_FILE: &str = "kwant-chrome-stderr.log";

/// How large [`STDERR_FILE`] may grow before kwnt empties it.
const STDERR_CAP: u64 = 256 * 1024;

/// How the Chrome kwant just started ended, if it has, written by the thread that reaps it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ChildExit {
    Code(i32),
    Signal(i32),
    Unknown,
}

impl ChildExit {
    fn from_status(status: std::process::ExitStatus) -> Self {
        if let Some(code) = status.code() {
            return Self::Code(code);
        }
        #[cfg(unix)]
        {
            use std::os::unix::process::ExitStatusExt;
            if let Some(signal) = status.signal() {
                return Self::Signal(signal);
            }
        }
        Self::Unknown
    }

    fn describe(&self) -> String {
        match self {
            Self::Code(code) => format!("exit code {code}"),
            Self::Signal(signal) => format!("signal {signal}"),
            Self::Unknown => "no exit code".into(),
        }
    }
}

/// What [`ensure_chrome_with`] knows about the Chrome it started: whether it has closed, and where
/// its stderr went. Empty (never closes, no stderr) for a start that doesn't track its child.
#[derive(Clone, Default)]
pub struct Launched {
    exit: std::sync::Arc<std::sync::OnceLock<ChildExit>>,
    stderr: Option<PathBuf>,
}

impl From<()> for Launched {
    fn from(_: ()) -> Self {
        Self::default()
    }
}

impl Launched {
    /// One whose exit is set through [`Launched::closed`], and whose stderr is in `stderr`.
    pub fn tracked(stderr: Option<PathBuf>) -> Self {
        Self { exit: Default::default(), stderr }
    }

    /// Records that the child ended (the first call wins).
    pub fn closed(&self, how: ChildExit) {
        let _ = self.exit.set(how);
    }

    pub fn exit(&self) -> Option<ChildExit> {
        self.exit.get().cloned()
    }

    /// The error for a Chrome that closed before it answered: in plain words first, with the stderr
    /// line that most likely says why (see [`headline_line`]), then up to three of its other last
    /// lines. The headline is not listed again; with no other lines there is no list.
    pub fn closed_message(&self, how: &ChildExit) -> String {
        let lines = self.stderr.as_deref().map(stderr_tail).unwrap_or_default();
        let Some(headline) = headline_line(&lines) else {
            return format!("kwant's Chrome closed right after starting ({}) and printed no error.", how.describe());
        };
        let others: Vec<&String> = lines.iter().filter(|line| *line != headline).collect();
        let listed = &others[others.len().saturating_sub(LISTED_LINES)..];
        if listed.is_empty() {
            return format!("kwant's Chrome closed right after starting: {headline} ({})", how.describe());
        }
        let mut text = format!("kwant's Chrome closed right after starting: {headline}\n\nIts last lines ({}):", how.describe());
        for line in listed {
            text.push('\n');
            text.push_str(line);
        }
        text
    }
}

/// How many of Chrome's last stderr lines [`stderr_tail`] keeps for the headline to be picked from.
const TAIL_LINES: usize = 8;

/// How many lines besides the headline [`Launched::closed_message`] lists.
const LISTED_LINES: usize = 3;

/// Chrome prints dbus failures (`Failed to connect to the bus: ...`) on most Linux machines,
/// often after the line that says why it closed, and they almost never are the reason.
fn is_dbus_noise(line: &str) -> bool {
    let line = line.to_ascii_lowercase();
    line.contains("dbus") || line.contains("failed to connect to the bus")
}

/// Chrome's own `[pid:tid:...:ERROR:file.cc(n)]` / `:FATAL:` lines, and plain ones such as the
/// loader's "error while loading shared libraries".
fn names_an_error(line: &str) -> bool {
    let line = line.to_ascii_lowercase();
    line.contains("error") || line.contains("fatal")
}

/// The line that most likely says why Chrome closed: the last error line that is not dbus noise,
/// else the last line that is not dbus noise, else the last line. None when there are no lines.
fn headline_line(lines: &[String]) -> Option<&String> {
    let clean = || lines.iter().rev().filter(|line| !is_dbus_noise(line));
    clean().find(|line| names_an_error(line)).or_else(|| clean().next()).or_else(|| lines.last())
}

/// The last (up to) [`TAIL_LINES`] non-blank lines of the stderr file at `path`, each cut to 300
/// characters.
pub fn stderr_tail(path: &Path) -> Vec<String> {
    use std::io::{Read, Seek, SeekFrom};
    let Ok(mut file) = std::fs::File::open(path) else { return Vec::new() };
    let len = file.metadata().map(|m| m.len()).unwrap_or(0);
    let _ = file.seek(SeekFrom::Start(len.saturating_sub(16 * 1024)));
    let mut raw = Vec::new();
    let _ = file.read_to_end(&mut raw);
    let text = String::from_utf8_lossy(&raw);
    let lines: Vec<String> = text
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
        .map(|line| match line.char_indices().nth(300) {
            Some((at, _)) => format!("{}…", &line[..at]),
            None => line.to_string(),
        })
        .collect();
    lines[lines.len().saturating_sub(TAIL_LINES)..].to_vec()
}

/// Waits for kwant's Chrome to end and records how, never killing it. Looks often while Chrome
/// starts, then once a second, and keeps its stderr file under [`STDERR_CAP`] while it runs.
fn reap_chrome(mut child: std::process::Child, launched: Launched) {
    let started = std::time::Instant::now();
    let mut last_cap_check = started;
    loop {
        match child.try_wait() {
            Ok(Some(status)) => {
                launched.closed(ChildExit::from_status(status));
                return;
            }
            Ok(None) => {}
            Err(_) => {
                // can't be waited for here: leave it to the port wait, as before
                let _ = child.wait();
                return;
            }
        }
        if last_cap_check.elapsed() >= Duration::from_secs(5) {
            last_cap_check = std::time::Instant::now();
            if let Some(path) = &launched.stderr {
                if std::fs::metadata(path).is_ok_and(|m| m.len() > STDERR_CAP) {
                    // opened for appending, so Chrome's next line lands at the new end
                    if let Ok(file) = std::fs::OpenOptions::new().write(true).open(path) {
                        let _ = file.set_len(0);
                    }
                }
            }
        }
        let starting = started.elapsed() < Duration::from_secs(60);
        std::thread::sleep(if starting { Duration::from_millis(50) } else { Duration::from_secs(1) });
    }
}

/// Starts the kwant Chrome on `profile`, detached, so it outlives a switch or a kwant restart.
/// Only [`ensure_local_chrome`] calls this, once no Chrome holds the profile.
fn launch_local_chrome(profile: &Path, headless: bool) -> Result<Launched, String> {
    let chrome = local_chrome_path()
        .ok_or_else(|| local_reason().unwrap_or_else(|| "No Chrome or Chromium was found.".into()))?;
    if !headless {
        if let Some(reason) = window_reason() {
            return Err(reason);
        }
    }
    std::fs::create_dir_all(profile).map_err(|e| e.to_string())?;
    // without it, a Chrome whose command line can't be read would be taken for the wrong form
    record_launch_mode(profile, headless)
        .and_then(|()| record_launch_identity(profile))
        .map_err(|e| format!("Could not write to {}: {e}", profile.display()))?;
    // stderr to a file emptied at each start (see STDERR_FILE), or nowhere if it can't be written
    let stderr_path = profile.join(STDERR_FILE);
    // (emptied through its own handle: on Windows an append-only one can't be cut)
    let stderr_file = std::fs::File::create(&stderr_path)
        .and_then(|_| std::fs::OpenOptions::new().append(true).open(&stderr_path))
        .ok();
    let launched = Launched::tracked(stderr_file.is_some().then_some(stderr_path));
    let mut cmd = std::process::Command::new(&chrome);
    cmd.args(chrome_args(profile, headless))
        .args(super::browser_proxy::local_chrome_args())
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(stderr_file.map_or_else(std::process::Stdio::null, std::process::Stdio::from));
    #[cfg(unix)]
    {
        // its own process group, so Ctrl+C on kwnt does not close the person's window
        use std::os::unix::process::CommandExt;
        cmd.process_group(0);
    }
    let child = cmd
        .spawn()
        .map_err(|e| format!("Could not start {}: {e}", chrome.display()))?;
    tracing::info!(pid = child.id(), headless, profile = %profile.display(), "started kwant's local Chrome");
    // reap it when it exits, and say so to the port wait; never kill it
    let reaper = launched.clone();
    std::thread::spawn(move || reap_chrome(child, reaper));
    Ok(launched)
}

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

    #[test]
    fn default_is_local_on_macos_and_vm_elsewhere() {
        assert_eq!(default_mode("macos", None), ComputerMode::Local);
        assert_eq!(default_mode("linux", None), ComputerMode::Vm);
        assert_eq!(default_mode("windows", None), ComputerMode::Vm);
    }

    #[test]
    fn env_overrides_default_and_saved_overrides_env() {
        assert_eq!(default_mode("linux", Some("local")), ComputerMode::Local);
        assert_eq!(default_mode("macos", Some(" VM ")), ComputerMode::Vm);
        // a bad env value is ignored
        assert_eq!(default_mode("macos", Some("docker")), ComputerMode::Local);
        assert_eq!(
            effective_mode(Some("vm"), "macos", Some("local")),
            ComputerMode::Vm
        );
        assert_eq!(
            effective_mode(Some("local"), "linux", Some("vm")),
            ComputerMode::Local
        );
        assert_eq!(
            effective_mode(None, "linux", Some("local")),
            ComputerMode::Local
        );
        // a bad saved value falls back to the default
        assert_eq!(
            effective_mode(Some("??"), "macos", None),
            ComputerMode::Local
        );
    }

    #[test]
    fn mode_round_trips_as_lowercase_json() {
        assert_eq!(
            serde_json::to_string(&ComputerMode::Local).unwrap(),
            "\"local\""
        );
        assert_eq!(
            serde_json::from_str::<ComputerMode>("\"vm\"").unwrap(),
            ComputerMode::Vm
        );
        assert!(serde_json::from_str::<ComputerMode>("\"VM\"").is_err());
        assert_eq!(ComputerMode::parse("Local"), Some(ComputerMode::Local));
        assert_eq!(ComputerMode::parse(""), None);
    }

    #[test]
    fn chrome_falls_back_to_the_newest_playwright_chromium() {
        let home = tempfile::tempdir().unwrap();
        let put = |rel: &str| {
            let p = home.path().join(rel);
            std::fs::create_dir_all(p.parent().unwrap()).unwrap();
            std::fs::write(&p, "").unwrap();
            p
        };
        assert_eq!(find_chrome(None, "linux", Some(home.path()), Some("")), None);
        put(".cache/ms-playwright/chromium-1100/chrome-linux/chrome");
        let newer = put(".cache/ms-playwright/chromium-1200/chrome-linux-arm64/chrome");
        put(".cache/ms-playwright/chromium_headless_shell-1300/chrome-linux/headless_shell");
        assert_eq!(find_chrome(None, "linux", Some(home.path()), Some("")), Some(newer));
        // a Chrome on PATH wins over the cache
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("google-chrome"), "").unwrap();
        let path = dir.path().to_string_lossy().to_string();
        assert_eq!(find_chrome(None, "linux", Some(home.path()), Some(&path)), Some(dir.path().join("google-chrome")));

        let mac = put("Library/Caches/ms-playwright/chromium-1200/chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing");
        assert_eq!(playwright_chromium("macos", home.path()), Some(mac));
    }

    #[test]
    fn chrome_is_found_by_override_or_on_path() {
        let dir = tempfile::tempdir().unwrap();
        let bin = dir.path().join("chromium");
        std::fs::write(&bin, "").unwrap();
        let path = dir.path().to_string_lossy().to_string();
        assert_eq!(
            find_chrome(None, "linux", None, Some(&path)),
            Some(bin.clone())
        );
        let custom = dir.path().join("my-chrome");
        std::fs::write(&custom, "").unwrap();
        assert_eq!(
            find_chrome(Some(custom.to_str().unwrap()), "linux", None, Some(&path)),
            Some(custom)
        );
        // an override naming nothing finds nothing, rather than silently using another browser
        assert_eq!(
            find_chrome(Some("/nope/chrome"), "linux", None, Some(&path)),
            None
        );
        let empty = tempfile::tempdir().unwrap();
        assert_eq!(
            find_chrome(None, "linux", None, Some(&empty.path().to_string_lossy())),
            None
        );
        assert_eq!(find_chrome(None, "linux", None, None), None);
    }

    #[test]
    fn chrome_is_found_in_mac_user_applications() {
        let home = tempfile::tempdir().unwrap();
        let app = home.path().join("Applications/Chromium.app/Contents/MacOS");
        std::fs::create_dir_all(&app).unwrap();
        std::fs::write(app.join("Chromium"), "").unwrap();
        let found = find_chrome(None, "macos", Some(home.path()), None);
        // /Applications on the test machine could hold a real Chrome first
        assert!(found.is_some());
        assert_eq!(find_chrome(None, "linux", Some(home.path()), None), None);
    }

    #[test]
    fn availability_reasons() {
        assert!(has_display("macos", None, None));
        assert!(!has_display("linux", None, None));
        assert!(!has_display("linux", Some(""), None));
        assert!(has_display("linux", Some(":0"), None));
        assert!(has_display("linux", None, Some("wayland-0")));

        // local Chrome runs without a window, so only a window needs a display
        let chrome = Path::new("/usr/bin/chromium");
        assert_eq!(local_unavailable_reason(Some(chrome), Platform::Linux), None);
        assert!(local_unavailable_reason(None, Platform::Linux)
            .unwrap()
            .contains(CHROME_PATH_ENV));
        assert!(local_unavailable_reason(None, Platform::Mac).unwrap().contains("brew install --cask google-chrome"));
        assert!(local_unavailable_reason(None, Platform::Docker).unwrap().contains("compose browser service"));
        assert_eq!(window_unavailable_reason(true), None);
        assert!(window_unavailable_reason(false).unwrap().contains("display"));

        if cfg!(windows) {
            assert_eq!(vm_unavailable_reason(true, true, Platform::Linux).as_deref(), Some(VM_NOT_ON_WINDOWS));
            return;
        }
        assert_eq!(vm_unavailable_reason(true, false, Platform::Linux), None);
        assert_eq!(vm_unavailable_reason(false, true, Platform::Docker), None);
        // each platform gets its own advice: no "Docker Desktop on a Mac" on a Linux server
        let linux = vm_unavailable_reason(false, false, Platform::Linux).unwrap();
        assert!(linux.contains("get.docker.com") && !linux.contains("Docker Desktop"), "{linux}");
        assert!(vm_unavailable_reason(false, false, Platform::Mac).unwrap().contains("Docker Desktop"));
        let docker = vm_unavailable_reason(false, false, Platform::Docker).unwrap();
        assert!(docker.contains("KWNT_BROWSER_CDP_URL") && docker.contains("docker compose up -d browser"), "{docker}");
    }

    #[test]
    fn windows_always_uses_this_computer() {
        assert_eq!(effective_mode(None, "windows", None), ComputerMode::Local);
        assert_eq!(effective_mode(Some("vm"), "windows", Some("vm")), ComputerMode::Local);
        // Mac and Linux keep their defaults and saved choices
        assert_eq!(effective_mode(None, "linux", None), ComputerMode::Vm);
        assert_eq!(effective_mode(Some("vm"), "macos", None), ComputerMode::Vm);
        assert!(VM_NOT_ON_WINDOWS.contains("not available on Windows yet"));
    }

    #[test]
    fn vm_isolates_the_built_in_shell_only_with_docker() {
        // Mac/Linux with Docker: the browser and the executor shell both run in containers
        assert_eq!(vm_isolates(true), ["browser", "kwnt_shell"]);
        // compose stack (browser service, no Docker socket): only the browser is isolated
        assert_eq!(vm_isolates(false), ["browser"]);
        // never the CLI agents, which still run where kwnt runs
        assert!(!vm_isolates(true).contains(&"cli_agents"));
    }

    #[test]
    fn chrome_uses_its_own_profile_and_a_loopback_port() {
        for headless in [true, false] {
            let args = chrome_args(Path::new("/data/local-chrome"), headless);
            assert!(args.contains(&"--user-data-dir=/data/local-chrome".to_string()));
            assert!(args.contains(&"--remote-debugging-port=0".to_string()));
            assert!(args.contains(&"--remote-debugging-address=127.0.0.1".to_string()));
        }
    }

    #[test]
    fn chrome_is_windowless_unless_a_window_is_asked_for() {
        let args = chrome_args(Path::new("/p"), true);
        assert!(args.contains(&"--headless=new".to_string()));
        assert!(args.contains(&"--window-size=1280,800".to_string()));
        let args = chrome_args(Path::new("/p"), false);
        assert!(!args.iter().any(|a| a.starts_with("--headless")));
        assert!(!args.iter().any(|a| a.starts_with("--window-size")));
        assert!(is_headless_user_agent("Mozilla/5.0 (X11; Linux x86_64) HeadlessChrome/131.0 Safari/537.36"));
        assert!(!is_headless_user_agent("Mozilla/5.0 (Macintosh) Chrome/131.0 Safari/537.36"));
    }

    #[test]
    fn web_fetch_sends_the_windowed_user_agent() {
        assert_eq!(
            headed_user_agent("Google Chrome 131.0.6778.86 \n", "macos").as_deref(),
            Some("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
        );
        assert_eq!(
            headed_user_agent("Chromium 154.0.8037.92 built on Ubuntu 24.04.5 LTS", "linux").as_deref(),
            Some("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/154.0.0.0 Safari/537.36")
        );
        assert!(headed_user_agent("Google Chrome 140.0.1.2", "windows").unwrap().contains("(Windows NT 10.0; Win64; x64)"));
        // the "24.04.5" in the build line is not taken for Chrome's version
        assert!(headed_user_agent("Chromium 154.0.8037.92 built on Ubuntu 24.04.5", "linux").unwrap().contains("Chrome/154.0.0.0"));
        assert_eq!(headed_user_agent("", "linux"), None);
        assert_eq!(headed_user_agent("Chromium version unknown", "linux"), None);

    }

    #[test]
    fn chrome_keeps_its_own_user_agent_and_is_not_marked_automated() {
        for headless in [true, false] {
            let args = chrome_args(Path::new("/p"), headless);
            // the flag empties the client hints Google asks for; the identity is set over DevTools
            assert!(!args.iter().any(|a| a.starts_with("--user-agent")), "{args:?}");
            assert!(!args.iter().any(|a| a.starts_with("--enable-automation")), "{args:?}");
            assert!(args.contains(&"--disable-blink-features=AutomationControlled".to_string()), "{args:?}");
        }
    }

    #[test]
    fn google_chrome_is_told_apart_from_chromium() {
        assert!(is_google_chrome(Path::new("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome")));
        assert!(is_google_chrome(Path::new("/usr/bin/google-chrome-stable")));
        assert!(is_google_chrome(Path::new(r"C:\Program Files\Google\Chrome\Application\chrome.exe")));
        assert!(!is_google_chrome(Path::new("/Applications/Chromium.app/Contents/MacOS/Chromium")));
        assert!(!is_google_chrome(Path::new("/usr/bin/chromium")));
        assert!(!is_google_chrome(Path::new("/home/me/.cache/kwant/chrome/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing")));
    }

    #[test]
    fn an_installed_google_chrome_is_preferred_over_a_chromium_earlier_on_the_path() {
        let early = tempfile::tempdir().unwrap();
        let late = tempfile::tempdir().unwrap();
        std::fs::write(early.path().join("chromium"), "").unwrap();
        std::fs::write(late.path().join("google-chrome"), "").unwrap();
        let path = std::env::join_paths([early.path(), late.path()]).unwrap();
        assert_eq!(find_chrome(None, "linux", None, path.to_str()), Some(late.path().join("google-chrome")));

        let machine = tempfile::tempdir().unwrap();
        let person = tempfile::tempdir().unwrap();
        let chromium = machine.path().join("Chromium/Application/chrome.exe");
        std::fs::create_dir_all(chromium.parent().unwrap()).unwrap();
        std::fs::write(&chromium, "").unwrap();
        let roots = [machine.path().to_path_buf(), person.path().to_path_buf()];
        assert_eq!(windows_chrome(&roots), Some(chromium));
        let chrome = person.path().join("Google/Chrome/Application/chrome.exe");
        std::fs::create_dir_all(chrome.parent().unwrap()).unwrap();
        std::fs::write(&chrome, "").unwrap();
        assert_eq!(windows_chrome(&roots), Some(chrome));
        assert_eq!(windows_chrome(&[]), None);
    }

    #[tokio::test]
    async fn the_fetch_user_agent_is_a_normal_chrome() {
        assert!(!browser_user_agent().await.contains("Headless"));
        assert!(browser_user_agent().await.contains(" Chrome/"));
    }

    #[test]
    fn windowless_is_read_from_the_command_line() {
        let headless = chrome_args(Path::new("/p"), true);
        assert!(is_headless_command_line(&format!("/usr/lib/chromium/chromium {}", headless.join(" "))));
        let window = chrome_args(Path::new("/p"), false);
        assert!(!is_headless_command_line(&format!("/usr/lib/chromium/chromium {}", window.join(" "))));
        assert!(is_headless_command_line("chrome --headless --user-data-dir=/p"));
        // a profile or user agent that merely mentions it is not the flag
        assert!(!is_headless_command_line("chrome --user-data-dir=/home/me/--headless-notes"));
        assert!(!is_headless_command_line("chrome --user-agent=Mozilla/5.0 HeadlessChrome/154 --headlessly"));
    }

    #[test]
    fn an_unreadable_command_line_falls_back_to_the_launch_record() {
        let agent = headed_user_agent("Chromium 154.0.8037.92", "linux").unwrap();
        // kwant's own windowless Chrome sends a windowed user agent: the record decides
        assert!(is_windowless(None, Some(true), &agent));
        assert!(!is_windowless(None, Some(false), &agent));
        // the command line wins over both
        assert!(!is_windowless(Some("chromium --user-data-dir=/p"), Some(true), "HeadlessChrome/154"));
        assert!(is_windowless(Some("chromium --headless=new"), Some(false), &agent));
        // an older kwant's Chrome left no record and still says so in its user agent
        assert!(is_windowless(None, None, "Mozilla/5.0 (X11; Linux x86_64) HeadlessChrome/154.0.0.0"));
        assert!(!is_windowless(None, None, &agent));

        let dir = tempfile::tempdir().unwrap();
        assert_eq!(launched_headless(dir.path()), None);
        record_launch_mode(dir.path(), true).unwrap();
        assert_eq!(launched_headless(dir.path()), Some(true));
        record_launch_mode(dir.path(), false).unwrap();
        assert_eq!(launched_headless(dir.path()), Some(false));
    }

    #[test]
    fn a_windowless_chrome_an_older_kwant_started_is_started_again() {
        let profile = Path::new("/p");
        let now = format!("chromium {}", chrome_args(profile, true).join(" "));
        assert!(!is_older_launch(Some(&now), false), "kwant's own launch, read from its command line");
        let old = format!(
            "chromium --user-data-dir=/p --remote-debugging-port=0 --headless=new --window-size={HEADLESS_WINDOW_SIZE} --user-agent=Mozilla/5.0 (X11; Linux x86_64) Chrome/141.0.0.0 Safari/537.36 about:blank"
        );
        assert!(is_older_launch(Some(&old), true), "0.9.4: a made-up user agent, marked automated");
        assert!(is_older_launch(Some(&format!("{now} --user-agent=x")), false));
        // no command line (Windows): kwant's mark decides
        assert!(is_older_launch(None, false));
        assert!(!is_older_launch(None, true));

        let dir = tempfile::tempdir().unwrap();
        assert!(!dir.path().join(LAUNCH_IDENTITY_FILE).exists());
        record_launch_identity(dir.path()).unwrap();
        assert!(dir.path().join(LAUNCH_IDENTITY_FILE).exists());
    }

    /// Rigel's finding on #22: kwant's windowless Chrome answers with a windowed user agent, and
    /// when its command line can't be read (no `SingletonLock` here, so no owner) it was taken for
    /// a window, so every call saw the wrong form and restarted it.
    #[tokio::test]
    async fn windowless_chrome_with_an_unreadable_command_line_is_still_windowless() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        tokio::spawn(async move {
            use tokio::io::{AsyncReadExt, AsyncWriteExt};
            while let Ok((mut stream, _)) = listener.accept().await {
                let mut buf = [0u8; 1024];
                let _ = stream.read(&mut buf).await;
                let body = r#"{"Browser":"Chrome/154.0.8037.92","User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/154.0.0.0 Safari/537.36"}"#;
                let reply = format!("HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", body.len());
                let _ = stream.write_all(reply.as_bytes()).await;
            }
        });
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("DevToolsActivePort"), format!("{port}\n/devtools/browser/x\n")).unwrap();
        record_launch_mode(dir.path(), true).unwrap();
        let (_, headless) = running_local_chrome(dir.path()).await.expect("chrome answers");
        assert!(headless, "kwant started it windowless");
        record_launch_mode(dir.path(), false).unwrap();
        let (_, headless) = running_local_chrome(dir.path()).await.unwrap();
        assert!(!headless);
    }

    #[test]
    fn devtools_port_file() {
        let dir = tempfile::tempdir().unwrap();
        assert_eq!(read_devtools_port(dir.path()), None);
        std::fs::write(
            dir.path().join("DevToolsActivePort"),
            "41234\n/devtools/browser/x\n",
        )
        .unwrap();
        assert_eq!(read_devtools_port(dir.path()), Some(41234));
        std::fs::write(dir.path().join("DevToolsActivePort"), "0\n").unwrap();
        assert_eq!(read_devtools_port(dir.path()), None);
    }

    fn fast() -> LaunchTiming {
        LaunchTiming {
            owner: Duration::from_millis(400),
            start: Duration::from_secs(5),
            step: Duration::from_millis(20),
        }
    }

    /// A pid that is not running: a child that already exited and was reaped.
    #[cfg(unix)]
    fn dead_pid() -> u32 {
        let mut child = std::process::Command::new("true").spawn().unwrap();
        let pid = child.id();
        child.wait().unwrap();
        pid
    }

    #[cfg(unix)]
    fn hold_profile(profile: &Path, pid: u32) {
        std::os::unix::fs::symlink(format!("host-{pid}"), profile.join("SingletonLock")).unwrap();
    }

    /// A live process, alive until dropped. `chrome_on`: it looks like a Chrome started on that
    /// profile ("chrome --user-data-dir=<profile>" on its command line); otherwise it is some
    /// unrelated program, like the `sleep` whose pid reused a crashed Chrome's.
    #[cfg(unix)]
    struct Process(std::process::Child);

    #[cfg(unix)]
    impl Process {
        fn start(chrome_on: Option<&Path>) -> Self {
            let mut cmd = std::process::Command::new("sh");
            cmd.args(["-c", "read _"]);
            if let Some(profile) = chrome_on {
                cmd.arg("chrome").arg(format!("--user-data-dir={}", profile.display()));
            }
            let child = cmd.stdin(std::process::Stdio::piped()).spawn().unwrap();
            // just after the spawn its command line can still read as empty, which made
            // `profile_owner` miss it on busy machines; wait until `sh` shows up there
            let started = std::time::Instant::now();
            while !command_line(child.id()).is_some_and(|line| line.contains("read _")) {
                assert!(started.elapsed() < Duration::from_secs(5), "test process did not start");
                std::thread::sleep(Duration::from_millis(5));
            }
            Self(child)
        }
        fn id(&self) -> u32 { self.0.id() }
    }

    #[cfg(unix)]
    impl Drop for Process {
        fn drop(&mut self) {
            let _ = self.0.kill();
            let _ = self.0.wait();
        }
    }

    #[cfg(unix)]
    #[test]
    fn profile_owner_reads_chromes_singleton_lock() {
        let dir = tempfile::tempdir().unwrap();
        assert_eq!(profile_owner(dir.path()), None);
        let chrome = Process::start(Some(dir.path()));
        hold_profile(dir.path(), chrome.id());
        assert_eq!(profile_owner(dir.path()), Some(chrome.id()));
        std::fs::remove_file(dir.path().join("SingletonLock")).unwrap();
        hold_profile(dir.path(), dead_pid());
        assert_eq!(profile_owner(dir.path()), None);
    }

    /// Bug A: Chrome crashed and its pid now belongs to an unrelated live program. The lock names
    /// that pid, but it does not hold the profile.
    #[cfg(unix)]
    #[test]
    fn a_live_pid_that_is_not_this_profiles_chrome_does_not_hold_it() {
        let dir = tempfile::tempdir().unwrap();
        let other = Process::start(None);
        hold_profile(dir.path(), other.id());
        assert_eq!(profile_owner(dir.path()), None);
        // nor does a Chrome on another profile, even one whose path starts with this one
        let sibling = dir.path().with_extension("other");
        let chrome = Process::start(Some(&sibling));
        std::fs::remove_file(dir.path().join("SingletonLock")).unwrap();
        hold_profile(dir.path(), chrome.id());
        assert_eq!(profile_owner(dir.path()), None);
    }

    #[test]
    fn chrome_command_lines() {
        let p = Path::new("/Users/o/Library/Application Support/kwant/local-chrome");
        let flag = format!("--user-data-dir={}", p.display());
        assert!(is_chrome_on(&format!("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome {flag} --remote-debugging-port=0"), p));
        assert!(is_chrome_on(&format!("/usr/bin/chromium {flag}"), p));
        assert!(!is_chrome_on(&format!("/usr/bin/chromium {flag}2"), p));
        assert!(!is_chrome_on("sleep 600", p));
        // the profile is called local-chrome, which alone is not a Chrome
        assert!(!is_chrome_on(&format!("/usr/bin/python3 {flag}"), p));
    }

    /// Rigel's repro of Bug A: Chrome was killed, and SingletonLock names a live `sleep`. One
    /// fresh Chrome starts at once, and the stale lock is cleared so it can.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_lock_naming_another_program_starts_one_chrome() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("DevToolsActivePort"), "1\n").unwrap();
        let other = Process::start(None);
        hold_profile(dir.path(), other.id());
        let up = std::sync::atomic::AtomicBool::new(false);
        let probe = || {
            let found = up.load(std::sync::atomic::Ordering::SeqCst);
            async move { found.then(|| ("http://127.0.0.1:9".to_string(), true)) }
        };
        let lock = dir.path().join("SingletonLock");
        let mut spawns = 0;
        let timing = LaunchTiming { owner: Duration::from_secs(30), ..fast() };
        let started = std::time::Instant::now();
        let result = ensure_chrome_with(dir.path(), probe, || {
            assert!(std::fs::symlink_metadata(&lock).is_err(), "the stale lock goes before the start");
            spawns += 1;
            up.store(true, std::sync::atomic::Ordering::SeqCst);
            Ok(())
        }, timing).await;
        assert!(result.is_ok(), "{result:?}");
        assert_eq!(spawns, 1);
        assert!(started.elapsed() < Duration::from_secs(5), "it did not wait on the other program");
    }

    /// The Bot browser button, its stream and a bot's turn all asking at once start one Chrome.
    #[tokio::test]
    async fn concurrent_launches_start_one_chrome() {
        use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst};
        use std::sync::Arc;
        let dir = tempfile::tempdir().unwrap();
        let profile = dir.path().join("local-chrome");
        let spawns = Arc::new(AtomicUsize::new(0));
        let up = Arc::new(AtomicBool::new(false));
        let mut calls = Vec::new();
        for _ in 0..10 {
            let (profile, spawns, up) = (profile.clone(), spawns.clone(), up.clone());
            calls.push(tokio::spawn(async move {
                let probe = || {
                    let up = up.clone();
                    async move { up.load(SeqCst).then(|| ("http://127.0.0.1:9".to_string(), true)) }
                };
                let spawn = || {
                    spawns.fetch_add(1, SeqCst);
                    let up = up.clone();
                    // Chrome takes a moment to open its port
                    tokio::spawn(async move {
                        tokio::time::sleep(Duration::from_millis(150)).await;
                        up.store(true, SeqCst);
                    });
                    Ok(())
                };
                ensure_chrome_with(&profile, probe, spawn, fast()).await
            }));
        }
        for call in calls {
            assert!(call.await.unwrap().is_ok());
        }
        assert_eq!(spawns.load(SeqCst), 1);
    }

    /// A live Chrome that holds the profile but does not answer (its port file stale or gone) is
    /// never started again, and its port file is left alone.
    #[cfg(unix)]
    #[tokio::test]
    async fn stale_port_file_with_live_chrome_does_not_start_another() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("DevToolsActivePort"), "1\n/devtools/browser/x\n").unwrap();
        let chrome = Process::start(Some(dir.path()));
        hold_profile(dir.path(), chrome.id());
        let mut spawned = false;
        let result = ensure_chrome_with(dir.path(), || async { None }, || { spawned = true; Ok(()) }, fast()).await;
        let error = result.unwrap_err();
        assert!(!spawned);
        assert!(error.contains("did not start another"), "{error}");
        assert!(dir.path().join("DevToolsActivePort").exists());
    }

    /// Clicks queued behind one that waited the full time for a stuck Chrome give up at once.
    #[cfg(unix)]
    #[tokio::test]
    async fn callers_behind_a_stuck_chrome_do_not_each_wait() {
        let dir = tempfile::tempdir().unwrap();
        let chrome = Process::start(Some(dir.path()));
        hold_profile(dir.path(), chrome.id());
        let timing = LaunchTiming { owner: Duration::from_secs(2), ..fast() };
        let first = std::time::Instant::now();
        assert!(ensure_chrome_with(dir.path(), || async { None }, || Ok(()), timing).await.is_err());
        assert!(first.elapsed() >= Duration::from_secs(2));
        let again = std::time::Instant::now();
        let error = ensure_chrome_with(dir.path(), || async { None }, || Ok(()), timing).await.unwrap_err();
        assert!(again.elapsed() < Duration::from_millis(500), "{:?}", again.elapsed());
        assert!(error.contains("did not start another"), "{error}");
        // once it answers it is used, and forgotten as stuck
        let found = ensure_chrome_with(dir.path(), || async { Some(("u".to_string(), true)) }, || Ok(()), timing).await;
        assert_eq!(found.unwrap().0, "u");
        assert!(unresponsive(dir.path(), None).is_none());
    }

    /// The same live Chrome that answers once it has started is reused, not started again.
    #[cfg(unix)]
    #[tokio::test]
    async fn starting_chrome_is_waited_for() {
        use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
        let dir = tempfile::tempdir().unwrap();
        let chrome = Process::start(Some(dir.path()));
        hold_profile(dir.path(), chrome.id());
        let probes = AtomicUsize::new(0);
        let probe = || {
            let n = probes.fetch_add(1, SeqCst);
            async move { (n >= 3).then(|| ("http://127.0.0.1:9".to_string(), false)) }
        };
        let mut spawned = false;
        let found = ensure_chrome_with(dir.path(), probe, || { spawned = true; Ok(()) }, fast()).await.unwrap();
        assert!(!spawned);
        assert_eq!(found, ("http://127.0.0.1:9".to_string(), false));
    }

    /// A Chrome that closes before it answers ends the wait at once, with its own last lines.
    #[tokio::test]
    async fn a_chrome_that_closes_at_once_stops_the_wait_with_its_last_lines() {
        let dir = tempfile::tempdir().unwrap();
        let stderr = dir.path().join(STDERR_FILE);
        std::fs::write(&stderr, "zero\none\n\ntwo\nthree\n  \nlibnss3.so: cannot open shared object file\n\n").unwrap();
        let started = std::time::Instant::now();
        let timing = LaunchTiming { start: Duration::from_secs(20), ..fast() };
        let error = ensure_chrome_with(dir.path(), || async { None }, || {
            let launched = Launched::tracked(Some(stderr.clone()));
            launched.closed(ChildExit::Code(127));
            Ok(launched)
        }, timing).await.unwrap_err();
        assert!(started.elapsed() < Duration::from_secs(2), "{:?}", started.elapsed());
        assert_eq!(
            error,
            "kwant's Chrome closed right after starting: libnss3.so: cannot open shared object file\n\n\
             Its last lines (exit code 127):\none\ntwo\nthree"
        );
    }

    /// The headline of a Chrome that closed, from these stderr lines.
    fn closed_with(stderr: &str, how: ChildExit) -> String {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(STDERR_FILE);
        std::fs::write(&path, stderr).unwrap();
        let launched = Launched::tracked(Some(path));
        launched.closed(how.clone());
        launched.closed_message(&how)
    }

    /// Real Chrome with no display (Rigel's #557 QA): the cause is an ERROR line, and dbus lines
    /// printed after it are not the headline. The cause is said once, not again in the list.
    #[tokio::test]
    async fn the_headline_is_the_last_error_line_not_dbus_noise_after_it() {
        let dir = tempfile::tempdir().unwrap();
        let stderr = dir.path().join(STDERR_FILE);
        std::fs::write(&stderr, "\
[9:9:1113/054200.101:WARNING:chrome_main_linux.cc(80)] Read channel stable from /opt/chromium/CHROME_VERSION_EXTRA
[9:9:1113/054200.102:ERROR:ozone_platform_x11.cc(240)] Missing X server or $DISPLAY
[9:30:1113/054200.103:ERROR:bus.cc(407)] Failed to connect to the bus: Could not parse server address: Unknown address type
[9:31:1113/054200.104:ERROR:object_proxy.cc(576)] Failed to call method: org.freedesktop.DBus.Properties.Get
").unwrap();
        let error = ensure_chrome_with(dir.path(), || async { None }, || {
            let launched = Launched::tracked(Some(stderr.clone()));
            launched.closed(ChildExit::Code(1));
            Ok(launched)
        }, fast()).await.unwrap_err();
        assert!(
            error.starts_with("kwant's Chrome closed right after starting: [9:9:1113/054200.102:ERROR:ozone_platform_x11.cc(240)] Missing X server or $DISPLAY\n\nIts last lines (exit code 1):\n"),
            "{error}"
        );
        assert_eq!(error.matches("Missing X server").count(), 1, "said once: {error}");
        assert!(error.ends_with("Unknown address type\n[9:31:1113/054200.104:ERROR:object_proxy.cc(576)] Failed to call method: org.freedesktop.DBus.Properties.Get"), "{error}");
        assert!(error.contains("(exit code 1):\n[9:9:1113/054200.101:WARNING"), "the other lines are listed: {error}");
    }

    /// The pick: an error line wins over a later plain line, a plain "error while loading" counts,
    /// the cause is found further back than the three listed lines, and repeats of it aren't listed.
    #[test]
    fn the_headline_prefers_errors_and_looks_past_the_listed_lines() {
        let error = closed_with("[1:1:ERROR:gpu_init.cc] GPU process isn't usable\nOpening in existing browser session.\n", ChildExit::Code(0));
        assert_eq!(
            error,
            "kwant's Chrome closed right after starting: [1:1:ERROR:gpu_init.cc] GPU process isn't usable\n\n\
             Its last lines (exit code 0):\nOpening in existing browser session."
        );
        let error = closed_with(
            "[1:1:ERROR:sandbox_linux.cc] starting up\nchrome: error while loading shared libraries: libnss3.so\n",
            ChildExit::Code(127),
        );
        assert!(error.starts_with("kwant's Chrome closed right after starting: chrome: error while loading shared libraries: libnss3.so\n"), "{error}");
        let dbus = "[1:2:ERROR:bus.cc(407)] Failed to connect to the bus: Could not parse server address\n";
        let error = closed_with(&format!("[1:1:FATAL:zygote_host_impl_linux.cc] No usable sandbox!\n{}", dbus.repeat(5)), ChildExit::Signal(5));
        assert!(error.starts_with("kwant's Chrome closed right after starting: [1:1:FATAL:zygote_host_impl_linux.cc] No usable sandbox!\n"), "{error}");
        assert_eq!(error.lines().filter(|line| line.contains("Failed to connect")).count(), 3, "at most three listed: {error}");
        let error = closed_with("[1:1:ERROR:a.cc] same cause\nother\n[1:1:ERROR:a.cc] same cause\n", ChildExit::Code(1));
        assert_eq!(error, "kwant's Chrome closed right after starting: [1:1:ERROR:a.cc] same cause\n\nIts last lines (exit code 1):\nother");
    }

    /// Only dbus lines: today's headline (the last line), not repeated in the list.
    #[test]
    fn all_dbus_lines_fall_back_to_the_last_line() {
        let error = closed_with(
            "Failed to connect to the bus: first\n[1:2:ERROR:bus.cc(407)] Failed to connect to the bus: second\n",
            ChildExit::Code(1),
        );
        assert_eq!(
            error,
            "kwant's Chrome closed right after starting: [1:2:ERROR:bus.cc(407)] Failed to connect to the bus: second\n\n\
             Its last lines (exit code 1):\nFailed to connect to the bus: first"
        );
    }

    /// One line is the headline alone, still with how Chrome ended; blank stderr printed no error.
    #[test]
    fn one_line_has_no_list_and_blank_stderr_printed_no_error() {
        assert_eq!(
            closed_with("\n  libnss3.so: cannot open shared object file\n\n", ChildExit::Code(127)),
            "kwant's Chrome closed right after starting: libnss3.so: cannot open shared object file (exit code 127)"
        );
        assert_eq!(
            closed_with("\n   \n\n", ChildExit::Signal(6)),
            "kwant's Chrome closed right after starting (signal 6) and printed no error."
        );
    }

    /// One that printed nothing still says it closed, and how.
    #[tokio::test]
    async fn a_silent_chrome_that_closes_says_so() {
        let dir = tempfile::tempdir().unwrap();
        let error = ensure_chrome_with(dir.path(), || async { None }, || {
            let launched = Launched::tracked(None);
            launched.closed(ChildExit::Signal(6));
            Ok(launched)
        }, fast()).await.unwrap_err();
        assert_eq!(error, "kwant's Chrome closed right after starting (signal 6) and printed no error.");
    }

    /// A Chrome that answers is used even if the process kwant started has ended (it handed over).
    #[tokio::test]
    async fn a_chrome_that_answers_is_used_even_after_its_launcher_ended() {
        let dir = tempfile::tempdir().unwrap();
        // nothing answers before the start; once started, it answers though its process has ended
        let probes = std::sync::atomic::AtomicUsize::new(0);
        let probe = || {
            let n = probes.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            async move { (n >= 1).then(|| ("v".to_string(), true)) }
        };
        let found = ensure_chrome_with(dir.path(), probe, || {
            let launched = Launched::tracked(None);
            launched.closed(ChildExit::Code(0));
            Ok(launched)
        }, fast()).await;
        assert_eq!(found.unwrap().0, "v");
    }

    #[test]
    fn stderr_tail_reads_only_the_end_and_cuts_long_lines() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(STDERR_FILE);
        assert!(stderr_tail(&path).is_empty(), "no file");
        let mut text = "early line\n".repeat(5000); // more than the 16 KB read
        text.push_str(&"x".repeat(400));
        text.push_str("\nlast\n");
        std::fs::write(&path, text).unwrap();
        let tail = stderr_tail(&path);
        assert_eq!(tail.len(), TAIL_LINES);
        assert_eq!(tail[TAIL_LINES - 3], "early line");
        assert_eq!(tail[TAIL_LINES - 2], format!("{}…", "x".repeat(300)));
        assert_eq!(tail[TAIL_LINES - 1], "last");
    }

    /// A port file left by a Chrome that is gone is removed and one fresh Chrome starts.
    #[cfg(unix)]
    #[tokio::test]
    async fn stale_port_file_with_dead_chrome_starts_one() {
        let dir = tempfile::tempdir().unwrap();
        let port_file = dir.path().join("DevToolsActivePort");
        std::fs::write(&port_file, "1\n").unwrap();
        hold_profile(dir.path(), dead_pid());
        let up = std::sync::atomic::AtomicBool::new(false);
        let probe = || {
            let found = up.load(std::sync::atomic::Ordering::SeqCst);
            async move { found.then(|| ("http://127.0.0.1:9".to_string(), true)) }
        };
        let mut spawns = 0;
        let result = ensure_chrome_with(dir.path(), probe, || {
            assert!(!port_file.exists(), "the stale port file goes before the start");
            spawns += 1;
            up.store(true, std::sync::atomic::Ordering::SeqCst);
            Ok(())
        }, fast()).await;
        assert!(result.is_ok());
        assert_eq!(spawns, 1);
    }
}