rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
use pretty_assertions::assert_eq;
use rho_protocol::{ClientInfo, ConnectionId};

use super::*;

fn caller() -> Caller {
    Caller::new(
        ConnectionId::new(1),
        ClientInfo {
            name: "test".to_owned(),
            version: "0".to_owned(),
        },
    )
}

/// A login shell at `dir/shell` that runs `body` as its login files, then
/// the command it is given, and counts its runs in `dir/runs`; its user's
/// home is `dir`.
///
/// A child process writes it: a write fd held by this test binary can be
/// inherited across a concurrent test's fork, and exec of the fresh script
/// would then fail with ETXTBSY.
fn fake_login(dir: &Path, body: &str) -> Login {
    let shell = dir.join("shell");
    let runs = dir.join("runs");
    let script = format!(
        "#!/bin/sh\necho run >> '{}'\n{body}\nshift\nexec /bin/sh \"$@\"\n",
        runs.display()
    );
    let written = std::process::Command::new("/bin/sh")
        .args(["-c", r#"printf '%s' "$1" > "$2" && chmod +x "$2""#, "sh"])
        .arg(script)
        .arg(&shell)
        .status()
        .unwrap();
    assert!(written.success(), "writing {}", shell.display());
    Login {
        home: dir.to_path_buf(),
        shell,
    }
}

fn runs(dir: &Path) -> usize {
    std::fs::read_to_string(dir.join("runs"))
        .map(|runs| runs.lines().count())
        .unwrap_or(0)
}

// Covers: host info gives the environment the user's login shell prints,
// past what its login files print first, with a value that spans lines;
// the shell starts in the home with a login's variables, not the daemon's
// own; it runs once and its environment is kept for later calls.
// Owner: daemon host calls.
#[tokio::test]
async fn host_info_gives_the_login_shells_environment_once_read() {
    let dir = tempfile::tempdir().unwrap();
    let login = fake_login(
        dir.path(),
        "echo 'Welcome!'\nexport FROM_PROFILE=yes\nexport SPANS='one\ntwo'\nexport STARTED_IN=\"$(pwd)\"",
    );
    let shell = login.shell.clone();
    let machine = Machine::with_login(Path::new("/home/me/.rho"), Some(login), Daemon::idle());

    let first = machine
        .host_info(caller(), HostInfoParams::default())
        .await
        .unwrap();
    let second = machine
        .host_info(caller(), HostInfoParams::default())
        .await
        .unwrap();

    let environment: std::collections::BTreeMap<_, _> = first.login_environment.iter().collect();
    let home = dir.path().to_str().unwrap();
    assert_eq!(environment.get("FROM_PROFILE"), Some(&"yes"));
    assert_eq!(environment.get("SPANS"), Some(&"one\ntwo"));
    assert_eq!(environment.get("HOME"), Some(&home));
    // Compared resolved: macOS's temporary directory is under /var, a
    // symlink, and `pwd` gives /private/var.
    assert_eq!(
        environment
            .get("STARTED_IN")
            .map(|dir| std::fs::canonicalize(dir).unwrap()),
        Some(dir.path().canonicalize().unwrap())
    );
    // The test runner's own, which no login has.
    assert_eq!(environment.get("CARGO_PKG_NAME"), None);
    assert_eq!(first.rho_home, HostPath::new("/home/me/.rho"));
    assert_eq!(first.shell, Some(HostPath::new(shell.to_str().unwrap())));
    assert_eq!(second.login_environment, first.login_environment);
    assert_eq!(runs(dir.path()), 1);
}

// Covers: a login shell that fails gives the environment it would have
// started from, never the daemon's own, and is asked again on the next
// call rather than the failure kept.
// Owner: daemon host calls.
#[tokio::test]
async fn a_failing_login_shell_gives_what_it_starts_from_and_is_asked_again() {
    let dir = tempfile::tempdir().unwrap();
    let login = fake_login(dir.path(), "exit 3");
    let machine = Machine::with_login(
        Path::new("/home/me/.rho"),
        Some(login.clone()),
        Daemon::idle(),
    );

    let info = machine
        .host_info(caller(), HostInfoParams::default())
        .await
        .unwrap();
    machine
        .host_info(caller(), HostInfoParams::default())
        .await
        .unwrap();

    assert_eq!(info.login_environment, starting_environment(&login));
    assert_eq!(runs(dir.path()), 2);
}

// Covers: `env` output whose lines continue a value or name no variable,
// such as a function bash exports, reads as the variables alone, less one
// whose value is not UTF-8.
// Owner: daemon host calls.
#[test]
fn env_output_reads_as_its_variables() {
    let environment = parse_env(
        b"PATH=/bin\nSPANS=one\ntwo\nBASH_FUNC_f%%=() {  echo\n}\nBAD=a\n\xff\n_=/usr/bin/env\n",
    );

    let variables: Vec<_> = environment.iter().collect();
    assert_eq!(
        variables,
        [
            ("PATH", "/bin"),
            ("SPANS", "one\ntwo"),
            ("_", "/usr/bin/env")
        ]
    );
}