rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! `rho browser install`: installs the pinned chrome-headless-shell, unless
//! `[browser] executable` names another browser, then starts the browser
//! once the way the daemon does, so a problem shows now rather than on the
//! agent's first browser call.

use std::io::{IsTerminal, Write};
use std::time::Instant;

use anyhow::Context as _;
use rho_browser::install::{Platform, Progress, VERSION};
use rho_browser::manager::{Executable, Manager, ManagerError};
use rho_browser::Sandbox;

use super::config_repository::ConfigRepository;
use crate::browser::start;
use crate::cli::{BrowserCommand, Cli};
use crate::daemon::DaemonPaths;

pub(super) async fn run(command: &BrowserCommand, cli: &Cli) -> anyhow::Result<()> {
    match command {
        BrowserCommand::Install => install(cli).await,
    }
}

async fn install(cli: &Cli) -> anyhow::Result<()> {
    let config = ConfigRepository::new(cli.config.clone()).load()?;
    let paths = DaemonPaths::of_this_process()?;
    paths.prepare_runtime_dir()?;
    let client = start::download_client().context("could not set up downloads")?;
    let executable = start::executable(&config.browser, &paths.home, client);
    let failed = |error: ManagerError| anyhow::anyhow!(start::failure_text(&error));
    match &executable {
        Executable::Path(path) => {
            println!("checking {} from `[browser] executable`", path.display());
        }
        Executable::Pinned { install, client } => {
            let platform = Platform::current()
                .ok_or(ManagerError::UnsupportedPlatform)
                .map_err(failed)?;
            let mut meter = Meter::new();
            let installed = install
                .ensure(platform, client, |progress| meter.show(progress))
                .await;
            meter.finish();
            let executable = installed.map_err(|error| failed(error.into()))?;
            println!(
                "chrome-headless-shell {VERSION} is installed at {}",
                executable.display()
            );
        }
    }
    // After the download, which uses rho's own proxy support, so a proxy
    // only the browser cannot use still lets it finish.
    let options = start::manager_options(&config.browser, &paths.runtime_dir, executable)
        .map_err(anyhow::Error::msg)?;
    match options.sandbox {
        Sandbox::Enabled => {}
        Sandbox::Disabled => {
            eprintln!("warning: `[browser] sandbox = false` runs pages without Chrome's sandbox");
        }
    }
    let manager = Manager::<()>::new(options);
    let started = Instant::now();
    let context = manager.context(&()).await.map_err(failed)?;
    let elapsed = started.elapsed();
    drop(context);
    manager.close().await;
    println!("the browser starts here ({} ms)", elapsed.as_millis());
    Ok(())
}

/// Shows a download's progress on stderr: a live percentage on a terminal,
/// otherwise one line when it starts.
struct Meter {
    live: bool,
    started: bool,
    shown: Option<u64>,
}

impl Meter {
    fn new() -> Self {
        Self {
            live: std::io::stderr().is_terminal(),
            started: false,
            shown: None,
        }
    }

    fn show(&mut self, progress: Progress) {
        if !self.started {
            self.started = true;
            eprintln!(
                "downloading chrome-headless-shell {VERSION} ({} MB)",
                progress.total.div_ceil(1_000_000)
            );
        }
        let percent = (progress.downloaded * 100)
            .checked_div(progress.total)
            .unwrap_or(100);
        if self.live && self.shown != Some(percent) {
            self.shown = Some(percent);
            let mut stderr = std::io::stderr();
            let _ = write!(stderr, "\r{percent}%");
            let _ = stderr.flush();
        }
    }

    fn finish(&self) {
        if self.live && self.shown.is_some() {
            eprintln!();
        }
    }
}