rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
use std::{cell::RefCell, io, path::Path, process::Command};

use pretty_assertions::assert_eq;

use super::LaunchAgent;
use crate::daemon::paths::DaemonPaths;

fn paths(home: &Path) -> DaemonPaths {
    DaemonPaths::resolve(home, |_| None).expect("daemon paths")
}

// Covers: the agent runs exactly the command the spawner built, with only
// that command's variables, from `/`, unthrottled, without killing what the
// daemon leaves behind, and with values holding XML's special characters
// escaped; and each home gets an agent of its own, so a scratch daemon never
// replaces the user's.
// Owner: the home's LaunchAgent (macOS daemon start).
#[test]
fn the_agent_runs_the_spawners_command_under_a_label_of_its_home() {
    let agent = LaunchAgent::of(&paths(Path::new("/Users/me/.rho")));
    let mut command = Command::new("/Applications/R&D/rho");
    command
        .args(["daemon", "run"])
        .env_clear()
        .env("RHO_HOME", "/Users/me/.rho")
        .env("PATH", "/opt/<tools>/bin:/usr/bin")
        .current_dir("/");

    assert_eq!(
        agent.plist(&command).expect("a UTF-8 command"),
        format!(
            r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>{}</string>
  <key>ProgramArguments</key>
  <array>
    <string>/Applications/R&amp;D/rho</string>
    <string>daemon</string>
    <string>run</string>
  </array>
  <key>EnvironmentVariables</key>
  <dict>
    <key>PATH</key>
    <string>/opt/&lt;tools&gt;/bin:/usr/bin</string>
    <key>RHO_HOME</key>
    <string>/Users/me/.rho</string>
  </dict>
  <key>WorkingDirectory</key>
  <string>/</string>
  <key>RunAtLoad</key>
  <true/>
  <!-- Unthrottled, as a daemon a terminal starts: launchd throttles the CPU and I/O of an agent with no type. -->
  <key>ProcessType</key>
  <string>Interactive</string>
  <!-- The processes the daemon leaves behind outlive it, as they do where a client starts it. -->
  <key>AbandonProcessGroup</key>
  <true/>
</dict>
</plist>
"#,
            agent.label
        )
    );

    let again = LaunchAgent::of(&paths(Path::new("/Users/me/.rho")));
    let scratch = LaunchAgent::of(&paths(Path::new("/tmp/scratch-home/.rho")));
    assert_eq!(again.label, agent.label);
    assert!(
        scratch.label != agent.label,
        "two homes share the label {}",
        agent.label
    );
}

/// A launchd that keeps one agent, answering `print` while it is loaded.
#[derive(Default)]
struct FakeLaunchd {
    loaded: RefCell<bool>,
    calls: RefCell<Vec<String>>,
}

impl FakeLaunchd {
    fn run(&self, args: &[&str]) -> io::Result<()> {
        self.calls.borrow_mut().push(args.join(" "));
        let mut loaded = self.loaded.borrow_mut();
        match args[0] {
            "print" if !*loaded => return Err(io::Error::other("not loaded")),
            "bootstrap" => *loaded = true,
            "bootout" => *loaded = false,
            _ => {}
        }
        Ok(())
    }
}

// Covers: a start loads the agent from the definition it saves, and one
// still loaded from an earlier start, which may have run another executable
// or environment, is unloaded first: loading it twice fails, and a kickstart
// waits out launchd's 10 s throttle, past the client's start timeout.
// Owner: the home's LaunchAgent (macOS daemon start).
#[test]
fn a_start_loads_the_agent_afresh_from_the_definition_it_saves() {
    let home = tempfile::tempdir().expect("temp home");
    let agent = LaunchAgent::of(&paths(home.path()));
    let definition = agent.definition.to_str().expect("UTF-8").to_owned();
    std::fs::create_dir_all(agent.definition.parent().expect("state dir")).expect("state dir");
    std::fs::write(&agent.definition, "<plist>old</plist>").expect("earlier definition");
    let target = format!("gui/501/{}", agent.label);
    for (case, loaded, expected) in [
        (
            "not loaded",
            false,
            vec![
                format!("print {target}"),
                format!("bootstrap gui/501 {definition}"),
            ],
        ),
        (
            "loaded by an earlier start",
            true,
            vec![
                format!("print {target}"),
                format!("bootout {target}"),
                format!("print {target}"),
                format!("bootstrap gui/501 {definition}"),
            ],
        ),
    ] {
        let launchd = FakeLaunchd {
            loaded: RefCell::new(loaded),
            ..FakeLaunchd::default()
        };

        agent
            .start("gui/501", "<plist>new</plist>", &|args| launchd.run(args))
            .expect(case);

        assert_eq!(
            (
                launchd.calls.take(),
                *launchd.loaded.borrow(),
                std::fs::read_to_string(&agent.definition).expect("definition"),
            ),
            (expected, true, "<plist>new</plist>".to_owned()),
            "{case}"
        );
    }
}