rho-coding-agent 3.7.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The output of a session's background processes, which its pump reads
//! from the daemon (`rho/session/processes`) for a host that shows it
//! (`HostFeatures::display_terminals`), as long as the host is told the
//! processes run. The daemon pushes no output, so the pump reads it every
//! [`READ_EVERY`], and once more as a process stops, so the host has all
//! of it before it hears the process ended.

use std::{collections::BTreeMap, sync::Arc, time::Duration};

use agent_client_protocol::v1::schema::SessionId as AcpSessionId;
use rho_protocol::{BackgroundItem, BackgroundWork, ProcessOutput, SessionId};
use tokio::time::{interval, Interval, MissedTickBehavior};

use super::Attacher;
use crate::app::acp::{inputs::InputContext, AcpClientPort};

/// How long the pump waits between two reads of a followed process's
/// output: what the host's terminal lags behind the process at most.
/// Measured on a debug build: at this interval a followed process's 120
/// reads in 30 s cost the daemon 0.05 s of CPU over idle (about 0.4 ms a
/// read, 0.2% of a core), each answered within 1.4 ms (p99), so the 16
/// processes a session may run (`ProcessLimits`) cost under 3%. Rho's TUI
/// reads the same output for its process peek every 500 ms
/// (`tui::daemon_jobs::RAIL_POLL`).
pub(super) const READ_EVERY: Duration = Duration::from_millis(250);

/// The processes a session's pump follows, by id, each with the cursor its
/// next read starts at, and what it reads them with. Inert for a host that
/// shows no output: it follows nothing.
pub(super) struct Outputs {
    reader: Option<Reader>,
    followed: BTreeMap<String, u64>,
    /// When the next read is due, while any process is followed.
    reads: Option<Interval>,
}

/// What a pump reads output with and tells it to.
struct Reader {
    attacher: Arc<dyn Attacher>,
    port: Arc<dyn AcpClientPort>,
    session: SessionId,
    acp_id: AcpSessionId,
}

impl Reader {
    async fn read(&self, process: &str, from: u64) -> Option<ProcessOutput> {
        self.attacher
            .process_output(&self.session, process, from)
            .await
    }

    /// Tells the host what `output` adds, and returns where the next read
    /// starts.
    fn tell(&self, process: &str, output: &ProcessOutput) -> u64 {
        let text = text(output);
        if !text.is_empty() {
            self.port.terminal_output(&self.acp_id, process, &text);
        }
        output.next_cursor
    }
}

impl Outputs {
    /// The outputs of `context`'s session, read with `attacher`, for a host
    /// that shows them ([`HostFeatures::display_terminals`]).
    pub(super) fn new(context: &InputContext, attacher: &Arc<dyn Attacher>) -> Self {
        let reader = context.features.display_terminals().then(|| Reader {
            attacher: Arc::clone(attacher),
            port: Arc::clone(&context.port),
            session: context.session.clone(),
            acp_id: context.acp_id.clone(),
        });
        Self {
            reader,
            followed: BTreeMap::new(),
            reads: None,
        }
    }

    /// Resolves when the next read is due; never while nothing is
    /// followed.
    pub(super) async fn due(&mut self) {
        match &mut self.reads {
            Some(reads) => {
                reads.tick().await;
            }
            None => std::future::pending().await,
        }
    }

    /// Reads on from where each followed process's last read ended.
    pub(super) async fn read(&mut self) {
        let Some(reader) = &self.reader else { return };
        for (process, cursor) in &mut self.followed {
            if let Some(output) = reader.read(process, *cursor).await {
                *cursor = reader.tell(process, &output);
            }
        }
    }

    /// Follows the processes the host is now told run in `current`, from
    /// their start, and stops following the others once it has told the
    /// host the rest of their output. Called before the host hears of the
    /// change, so a stopped process's output comes before its exit.
    pub(super) async fn changed(&mut self, current: &[BackgroundWork]) {
        let Some(reader) = &self.reader else { return };
        let running = running(current);
        let stopped: Vec<_> = self
            .followed
            .keys()
            .filter(|process| !running.contains(&process.as_str()))
            .cloned()
            .collect();
        for process in stopped {
            if let Some(cursor) = self.followed.remove(&process) {
                if let Some(output) = reader.read(&process, cursor).await {
                    reader.tell(&process, &output);
                }
            }
        }
        for process in running {
            self.followed.entry(process.to_owned()).or_insert(0);
        }
        self.schedule();
    }

    /// The retained output of each process `current` runs, which a host
    /// that resumes the session is sent whole, replacing what it kept. The
    /// process is followed on from where that output ends. Empty for a
    /// host that shows no output.
    pub(super) async fn snapshot(
        &mut self,
        current: &[BackgroundWork],
    ) -> BTreeMap<String, String> {
        self.followed.clear();
        let mut snapshots = BTreeMap::new();
        if let Some(reader) = &self.reader {
            for process in running(current) {
                // One the daemon did not answer for starts over empty, and
                // its output follows from the start.
                let (text, next) = match reader.read(process, 0).await {
                    Some(output) => (text(&output), output.next_cursor),
                    None => (String::new(), 0),
                };
                snapshots.insert(process.to_owned(), text);
                self.followed.insert(process.to_owned(), next);
            }
        }
        self.schedule();
        snapshots
    }

    /// Stops following every process: the session is gone.
    pub(super) fn stop(&mut self) {
        self.followed.clear();
        self.schedule();
    }

    /// Reads on a schedule while any process is followed.
    fn schedule(&mut self) {
        if self.followed.is_empty() {
            self.reads = None;
        } else if self.reads.is_none() {
            let mut reads = interval(READ_EVERY);
            reads.set_missed_tick_behavior(MissedTickBehavior::Delay);
            self.reads = Some(reads);
        }
    }
}

/// The text of `output`'s chunks, stdout's and stderr's, in cursor order.
fn text(output: &ProcessOutput) -> String {
    output.chunks.iter().map(|chunk| &*chunk.text).collect()
}

/// The ids of the processes `work` lists running.
fn running(work: &[BackgroundWork]) -> Vec<&str> {
    work.iter()
        .filter(|work| work.status.is_running())
        .filter_map(|work| match &work.item {
            BackgroundItem::Process { id } => Some(id.as_str()),
            _ => None,
        })
        .collect()
}