use pretty_assertions::assert_eq;
use futures_util::{future::BoxFuture, FutureExt};
use super::{
super::{
agent_activity::{AgentActivity, CallRunning},
budget::{
test_support::{answer, Turn},
Lending,
},
idle_wake::IdleWatch,
},
idle_delivery, of_sources, TurnDelivery,
};
use crate::{
acp_runtime::agent_tools::Readied,
app::{
agent_concurrency::RuntimePermits,
background_delivery::{BackgroundDelivery, BackgroundSources},
session_runtime::{BackgroundWait, ChildAgents, IdleTurns},
subagent_manager::SubagentManager,
},
cli_runtime::parent_messages::Delivered,
tools::workflow_tracker::{WorkflowFinishedSnapshot, WorkflowRunTracker},
};
const SESSION_ID: &str = "acp-background-fixture";
fn manager(root: &std::path::Path) -> SubagentManager {
SubagentManager::new(
crate::config::Config::default(),
root.join("config.toml"),
root.to_path_buf(),
crate::app::subagent_pool::SubagentPool::Own,
)
}
fn sources<'a>(
manager: &'a SubagentManager,
workflows: &'a WorkflowRunTracker,
) -> BackgroundSources<'a> {
BackgroundSources {
subagents: Some(manager),
processes: None,
workflows,
surfaces: None,
pull_requests: None,
peer_sessions: None,
}
}
fn workflow(workflows: &WorkflowRunTracker, run: &str, finished: bool) {
assert!(workflows.register_start(run, "fixture", "digest", Some(SESSION_ID.into())));
if finished {
workflows.mark_finished(
run,
WorkflowFinishedSnapshot {
lifecycle: "completed".into(),
outcome: Some("success".into()),
nodes: Vec::new(),
error: None,
outputs: Vec::new(),
},
);
}
}
#[derive(Clone, Copy, Debug)]
enum Run {
SentThePrompt,
EndedFirst,
}
#[tokio::test]
async fn a_turn_commits_only_the_results_its_run_delivered() {
let mut seen = Vec::new();
for run in [Run::SentThePrompt, Run::EndedFirst] {
let root = tempfile::tempdir().unwrap();
let manager = manager(root.path());
let workflows = WorkflowRunTracker::new();
workflow(&workflows, "wf-1", true);
let delivery =
BackgroundDelivery::bind(SESSION_ID.to_owned(), sources(&manager, &workflows), None);
let (turn, mailbox) = TurnDelivery::start(delivery, AgentActivity::default());
let carried = mailbox.prompt_results.is_some();
match run {
Run::SentThePrompt => {
let shown = mailbox
.prompt_results
.map(|results| results.settle(Delivered::NextTurn));
assert!(shown.is_some_and(|shown| !shown.is_empty()), "{run:?}");
}
Run::EndedFirst => drop(mailbox),
}
let held = turn.finish();
let mut next =
BackgroundDelivery::bind(SESSION_ID.to_owned(), sources(&manager, &workflows), held);
let left = {
let lock = crate::app::notification_delivery::lock();
next.collect(&lock)
};
seen.push((carried, left.has_results()));
}
assert_eq!(seen, vec![(true, false), (true, true)]);
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Busy {
CallRuns,
AnswerWaits,
}
enum Busying {
Call(CallRunning),
Answer {
other: RuntimePermits,
answer: BoxFuture<'static, Readied>,
},
}
#[tokio::test]
async fn a_turn_is_sent_nothing_while_the_served_tools_are_busy() {
let cases = [Busy::CallRuns, Busy::AnswerWaits];
let mut seen = Vec::new();
for busy in cases {
let root = tempfile::tempdir().unwrap();
let manager = manager(root.path());
let workflows = WorkflowRunTracker::new();
let (budget_turn, budgeted) = Turn::admitted().await;
budget_turn.start_child();
let lending = budget_turn.run(budgeted, Lending::WhileAgentBlocked);
tokio::pin!(lending);
let activity = budget_turn.model.activity();
let delivery =
BackgroundDelivery::bind(SESSION_ID.to_owned(), sources(&manager, &workflows), None);
let (mut turn, mut mailbox) = TurnDelivery::start(delivery, activity.clone());
let busying = match busy {
Busy::CallRuns => Busying::Call(activity.call_running()),
Busy::AnswerWaits => {
let request = budget_turn.request();
assert!(lending.as_mut().now_or_never().is_none());
let other = budget_turn.take_lent_slot();
let mut answer = answer(request);
assert!(answer.as_mut().now_or_never().is_none());
Busying::Answer { other, answer }
}
};
workflow(&workflows, "wf-1", true);
let mut pump = Box::pin(turn.deliver());
let pumping = pump.as_mut().now_or_never().is_none();
let sent_while_busy = mailbox.inbox.recv().now_or_never().is_some();
match busying {
Busying::Call(running) => drop(running),
Busying::Answer { other, mut answer } => {
drop(other);
assert_eq!(answer.as_mut().now_or_never(), Some(Readied::Ready));
}
}
let still_pumping = pump.as_mut().now_or_never().is_none();
let sent_after = mailbox.inbox.recv().now_or_never().flatten().is_some();
seen.push((busy, pumping, sent_while_busy, still_pumping, sent_after));
}
assert_eq!(
seen,
cases.map(|busy| (busy, true, false, true, true)).to_vec()
);
}
#[test]
fn only_a_session_whose_client_takes_daemon_turns_is_woken_for_a_result() {
let cases = [
(ChildAgents::InProcess, IdleTurns::Host),
(ChildAgents::HostThreads, IdleTurns::Host),
];
let mut seen = Vec::new();
for (children, idle_turns) in cases {
let root = tempfile::tempdir().unwrap();
let manager = manager(root.path());
let workflows = WorkflowRunTracker::new();
workflow(&workflows, "wf-1", true);
let idle = idle_delivery(BackgroundWait::of(children, idle_turns));
let background = of_sources(SESSION_ID.to_owned(), idle, sources(&manager, &workflows));
seen.push((
IdleWatch::for_wait(background.wait()).is_some(),
background.awaited().is_some_and(|work| work.has_result()),
));
}
assert_eq!(seen, vec![(true, true), (false, false)]);
}