use std::{collections::BTreeSet, path::PathBuf};
use pretty_assertions::assert_eq;
use rho_protocol::{
methods::{JobList, SessionAttach, SessionDetach, SessionList, SessionNew},
Ask, ChildThreads, Client, ClientError, DaemonNotification, ErrorCode, IdleWake, JobKind,
JobListParams, JobState, Operation, PathScope, SessionAttachParams, SessionDetachParams,
SessionEvent, SessionEventParams, SessionId, SessionListParams, SessionNewParams, SessionPart,
SessionSetup, SystemPrompt, SystemPromptMode, ToolCallId, ToolStatus, TurnOutcome,
};
use serde_json::Value;
use super::sessions::{settled_job, Sandbox, ARCHIVIST_AGENT, DEADLINE};
pub(super) fn extra_dir(sandbox: &Sandbox) -> PathBuf {
let extra = sandbox.isolated.path().join("extra");
std::fs::create_dir(&extra).unwrap();
extra.canonicalize().unwrap()
}
async fn new_session(
sandbox: &Sandbox,
client: &Client,
agent: Option<&str>,
setup: SessionSetup,
) -> Result<SessionId, Option<ErrorCode>> {
client
.request::<SessionNew>(&SessionNewParams {
cwd: sandbox.workspace.clone(),
environment: sandbox.client_environment(),
agent: agent.map(str::to_owned),
setup,
parent: None,
grant: None,
worktree: false,
})
.await
.map(|opened| opened.session)
.map_err(|error| match error {
ClientError::Rpc { error, .. } => error.error_code(),
error => panic!("session/new failed outside the protocol: {error}"),
})
}
fn attach(sandbox: &Sandbox, session: &SessionId) -> SessionAttachParams {
SessionAttachParams {
session: session.clone(),
after: None,
environment: sandbox.client_environment(),
setup: SessionSetup::default(),
}
}
pub(super) async fn asked_operation(
sandbox: &Sandbox,
client: &Client,
session: &SessionId,
) -> Operation {
sandbox
.poll_until("the turn to ask", async || {
let jobs = client.request::<JobList>(&JobListParams {}).await.unwrap();
jobs.jobs.into_iter().find(|job| {
job.session.as_ref() == Some(session) && job.state == JobState::WaitingForInput
})
})
.await;
let (follower, _notifications) = sandbox.connect_following().await;
let attached = follower
.request::<SessionAttach>(&attach(sandbox, session))
.await
.unwrap();
match attached
.inputs
.into_iter()
.next()
.map(|request| request.ask)
{
Some(Ask::Approval(approval)) => approval.operation,
ask => panic!("the turn asks for approval: {ask:?}"),
}
}
async fn inspected_request(sandbox: &Sandbox, client: &Client, session: &SessionId) -> Value {
inspected_turn(sandbox, client, session, "hello").await.0
}
pub(super) async fn inspected_turn(
sandbox: &Sandbox,
client: &Client,
session: &SessionId,
text: &str,
) -> (Value, Vec<SessionEvent>) {
match turn(sandbox, client, session, text).await {
(TurnOutcome::Answered { text, .. }, events) => {
(serde_json::from_str(&text).unwrap(), events)
}
(outcome, _) => panic!("the turn answers: {outcome:?}"),
}
}
pub(super) async fn turn(
sandbox: &Sandbox,
client: &Client,
session: &SessionId,
text: &str,
) -> (TurnOutcome, Vec<SessionEvent>) {
let (follower, mut notifications) = sandbox.connect_following().await;
let attached = follower
.request::<SessionAttach>(&attach(sandbox, session))
.await
.unwrap();
assert_eq!(sandbox.prompt_text(client, session, text).await, Ok(()));
let mut replayed = attached.replay_events;
let mut events = Vec::new();
loop {
let notification = tokio::time::timeout(DEADLINE, notifications.recv())
.await
.expect("the daemon sends the session's next event")
.expect("the connection stays open");
let DaemonNotification::SessionEvent(SessionEventParams { event, .. }) = notification
else {
continue;
};
if replayed > 0 {
replayed -= 1;
continue;
}
if let SessionEvent::TurnEnded { outcome, .. } = event {
return (outcome, events);
}
events.push(event);
}
}
fn offered_tools(request: &Value) -> BTreeSet<String> {
request["tools"]
.as_array()
.expect("the request lists its tools")
.iter()
.map(|tool| tool["name"].as_str().unwrap().to_owned())
.collect()
}
#[derive(Clone, Copy, Debug, PartialEq)]
struct Offered {
system_prompt: bool,
tools: bool,
questionnaire: bool,
agent: bool,
}
impl Offered {
fn by(request: &Value) -> Self {
let tools = request["tools"]
.as_array()
.expect("the request lists its tools");
let offers = |name: &str| tools.iter().any(|tool| tool["name"] == name);
Self {
system_prompt: request["messages"][0].get("System").is_some(),
tools: !tools.is_empty(),
questionnaire: offers("questionnaire"),
agent: offers("agent"),
}
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_session_takes_its_additional_directories() {
let sandbox = Sandbox::new();
sandbox.set_permission_mode("supervised");
let extra = extra_dir(&sandbox);
let note = extra.join("note.txt");
let client = sandbox.start_daemon("tool-call").await;
let call = serde_json::json!({
"id": "edit",
"name": "write",
"arguments": {"path": note, "content": "granted"},
});
let granted = SessionSetup {
additional_directories: vec![extra.clone()],
..SessionSetup::default()
};
let mut asked = Vec::new();
for setup in [granted, SessionSetup::default()] {
let session = new_session(&sandbox, &client, None, setup).await.unwrap();
sandbox.prompt_tool_call(&client, &session, &call).await;
asked.push(asked_operation(&sandbox, &client, &session).await);
}
assert_eq!(
asked,
vec![
Operation::WritePath {
path: note.clone(),
scope: PathScope::GrantedRoot {
root: extra.clone()
},
},
Operation::WritePath {
path: note,
scope: PathScope::Unrestricted,
},
],
"log:\n{}",
sandbox.isolated.daemon_log()
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_session_offers_the_model_only_the_parts_its_setup_keeps() {
let sandbox = Sandbox::new();
let client = sandbox.start_daemon("inspect").await;
let all = Offered {
system_prompt: true,
tools: true,
questionnaire: true,
agent: true,
};
let rows = [
(None, all),
(
Some(SessionPart::Tools),
Offered {
tools: false,
questionnaire: false,
agent: false,
..all
},
),
(
Some(SessionPart::Questions),
Offered {
questionnaire: false,
..all
},
),
(
Some(SessionPart::Subagents),
Offered {
agent: false,
..all
},
),
(
Some(SessionPart::SystemPrompt),
Offered {
system_prompt: false,
..all
},
),
];
let mut offered = Vec::new();
for (without, _) in &rows {
let setup = SessionSetup {
without: without.iter().copied().collect(),
..SessionSetup::default()
};
let session = new_session(&sandbox, &client, None, setup).await.unwrap();
offered.push((
*without,
Offered::by(&inspected_request(&sandbox, &client, &session).await),
));
}
assert_eq!(offered, rows, "log:\n{}", sandbox.isolated.daemon_log());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_session_keeps_its_setup_when_a_reopen_brings_none() {
let sandbox = Sandbox::new();
let extra = extra_dir(&sandbox);
let client = sandbox
.start_daemon_with("inspect", &["--unload-idle-after", "200ms"])
.await;
let setup = SessionSetup {
additional_directories: vec![extra.clone()],
without: BTreeSet::from([SessionPart::Tools]),
..SessionSetup::default()
};
let session = new_session(&sandbox, &client, None, setup).await.unwrap();
assert_eq!(sandbox.prompt(&client, &session).await, Ok(()));
settled_job(&sandbox, &client, &session).await;
sandbox.wait_unloaded(&session, 1).await;
let reopened = Offered::by(&inspected_request(&sandbox, &client, &session).await);
let saved_dirs = client
.request::<SessionList>(&SessionListParams::default())
.await
.unwrap()
.sessions
.into_iter()
.find(|listed| listed.session == session)
.map(|listed| listed.added_dirs);
assert_eq!(
(reopened.tools, saved_dirs),
(false, Some(vec![extra])),
"log:\n{}",
sandbox.isolated.daemon_log()
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_reopen_that_narrows_a_session_saves_it_narrowed() {
let sandbox = Sandbox::new();
let client = sandbox
.start_daemon_with("inspect", &["--unload-idle-after", "200ms"])
.await;
let session = new_session(&sandbox, &client, None, SessionSetup::default())
.await
.unwrap();
assert_eq!(sandbox.prompt(&client, &session).await, Ok(()));
settled_job(&sandbox, &client, &session).await;
sandbox.wait_unloaded(&session, 1).await;
let narrowing = SessionAttachParams {
setup: SessionSetup {
without: BTreeSet::from([SessionPart::Tools]),
..SessionSetup::default()
},
..attach(&sandbox, &session)
};
let (follower, _notifications) = sandbox.connect_following().await;
follower.request::<SessionAttach>(&narrowing).await.unwrap();
follower
.request::<SessionDetach>(&SessionDetachParams {
session: session.clone(),
})
.await
.unwrap();
sandbox.wait_unloaded(&session, 2).await;
assert_eq!(
Offered::by(&inspected_request(&sandbox, &client, &session).await),
Offered {
system_prompt: true,
tools: false,
questionnaire: false,
agent: false,
},
"log:\n{}",
sandbox.isolated.daemon_log()
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_session_keeps_its_system_prompt_when_a_reopen_brings_none() {
let sandbox = Sandbox::new();
let client = sandbox
.start_daemon_with("inspect", &["--unload-idle-after", "200ms"])
.await;
let system = |request: &Value| request["messages"][0]["System"].as_str().map(str::to_owned);
let setup = SessionSetup {
system_prompt: Some(SystemPrompt::new(
SystemPromptMode::Override,
"Answer as a pirate.",
)),
..SessionSetup::default()
};
let session = new_session(&sandbox, &client, None, setup).await.unwrap();
let opened = system(&inspected_request(&sandbox, &client, &session).await);
settled_job(&sandbox, &client, &session).await;
sandbox.wait_unloaded(&session, 1).await;
let reopened = system(&inspected_request(&sandbox, &client, &session).await);
assert_eq!(
(
opened
.as_deref()
.map(|text| text.starts_with("Answer as a pirate.\n")),
reopened == opened,
),
(Some(true), true),
"log:\n{}",
sandbox.isolated.daemon_log()
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_session_runs_as_the_agent_its_client_names() {
let sandbox = Sandbox::new();
let archivist = sandbox.isolated.home.join(".agents/agents/archivist.md");
std::fs::create_dir_all(archivist.parent().unwrap()).unwrap();
std::fs::write(&archivist, ARCHIVIST_AGENT).unwrap();
let client = sandbox.start_daemon("inspect").await;
let mut instructed = Vec::new();
for agent in [None, Some("archivist")] {
let session = new_session(&sandbox, &client, agent, SessionSetup::default())
.await
.unwrap();
let request = inspected_request(&sandbox, &client, &session).await;
let system = request["messages"][0]["System"]
.as_str()
.expect("the request has a system prompt");
instructed.push((agent, system.contains("Archive.")));
}
assert_eq!(
instructed,
[(None, false), (Some("archivist"), true)],
"log:\n{}",
sandbox.isolated.daemon_log()
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn an_agent_command_runs_its_task_as_that_agent() {
let sandbox = Sandbox::new();
let archivist = sandbox.isolated.home.join(".agents/agents/archivist.md");
std::fs::create_dir_all(archivist.parent().unwrap()).unwrap();
std::fs::write(
&archivist,
"---\ndescription: Fixture agent with its own model\nmodel-policy: select\nprovider: xai\nmodel: grok-child\n---\n\nArchive.\n",
)
.unwrap();
let client = sandbox.start_daemon("inspect").await;
let session = new_session(&sandbox, &client, None, SessionSetup::default())
.await
.unwrap();
let command = "/agent:archivist summarize the notes";
let (request, events) = inspected_turn(&sandbox, &client, &session, command).await;
let system = request["messages"][0]["System"]
.as_str()
.expect("the request has a system prompt");
let prompt = request["messages"]
.as_array()
.unwrap()
.iter()
.rev()
.find(|message| message.get("User").is_some())
.cloned();
let mut order: Vec<_> = events
.iter()
.filter_map(|event| match event {
SessionEvent::OptionsChanged { .. } => Some("options_changed"),
SessionEvent::AgentMessageChunk { .. } => Some("agent_message_chunk"),
_ => None,
})
.collect();
order.dedup();
order.truncate(2);
let rebound_to = events.iter().find_map(|event| match event {
SessionEvent::Agent { id } => Some(id.clone()),
_ => None,
});
assert_eq!(
(system.contains("Archive."), prompt, order, rebound_to),
(
true,
Some(serde_json::json!({"User": [{"Text": "summarize the notes"}]})),
vec!["options_changed", "agent_message_chunk"],
Some("archivist".to_owned()),
),
"events: {events:?}\nlog:\n{}",
sandbox.isolated.daemon_log()
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_rebound_session_keeps_its_root_agents_tools_after_a_reopen() {
let sandbox = Sandbox::new();
let client = sandbox
.start_daemon_with("inspect", &["--unload-idle-after", "200ms"])
.await;
let explorer = Some("explorer");
let baseline = new_session(&sandbox, &client, explorer, SessionSetup::default())
.await
.unwrap();
let read_only = offered_tools(&inspected_request(&sandbox, &client, &baseline).await);
assert!(
!read_only.contains("write"),
"explorer is read-only: {read_only:?}"
);
let session = new_session(&sandbox, &client, explorer, SessionSetup::default())
.await
.unwrap();
let command = "/agent:worker summarize the notes";
let rebound = offered_tools(&inspected_turn(&sandbox, &client, &session, command).await.0);
settled_job(&sandbox, &client, &session).await;
sandbox.wait_unloaded(&session, 1).await;
let reopened = offered_tools(&inspected_request(&sandbox, &client, &session).await);
assert_eq!(
(
rebound.difference(&read_only).cloned().collect::<Vec<_>>(),
reopened,
),
(Vec::new(), rebound.clone()),
"log:\n{}",
sandbox.isolated.daemon_log()
);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_setups_mcp_server_replaces_the_config_server_of_its_name() {
use std::os::unix::fs::PermissionsExt;
use rho_protocol::McpServer;
let sandbox = Sandbox::new();
let root = sandbox.workspace.parent().unwrap().to_path_buf();
let record = root.join("mcp.txt");
let install = |name: &str| {
let path = root.join(name);
std::fs::write(
&path,
format!(
"#!/bin/sh\nprintf '%s|%s\\n' {name} \"${{TOKEN-unset}}\" >> {}\n",
record.display()
),
)
.unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
path
};
let configured = install("config-probe").display().to_string();
let provided = install("setup-probe");
sandbox.set_config(
"supervised",
&format!("[mcp.servers.probe]\ntransport = \"stdio\"\ncommand = {configured:?}\n"),
);
let client = sandbox.start_daemon("fixed").await;
let setup = SessionSetup {
mcp_servers: vec![McpServer::Stdio {
name: "probe".into(),
command: provided,
args: Vec::new(),
env: [("TOKEN".to_owned(), "token-setup".to_owned())]
.into_iter()
.collect(),
}],
..SessionSetup::default()
};
let session = new_session(&sandbox, &client, None, setup).await.unwrap();
assert_eq!(sandbox.prompt(&client, &session).await, Ok(()));
settled_job(&sandbox, &client, &session).await;
assert_eq!(
std::fs::read_to_string(&record).unwrap_or_default(),
"setup-probe|token-setup\n",
"log:\n{}",
sandbox.isolated.daemon_log()
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn child_threads_follow_the_client_that_opened_the_session() {
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 {
child_threads: ChildThreads::Host,
..SessionSetup::default()
};
let session = new_session(&sandbox, &client, None, setup).await.unwrap();
let mut outcomes = Vec::new();
for (unloads, id) in [(0, "spawn-new"), (1, "spawn-reopened")] {
if unloads > 0 {
settled_job(&sandbox, &client, &session).await;
sandbox.wait_unloaded(&session, unloads).await;
}
let call = serde_json::json!({
"id": id,
"name": "agent",
"arguments": {"agent_id": "worker", "prompt": "inspect the workspace"},
});
let (_, events) = turn(&sandbox, &client, &session, &call.to_string()).await;
let id = ToolCallId::new(id);
let status = events.iter().rev().find_map(|event| match event {
SessionEvent::ToolCall(update) if update.id == id => update.status,
_ => None,
});
let jobs = client.request::<JobList>(&JobListParams {}).await.unwrap();
let subagents = jobs
.jobs
.iter()
.filter(|job| job.kind == JobKind::Subagent)
.count();
outcomes.push((status, subagents));
}
assert_eq!(
outcomes,
[
(Some(ToolStatus::Failed), 0),
(Some(ToolStatus::Completed), 1)
],
"log:\n{}",
sandbox.isolated.daemon_log()
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn only_a_session_the_daemon_wakes_offers_pull_request_tools() {
let sandbox = Sandbox::new();
let client = sandbox.start_daemon("inspect").await;
let setups = [
SessionSetup {
idle_wake: IdleWake::Turn,
..SessionSetup::default()
},
SessionSetup {
idle_wake: IdleWake::Never,
..SessionSetup::default()
},
SessionSetup {
child_threads: ChildThreads::Host,
idle_wake: IdleWake::Turn,
..SessionSetup::default()
},
];
let mut offered = Vec::new();
for setup in setups {
let session = new_session(&sandbox, &client, None, setup).await.unwrap();
let tools = offered_tools(&inspected_request(&sandbox, &client, &session).await);
offered.push(
tools
.into_iter()
.filter(|tool| tool.contains("pull_request"))
.collect::<Vec<_>>(),
);
}
assert_eq!(
offered,
[
vec![
"unwatch_pull_request".to_owned(),
"watch_pull_request".to_owned()
],
Vec::new(),
Vec::new(),
],
"log:\n{}",
sandbox.isolated.daemon_log()
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_session_opened_without_saving_leaves_no_file() {
let sandbox = Sandbox::new();
let client = sandbox
.start_daemon_with("fixed", &["--unload-idle-after", "200ms"])
.await;
let unsaved = SessionSetup {
without: BTreeSet::from([SessionPart::Saving]),
..SessionSetup::default()
};
let mut opened = Vec::new();
let mut answered = Vec::new();
for setup in [SessionSetup::default(), unsaved.clone()] {
let session = new_session(&sandbox, &client, None, setup).await.unwrap();
let (outcome, _events) = turn(&sandbox, &client, &session, "hello").await;
answered.push(matches!(outcome, TurnOutcome::Answered { .. }));
opened.push(session);
}
let [kept, ephemeral] = <[SessionId; 2]>::try_from(opened).unwrap();
let listed: Vec<_> = client
.request::<SessionList>(&SessionListParams::default())
.await
.unwrap()
.sessions
.into_iter()
.map(|listed| listed.session)
.collect();
sandbox.wait_unloaded(&kept, 1).await;
let (reopener, _notifications) = sandbox.connect_following().await;
let reopened = reopener
.request::<SessionAttach>(&SessionAttachParams {
setup: unsaved,
..attach(&sandbox, &kept)
})
.await
.map(|_| ())
.map_err(|error| match error {
ClientError::Rpc { error, .. } => error.error_code(),
error => panic!("session/attach failed outside the protocol: {error}"),
});
sandbox
.poll_until("the daemon to discard the idle session", async || {
sandbox
.isolated
.daemon_log()
.lines()
.any(|line| {
line.contains("discarded unsaved idle session")
&& line.contains(ephemeral.as_str())
})
.then_some(())
})
.await;
let prompted = sandbox.prompt(&client, &ephemeral).await;
assert_eq!(
(answered, listed, reopened, prompted),
(
vec![true, true],
vec![kept],
Err(Some(ErrorCode::InvalidParams)),
Err(Some(ErrorCode::SessionNotFound)),
),
"log:\n{}",
sandbox.isolated.daemon_log()
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_session_the_daemon_cannot_set_up_does_not_open() {
let sandbox = Sandbox::new();
let client = sandbox.start_daemon("fixed").await;
let relative = SessionSetup {
additional_directories: vec!["shared-lib".into()],
..SessionSetup::default()
};
let refused = [
new_session(&sandbox, &client, None, relative).await,
new_session(
&sandbox,
&client,
Some("no-such-agent"),
SessionSetup::default(),
)
.await,
];
let jobs = client.request::<JobList>(&JobListParams {}).await.unwrap();
assert_eq!(
(refused, jobs.jobs),
(
[
Err(Some(ErrorCode::InvalidParams)),
Err(Some(ErrorCode::SessionOpenFailed)),
],
Vec::new(),
),
"log:\n{}",
sandbox.isolated.daemon_log()
);
}