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.

58.7 KB
Raw Blame
//! One browser service per installation; isolated CDP contexts per bot/team.
//! The private CDP endpoint is used only by the server, never by the web client.
use super::browser::{outage, BrowserController, BrowserError, Outage};
use super::browser_downloads::DownloadHome;
use super::chrome_download::{self, ChromeSetup};
use super::browser_proxy::{BrowserProxy, ENV_BYPASS, ENV_PROXY};
use super::computer::{self, ComputerMode};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::{collections::HashMap, path::{Path, PathBuf}, time::Duration};
use tokio::{process::Command, sync::Mutex, time::{sleep, timeout}};

/// The `--pids-limit` of kwant's own browser container ([`managed_run_args`]): processes and
/// threads together. Chrome and its DevTools proxy can't fork past it, so the browser's pages are
/// kept under a budget derived from it (31b, [`crate::server::browser_pages::PAGE_PID_BUDGET`]).
pub const BROWSER_PIDS_LIMIT: u64 = 512;

/// The VM browser's image. Bump it whenever `docker/browser.Dockerfile` or
/// `docker/browser-entrypoint.sh` change: kwant builds an image only when its tag is missing, and
/// replaces a browser container made from another tag, so the bump is what ships the change.
pub const BROWSER_IMAGE: &str = "kwnt-browser:v5";
const BROWSER_DOCKERFILE: &str = include_str!("../../docker/browser.Dockerfile");
const BROWSER_ENTRYPOINT: &str = include_str!("../../docker/browser-entrypoint.sh");

/// What a bot (and the panel) is told when the VM browser didn't answer in time, even after
/// retrying for about [`crate::server::browser_pages::RETRY_WINDOW`]: it is there but overloaded.
/// It says the problem is temporary and what to do, so a bot retries the step instead of
/// ending its work (0.9.4 follow-through, 0.9.5 no-silent-stops key on it). Calls that fail
/// this way also carry `"code": "BROWSER_BUSY"` and `"retryable": true`.
pub const BROWSER_BUSY: &str = "The browser isn't responding right now (it is overloaded, not gone). \
This is temporary: retry the same step in a minute.";
/// The `code` of a call that failed because the browser is busy (see [`BROWSER_BUSY`]).
pub const BROWSER_BUSY_CODE: &str = "BROWSER_BUSY";
/// What the live view shows while it reconnects to a browser that is busy.
pub const BROWSER_RECONNECTING: &str = "The browser isn't responding. Reconnecting…";
/// How long the status check waits for the browser's answer before calling it busy.
const PING_WAIT: Duration = Duration::from_secs(5);
/// What the live view shows when nothing answers at the browser's address.
pub const BROWSER_UNREACHABLE_VIEW: &str = "Browser service unavailable. Check Docker or KWNT_BROWSER_CDP_URL.";

/// How a page was put to rest by the idle sweep (see `browser_pages::rest_idle`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Rest {
    /// Media paused and the page frozen; it wakes before its next use.
    Frozen,
    /// A team page idle for hours, sent to about:blank (its cookies stay in the jar).
    Blank,
}

/// Joins a job page's key: `team#bot#chat` (see [`job_page_key`]).
pub const PAGE_SEP: char = '#';

/// The key of a job's own page in its team's browser: one page per (sandbox target, bot, chat).
/// `None` when a part is empty or holds [`PAGE_SEP`] (such a job uses the team page).
pub fn job_page_key(team: &str, kwant: &str, chat: &str) -> Option<String> {
    let ok = |p: &str| !p.is_empty() && !p.contains(PAGE_SEP);
    (ok(team) && ok(kwant) && ok(chat)).then(|| format!("{team}{PAGE_SEP}{kwant}{PAGE_SEP}{chat}"))
}

/// The team (sandbox target) a page belongs to: the key itself for the team page.
pub fn page_team(key: &str) -> &str {
    key.split(PAGE_SEP).next().unwrap_or(key)
}

/// Whether this key names a job's own page rather than a team page.
pub fn is_job_page(key: &str) -> bool {
    key.contains(PAGE_SEP)
}

#[derive(Clone, Serialize, Deserialize)]
struct SessionTarget {
    context: String,
    target: String,
}

/// The page before the current one in the tab `target` of the browser at `endpoint`.
async fn previous_entry(endpoint: &str, target: &str) -> Option<String> {
    let page = BrowserController::at_endpoint(endpoint, Some(target.to_string()), false);
    let history = page.send_cdp_command("Page.getNavigationHistory", json!({})).await.ok()?;
    let index = history["currentIndex"].as_u64()? as usize;
    history["entries"].as_array()?.get(index.checked_sub(1)?)?["url"].as_str().map(str::to_string)
}

/// 29d: what a live view on a page the person picked last read there (its own `location`
/// message), kept per page key for the tab list. Such a view never writes the controller's
/// address (29a), so without this the page's tab-list entry would stay on its old address while
/// the person clicks links or goes Back/Forward in it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SeenLocation {
    pub url: String,
    pub title: String,
    /// The controller's `(current_url, current_title)` when this was read. While the controller
    /// still holds exactly these, nothing wrote it since, so this read is the newer one; once it
    /// holds anything else, browser.rs wrote it after this read and the controller is newer.
    pub over: (Option<String>, Option<String>),
}

/// Each page's [`SeenLocation`], by page key. Cloned handles share one map.
#[derive(Clone, Default)]
pub struct PagesSeen(std::sync::Arc<std::sync::Mutex<HashMap<String, SeenLocation>>>);

impl PagesSeen {
    fn map(&self) -> std::sync::MutexGuard<'_, HashMap<String, SeenLocation>> {
        self.0.lock().unwrap_or_else(|e| e.into_inner())
    }

    pub fn record(&self, key: &str, seen: SeenLocation) {
        self.map().insert(key.to_string(), seen);
    }

    pub fn get(&self, key: &str) -> Option<SeenLocation> {
        self.map().get(key).cloned()
    }

    pub fn forget(&self, key: &str) {
        self.map().remove(key);
    }

    /// Forgets the team page `team` and all its job pages.
    pub fn forget_team(&self, team: &str) {
        let prefix = format!("{team}{PAGE_SEP}");
        self.map().retain(|k, _| k != team && !k.starts_with(&prefix));
    }
}

pub struct BrowserService {
    root: PathBuf,
    endpoint: Option<String>,
    /// Local Chrome or the vm browser; changing it drops the connection (see [`Self::set_mode`]).
    mode: std::sync::RwLock<ComputerMode>,
    /// Local mode only: whether the person asked to see the kwant Chrome as a window (to sign in
    /// or solve a CAPTCHA). Otherwise it runs without one and the app streams it. Not saved: a
    /// restart goes back to the in-app view.
    local_window: std::sync::atomic::AtomicBool,
    // Serialize startup and session creation, including simultaneous status/frame requests.
    state: Mutex<Option<ServiceState>>,
    /// Why the last [`Self::session`] failed, for the error the person sees.
    last_error: std::sync::Mutex<Option<String>>,
    /// When a bot last used the browser (see [`Self::note_use`]).
    last_use: std::sync::Mutex<Option<std::time::SystemTime>>,
    /// Local mode without Chrome: the private browser kwnt downloads on first use (O5).
    chrome_setup: std::sync::Arc<ChromeSetup>,
    /// When each page (team or job page) was last used in this run: the job-page cap closes the
    /// least recently used one, the idle sweep the ones past their limit, and the live view
    /// shows the newest. A page kept from an earlier run counts from when this run first saw it.
    page_use: std::sync::Mutex<HashMap<String, std::time::Instant>>,
    /// Why the last [`Self::session`] failed, as far as what to do next goes (VM mode).
    last_outage: std::sync::Mutex<Option<Outage>>,
    /// Pages the idle sweep put to rest, until they are used again (see [`Self::touch_page`]).
    rested: std::sync::Mutex<HashMap<String, Rest>>,
    /// 29d: what a view on a picked page last read there, for the tab list ([`PagesSeen`]).
    pages_seen: PagesSeen,
}

struct ServiceState {
    browser: BrowserController,
    endpoint: String,
    sessions: HashMap<String, SessionTarget>,
    /// The configured controller behind each live session, reused across calls so its
    /// `downloads` connection (see `browser_downloads.rs`) stays the one background task the
    /// whole session's downloads and file choosers are tracked on, instead of a blank one per
    /// call. Not persisted: a reconnect starts empty and each session gets a fresh controller the
    /// next time it's used, same as before this cache existed.
    controllers: HashMap<String, BrowserController>,
}

impl BrowserService {
    pub fn new(root: PathBuf, endpoint: Option<String>) -> Self {
        let mode = computer::current_mode(None);
        Self {
            root, endpoint, mode: std::sync::RwLock::new(mode),
            local_window: std::sync::atomic::AtomicBool::new(false), state: Mutex::new(None),
            last_error: std::sync::Mutex::new(None), last_use: std::sync::Mutex::new(None),
            chrome_setup: std::sync::Arc::new(ChromeSetup::system()),
            page_use: Default::default(),
            last_outage: Default::default(),
            rested: Default::default(),
            pages_seen: Default::default(),
        }
    }

    /// The same service with its private browser downloaded through `setup` (tests).
    pub fn with_chrome_setup(mut self, setup: ChromeSetup) -> Self {
        self.chrome_setup = std::sync::Arc::new(setup);
        self
    }

    /// The private browser download (O5): its state for the UI, and "Try again".
    pub fn chrome_setup(&self) -> &std::sync::Arc<ChromeSetup> { &self.chrome_setup }

    /// Local mode with no Chrome on this computer: downloads the private browser first, outside
    /// the connection lock so status and frames don't wait for a download.
    async fn ensure_private_browser(&self) -> Result<(), BrowserError> {
        if self.mode() != ComputerMode::Local || !self.chrome_setup.available() {
            return Ok(());
        }
        let found = tokio::task::spawn_blocking(computer::local_chrome_path).await.ok().flatten();
        if found.is_none() {
            self.chrome_setup.ensure().await.map_err(BrowserError::Http)?;
        }
        Ok(())
    }

    pub fn mode(&self) -> ComputerMode {
        *self.mode.read().unwrap_or_else(|e| e.into_inner())
    }

    /// Whether local Chrome is shown as a window instead of in the app.
    pub fn local_window(&self) -> bool {
        self.local_window.load(std::sync::atomic::Ordering::SeqCst)
    }

    fn local_profile(&self) -> PathBuf { self.root.join("local-chrome") }

    /// The addresses of the local Chrome's pages, or `None` when it isn't running.
    pub async fn local_page_urls(&self) -> Option<Vec<String>> {
        let (endpoint, _) = computer::running_local_chrome(&self.local_profile()).await?;
        let browser = BrowserController::at_endpoint(&endpoint, None, true);
        let targets = browser.send_cdp_command("Target.getTargets", json!({})).await.ok()?;
        Some(targets["targetInfos"].as_array().into_iter().flatten()
            .filter(|t| t["type"] == "page")
            .filter_map(|t| t["url"].as_str().map(str::to_string))
            .collect())
    }

    /// Shows the local Chrome as a real window (`visible`) or runs it without one, streamed into
    /// the app. One profile cannot be open twice, so the running Chrome is closed and started
    /// again in the other form; each bot's open page is reopened there, and sign-ins saved in the
    /// profile carry over. On failure the previous form is kept.
    pub async fn set_local_window(&self, visible: bool) -> Result<(), BrowserError> {
        use std::sync::atomic::Ordering::SeqCst;
        let mut lock = self.state.lock().await;
        let previous = self.local_window.swap(visible, SeqCst);
        if self.mode() != ComputerMode::Local { return Ok(()); }
        // the page each bot had open, to reopen in the new Chrome
        let mut urls: HashMap<String, String> = HashMap::new();
        if let Some((endpoint, _)) = computer::running_local_chrome(&self.local_profile()).await {
            let browser = BrowserController::at_endpoint(&endpoint, None, true);
            if let Ok(targets) = browser.send_cdp_command("Target.getTargets", json!({})).await {
                for info in targets["targetInfos"].as_array().into_iter().flatten() {
                    if let (Some(id), Some(url)) = (info["targetId"].as_str(), info["url"].as_str()) {
                        // a sign-in Google refused opens again at the sign-in, not at the refusal
                        let previous = if super::signin_gate::is_rejected(url) {
                            previous_entry(&endpoint, id).await
                        } else {
                            None
                        };
                        if let Some(url) = super::signin_gate::reopen_url(url, previous.as_deref()) {
                            urls.insert(id.to_string(), url);
                        }
                    }
                }
            }
        }
        *lock = None;
        let mut state = match self.connect().await {
            Ok(state) => state,
            Err(error) => { self.local_window.store(previous, SeqCst); return Err(error); }
        };
        let live = state.browser.send_cdp_command("Target.getTargets", json!({})).await?;
        let live: Vec<(String, bool)> = live["targetInfos"].as_array().into_iter().flatten()
            .filter_map(|t| Some((t["targetId"].as_str()?.to_string(), t["type"] == "page" && t["url"] == "about:blank")))
            .collect();
        // Reopen only the pages that showed a site. A blank page would be one more empty window
        // per bot that ever used the browser; its bot gets a new one when it next asks.
        let mut dropped = Vec::new();
        for (bot, session) in state.sessions.iter_mut() {
            if live.iter().any(|(id, _)| *id == session.target) { continue; }
            let Some(url) = urls.get(&session.target).filter(|u| u.starts_with("http")) else {
                dropped.push(bot.clone());
                continue;
            };
            match state.browser.send_cdp_command("Target.createTarget", json!({"url": url, "newWindow": true})).await {
                Ok(target) => if let Some(id) = target["targetId"].as_str() { session.target = id.to_string(); },
                Err(_) => dropped.push(bot.clone()),
            }
        }
        for bot in dropped { state.sessions.remove(&bot); }
        // Chrome's own blank start window would sit on top of the bots' pages in the window
        if visible && !state.sessions.is_empty() {
            for (id, _) in live.iter().filter(|(id, blank)| *blank && !state.sessions.values().any(|s| s.target == *id)) {
                let _ = state.browser.send_cdp_command("Target.closeTarget", json!({"targetId": id})).await;
            }
        }
        self.save_sessions(&state.sessions).await?;
        *lock = Some(state);
        Ok(())
    }

    /// The local Chrome's endpoint, in the form asked for (window or not), starting it if needed.
    async fn local_endpoint(&self) -> Result<String, BrowserError> {
        let profile = self.local_profile();
        let headless = !self.local_window();
        // at most one kwant Chrome per profile: reuse it, or wait for the one starting
        let (endpoint, running_headless) = computer::ensure_local_chrome(&profile, headless).await
            .map_err(BrowserError::Http)?;
        // what pages tell sites is set over DevTools (`identity`), so a Chrome in the right form
        // will do, unless an older kwant started it marked as automated, which that can't undo
        let older = running_headless && headless && computer::started_by_older_kwant(&profile);
        if running_headless == headless && !older { return Ok(endpoint); }
        // the other form (or that older one) is running on this profile: close it first
        let _ = BrowserController::at_endpoint(&endpoint, None, true)
            .send_cdp_command("Browser.close", json!({})).await;
        computer::wait_local_chrome_gone(&profile).await.map_err(BrowserError::Http)?;
        let (endpoint, _) = computer::ensure_local_chrome(&profile, headless).await.map_err(BrowserError::Http)?;
        Ok(endpoint)
    }

    async fn save_sessions(&self, sessions: &HashMap<String, SessionTarget>) -> Result<(), BrowserError> {
        tokio::fs::create_dir_all(&self.root).await.map_err(|e| BrowserError::Http(e.to_string()))?;
        let file = self.sessions_file();
        tokio::fs::write(file.with_extension("tmp"), serde_json::to_vec(sessions).unwrap()).await
            .map_err(|e| BrowserError::Http(e.to_string()))?;
        tokio::fs::rename(file.with_extension("tmp"), file).await.map_err(|e| BrowserError::Http(e.to_string()))
    }

    /// Whether a browser service URL (`KWNT_BROWSER_CDP_URL`) is configured for vm mode.
    pub fn has_endpoint(&self) -> bool { self.endpoint.is_some() }

    /// Switches where the browser runs. The current connection is dropped; the vm container and
    /// a local Chrome window keep running, while a windowless local Chrome is closed, since
    /// nothing would show it. Returns whether the mode changed.
    pub async fn set_mode(&self, mode: ComputerMode) -> bool {
        let mut lock = self.state.lock().await;
        let previous = {
            let mut current = self.mode.write().unwrap_or_else(|e| e.into_inner());
            if *current == mode { return false; }
            std::mem::replace(&mut *current, mode)
        };
        *lock = None;
        if previous == ComputerMode::Local {
            if let Some((endpoint, true)) = computer::running_local_chrome(&self.local_profile()).await {
                let _ = BrowserController::at_endpoint(&endpoint, None, true)
                    .send_cdp_command("Browser.close", json!({})).await;
            }
        }
        true
    }

    /// Each mode keeps its own saved pages, since they live in different browsers.
    fn sessions_file(&self) -> PathBuf {
        self.root.join(match self.mode() {
            ComputerMode::Vm => "browser-sessions.json",
            ComputerMode::Local => "browser-sessions-local.json",
        })
    }

    pub(crate) async fn docker(args: &[&str], seconds: u64) -> Result<String, BrowserError> {
        let out = timeout(Duration::from_secs(seconds),
            crate::helper_process::output(Command::new("docker").args(args).kill_on_drop(true))).await
            .map_err(|_| BrowserError::Timeout)?
            .map_err(|e| BrowserError::Http(format!("docker: {e}")))?;
        // "docker:" marks it as Docker's failure, not the browser's (see [`outage`])
        if !out.status.success() {
            return Err(BrowserError::Protocol(format!("docker: {}", String::from_utf8_lossy(&out.stderr).trim())));
        }
        Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
    }

    async fn managed_endpoint(&self) -> Result<String, BrowserError> {
        let name = managed_container_name(&self.root);
        let found = Self::docker(&["inspect", "--format",
            &format!("{{{{.Config.Image}}}}|{{{{index .Config.Labels \"{LABEL_BROWSER}\"}}}}|{{{{index .Config.Labels \"{LABEL_PROXY}\"}}}}"), &name], 5).await.ok();
        // The proxy is part of the container (env + label): a changed setting makes a new one.
        let proxy = match BrowserProxy::from_env() {
            Ok(p) => p,
            Err(why) => { tracing::warn!("browser proxy ignored: {why}"); None }
        };
        let proxy_label = proxy.as_ref().map(|p| format!("{}|{}", p.url, p.bypass.join(";"))).unwrap_or_default();
        // A container made from an older image keeps that image's browser, and one made before
        // the labels (by an older kwant) restarts on boot and can't be reaped: make a new one.
        // Its profile is on tmpfs, so nothing is lost; cookies are kept in the data folder.
        let current = found.as_deref() == Some(&format!("{BROWSER_IMAGE}|1|{proxy_label}"));
        if found.is_some() && !current {
            Self::docker(&["rm", "-f", &name], 30).await?;
        }
        self.note_use();
        if current {
            if !matches!(Self::docker(&["inspect", "--format", "{{.State.Running}}", &name], 5).await.as_deref(), Ok("true")) {
                Self::docker(&["start", &name], 30).await?;
            }
        } else {
            if Self::docker(&["image", "inspect", BROWSER_IMAGE], 5).await.is_err() {
                let build = self.root.join("browser-image");
                tokio::fs::create_dir_all(&build).await.map_err(|e| BrowserError::Http(e.to_string()))?;
                tokio::fs::write(build.join("Dockerfile"), BROWSER_DOCKERFILE).await
                    .map_err(|e| BrowserError::Http(e.to_string()))?;
                tokio::fs::write(build.join("browser-entrypoint.sh"), BROWSER_ENTRYPOINT).await
                    .map_err(|e| BrowserError::Http(e.to_string()))?;
                Self::docker(&["build", "-t", BROWSER_IMAGE, &build.to_string_lossy()], 600).await?;
            }
            let args = managed_run_args(&name, &self.root, proxy.as_ref());
            let args: Vec<&str> = args.iter().map(String::as_str).collect();
            Self::docker(&args, 30).await?;
        }
        let binding = Self::docker(&["port", &name, "9222/tcp"], 5).await?;
        let port = binding.lines().next().and_then(|line| line.rsplit(':').next())
            .and_then(|p| p.parse::<u16>().ok()).ok_or_else(|| BrowserError::Protocol("Browser port missing".into()))?;
        Ok(format!("http://127.0.0.1:{port}"))
    }

    /// Records that a bot used the browser, for the idle reaper (see [`reap_containers`]). The
    /// time is kept in a file in the data folder so another kwant's reaper sees it too; it is
    /// written at most once a minute.
    pub fn note_use(&self) {
        let now = std::time::SystemTime::now();
        let mut last = self.last_use.lock().unwrap_or_else(|e| e.into_inner());
        if last.is_some_and(|t| now.duration_since(t).is_ok_and(|d| d < Duration::from_secs(60))) { return; }
        *last = Some(now);
        let _ = std::fs::create_dir_all(&self.root);
        let _ = std::fs::write(self.root.join(LAST_USE_FILE), b"");
    }

    /// Stops this kwant's browser container, if it runs one. Called when kwant shuts down; the
    /// next browser request starts it again. Its pages close; cookies are kept in the data folder.
    pub async fn shutdown(&self) {
        let mut lock = self.state.lock().await;
        *lock = None;
        if self.endpoint.is_some() { return; }
        let name = managed_container_name(&self.root);
        if matches!(Self::docker(&["inspect", "--format", "{{.State.Running}}", &name], 5).await.as_deref(), Ok("true")) {
            match Self::docker(&["stop", "-t", "5", &name], 20).await {
                Ok(_) => tracing::info!("Stopped the browser container {name}"),
                Err(e) => tracing::warn!("Could not stop the browser container {name}: {e}"),
            }
        }
    }

    /// Removes kwant browser containers whose data folder is gone and stops ones nobody has used
    /// for `idle` (see [`reap_action`]). This kwant's own container is stopped under the state
    /// lock, so no request is using it; the next one starts it again. Returns (removed, stopped).
    pub async fn reap_containers(&self, idle: Duration) -> (usize, usize) {
        let Ok(list) = Self::docker(&["ps", "-a", "--filter", &format!("label={LABEL_BROWSER}=1"),
            "--format", &format!("{{{{.Names}}}}\t{{{{.State}}}}\t{{{{.Label \"{LABEL_ROOT}\"}}}}")], 10).await
        else { return (0, 0) };
        let own = managed_container_name(&self.root);
        let (mut removed, mut stopped) = (0, 0);
        for line in list.lines() {
            let mut parts = line.splitn(3, '\t');
            let (Some(name), Some(state), Some(root)) = (parts.next(), parts.next(), parts.next()) else { continue };
            let root = Path::new(root);
            // a relative or missing label can't be checked from here: never treat it as gone
            let root_gone = root.is_absolute() && !root.is_dir();
            let idle_for = std::fs::metadata(root.join(LAST_USE_FILE)).and_then(|m| m.modified()).ok()
                .and_then(|t| std::time::SystemTime::now().duration_since(t).ok());
            let action = reap_action(state == "running", root_gone, idle_for, idle);
            match action {
                ReapAction::Keep => {}
                ReapAction::Remove => {
                    if name == own { *self.state.lock().await = None; }
                    if Self::docker(&["rm", "-f", name], 30).await.is_ok() { removed += 1; }
                }
                ReapAction::Stop => {
                    // another request may be using our own container: wait for it, then re-check
                    let guard = if name == own { Some(self.state.lock().await) } else { None };
                    if name == own {
                        let fresh = self.last_use.lock().unwrap_or_else(|e| e.into_inner())
                            .and_then(|t| std::time::SystemTime::now().duration_since(t).ok());
                        if fresh.is_some_and(|d| d < idle) { continue; }
                    }
                    if let Some(mut guard) = guard { *guard = None; }
                    if Self::docker(&["stop", "-t", "5", name], 20).await.is_ok() { stopped += 1; }
                }
            }
        }
        (removed, stopped)
    }

    /// Runs [`Self::reap_containers`] at startup and then every [`REAP_EVERY`] until `cancel`.
    /// Does nothing when kwant uses an outside browser service and runs no container of its own,
    /// or when Docker isn't there.
    pub fn spawn_reaper(self: std::sync::Arc<Self>, cancel: tokio_util::sync::CancellationToken) {
        if self.endpoint.is_some() { return; }
        let idle = idle_limit();
        tokio::spawn(async move {
            loop {
                let (removed, stopped) = self.reap_containers(idle).await;
                if removed + stopped > 0 {
                    tracing::info!("browser: removed {removed} and stopped {stopped} leftover browser containers");
                }
                tokio::select! {
                    _ = cancel.cancelled() => return,
                    _ = sleep(REAP_EVERY) => {}
                }
            }
        });
    }

    async fn connect(&self) -> Result<ServiceState, BrowserError> {
        let local = self.mode() == ComputerMode::Local;
        let endpoint = match &self.endpoint {
            _ if local => self.local_endpoint().await?,
            Some(endpoint) => endpoint.trim_end_matches('/').to_string(),
            None => self.managed_endpoint().await?,
        };
        let browser = BrowserController::at_endpoint(&endpoint, None, true);
        if self.endpoint.is_some() || local {
            browser.send_cdp_command("Browser.getVersion", json!({})).await?;
        } else { timeout(Duration::from_secs(30), async {
            loop {
                if browser.send_cdp_command("Browser.getVersion", json!({})).await.is_ok() { break; }
                sleep(Duration::from_millis(250)).await;
            }
        }).await.map_err(|_| BrowserError::Timeout)?; }
        // every page, popup and worker tells sites what this Chrome is, before any page loads
        browser.keep_identity().await;
        let sessions = tokio::fs::read(self.sessions_file()).await.ok()
            .and_then(|bytes| serde_json::from_slice(&bytes).ok()).unwrap_or_default();
        Ok(ServiceState { browser, endpoint, sessions, controllers: HashMap::new() })
    }

    /// What to tell the person when the browser could not be reached. In local mode that is the
    /// reason kwant's Chrome did not start, not Docker, which local mode does not use.
    /// In VM mode a browser that is there but didn't answer gets [`BROWSER_BUSY`]; the Docker
    /// advice is kept for one that can't be reached at all.
    pub fn unavailable_reason(&self) -> String {
        if self.mode() != ComputerMode::Local {
            if self.last_outage() == Some(Outage::Busy) {
                return BROWSER_BUSY.into();
            }
            return "Sandbox browser is unavailable. Check that Docker is running, then restart the browser.".into();
        }
        let last = self.last_error.lock().unwrap_or_else(|e| e.into_inner()).clone();
        match last {
            Some(reason) if reason.starts_with(chrome_download::FAILED_LINE) => reason,
            Some(reason) => format!("The bot browser could not start kwant's Chrome on this computer: {reason}"),
            None => "The bot browser could not start kwant's Chrome on this computer. Restart the browser and try again.".into(),
        }
    }

    pub async fn session(&self, id: &str, workspace: &Path) -> Result<BrowserController, BrowserError> {
        self.open(id, workspace).await
    }

    /// A job's own page ([`job_page_key`]): a new page in its team's browser context, so the
    /// team's sign-ins and cookies are shared, opened in a window of its own in local mode. It
    /// is kept across restarts like a team page. The team page is opened first if needed (its
    /// context is the one shared).
    pub async fn page_session(&self, key: &str, workspace: &Path) -> Result<BrowserController, BrowserError> {
        self.open(key, workspace).await
    }

    async fn open(&self, id: &str, workspace: &Path) -> Result<BrowserController, BrowserError> {
        let result = match self.ensure_private_browser().await {
            Ok(()) => self.open_session(id, workspace).await,
            Err(e) => Err(e),
        };
        *self.last_error.lock().unwrap_or_else(|e| e.into_inner()) = result.as_ref().err().map(|e| match e {
            // the local start's own words, without the CDP prefix
            BrowserError::Http(reason) => reason.clone(),
            other => other.to_string(),
        });
        *self.last_outage.lock().unwrap_or_else(|e| e.into_inner()) = result.as_ref().err().map(outage);
        result
    }

    /// How the last attempt to open a page failed, if it did (see [`Outage`]).
    pub fn last_outage(&self) -> Option<Outage> {
        *self.last_outage.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// Whether the browser answers, without opening a page: connects first if needed (in VM mode
    /// that starts its container, as before). The panel's status uses it.
    /// A browser that takes longer than [`PING_WAIT`] is reported busy, so a status poll never
    /// waits out a whole command timeout.
    pub async fn ping(&self) -> Result<(), BrowserError> {
        // starting the container (Docker mode) isn't cut short; only the browser's answer is
        self.ensure_private_browser().await?;
        let result = match timeout(PING_WAIT, async {
            let mut lock = self.state.lock().await;
            if lock.is_none() { *lock = Some(self.connect().await?); }
            let result = lock.as_ref().unwrap().browser.send_cdp_command("Browser.getVersion", json!({})).await;
            if result.is_err() { *lock = None; }
            result.map(|_| ())
        }).await {
            Ok(result) => result,
            Err(_) => Err(BrowserError::Timeout),
        };
        if let Err(error) = &result {
            *self.last_outage.lock().unwrap_or_else(|e| e.into_inner()) = Some(outage(error));
        }
        result
    }

    /// Whether this page (team or job page) is open, or kept from an earlier run, as far as
    /// this kwant knows. Opens nothing.
    pub async fn has_page(&self, key: &str) -> bool {
        if let Some(state) = self.state.lock().await.as_ref() {
            return state.sessions.contains_key(key);
        }
        tokio::fs::read(self.sessions_file()).await.ok()
            .and_then(|bytes| serde_json::from_slice::<HashMap<String, SessionTarget>>(&bytes).ok())
            .is_some_and(|sessions| sessions.contains_key(key))
    }

    /// VM mode: a controller for a page that is already open, never creating one (the idle sweep
    /// rests pages no bot has a controller for this run). `None` when it isn't open, the browser
    /// isn't connected, or in local mode.
    pub async fn existing_page(&self, key: &str) -> Option<BrowserController> {
        if self.mode() == ComputerMode::Local { return None; }
        let lock = self.state.lock().await;
        let state = lock.as_ref()?;
        let session = state.sessions.get(key)?;
        let ctrl = BrowserController::at_endpoint(&state.endpoint, Some(session.target.clone()), false);
        ctrl.set_cookie_jar(Some(self.cookie_jar(page_team(key))));
        ctrl.wake_before_use();
        Some(ctrl)
    }

    /// Every open page (team and job pages) with when it was last used. A page kept from an
    /// earlier run that this run hasn't used counts from when it was first seen here.
    pub async fn open_pages(&self) -> Vec<(String, std::time::Instant)> {
        let keys: Vec<String> = match self.state.lock().await.as_ref() {
            Some(state) => state.sessions.keys().cloned().collect(),
            None => return Vec::new(),
        };
        let now = std::time::Instant::now();
        let mut use_ = self.page_use.lock().unwrap_or_else(|e| e.into_inner());
        let mut pages: Vec<_> = keys.into_iter().map(|k| { let at = *use_.entry(k.clone()).or_insert(now); (k, at) }).collect();
        pages.sort_by_key(|(_, at)| *at);
        pages
    }

    /// [`Self::open_pages`] whose page is still there in the browser (31b): after the container
    /// restarts, pages kept from before stay listed until reused or closed, and must not count
    /// toward the browser's process budget. Every open page when the browser can't be asked.
    pub async fn live_pages(&self) -> Vec<(String, std::time::Instant)> {
        let alive: Option<std::collections::HashSet<String>> = {
            let lock = self.state.lock().await;
            let Some(state) = lock.as_ref() else { return Vec::new() };
            match state.browser.send_cdp_command("Target.getTargets", json!({})).await {
                Ok(targets) => {
                    let live: std::collections::HashSet<&str> = targets["targetInfos"].as_array().into_iter().flatten()
                        .filter_map(|t| t["targetId"].as_str()).collect();
                    Some(state.sessions.iter().filter(|(_, s)| live.contains(s.target.as_str())).map(|(k, _)| k.clone()).collect())
                }
                Err(_) => None,
            }
        };
        let pages = self.open_pages().await;
        match alive {
            Some(alive) => pages.into_iter().filter(|(k, _)| alive.contains(k)).collect(),
            None => pages,
        }
    }

    /// Records that the idle sweep put a page to rest.
    pub fn mark_rested(&self, key: &str, rest: Rest) {
        self.rested.lock().unwrap_or_else(|e| e.into_inner()).insert(key.to_string(), rest);
    }

    /// How the page was put to rest, if it was and hasn't been used since.
    pub fn rest_of(&self, key: &str) -> Option<Rest> {
        self.rested.lock().unwrap_or_else(|e| e.into_inner()).get(key).copied()
    }

    async fn open_session(&self, id: &str, workspace: &Path) -> Result<BrowserController, BrowserError> {
        let mut lock = self.state.lock().await;
        if lock.is_none() { *lock = Some(self.connect().await?); }
        let mut targets = lock.as_ref().unwrap().browser.send_cdp_command("Target.getTargets", json!({})).await;
        if targets.is_err() && self.mode() == ComputerMode::Local {
            // Chrome quit, or the person closed its window once done there: start it again in
            // this same call, back in the app
            self.local_window.store(false, std::sync::atomic::Ordering::SeqCst);
            *lock = None;
            *lock = Some(self.connect().await?);
            targets = lock.as_ref().unwrap().browser.send_cdp_command("Target.getTargets", json!({})).await;
        }
        let state = lock.as_mut().unwrap();
        let targets = match targets {
            Ok(targets) => targets,
            Err(error) => { *lock = None; return Err(error); }
        };
        let existing = state.sessions.get(id).filter(|session| targets["targetInfos"].as_array()
            .is_some_and(|targets| targets.iter().any(|target| target["targetId"] == session.target)));
        let reused = existing.is_some();
        let local = self.mode() == ComputerMode::Local;
        let alive = |target: &str| targets["targetInfos"].as_array()
            .is_some_and(|targets| targets.iter().any(|t| t["targetId"] == target));
        let team = page_team(id);
        let job = is_job_page(id);
        let mut fresh_context = existing.is_none() && !local;
        let session = if let Some(existing) = existing { existing.clone() } else if local {
            // Local pages share the kwant profile's default context, so a sign-in in the window
            // is kept. (`context` stays empty.) Each bot gets its own window, not a tab: Chrome
            // only paints the front tab of a window, so a background tab's screenshot never comes.
            let target = state.browser.send_cdp_command("Target.createTarget", json!({"url": "about:blank", "newWindow": true})).await?;
            SessionTarget { context: String::new(), target: target["targetId"].as_str()
                .ok_or_else(|| BrowserError::Protocol("Browser page missing".into()))?.to_string() }
        } else if job {
            // A job page: a new page in the team's context (the team page's), never a context of
            // its own, so a sign-in made on any page of the team holds on all of them. In a window
            // of its own, as in local mode: a second tab would leave the page behind it unpainted,
            // and its screenshots (so every navigation) would hang until the 15 s timeout.
            let team_session = state.sessions.get(team).filter(|s| alive(&s.target)).cloned();
            let context = match team_session {
                Some(team_session) => { fresh_context = false; team_session.context }
                None => {
                    let team_session = Self::new_context_page(&state.browser).await?;
                    state.sessions.insert(team.to_string(), team_session.clone());
                    team_session.context
                }
            };
            let target = state.browser.send_cdp_command("Target.createTarget", json!({
                "url": "about:blank", "browserContextId": context, "newWindow": true
            })).await?;
            SessionTarget { context, target: target["targetId"].as_str()
                .ok_or_else(|| BrowserError::Protocol("Browser page missing".into()))?.to_string() }
        } else {
            Self::new_context_page(&state.browser).await?
        };
        state.sessions.insert(id.to_string(), session.clone());
        self.save_sessions(&state.sessions).await?;
        // Reuse the same session's controller, not a fresh one, so its `downloads` connection (a
        // dedicated background task; see `configure_downloads` below) stays the one the whole
        // session's downloads and file choosers are tracked on. A fresh controller here would
        // get a fresh, empty `downloads`, so every call would start its own blank-state download
        // center and never see what an earlier call's center already observed.
        let cached = reused.then(|| state.controllers.get(id).cloned()).flatten();
        let ctrl = match cached {
            Some(ctrl) => ctrl,
            None => {
                let ctrl = BrowserController::at_endpoint(&state.endpoint, Some(session.target.clone()), false);
                state.controllers.insert(id.to_string(), ctrl.clone());
                ctrl
            }
        };
        if !local {
            // The VM browser's profile is on tmpfs, so its contexts' cookies go when the
            // container restarts: keep them per team in the data folder (local mode's on-disk
            // profile already keeps them). A job page shares its team's context, so its jar.
            ctrl.set_cookie_jar(Some(self.cookie_jar(team)));
            if fresh_context {
                let restored = ctrl.restore_cookies().await;
                if restored > 0 { tracing::debug!("Restored {} browser cookies for {}", restored, id); }
            }
        }
        // The page may have been frozen by the idle sweep through another controller, or by an
        // earlier run of kwant: wake it before anything else is sent (a no-op for an awake page)
        if !local { ctrl.wake_before_use(); }
        // A real window keeps its own size; a windowless browser gets the viewer's fixed viewport.
        if !local || !self.local_window() {
            ctrl.set_viewport(1280, 800).await?;
        }
        ctrl.refresh_location().await?;
        // Next to #578's attachments root/chooser-tmp: one folder shared by every session's
        // download staging, outside any bot's workspace (see `browser_downloads.rs`'s doc).
        let download_staging = self.root.join("attachments").join("download-tmp");
        let context_id = (!session.context.is_empty()).then_some(session.context.clone());
        let home = download_home(local, self.endpoint.is_some(), &self.root);
        ctrl.configure_downloads(workspace.to_path_buf(), home, context_id, download_staging).await;
        Ok(ctrl)
    }

    /// A new browser context (VM mode) with one blank page in it.
    async fn new_context_page(browser: &BrowserController) -> Result<SessionTarget, BrowserError> {
        {
            // Do not dispose on detach: contexts survive a Kwnt server restart.
            let context = browser.send_cdp_command("Target.createBrowserContext", json!({"disposeOnDetach": false})).await?;
            let context = context["browserContextId"].as_str()
                .ok_or_else(|| BrowserError::Protocol("Browser context missing".into()))?.to_string();
            let target = browser.send_cdp_command("Target.createTarget", json!({
                "url": "about:blank", "browserContextId": context
            })).await;
            let target = match target {
                Ok(target) => target,
                Err(error) => {
                    let _ = browser.send_cdp_command("Target.disposeBrowserContext", json!({"browserContextId": context})).await;
                    return Err(error);
                }
            };
            Ok(SessionTarget { context, target: target["targetId"].as_str()
                .ok_or_else(|| BrowserError::Protocol("Browser page missing".into()))?.to_string() })
        }
    }

    /// Records that a page was used now (see `page_use`).
    pub fn touch_page(&self, key: &str) {
        self.page_use.lock().unwrap_or_else(|e| e.into_inner()).insert(key.to_string(), std::time::Instant::now());
        // its controller wakes it before the first command
        self.rested.lock().unwrap_or_else(|e| e.into_inner()).remove(key);
    }

    /// Forgets a job page's use when it couldn't open (no room, or the browser failed), so it
    /// isn't counted as one of its team's pages.
    pub fn forget_page(&self, key: &str) {
        if is_job_page(key) {
            self.page_use.lock().unwrap_or_else(|e| e.into_inner()).remove(key);
            self.pages_seen.forget(key);
        }
    }

    /// 29d: each picked page's last seen address, shared with the live views that record it.
    pub fn pages_seen(&self) -> PagesSeen {
        self.pages_seen.clone()
    }

    /// When a page was last used in this run, if it was.
    pub fn page_used_at(&self, key: &str) -> Option<std::time::Instant> {
        self.page_use.lock().unwrap_or_else(|e| e.into_inner()).get(key).copied()
    }

    /// The team's job pages that are open (or kept from an earlier run), each with when it was
    /// last used, oldest first. A kept page this run hasn't used yet counts as used now.
    pub async fn job_pages(&self, team: &str) -> Vec<(String, std::time::Instant)> {
        let prefix = format!("{team}{PAGE_SEP}");
        let mut keys: Vec<String> = match self.state.lock().await.as_ref() {
            Some(state) => state.sessions.keys().filter(|k| k.starts_with(&prefix)).cloned().collect(),
            None => Vec::new(),
        };
        let mut use_ = self.page_use.lock().unwrap_or_else(|e| e.into_inner());
        keys.extend(use_.keys().filter(|k| k.starts_with(&prefix)).cloned());
        keys.sort();
        keys.dedup();
        let now = std::time::Instant::now();
        let mut pages: Vec<(String, std::time::Instant)> = keys.into_iter()
            .map(|k| { let at = *use_.entry(k.clone()).or_insert(now); (k, at) }).collect();
        pages.sort_by_key(|(_, at)| *at);
        pages
    }

    /// Every page this run knows of (team and job pages), with when it was last used.
    pub fn pages_in_use(&self) -> Vec<(String, std::time::Instant)> {
        self.page_use.lock().unwrap_or_else(|e| e.into_inner()).iter().map(|(k, at)| (k.clone(), *at)).collect()
    }

    /// Closes a job's page. Its team's context and sign-ins stay; the next call from that job
    /// opens a new page.
    pub async fn close_page(&self, key: &str) -> Result<(), BrowserError> {
        if !is_job_page(key) { return Ok(()); }
        self.page_use.lock().unwrap_or_else(|e| e.into_inner()).remove(key);
        self.rested.lock().unwrap_or_else(|e| e.into_inner()).remove(key);
        self.pages_seen.forget(key);
        let mut lock = self.state.lock().await;
        if let Some(state) = lock.as_mut() {
            // Drop this page's own cached controller too (#753): otherwise its downloads/site
            // guard/popups connections to the browser outlive the page they were opened for,
            // even though `Target.closeTarget` below ends the page itself.
            state.controllers.remove(key);
            if let Some(session) = state.sessions.remove(key) {
                let _ = state.browser.send_cdp_command("Target.closeTarget", json!({"targetId": session.target})).await;
                self.save_sessions(&state.sessions).await?;
            }
        }
        Ok(())
    }

    /// Drops a page's cached controller without closing its page or context (#753): the next use
    /// reconnects lazily in [`Self::open_session`]. For a page that stays open but has been idle,
    /// freeing its DevTools connections (and the download/site-guard/popups tasks that hold them)
    /// without losing the session, its sign-ins, or its place in the page.
    pub async fn drop_connection(&self, key: &str) -> bool {
        match self.state.lock().await.as_mut() {
            Some(state) => state.controllers.remove(key).is_some(),
            None => false,
        }
    }

    /// Where a bot's VM-browser cookies are kept between container restarts.
    pub fn cookie_jar(&self, id: &str) -> PathBuf {
        let name: String = id.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).take(120).collect();
        self.root.join("browser-cookies").join(format!("{name}.json"))
    }

    pub async fn reset(&self, id: &str) -> Result<(), BrowserError> {
        // a job page shares its team's context: resetting it only closes it
        if is_job_page(id) { return self.close_page(id).await; }
        // A reset is a clean slate, including the saved sign-ins
        let _ = std::fs::remove_file(self.cookie_jar(id));
        let prefix = format!("{id}{PAGE_SEP}");
        self.page_use.lock().unwrap_or_else(|e| e.into_inner()).retain(|k, _| !k.starts_with(&prefix));
        self.rested.lock().unwrap_or_else(|e| e.into_inner()).retain(|k, _| k != id && !k.starts_with(&prefix));
        self.pages_seen.forget_team(id);
        let mut lock = self.state.lock().await;
        if lock.is_none() && self.sessions_file().exists() {
            *lock = Some(self.connect().await?);
        }
        if let Some(state) = lock.as_mut() {
            // Its own and its job pages' cached controllers go with the context (#753): their
            // downloads/site-guard/popups tasks would otherwise outlive the disposed context.
            state.controllers.remove(id);
            state.controllers.retain(|k, _| !k.starts_with(&prefix));
            if let Some(session) = state.sessions.remove(id) {
                if session.context.is_empty() {
                    // a local tab in the shared profile: close just that tab
                    let _ = state.browser.send_cdp_command("Target.closeTarget", json!({"targetId": session.target})).await;
                } else {
                    state.browser.send_cdp_command("Target.disposeBrowserContext", json!({"browserContextId": session.context})).await?;
                }
            }
            // the team's job pages go with it (in the VM they were in the context just disposed)
            let jobs: Vec<String> = state.sessions.keys().filter(|k| k.starts_with(&prefix)).cloned().collect();
            for key in jobs {
                if let Some(session) = state.sessions.remove(&key) {
                    let _ = state.browser.send_cdp_command("Target.closeTarget", json!({"targetId": session.target})).await;
                }
            }
            self.save_sessions(&state.sessions).await?;
        }
        Ok(())
    }
}

/// Labels on every browser container kwant starts: what it is, and whose data folder it serves.
pub const LABEL_BROWSER: &str = "kwnt.browser";
pub const LABEL_ROOT: &str = "kwnt.root";
/// The proxy the container was made for (credential-free URL and extra bypass), empty without one.
pub const LABEL_PROXY: &str = "kwnt.browser.proxy";
/// Touched in the data folder whenever a bot uses the browser; its age is the container's idle time.
pub const LAST_USE_FILE: &str = "browser-last-used";
/// A browser container nobody has used for this long is stopped (`KWNT_BROWSER_IDLE_MINUTES`).
pub const DEFAULT_IDLE_MINUTES: u64 = 30;
/// How often a running kwant looks for leftover browser containers.
pub const REAP_EVERY: Duration = Duration::from_secs(10 * 60);

/// The idle limit: `KWNT_BROWSER_IDLE_MINUTES` (at least 1), else [`DEFAULT_IDLE_MINUTES`].
pub fn idle_limit() -> Duration {
    let minutes = std::env::var("KWNT_BROWSER_IDLE_MINUTES").ok()
        .and_then(|v| v.trim().parse::<u64>().ok()).filter(|m| *m > 0).unwrap_or(DEFAULT_IDLE_MINUTES);
    Duration::from_secs(minutes * 60)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReapAction { Keep, Stop, Remove }

/// What the reaper does with one labelled browser container. Its data folder gone: remove it,
/// running or not, since no kwant can use it again. Running and unused for `limit`, or with no
/// record of use: stop it; kwant starts it again on the next browser request. Otherwise keep it.
pub fn reap_action(running: bool, root_gone: bool, idle_for: Option<Duration>, limit: Duration) -> ReapAction {
    if root_gone { return ReapAction::Remove; }
    if running && idle_for.is_none_or(|d| d >= limit) { return ReapAction::Stop; }
    ReapAction::Keep
}

/// The `docker run` arguments for the browser container of the kwant whose data folder is
/// `root`. It never restarts on its own (kwant starts it on demand), and it carries labels so a
/// later kwant can find it, stop it when idle and remove it once its data folder is gone.
pub fn managed_run_args(name: &str, root: &Path, proxy: Option<&BrowserProxy>) -> Vec<String> {
    let root = std::fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
    let mut args: Vec<String> = [
        "run", "-d", "--name", name, "--restart", "no",
        "--label", &format!("{LABEL_BROWSER}=1"), "--label", &format!("{LABEL_ROOT}={}", root.display()),
        "--init", "--cap-drop=ALL", "--security-opt=no-new-privileges", "--memory=1536m",
        "--cpus=2", "--pids-limit=512", "--read-only", "--tmpfs", "/tmp:rw,nosuid,size=512m",
        "-p", "127.0.0.1::9222",
    ].iter().map(|a| a.to_string()).collect();
    if let Some(p) = proxy {
        // the URL carries no credentials ([`BrowserProxy::parse`] refuses them)
        args.extend([
            "--label".into(), format!("{LABEL_PROXY}={}|{}", p.url, p.bypass.join(";")),
            "-e".into(), format!("{ENV_PROXY}={}", p.url),
            "-e".into(), format!("{ENV_BYPASS}={}", p.bypass.join(";")),
        ]);
    }
    args.push(BROWSER_IMAGE.to_string());
    args
}

/// Where a session's browser keeps its downloads: Chrome on this computer, kwant's own browser
/// container (vm mode with no `KWNT_BROWSER_CDP_URL`), or a browser on another computer that
/// kwant only reaches over DevTools.
pub fn download_home(local: bool, external_endpoint: bool, root: &Path) -> DownloadHome {
    if local {
        DownloadHome::Local
    } else if external_endpoint {
        DownloadHome::Elsewhere
    } else {
        DownloadHome::Container(managed_container_name(root))
    }
}

/// The VM browser container of the kwant whose data folder is `root`: one name per installation
/// avoids collisions between local kwant instances.
pub fn managed_container_name(root: &Path) -> String {
    use std::hash::{Hash, Hasher};
    let mut hash = std::collections::hash_map::DefaultHasher::new();
    root.hash(&mut hash);
    format!("kwnt-browser-{:016x}", hash.finish())
}

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

    const LIMIT: Duration = Duration::from_secs(30 * 60);
    const MIN: Duration = Duration::from_secs(60);

    // 20g: only a browser kwant runs itself in Docker gets its downloads copied out; a browser
    // the person pointed kwant at elsewhere keeps refusing, and local mode wins over both.
    #[test]
    fn downloads_come_home_from_the_managed_container_only() {
        let root = Path::new("/srv/kwnt-data");
        assert_eq!(download_home(true, false, root), DownloadHome::Local);
        assert_eq!(download_home(true, true, root), DownloadHome::Local);
        assert_eq!(download_home(false, true, root), DownloadHome::Elsewhere);
        assert_eq!(download_home(false, false, root), DownloadHome::Container(managed_container_name(root)));
    }

    #[test]
    fn a_container_whose_data_folder_is_gone_is_removed_running_or_not() {
        for running in [true, false] {
            for idle in [None, Some(MIN), Some(LIMIT * 2)] {
                assert_eq!(reap_action(running, true, idle, LIMIT), ReapAction::Remove);
            }
        }
    }

    #[test]
    fn a_running_container_is_stopped_only_once_idle_past_the_limit() {
        assert_eq!(reap_action(true, false, Some(MIN), LIMIT), ReapAction::Keep);
        assert_eq!(reap_action(true, false, Some(LIMIT - MIN), LIMIT), ReapAction::Keep);
        assert_eq!(reap_action(true, false, Some(LIMIT), LIMIT), ReapAction::Stop);
        assert_eq!(reap_action(true, false, Some(LIMIT * 10), LIMIT), ReapAction::Stop);
        // never used since kwant started tracking it: nothing is waiting on it
        assert_eq!(reap_action(true, false, None, LIMIT), ReapAction::Stop);
    }

    #[test]
    fn a_stopped_container_with_its_folder_is_left_for_kwant_to_start_again() {
        for idle in [None, Some(MIN), Some(LIMIT * 10)] {
            assert_eq!(reap_action(false, false, idle, LIMIT), ReapAction::Keep);
        }
    }

    #[test]
    fn a_proxy_reaches_the_container_as_env_and_label_and_no_proxy_adds_nothing() {
        let none = managed_run_args("n", Path::new("."), None);
        assert!(!none.iter().any(|a| a.contains("PROXY") || a.contains("kwnt.browser.proxy")), "{none:?}");
        let proxy = BrowserProxy::parse("socks5://172.17.0.1:1080", "example.com").unwrap().unwrap();
        let args = managed_run_args("n", Path::new("."), Some(&proxy));
        let pairs: Vec<(&str, &str)> = args.windows(2).map(|w| (w[0].as_str(), w[1].as_str())).collect();
        assert!(pairs.contains(&("-e", "KWNT_BROWSER_PROXY=socks5://172.17.0.1:1080")), "{args:?}");
        assert!(pairs.contains(&("-e", "KWNT_BROWSER_PROXY_BYPASS=example.com")), "{args:?}");
        assert!(pairs.contains(&("--label", "kwnt.browser.proxy=socks5://172.17.0.1:1080|example.com")), "{args:?}");
        assert_eq!(args.last().map(String::as_str), Some(BROWSER_IMAGE));
    }

    #[test]
    fn the_container_never_restarts_on_its_own_and_carries_its_labels() {
        let tmp = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(tmp.path()).unwrap();
        let args = managed_run_args("kwnt-browser-x", tmp.path(), None);
        let pairs: Vec<(&str, &str)> = args.windows(2).map(|w| (w[0].as_str(), w[1].as_str())).collect();
        assert!(pairs.contains(&("--restart", "no")), "{args:?}");
        assert!(!args.iter().any(|a| a.contains("unless-stopped") || a.contains("always")), "{args:?}");
        assert!(pairs.contains(&("--label", "kwnt.browser=1")), "{args:?}");
        let root_label = format!("kwnt.root={}", root.display());
        assert!(pairs.contains(&("--label", root_label.as_str())), "{args:?}");
        assert!(pairs.contains(&("--name", "kwnt-browser-x")), "{args:?}");
        assert_eq!(args.last().map(String::as_str), Some(BROWSER_IMAGE));
        // the published port stays loopback-only
        assert!(pairs.contains(&("-p", "127.0.0.1::9222")), "{args:?}");
    }

    #[test]
    fn a_relative_data_folder_is_labelled_absolute() {
        let args = managed_run_args("kwnt-browser-x", Path::new("."), None);
        let label = args.iter().find(|a| a.starts_with("kwnt.root=")).unwrap();
        assert!(Path::new(label.trim_start_matches("kwnt.root=")).is_absolute(), "{label}");
    }

    #[test]
    fn use_is_recorded_in_the_data_folder_at_most_once_a_minute() {
        let tmp = tempfile::tempdir().unwrap();
        let service = BrowserService::new(tmp.path().to_path_buf(), None);
        service.note_use();
        let file = tmp.path().join(LAST_USE_FILE);
        let first = std::fs::metadata(&file).unwrap().modified().unwrap();
        std::fs::remove_file(&file).unwrap();
        service.note_use();
        assert!(!file.exists(), "a second use within a minute writes nothing");
        assert!(first <= std::time::SystemTime::now());
    }
}

#[cfg(test)]
mod image_tests {
    use super::{BROWSER_DOCKERFILE, BROWSER_ENTRYPOINT, BROWSER_IMAGE};
    use sha2::{Digest, Sha256};

    /// The browser files `kwnt-browser:v5` was built from. A change to them without a new
    /// [`BROWSER_IMAGE`] would never reach a computer that already has the old tag.
    #[test]
    fn the_browser_image_tag_moves_with_its_files() {
        let mut files = Sha256::new();
        files.update(BROWSER_DOCKERFILE);
        files.update(BROWSER_ENTRYPOINT);
        let hash: String = files.finalize().iter().take(8).map(|b| format!("{b:02x}")).collect();
        assert_eq!(
            (BROWSER_IMAGE, hash.as_str()),
            ("kwnt-browser:v5", "67a48c2dc2d62735"),
            "docker/browser files changed: bump BROWSER_IMAGE, then record the new hash here"
        );
    }
}

#[cfg(test)]
mod outage_reason_tests {
    use super::{BrowserService, ComputerMode, Outage, BROWSER_BUSY};

    #[test]
    fn a_busy_browser_says_retry_and_never_blames_docker() {
        let tmp = tempfile::tempdir().unwrap();
        let service = BrowserService::new(tmp.path().into(), Some("http://127.0.0.1:9".into()));
        // The VM browser, whatever this computer's default is (Windows defaults to local Chrome).
        *service.mode.write().unwrap() = ComputerMode::Vm;
        assert!(service.unavailable_reason().contains("Docker"), "no answer yet: the old text");
        *service.last_outage.lock().unwrap() = Some(Outage::Busy);
        assert_eq!(service.unavailable_reason(), BROWSER_BUSY);
        assert!(!BROWSER_BUSY.contains("Docker"));
        *service.last_outage.lock().unwrap() = Some(Outage::Unreachable);
        assert!(service.unavailable_reason().contains("Docker"));
    }
}