rho-coding-agent 3.12.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::ClientEnvironment;

use super::{is_copy, newer, on_path};

// Covers: an installer that finished without changing the version, as
// mise holding a pinned version does, is an error naming the file and the
// version it still prints, not an update "installed" to the version the
// daemon runs; a newer one is the version the update answers.
// Owner: unattended update, probe of the installed rho.
#[test]
fn an_installed_rho_no_newer_than_the_running_one_is_an_error() {
    let path = Path::new("/opt/rho/bin/rho");

    let same = newer(path, "3.10.0".to_owned(), "3.10.0").unwrap_err();
    let newer_one = newer(path, "3.11.0".to_owned(), "3.10.0").unwrap();

    assert_eq!(
        same.to_string(),
        "the installer finished, but /opt/rho/bin/rho still reports rho 3.10.0"
    );
    assert_eq!(newer_one, "3.11.0");
}

// Covers: the installed rho mise and Scoop put at another path is found in
// the first absolute PATH entry that has it; empty and relative entries,
// which only name something from a working directory, are skipped even when
// they do name a rho from the test's own.
// Owner: unattended update, probe of the installed rho.
#[cfg(unix)]
#[test]
fn the_login_path_finds_rho_in_its_first_absolute_entry_that_has_it() {
    use std::path::Component;

    let [relative_dir, without, first, second] =
        std::array::from_fn::<_, 4, _>(|_| tempfile::tempdir().unwrap());
    for dir in [&relative_dir, &first, &second] {
        std::fs::write(dir.path().join("rho"), "").unwrap();
    }
    // The relative dir, reached from the working directory by `..`s.
    let up = std::env::current_dir()
        .unwrap()
        .components()
        .filter(|component| matches!(component, Component::Normal(_)))
        .count();
    let relative = std::iter::repeat_n("..", up)
        .collect::<PathBuf>()
        .join(relative_dir.path().strip_prefix("/").unwrap());
    assert!(relative.join("rho").is_file(), "{}", relative.display());
    let entries = [
        PathBuf::new(),
        relative,
        without.path().to_owned(),
        first.path().to_owned(),
        second.path().to_owned(),
    ];
    let path = std::env::join_paths(entries).unwrap();
    let environment =
        ClientEnvironment::from_iter([("PATH".to_owned(), path.into_string().unwrap())]);

    let found = on_path(&environment);
    let none = on_path(&ClientEnvironment::default());

    assert_eq!(found, Some(first.path().join("rho")));
    assert_eq!(none, None);
}

// Covers: the daemon tells it runs from its own copy of rho, as for a
// Scoop install, only when its file is in the copies directory, through a
// symlink too, so it names the Scoop command rather than updating the copy
// as if the install script had put it there.
// Owner: unattended update, install method detection.
#[test]
fn only_a_file_in_the_copies_directory_is_a_copy() {
    let (state, elsewhere) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
    let copies = state.path().join("bin");
    std::fs::create_dir(&copies).unwrap();
    let copy = copies.join("rho-3.10.0");
    std::fs::write(&copy, "").unwrap();
    let installed = elsewhere.path().join("rho");
    std::fs::write(&installed, "").unwrap();

    let found = [
        is_copy(&copy, &copies),
        is_copy(&installed, &copies),
        is_copy(&copy, &state.path().join("missing")),
    ];

    assert_eq!(found, [true, false, false]);
}

#[cfg(not(windows))]
mod installer {
    use std::time::Duration;

    use pretty_assertions::assert_eq;

    use super::super::{forward_lines, run_reporting, INSTALLER_DEADLINE, LINE_MAX_BYTES};
    use crate::update::tests::{Recorded, Said};

    fn sh(script: &str) -> tokio::process::Command {
        let mut command = tokio::process::Command::new("sh");
        command.args(["-c", script]);
        command
    }

    // Covers: each line the installer prints, to stdout or stderr, reaches
    // the report, and an installer that exits unsuccessfully is an error
    // naming the update command and its status, as `rho update` says it.
    // Owner: unattended update, installer runner.
    #[tokio::test]
    async fn the_installers_lines_are_reported_and_its_failure_is_an_error() {
        let mut recorded = Recorded::default();

        let error = run_reporting(
            sh("echo out; echo err >&2; exit 3"),
            "test",
            INSTALLER_DEADLINE,
            &mut recorded,
        )
        .await
        .unwrap_err();

        // stdout and stderr are read apart, in no order between them.
        recorded.0.sort();
        assert_eq!(
            recorded.0,
            [
                Said::Stdout("err".to_owned()),
                Said::Stdout("out".to_owned())
            ]
        );
        assert_eq!(
            error.to_string(),
            "test update command exited with exit status: 3"
        );
    }

    // Covers: an installer that never ends, as one waiting on a lock, is
    // stopped at INSTALLER_DEADLINE with an error naming the limit, rather
    // than holding the daemon's one update forever.
    // Owner: unattended update, installer runner.
    #[tokio::test(start_paused = true)]
    async fn an_installer_past_its_deadline_is_stopped_and_named() {
        let error = run_reporting(
            sh("sleep 30"),
            "test",
            INSTALLER_DEADLINE,
            &mut Recorded::default(),
        )
        .await
        .unwrap_err();

        assert_eq!(
            error.to_string(),
            "test update command ran past INSTALLER_DEADLINE (60 min), so rho stopped it"
        );
    }

    // Covers: a process the installer left running, which holds its output
    // open, does not hold the update once the installer exited: what it
    // printed before is reported, and the update ends after the bounded
    // drain, not when that process does (30 s here, past the 20 s the test
    // gives it).
    // Owner: unattended update, installer runner.
    #[tokio::test]
    async fn a_process_the_installer_left_running_does_not_hold_the_update() {
        let mut recorded = Recorded::default();

        let ran = tokio::time::timeout(
            Duration::from_secs(20),
            run_reporting(
                sh("echo $$; sleep 30 & exit 0"),
                "test",
                INSTALLER_DEADLINE,
                &mut recorded,
            ),
        )
        .await;

        // The installer led its own process group: stop what it left.
        let group = match recorded.0.first() {
            Some(Said::Stdout(group)) => group.parse::<libc::pid_t>().ok(),
            _ => None,
        };
        if let Some(group) = group {
            // SAFETY: killpg takes no pointers.
            unsafe { libc::killpg(group, libc::SIGKILL) };
        }
        assert!(matches!(ran, Ok(Ok(()))), "{ran:?}");
        assert!(group.is_some(), "{:?}", recorded.0);
    }

    // Covers: output that never ends its line, as a progress meter writing
    // only `\r`, is cut into lines of LINE_MAX_BYTES, so it cannot grow a
    // buffer without bound; a line's own `\r\n` ending is not part of it.
    // Owner: unattended update, installer runner.
    #[tokio::test]
    async fn a_line_without_an_end_is_split_at_line_max_bytes() {
        let mut output = vec![b'a'; LINE_MAX_BYTES + 10];
        output.extend_from_slice(b"\rdone\r\n");
        let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();

        forward_lines(output.as_slice(), sender).await;

        let mut lines = Vec::new();
        while let Ok(line) = receiver.try_recv() {
            lines.push(line);
        }
        assert_eq!(
            lines,
            [
                "a".repeat(LINE_MAX_BYTES),
                format!("{}\rdone", "a".repeat(10))
            ]
        );
    }
}

#[cfg(unix)]
mod login {
    use std::time::Duration;

    use pretty_assertions::assert_eq;
    use rho_protocol::ClientEnvironment;
    use tokio::runtime::Handle;

    use super::super::{Login, LOOKUP_TIMEOUT};
    use crate::installation::Probe as _;

    fn environment(home: &std::path::Path) -> ClientEnvironment {
        ClientEnvironment::from_iter([
            ("PATH".to_owned(), "/usr/bin:/bin".to_owned()),
            ("HOME".to_owned(), home.to_str().unwrap().to_owned()),
            ("ONLY".to_owned(), "login".to_owned()),
        ])
    }

    // Covers: the daemon asks how rho was installed in the user's login
    // environment alone, from its home, never with the daemon's own, whose
    // PATH may miss `cargo` and `mise`; its variables, which place mise's
    // installs, are the login's too.
    // Owner: unattended update, install method detection.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn lookups_run_in_the_login_environment_alone() {
        // The test process's own, which the login does not have.
        assert!(std::env::var_os("CARGO_MANIFEST_DIR").is_some());
        let home = tempfile::tempdir().unwrap();
        let login = Login::new(environment(home.path()), Handle::current(), LOOKUP_TIMEOUT);
        let mut command = std::process::Command::new("sh");
        command.args([
            "-c",
            r#"printf '%s|%s|%s' "$ONLY" "${CARGO_MANIFEST_DIR-unset}" "$(pwd -P)""#,
        ]);

        let (output, only) =
            tokio::task::spawn_blocking(move || (login.output(command), login.var("ONLY")))
                .await
                .unwrap();

        let home = std::fs::canonicalize(home.path()).unwrap();
        assert_eq!(
            (String::from_utf8(output.unwrap().stdout).unwrap(), only),
            (
                format!("login|unset|{}", home.display()),
                Some("login".into())
            )
        );
    }

    // Covers: a lookup that runs past its time fails, naming the command and
    // LOOKUP_TIMEOUT, and is kept, so detection fails rather than reading a
    // hung `cargo install --list` as "not installed by Cargo" and running the
    // install script over a Cargo install.
    // Owner: unattended update, install method detection.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_lookup_past_its_time_is_kept_to_fail_the_detection() {
        let home = tempfile::tempdir().unwrap();
        let login = Login::new(
            environment(home.path()),
            Handle::current(),
            Duration::from_millis(100),
        );
        let mut command = std::process::Command::new("sleep");
        command.arg("5");

        let (ran, kept) = tokio::task::spawn_blocking(move || {
            let ran = login
                .output(command)
                .map(|_| ())
                .map_err(|error| error.kind());
            (ran, login.timed_out())
        })
        .await
        .unwrap();

        assert_eq!(
            (ran, kept.as_deref()),
            (
                Err(std::io::ErrorKind::TimedOut),
                Some("`sleep 5` did not answer within LOOKUP_TIMEOUT (100ms)")
            )
        );
    }
}