rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! What a session's browser looks like to its clients: whether it runs, its
//! tabs, and which one is current. The session's browser tools keep it up
//! to date through the session's [`super::SessionBrowser`], and the daemon
//! reports each change to the session's clients as
//! [`rho_protocol::SessionEvent::Browser`].
//!
//! A browser call names the tab it acted on with a [`ToolAsset`] the
//! session's events turn into [`rho_protocol::ToolContent::Browser`], as
//! the `ui` tool names the surface it showed, and a click or hover by ref
//! says where its element was with another, which becomes
//! [`rho_protocol::ToolContent::BrowserElement`].

use rho_protocol::{BrowserElement, BrowserRect, BrowserViewport, ToolContent};
use rho_sdk::tool::{ToolAsset, ToolMetadata};
use serde::{Deserialize, Serialize};

/// A session's browser.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct BrowserView {
    pub(crate) state: BrowserState,
    /// The session's tabs, in the order they opened.
    pub(crate) tabs: Vec<ViewTab>,
    /// The tab the agent's calls use when they name none.
    pub(crate) current: Option<String>,
    pub(crate) driver: Driver,
}

/// Who drives a session's browser.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[cfg_attr(not(feature = "browser"), allow(dead_code))]
pub(crate) enum Driver {
    /// The agent's browser tools.
    #[default]
    Agent,
    /// A person, from a client; the agent's browser tools wait.
    Person,
}

/// Where a session's browser stands. Only a build with the browser starts
/// one.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[cfg_attr(not(feature = "browser"), allow(dead_code))]
pub(crate) enum BrowserState {
    /// No browser call came yet.
    #[default]
    NotStarted,
    /// A call is starting the browser, or downloading it first.
    Starting,
    Running,
    /// The browser closed after going unused, or as its config changed.
    Unloaded,
    /// The browser exited on its own.
    Crashed,
}

/// One of a session's tabs.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ViewTab {
    pub(crate) id: String,
    /// The browser's own id for the tab, which a watch screencasts.
    #[cfg(feature = "browser")]
    pub(crate) target: rho_browser::cdp::TargetId,
    pub(crate) title: String,
    pub(crate) url: String,
    pub(crate) loading: bool,
}

/// The media type of the [`ToolAsset`] that names the tab a browser call
/// acted on: the tab's id, as UTF-8.
const TAB_MEDIA_TYPE: &str = "application/vnd.rho.browser-tab";

/// The media type of the [`ToolAsset`] that says where the element a call
/// acted on by ref was: a [`Placed`], as JSON.
const ELEMENT_MEDIA_TYPE: &str = "application/vnd.rho.browser-element";

/// Where the element a click or hover by ref acted on was, just before it
/// acted.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct Placed {
    /// The ref the call named, such as `ref_12`.
    pub(crate) element: String,
    /// The part of its box inside the viewport.
    pub(crate) rect: BrowserRect,
    pub(crate) viewport: BrowserViewport,
}

/// `metadata` naming `tab` as the one the call acted on, and where the
/// element it acted on by ref was, if it did.
#[cfg_attr(not(feature = "browser"), allow(dead_code))]
pub(crate) fn acted_on(metadata: ToolMetadata, tab: &str, placed: Option<&Placed>) -> ToolMetadata {
    let metadata = metadata.asset(ToolAsset::new(TAB_MEDIA_TYPE, tab.as_bytes().to_vec()));
    match placed.map(serde_json::to_vec) {
        Some(Ok(placed)) => metadata.asset(ToolAsset::new(ELEMENT_MEDIA_TYPE, placed)),
        // A `Placed` always serializes; without one there is none to show.
        Some(Err(_)) | None => metadata,
    }
}

/// The tab `metadata` names, if a browser call acted on one, then the
/// element it acted on there by ref, if it did.
pub(crate) fn shown_tab(metadata: &ToolMetadata) -> Vec<ToolContent> {
    let asset = |media_type: &str| {
        metadata
            .assets()
            .iter()
            .find(|asset| asset.media_type() == media_type)
            .map(ToolAsset::bytes)
    };
    let Some(tab) = asset(TAB_MEDIA_TYPE).and_then(|tab| String::from_utf8(tab.to_vec()).ok())
    else {
        return Vec::new();
    };
    let element = asset(ELEMENT_MEDIA_TYPE)
        .and_then(|placed| serde_json::from_slice::<Placed>(placed).ok())
        .map(|placed| {
            ToolContent::BrowserElement(BrowserElement::new(
                tab.clone(),
                placed.element,
                placed.rect,
                placed.viewport,
            ))
        });
    std::iter::once(ToolContent::Browser { tab })
        .chain(element)
        .collect()
}