rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
use pretty_assertions::assert_eq;

use futures_util::{future::BoxFuture, FutureExt};

use super::{
    super::{
        agent_activity::{AgentActivity, CallRunning},
        budget::{
            test_support::{answer, Turn},
            Lending,
        },
        idle_wake::IdleWatch,
    },
    idle_delivery, of_sources, TurnDelivery,
};
use crate::{
    acp_runtime::agent_tools::Readied,
    app::{
        agent_concurrency::RuntimePermits,
        background_delivery::{BackgroundDelivery, BackgroundSources},
        session_runtime::{BackgroundWait, ChildAgents, IdleTurns},
        subagent_manager::SubagentManager,
    },
    cli_runtime::parent_messages::Delivered,
    tools::workflow_tracker::{WorkflowFinishedSnapshot, WorkflowRunTracker},
};

const SESSION_ID: &str = "acp-background-fixture";

fn manager(root: &std::path::Path) -> SubagentManager {
    SubagentManager::new(
        crate::config::Config::default(),
        root.join("config.toml"),
        root.to_path_buf(),
        crate::app::subagent_pool::SubagentPool::Own,
    )
}

fn sources<'a>(
    manager: &'a SubagentManager,
    workflows: &'a WorkflowRunTracker,
) -> BackgroundSources<'a> {
    BackgroundSources {
        subagents: Some(manager),
        processes: None,
        workflows,
        surfaces: None,
        pull_requests: None,
        peer_sessions: None,
        answers: None,
    }
}

/// Registers workflow run `run` to the fixture session, finished when
/// `finished`.
fn workflow(workflows: &WorkflowRunTracker, run: &str, finished: bool) {
    assert!(workflows.register_start(run, "fixture", "digest", Some(SESSION_ID.into())));
    if finished {
        workflows.mark_finished(
            run,
            WorkflowFinishedSnapshot {
                lifecycle: "completed".into(),
                outcome: Some("success".into()),
                nodes: Vec::new(),
                error: None,
                outputs: Vec::new(),
            },
        );
    }
}

/// What the run does with the results a turn's prompt carries.
#[derive(Clone, Copy, Debug)]
enum Run {
    /// It sent the prompt, so the results went with it.
    SentThePrompt,
    /// It ended before it sent the prompt, as one whose agent failed to
    /// start does.
    EndedFirst,
}

// Covers: results the next turn's prompt carries are committed once the
// run delivered them, even when the turn ends before the delivery pump
// heard the receipt, and put back for the next turn when the run never
// sent them. Kills: `TurnDelivery::finish` dropping a delivered batch
// uncommitted (the agent gets the same result again next turn) or
// committing one the run never delivered (the agent never gets it).
// Owner: daemon ACP background delivery (commit points).
#[tokio::test]
async fn a_turn_commits_only_the_results_its_run_delivered() {
    let mut seen = Vec::new();
    for run in [Run::SentThePrompt, Run::EndedFirst] {
        let root = tempfile::tempdir().unwrap();
        let manager = manager(root.path());
        let workflows = WorkflowRunTracker::new();
        workflow(&workflows, "wf-1", /*finished*/ true);
        let delivery =
            BackgroundDelivery::bind(SESSION_ID.to_owned(), sources(&manager, &workflows), None);

        let (turn, mailbox) = TurnDelivery::start(delivery, AgentActivity::default());
        let carried = mailbox.prompt_results.is_some();
        match run {
            Run::SentThePrompt => {
                let shown = mailbox
                    .prompt_results
                    .map(|results| results.settle(Delivered::NextTurn));
                assert!(shown.is_some_and(|shown| !shown.is_empty()), "{run:?}");
            }
            Run::EndedFirst => drop(mailbox),
        }
        let held = turn.finish();
        let mut next =
            BackgroundDelivery::bind(SESSION_ID.to_owned(), sources(&manager, &workflows), held);
        let left = {
            let lock = crate::app::notification_delivery::lock();
            next.collect(&lock)
        };
        seen.push((carried, left.has_results()));
    }

    // (the prompt carried them, the next turn finds them)
    assert_eq!(seen, vec![(true, false), (true, true)]);
}

/// What keeps the served tools busy while a result lands.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Busy {
    /// A served call runs, a parked one included.
    CallRuns,
    /// One of the agent's requests waits for its answer to go back, its
    /// call already ended: it waits in line for the slot its turn lent,
    /// which another run took.
    AnswerWaits,
}

/// What keeps the served tools busy, until it ends ([`Busy`]).
enum Busying {
    Call(CallRunning),
    Answer {
        /// The run that took the turn's lent slot.
        other: RuntimePermits,
        /// The answer, waiting in line for the slot.
        answer: BoxFuture<'static, Readied>,
    },
}

// Covers: a result that lands while the served tools are busy is not sent
// into the turn until they are not, and is sent once they are, with no
// other wake: while a served call runs, and while a request's answer, its
// call ended, waits in line for the slot its lent turn takes back
// (`ModelSlot::request` on a turn that lent its slot).
// Kills: the pump collecting mid-call (`process poll` or `agents status`
// returns the result and the pump steers it in too); `ModelSlot::request`
// dropping `pending` with `blocking`, before the retake, or
// `served_tools_busy` reading `requests` for `answers` (the answer-waits
// row: a process-exit notice steered in reaches the agent ahead of the
// call's own answer); the pump never looking again once the tools are idle
// (the result waits for the next turn).
// Owner: daemon ACP background delivery (mid-turn gate on served tools).
#[tokio::test]
async fn a_turn_is_sent_nothing_while_the_served_tools_are_busy() {
    let cases = [Busy::CallRuns, Busy::AnswerWaits];
    let mut seen = Vec::new();
    for busy in cases {
        let root = tempfile::tempdir().unwrap();
        let manager = manager(root.path());
        let workflows = WorkflowRunTracker::new();
        let (budget_turn, budgeted) = Turn::admitted().await;
        budget_turn.start_child();
        let lending = budget_turn.run(budgeted, Lending::WhileAgentBlocked);
        tokio::pin!(lending);
        let activity = budget_turn.model.activity();
        let delivery =
            BackgroundDelivery::bind(SESSION_ID.to_owned(), sources(&manager, &workflows), None);
        let (mut turn, mut mailbox) = TurnDelivery::start(delivery, activity.clone());

        let busying = match busy {
            Busy::CallRuns => Busying::Call(activity.call_running()),
            Busy::AnswerWaits => {
                let request = budget_turn.request();
                // The turn lends its slot to the agent's wait.
                assert!(lending.as_mut().now_or_never().is_none());
                let other = budget_turn.take_lent_slot();
                let mut answer = answer(request);
                assert!(answer.as_mut().now_or_never().is_none());
                Busying::Answer { other, answer }
            }
        };
        workflow(&workflows, "wf-1", /*finished*/ true);
        let mut pump = Box::pin(turn.deliver());
        // Each poll runs the pump until it waits.
        let pumping = pump.as_mut().now_or_never().is_none();
        let sent_while_busy = mailbox.inbox.recv().now_or_never().is_some();
        match busying {
            Busying::Call(running) => drop(running),
            Busying::Answer { other, mut answer } => {
                drop(other);
                assert_eq!(answer.as_mut().now_or_never(), Some(Readied::Ready));
            }
        }
        let still_pumping = pump.as_mut().now_or_never().is_none();
        let sent_after = mailbox.inbox.recv().now_or_never().flatten().is_some();
        seen.push((busy, pumping, sent_while_busy, still_pumping, sent_after));
    }

    assert_eq!(
        seen,
        cases.map(|busy| (busy, true, false, true, true)).to_vec()
    );
}

// Covers: a session an agent of another runtime runs is woken for its
// background results where a Rho session opened the same way would be
// woken by the daemon, and not where a T3 Code client's own threads would
// wake that Rho session (`HostWakes`), a waker no agent of another
// runtime's session has: only a woken session gets an idle watcher, and
// waits on a finished result, which keeps it active until a turn takes it.
// Kills: the T3 arm mapped to a daemon wake (a watcher starts turns the
// client never asked for), and a woken session's background waiting as
// `HoldPrompt` (no watcher, so a result waits for a prompt).
// Owner: daemon ACP background delivery (idle wake gate).
#[test]
fn only_a_session_whose_client_takes_daemon_turns_is_woken_for_a_result() {
    let cases = [
        (ChildAgents::InProcess, IdleTurns::Host),
        (ChildAgents::HostThreads, IdleTurns::Host),
    ];
    let mut seen = Vec::new();
    for (children, idle_turns) in cases {
        let root = tempfile::tempdir().unwrap();
        let manager = manager(root.path());
        let workflows = WorkflowRunTracker::new();
        workflow(&workflows, "wf-1", /*finished*/ true);
        let idle = idle_delivery(BackgroundWait::of(children, idle_turns));
        let background = of_sources(SESSION_ID.to_owned(), idle, sources(&manager, &workflows));

        seen.push((
            IdleWatch::for_wait(background.wait()).is_some(),
            background.awaited().is_some_and(|work| work.has_result()),
        ));
    }

    // (watched, waits on the finished result)
    assert_eq!(seen, vec![(true, true), (false, false)]);
}