rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
use super::super::{lock, Browsers, SessionBrowser};
use crate::browser::config::BrowserConfig;
use crate::browser::drive::{PersonTabs, Refused};
use crate::browser::view::{Driver, ViewTab};
use crate::browser::watch::Pointer;
use futures_util::future::BoxFuture;
use pretty_assertions::assert_eq;
use rho_browser::cdp::TargetId;
use rho_protocol::{
    BrowserCursor, BrowserDestination, BrowserInput, BrowserKeyAction, BrowserModifiers,
    BrowserMouseAction, BrowserMouseButton, BrowserTabAction, ConnectionId,
};
use rho_sdk::SessionId;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::sync::{Notify, Semaphore};

/// Tabs that record the input they get, each held at dispatch until the
/// test lets one through, as a browser busy drawing holds a move.
struct Gated {
    got: Mutex<Vec<String>>,
    dispatching: Notify,
    gate: Semaphore,
}

impl Gated {
    fn closed() -> Self {
        Self {
            got: Mutex::default(),
            dispatching: Notify::new(),
            gate: Semaphore::new(0),
        }
    }
}

/// `future`, failing the test past a generous bound rather than hanging.
async fn soon<F: std::future::Future>(future: F) -> Result<F::Output, tokio::time::error::Elapsed> {
    tokio::time::timeout(Duration::from_secs(10), future).await
}

impl PersonTabs for Gated {
    fn input(
        &self,
        _: String,
        input: BrowserInput,
    ) -> BoxFuture<'_, Result<Option<BrowserCursor>, Refused>> {
        Box::pin(async move {
            self.got.lock().unwrap().push(name(&input));
            self.dispatching.notify_one();
            self.gate.acquire().await.unwrap().forget();
            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 {})
    }
}

fn name(input: &BrowserInput) -> String {
    match input {
        BrowserInput::Mouse { action, x, .. } => format!("{action:?} {x}"),
        BrowserInput::Key { action, key, .. } => format!("{action:?} {key}"),
        _ => "other".to_owned(),
    }
}

fn mouse(action: BrowserMouseAction, x: f64) -> BrowserInput {
    let button = (action != BrowserMouseAction::Moved).then_some(BrowserMouseButton::Left);
    BrowserInput::Mouse {
        action,
        x,
        y: 0.0,
        button,
        clicks: u32::from(button.is_some()),
        modifiers: BrowserModifiers::NONE,
    }
}

/// A session browser showing tab `tab-1`, a person driving it through
/// `tabs`, whose browser never starts.
fn driven(home: &tempfile::TempDir, tabs: &Arc<dyn PersonTabs>) -> SessionBrowser {
    let config = BrowserConfig {
        executable: Some(home.path().join("no-browser")),
        ..BrowserConfig::default()
    };
    let browsers = Browsers::for_tests(home.path(), config);
    let session = Browsers::session(Some(&browsers), &SessionId::new()).unwrap();
    session.drive_with(Arc::downgrade(tabs));
    session.show(|view| {
        view.tabs.push(ViewTab {
            id: "tab-1".into(),
            target: TargetId::from("tab-1"),
            title: String::new(),
            url: String::new(),
            loading: false,
        });
    });
    session.control(Driver::Person, ConnectionId::new(1));
    session
}

// Covers: a person's moves are answered at once, and only the newest of
// those that came while the tab was taking one is sent; a press that
// comes meanwhile goes after that newest move, and input after the press
// after it; a move to a tab the session lacks is refused, not merged.
// Otherwise a moving mouse queues seconds of moves ahead of a
// click, or a click lands before the move that put the pointer there.
// Owner: daemon browser service (person input)
#[tokio::test]
async fn moves_merge_and_other_input_keeps_its_place() {
    let home = tempfile::tempdir().unwrap();
    let gated = Arc::new(Gated::closed());
    let tabs: Arc<dyn PersonTabs> = gated.clone();
    let session = driven(&home, &tabs);

    let elsewhere = session
        .person_input("tab-9".into(), mouse(BrowserMouseAction::Moved, 1.0))
        .await;
    assert!(matches!(elsewhere, Err(Refused::NoTab(tab)) if tab == "tab-9"));

    // The first move goes to the tab, which holds it.
    session
        .person_input("tab-1".into(), mouse(BrowserMouseAction::Moved, 1.0))
        .await
        .unwrap();
    soon(gated.dispatching.notified())
        .await
        .expect("the first move reaches the tab");
    // More moves, answered while the tab still holds the first.
    for x in [2.0, 3.0, 4.0] {
        soon(session.person_input("tab-1".into(), mouse(BrowserMouseAction::Moved, x)))
            .await
            .expect("a move is answered without waiting for the tab")
            .unwrap();
    }
    // A click and a key, in the connection's order, behind the held move.
    let pressing = session.clone();
    let clicked = tokio::spawn(async move {
        for input in [
            mouse(BrowserMouseAction::Pressed, 4.0),
            BrowserInput::Key {
                action: BrowserKeyAction::Down,
                key: "a".into(),
                code: None,
                text: Some("a".into()),
                modifiers: BrowserModifiers::NONE,
            },
        ] {
            pressing.person_input("tab-1".into(), input).await.unwrap();
        }
    });
    // Let the press queue for the tabs behind the held move, so that it,
    // not the task sending moves, sends the waiting move. Without these
    // yields the order comes out the same, but that path goes untested.
    for _ in 0..8 {
        tokio::task::yield_now().await;
    }
    gated.gate.add_permits(10);
    soon(clicked).await.expect("the click is sent").unwrap();

    assert_eq!(
        *gated.got.lock().unwrap(),
        ["Moved 1", "Moved 4", "Pressed 4", "Down a"]
    );
}

/// Resolves once no task sends the session's waiting moves.
async fn drained(session: &SessionBrowser) {
    soon(async {
        while lock(&session.moves.waiting).draining {
            tokio::task::yield_now().await;
        }
    })
    .await
    .expect("the moves are sent");
}

// Covers: the page's cursor after a person's input goes to the watches of
// its tab once per change; a hand-back clears it; and one the page answers
// after the person handed the browser back, whether or not they took it
// over again since, does not show. Otherwise a watch sends the cursor
// again on every move, or the cursor of a turn that ended shows in the
// agent's or the next, which starts from none.
// Owner: daemon browser service (person input)
#[tokio::test]
async fn a_cursor_shows_once_and_only_in_the_turn_it_came_in() {
    let home = tempfile::tempdir().unwrap();
    let gated = Arc::new(Gated::closed());
    let tabs: Arc<dyn PersonTabs> = gated.clone();
    let session = driven(&home, &tabs);
    let mut pointer = session.pointer.subscribe();
    let connection = ConnectionId::new(1);
    let move_to = |x| session.person_input("tab-1".into(), mouse(BrowserMouseAction::Moved, x));

    gated.gate.add_permits(1);
    move_to(1.0).await.unwrap();
    drained(&session).await;
    let shown = pointer.borrow_and_update().clone();
    gated.gate.add_permits(1);
    move_to(2.0).await.unwrap();
    drained(&session).await;
    let shown_again = pointer.has_changed().unwrap();
    session.control(Driver::Agent, connection);
    let handed_back = pointer.borrow_and_update().clone();

    // The page answers a move's cursor after a hand-back, then after a
    // hand-back and a new takeover.
    let mut late = Vec::new();
    for retake in [false, true] {
        session.control(Driver::Person, connection);
        pointer.borrow_and_update();
        move_to(3.0).await.unwrap();
        soon(gated.dispatching.notified())
            .await
            .expect("the move reaches the tab");
        session.control(Driver::Agent, connection);
        if retake {
            session.control(Driver::Person, connection);
        }
        gated.gate.add_permits(1);
        drained(&session).await;
        late.push(pointer.borrow_and_update().clone());
    }

    let pointed = Some(Pointer {
        target: TargetId::from("tab-1"),
        cursor: BrowserCursor::Pointer,
    });
    assert_eq!(
        (shown, shown_again, handed_back, late),
        (pointed, false, None, vec![None, None])
    );
}