rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
use std::{path::Path, time::Duration};

use pretty_assertions::assert_eq;
use tokio::sync::watch;

use super::{
    super::pull_request_wake::{watch_for_tests, PullRequestWake},
    *,
};
use crate::{
    app::{
        agent_executor::AgentRunHandle, pull_requests::ScriptedForge, subagent_pool::SubagentPool,
    },
    subagent::{RunState, RunStatus},
    tools::process::{KeepWarm, ProcessLimits, ProcessRole},
};

/// A command that outlives every wait here, in the shell of either platform.
const LONG_RUNNING_COMMAND: &str = "sleep 300";

/// Bounds each wait on a real process exit; a hang fails.
const TEST_WAIT: Duration = Duration::from_secs(10);

const SESSION: &str = "parent";

/// What one session started.
#[derive(Clone, Copy, Debug)]
enum Work {
    Nothing,
    LiveTask,
    ExitedTask,
    LiveService,
    ExitedService,
    RunningSubagent,
    FinishedSubagent,
    /// A watched pull request, with no news yet.
    QuietWatch,
    /// A watched pull request whose check failed since.
    PullRequestNews,
}

const TASK: ProcessRole = ProcessRole::Task {
    keep_warm: KeepWarm::Off,
};

/// What [`AwaitedWork`] says of a session's work.
#[derive(Debug, PartialEq)]
struct Awaited {
    outstanding: bool,
    has_result: bool,
    running: bool,
}

/// A session that started `work`, its daemon turns delivering its
/// subagents; its process manager; and what keeps a running subagent
/// running.
async fn started(
    work: Work,
    root: &Path,
) -> (AwaitedWork, ProcessManager, Option<watch::Sender<bool>>) {
    let started = started_waiting(BackgroundWait::HostTurns, work, root).await;
    let awaited = started
        .awaited
        .expect("a session the daemon wakes awaits work");
    (awaited, started.processes, started.running)
}

/// What [`started_waiting`] started.
struct Started {
    /// What the session waits on; `None` for one that waits on nothing.
    awaited: Option<AwaitedWork>,
    processes: ProcessManager,
    /// What keeps a running subagent running.
    running: Option<watch::Sender<bool>>,
    /// The work as the session's clients see it, for one live process or
    /// running subagent.
    item: Option<wire::BackgroundItem>,
}

/// A session that waits for its work as `wait` and started `work`.
async fn started_waiting(wait: BackgroundWait, work: Work, root: &Path) -> Started {
    let processes = ProcessManager::new(ProcessLimits::default());
    let subagents = SubagentManager::new(
        crate::config::Config::default(),
        root.join("config.toml"),
        root.to_path_buf(),
        SubagentPool::Own,
    );
    let mut running = None;
    let mut item = None;
    let forge = ScriptedForge::new();
    let pull_requests = PullRequestWake::open(root, forge.clone());
    let inbox = pull_requests.inbox(&rho_sdk::SessionId::from_string(SESSION).unwrap(), root);
    match work {
        Work::Nothing => {}
        Work::QuietWatch => watch_for_tests(&forge, &inbox).await,
        Work::PullRequestNews => {
            watch_for_tests(&forge, &inbox).await;
            pull_requests
                .fail_checks_for_tests(&forge, &["ci"], 1)
                .await;
        }
        Work::LiveTask => {
            let id = start(&processes, root, TASK).await;
            item = Some(wire::BackgroundItem::Process { id });
        }
        Work::LiveService => {
            let id = start(&processes, root, ProcessRole::Service).await;
            item = Some(wire::BackgroundItem::Process { id });
        }
        Work::ExitedTask => exit(&processes, &start(&processes, root, TASK).await).await,
        Work::ExitedService => {
            let id = start(&processes, root, ProcessRole::Service).await;
            exit(&processes, &id).await;
        }
        Work::RunningSubagent => {
            let (_status, status) = watch::channel(RunStatus {
                state: RunState::Running,
                ..Default::default()
            });
            let (completion, completion_rx) = watch::channel(false);
            subagents.insert_handle_for_test(
                "abc123",
                SESSION,
                AgentRunHandle::controlled_for_test(
                    status,
                    completion_rx,
                    rho_tools::cancellation::RunCancellation::new(),
                ),
            );
            running = Some(completion);
            item = Some(wire::BackgroundItem::Subagent {
                run: "abc123".into(),
                session: None,
            });
        }
        Work::FinishedSubagent => subagents.insert_completed_status_for_test(
            "abc123",
            SESSION,
            RunStatus {
                state: RunState::Ok,
                ..Default::default()
            },
        ),
    }
    let awaited = AwaitedWork::new(
        wait,
        SESSION.into(),
        WorkflowRunTracker::new(),
        Sources {
            processes: Some(processes.clone()),
            subagents: Some(subagents),
            pull_requests: Some(inbox),
            ..Sources::default()
        },
    );
    Started {
        awaited,
        processes,
        running,
        item,
    }
}

/// Starts a long-running process as `role` in `root`; returns its id.
async fn start(processes: &ProcessManager, root: &Path, role: ProcessRole) -> String {
    processes
        .start_as(LONG_RUNNING_COMMAND.into(), root, None, role)
        .await
        .unwrap()
        .process_id
}

/// Stops process `id` and returns once it exited.
async fn exit(processes: &ProcessManager, id: &str) {
    let exited = processes.notified_owned();
    processes.stop(id, Duration::ZERO).await.unwrap();
    tokio::time::timeout(TEST_WAIT, exited).await.unwrap();
}

// Covers: a task or subagent the session started is awaited until a turn
// takes its result, and is a result once it finished; a service, live or
// exited, is neither, so it never wakes the idle session nor keeps it from
// settling; and work counts as running exactly while it may still give a
// result, which a waker that gave up relies on. A watched pull request is
// never running work, so a quiet watch keeps nothing active, and its news
// is a result until a turn takes it. Owner: daemon awaited work.
#[tokio::test]
async fn tasks_and_subagents_are_awaited_and_services_are_not() {
    let awaited = |outstanding, has_result, running| Awaited {
        outstanding,
        has_result,
        running,
    };
    let cases = [
        (Work::Nothing, awaited(false, false, false)),
        (Work::LiveTask, awaited(true, false, true)),
        (Work::ExitedTask, awaited(true, true, false)),
        (Work::LiveService, awaited(false, false, false)),
        (Work::ExitedService, awaited(false, false, false)),
        (Work::RunningSubagent, awaited(true, false, true)),
        (Work::FinishedSubagent, awaited(true, true, false)),
        (Work::QuietWatch, awaited(false, false, false)),
        (Work::PullRequestNews, awaited(true, true, false)),
    ];
    for (work, expected) in cases {
        let root = tempfile::tempdir().unwrap();
        let (work_of, processes, _running) = started(work, root.path()).await;
        assert_eq!(
            Awaited {
                outstanding: work_of.outstanding(),
                has_result: work_of.has_result(),
                running: work_of.running(),
            },
            expected,
            "{work:?}"
        );
        processes.shutdown().await;
    }
}

// Covers: the background list says a session waits on a task and a
// subagent its daemon turns deliver, never on a service, and on nothing of
// a session whose prompts hold until their work finishes or, for a
// subagent, whose host runs its children; so a client that shows the
// session as waiting agrees with when it settles. Owner: daemon awaited
// work.
#[tokio::test]
async fn each_listed_item_is_awaited_as_its_session_waits() {
    let cases = [
        (BackgroundWait::HostTurns, Work::LiveTask, Some(true)),
        (BackgroundWait::HostTurns, Work::LiveService, Some(false)),
        (BackgroundWait::HostTurns, Work::RunningSubagent, Some(true)),
        (BackgroundWait::HostWakes, Work::LiveTask, Some(true)),
        (
            BackgroundWait::HostWakes,
            Work::RunningSubagent,
            Some(false),
        ),
        (BackgroundWait::HoldPrompt, Work::LiveTask, Some(false)),
    ];
    for (wait, work, expected) in cases {
        let root = tempfile::tempdir().unwrap();
        let started = started_waiting(wait, work, root.path()).await;
        let item = started.item.expect("the work has an item");
        assert_eq!(
            awaits(started.awaited.as_ref(), &item),
            expected,
            "{work:?} in a session waiting as {wait:?}"
        );
        started.processes.shutdown().await;
    }
}