rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! A person's input to the session's tabs, with their mouse moves merged.
//!
//! While the pointer keeps moving, the browser takes a move about once a
//! frame: `Input.dispatchMouseEvent` for a move answers after the page's
//! next frame, 16.5 ms apart at 60 Hz (chrome-headless-shell 158). A mouse
//! reports moves faster than that (125 a second and up), and a
//! connection runs its input one request at a time, so unmerged moves
//! queued: a second of moving put a click 0.8 s behind. So a move is
//! answered as soon as it is taken, and the tabs get only the newest move
//! that came while they were still taking one: one waiting move for the
//! session's tabs, as one person drives them with one pointer. Any other
//! input sends the move still waiting first, so a press lands where the
//! pointer last went and nothing else changes order. A merged move that
//! fails, its tab closed meanwhile, goes unreported: it was answered.
//! The page's cursor after each mouse input goes to the watches of its
//! tab ([`SessionBrowser::point`]).

use super::{lock, SessionBrowser};
use crate::browser::drive::{PersonTabs, Refused};
use crate::browser::watch::Pointer;
use rho_protocol::{BrowserCursor, BrowserInput, BrowserMouseAction};
use std::sync::Mutex;

/// The session's merged moves: the one waiting, and one input at a time
/// sent to the tabs.
#[derive(Default)]
pub(super) struct Moves {
    waiting: Mutex<Waiting>,
    /// Held while an input goes to the tabs. Waiters take it in the order
    /// they came, so input waiting behind a move goes next.
    sending: tokio::sync::Mutex<()>,
}

#[derive(Default)]
struct Waiting {
    /// The newest move not yet sent.
    next: Option<WaitingMove>,
    /// Whether a task is sending the waiting moves.
    draining: bool,
}

/// A move taken but not yet sent.
struct WaitingMove {
    tab: String,
    input: BrowserInput,
    /// [`SessionBrowser::takeovers`] when it came: a move that waited past
    /// the person's driving, the agent's turn since or another takeover,
    /// is dropped.
    takeover: u64,
}

impl SessionBrowser {
    /// Sends a person's `input` to tab `tab`: a move once the tabs take
    /// moves again, merged with the moves after it, and anything else
    /// after the move still waiting.
    pub(crate) async fn person_input(
        &self,
        tab: String,
        input: BrowserInput,
    ) -> Result<(), Refused> {
        let tabs = self.driven_by_person()?;
        let takeover = self.takeovers();
        let sent = if is_move(&input) {
            if !self.shows_tab(&tab) {
                return Err(Refused::NoTab(tab));
            }
            self.merge_move(WaitingMove {
                tab,
                input,
                takeover,
            });
            Ok(())
        } else {
            let _sending = self.moves.sending.lock().await;
            let waiting = lock(&self.moves.waiting).next.take();
            if let Some(waiting) = waiting {
                self.send_move(tabs.as_ref(), waiting).await;
            }
            self.send(tabs.as_ref(), tab, input, takeover).await
        };
        self.follow_person();
        sent
    }

    /// Makes `next` the move to send next, and starts sending moves if no
    /// task is.
    fn merge_move(&self, next: WaitingMove) {
        let mut waiting = lock(&self.moves.waiting);
        waiting.next = Some(next);
        if std::mem::replace(&mut waiting.draining, true) {
            return;
        }
        let browser = self.clone();
        tokio::spawn(async move { browser.drain_moves().await });
    }

    /// Sends the waiting moves, one per turn at the tabs, until none waits.
    async fn drain_moves(&self) {
        loop {
            let _sending = self.moves.sending.lock().await;
            let next = {
                let mut waiting = lock(&self.moves.waiting);
                let next = waiting.next.take();
                waiting.draining = next.is_some();
                next
            };
            let Some(next) = next else { return };
            if let Ok(tabs) = self.driven_by_person() {
                self.send_move(tabs.as_ref(), next).await;
            }
        }
    }

    /// Sends a merged move, unless it waited past the takeover it came in.
    /// It was answered when taken, so a failure has no one to tell.
    async fn send_move(&self, tabs: &dyn PersonTabs, waiting: WaitingMove) {
        if waiting.takeover != self.takeovers() {
            return;
        }
        let sent = self
            .send(tabs, waiting.tab, waiting.input, waiting.takeover)
            .await;
        if let Err(refused) = sent {
            tracing::debug!(?refused, "a person's mouse move did not reach the tab");
        }
    }

    /// Sends `input`, which came in takeover `takeover`, to tab `tab`, then
    /// points the tab's watches at the page's cursor there.
    async fn send(
        &self,
        tabs: &dyn PersonTabs,
        tab: String,
        input: BrowserInput,
        takeover: u64,
    ) -> Result<(), Refused> {
        if let Some(cursor) = tabs.input(tab.clone(), input).await? {
            self.point(&tab, takeover, cursor);
        }
        Ok(())
    }

    /// Points the watches of tab `tab` at `cursor`, unless the person of
    /// takeover `takeover` no longer drives. A cursor equal to the
    /// session's pointer wakes no watch.
    fn point(&self, tab: &str, takeover: u64, cursor: BrowserCursor) {
        // Held across the check and the send, so a hand-over's reset never
        // lands between them to be overwritten by a cursor of its turn.
        let control = lock(&self.control);
        if control.person.is_none() || control.takeovers != takeover {
            return;
        }
        let Some(target) = self.target_of(tab) else {
            return;
        };
        let next = Some(Pointer { target, cursor });
        self.pointer.send_if_modified(|pointer| {
            let changed = *pointer != next;
            *pointer = next;
            changed
        });
    }
}

/// Whether `input` only moves the pointer. Any other input, an action a
/// newer protocol adds included, keeps its place.
fn is_move(input: &BrowserInput) -> bool {
    matches!(
        input,
        BrowserInput::Mouse {
            action: BrowserMouseAction::Moved,
            ..
        }
    )
}

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