use std::path::Path;
use pretty_assertions::assert_eq;
use rho_protocol::{
methods::{
SessionBackgroundHold, SessionBackgroundList, SessionBackgroundStop, SessionCancel,
SessionDelete,
},
BackgroundStatus, DeleteWork, ErrorCode, IdleWake, JobState, SessionBackgroundHoldParams,
SessionBackgroundListParams, SessionBackgroundStopParams, SessionCancelParams,
SessionDeleteParams, SessionSetup,
};
use serde_json::json;
use super::{
sessions::{settled_job, Sandbox},
upgrade::{fifo, open_gate},
};
fn sleeper(file: &str) -> String {
format!("sleep 600 & echo $! > {file} && wait")
}
fn recorded_pid(workspace: &Path, file: &str) -> Option<libc::pid_t> {
std::fs::read_to_string(workspace.join(file))
.ok()?
.trim()
.parse()
.ok()
}
fn running(pid: libc::pid_t) -> bool {
if unsafe { libc::kill(pid, 0) } != 0 {
return false;
}
#[cfg(target_os = "linux")]
{
let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) else {
return false;
};
stat.rsplit_once(") ")
.is_none_or(|(_, fields)| !fields.starts_with("Z "))
}
#[cfg(not(target_os = "linux"))]
true
}
struct Sleepers(Vec<libc::pid_t>);
impl Drop for Sleepers {
fn drop(&mut self) {
for &pid in self.0.iter().filter(|&&pid| running(pid)) {
unsafe {
let group = libc::getpgid(pid);
if group > 0 {
libc::killpg(group, libc::SIGKILL);
}
}
}
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn the_background_list_shows_work_that_outlives_the_turn() {
let sandbox = Sandbox::new();
sandbox.set_permission_mode("bypass");
let client = sandbox.start_daemon("tool-call").await;
let session = sandbox
.new_session_with_setup(
&client,
SessionSetup {
idle_wake: IdleWake::Turn,
..SessionSetup::default()
},
)
.await;
let gate = fifo(sandbox.workspace.join("background.fifo"));
let command = "read _ < background.fifo";
let process = json!({
"id": "background",
"name": "process",
"arguments": {"action": "start", "command": command},
});
sandbox.prompt_tool_call(&client, &session, &process).await;
let listed = async || {
let list = client
.request::<SessionBackgroundList>(&SessionBackgroundListParams {})
.await
.unwrap();
list.sessions
.into_iter()
.filter(|listed| listed.session == session)
.flat_map(|listed| listed.work)
.map(|work| (work.title, work.status))
.collect::<Vec<_>>()
};
let completed = settled_job(&sandbox, &client, &session).await.state;
let outlived = listed().await;
assert_eq!(
(completed, outlived),
(
JobState::Completed,
vec![(command.to_owned(), BackgroundStatus::Running)],
),
"log:\n{}",
sandbox.isolated.daemon_log()
);
open_gate(&sandbox, &gate).await;
sandbox
.poll_until("the session to leave the background list", async || {
listed().await.is_empty().then_some(())
})
.await;
settled_job(&sandbox, &client, &session).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_delete_that_stops_the_sessions_work_cancels_its_turn_and_ends_its_processes() {
let cases = [
("process", JobState::Completed),
("bash", JobState::Cancelled),
];
let (mut outcomes, mut logs) = (Vec::new(), String::new());
for (tool, _) in cases {
let sandbox = Sandbox::new();
sandbox.set_permission_mode("bypass");
let client = sandbox.start_daemon("tool-call").await;
let setup = SessionSetup {
idle_wake: IdleWake::Turn,
..SessionSetup::default()
};
let session = sandbox.new_session_with_setup(&client, setup).await;
let arguments = match tool {
"process" => json!({"action": "start", "command": sleeper("work.pid")}),
_ => json!({"command": sleeper("work.pid")}),
};
let call = json!({"id": "work", "name": tool, "arguments": arguments});
sandbox.prompt_tool_call(&client, &session, &call).await;
let pid = sandbox
.poll_until("the sleeper to start", async || {
recorded_pid(&sandbox.workspace, "work.pid")
})
.await;
let _leftover = Sleepers(vec![pid]);
if tool == "process" {
settled_job(&sandbox, &client, &session).await;
}
let delete = |work| SessionDeleteParams {
session: session.clone(),
unless_attached: false,
work,
};
let refused = client
.request::<SessionDelete>(&delete(DeleteWork::Refuse))
.await
.map_err(|error| error.error_code());
let stopped = client
.request::<SessionDelete>(&delete(DeleteWork::Stop))
.await
.map_err(|error| error.error_code());
sandbox
.poll_until("the sleeper to end", async || (!running(pid)).then_some(()))
.await;
let ended = settled_job(&sandbox, &client, &session).await.state;
outcomes.push((refused, stopped, ended));
logs += &format!("{tool} log:\n{}\n", sandbox.isolated.daemon_log());
}
let expected: Vec<_> = cases
.iter()
.map(|&(_, ended)| {
(
Err(Some(ErrorCode::SessionBusy)),
Ok(Default::default()),
ended,
)
})
.collect();
assert_eq!(outcomes, expected, "{logs}");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_held_session_starts_no_turn_for_its_stopped_work_and_unloads() {
let sandbox = Sandbox::new();
sandbox.set_permission_mode("bypass");
let client = sandbox
.start_daemon_with("tool-call", &["--unload-idle-after", "200ms"])
.await;
let setup = SessionSetup {
idle_wake: IdleWake::Turn,
..SessionSetup::default()
};
let session = sandbox.new_session_with_setup(&client, setup).await;
let process = json!({
"id": "background",
"name": "process",
"arguments": {"action": "start", "command": sleeper("background.pid")},
});
sandbox.prompt_tool_call(&client, &session, &process).await;
let pid = sandbox
.poll_until("the process to start", async || {
recorded_pid(&sandbox.workspace, "background.pid")
})
.await;
let _leftover = Sleepers(vec![pid]);
settled_job(&sandbox, &client, &session).await;
let records = sandbox.session_records(&session).len();
let list = client
.request::<SessionBackgroundList>(&SessionBackgroundListParams {})
.await
.unwrap();
let work = list
.sessions
.into_iter()
.filter(|listed| listed.session == session)
.flat_map(|listed| listed.work)
.map(|work| work.item)
.next()
.expect("the daemon lists the process");
client
.request::<SessionBackgroundHold>(&SessionBackgroundHoldParams {
session: session.clone(),
})
.await
.unwrap();
client
.request::<SessionBackgroundStop>(&SessionBackgroundStopParams {
session: session.clone(),
work,
})
.await
.unwrap();
sandbox
.poll_until("the process to end", async || (!running(pid)).then_some(()))
.await;
sandbox.wait_unloaded(&session, 1).await;
assert_eq!(
sandbox.session_records(&session).len(),
records,
"log:\n{}",
sandbox.isolated.daemon_log()
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn the_daemons_stop_ends_the_processes_its_sessions_started() {
let sandbox = Sandbox::new();
sandbox.set_permission_mode("bypass");
let (mut daemon, client) = sandbox.spawn_daemon(sandbox.rho("tool-call"), &[]).await;
let running_turn = sandbox.new_session(&client).await;
let bash = json!({
"id": "foreground",
"name": "bash",
"arguments": {"command": sleeper("foreground.pid")},
});
sandbox
.prompt_tool_call(&client, &running_turn, &bash)
.await;
let cancelled = sandbox.new_session(&client).await;
let process = json!({
"id": "background",
"name": "process",
"arguments": {"action": "start", "command": sleeper("background.pid")},
});
sandbox
.prompt_tool_call(&client, &cancelled, &process)
.await;
let pids = sandbox
.poll_until("both processes to start", async || {
Some([
recorded_pid(&sandbox.workspace, "foreground.pid")?,
recorded_pid(&sandbox.workspace, "background.pid")?,
])
})
.await;
let _leftovers = Sleepers(pids.to_vec());
client
.request::<SessionCancel>(&SessionCancelParams {
session: cancelled.clone(),
})
.await
.unwrap();
let cancelled_state = settled_job(&sandbox, &client, &cancelled).await.state;
let before_stop = pids.map(running);
let stop = sandbox
.rho("tool-call")
.args(["daemon", "stop"])
.status()
.unwrap();
assert!(stop.success(), "log:\n{}", sandbox.isolated.daemon_log());
daemon.wait().unwrap();
sandbox
.poll_until("the processes to end", async || {
(!pids.into_iter().any(running)).then_some(())
})
.await;
assert_eq!(
(cancelled_state, before_stop),
(JobState::Cancelled, [true, true]),
"log:\n{}",
sandbox.isolated.daemon_log()
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_sessions_tools_run_with_the_prompting_clients_environment() {
let sandbox = Sandbox::new();
sandbox.set_permission_mode("bypass");
let client = sandbox.start_daemon("tool-call").await;
let session = sandbox.new_session(&client).await;
std::fs::write(
sandbox.isolated.home.join(".bash_profile"),
"export PATH=/usr/bin:/bin\n",
)
.unwrap();
let record = "printf '%s|%s|%s|%s' \"${PATH%%:*}\" \"$PROBE\" \"${XAI_API_KEY-unset}\" \"${RHO_AUTOMATION_TEST_MODE-unset}\" > env.txt";
let calls = [
(
"probe-1659-bash",
json!({"id": "bash", "name": "bash", "arguments": {"command": record}}),
),
(
"probe-1659-process",
json!({
"id": "process",
"name": "process",
"arguments": {"action": "start", "command": record},
}),
),
];
let mut seen = Vec::new();
for (probe, call) in calls {
let path = format!("/rho-client-1659:{}", std::env::var("PATH").unwrap());
let environment = sandbox
.client_environment()
.into_iter()
.chain([
("PATH".to_owned(), path),
("PROBE".to_owned(), probe.to_owned()),
("XAI_API_KEY".to_owned(), "key-1659".to_owned()),
])
.collect();
sandbox
.prompt_tool_call_with_environment(&client, &session, &call, environment)
.await;
settled_job(&sandbox, &client, &session).await;
seen.push(std::fs::read_to_string(sandbox.workspace.join("env.txt")).unwrap());
}
let saved = serde_json::to_string(&sandbox.session_records(&session)).unwrap();
let log = sandbox.isolated.daemon_log();
assert_eq!(
seen,
[
"/rho-client-1659|probe-1659-bash|unset|unset",
"/rho-client-1659|probe-1659-process|unset|unset"
],
"log:\n{log}"
);
assert_eq!(
["probe-1659", "key-1659", "rho-client-1659"]
.map(|value| saved.contains(value) || log.contains(value)),
[false, false, false]
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn each_sessions_commands_get_their_own_temp_dir() {
let sandbox = Sandbox::new();
sandbox.set_permission_mode("bypass");
let client = sandbox.start_daemon("tool-call").await;
let clients = sandbox
.client_environment()
.iter()
.find_map(|(name, value)| (name == "TMPDIR").then(|| value.to_owned()))
.unwrap_or_default();
let sessions = [
sandbox.new_session(&client).await,
sandbox.new_session(&client).await,
];
let mut dirs = Vec::new();
for (index, session) in sessions.iter().enumerate() {
let record = format!("printf '%s' \"$TMPDIR\" > tmpdir-{index}.txt");
let call = json!({"id": "bash", "name": "bash", "arguments": {"command": record}});
sandbox.prompt_tool_call(&client, session, &call).await;
settled_job(&sandbox, &client, session).await;
dirs.push(
std::fs::read_to_string(sandbox.workspace.join(format!("tmpdir-{index}.txt"))).unwrap(),
);
}
assert_eq!(
(
dirs[0] != dirs[1],
dirs.iter()
.map(|dir| dir != &clients && Path::new(dir).is_dir())
.collect::<Vec<_>>(),
),
(true, vec![true, true]),
"{dirs:?}, client's {clients}, log:\n{}",
sandbox.isolated.daemon_log()
);
}
fn client_environment_with_bin(
sandbox: &Sandbox,
bin: &Path,
extra: &[(&str, &str)],
) -> rho_protocol::ClientEnvironment {
let path = format!("{}:{}", bin.display(), std::env::var("PATH").unwrap());
sandbox
.client_environment()
.into_iter()
.chain([("PATH".to_owned(), path)])
.chain(
extra
.iter()
.map(|(name, value)| ((*name).to_owned(), (*value).to_owned())),
)
.collect()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_sessions_mcp_servers_and_hooks_see_its_clients_environment() {
use std::os::unix::fs::PermissionsExt;
let sandbox = Sandbox::new();
let root = sandbox.workspace.parent().unwrap().to_path_buf();
let bin = root.join("client-bin-1659");
std::fs::create_dir_all(&bin).unwrap();
let record = |file: &str, value: &str| {
format!(
"printf '%s|%s\\n' \"${{PATH%%:*}}\" \"{value}\" >> {}",
root.join(file).display()
)
};
let server = bin.join("probe-mcp-1659");
std::fs::write(
&server,
format!("#!/bin/sh\n{}\n", record("mcp.txt", "${TOKEN-unset}")),
)
.unwrap();
std::fs::set_permissions(&server, std::fs::Permissions::from_mode(0o755)).unwrap();
sandbox.set_config(
"bypass",
r#"
[mcp.servers.probe]
transport = "stdio"
command = "probe-mcp-1659"
env_from_env = { TOKEN = "PROBE_TOKEN" }
"#,
);
let hook = record("hook.txt", "${PROBE-unset}")
+ " && printf '{\"version\": 1, \"decision\": \"continue\"}'";
std::fs::write(
sandbox.isolated.rho_home().join("hooks.toml"),
format!(
r#"version = 1
[[hook]]
id = "probe"
on = "before_tool_use"
tools = ["bash"]
command = ["/bin/sh", "-c", {hook:?}]
env = ["PROBE"]
timeout = "10s"
"#
),
)
.unwrap();
let client = sandbox.start_daemon("tool-call").await;
let session = sandbox
.new_session_with_environment(
&client,
client_environment_with_bin(&sandbox, &bin, &[("PROBE_TOKEN", "token-1659")]),
)
.await;
let call = json!({"id": "bash", "name": "bash", "arguments": {"command": "true"}});
for probe in ["first-1659", "second-1659"] {
let environment = client_environment_with_bin(&sandbox, &bin, &[("PROBE", probe)]);
sandbox
.prompt_tool_call_with_environment(&client, &session, &call, environment)
.await;
settled_job(&sandbox, &client, &session).await;
}
let read = |file: &str| std::fs::read_to_string(root.join(file)).unwrap_or_default();
let bin = bin.display();
assert_eq!(
[read("mcp.txt"), read("hook.txt")],
[
format!("{bin}|token-1659\n"),
format!("{bin}|first-1659\n{bin}|second-1659\n"),
],
"log:\n{}",
sandbox.isolated.daemon_log()
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_rho_a_hook_runs_reaches_its_sessions_daemon() {
let sandbox = Sandbox::new();
let root = sandbox.workspace.parent().unwrap().to_path_buf();
let status = root.join("nested-status.txt");
let hook =
"\"$0\" daemon status --json > \"$1\" 2>&1; printf '{\"version\": 1, \"decision\": \"continue\"}'";
std::fs::write(
sandbox.isolated.rho_home().join("hooks.toml"),
format!(
r#"version = 1
[[hook]]
id = "nested"
on = "before_tool_use"
tools = ["bash"]
command = ["/bin/sh", "-c", {hook:?}, {:?}, {:?}]
timeout = "30s"
"#,
env!("CARGO_BIN_EXE_rho"),
status.display().to_string(),
),
)
.unwrap();
sandbox.set_permission_mode("bypass");
let (daemon, client) = sandbox.spawn_daemon(sandbox.rho("tool-call"), &[]).await;
let session = sandbox.new_session(&client).await;
let elsewhere = root.join("elsewhere-home");
std::fs::create_dir_all(&elsewhere).unwrap();
let environment = sandbox
.client_environment()
.into_iter()
.chain([("HOME".to_owned(), elsewhere.display().to_string())])
.collect();
let call = json!({"id": "bash", "name": "bash", "arguments": {"command": "true"}});
sandbox
.prompt_tool_call_with_environment(&client, &session, &call, environment)
.await;
settled_job(&sandbox, &client, &session).await;
let printed = std::fs::read_to_string(&status).unwrap_or_default();
let reached = serde_json::from_str::<serde_json::Value>(&printed)
.ok()
.and_then(|status| status["pid"].as_u64());
assert_eq!(
reached,
Some(u64::from(daemon.id())),
"nested rho printed:\n{printed}\nlog:\n{}",
sandbox.isolated.daemon_log()
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_sessions_cli_agents_and_workflow_commands_see_its_clients_environment() {
use std::os::unix::fs::PermissionsExt;
let sandbox = Sandbox::new();
let root = sandbox.workspace.parent().unwrap().to_path_buf();
let bin = root.join("client-bin-1659");
std::fs::create_dir_all(&bin).unwrap();
let install = |name: &str, contents: String| {
let path = bin.join(name);
std::fs::write(&path, contents).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
};
let record = |file: &str| {
format!(
"printf '%s|%s|%s\\n' \"${{PATH%%:*}}\" \"${{PROBE-unset}}\" \"${{XAI_API_KEY-unset}}\" >> {}",
root.join(file).display()
)
};
install(
"claude-agent-acp",
format!(
"#!/bin/sh\nif [ \"${{1-}}\" = \"--cli\" ]; then printf '%s\\n' '{{\"loggedIn\":true}}'; exit 0; fi\n{}\nexit 1\n",
record("cli.txt")
),
);
std::os::unix::fs::symlink("/bin/sh", bin.join("sh-1659")).unwrap();
install(
"probe-1659",
format!("#!/usr/bin/env sh-1659\n{}\n", record("command.txt")),
);
std::fs::create_dir_all(sandbox.isolated.rho_home().join("agents")).unwrap();
std::fs::write(
sandbox.isolated.rho_home().join("agents/claude-env.md"),
"---\nid: claude-env\ndescription: Claude Code agent for the environment test\nruntime: claude-cli\nprompt: replace\n---\nWork.\n",
)
.unwrap();
std::fs::create_dir_all(sandbox.workspace.join("wf")).unwrap();
std::fs::write(
sandbox.workspace.join("wf/main.star"),
r#"def build(inputs):
return workflow(name = "env-run", nodes = [
command(
name = "probe",
argv = ["probe-1659"],
cwd = ".",
timeout_seconds = 600,
max_output_bytes = 1000,
),
])
WORKFLOW = define(inputs = {}, build = build)
"#,
)
.unwrap();
sandbox.set_permission_mode("bypass");
let client = sandbox.start_daemon("tool-call").await;
let session = sandbox.new_session(&client).await;
let mut calls = vec![(
"cli.txt",
"cli-1659",
json!({"id": "delegate", "name": "agent", "arguments": {"agent_id": "claude-env", "prompt": "Work."}}),
"key-1659",
)];
if cfg!(any(target_os = "linux", target_os = "android")) {
calls.push((
"command.txt",
"workflow-1659",
json!({"id": "start", "name": "workflow", "arguments": {"action": "start", "file": "wf/main.star"}}),
"unset",
));
}
let mut seen = Vec::new();
let mut expected = Vec::new();
for (file, probe, call, key) in calls {
let environment = client_environment_with_bin(
&sandbox,
&bin,
&[("PROBE", probe), ("XAI_API_KEY", "key-1659")],
);
sandbox
.prompt_tool_call_with_environment(&client, &session, &call, environment)
.await;
settled_job(&sandbox, &client, &session).await;
seen.push(
sandbox
.poll_until(file, async || std::fs::read_to_string(root.join(file)).ok())
.await,
);
expected.push(format!("{}|{probe}|{key}\n", bin.display()));
}
assert_eq!(seen, expected, "log:\n{}", sandbox.isolated.daemon_log());
}