rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The tools that look at and move the viewport: `screenshot`, `zoom`,
//! `scroll` and `scroll_to`.

use super::calls::{Image, Reply};
use super::inputs::{Direction, Region};
use super::schema::NOTCH;
use super::tabs::{execution, OpenTab};
use crate::browser::VIEWPORT;
use base64::Engine as _;
use rho_browser::cdp::input::{DispatchMouseEvent, Modifiers, MouseEventKind};
use rho_browser::cdp::page::{CaptureScreenshot, Clip, GetLayoutMetrics, ImageFormat};
use rho_sdk::tool::ToolError;

/// JPEG quality for screenshots. At 80 a 1280x800 Hacker News page was
/// 115 KB against PNG's 163 KB, and example.com 65 KB against 76 KB. The
/// model is billed by pixels, not bytes, so this only trims the request.
const JPEG_QUALITY: u8 = 80;

pub(super) async fn screenshot(open: &mut OpenTab) -> Result<Reply, ToolError> {
    let caption = format!("Screenshot of {}.", open.id);
    capture(open, None, caption).await
}

/// `region` of the viewport, upscaled to fill the viewport's size at most,
/// so the image costs no more than a screenshot.
pub(super) async fn zoom(open: &mut OpenTab, region: Region) -> Result<Reply, ToolError> {
    let Region { x0, y0, x1, y1 } = region;
    let viewport = open.call(&GetLayoutMetrics {}).await?.css_visual_viewport;
    let (width, height) = (f64::from(x1 - x0), f64::from(y1 - y0));
    let scale = (f64::from(VIEWPORT.width) / width)
        .min(f64::from(VIEWPORT.height) / height)
        .max(1.0);
    // Clips are in document coordinates.
    let clip = Clip {
        x: viewport.page_x + f64::from(x0),
        y: viewport.page_y + f64::from(y0),
        width,
        height,
        scale,
    };
    let caption = format!("Zoomed into [{x0}, {y0}, {x1}, {y1}] at {scale:.1}x.");
    capture(open, Some(clip), caption).await
}

/// Scrolls the element at `(x, y)` by `notches` wheel notches.
pub(super) async fn scroll(
    open: &mut OpenTab,
    x: u32,
    y: u32,
    direction: Direction,
    notches: u8,
) -> Result<Reply, ToolError> {
    let distance = f64::from(u32::from(notches) * NOTCH);
    let (delta_x, delta_y) = match direction {
        Direction::Up => (0.0, -distance),
        Direction::Down => (0.0, distance),
        Direction::Left => (-distance, 0.0),
        Direction::Right => (distance, 0.0),
    };
    open.call(&DispatchMouseEvent {
        kind: MouseEventKind::Wheel,
        x: f64::from(x),
        y: f64::from(y),
        button: None,
        click_count: None,
        modifiers: Modifiers::NONE,
        delta_x: Some(delta_x),
        delta_y: Some(delta_y),
    })
    .await?;
    open.drawn().await?;
    Ok(Reply::text(format!(
        "Scrolled {} {distance} px at ({x}, {y}).",
        direction.name()
    )))
}

pub(super) async fn scroll_to(open: &mut OpenTab, element: &str) -> Result<Reply, ToolError> {
    let node = open.node(element).await?;
    open.scroll_into_view(&node).await?;
    Ok(Reply::text(format!("Scrolled {element} into view.")))
}

async fn capture(open: &OpenTab, clip: Option<Clip>, caption: String) -> Result<Reply, ToolError> {
    let shot = open
        .call(&CaptureScreenshot {
            format: Some(ImageFormat::Jpeg),
            quality: Some(JPEG_QUALITY),
            clip,
        })
        .await?;
    let bytes = base64::engine::general_purpose::STANDARD
        .decode(&shot.data)
        .map_err(|error| execution(format!("the browser sent a malformed image: {error}")))?;
    Ok(Reply {
        text: caption,
        image: Some(Image {
            data: shot.data,
            bytes,
        }),
        placed: None,
    })
}