rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! A session's tabs against a real chrome-headless-shell. Set
//! `RHO_BROWSER_EXECUTABLE` to one and run with
//! `cargo test -p rho-coding-agent --lib tools::browser::tabs -- --ignored`.

use super::*;
use crate::browser::config::BrowserConfig;
use crate::browser::Browsers;
use crate::tools::browser::actions::{self, Act, Pointer, Target};
use pretty_assertions::assert_eq;
use rho_browser::cdp::input::Modifiers;
use rho_sdk::SessionId;
use tokio::io::{AsyncReadExt, AsyncWriteExt};

/// A link that opens a new tab, a plain link, and a button that opens one
/// from script, each 40 pixels high down the left edge.
const OPENERS: &str = r##"<style>a, button { position: absolute; left: 0; width: 200px; height: 40px; }</style>
<a href="/blank" target="_blank" style="top: 0">blank</a>
<a href="/plain" style="top: 50px">plain</a>
<button style="top: 100px" onclick="window.open('/scripted')">scripted</button>"##;

/// Serves [`OPENERS`] at `/` and an empty page anywhere else.
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 read = stream.read(&mut request).await.unwrap_or(0);
                let request = String::from_utf8_lossy(&request[..read]).into_owned();
                let body = match request.split_whitespace().nth(1) {
                    Some("/") => OPENERS,
                    _ => "<title>opened</title>",
                };
                let response = format!(
                    "HTTP/1.1 200 OK\r\ncontent-type: text/html\r\ncontent-length: {}\r\n\r\n{body}",
                    body.len()
                );
                let _ = stream.write_all(response.as_bytes()).await;
            });
        }
    });
    address
}

/// A daemon's browsers, with a session on them, and the URL of
/// [`OPENERS`]. The browsers' home lives as long as the directory.
async fn started() -> (
    tempfile::TempDir,
    std::sync::Arc<Browsers>,
    SessionTabs,
    String,
) {
    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 session = SessionTabs::new(browser);
    let start = format!("http://{}/", serve().await);
    (home, browsers, session, start)
}

/// Waits for the browser to report a tab destroyed, returning its target
/// id.
async fn destroyed(events: &mut rho_browser::EventStream) -> String {
    tokio::time::timeout(std::time::Duration::from_secs(5), async {
        loop {
            let event = events.recv().await.unwrap();
            if event.method == "Target.targetDestroyed" {
                return event.params["targetId"].as_str().unwrap().to_owned();
            }
        }
    })
    .await
    .expect("the tab should close")
}

/// Clicks the current tab at `(100, y)` with `pointer`.
async fn click(tabs: &mut Tabs, pointer: Pointer, y: u32) {
    let act = Act::Point {
        pointer,
        target: Target::Point { x: 100, y },
        modifiers: Modifiers::NONE,
    };
    actions::run(tabs.get(None).unwrap(), &act).await.unwrap();
}

// Covers: a tab a page opens, by a target="_blank" link, a middle click or
// window.open, becomes one of the session's tabs the model can reach, the
// current tab staying current; once the session has TAB_LIMIT tabs, one
// more is closed and reported once rather than left open outside the limit.
// Owner: session tabs, end to end
#[tokio::test]
#[ignore = "needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE"]
async fn tabs_pages_open_are_taken_in_up_to_the_limit() {
    let (_home, browsers, session, start) = started().await;
    let mut held = session.hold().await.unwrap();
    let context = &held.context;
    let tabs = &mut held.tabs;
    tabs.open(context).await.unwrap();
    tabs.get(None).unwrap().load(&start).await.unwrap();

    let mut seen = Vec::new();
    for (pointer, y) in [
        (Pointer::Left, 20),
        (Pointer::Middle, 70),
        (Pointer::Left, 120),
    ] {
        click(tabs, pointer, y).await;
        seen.push(tabs.take_in(context).await);
    }
    seen.push(tabs.take_in(context).await);
    let urls: Vec<_> = tabs
        .lines()
        .await
        .into_iter()
        .map(|line| line.url)
        .collect();
    let current = tabs.current().map(str::to_owned);
    while tabs.open.len() < TAB_LIMIT {
        tabs.open(context).await.unwrap();
    }
    tabs.switch("tab-1").unwrap();
    // Reports each tab the browser closes from now on.
    let connection = context.connection();
    let mut events = connection.events();
    connection
        .call_raw(
            "Target.setDiscoverTargets",
            serde_json::json!({ "discover": true }),
        )
        .await
        .unwrap();
    click(tabs, Pointer::Left, 120).await;
    seen.push(tabs.take_in(context).await);
    // At once, while the browser may still list the tab it is closing: in
    // one of two runs it did. Gone or still going, it is not reported again.
    seen.push(tabs.take_in(context).await);
    let destroyed = destroyed(&mut events).await;
    let known = tabs
        .open
        .iter()
        .any(|open| open.tab.page().target_id().to_string() == destroyed);
    let kept = tabs.open.len();

    let taken = |id: &str| PageTabs {
        taken: vec![id.to_owned()],
        ..PageTabs::default()
    };
    assert_eq!(
        (seen, urls, current, kept, known),
        (
            vec![
                taken("tab-2"),
                taken("tab-3"),
                taken("tab-4"),
                PageTabs::default(),
                PageTabs {
                    refused: 1,
                    ..PageTabs::default()
                },
                PageTabs::default(),
            ],
            vec![
                start.clone(),
                format!("{start}blank"),
                format!("{start}plain"),
                format!("{start}scripted"),
            ],
            Some("tab-1".to_owned()),
            TAB_LIMIT,
            false,
        )
    );
    drop(held);
    browsers.close().await;
}

// Covers: a tab that closes itself, as a popup does with window.close() at
// the end of a sign-in, is forgotten and reported, frees its place under
// TAB_LIMIT, and hands current to the last tab opened if it was current.
// Owner: session tabs, end to end
#[tokio::test]
#[ignore = "needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE"]
async fn tabs_that_close_themselves_are_forgotten() {
    let (_home, browsers, session, start) = started().await;
    let mut held = session.hold().await.unwrap();
    let context = &held.context;
    let tabs = &mut held.tabs;
    tabs.open(context).await.unwrap();
    tabs.get(None).unwrap().load(&start).await.unwrap();
    click(tabs, Pointer::Left, 120).await;
    let taken = tabs.take_in(context).await;
    tabs.switch("tab-2").unwrap();
    let connection = context.connection();
    let mut events = connection.events();
    connection
        .call_raw(
            "Target.setDiscoverTargets",
            serde_json::json!({ "discover": true }),
        )
        .await
        .unwrap();

    // A window a script opened may close itself.
    let popup = tabs.get(Some("tab-2")).unwrap();
    popup
        .tab
        .page()
        .call(&Evaluate {
            expression: "window.close()".into(),
            context_id: None,
            return_by_value: true,
            await_promise: false,
            timeout: None,
        })
        .await
        .unwrap();
    let closed = destroyed(&mut events).await;
    let popup_target = popup.tab.page().target_id().to_string();
    let gone = tabs.take_in(context).await;
    let ids: Vec<_> = tabs.open.iter().map(|open| open.id.clone()).collect();
    let current = tabs.current().map(str::to_owned);

    assert_eq!(
        (taken.taken, closed == popup_target, gone, ids, current),
        (
            vec!["tab-2".to_owned()],
            true,
            PageTabs {
                gone: vec!["tab-2".to_owned()],
                ..PageTabs::default()
            },
            vec!["tab-1".to_owned()],
            Some("tab-1".to_owned()),
        )
    );
    drop(held);
    browsers.close().await;
}

/// How long a call queued behind another gets to wrongly go on while a
/// person drives. Holding the tabs of a running browser took 6 to 11 us
/// over 20 calls (chrome-headless-shell 158, Linux).
const QUEUED_WAIT: std::time::Duration = std::time::Duration::from_millis(100);

// Covers: an agent call learns that a person drove the session's browser
// since the last call that could tell it, whether or not it waited for
// them, even when a call between could not start the browser; and a call
// queued behind another when a person takes over waits out their driving.
// Otherwise the model acts on refs a person invalidated without being
// told, or acts under a person's hands.
// Owner: session tabs
#[tokio::test]
#[ignore = "needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE"]
async fn an_agent_call_waits_out_a_person_and_learns_they_drove() {
    use crate::browser::view::Driver;
    use rho_protocol::ConnectionId;
    use std::sync::Arc;
    let executable = std::env::var_os("RHO_BROWSER_EXECUTABLE")
        .expect("needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE");
    let home = tempfile::tempdir().unwrap();
    // A browser that cannot start until the test fixes its executable.
    let config = Arc::new(std::sync::Mutex::new(BrowserConfig {
        executable: Some(home.path().join("no-browser")),
        ..BrowserConfig::default()
    }));
    let read = Arc::clone(&config);
    let browsers = Browsers::for_daemon(
        home.path(),
        Box::new(move || Box::pin(std::future::ready(read.lock().unwrap().clone()))),
    )
    .unwrap();
    let browser = Browsers::session(Some(&browsers), &SessionId::new()).unwrap();
    let session = Arc::new(SessionTabs::new(browser));
    let person = ConnectionId::new(1);
    // Whether the call was told a person drove, and whether the agent
    // drove when it got the tabs.
    let call = |session: &Arc<SessionTabs>| {
        let session = Arc::clone(session);
        async move {
            let held = session.hold().await.unwrap();
            (held.person_drove, session.browser.agent_drives().is_some())
        }
    };

    session.browser.control(Driver::Person, person);
    session.browser.control(Driver::Agent, person);
    let failed = session.hold().await.is_err();
    config.lock().unwrap().executable = Some(executable.into());
    let after_takeover = call(&session).await;
    let next = call(&session).await;
    let running = session.hold().await.unwrap();
    let mut queued = tokio::spawn(call(&session));
    tokio::task::yield_now().await;
    session.browser.control(Driver::Person, person);
    drop(running);
    let early = tokio::time::timeout(QUEUED_WAIT, &mut queued).await;
    let went_on_early = early.is_ok();
    session.browser.control(Driver::Agent, person);
    let queued = match early {
        Ok(done) => done.unwrap(),
        Err(_) => queued.await.unwrap(),
    };

    assert_eq!(
        (failed, after_takeover, next, went_on_early, queued),
        (true, (true, true), (false, true), false, (true, true))
    );
}

// Covers: a tab shows loading until the last of its overlapping loads
// ends, as when a person navigates again before the first page loaded, or
// the agent navigates while a person's load runs on. Otherwise clients
// show a page as loaded while it still loads.
// Owner: session tabs
#[tokio::test]
#[ignore = "needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE"]
async fn a_tab_shows_loading_until_its_last_load_ends() {
    let (_home, _browsers, session, _) = started().await;
    let mut held = session.hold().await.unwrap();
    held.tabs.open(&held.context).await.unwrap();
    held.show_tabs().await;
    let browser = held.browser.clone();
    let context = held.context.id().clone();
    let loading = || -> Vec<bool> {
        let view = browser.view();
        let tabs = view.borrow().tabs.iter().map(|tab| tab.loading).collect();
        tabs
    };
    let open = held.tabs.get(None).unwrap();
    let first = show_loading(&browser, &context, open, None);
    let second = show_loading(&browser, &context, open, None);
    drop(first);
    let after_first = loading();
    drop(second);
    let after_second = loading();

    assert_eq!((after_first, after_second), (vec![true], vec![false]));
}