rho-coding-agent 3.13.0

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

use super::*;
use crate::browser::config::BrowserConfig;
use crate::browser::view::{shown_tab, BrowserState, BrowserView, ViewTab};
use crate::browser::Browsers;
use crate::permission::{PermissionMode, SessionWriteLog};
use pretty_assertions::assert_eq;
use rho_browser::cdp::target::GetTargetInfo;
use rho_sdk::model::{ContentBlock, ModelIdentity, ModelResponse, ToolCall};
use rho_sdk::provider::{ScriptedProvider, ScriptedTurn};
use rho_sdk::tool::ToolErrorKind;
use rho_sdk::{Rho, RunEvent, SessionId, SessionOptions, ToolCompletion, UserInput, Workspace};
use serde_json::json;
use std::sync::Mutex;
use tokio::io::{AsyncReadExt, AsyncWriteExt};

/// A form whose submit button fills the top left of the viewport.
const FORM: &str = r##"<form action="/submitted"><button style="position: absolute; left: 0; top: 0; width: 200px; height: 100px">send</button></form>"##;

/// Serves [`FORM`] at every path, and records the paths asked for.
async fn serve(paths: Arc<Mutex<Vec<String>>>) -> 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 {
            let paths = Arc::clone(&paths);
            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();
                if let Some(path) = request.split_whitespace().nth(1) {
                    paths.lock().unwrap().push(path.to_owned());
                }
                let response = format!(
                    "HTTP/1.1 200 OK\r\ncontent-type: text/html\r\ncontent-length: {}\r\n\r\n{FORM}",
                    FORM.len()
                );
                let _ = stream.write_all(response.as_bytes()).await;
            });
        }
    });
    address
}

/// Whether, in a session of `mode`, a click on the form's button was
/// refused by the session's policy, and whether the form was submitted.
async fn click_in(mode: PermissionMode) -> (Option<ToolErrorKind>, bool) {
    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));
    let tool = |action| BrowserTool {
        tabs: Arc::clone(&tabs),
        action,
        max_output_bytes: 50_000,
        offer: Arc::default(),
    };
    let paths = Arc::new(Mutex::new(Vec::new()));
    let address = serve(Arc::clone(&paths)).await;
    let call = |id: &str, action: Action, arguments: Value| {
        ScriptedTurn::completed(ModelResponse::Assistant(vec![ContentBlock::ToolCall(
            ToolCall::new(id.into(), action.name().into(), arguments),
        )]))
    };
    let provider = ScriptedProvider::new(
        ModelIdentity::new("scripted", "test", "model"),
        [
            call(
                "navigate",
                Action::Navigate,
                json!({ "url": format!("http://{address}/") }),
            ),
            call(
                "click",
                Action::LeftClick,
                json!({ "target": { "type": "coordinate", "x": 50, "y": 50 } }),
            ),
            ScriptedTurn::completed(ModelResponse::Assistant(vec![ContentBlock::Text(
                "done".into(),
            )])),
        ],
    );
    let policy = mode
        .workspace_policy(SessionWriteLog::default(), None)
        .expect("a checked mode");
    let runtime = Rho::builder()
        .provider(provider)
        .workspace(Workspace::new(home.path()).unwrap())
        .workspace_policy(policy)
        .tool(tool(Action::Navigate))
        .tool(tool(Action::LeftClick))
        .build()
        .unwrap();
    let session = runtime.session(SessionOptions::default()).await.unwrap();
    let mut run = session.start(UserInput::text("submit it")).await.unwrap();
    let mut results = Vec::new();
    while let Some(event) = run.next_event().await {
        if let RunEvent::ToolFinished { result, .. } = event {
            let refused = match result {
                ToolCompletion::Failure(failure) => Some(failure.kind()),
                _ => None,
            };
            results.push(refused);
        }
    }
    run.outcome().await.unwrap();
    browsers.close().await;
    assert_eq!(
        results.first(),
        Some(&None),
        "the page should load in {mode:?}"
    );
    let submitted = paths
        .lock()
        .unwrap()
        .iter()
        .any(|path| path.starts_with("/submitted"));
    (results.get(1).copied().flatten(), submitted)
}

// Covers: a page action asks the session's policy before it acts, so plan
// mode, which only reads, refuses a click that would submit a form while
// still loading the page, and supervised mode lets the same click submit.
// Owner: browser tools, as a session runs them
#[tokio::test]
#[ignore = "needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE"]
async fn a_page_action_follows_the_sessions_permission_mode() {
    let mut outcomes = Vec::new();
    for mode in [PermissionMode::Plan, PermissionMode::Supervised] {
        outcomes.push((mode, click_in(mode).await));
    }
    assert_eq!(
        outcomes,
        [
            (
                PermissionMode::Plan,
                (Some(ToolErrorKind::PolicyDenied), false)
            ),
            (PermissionMode::Supervised, (None, true)),
        ]
    );
}

/// Waits for `view` to reach `state`, returning it then.
async fn until(
    view: &mut tokio::sync::watch::Receiver<BrowserView>,
    state: BrowserState,
) -> BrowserView {
    tokio::time::timeout(
        Duration::from_secs(10),
        view.wait_for(|view| view.state == state),
    )
    .await
    .unwrap_or_else(|_| panic!("the browser should reach {state:?}"))
    .unwrap()
    .clone()
}

// Covers: a session's browser view follows its calls, naming the
// browser's own tab for each of its tabs, each call's card
// names the tab it acted on (none for list_tabs), and a hover by ref's card
// also where its element was, and when the browser
// closes the view tells how: Unloaded when it went unused and rho closed
// it, Crashed when it died on its own, its tabs gone either way. A client
// would otherwise show tabs of a browser that is gone, or a crash as a
// routine unload.
// Owner: browser tools, as a session runs them
#[tokio::test]
#[ignore = "needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE"]
async fn a_sessions_browser_view_follows_its_calls_and_how_the_browser_closed() {
    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()),
        unload_idle_after: Some(Duration::from_millis(500)),
        ..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 mut view = browser.view();
    let tabs = Arc::new(SessionTabs::new(browser.clone()));
    let tool = |action| BrowserTool {
        tabs: Arc::clone(&tabs),
        action,
        max_output_bytes: 50_000,
        offer: Arc::default(),
    };
    let address = serve(Arc::new(Mutex::new(Vec::new()))).await;
    let page = format!("http://{address}/");
    let call = |id: &str, action: Action, arguments: Value| {
        ScriptedTurn::completed(ModelResponse::Assistant(vec![ContentBlock::ToolCall(
            ToolCall::new(id.into(), action.name().into(), arguments),
        )]))
    };
    let provider = ScriptedProvider::new(
        ModelIdentity::new("scripted", "test", "model"),
        [
            call("navigate", Action::Navigate, json!({ "url": page })),
            call("read_page", Action::ReadPage, json!({})),
            // The form's button, which read_page names `ref_2`.
            call(
                "hover",
                Action::Hover,
                json!({ "target": { "type": "ref", "ref": "ref_2" } }),
            ),
            call("new_tab", Action::NewTab, json!({})),
            call("list_tabs", Action::ListTabs, json!({})),
            ScriptedTurn::completed(ModelResponse::Assistant(vec![ContentBlock::Text(
                "done".into(),
            )])),
        ],
    );
    let policy = PermissionMode::Supervised
        .workspace_policy(SessionWriteLog::default(), None)
        .expect("a checked mode");
    let runtime = Rho::builder()
        .provider(provider)
        .workspace(Workspace::new(home.path()).unwrap())
        .workspace_policy(policy)
        .tool(tool(Action::Navigate))
        .tool(tool(Action::ReadPage))
        .tool(tool(Action::Hover))
        .tool(tool(Action::NewTab))
        .tool(tool(Action::ListTabs))
        .build()
        .unwrap();
    let session = runtime.session(SessionOptions::default()).await.unwrap();
    // Keeps the browser from its idle unload while the calls run.
    let held = browser.context().await.unwrap();
    let mut run = session.start(UserInput::text("browse")).await.unwrap();
    let mut cards = Vec::new();
    while let Some(event) = run.next_event().await {
        if let RunEvent::ToolFinished { result, .. } = event {
            cards.push(
                result
                    .output()
                    .map(|output| shown_tab(output.presentation()))
                    .unwrap_or_default(),
            );
        }
    }
    run.outcome().await.unwrap();
    let browsed = view.borrow_and_update().clone();
    // What the browser shows in the tab each view tab names.
    let mut shown_in = Vec::new();
    for tab in &browsed.tabs {
        let info = held
            .connection()
            .call(&GetTargetInfo {
                target_id: tab.target.clone(),
            })
            .await
            .unwrap();
        shown_in.push((tab.id.clone(), info.target_info.url));
    }
    drop(held);
    // Nothing holds the browser now, so it closes once idle.
    let unloaded = until(&mut view, BrowserState::Unloaded).await;
    let context = browser.context().await.unwrap();
    let restarted = view.borrow_and_update().state;
    // Answered or not, the browser dies.
    let _ = context
        .connection()
        .call_raw("Browser.crash", json!({}))
        .await;
    let crashed = until(&mut view, BrowserState::Crashed).await;
    drop(context);
    browsers.close().await;

    let tab = |id: &str| vec![rho_protocol::ToolContent::Browser { tab: id.into() }];
    let gone = |state| BrowserView {
        state,
        ..BrowserView::default()
    };
    assert_eq!(
        (
            cards,
            shown_in,
            browsed.clone(),
            unloaded,
            restarted,
            crashed
        ),
        (
            vec![
                tab("tab-1"),
                tab("tab-1"),
                tab("tab-1")
                    .into_iter()
                    .chain([rho_protocol::ToolContent::BrowserElement(
                        rho_protocol::BrowserElement::new(
                            "tab-1",
                            "ref_2",
                            rho_protocol::BrowserRect::new(0, 0, 200, 100),
                            rho_protocol::BrowserViewport::new(1280, 800),
                        ),
                    )])
                    .collect(),
                tab("tab-2"),
                Vec::new(),
            ],
            vec![
                ("tab-1".to_owned(), page.clone()),
                ("tab-2".to_owned(), "about:blank".to_owned()),
            ],
            BrowserView {
                state: BrowserState::Running,
                tabs: vec![
                    ViewTab {
                        id: "tab-1".into(),
                        target: browsed.tabs[0].target.clone(),
                        // Chrome's title for a page without one.
                        title: address.to_string(),
                        url: page.clone(),
                        loading: false,
                    },
                    ViewTab {
                        id: "tab-2".into(),
                        target: browsed.tabs[1].target.clone(),
                        title: "about:blank".into(),
                        url: "about:blank".into(),
                        loading: false,
                    },
                ],
                current: Some("tab-2".into()),
                ..BrowserView::default()
            },
            gone(BrowserState::Unloaded),
            BrowserState::Running,
            gone(BrowserState::Crashed),
        )
    );
}