marathon-cli 0.1.1

Keep your Mac awake while AI agents and local models work. The `marathon` command.
//! End-to-end tests of the `marathon` binary on a real Mac: real IOKit
//! assertions, real background holder, private socket folder per test.

use std::path::PathBuf;
use std::process::{Command, Output};
use std::thread::sleep;
use std::time::{Duration, Instant};

struct Env {
    dir: PathBuf,
}

impl Env {
    fn new(name: &str) -> Env {
        // Short path: Unix socket paths are limited to 104 bytes.
        let dir = PathBuf::from(format!("/tmp/mt-{}-{name}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        Env { dir }
    }

    fn run(&self, args: &[&str]) -> Output {
        Command::new(env!("CARGO_BIN_EXE_marathon"))
            .args(args)
            .env("MARATHON_DIR", &self.dir)
            .output()
            .unwrap()
    }

    fn status(&self) -> serde_json::Value {
        let out = self.run(&["status", "--json"]);
        assert!(out.status.success(), "{out:?}");
        serde_json::from_slice(&out.stdout).unwrap()
    }
}

impl Drop for Env {
    fn drop(&mut self) {
        let _ = self.run(&["off"]);
        let _ = std::fs::remove_dir_all(&self.dir);
    }
}

fn assertions_of(pid: u64) -> String {
    let out = Command::new("pmset")
        .args(["-g", "assertions"])
        .output()
        .unwrap();
    let tag = format!("pid {pid}(");
    String::from_utf8_lossy(&out.stdout)
        .lines()
        .filter(|l| l.contains(&tag))
        .collect::<Vec<_>>()
        .join("\n")
}

fn alive(pid: u64) -> bool {
    Command::new("kill")
        .args(["-0", &pid.to_string()])
        .status()
        .unwrap()
        .success()
}

fn wait_until(limit: Duration, mut f: impl FnMut() -> bool) -> bool {
    let end = Instant::now() + limit;
    while Instant::now() < end {
        if f() {
            return true;
        }
        sleep(Duration::from_millis(50));
    }
    f()
}

#[test]
fn on_status_off_with_background_holder() {
    let env = Env::new("onoff");
    assert_eq!(env.status()["active"], false);

    let out = env.run(&["on", "-s"]);
    assert!(out.status.success(), "{out:?}");
    let s = env.status();
    assert_eq!(s["active"], true);
    assert_eq!(s["session"]["mode"], "system");
    assert_eq!(s["holder"], "cli");
    let pid = s["pid"].as_u64().unwrap();
    let held = assertions_of(pid);
    assert!(held.contains("PreventUserIdleSystemSleep"), "{held}");
    assert!(held.contains("Marathon (cli)"), "{held}");

    // Switching mode replaces the assertion in the same holder.
    env.run(&["on"]);
    let held = assertions_of(pid);
    assert!(held.contains("PreventUserIdleDisplaySleep"), "{held}");
    assert!(!held.contains("PreventUserIdleSystemSleep"), "{held}");

    let out = env.run(&["off"]);
    assert!(String::from_utf8_lossy(&out.stdout).starts_with("Off"));
    assert!(
        wait_until(Duration::from_secs(3), || !alive(pid)),
        "holder should exit"
    );
    assert_eq!(env.status()["active"], false);
}

#[test]
fn timed_session_expires_and_holder_exits() {
    let env = Env::new("timed");
    let out = env.run(&["on", "2s"]);
    assert!(out.status.success(), "{out:?}");
    let s = env.status();
    assert!(s["remaining_secs"].as_u64().unwrap() <= 2);
    let pid = s["pid"].as_u64().unwrap();
    assert!(
        wait_until(Duration::from_secs(5), || !alive(pid)),
        "holder should exit at the deadline"
    );
    assert_eq!(assertions_of(pid), "");
    assert_eq!(env.status()["active"], false);
}

#[test]
fn toggle_flips() {
    let env = Env::new("toggle");
    env.run(&["toggle"]);
    assert_eq!(env.status()["active"], true);
    env.run(&["toggle"]);
    assert_eq!(env.status()["active"], false);
}

#[test]
fn command_mode_holds_while_running_and_forwards_exit_code() {
    let env = Env::new("cmd");
    let screen_may_sleep = "Marathon (command): Mac stays awake, screen may turn off while `sh -c";
    for args in [
        &[
            "while",
            "--display-sleep-ok",
            "sh",
            "-c",
            "pmset -g assertions; exit 7",
        ][..],
        &[
            "--display-sleep-ok",
            "while",
            "sh",
            "-c",
            "pmset -g assertions; exit 7",
        ],
        // The older form still works.
        &["-s", "--", "sh", "-c", "pmset -g assertions; exit 7"],
    ] {
        let out = env.run(args);
        assert_eq!(out.status.code(), Some(7), "{args:?}");
        let text = String::from_utf8_lossy(&out.stdout);
        assert!(text.contains(screen_may_sleep), "{args:?}: {text}");
    }
    // A command's own options stay its own.
    let out = env.run(&["while", "sh", "-c", "echo \"$0 $1\"", "--json", "-s"]);
    assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "--json -s");
}

#[test]
fn ai_on_and_off_save_the_setting() {
    let env = Env::new("ai");
    let out = env.run(&["ai", "on"]);
    assert!(out.status.success(), "{out:?}");
    let rules = std::fs::read_to_string(env.dir.join("rules.json")).unwrap();
    assert!(rules.contains(r#""ai_agents": true"#), "{rules}");
    let status = String::from_utf8(env.run(&["status"]).stdout).unwrap();
    assert!(status.contains("AI-aware mode is on"), "{status}");
    env.run(&["ai", "off"]);
    let status = String::from_utf8(env.run(&["status"]).stdout).unwrap();
    assert!(!status.contains("AI-aware"), "{status}");
}

#[test]
fn concurrent_on_all_succeed_with_one_holder() {
    let env = Env::new("race");
    let children: Vec<_> = (0..6)
        .map(|_| {
            Command::new(env!("CARGO_BIN_EXE_marathon"))
                .args(["on", "-s", "30s"])
                .env("MARATHON_DIR", &env.dir)
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::piped())
                .spawn()
                .unwrap()
        })
        .collect();
    for c in children {
        let out = c.wait_with_output().unwrap();
        assert!(out.status.success(), "{out:?}");
    }
    let pid = env.status()["pid"].as_u64().unwrap();
    assert_eq!(assertions_of(pid).lines().count(), 1);
}

#[test]
fn help_explains_each_command() {
    let env = Env::new("help");
    let all = String::from_utf8(env.run(&["--help"]).stdout).unwrap();
    for word in [
        "marathon on 2h",
        "until 6pm",
        "marathon off",
        "marathon status",
        "marathon while COMMAND",
        "marathon ai on",
        "marathon ai check",
        "--display-sleep-ok",
    ] {
        assert!(all.contains(word), "{word} missing from help");
    }
    for (args, expect) in [
        (&["help", "toggle"][..], "Turn Marathon off if it is on"),
        (&["on", "--help"], "stay awake for a while"),
        (&["help", "while"], "command's exit code"),
        (&["--help", "--", "x"], "command's exit code"),
        (&["help", "ai"], "marathon ai off"),
    ] {
        let out = env.run(args);
        assert!(out.status.success());
        assert!(
            String::from_utf8_lossy(&out.stdout).contains(expect),
            "{args:?}"
        );
    }
}

#[test]
fn rejects_bad_input() {
    let env = Env::new("bad");
    for args in [
        &["on", "soon"][..],
        &["frobnicate"],
        &["--nope"],
        &["off", "now"],
        &["--"],
        &["while"],
        &["ai", "maybe"],
    ] {
        let out = env.run(args);
        assert_eq!(out.status.code(), Some(2), "{args:?}");
        assert!(!out.stderr.is_empty());
    }
}