use std::{
collections::BTreeSet,
path::{Path, PathBuf},
sync::{Arc, Mutex},
};
use pretty_assertions::assert_eq;
use serde_json::{json, Value};
use super::OUTLIVED;
use crate::{
acp_runtime::{
policy::AcpProtocol,
runtime_children::{ChildRecord, RuntimeChild, RuntimeChildren, StartedChild},
scripted_agent::{Script, ScriptedAgent, V2Script, V2Step},
session::run_on_channel,
test_support::{read_artifacts, request, TestPolicy, TEST_BUDGET},
},
cli_runtime::CliPrompt,
run_artifacts::AttachmentEvent,
subagent::{RunState, RunStatus},
};
const CHILD: &str = "child-1";
const ROOT: &str = "scripted-session";
struct Recorded {
dir: PathBuf,
started: Mutex<Vec<RuntimeChild>>,
nested: Option<Arc<Recorded>>,
}
impl Recorded {
fn new(dir: PathBuf, nested: Option<Arc<Recorded>>) -> Arc<Self> {
Arc::new(Self {
dir,
started: Mutex::new(Vec::new()),
nested,
})
}
}
impl RuntimeChildren for Recorded {
fn started(&self, child: RuntimeChild) -> StartedChild<'_> {
let dir = self.dir.join(&child.id);
std::fs::create_dir_all(&dir).unwrap();
self.started.lock().unwrap().push(child);
Box::pin(std::future::ready(Ok(ChildRecord {
output_file: dir.join("result.json"),
works_for: Some(ROOT.into()),
identity: request(&dir, None).identity,
status_tx: None,
observer: None,
children: self
.nested
.clone()
.map(|nested| nested as Arc<dyn RuntimeChildren>),
})))
}
}
fn update(session: &str, update: Value) -> V2Step {
let session = (session != ROOT).then_some(session);
serde_json::from_value(json!({"step": "update", "session": session, "update": update})).unwrap()
}
fn said(session: &str, text: &str) -> V2Step {
update(
session,
json!({"sessionUpdate": "agent_message_chunk", "messageId": "m", "content": {"type": "text", "text": text}}),
)
}
fn announces(parent: &str, child: &str, title: &str, state: Value) -> V2Step {
update(
parent,
json!({
"sessionUpdate": "subagent_update",
"sessionId": child,
"title": title,
"description": "general-purpose",
"capabilities": {"cancel": {}},
"state": state,
}),
)
}
fn running() -> Value {
json!({"state": "running", "background": []})
}
fn message(on: &str, from: &str, to: &str, text: &str) -> V2Step {
update(
on,
json!({
"sessionUpdate": "session_message",
"messageId": format!("{from}-{to}"),
"senderSessionId": from,
"recipientSessionId": to,
"content": [{"type": "text", "text": text}],
}),
)
}
fn goes_idle(session: &str) -> V2Step {
update(
session,
json!({"sessionUpdate": "state_update", "state": "idle", "stopReason": "end_turn", "background": []}),
)
}
async fn run(dir: &Path, turn: Vec<V2Step>, host: Arc<Recorded>) {
let script = Script {
v2: Some(V2Script {
turns: vec![turn],
..V2Script::default()
}),
..Script::default()
};
let mut policy = TestPolicy::new(dir);
policy.protocol = AcpProtocol::V2;
let mut asked = request(dir, None);
asked.overrides.runtime_children = Some(host);
let (client, agent) = agent_client_protocol::Channel::duplex();
let (fake, _record, _signals) = ScriptedAgent::new(script);
tokio::time::timeout(TEST_BUDGET, async {
let (client, agent) = tokio::join!(run_on_channel(asked, policy, client), fake.run(agent));
client.unwrap();
agent.unwrap();
})
.await
.expect("ACP runtime/agent finished");
}
#[derive(Debug, PartialEq)]
struct ChildRun {
state: RunState,
reply: Option<String>,
agent_session: Option<String>,
works_for: Option<String>,
cost: Option<f64>,
calls: BTreeSet<String>,
shown: Vec<AttachmentEvent>,
}
fn child_run(dir: &Path) -> Option<ChildRun> {
if !dir.join("result.json").exists() {
return None;
}
let (
RunStatus {
state,
result,
runtime_session_id,
parent_session_id,
total_cost_usd,
..
},
events,
) = read_artifacts(dir);
let calls = events
.iter()
.filter_map(|event| match event {
AttachmentEvent::ToolStarted { key: Some(key), .. } => Some(key.clone()),
_ => None,
})
.collect();
let shown = events
.into_iter()
.filter(|event| {
matches!(
event,
AttachmentEvent::Prompt(_)
| AttachmentEvent::Notice(_)
| AttachmentEvent::Completed
| AttachmentEvent::Cancelled
| AttachmentEvent::Failed(_)
)
})
.collect();
Some(ChildRun {
state,
reply: result,
agent_session: runtime_session_id,
works_for: parent_session_id,
cost: total_cost_usd,
calls,
shown,
})
}
#[tokio::test]
async fn a_subagent_is_recorded_as_a_run_of_its_own() {
let idle = |stop: &str| json!({"state": "idle", "stopReason": stop, "background": []});
let outlived = AttachmentEvent::Notice(OUTLIVED.into());
let cases = [
(
"the child goes idle",
vec![goes_idle(CHILD)],
RunState::Ok,
vec![AttachmentEvent::Completed],
),
(
"the root mirrors the child's cancel",
vec![announces(ROOT, CHILD, "Reply pong", idle("cancelled"))],
RunState::Stopped,
vec![AttachmentEvent::Cancelled],
),
(
"the root's run ends first",
vec![],
RunState::Stopped,
vec![outlived, AttachmentEvent::Cancelled],
),
];
for (name, ends, state, end) in cases {
let dir = tempfile::tempdir().unwrap();
let mut turn = vec![
V2Step::Running,
announces(ROOT, CHILD, "Reply pong", running()),
message(ROOT, ROOT, CHILD, "Reply pong"),
update(
CHILD,
json!({"sessionUpdate": "tool_call_update", "toolCallId": "toolu_c1", "name": "Bash", "title": "ls", "kind": "execute", "status": "in_progress"}),
),
said(CHILD, "pong"),
update(
CHILD,
json!({"sessionUpdate": "usage_update", "used": 10, "size": 100, "cost": {"amount": 0.25, "currency": "USD"}}),
),
];
turn.extend(ends);
turn.extend([
message(ROOT, CHILD, ROOT, "pong"),
said(ROOT, "done"),
V2Step::Idle {
stop_reason: Some(agent_client_protocol::v2::schema::StopReason::EndTurn),
},
]);
let host = Recorded::new(dir.path().join("children"), None);
run(dir.path(), turn, host.clone()).await;
let (root, _) = read_artifacts(dir.path());
assert_eq!(
(
host.started.lock().unwrap().clone(),
child_run(&dir.path().join("children").join(CHILD)),
root.result,
),
(
vec![RuntimeChild {
id: CHILD.into(),
title: Some("Reply pong".into()),
description: Some("general-purpose".into()),
task: CliPrompt::text("Reply pong"),
}],
Some(ChildRun {
state,
reply: Some("pong".into()),
agent_session: None,
works_for: Some(ROOT.into()),
cost: None,
calls: BTreeSet::from(["toolu_c1".to_owned()]),
shown: [vec![AttachmentEvent::Prompt("Reply pong".into())], end].concat(),
}),
Some("done".into()),
),
"{name}"
);
}
}
#[tokio::test]
async fn a_subagents_own_subagent_is_recorded_by_its_parents_host() {
const GRANDCHILD: &str = "child-2";
let turn = || {
vec![
V2Step::Running,
announces(ROOT, CHILD, "Ask a helper", running()),
message(ROOT, ROOT, CHILD, "Ask a helper"),
announces(CHILD, GRANDCHILD, "Reply ping", running()),
message(CHILD, CHILD, GRANDCHILD, "Reply ping"),
said(CHILD, "pong"),
goes_idle(CHILD),
said(GRANDCHILD, "ping"),
message(GRANDCHILD, GRANDCHILD, CHILD, "ping"),
message(CHILD, GRANDCHILD, CHILD, "ping"),
goes_idle(GRANDCHILD),
message(ROOT, CHILD, ROOT, "pong"),
said(ROOT, "done"),
V2Step::Idle {
stop_reason: Some(agent_client_protocol::v2::schema::StopReason::EndTurn),
},
]
};
let ran = |state| Some((state, Some("ping".to_owned())));
let cases = [(true, ran(RunState::Ok)), (false, None)];
for (names_host, grandchild) in cases {
let dir = tempfile::tempdir().unwrap();
let deeper = Recorded::new(dir.path().join("deeper"), None);
let nested = Recorded::new(dir.path().join("grandchildren"), Some(deeper.clone()));
let host = Recorded::new(
dir.path().join("children"),
names_host.then(|| nested.clone()),
);
run(dir.path(), turn(), host.clone()).await;
let started = |host: &Recorded| -> Vec<String> {
let started = host.started.lock().unwrap();
started.iter().map(|child| child.id.clone()).collect()
};
let reply = |dir: PathBuf| child_run(&dir).map(|run| (run.state, run.reply));
assert_eq!(
(
started(&host),
started(&deeper),
reply(dir.path().join("children").join(CHILD)),
reply(dir.path().join("grandchildren").join(GRANDCHILD)),
),
(
vec![CHILD.to_owned()],
Vec::<String>::new(),
Some((RunState::Ok, Some("pong".into()))),
grandchild,
),
"names a host: {names_host}"
);
}
}