use std::{
path::{Path, PathBuf},
sync::Arc,
time::Duration,
};
use agent_client_protocol::v1::schema::ToolCallId;
use futures_util::future::BoxFuture;
use pretty_assertions::assert_eq;
use rho_tools::cancellation::RunCancellation;
use rmcp::{
model::{CallToolRequestParams, CallToolResult, ContentBlock, Tool},
service::RunningService,
RoleClient, ServiceExt,
};
use serde_json::{json, Map, Value};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt, DuplexStream},
sync::{mpsc, Notify},
};
use super::{relay_program, serve, Announced, BridgeCalls, Parked, ToolCalls};
use crate::{
acp_runtime::agent_tools::{
parked::{AGENT_CALL_LIMIT, ANSWER_BY, CALL_WAIT},
AgentRequest, AgentToolCall, AgentTools,
},
cli_runtime::agent_event::AgentEvent,
};
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
struct Slow {
release: Arc<Notify>,
requests: mpsc::UnboundedSender<Heard>,
readies: Readies,
}
#[derive(Clone, Copy)]
enum Readies {
AtOnce,
Never,
}
#[derive(Debug, PartialEq)]
enum Heard {
Request,
Answer,
Overdue,
}
const OVERDUE_NOTICE: &str = "went back unreadied";
impl AgentTools for Slow {
fn list(&self) -> Vec<Tool> {
vec![Tool::new("slow", "Ends when let", Arc::new(Map::new()))]
}
fn call(&self, call: AgentToolCall) -> BoxFuture<'static, CallToolResult> {
let release = Arc::clone(&self.release);
let key = call.cards.key().to_string();
Box::pin(async move {
release.notified().await;
CallToolResult::success(vec![ContentBlock::text(key)])
})
}
fn request(&self) -> AgentRequest {
let requests = self.requests.clone();
let _ = requests.send(Heard::Request);
let overdue = requests.clone();
let readies = self.readies;
AgentRequest::new(
Box::pin(async move {
match readies {
Readies::AtOnce => {}
Readies::Never => std::future::pending().await,
}
let _ = requests.send(Heard::Answer);
}),
Box::new(move || {
let _ = overdue.send(Heard::Overdue);
Some(OVERDUE_NOTICE.to_owned())
}),
)
}
}
type SlowBridge = (
Arc<BridgeCalls>,
mpsc::UnboundedReceiver<AgentEvent>,
mpsc::UnboundedReceiver<Heard>,
);
fn bridge_calls(release: &Arc<Notify>, readies: Readies) -> SlowBridge {
let (events, drawn) = mpsc::unbounded_channel();
let (requests, heard) = mpsc::unbounded_channel();
let calls = BridgeCalls {
calls: ToolCalls {
tools: Arc::new(Slow {
release: Arc::clone(release),
requests,
readies,
}),
over: RunCancellation::new(),
events,
},
announced: Announced::default(),
parked: Parked::default(),
};
(Arc::new(calls), drawn, heard)
}
fn connection(calls: Arc<BridgeCalls>) -> (DuplexStream, tokio::task::JoinHandle<()>) {
let (relay, bridge) = tokio::io::duplex(64 * 1024);
let served = tokio::spawn(async move { serve(bridge, TOKEN, calls).await });
(relay, served)
}
async fn client(mut relay: DuplexStream) -> RunningService<RoleClient, ()> {
relay
.write_all(format!("{TOKEN}\n").as_bytes())
.await
.unwrap();
().serve(relay).await.unwrap()
}
#[tokio::test]
async fn only_the_runs_token_opens_its_tools() {
let release = Arc::new(Notify::new());
let mut refused = Vec::new();
for presented in [
format!("{}\n", "f".repeat(64)),
format!("{}\n", &TOKEN[..32]),
String::new(),
] {
let (calls, _drawn, _heard) = bridge_calls(&release, Readies::AtOnce);
let (mut relay, served) = connection(calls);
relay.write_all(presented.as_bytes()).await.unwrap();
relay.write_all(LIST_REQUEST.as_bytes()).await.unwrap();
relay.shutdown().await.unwrap();
let mut heard = Vec::new();
relay.read_to_end(&mut heard).await.unwrap();
served.await.unwrap();
refused.push(heard);
}
let (calls, _drawn, _heard) = bridge_calls(&release, Readies::AtOnce);
let (relay, _served) = connection(calls);
let listed: Vec<String> = client(relay)
.await
.list_all_tools()
.await
.unwrap()
.into_iter()
.map(|tool| tool.name.into_owned())
.collect();
assert_eq!(
(refused, listed),
(
vec![Vec::new(); 3],
vec!["slow".to_owned(), "await".to_owned()]
)
);
}
const LIST_REQUEST: &str = concat!(
r#"{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"_meta":{"#,
r#""io.modelcontextprotocol/protocolVersion":"2026-07-28"}}}"#,
"\n"
);
fn text_of(result: &CallToolResult) -> (String, bool) {
let text = result
.content
.iter()
.filter_map(|block| block.as_text().map(|text| text.text.clone()))
.collect();
(text, result.is_error == Some(true))
}
fn parked_id(result: &CallToolResult) -> String {
let id = result
.structured_content
.as_ref()
.map(|content| &content["id"]);
id.and_then(Value::as_str)
.expect("a still-running answer names its id")
.to_owned()
}
fn call(name: &str, arguments: Value) -> CallToolRequestParams {
let Value::Object(arguments) = arguments else {
unreachable!("arguments are an object");
};
CallToolRequestParams::new(name.to_owned()).with_arguments(arguments)
}
#[tokio::test(start_paused = true)]
async fn a_call_past_one_mcp_calls_wait_is_awaited_to_its_end() {
let release = Arc::new(Notify::new());
let (calls, mut drawn, _heard) = bridge_calls(&release, Readies::AtOnce);
for (tool, id) in [
("slow", "agent-slow"),
("await", "agent-await-1"),
("await", "agent-await-2"),
("await", "agent-await-3"),
] {
calls
.announced
.announce(tool, ToolCallId::new(id), None);
}
let (relay, _served) = connection(Arc::clone(&calls));
let client = client(relay).await;
let started = tokio::time::Instant::now();
let first = client.call_tool(call("slow", json!({}))).await.unwrap();
let waited = started.elapsed().as_secs();
let id = parked_id(&first);
let again = client
.call_tool(call("await", json!({"id": id})))
.await
.unwrap();
release.notify_one();
let ended = client
.call_tool(call("await", json!({"id": id})))
.await
.unwrap();
let gone = client
.call_tool(call("await", json!({"id": id})))
.await
.unwrap();
let mut cards = Vec::new();
while let Ok(event) = drawn.try_recv() {
match event {
AgentEvent::Served { call, .. } => cards.push((call.to_string(), false)),
AgentEvent::ServedHidden(call) => cards.push((call.to_string(), true)),
_ => {}
}
}
assert_eq!(
(
waited,
text_of(&first).1,
parked_id(&again),
text_of(&ended),
text_of(&gone).1,
cards,
),
(
CALL_WAIT.as_secs(),
false,
id,
("agent-slow".to_owned(), false),
true,
vec![
("agent-await-1".to_owned(), true),
("agent-await-2".to_owned(), true),
("agent-await-3".to_owned(), true),
],
)
);
}
fn heard(requests: &mut mpsc::UnboundedReceiver<Heard>) -> Vec<Heard> {
std::iter::from_fn(|| requests.try_recv().ok()).collect()
}
#[tokio::test(start_paused = true)]
async fn agy_is_blocked_only_while_its_mcp_call_is_outstanding() {
let release = Arc::new(Notify::new());
let (calls, _drawn, mut requests) = bridge_calls(&release, Readies::AtOnce);
for (tool, id) in [("slow", "agent-slow"), ("await", "agent-await")] {
calls
.announced
.announce(tool, ToolCallId::new(id), None);
}
let (relay, _served) = connection(Arc::clone(&calls));
let client = client(relay).await;
let first = client.call_tool(call("slow", json!({}))).await.unwrap();
let before_still_running = heard(&mut requests);
let id = parked_id(&first);
let awaiting = client.call_tool(call("await", json!({"id": id})));
tokio::pin!(awaiting);
let awaited = tokio::select! {
biased;
heard = requests.recv() => heard,
_ = &mut awaiting => None,
};
release.notify_one();
let ended = awaiting.await.unwrap();
let before_the_result = heard(&mut requests);
assert_eq!(
(
before_still_running,
awaited,
text_of(&ended),
before_the_result
),
(
vec![Heard::Request, Heard::Answer],
Some(Heard::Request),
("agent-slow".to_owned(), false),
vec![Heard::Answer],
)
);
}
#[tokio::test(start_paused = true)]
async fn an_answer_goes_back_unreadied_before_agys_cut_off() {
let release = Arc::new(Notify::new());
let (calls, mut drawn, mut requests) = bridge_calls(&release, Readies::Never);
calls
.announced
.announce("slow", ToolCallId::new("agent-slow"), None);
let (relay, _served) = connection(Arc::clone(&calls));
let client = client(relay).await;
let started = tokio::time::Instant::now();
let releasing = Arc::clone(&release);
tokio::spawn(async move {
tokio::time::sleep(Duration::from_secs(10)).await;
releasing.notify_one();
});
let answered =
tokio::time::timeout(AGENT_CALL_LIMIT, client.call_tool(call("slow", json!({}))))
.await
.map(|answer| (text_of(&answer.unwrap()), started.elapsed().as_secs()));
let notices: Vec<String> = std::iter::from_fn(|| drawn.try_recv().ok())
.filter_map(|event| match event {
AgentEvent::Notice(notice) => Some(notice),
_ => None,
})
.collect();
assert_eq!(
(answered, heard(&mut requests), notices),
(
Ok((("agent-slow".to_owned(), false), ANSWER_BY.as_secs())),
vec![Heard::Request, Heard::Overdue],
vec![OVERDUE_NOTICE.to_owned()],
)
);
}
#[test]
fn the_relay_is_rho_by_the_path_it_was_started_from() {
let started = || Ok(PathBuf::from("/opt/rho"));
let running = || Ok(PathBuf::from("/nix/store/rho"));
type Case = (
&'static str,
std::io::Result<PathBuf>,
std::io::Result<PathBuf>,
&'static [&'static str],
Result<PathBuf, String>,
);
let cases: [Case; 5] = [
(
"the started path is a file",
started(),
running(),
&["/opt/rho", "/opt/rho.exe", "/nix/store/rho"],
Ok(PathBuf::from("/opt/rho")),
),
(
"started without its suffix",
started(),
running(),
&["/opt/rho.exe", "/nix/store/rho"],
Ok(PathBuf::from("/opt/rho.exe")),
),
(
"only the running file",
started(),
running(),
&["/nix/store/rho"],
Ok(PathBuf::from("/nix/store/rho")),
),
(
"none is a file",
started(),
running(),
&[],
Err("rho's executable is at none of /opt/rho, /opt/rho.exe, /nix/store/rho".to_owned()),
),
(
"no path at all",
Err(std::io::Error::other("no argv[0]")),
Err(std::io::Error::other("no current_exe")),
&[],
Err("could not find rho's own executable: no argv[0]".to_owned()),
),
];
for (name, started, current, files, expected) in cases {
let is_file = |path: &Path| files.iter().any(|file| path == Path::new(file));
let chosen = relay_program(started, ".exe", current, is_file);
assert_eq!(chosen, expected, "{name}");
}
}