rho-coding-agent 3.10.0

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

use super::{BackgroundDelivery, BackgroundSources, Batch, Notices};
use crate::{
    app::{
        agent_executor::AgentRunHandle,
        subagent_manager::SubagentManager,
        subagent_messaging::{NoticeDelivery, SubagentNotice},
    },
    subagent::{RunState, RunStatus},
    tools::{
        process::{ProcessLimits, ProcessManager},
        workflow_tracker::{WorkflowFinishedSnapshot, WorkflowRunTracker},
    },
};

const SESSION_ID: &str = "delivery-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,
    )
}

/// A child's informational notice to the fixture session.
fn notice(message: &str) -> SubagentNotice {
    SubagentNotice {
        run_id: "abc123".into(),
        agent_id: "fixture".into(),
        parent_session_id: rho_sdk::SessionId::from_string(SESSION_ID).unwrap(),
        message: message.into(),
        delivery: NoticeDelivery::NextTurn,
        acknowledged: Default::default(),
    }
}

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

/// What one look at the delivery finds: the children's notices waiting,
/// whether the first notice was acknowledged, and how many results each
/// source holds, as a fresh collect reserves them (and puts them back).
fn look(delivery: &mut BackgroundDelivery, first: &SubagentNotice) -> (bool, bool, Vec<bool>) {
    let batch = collect(delivery);
    (
        delivery.has_notices(),
        first.is_acknowledged(),
        batch.results_by_source(),
    )
}

/// What `delivery` collects now, under the delivery lock.
fn collect(delivery: &mut BackgroundDelivery) -> Batch {
    let lock = crate::app::notification_delivery::lock();
    delivery.collect(&lock)
}

// Covers: a delivery committed with its notices kept takes its results but
// leaves the children's notices waiting, unacknowledged; one committed with
// them offered acknowledges them, so neither is delivered twice, and a batch
// dropped uncommitted puts its results back for the next delivery. Kills:
// `commit` acknowledging notices it did not offer (the ACP mid-turn pump
// keeps informational notices for the next turn's prompt), `commit` not
// draining offered ones, and a dropped batch losing its results (an ACP turn
// that ends before the agent took a steer).
// Owner: shared Rho/ACP background delivery (collect, render, commit).
#[tokio::test]
async fn commit_takes_the_batch_and_only_the_notices_it_offered() {
    let root = tempfile::tempdir().unwrap();
    let manager = manager(root.path());
    let workflows = WorkflowRunTracker::new();
    let mut delivery = BackgroundDelivery::bind(
        SESSION_ID.to_owned(),
        BackgroundSources {
            subagents: Some(&manager),
            processes: None,
            workflows: &workflows,
            surfaces: None,
            pull_requests: None,
            peer_sessions: None,
        },
        /*held*/ None,
    );
    let first = notice("finding");
    manager.post_notice_for_test(first.clone());
    finish_workflow(&workflows, "wf-1");

    // (notices waiting, first acknowledged, [subagents, workflows] hold results)
    let before = look(&mut delivery, &first);
    let batch = collect(&mut delivery);
    let rendered = delivery.render(&batch).is_some();
    delivery.commit(batch, Notices::Kept);
    let kept = look(&mut delivery, &first);

    finish_workflow(&workflows, "wf-2");
    drop(collect(&mut delivery));
    let put_back = look(&mut delivery, &first);

    let batch = collect(&mut delivery);
    delivery.commit(batch, Notices::Offered);
    let offered = look(&mut delivery, &first);

    assert_eq!(
        (before, rendered, kept, put_back, offered),
        (
            (true, false, vec![false, true]),
            true,
            (true, false, vec![false, false]),
            (true, false, vec![false, true]),
            (false, true, vec![false, false]),
        )
    );
}

// Covers: a held binding carries the children's undelivered notices to the
// next delivery, which renders them, instead of binding afresh and losing
// them; this is what keeps an ACP session's notices between its turns.
// Kills: `bind` ignoring `held`, and `HeldNotices::has_undelivered` missing
// a notice still queued on the binding's channel.
// Owner: shared Rho/ACP notice binding handoff.
#[tokio::test]
async fn held_notices_reach_the_next_delivery() {
    let root = tempfile::tempdir().unwrap();
    let manager = manager(root.path());
    let workflows = WorkflowRunTracker::new();
    let sources = || BackgroundSources {
        subagents: Some(&manager),
        processes: None,
        workflows: &workflows,
        surfaces: None,
        pull_requests: None,
        peer_sessions: None,
    };
    let first = BackgroundDelivery::bind(SESSION_ID.to_owned(), sources(), /*held*/ None);
    let held = first.hold();
    let queued = notice("found it between turns");
    manager.post_notice_for_test(queued.clone());
    let undelivered = held.as_ref().map(super::HeldNotices::has_undelivered);

    let mut next = BackgroundDelivery::bind(SESSION_ID.to_owned(), sources(), held);
    let batch = collect(&mut next);
    let waiting = next.has_notices();
    next.commit(batch, Notices::Offered);

    assert_eq!(
        (undelivered, waiting, queued.is_acknowledged()),
        (Some(true), true, true)
    );
}

/// One piece of a session's background work.
#[derive(Clone, Copy, Debug)]
enum Work {
    Nothing,
    LiveTask,
    /// A task that exited, its result undelivered.
    ExitedTask,
    RunningSubagent,
    /// A subagent that finished, its result undelivered.
    FinishedSubagent,
    LiveWorkflow,
    /// A workflow run that finished, its result undelivered.
    FinishedWorkflow,
}

/// A command that outlives every wait here, in the shell of either platform.
#[cfg(unix)]
const LONG_RUNNING_COMMAND: &str = "sleep 300";
#[cfg(windows)]
const LONG_RUNNING_COMMAND: &str = "Start-Sleep -Seconds 300";

// Covers: live work (a running process, subagent or workflow run) is both
// background work and live work; a finished one's undelivered result is
// background work only, so a host with no idle waker (a daemon session an
// agent of another runtime runs) does not keep the session loaded, or an
// upgrade waiting, on a result no turn will take. Kills: `has_live_work`
// counting a result (an ACP session never unloads) or missing live work
// (an unload kills it), and `has_work` dropping a result (Rho's sessions
// unload with one undelivered).
// Owner: shared Rho/ACP background work predicates (unload, upgrade, delete).
#[tokio::test]
async fn only_running_work_is_live_work() {
    let mut seen = Vec::new();
    for work in [
        Work::Nothing,
        Work::LiveTask,
        Work::ExitedTask,
        Work::RunningSubagent,
        Work::FinishedSubagent,
        Work::LiveWorkflow,
        Work::FinishedWorkflow,
    ] {
        let root = tempfile::tempdir().unwrap();
        let manager = manager(root.path());
        let workflows = WorkflowRunTracker::new();
        let processes = ProcessManager::new(ProcessLimits::default());
        // Keeps a running subagent running.
        let mut _running = None;
        match work {
            Work::Nothing => {}
            Work::LiveTask | Work::ExitedTask => {
                let id = processes
                    .start(LONG_RUNNING_COMMAND.into(), root.path(), None)
                    .await
                    .unwrap()
                    .process_id;
                if matches!(work, Work::ExitedTask) {
                    let exited = processes.notified_owned();
                    processes
                        .stop(&id, std::time::Duration::ZERO)
                        .await
                        .unwrap();
                    exited.await;
                }
            }
            Work::RunningSubagent => {
                let (_status, status) = tokio::sync::watch::channel(RunStatus {
                    state: RunState::Running,
                    ..Default::default()
                });
                let (completion, completion_rx) = tokio::sync::watch::channel(false);
                manager.insert_handle_for_test(
                    "abc123",
                    SESSION_ID,
                    AgentRunHandle::controlled_for_test(
                        status,
                        completion_rx,
                        rho_tools::cancellation::RunCancellation::new(),
                    ),
                );
                _running = Some(completion);
            }
            Work::FinishedSubagent => manager.insert_completed_status_for_test(
                "abc123",
                SESSION_ID,
                RunStatus {
                    state: RunState::Ok,
                    ..Default::default()
                },
            ),
            Work::LiveWorkflow => {
                let started =
                    workflows.register_start("wf-1", "fixture", "digest", Some(SESSION_ID.into()));
                assert!(started);
            }
            Work::FinishedWorkflow => finish_workflow(&workflows, "wf-1"),
        }
        let sources = BackgroundSources {
            subagents: Some(&manager),
            processes: Some(&processes),
            workflows: &workflows,
            surfaces: None,
            pull_requests: None,
            peer_sessions: None,
        };
        seen.push((
            format!("{work:?}"),
            sources.has_work(SESSION_ID),
            sources.has_live_work(SESSION_ID),
        ));
        processes.shutdown().await;
    }

    // (work, has_work, has_live_work)
    let row = |work: &str, has_work, has_live_work| (work.to_owned(), has_work, has_live_work);
    assert_eq!(
        seen,
        vec![
            row("Nothing", false, false),
            row("LiveTask", true, true),
            row("ExitedTask", true, false),
            row("RunningSubagent", true, true),
            row("FinishedSubagent", true, false),
            row("LiveWorkflow", true, true),
            row("FinishedWorkflow", true, false),
        ]
    );
}