rho-coding-agent 3.10.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Element refs: the `ref_N` names `read_page` and `find` give a tab's
//! elements, which later calls pass back to act on one.
//!
//! A ref keeps its number for as long as the document that gave it does, so
//! a second read names an element as the first did. A new document starts
//! the numbering over: its node ids can repeat the old document's, since it
//! may render in a new process, so an old ref must not reach a new node.

use rho_browser::cdp::BackendNodeId;
use std::collections::HashMap;

/// One tab's refs, for the document its loader names.
#[derive(Debug, Default)]
pub(super) struct Refs {
    loader: String,
    numbers: HashMap<BackendNodeId, usize>,
    /// The node of each ref, by its number less one.
    nodes: Vec<BackendNodeId>,
}

/// A ref the tab's current document did not give.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct StaleRef(pub(super) String);

impl std::fmt::Display for StaleRef {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{} is stale or not found on the current page. Re-read the page to get fresh references.",
            self.0
        )
    }
}

impl Refs {
    /// Forgets every ref when the tab's document is no longer the one of
    /// `loader`.
    pub(super) fn follow(&mut self, loader: &str) {
        if self.loader != loader {
            *self = Self {
                loader: loader.to_owned(),
                ..Self::default()
            };
        }
    }

    /// The ref of `node`, giving it the next number the first time.
    pub(super) fn name(&mut self, node: BackendNodeId) -> String {
        let number = *self.numbers.entry(node).or_insert_with(|| {
            self.nodes.push(node);
            self.nodes.len()
        });
        format!("ref_{number}")
    }

    /// The node `name`, such as `ref_3`, names in the document of `loader`.
    pub(super) fn node(&self, name: &str, loader: &str) -> Result<BackendNodeId, StaleRef> {
        let stale = || StaleRef(name.to_owned());
        if self.loader != loader {
            return Err(stale());
        }
        let number = name
            .strip_prefix("ref_")
            .and_then(|number| number.parse::<usize>().ok())
            .ok_or_else(stale)?;
        number
            .checked_sub(1)
            .and_then(|index| self.nodes.get(index))
            .copied()
            .ok_or_else(stale)
    }
}

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