rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Watches of a real chrome-headless-shell's tabs, over a protocol
//! connection. Set `RHO_BROWSER_EXECUTABLE` to one and run with
//! `--include-ignored`.

use futures_util::future::BoxFuture;
use std::{sync::Arc, time::Duration};

use pretty_assertions::assert_eq;
use rho_browser::tab::Tab;
use rho_protocol::{
    self as wire,
    methods::{BrowserFrameAck, BrowserUnwatch, BrowserWatch},
    BrowserCursor, BrowserCursorParams, BrowserDestination, BrowserFrameAckParams,
    BrowserFrameAckResponse, BrowserFrameParams, BrowserFrames, BrowserInput, BrowserModifiers,
    BrowserMouseAction, BrowserTabAction, BrowserUnwatchParams, BrowserUnwatchResponse,
    BrowserViewport, BrowserWatchId, BrowserWatchParams, BrowserWatchResponse, BuildId, Client,
    ClientHello, ClientInfo, ConnectionId, DaemonInfo, DaemonNotification, DaemonStatus, ErrorCode,
    Notifications, RestartCost, RpcError, Service, SettingsService,
};
use tempfile::TempDir;
use tokio::sync::watch;

use super::super::{test_sessions::load_browsing, Sessions};
use crate::{
    app::{
        daemon_host::jobs::{JobRegistry, JobStore},
        pull_requests::ScriptedForge,
    },
    browser::{
        drive::{PersonTabs, Refused},
        view::{BrowserState, BrowserView, Driver, ViewTab},
        Browsers, SessionBrowser, VIEWPORT,
    },
};

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

/// Serves the browser watch methods as the daemon does, from `Sessions`.
struct Watching(Arc<Sessions>);

impl Service for Watching {
    fn refused_newer(&self, _: wire::ProtocolVersion) -> RestartCost {
        RestartCost {
            in_progress: 0,
            clients: 0,
        }
    }

    fn skewed(&self, _: &ClientInfo, _: &BuildId) -> RestartCost {
        RestartCost {
            in_progress: 0,
            clients: 0,
        }
    }

    async fn status(&self) -> DaemonStatus {
        unreachable!("the test asks no status")
    }

    async fn stop(&self) {}

    async fn restart(&self) {}

    async fn list_jobs(&self) -> wire::JobListResponse {
        unreachable!("the test lists no jobs")
    }

    async fn watch_browser(
        &self,
        params: BrowserWatchParams,
    ) -> Result<(BrowserWatchResponse, BrowserFrames), RpcError> {
        self.0.watch_browser(params).await
    }

    async fn ack_browser_frame(
        &self,
        params: BrowserFrameAckParams,
    ) -> Result<BrowserFrameAckResponse, RpcError> {
        self.0.ack_browser_frame(params)
    }

    async fn unwatch_browser(
        &self,
        params: BrowserUnwatchParams,
    ) -> Result<BrowserUnwatchResponse, RpcError> {
        Ok(self.0.unwatch_browser(params))
    }
}

impl SettingsService for Watching {}

/// A client of `sessions` over an in-memory connection.
async fn connect(sessions: &Arc<Sessions>) -> (Client, Notifications) {
    let (stream, served) = tokio::io::duplex(1 << 20);
    let info = DaemonInfo {
        version: "test".into(),
        pid: 0,
        build: BuildId::of_this_crate(),
    };
    let service = Arc::new(Watching(Arc::clone(sessions)));
    tokio::spawn(async move {
        rho_protocol::serve_connection(served, &info, service, std::future::pending()).await
    });
    let hello = ClientHello::command(ClientInfo {
        name: "browser-watch-test".into(),
        version: "0".into(),
    });
    let (client, notifications, _) = Client::handshake(stream, hello).await.unwrap();
    (client, notifications)
}

/// Opens a tab in `browser`'s context showing `url`, and lists it in the
/// session's view as tab `id`, as the session's browser tools do.
async fn open_tab(browser: &SessionBrowser, id: &str, url: &str) -> Tab {
    let context = browser.context().await.unwrap();
    let tab = Tab::open(context.connection(), context.id(), VIEWPORT)
        .await
        .unwrap();
    tab.load(url, BUDGET).await.unwrap();
    browser.show(|view| {
        view.tabs.push(ViewTab {
            id: id.into(),
            target: tab.page().target_id().clone(),
            title: String::new(),
            url: url.into(),
            loading: false,
        });
    });
    tab
}

/// The next of `notifications` that `pick` takes, if one comes within
/// `wait`.
async fn next<T>(
    notifications: &mut Notifications,
    wait: Duration,
    pick: impl Fn(DaemonNotification) -> Option<T>,
) -> Option<T> {
    tokio::time::timeout(wait, async {
        loop {
            match notifications.recv().await {
                Some(notification) => {
                    if let Some(picked) = pick(notification) {
                        return picked;
                    }
                }
                None => panic!("the connection closed"),
            }
        }
    })
    .await
    .ok()
}

fn frame(notification: DaemonNotification) -> Option<BrowserFrameParams> {
    match notification {
        DaemonNotification::BrowserFrame(frame) => Some(frame),
        _ => None,
    }
}

fn cursor(notification: DaemonNotification) -> Option<BrowserCursorParams> {
    match notification {
        DaemonNotification::BrowserCursor(cursor) => Some(cursor),
        _ => None,
    }
}

async fn until_state(view: &mut watch::Receiver<BrowserView>, state: BrowserState) {
    tokio::time::timeout(BUDGET, view.wait_for(|view| view.state == state))
        .await
        .unwrap_or_else(|_| panic!("the browser should reach {state:?}"))
        .unwrap();
}

/// A page that draws a frame each time the browser does.
const ANIMATED: &str = "data:text/html,<style>@keyframes s{to{transform:rotate(1turn)}}\
    div{width:300px;height:300px;background:linear-gradient(red,blue);\
    animation:s 1s linear infinite}</style><div></div>";

// Covers: a client watching a session's tab gets the viewport, then the
// tab's frames scaled to fit its size, at most two ahead of its acks and
// more once it acks; the watch holds the browser open past its idle
// unload until the client unwatches; and a tab that closes ends its watch,
// so acks for it are refused. Without it, the panel gets frames too large
// or too many for its link, the browser unloads under a person watching
// it, or a closed tab's watch leaks its screencast.
// Owner: daemon browser watches
#[tokio::test]
#[ignore = "needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE"]
async fn a_watch_streams_a_tab_by_its_clients_acks_while_holding_the_browser() {
    let executable = std::env::var("RHO_BROWSER_EXECUTABLE")
        .expect("needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE");
    let (root, home) = (TempDir::new().unwrap(), TempDir::new().unwrap());
    std::fs::write(
        home.path().join("config.toml"),
        format!("[browser]\nexecutable = {executable:?}\nunload_idle_after = \"500ms\"\n"),
    )
    .unwrap();
    let sessions = Sessions::new(
        Arc::new(JobRegistry::open(JobStore::open(home.path()).unwrap())),
        home.path(),
        ScriptedForge::new(),
    );
    let browser =
        Browsers::session(sessions.browsers.as_ref(), &rho_sdk::SessionId::new()).unwrap();
    let loaded = load_browsing(&sessions, &root, browser.clone()).await;
    let session = wire::SessionId::new(loaded.id.to_string());
    let mut view = browser.view();
    let (client, mut notifications) = connect(&sessions).await;
    let ack = |watch: &BrowserWatchId, seq| {
        let (client, params) = (&client, BrowserFrameAckParams::new(watch.clone(), seq));
        async move { client.request::<BrowserFrameAck>(&params).await }
    };

    let _tab = open_tab(&browser, "tab-1", ANIMATED).await;
    let watched = client
        .request::<BrowserWatch>(&BrowserWatchParams::new(session.clone(), "tab-1", 800, 900))
        .await
        .unwrap();
    let watch = watched.watch.clone();
    let first = next(&mut notifications, BUDGET, frame).await.unwrap();
    let second = next(&mut notifications, BUDGET, frame).await.unwrap();
    // Unacked, the animation draws on but no third frame comes; by now
    // the browser has gone unused past its 500 ms unload.
    let unacked = next(&mut notifications, Duration::from_secs(1), frame).await;
    let after_unload = view.borrow().state;
    ack(&watch, 2).await.unwrap();
    let acked = next(&mut notifications, BUDGET, frame)
        .await
        .map(|frame| frame.seq);
    client
        .request::<BrowserUnwatch>(&BrowserUnwatchParams::new(watch.clone()))
        .await
        .unwrap();
    until_state(&mut view, BrowserState::Unloaded).await;

    let tab = open_tab(&browser, "tab-2", ANIMATED).await;
    let closing = client
        .request::<BrowserWatch>(&BrowserWatchParams::new(session, "tab-2", 800, 900))
        .await
        .unwrap()
        .watch;
    tab.close().await.unwrap();
    let ended = tokio::time::timeout(BUDGET, async {
        loop {
            match ack(&closing, 0).await {
                Ok(_) => tokio::task::yield_now().await,
                Err(error) => return error.error_code(),
            }
        }
    })
    .await
    .expect("the watch should end with its tab");

    let shape = |frame: &BrowserFrameParams| {
        (
            frame.watch.clone(),
            frame.seq,
            frame.mime.clone(),
            frame.width,
            frame.height,
        )
    };
    let jpeg = |seq| (watch.clone(), seq, "image/jpeg".to_owned(), 800, 500);
    assert_eq!(
        (
            watched.viewport,
            shape(&first),
            shape(&second),
            unacked.map(|frame| frame.seq),
            after_unload,
            acked,
            ended,
        ),
        (
            BrowserViewport::new(1280, 800),
            jpeg(1),
            jpeg(2),
            None,
            BrowserState::Running,
            Some(3),
            Some(ErrorCode::InvalidParams),
        )
    );
    sessions.browsers.as_ref().unwrap().close().await;
}

/// A person's tabs whose page has a pointer cursor everywhere, which carry
/// out nothing else.
struct Pointing;

impl PersonTabs for Pointing {
    fn input(
        &self,
        _: String,
        _: BrowserInput,
    ) -> BoxFuture<'_, Result<Option<BrowserCursor>, Refused>> {
        Box::pin(async { Ok(Some(BrowserCursor::Pointer)) })
    }

    fn navigate(&self, tab: String, _: BrowserDestination) -> BoxFuture<'_, Result<(), Refused>> {
        Box::pin(async move { Err(Refused::NoTab(tab)) })
    }

    fn tab(&self, _: BrowserTabAction) -> BoxFuture<'_, Result<Option<String>, Refused>> {
        Box::pin(async { Ok(None) })
    }

    fn close(&self) -> BoxFuture<'_, ()> {
        Box::pin(async {})
    }

    fn fit(&self) -> BoxFuture<'_, ()> {
        Box::pin(async {})
    }

    fn follow(&self) -> BoxFuture<'_, ()> {
        Box::pin(async {})
    }
}

// Covers: while a person drives, a client watching the tab under their
// pointer gets the page's cursor after their input, over its connection,
// a watch of the tab that starts later gets it at once, and a watch of
// another tab gets none. Otherwise the client never learns the cursor to
// show over the frame, a second window shows none until the pointer moves
// again, or a tab shows the cursor of the pointer over another.
// Owner: daemon browser watches
#[tokio::test]
#[ignore = "needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE"]
async fn a_watch_sends_the_cursor_under_the_persons_pointer() {
    let executable = std::env::var("RHO_BROWSER_EXECUTABLE")
        .expect("needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE");
    let (root, home) = (TempDir::new().unwrap(), TempDir::new().unwrap());
    std::fs::write(
        home.path().join("config.toml"),
        format!("[browser]\nexecutable = {executable:?}\n"),
    )
    .unwrap();
    let sessions = Sessions::new(
        Arc::new(JobRegistry::open(JobStore::open(home.path()).unwrap())),
        home.path(),
        ScriptedForge::new(),
    );
    let browser =
        Browsers::session(sessions.browsers.as_ref(), &rho_sdk::SessionId::new()).unwrap();
    let tabs: Arc<dyn PersonTabs> = Arc::new(Pointing);
    browser.drive_with(Arc::downgrade(&tabs));
    let loaded = load_browsing(&sessions, &root, browser.clone()).await;
    let session = wire::SessionId::new(loaded.id.to_string());
    let (client, mut notifications) = connect(&sessions).await;
    let watch = |tab: &str| {
        let params = BrowserWatchParams::new(session.clone(), tab, 800, 900);
        let client = &client;
        async move { client.request::<BrowserWatch>(&params).await.unwrap().watch }
    };

    let _tab = open_tab(&browser, "tab-1", ANIMATED).await;
    let _other = open_tab(&browser, "tab-2", ANIMATED).await;
    let first = watch("tab-1").await;
    let _elsewhere = watch("tab-2").await;
    browser.control(Driver::Person, ConnectionId::new(1));
    let moved = BrowserInput::Mouse {
        action: BrowserMouseAction::Moved,
        x: 10.0,
        y: 10.0,
        button: None,
        clicks: 0,
        modifiers: BrowserModifiers::NONE,
    };
    browser.person_input("tab-1".into(), moved).await.unwrap();
    let pointed = next(&mut notifications, BUDGET, cursor).await;
    let second = watch("tab-1").await;
    // Every cursor up to the late watch's.
    let mut late = Vec::new();
    while let Some(sent) = next(&mut notifications, BUDGET, cursor).await {
        let done = sent.watch == second;
        late.push(sent);
        if done {
            break;
        }
    }

    assert_eq!(
        (pointed, late),
        (
            Some(BrowserCursorParams::new(first, BrowserCursor::Pointer)),
            vec![BrowserCursorParams::new(second, BrowserCursor::Pointer)],
        )
    );
    sessions.browsers.as_ref().unwrap().close().await;
}