rho-coding-agent 3.10.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! A person driving the session's tabs from a client ([`PersonTabs`]):
//! their input, navigation and tab actions act on the same tabs the agent's
//! calls use, and the session's view follows what their driving does.

use super::tabs::{Held, Loading, SessionTabs};
use super::text::{self, Destination};
use super::{keys, schema::NAVIGATION_LIMIT};
use crate::browser::drive::{PersonTabs, Refused};
use crate::browser::view::{BrowserState, Driver};
use crate::browser::{navigation, SessionBrowser};
use futures_util::future::BoxFuture;
use rho_browser::cdp::input::{
    DispatchKeyEvent, DispatchMouseEvent, InsertText, KeyEventKind, Modifiers, MouseButton,
    MouseEventKind,
};
use rho_browser::cdp::target::{SetDiscoverTargets, TargetCreated, TargetInfoChanged};
use rho_browser::cdp::BrowserContextId;
use rho_browser::tab::{Step, Tab};
use rho_protocol::{
    BrowserDestination, BrowserInput, BrowserKeyAction, BrowserModifiers, BrowserMouseAction,
    BrowserMouseButton, BrowserTabAction,
};

impl PersonTabs for SessionTabs {
    fn input(&self, tab: String, input: BrowserInput) -> BoxFuture<'_, Result<(), Refused>> {
        Box::pin(async move {
            let mut held = self.person_hold(&tab).await?;
            let takeovers = held.browser.takeovers();
            let command = command(input, held.tabs.person_button.under(takeovers));
            let open = held.tabs.get(Some(&tab)).map_err(|_| Refused::NoTab(tab))?;
            let sent = match command {
                Command::Mouse(event) => open.call(&event).await.map(drop),
                Command::Key(event) => open.call(&event).await.map(drop),
                Command::Text(event) => open.call(&event).await.map(drop),
            };
            sent.map_err(|error| Refused::Browser(error.message().to_owned()))
        })
    }

    fn navigate(&self, tab: String, to: BrowserDestination) -> BoxFuture<'_, Result<(), Refused>> {
        Box::pin(async move {
            let destination = match to {
                BrowserDestination::Url { url } => {
                    let destination = text::destination(&url).map_err(Refused::Invalid)?;
                    if let Destination::Url(url) = &destination {
                        navigation::allowed(url.as_str()).await.map_err(|reason| {
                            Refused::Invalid(format!("Navigation refused: {reason}."))
                        })?;
                    }
                    destination
                }
                BrowserDestination::Back => Destination::Back,
                BrowserDestination::Forward => Destination::Forward,
                BrowserDestination::Reload => Destination::Reload,
                _ => return Err(Refused::Invalid("an unknown destination".to_owned())),
            };
            let mut held = self.person_hold(&tab).await?;
            let open = held
                .tabs
                .get(Some(&tab))
                .map_err(|_| Refused::NoTab(tab.clone()))?;
            let new_url = match &destination {
                Destination::Url(url) => Some(url.as_str()),
                Destination::Back | Destination::Forward | Destination::Reload => None,
            };
            let loading = super::tabs::show_loading(held.browser, held.context.id(), open, new_url);
            tokio::spawn(load(
                held.browser.clone(),
                held.context.id().clone(),
                open.tab().clone(),
                destination,
                loading,
            ));
            Ok(())
        })
    }

    fn tab(&self, action: BrowserTabAction) -> BoxFuture<'_, Result<Option<String>, Refused>> {
        Box::pin(async move {
            let mut held = self.hold_now().await.map_err(browser_error)?;
            let opened = match action {
                BrowserTabAction::New => {
                    let opened = held
                        .tabs
                        .open(&held.context)
                        .await
                        .map_err(|error| Refused::Invalid(error.message().to_owned()))?;
                    Some(opened.id.clone())
                }
                BrowserTabAction::Close { tab } => {
                    if !held.tabs.has(&tab) {
                        return Err(Refused::NoTab(tab));
                    }
                    held.tabs.close(&tab).await.map_err(browser_error)?;
                    None
                }
                BrowserTabAction::Activate { tab } => {
                    held.tabs.switch(&tab).map_err(|_| Refused::NoTab(tab))?;
                    None
                }
                _ => return Err(Refused::Invalid("an unknown tab action".to_owned())),
            };
            held.show_tabs().await;
            Ok(opened)
        })
    }

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

    fn follow(&self) -> BoxFuture<'_, ()> {
        Box::pin(async move {
            let browser = self.browser();
            let mut view = browser.view();
            // A browser that is not running has nothing to follow; the
            // person's next action, which may start it, follows it then.
            if view.borrow_and_update().state != BrowserState::Running {
                return;
            }
            let (connection, context) = match self.hold_now().await {
                Ok(held) => (held.context.connection().clone(), held.context.id().clone()),
                Err(_) => return,
            };
            let mut events = connection.events();
            if connection
                .call(&SetDiscoverTargets { discover: true })
                .await
                .is_err()
            {
                return;
            }
            loop {
                tokio::select! {
                    event = events.recv() => {
                        // The browser closed.
                        let Ok(event) = event else { return };
                        if let Some(Ok(changed)) = event.parse::<TargetInfoChanged>() {
                            let info = changed.target_info;
                            browser.show_in(&context, |view| {
                                if let Some(tab) = view.tabs.iter_mut().find(|tab| tab.target == info.target_id) {
                                    tab.title = info.title;
                                    tab.url = info.url;
                                }
                            });
                        } else if let Some(Ok(created)) = event.parse::<TargetCreated>() {
                            let info = created.target_info;
                            if info.kind == "page" && info.browser_context_id.as_ref() == Some(&context) {
                                self.take_in_pages().await;
                            }
                        }
                    }
                    () = agent_drives(&mut view) => return,
                }
            }
        })
    }
}

impl SessionTabs {
    /// The session's tabs for a person's action on tab `tab`, which the
    /// session's view lists, so an action on a tab of a browser that closed
    /// never starts it again.
    async fn person_hold(&self, tab: &str) -> Result<Held<'_>, Refused> {
        if !self.browser().shows_tab(tab) {
            return Err(Refused::NoTab(tab.to_owned()));
        }
        self.hold_now().await.map_err(browser_error)
    }

    /// Takes in the tabs pages opened, as a link a person clicked did, and
    /// shows them.
    async fn take_in_pages(&self) {
        if let Ok(mut held) = self.hold_now().await {
            held.tabs.take_in(&held.context).await;
            held.show_tabs().await;
        }
    }
}

/// Resolves once the agent drives the browser again, or the session's
/// view is gone.
async fn agent_drives(view: &mut tokio::sync::watch::Receiver<crate::browser::view::BrowserView>) {
    let _ = view.wait_for(|view| view.driver == Driver::Agent).await;
}

fn browser_error(error: rho_sdk::tool::ToolError) -> Refused {
    Refused::Browser(error.message().to_owned())
}

/// Loads `destination` in `tab` of `context`, then shows the tab's title
/// and URL as loaded, or as far as it got, and no longer `loading`.
async fn load(
    browser: SessionBrowser,
    context: BrowserContextId,
    tab: Tab,
    destination: Destination,
    loading: Loading,
) {
    let loaded = match &destination {
        Destination::Url(url) => tab.load(url.as_str(), NAVIGATION_LIMIT).await,
        Destination::Back => tab.go(Step::Back, NAVIGATION_LIMIT).await,
        Destination::Forward => tab.go(Step::Forward, NAVIGATION_LIMIT).await,
        Destination::Reload => tab.go(Step::Reload, NAVIGATION_LIMIT).await,
    };
    if let Err(error) = loaded {
        tracing::debug!(%error, "a person's navigation did not finish");
    }
    let info = tab.info().await.ok();
    let target = tab.page().target_id().clone();
    browser.show_in(&context, |view| {
        if let Some(shown) = view.tabs.iter_mut().find(|shown| shown.target == target) {
            if let Some(info) = info {
                shown.title = info.title;
                shown.url = info.url;
            }
        }
    });
    drop(loading);
}

/// The browser command a person's input sends.
#[derive(Debug, Clone)]
enum Command {
    Mouse(DispatchMouseEvent),
    Key(DispatchKeyEvent),
    Text(InsertText),
}

/// The command for `input`. `held` is the mouse button the person holds
/// down, which a move drags: a press holds it and a release lets go.
/// The mouse button a person driving the browser holds down, which their
/// moves drag. A button pressed under an earlier takeover was let go with
/// it, as when a client left between a press and its release.
#[derive(Debug, Default)]
pub(super) struct HeldButton {
    /// The takeover, as [`SessionBrowser::takeovers`] counts them, the
    /// button was pressed under.
    takeover: u64,
    button: Option<MouseButton>,
}

impl HeldButton {
    /// The button held under takeover `takeover`.
    pub(super) fn under(&mut self, takeover: u64) -> &mut Option<MouseButton> {
        if self.takeover != takeover {
            *self = Self {
                takeover,
                button: None,
            };
        }
        &mut self.button
    }
}

fn command(input: BrowserInput, held: &mut Option<MouseButton>) -> Command {
    match input {
        BrowserInput::Mouse {
            action,
            x,
            y,
            button,
            clicks,
            modifiers,
        } => {
            let button = button.map(mouse_button);
            let (kind, button, click_count) = match action {
                BrowserMouseAction::Moved => (MouseEventKind::Moved, *held, None),
                BrowserMouseAction::Pressed => {
                    *held = button;
                    (MouseEventKind::Pressed, button, Some(clicks.max(1)))
                }
                BrowserMouseAction::Released => {
                    *held = None;
                    (MouseEventKind::Released, button, Some(clicks.max(1)))
                }
                _ => (MouseEventKind::Moved, *held, None),
            };
            Command::Mouse(DispatchMouseEvent {
                kind,
                x,
                y,
                button,
                click_count,
                modifiers: modifiers_of(modifiers),
                delta_x: None,
                delta_y: None,
            })
        }
        BrowserInput::Wheel {
            x,
            y,
            dx,
            dy,
            modifiers,
        } => Command::Mouse(DispatchMouseEvent {
            kind: MouseEventKind::Wheel,
            x,
            y,
            button: None,
            click_count: None,
            modifiers: modifiers_of(modifiers),
            delta_x: Some(dx),
            delta_y: Some(dy),
        }),
        BrowserInput::Key {
            action,
            key,
            code,
            text,
            modifiers,
        } => {
            let modifiers = modifiers_of(modifiers);
            // As the agent's `key` does: a key types only with no modifier
            // but shift held.
            let text = text.filter(|text| {
                !text.is_empty() && modifiers.without(Modifiers::SHIFT) == Modifiers::NONE
            });
            let (kind, text) = match (action, text) {
                (BrowserKeyAction::Down, Some(text)) => (KeyEventKind::KeyDown, Some(text)),
                (BrowserKeyAction::Up, _) => (KeyEventKind::KeyUp, None),
                (_, _) => (KeyEventKind::RawKeyDown, None),
            };
            Command::Key(DispatchKeyEvent {
                kind,
                windows_virtual_key_code: keys::key_code(&key),
                key,
                code,
                text,
                modifiers,
            })
        }
        BrowserInput::Text { text } => Command::Text(InsertText { text }),
        // A newer client's input this daemon cannot send moves nothing.
        _ => Command::Text(InsertText {
            text: String::new(),
        }),
    }
}

fn mouse_button(button: BrowserMouseButton) -> MouseButton {
    match button {
        BrowserMouseButton::Left => MouseButton::Left,
        BrowserMouseButton::Middle => MouseButton::Middle,
        BrowserMouseButton::Right => MouseButton::Right,
        _ => MouseButton::Left,
    }
}

fn modifiers_of(held: BrowserModifiers) -> Modifiers {
    [
        (held.alt, Modifiers::ALT),
        (held.ctrl, Modifiers::CTRL),
        (held.meta, Modifiers::META),
        (held.shift, Modifiers::SHIFT),
    ]
    .into_iter()
    .filter(|(on, _)| *on)
    .fold(Modifiers::NONE, |all, (_, modifier)| all.with(modifier))
}

#[cfg(test)]
#[path = "person_tests.rs"]
mod tests;

#[cfg(test)]
#[path = "person_live_tests.rs"]
mod live_tests;