rho-coding-agent 3.7.0

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

use pretty_assertions::assert_eq;
use rho_protocol::{Location, SessionRef, SubagentRef, ToolContent, ToolKind, ToolStatus};
use rho_sdk::tool::{OperationKind, ToolFileChange, ToolMetadata, ToolOutput};
use serde_json::json;

use super::{finished_locations, kind, saved_session, started_locations, CallLinks};
use crate::app::subagent_manager::SubagentManager;
use crate::tools::process::{ProcessLimits, ProcessManager};

fn location(path: &str, line: Option<u32>) -> Location {
    Location {
        path: PathBuf::from(path),
        line,
    }
}

// Covers: kinds beyond the operation map: a patch that only deletes or only
// moves files, the checklist as planning, and plan exit as a mode switch.
// A patch that does anything else, or cannot parse, stays an edit.
// Owner: session event tool presentation
#[test]
fn started_calls_name_their_kind() {
    let write = || ToolMetadata::new().operation(OperationKind::Write);
    let patch = |body: &str| json!({"input": format!("*** Begin Patch\n{body}*** End Patch")});
    let cases = [
        ("write", None, write(), ToolKind::Edit),
        (
            "apply_patch",
            Some(patch("*** Delete File: a.txt\n*** Delete File: b.txt\n")),
            write(),
            ToolKind::Delete,
        ),
        (
            "apply_patch",
            Some(patch(
                "*** Update File: a.txt\n*** Move to: b.txt\n@@\n-a\n+b\n",
            )),
            write(),
            ToolKind::Move,
        ),
        (
            "apply_patch",
            Some(patch(
                "*** Delete File: a.txt\n*** Update File: b.txt\n@@\n-a\n+b\n",
            )),
            write(),
            ToolKind::Edit,
        ),
        (
            "apply_patch",
            Some(json!({"input": "not a patch"})),
            write(),
            ToolKind::Edit,
        ),
        (
            "edit",
            Some(json!({"input": "*** Delete File: a.txt"})),
            write(),
            ToolKind::Edit,
        ),
        (
            "todo",
            Some(json!({"todos": []})),
            ToolMetadata::new(),
            ToolKind::Think,
        ),
        (
            "exit_plan_mode",
            Some(json!({"plan": "p"})),
            ToolMetadata::new(),
            ToolKind::SwitchMode,
        ),
        (
            "agent",
            None,
            ToolMetadata::new().operation(OperationKind::Other("agent".into())),
            ToolKind::Other,
        ),
    ];
    for (name, arguments, metadata, expected) in cases {
        assert_eq!(
            kind(name, arguments.as_ref(), &metadata),
            expected,
            "{name} {arguments:?}"
        );
    }
}

// Covers: started locations are absolute, and a read names the 0-based row
// its 1-based `offset` starts at; another tool's `offset` is no line.
// Owner: session event tool presentation
#[test]
fn started_locations_are_absolute_and_a_read_names_its_line() {
    let cwd = Path::new("/work");
    let cases = [
        (
            "read_file",
            json!({"path": "src/a.rs", "offset": 10}),
            "src/a.rs",
            location("/work/src/a.rs", Some(9)),
        ),
        (
            "read_file",
            json!({"path": "/abs/a.rs"}),
            "/abs/a.rs",
            location("/abs/a.rs", None),
        ),
        (
            "process",
            json!({"path": "log.txt", "offset": 10}),
            "log.txt",
            location("/work/log.txt", None),
        ),
    ];
    for (name, arguments, path, expected) in cases {
        let metadata = ToolMetadata::new().affected_path(path);
        assert_eq!(
            started_locations(name, Some(&arguments), &metadata, cwd),
            vec![expected],
            "{name}"
        );
    }
}

// Covers: a finished edit points at each changed file's first changed row
// (0-based): after a change, an append, or a cut from the end. New, emptied,
// and unchanged files have no line. Output naming no files keeps the started
// locations.
// Owner: session event tool presentation
#[test]
fn finished_edits_point_at_the_first_changed_line() {
    let cases = [
        (
            ToolFileChange::modified("a.txt", "a\nb\nc\n", "a\nB\nc\n"),
            Some(1),
        ),
        (
            ToolFileChange::modified("a.txt", "a\r\nb", "a\r\nb\r\nc"),
            Some(2),
        ),
        (
            ToolFileChange::modified("a.txt", "a\nb\nc", "a\nb"),
            Some(1),
        ),
        (ToolFileChange::modified("a.txt", "a\n", "a\n"), None),
        (ToolFileChange::created("a.txt", "new\n"), None),
        (ToolFileChange::deleted("a.txt", "old\n"), None),
    ];
    for (change, line) in cases {
        let output = ToolOutput::text("ok").metadata(ToolMetadata::new().file_change(change));
        assert_eq!(
            finished_locations(&output, Path::new("/work")),
            Some(vec![location("/work/a.txt", line)]),
            "{line:?}"
        );
    }
    let plain = ToolOutput::text("ok").metadata(
        ToolMetadata::new()
            .operation(OperationKind::Search)
            .affected_path("src"),
    );
    assert_eq!(finished_locations(&plain, Path::new("/work")), None);
}

// Covers: a finished call links the work it started as a replay of it does:
// a process start's terminal while the process runs, even when the call
// itself failed after starting it, but a subagent only for an `agent` call
// that succeeded, since a failed one started no run of its own.
// Owner: session event background-start links
#[tokio::test]
async fn a_finished_call_links_what_it_started() {
    let root = tempfile::tempdir().unwrap();
    let processes = ProcessManager::new(ProcessLimits::default());
    let process = processes
        .start("sleep 30".into(), root.path(), /*timeout*/ None)
        .await
        .unwrap()
        .process_id;
    let subagents = SubagentManager::new(
        crate::config::Config::default(),
        root.path().join("config.toml"),
        root.path().to_path_buf(),
        crate::app::subagent_pool::SubagentPool::Own,
    );
    subagents.bind_parent_session(
        "session",
        /*storage*/ None,
        crate::session::SessionPersistence::Saved,
    );
    subagents.insert_completed_for_test("run", "session", None);
    let terminal = ToolContent::Terminal {
        process: process.clone(),
    };
    let subagent = ToolContent::Subagent(SubagentRef::new("run", None));
    let start = json!({"action": "start", "command": "sleep 30"});
    let cases = [
        (
            "process",
            Some(&start),
            ToolStatus::Completed,
            Some(terminal.clone()),
        ),
        ("process", Some(&start), ToolStatus::Failed, Some(terminal)),
        ("agent", None, ToolStatus::Completed, Some(subagent)),
        ("agent", None, ToolStatus::Failed, None),
    ];

    for (name, arguments, status, expected) in cases {
        let call = format!("{name}-{status:?}");
        processes.record_starter(&process, &call);
        subagents.record_starter("run", &call);
        let mut starts = CallLinks::new(Some(processes.clone()), Some(subagents.clone()));
        starts.started(&call, name, arguments);
        assert_eq!(starts.finished(&call, status, None), expected, "{call}");
    }
}

// Covers: a `sessions` call that succeeded names the one session it acted
// on, whose id its result gives, live and on replay alike, even with the
// line that follows a control result; a failed call, a `list`, and a
// history read, whose `session` is a search handle, name none, even under
// an id an earlier call that would have named one started with.
// Owner: session event session links
#[test]
fn a_finished_sessions_call_names_its_session() {
    let named = ToolContent::Session(SessionRef::new(rho_protocol::SessionId::new("s1")));
    let told = "{\n  \"session\": \"s1\"\n}\nrho tells you when this turn ends or asks a question.";
    let prompt = json!({"action": "prompt", "session": "s1", "prompt": "go", "cursor": null});
    let list = json!({"action": "list"});
    let history = json!({"action": "read", "session": "s1", "anchor": "m1"});
    let cases = [
        ("prompt", &prompt, ToolStatus::Completed, told, Some(named)),
        ("failed prompt", &prompt, ToolStatus::Failed, told, None),
        (
            "list",
            &list,
            ToolStatus::Completed,
            r#"{"sessions": [], "more": false}"#,
            None,
        ),
        (
            "history read",
            &history,
            ToolStatus::Completed,
            r#"{"session": "s1"}"#,
            None,
        ),
    ];
    for (case, arguments, status, text, expected) in cases {
        let mut calls = CallLinks::new(/*processes*/ None, /*subagents*/ None);
        // A provider that reuses an id: the earlier call's link is dropped.
        calls.started(case, "sessions", Some(&prompt));
        calls.started(case, "sessions", Some(arguments));
        assert_eq!(
            calls.finished(case, status, Some(text)),
            expected,
            "live {case}"
        );
        let saved =
            rho_sdk::model::ToolCall::new(case.into(), "sessions".into(), arguments.clone());
        assert_eq!(
            saved_session(&saved, status, text),
            expected,
            "replay {case}"
        );
    }
}