rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! A person driving a real chrome-headless-shell. Set
//! `RHO_BROWSER_EXECUTABLE` to one and run with `--include-ignored`.

use super::super::tabs::SessionTabs;
use crate::browser::config::BrowserConfig;
use crate::browser::drive::PersonTabs;
use crate::browser::view::{BrowserState, BrowserView, Driver};
use crate::browser::{Browsers, SessionBrowser, VIEWPORT};
use pretty_assertions::assert_eq;
use rho_browser::cdp::runtime::Evaluate;
use rho_browser::screencast::Fit;
use rho_browser::tab::Viewport;
use rho_protocol::{
    BrowserDestination, BrowserInput, BrowserKeyAction, BrowserModifiers, BrowserMouseAction,
    BrowserMouseButton, BrowserTabAction, ConnectionId,
};
use rho_sdk::SessionId;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};

/// Bounds each wait on the browser; never the way the test syncs.
const BUDGET: Duration = Duration::from_secs(10);

/// A link that opens a popup across the page's top left, and a field.
const PAGE: &str = r#"<title>drive</title>
<a href="/popup" target="_blank" style="position:absolute;left:0;top:0;width:400px;height:200px">open</a>
<input id="field" style="position:absolute;left:500px;top:20px;width:200px;height:30px">"#;

/// Serves [`PAGE`] at every path.
async fn serve() -> std::net::SocketAddr {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let address = listener.local_addr().unwrap();
    tokio::spawn(async move {
        while let Ok((mut stream, _)) = listener.accept().await {
            tokio::spawn(async move {
                let mut request = vec![0; 4096];
                let _ = stream.read(&mut request).await;
                let response = format!(
                    "HTTP/1.1 200 OK\r\ncontent-type: text/html\r\ncontent-length: {}\r\n\r\n{PAGE}",
                    PAGE.len()
                );
                let _ = stream.write_all(response.as_bytes()).await;
            });
        }
    });
    address
}

/// A click at `(x, y)` as a client sends one: the pointer moves there,
/// then the button goes down and up.
fn click(x: f64, y: f64) -> [BrowserInput; 3] {
    let mouse = |action, button, clicks| BrowserInput::Mouse {
        action,
        x,
        y,
        button,
        clicks,
        modifiers: BrowserModifiers::NONE,
    };
    let left = Some(BrowserMouseButton::Left);
    [
        mouse(BrowserMouseAction::Moved, None, 0),
        mouse(BrowserMouseAction::Pressed, left, 1),
        mouse(BrowserMouseAction::Released, left, 1),
    ]
}

fn key(action: BrowserKeyAction, text: Option<&str>) -> BrowserInput {
    BrowserInput::Key {
        action,
        key: "h".into(),
        code: Some("KeyH".into()),
        text: text.map(str::to_owned),
        modifiers: BrowserModifiers::NONE,
    }
}

async fn until(
    view: &mut tokio::sync::watch::Receiver<BrowserView>,
    what: &str,
    done: impl FnMut(&BrowserView) -> bool,
) {
    tokio::time::timeout(BUDGET, view.wait_for(done))
        .await
        .unwrap_or_else(|_| panic!("{what}"))
        .unwrap();
}

// Covers: a person who took a session's browser over opens a tab, loads a
// page in it, clicks and types into it, and a popup their click opens
// joins the session's tabs, all in the tabs the agent uses; an agent's call
// meanwhile waits, and goes on once the person's connection leaves, seeing
// what the person typed and learning a person drove. Without it, a
// person's driving would act on tabs the agent never sees, or under the
// agent's hands.
// Owner: person driving the session's tabs
#[tokio::test]
#[ignore = "needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE"]
async fn a_person_drives_the_tabs_the_agent_uses_while_it_waits() {
    let executable = std::env::var_os("RHO_BROWSER_EXECUTABLE")
        .expect("needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE");
    let home = tempfile::tempdir().unwrap();
    let config = BrowserConfig {
        executable: Some(executable.into()),
        ..BrowserConfig::default()
    };
    let browsers = Browsers::for_daemon(
        home.path(),
        Box::new(move || Box::pin(std::future::ready(config.clone()))),
    )
    .unwrap();
    let browser = Browsers::session(Some(&browsers), &SessionId::new()).unwrap();
    let tabs = Arc::new(SessionTabs::new(browser.clone()));
    let person: Arc<dyn PersonTabs> = tabs.clone();
    browser.drive_with(Arc::downgrade(&person));
    let mut view = browser.view();
    let page = format!("http://{}/", serve().await);
    let connection = ConnectionId::new(1);

    browser.control(Driver::Person, connection);
    let opened = browser.person_tab(BrowserTabAction::New).await.unwrap();
    browser
        .person_navigate(
            "tab-1".into(),
            BrowserDestination::Url { url: page.clone() },
        )
        .await
        .unwrap();
    until(&mut view, "the page should load", |view| {
        view.tabs
            .first()
            .is_some_and(|tab| tab.url == page && !tab.loading)
    })
    .await;
    let typing = click(600.0, 35.0).into_iter().chain([
        key(BrowserKeyAction::Down, Some("h")),
        key(BrowserKeyAction::Up, None),
        BrowserInput::Text { text: "i!".into() },
    ]);
    for input in typing {
        browser.person_input("tab-1".into(), input).await.unwrap();
    }
    let agent = tokio::spawn({
        let tabs = Arc::clone(&tabs);
        async move {
            let mut held = tabs.hold().await.unwrap();
            let typed = held
                .tabs
                .get(Some("tab-1"))
                .unwrap()
                .call(&Evaluate {
                    expression: "document.getElementById('field').value".into(),
                    context_id: None,
                    return_by_value: true,
                    await_promise: false,
                    timeout: None,
                })
                .await
                .unwrap()
                .result
                .value;
            (held.person_drove, typed)
        }
    });
    for input in click(100.0, 100.0) {
        browser.person_input("tab-1".into(), input).await.unwrap();
    }
    until(&mut view, "the popup should join the tabs", |view| {
        view.tabs.len() == 2
    })
    .await;
    let waited = !agent.is_finished();
    browser.connection_left(connection);
    let (person_drove, typed) = tokio::time::timeout(BUDGET, agent)
        .await
        .expect("the agent's call should go on")
        .unwrap();

    let ids: Vec<_> = view
        .borrow()
        .tabs
        .iter()
        .map(|tab| tab.id.clone())
        .collect();
    assert_eq!(
        (opened, ids, waited, person_drove, typed, browser.driver()),
        (
            Some("tab-1".to_owned()),
            vec!["tab-1".to_owned(), "tab-2".to_owned()],
            true,
            true,
            Some(serde_json::json!("hi!")),
            Driver::Agent,
        )
    );
    browsers.close().await;
}

/// Takes `browser` over for the person at `connection`, opens a tab and
/// loads `page` in it, then hands the browser back, answering the state
/// right after the take-over.
async fn take_over_and_load(
    browser: &SessionBrowser,
    view: &mut tokio::sync::watch::Receiver<BrowserView>,
    connection: ConnectionId,
    page: &str,
) -> BrowserState {
    browser.take_over(connection, None).await.unwrap();
    let taken = view.borrow().state;
    let opened = browser
        .person_tab(BrowserTabAction::New)
        .await
        .unwrap()
        .expect("a new tab has an id");
    browser
        .person_navigate(opened.clone(), BrowserDestination::Url { url: page.into() })
        .await
        .unwrap();
    until(view, "the page should load", |view| {
        view.tabs
            .iter()
            .any(|tab| tab.id == opened && tab.url == page && !tab.loading)
    })
    .await;
    browser.control(Driver::Agent, connection);
    taken
}

// Covers: a person who takes over a session's browser that is not running,
// as one that never started, went unused and unloaded, or crashed, starts
// it, and then opens a tab and loads a page in it, which the session's view
// shows. Otherwise a person could drive a browser only once the agent had
// started one.
// Owner: person driving the session's tabs
#[tokio::test]
#[ignore = "needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE"]
async fn taking_over_a_browser_that_is_not_running_starts_it() {
    let executable = std::env::var_os("RHO_BROWSER_EXECUTABLE")
        .expect("needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE");
    let home = tempfile::tempdir().unwrap();
    let browsers = Browsers::for_tests(
        home.path(),
        BrowserConfig {
            executable: Some(executable.into()),
            unload_idle_after: Some(Duration::from_millis(500)),
            ..BrowserConfig::default()
        },
    );
    let browser = Browsers::session(Some(&browsers), &SessionId::new()).unwrap();
    let tabs = Arc::new(SessionTabs::new(browser.clone()));
    let person: Arc<dyn PersonTabs> = tabs.clone();
    browser.drive_with(Arc::downgrade(&person));
    let mut view = browser.view();
    let page = format!("http://{}/", serve().await);
    let connection = ConnectionId::new(1);

    let never_started = view.borrow().state;
    let first = take_over_and_load(&browser, &mut view, connection, &page).await;
    until(&mut view, "the browser should unload", |view| {
        view.state == BrowserState::Unloaded
    })
    .await;
    let after_unload = take_over_and_load(&browser, &mut view, connection, &page).await;
    let context = browser.context().await.unwrap();
    // Answered or not, the browser dies.
    let _ = context
        .connection()
        .call_raw("Browser.crash", serde_json::json!({}))
        .await;
    drop(context);
    until(&mut view, "the browser should crash", |view| {
        view.state == BrowserState::Crashed
    })
    .await;
    let after_crash = take_over_and_load(&browser, &mut view, connection, &page).await;
    browsers.close().await;

    assert_eq!(
        (never_started, first, after_unload, after_crash),
        (
            BrowserState::NotStarted,
            BrowserState::Running,
            BrowserState::Running,
            BrowserState::Running
        )
    );
}

/// The size tab `tab` lays its page out at, as the page sees it.
async fn laid_out_at(tabs: &SessionTabs, tab: &str) -> Viewport {
    let mut held = tabs.hold_now().await.unwrap();
    let size = held
        .tabs
        .get(Some(tab))
        .unwrap()
        .call(&Evaluate {
            expression: "[innerWidth, innerHeight]".into(),
            context_id: None,
            return_by_value: true,
            await_promise: false,
            timeout: None,
        })
        .await
        .unwrap()
        .result
        .value;
    let size: (u32, u32) = serde_json::from_value(size.unwrap()).unwrap();
    Viewport {
        width: size.0,
        height: size.1,
    }
}

// Covers: a person who takes over a browser that is not running, naming
// the size they view it at, gets tabs that open and lay out at that size,
// and a watch starts at it; a resize while they drive lays the tabs out
// again; and once they hand back, the agent's next call finds its tabs at
// the agent's size. Otherwise the panel shows a page shrunk to its width
// with half of it empty, or the agent's screenshots and coordinates come
// at the person's size.
// Owner: person driving the session's tabs
#[tokio::test]
#[ignore = "needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE"]
async fn a_persons_tabs_render_at_their_size_until_the_agent_gets_them_back() {
    let executable = std::env::var_os("RHO_BROWSER_EXECUTABLE")
        .expect("needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE");
    let home = tempfile::tempdir().unwrap();
    let browsers = Browsers::for_tests(
        home.path(),
        BrowserConfig {
            executable: Some(executable.into()),
            ..BrowserConfig::default()
        },
    );
    let browser = Browsers::session(Some(&browsers), &SessionId::new()).unwrap();
    let tabs = Arc::new(SessionTabs::new(browser.clone()));
    let person: Arc<dyn PersonTabs> = tabs.clone();
    browser.drive_with(Arc::downgrade(&person));
    let connection = ConnectionId::new(1);
    let panel = Viewport {
        width: 400,
        height: 700,
    };
    let wider = Viewport {
        width: 600,
        height: 900,
    };
    let fit = Fit {
        max_width: 800,
        max_height: 900,
    };

    let taken = browser.take_over(connection, Some(panel)).await.unwrap();
    let opened = browser.person_tab(BrowserTabAction::New).await.unwrap();
    let at_take_over = laid_out_at(&tabs, "tab-1").await;
    let (watched, _frames) = browser.watch("tab-1", fit).await.unwrap();
    browser.person_resize(wider).unwrap();
    // The person's next action holds the tabs after the resize's fit.
    let after_resize = laid_out_at(&tabs, "tab-1").await;
    browser.control(Driver::Agent, connection);
    let (person_drove, for_the_agent) = {
        let held = tabs.hold().await.unwrap();
        (held.person_drove, held.tabs.has("tab-1"))
    };
    let after_hand_back = laid_out_at(&tabs, "tab-1").await;
    browsers.close().await;

    assert_eq!(
        (
            taken,
            opened,
            at_take_over,
            watched.viewport,
            after_resize,
            (person_drove, for_the_agent),
            after_hand_back,
            browser.viewport(),
        ),
        (
            panel,
            Some("tab-1".to_owned()),
            panel,
            rho_protocol::BrowserViewport::new(400, 700),
            wider,
            (true, true),
            VIEWPORT,
            VIEWPORT,
        )
    );
}