rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! The control worker's reads: requests that change nothing, so they go
//! at once rather than one after another.

use std::future::Future;

use futures_util::{stream::FuturesUnordered, StreamExt};

use rho_protocol::{
    methods::{SessionInspect, SessionMcp, SessionProcesses},
    ProcessOutputParams, SessionInspectParams, SessionMcpParams, SessionProcessesParams,
    SessionReport,
};
use tokio::sync::{mpsc, watch};

use super::{jobs_follow::JobsFollow, on_attachment, report_answer, Change, Control, Target, LOST};
use crate::{app::daemon_client::Daemon, tui::daemon_events::DaemonView};

/// A control request that only reads; its answer arrives as a view.
#[derive(Debug, PartialEq)]
pub(super) enum Read {
    Mcp,
    Jobs,
    /// The session's processes, and the output named, if any.
    Processes(Option<ProcessOutputParams>),
    Inspect(SessionReport),
}

impl Read {
    /// Sends this read where `target` says, and its answer to `views`; a
    /// job read is answered from `jobs` while it follows the list.
    pub(super) async fn answer(
        self,
        mut target: watch::Receiver<Target>,
        daemon: &Daemon,
        jobs: &JobsFollow,
        views: &mpsc::UnboundedSender<DaemonView>,
    ) {
        let view = match self {
            Self::Mcp => {
                let answer = on_attachment(&mut target, |link, session| async move {
                    link.request::<SessionMcp>(&SessionMcpParams { session })
                        .await
                })
                .await;
                DaemonView::McpInventory(match answer {
                    Some((_, answer)) => answer
                        .map(Box::new)
                        .map_err(|error| format!("could not read session MCP inventory: {error}")),
                    None => Err(LOST.to_owned()),
                })
            }
            Self::Jobs => jobs.read(target, daemon).await,
            Self::Processes(output) => {
                let answer = on_attachment(&mut target, |link, session| {
                    let output = output.clone();
                    async move {
                        link.request::<SessionProcesses>(&SessionProcessesParams {
                            session,
                            output,
                        })
                        .await
                    }
                })
                .await;
                DaemonView::Processes {
                    asked: output,
                    result: match answer {
                        Some((_, answer)) => answer.map_err(|error| error.to_string()),
                        None => Err(LOST.to_owned()),
                    },
                }
            }
            Self::Inspect(report) => {
                let answer = on_attachment(&mut target, |link, session| async move {
                    link.request::<SessionInspect>(&SessionInspectParams { session, report })
                        .await
                })
                .await;
                DaemonView::Report {
                    report,
                    result: report_answer(answer),
                }
            }
        };
        let _ = views.send(view);
    }
}

/// The control worker's reads under way, `F` each one's answer.
pub(super) struct Reads<F> {
    reading: FuturesUnordered<F>,
}

impl<F: Future<Output = ()>> Reads<F> {
    pub(super) fn new() -> Self {
        Self {
            reading: FuturesUnordered::new(),
        }
    }

    /// The next change `requests` holds, once every read sent before it
    /// is answered; `None` once `requests` closed. Each read on the way
    /// goes at once, through `start`, beside those still unanswered.
    pub(super) async fn next_change(
        &mut self,
        requests: &mut mpsc::UnboundedReceiver<Control>,
        mut start: impl FnMut(Read) -> F,
    ) -> Option<Change> {
        loop {
            tokio::select! {
                request = requests.recv() => match request? {
                    Control::Read(read) => self.reading.push(start(read)),
                    Control::Change(change) => {
                        while self.reading.next().await.is_some() {}
                        return Some(change);
                    }
                },
                Some(()) = self.reading.next(), if !self.reading.is_empty() => {}
            }
        }
    }
}

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