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 rho_protocol::{
    methods::{FsRead, FsReadParams, HostStreamEnd, GIT_DIFF_MAX_BYTES},
    ErrorCode, FsService,
};

use super::*;
use crate::app::daemon_host::machine_test_support::*;

/// What a `diff` of the repository at `repo` streamed, and how it ended.
async fn patch(caller: &Caller, diff: GitDiff, repo: &Path) -> (Vec<u8>, HostStreamEnd) {
    let GitDiff::Patch { top, stream } = diff else {
        panic!("not a patch: {diff:?}");
    };
    assert_eq!(top, real(repo));
    read_out(caller, stream).await
}

/// The files a patch holds, by their `diff --git` lines.
fn headers(patch: &[u8]) -> Vec<String> {
    String::from_utf8_lossy(patch)
        .lines()
        .filter(|line| line.starts_with("diff --git "))
        .map(str::to_owned)
        .collect()
}

// Covers: `repos` answers each folder in the order asked: a checkout's
// branch, origin and project, and the first icon candidate in the
// project, with the stamp `rho/fs/read` gives it, skipping one that names
// a file outside it; a linked worktree's project as its main checkout; a
// detached worktree's whole commit; a repository the `.git` files leave to
// git, as git reads it; a plain folder as no repository, its
// project the folder resolved; and a missing folder as no repository, its
// project as asked, rather than failing the call.
// Owner: daemon host calls.
#[tokio::test]
async fn repos_reads_each_folder_in_order() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    let main = root.join("main");
    repository(&main, &[("assets/icon.svg", "<svg/>")]);
    let origin = "https://example.com/rho/main.git";
    git(&main, &["remote", "add", "origin", origin]);
    git(
        &main,
        &["worktree", "add", "-q", "-b", "feature", "../linked"],
    );
    git(&main, &["worktree", "add", "-q", "--detach", "../detached"]);
    let commit = git(&main, &["rev-parse", "HEAD"]);
    let included = root.join("included");
    repository(&included, &[("a.txt", "a")]);
    git(&included, &["config", "include.path", "more"]);
    let plain = root.join("plain");
    std::fs::create_dir(&plain).unwrap();
    let missing = root.join("missing");
    std::fs::write(root.join("outside.svg"), "<svg/>").unwrap();
    let candidates = ["../outside.svg", "favicon.ico", "assets/icon.svg"]
        .map(str::to_owned)
        .to_vec();
    let machine = machine();
    let read = machine
        .read(
            caller(),
            FsReadParams::new(real(&main), HostPath::new("assets/icon.svg"), 0, 0),
        )
        .await
        .unwrap();
    let FsRead::File {
        size, modified_ns, ..
    } = read
    else {
        panic!("not a file: {read:?}");
    };
    let icon = Some(GitIcon::new("assets/icon.svg", size, modified_ns));
    let repo = |head| Some(GitRepo::new(Some(head), Some(origin.to_owned())));
    let branch = |reference: &str| GitHead::Branch {
        reference: reference.to_owned(),
    };

    let answered = machine
        .repos(
            caller(),
            GitReposParams::new(
                vec![
                    host(&main.join("assets")),
                    host(&root.join("linked")),
                    host(&root.join("detached")),
                    host(&included),
                    host(&plain),
                    host(&missing),
                ],
                candidates,
            ),
        )
        .await
        .unwrap();

    assert_eq!(
        answered.folders,
        [
            GitFolder::new(repo(branch("refs/heads/main")), real(&main), icon.clone()),
            GitFolder::new(
                repo(branch("refs/heads/feature")),
                real(&main),
                icon.clone()
            ),
            GitFolder::new(repo(GitHead::Detached { commit }), real(&main), icon),
            GitFolder::new(
                Some(GitRepo::new(Some(branch("refs/heads/main")), None)),
                real(&included),
                None
            ),
            GitFolder::new(None, real(&plain), None),
            GitFolder::new(None, host(&missing), None),
        ]
    );
}

// Covers: `diff` streams, from any folder of a repository, its tracked
// changes, then each untracked file git doesn't ignore as a new one, with
// paths from the top, ending done; past a limit, only the leading whole
// files that fit, maybe none, ending truncated.
// Owner: daemon host calls.
#[tokio::test]
async fn diff_streams_whole_files_up_to_the_limit() {
    let dir = tempfile::tempdir().unwrap();
    let repo = dir.path().join("repo");
    repository(
        &repo,
        &[
            (".gitignore", "ignored.txt\n"),
            ("sub/tracked.txt", "old\n"),
        ],
    );
    std::fs::write(repo.join("sub/tracked.txt"), "new\n").unwrap();
    std::fs::write(repo.join("untracked.txt"), "fresh\n").unwrap();
    std::fs::write(repo.join("ignored.txt"), "ignored\n").unwrap();
    let machine = machine();
    let caller = caller();
    let diff = |limit| {
        machine.diff(
            caller.clone(),
            GitDiffParams::new(host(&repo.join("sub")), limit),
        )
    };

    let (whole, whole_end) = patch(&caller, diff(1 << 20).await.unwrap(), &repo).await;
    // The first file's patch ends with the newline before the second's.
    let first = String::from_utf8_lossy(&whole)
        .find("\ndiff --git a/untracked.txt")
        .unwrap()
        + 1;
    let into_second = first as u64 + 3;
    let cut = patch(&caller, diff(into_second).await.unwrap(), &repo).await;
    let none = patch(&caller, diff(3).await.unwrap(), &repo).await;

    assert_eq!(
        headers(&whole),
        [
            "diff --git a/sub/tracked.txt b/sub/tracked.txt",
            "diff --git a/untracked.txt b/untracked.txt",
        ]
    );
    assert_eq!(whole_end, HostStreamEnd::Done);
    assert_eq!(cut, (whole[..first].to_vec(), HostStreamEnd::Truncated));
    assert_eq!(none, (Vec::new(), HostStreamEnd::Truncated));
}

// Covers: before the first commit `diff` shows every file as new, staged
// and untracked; a folder in no repository is `not_repo`; a limit past
// the most and a relative folder are refused.
// Owner: daemon host calls.
#[tokio::test]
async fn diff_reads_a_first_commit_and_refuses_what_it_cannot_diff() {
    let dir = tempfile::tempdir().unwrap();
    let repo = dir.path().join("repo");
    std::fs::create_dir(&repo).unwrap();
    git(&repo, &["init", "-q"]);
    std::fs::write(repo.join("staged.txt"), "staged\n").unwrap();
    git(&repo, &["add", "staged.txt"]);
    std::fs::write(repo.join("new.txt"), "new\n").unwrap();
    let plain = dir.path().join("plain");
    std::fs::create_dir(&plain).unwrap();
    let machine = machine();
    let caller = caller();
    let diff =
        |folder: HostPath, limit| machine.diff(caller.clone(), GitDiffParams::new(folder, limit));

    let fresh = diff(host(&repo), 1 << 20).await.unwrap();
    let outside = diff(host(&plain), 1 << 20).await.unwrap();
    let too_much = diff(host(&repo), GIT_DIFF_MAX_BYTES + 1).await.unwrap_err();
    let relative = diff(HostPath::new("repo"), 1 << 20).await.unwrap_err();

    let (bytes, end) = patch(&caller, fresh, &repo).await;
    assert_eq!(
        headers(&bytes),
        [
            "diff --git a/staged.txt b/staged.txt",
            "diff --git a/new.txt b/new.txt",
        ]
    );
    assert_eq!(end, HostStreamEnd::Done);
    assert_eq!(outside, GitDiff::NotRepo);
    assert_eq!(too_much.code, ErrorCode::InvalidParams.code());
    assert!(
        too_much.message.contains(&GIT_DIFF_MAX_BYTES.to_string()),
        "{}",
        too_much.message
    );
    assert_eq!(relative.code, ErrorCode::InvalidParams.code());
}

async fn clone_into(
    machine: &Machine,
    caller: &Caller,
    url: &str,
    folder: &Path,
    name: &str,
) -> Result<GitCloneResponse, RpcError> {
    machine
        .clone_repo(caller.clone(), GitCloneParams::new(url, host(folder), name))
        .await
}

// Covers: `clone` makes the folder and clones into it, its progress
// ending done; asked again, takes the clone as it is with no progress;
// refuses a path holding something else, a folder inside another clone
// of the URL, whose origin git would read, or a clone with no commit yet;
// leaves nothing at the path when git fails; and refuses a name that is
// not one path part.
// Owner: daemon host calls.
#[tokio::test]
async fn clone_clones_once_and_refuses_what_else_is_there() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    let source = root.join("source");
    repository(&source, &[("a.txt", "a")]);
    let url = source.to_str().unwrap();
    let projects = root.join("projects/deeper");
    let machine = machine();
    let caller = caller();

    let first = clone_into(&machine, &caller, url, &projects, "copy")
        .await
        .unwrap();
    let copy = canonical(&projects).unwrap().join("copy");
    assert_eq!(first.path, host(&copy));
    let (_, end) = read_out(&caller, first.progress.unwrap()).await;
    assert_eq!(end, HostStreamEnd::Done);
    assert_eq!(
        git(&copy, &["rev-parse", "HEAD"]),
        git(&source, &["rev-parse", "HEAD"])
    );

    let again = clone_into(&machine, &caller, url, &projects, "copy")
        .await
        .unwrap();
    assert_eq!(again, GitCloneResponse::new(host(&copy), None));

    std::fs::create_dir_all(projects.join("other")).unwrap();
    std::fs::write(projects.join("other/file.txt"), "kept").unwrap();
    let other = clone_into(&machine, &caller, url, &projects, "other")
        .await
        .unwrap_err();
    assert_eq!(other.code, ErrorCode::HostCallFailed.code());
    assert!(
        other.message.ends_with("already holds something else."),
        "{}",
        other.message
    );
    assert!(projects.join("other/file.txt").exists());

    let started = projects.join("started");
    std::fs::create_dir(&started).unwrap();
    git(&started, &["init", "-q"]);
    git(&started, &["remote", "add", "origin", url]);
    let unfinished = clone_into(&machine, &caller, url, &projects, "started")
        .await
        .unwrap_err();
    assert_eq!(unfinished.code, ErrorCode::HostCallFailed.code());
    assert!(
        unfinished.message.contains("with no commit yet"),
        "{}",
        unfinished.message
    );

    let enclosing = root.join("enclosing");
    repository(&enclosing, &[("a.txt", "a")]);
    git(&enclosing, &["remote", "add", "origin", url]);
    std::fs::create_dir(enclosing.join("inner")).unwrap();
    let inside = clone_into(&machine, &caller, url, &enclosing, "inner")
        .await
        .unwrap_err();
    assert!(
        inside.message.ends_with("already holds something else."),
        "{}",
        inside.message
    );

    let missing = root.join("missing");
    let failing = clone_into(
        &machine,
        &caller,
        missing.to_str().unwrap(),
        &projects,
        "failed",
    )
    .await
    .unwrap();
    let (_, failed_end) = read_out(&caller, failing.progress.unwrap()).await;
    let HostStreamEnd::Failed { message, .. } = failed_end else {
        panic!("not failed: {failed_end:?}");
    };
    // Git's own reason, which it words per platform.
    assert!(message.contains("fatal: "), "{message}");
    assert!(!projects.join("failed").exists());

    let dots = clone_into(&machine, &caller, url, &projects, "..")
        .await
        .unwrap_err();
    assert_eq!(dots.code, ErrorCode::InvalidParams.code());
}

// Covers: a clone's URL is logged and shown without the credentials it
// carries, a URL `url::Url` can't parse included, and one that carries none
// as it is.
// Owner: daemon host calls.
#[test]
fn a_clone_url_is_shown_without_its_credentials() {
    use super::clone::without_credentials;

    assert_eq!(
        without_credentials("https://user:token@example.com/a/b.git"),
        "https://example.com/a/b.git"
    );
    assert_eq!(
        without_credentials("https://token@example.com/a/b.git"),
        "https://example.com/a/b.git"
    );
    assert_eq!(
        without_credentials("https://user:token@exa mple.com/a/b.git"),
        "https://exa mple.com/a/b.git"
    );
    assert_eq!(
        without_credentials("https://token@exa mple.com"),
        "https://exa mple.com"
    );
    // A password holding a `/`, which `url::Url` reads as a bad port.
    assert_eq!(
        without_credentials("https://user:ab/cd@example.com/a/b.git"),
        "https://example.com/a/b.git"
    );
    assert_eq!(
        without_credentials("git@example.com:a/b.git"),
        "git@example.com:a/b.git"
    );
}

// Covers: closing a clone's progress stream stops the clone: git and the
// remote helper it started are killed, so the server sees the connection
// close, and the folder the clone made is removed.
// Owner: daemon host calls.
#[cfg(unix)]
#[tokio::test]
async fn closing_a_clone_stream_kills_git_and_removes_the_clone() {
    use std::time::Duration;

    use tokio::io::AsyncReadExt as _;

    const WAIT: Duration = Duration::from_secs(10);
    let dir = tempfile::tempdir().unwrap();
    // Takes git's connection and never answers, so git waits on it.
    let server = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let url = format!("http://{}/x.git", server.local_addr().unwrap());
    let machine = machine();
    let caller = caller();

    let started = clone_into(&machine, &caller, &url, dir.path(), "x")
        .await
        .unwrap();
    let (mut connection, _) = tokio::time::timeout(WAIT, server.accept())
        .await
        .expect("git never connected")
        .unwrap();
    caller.close_stream(&started.progress.unwrap());

    let mut asked = Vec::new();
    let closed = tokio::time::timeout(WAIT, connection.read_to_end(&mut asked)).await;
    assert!(
        matches!(closed, Ok(Ok(_))),
        "the connection didn't end: {closed:?}"
    );
    let clone = Path::new(started.path.as_str());
    let removed = tokio::time::timeout(WAIT, async {
        while clone.exists() {
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    })
    .await;
    assert!(removed.is_ok(), "{} is still there", clone.display());
}