rho-coding-agent 3.10.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 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},
    BrowserFrameAckParams, BrowserFrameAckResponse, BrowserFrameParams, BrowserFrames,
    BrowserUnwatchParams, BrowserUnwatchResponse, BrowserViewport, BrowserWatchId,
    BrowserWatchParams, BrowserWatchResponse, BuildId, Client, ClientHello, ClientInfo, 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::{
        view::{BrowserState, BrowserView, 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 frame `notifications` bring, if one comes within `wait`.
async fn frame(notifications: &mut Notifications, wait: Duration) -> Option<BrowserFrameParams> {
    tokio::time::timeout(wait, async {
        loop {
            match notifications.recv().await {
                Some(DaemonNotification::BrowserFrame(frame)) => return frame,
                Some(_) => {}
                None => panic!("the connection closed"),
            }
        }
    })
    .await
    .ok()
}

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 = frame(&mut notifications, BUDGET).await.unwrap();
    let second = frame(&mut notifications, BUDGET).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 = frame(&mut notifications, Duration::from_secs(1)).await;
    let after_unload = view.borrow().state;
    ack(&watch, 2).await.unwrap();
    let acked = frame(&mut notifications, BUDGET)
        .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;
}