rho-coding-agent 3.7.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
use std::{collections::BTreeMap, path::PathBuf};

use pretty_assertions::assert_eq;
use rho_protocol::{BackgroundItem, BackgroundStatus, BackgroundWork, SessionId};
use serde_json::{json, Value};

use super::{announcements, changes, subagent, terminal, tool_call};

/// An absolute session directory on every platform, as v2's `cwd` must be.
fn workspace() -> PathBuf {
    std::env::temp_dir().join("work")
}

fn process(id: &str, status: BackgroundStatus, exit_code: Option<i32>) -> BackgroundWork {
    BackgroundWork {
        item: BackgroundItem::Process { id: id.to_owned() },
        title: format!("run {id}"),
        status,
        exit_code,
    }
}

fn workflow(run: &str, status: BackgroundStatus) -> BackgroundWork {
    BackgroundWork {
        item: BackgroundItem::Workflow {
            run: run.to_owned(),
        },
        title: "build".to_owned(),
        status,
        exit_code: None,
    }
}

fn subagent_work(run: &str, session: Option<&str>, status: BackgroundStatus) -> BackgroundWork {
    BackgroundWork {
        item: BackgroundItem::Subagent {
            run: run.to_owned(),
            session: session.map(SessionId::new),
        },
        title: "review".to_owned(),
        status,
        exit_code: None,
    }
}

// Covers: a host must hear of each piece of work as its v2 entity, with the
// capability to cancel it, before a state lists it, and of how it ended,
// with that capability withdrawn, before a state drops it; work it never
// saw running is never announced, and work that left unseen ends as far as
// the host can tell.
// Owner: ACP v2 background mapping
#[test]
fn work_is_announced_on_start_and_finalized_on_stop() {
    use BackgroundStatus::{Cancelled, Completed, Failed, Running};
    let cancel = json!({"cancel": {}});
    let cases = [
        (
            "a process that starts is a cancellable terminal in the workspace",
            vec![process("a", Running, None)],
            vec![process("a", Running, None), process("b", Running, None)],
            vec![json!({
                "sessionUpdate": "terminal_update", "terminalId": "b", "command": "run b",
                "cwd": workspace(), "capabilities": cancel,
            })],
        ),
        (
            "an exit finalizes the terminal with its code",
            vec![process("a", Running, None)],
            vec![process("a", Completed, Some(3))],
            vec![json!({
                "sessionUpdate": "terminal_update", "terminalId": "a",
                "exitStatus": {"exitCode": 3}, "capabilities": null,
            })],
        ),
        (
            "a process that left unseen exited with no known status",
            vec![process("a", Running, None)],
            vec![],
            vec![json!({
                "sessionUpdate": "terminal_update", "terminalId": "a", "exitStatus": {},
                "capabilities": null,
            })],
        ),
        (
            "a workflow run is a tool call rho starts, then gives its final status",
            vec![workflow("w", Running)],
            vec![workflow("w", Cancelled), workflow("x", Running)],
            vec![
                json!({
                    "sessionUpdate": "tool_call_update", "toolCallId": "rho-workflow-x",
                    "title": "build", "kind": "other", "status": "in_progress",
                    "capabilities": cancel,
                }),
                json!({
                    "sessionUpdate": "tool_call_update", "toolCallId": "rho-workflow-w",
                    "status": "cancelled", "capabilities": null,
                }),
            ],
        ),
        (
            "a subagent is a child session, by its own session or its run",
            vec![subagent_work("s", Some("child"), Running)],
            vec![
                subagent_work("s", Some("child"), Failed),
                subagent_work("t", None, Running),
            ],
            vec![
                json!({
                    "sessionUpdate": "subagent_update", "sessionId": "t", "title": "review",
                    "state": {"state": "running"}, "capabilities": cancel,
                }),
                // Its relay reports how the child with a session ended.
                json!({
                    "sessionUpdate": "subagent_update", "sessionId": "child",
                    "capabilities": null,
                }),
            ],
        ),
        (
            "a subagent with no session of its own ends as its run did",
            vec![subagent_work("t", None, Running)],
            vec![subagent_work("t", None, Failed)],
            vec![json!({
                "sessionUpdate": "subagent_update", "sessionId": "t",
                "state": {"state": "idle", "stopReason": "error"}, "capabilities": null,
            })],
        ),
        (
            "work that started and ended between reports is never listed",
            vec![],
            vec![process("a", Completed, Some(0)), workflow("w", Completed)],
            vec![],
        ),
        (
            "ended work leaving the list was already finalized",
            vec![process("a", Completed, Some(0))],
            vec![],
            vec![],
        ),
    ];
    for (case, previous, current, expected) in cases {
        let updates: Vec<Value> = changes(&previous, &current, &workspace())
            .updates
            .iter()
            .map(|update| serde_json::to_value(update).unwrap())
            .collect();
        assert_eq!(updates, expected, "{case}");
    }
}

// Covers: the relay of each child with a session hears how its run ended
// once the list no longer runs it, unknown when it left the list unseen,
// and never of a subagent without one, whose finalization says it.
// Owner: ACP v2 background mapping
#[test]
fn children_with_a_session_hear_how_their_run_ended() {
    use BackgroundStatus::{Cancelled, Running, Unknown};
    let cases = [
        (
            "a child that stopped ended as its run did",
            vec![subagent_work("s", Some("child"), Running)],
            vec![subagent_work("s", Some("child"), Cancelled)],
            vec![("child".to_owned(), Cancelled)],
        ),
        (
            "a child that left the list unseen ended unknown",
            vec![subagent_work("s", Some("child"), Running)],
            vec![],
            vec![("child".to_owned(), Unknown)],
        ),
        (
            "a subagent without a session and a running child are no news",
            vec![
                subagent_work("t", None, Running),
                subagent_work("s", Some("child"), Running),
            ],
            vec![subagent_work("s", Some("child"), Running)],
            vec![],
        ),
    ];
    for (case, previous, current, expected) in cases {
        assert_eq!(
            changes(&previous, &current, &workspace()).children_ended,
            expected,
            "{case}"
        );
    }
}

// Covers: a resume replaces each running terminal's output with what the
// daemon retains, base64 of the very bytes, so the host's buffer matches
// the process's; ended processes are not announced.
// Owner: ACP v2 background mapping
#[test]
fn resume_announces_terminals_with_their_retained_output() {
    use BackgroundStatus::{Completed, Running};
    let work = [
        process("p", Running, None),
        process("done", Completed, Some(0)),
    ];
    let output = BTreeMap::from([("p".to_owned(), "a€\n".to_owned())]);
    let updates: Vec<Value> = announcements(&work, &workspace(), &output)
        .iter()
        .map(|update| serde_json::to_value(update).unwrap())
        .collect();
    assert_eq!(
        updates,
        vec![json!({
            "sessionUpdate": "terminal_update", "terminalId": "p", "command": "run p",
            "cwd": workspace(), "output": {"data": "YeKCrAo="}, "capabilities": {"cancel": {}},
        })]
    );
}

// Covers: a cancel names running work only by the entity the host was told
// of; finished work and other kinds' ids are not cancellable.
// Owner: ACP v2 background mapping
#[test]
fn cancels_find_only_running_work_by_its_entity() {
    use BackgroundStatus::{Completed, Running};
    let work = [
        process("p", Running, None),
        process("done", Completed, Some(0)),
        workflow("w", Running),
        subagent_work("s", Some("child"), Running),
    ];
    assert_eq!(
        (
            terminal(&work, "p"),
            terminal(&work, "done"),
            terminal(&work, "rho-workflow-w"),
            tool_call(&work, "rho-workflow-w"),
            tool_call(&work, "w"),
            subagent(&work, "child"),
            subagent(&work, "s"),
        ),
        (
            Some(BackgroundItem::Process { id: "p".into() }),
            None,
            None,
            Some(BackgroundItem::Workflow { run: "w".into() }),
            None,
            Some(BackgroundItem::Subagent {
                run: "s".into(),
                session: Some(SessionId::new("child")),
            }),
            None,
        )
    );
}