rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Clients watching a session's tabs: each watch is a screencast of one
//! tab, relayed to the connection that started it and paced by that
//! client's acks (`rho/browser/watch`, `frame_ack`, `unwatch`).
//!
//! A watch holds the session's browser context, so the browser stays open
//! while anyone watches, as it does while a browser call runs. It ends when
//! its client unwatches or leaves, when the tab closes, or when the browser
//! goes away.
//!
//! While a person drives, each watch of the tab under their pointer also
//! sends the page's cursor there, as the session's [`Pointer`] changes.

use super::wire_viewport;
use rho_browser::cdp::TargetId;
use rho_browser::manager::Context;
use rho_browser::screencast::{Fit, Frame, FrameAck, Screencast};
use rho_browser::tab::Viewport;
use rho_browser::CdpError;
use rho_protocol::{
    browser_frames, BrowserCursor, BrowserCursorParams, BrowserFrameParams, BrowserFrameSender,
    BrowserFrames, BrowserWatchId, BrowserWatchParams, BrowserWatchResponse, FrameRefused,
};
use std::collections::HashMap;
use std::sync::{Arc, Mutex, PoisonError};
use tokio::sync::watch;

/// The JPEG quality frames are sent at. Across idle, animated and
/// scrolling pages at 800×900, q60 frames measured 4.4 to 150 KB and q80
/// ones 7.3 to 200 KB, so q60 keeps a scrolling page near 3 MB/s rather
/// than 3.7 (chrome-headless-shell 158).
const FRAME_QUALITY: u8 = 60;

/// How many frames a watch sends ahead of its client's acks.
const IN_FLIGHT: u64 = BrowserWatchParams::FRAMES_IN_FLIGHT as u64;

/// The page's cursor under a person's pointer, and the tab it is over.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Pointer {
    pub(crate) target: TargetId,
    pub(crate) cursor: BrowserCursor,
}

/// The daemon's watches, by id. Each running watch keeps the sender of
/// the last frame its client acked; dropping the sender ends the watch.
#[derive(Default)]
pub(crate) struct Watches {
    acks: Arc<Mutex<HashMap<BrowserWatchId, watch::Sender<u64>>>>,
}

impl Watches {
    /// Starts watching tab `target` of `context`, its frames scaled to
    /// `fit`, which renders at `viewport` as the watch starts, and the
    /// cursor of the session's `pointer` over it.
    pub(crate) async fn start(
        &self,
        context: Context,
        target: &TargetId,
        fit: Fit,
        viewport: Viewport,
        pointer: watch::Receiver<Option<Pointer>>,
    ) -> Result<(BrowserWatchResponse, BrowserFrames), CdpError> {
        let screencast =
            Screencast::start(context.connection(), target, fit, FRAME_QUALITY).await?;
        let id = BrowserWatchId::new(uuid::Uuid::new_v4().to_string());
        let (acked, acks) = watch::channel(0);
        self.lock().insert(id.clone(), acked);
        let (sender, frames) = browser_frames();
        let watch = Watch {
            id: id.clone(),
            target: target.clone(),
            screencast,
            sender,
            acks,
            pointer,
            _context: context,
        };
        tokio::spawn(watch.run(Arc::clone(&self.acks)));
        Ok((
            BrowserWatchResponse::new(id, wire_viewport(viewport)),
            frames,
        ))
    }

    /// Records that `watch`'s client drew frame `seq` and those before it,
    /// returning whether the watch runs.
    pub(crate) fn ack(&self, watch: &BrowserWatchId, seq: u64) -> bool {
        match self.lock().get(watch) {
            Some(acked) => {
                acked.send_modify(|acked| *acked = (*acked).max(seq));
                true
            }
            None => false,
        }
    }

    /// Ends `watch`, if it runs.
    pub(crate) fn unwatch(&self, watch: &BrowserWatchId) {
        self.lock().remove(watch);
    }

    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<BrowserWatchId, watch::Sender<u64>>> {
        self.acks.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

/// One running watch.
struct Watch {
    id: BrowserWatchId,
    target: TargetId,
    screencast: Screencast,
    sender: BrowserFrameSender,
    acks: watch::Receiver<u64>,
    pointer: watch::Receiver<Option<Pointer>>,
    /// Keeps the browser open while the watch runs.
    _context: Context,
}

impl Watch {
    /// Relays frames until the watch ends, then stops the screencast and
    /// forgets the watch.
    async fn run(mut self, watches: Arc<Mutex<HashMap<BrowserWatchId, watch::Sender<u64>>>>) {
        let mut pacer = Pacer::default();
        // A watch that starts under the pointer shows its cursor at once.
        self.point();
        loop {
            let steps = tokio::select! {
                frame = self.screencast.next() => match frame {
                    Some(frame) => {
                        let ack = frame.ack;
                        pacer.frame(frame, ack)
                    }
                    // The tab closed, or the browser went away.
                    None => break,
                },
                changed = self.acks.changed() => match changed {
                    Ok(()) => pacer.acked(*self.acks.borrow_and_update()),
                    // Unwatched.
                    Err(_) => break,
                },
                // Off once the session is gone; the frames go on. The same
                // cursor goes again only when the pointer came back from
                // another tab, which costs the client nothing.
                Ok(()) = self.pointer.changed() => {
                    self.point();
                    continue;
                }
                () = self.sender.closed() => break,
            };
            if !self.take(steps).await {
                break;
            }
        }
        watches
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .remove(&self.id);
        self.screencast.stop().await;
    }

    /// Sends the cursor of the session's pointer, if it is over this
    /// watch's tab.
    fn point(&mut self) {
        let pointer = self.pointer.borrow_and_update().clone();
        if let Some(pointer) = pointer.filter(|pointer| pointer.target == self.target) {
            self.sender
                .send_cursor(BrowserCursorParams::new(self.id.clone(), pointer.cursor));
        }
    }

    /// Takes `steps`, returning whether the watch goes on.
    async fn take(&self, steps: Vec<Step<Frame, FrameAck>>) -> bool {
        for step in steps {
            match step {
                Step::Send { frame, seq } => {
                    let params = BrowserFrameParams::new(
                        self.id.clone(),
                        seq,
                        "image/jpeg",
                        frame.data,
                        frame.width,
                        frame.height,
                        frame.at,
                    );
                    let params = match frame.viewport {
                        Some(shown) => params.with_viewport(wire_viewport(shown)),
                        None => params,
                    };
                    match self.sender.send(params) {
                        Ok(()) => {}
                        // Unreachable while the pacer holds frames to the
                        // relay's budget; the client's next ack recovers.
                        Err(FrameRefused::Full) => {
                            tracing::warn!(watch = %self.id, seq, "a browser watch's relay was full");
                        }
                        Err(FrameRefused::Closed) => return false,
                    }
                }
                Step::AckBrowser(ack) => {
                    if self.screencast.ack(ack).await.is_err() {
                        return false;
                    }
                }
            }
        }
        true
    }
}

/// What a watch does next.
#[derive(Debug, PartialEq, Eq)]
enum Step<F, A> {
    /// Send `frame` to the client as frame `seq`.
    Send { frame: F, seq: u64 },
    /// Let the browser send one more frame.
    AckBrowser(A),
}

/// Paces a watch: frames go to the client while fewer than [`IN_FLIGHT`]
/// wait for its ack. A frame past that waits in their place, replacing an
/// older one that waited, so the client's next ack brings the newest frame
/// rather than a stale one. The browser's acks wait as long, so it draws
/// no frames nobody will see. Each of them is a credit for one more frame
/// (see [`FrameAck`]), so every frame's ack is sent in the end, a replaced
/// frame's too.
#[derive(Debug)]
struct Pacer<F, A> {
    /// The last frame sent, and the last the client acked.
    sent: u64,
    acked: u64,
    waiting: Option<F>,
    /// The acks of the browser's frames, until it may send more.
    owed: Vec<A>,
}

impl<F, A> Default for Pacer<F, A> {
    fn default() -> Self {
        Self {
            sent: 0,
            acked: 0,
            waiting: None,
            owed: Vec::new(),
        }
    }
}

impl<F, A> Pacer<F, A> {
    /// The browser drew `frame`, which `ack` acks.
    fn frame(&mut self, frame: F, ack: A) -> Vec<Step<F, A>> {
        self.owed.push(ack);
        let mut steps = Vec::new();
        if self.in_flight() < IN_FLIGHT {
            steps.push(self.send(frame));
        } else {
            self.waiting = Some(frame);
        }
        self.release(&mut steps);
        steps
    }

    /// The client acked frame `seq` and those before it.
    fn acked(&mut self, seq: u64) -> Vec<Step<F, A>> {
        // A client cannot ack a frame it was not sent.
        self.acked = self.acked.max(seq.min(self.sent));
        let mut steps = Vec::new();
        if self.in_flight() < IN_FLIGHT {
            if let Some(frame) = self.waiting.take() {
                steps.push(self.send(frame));
            }
        }
        self.release(&mut steps);
        steps
    }

    fn in_flight(&self) -> u64 {
        self.sent - self.acked
    }

    fn send(&mut self, frame: F) -> Step<F, A> {
        self.sent += 1;
        Step::Send {
            frame,
            seq: self.sent,
        }
    }

    /// Acks the browser's frames once the client has room for the next.
    fn release(&mut self, steps: &mut Vec<Step<F, A>>) {
        if self.in_flight() < IN_FLIGHT && self.waiting.is_none() {
            steps.extend(self.owed.drain(..).map(Step::AckBrowser));
        }
    }
}

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