use std::future::Future;
use crate::{
app::{
background_delivery::{
self, BackgroundDelivery, BackgroundSources, Batch, CountedWork, HeldNotices, Notices,
},
notification_delivery,
peer_sessions::PeerInbox,
session_runtime::BackgroundWait,
},
cli_runtime::parent_messages::{
message_channel, DeliveryReceipt, ParentMessage, ParentMessageHandle, ParentMessageInbox,
},
display_transcript::{DisplayRow, DisplayTranscript},
run_artifacts::AttachmentEvent,
tools::{
sdk_registry::{AppToolSet, IdleDelivery},
workflow_tracker::WorkflowRunTracker,
},
};
use super::{
acp_tools::ServedTools,
agent_activity::AgentActivity,
background::{SessionBackground, Sources},
};
pub(super) fn idle_delivery(rho_wait: BackgroundWait) -> IdleDelivery {
match rho_wait {
BackgroundWait::HostTurns => IdleDelivery::WakeTurn,
BackgroundWait::HostWakes | BackgroundWait::HoldPrompt => IdleDelivery::NextPrompt,
}
}
fn wait(idle: IdleDelivery) -> BackgroundWait {
match idle {
IdleDelivery::WakeTurn => BackgroundWait::HostTurns,
IdleDelivery::NextPrompt => BackgroundWait::HoldPrompt,
}
}
fn sources(served: &ServedTools) -> BackgroundSources<'_> {
sources_of(served.set(), served.idle(), served.peers())
}
pub(super) fn sources_of<'a>(
set: &'a AppToolSet,
idle: IdleDelivery,
peers: Option<&'a PeerInbox>,
) -> BackgroundSources<'a> {
let of = BackgroundSources::of(set);
match idle {
IdleDelivery::WakeTurn => BackgroundSources {
peer_sessions: peers,
..of
},
IdleDelivery::NextPrompt => BackgroundSources {
pull_requests: None,
..of
},
}
}
pub(super) fn background(session_id: String, served: Option<&ServedTools>) -> SessionBackground {
match served {
Some(served) => of_sources(session_id, served.idle(), sources(served)),
None => SessionBackground::of_sources(
session_id,
wait(IdleDelivery::NextPrompt),
Sources::default(),
WorkflowRunTracker::new(),
),
}
}
fn of_sources(
session_id: String,
idle: IdleDelivery,
sources: BackgroundSources<'_>,
) -> SessionBackground {
SessionBackground::of_sources(
session_id,
wait(idle),
Sources {
processes: sources.processes.cloned(),
subagents: sources.subagents.cloned(),
surfaces: sources.surfaces.cloned(),
pull_requests: sources.pull_requests.cloned(),
peers: sources.peer_sessions.cloned(),
},
sources.workflows.clone(),
)
}
pub(super) fn has_work(session_id: &str, served: &ServedTools, counted: CountedWork) -> bool {
let counted = match served.idle() {
IdleDelivery::WakeTurn => counted,
IdleDelivery::NextPrompt => CountedWork::Live,
};
background_delivery::has_work(session_id, &sources(served), served.held_notices(), counted)
}
pub(super) fn bind(
session_id: String,
served: &ServedTools,
held: Option<HeldNotices>,
) -> BackgroundDelivery {
BackgroundDelivery::bind(session_id, sources(served), held)
}
#[derive(Clone, Copy)]
enum Moment {
TurnStart,
MidTurn,
}
pub(super) struct TurnMailbox {
inbox: ParentMessageInbox,
messages: ParentMessageHandle,
prompt_results: Option<ParentMessage>,
}
impl TurnMailbox {
pub(super) fn steers_only() -> Self {
let (messages, inbox) = message_channel();
Self {
inbox,
messages,
prompt_results: None,
}
}
pub(super) fn messages(&self) -> ParentMessageHandle {
self.messages.clone()
}
pub(super) fn prompt_results(&self) -> Option<&ParentMessage> {
self.prompt_results.as_ref()
}
pub(super) fn install(self, launch: &mut crate::app::agent_binding::ExternalLaunch) {
let Self {
inbox,
prompt_results,
..
} = self;
*launch.parent_messages_mut() = Some(inbox);
launch.overrides_mut().prompt_results = prompt_results;
}
}
struct InFlight {
batch: Batch,
delivered: DeliveryReceipt,
}
pub(super) struct TurnDelivery {
delivery: BackgroundDelivery,
messages: ParentMessageHandle,
in_flight: Option<InFlight>,
activity: AgentActivity,
}
impl TurnDelivery {
pub(super) fn start(
delivery: BackgroundDelivery,
activity: AgentActivity,
) -> (Self, TurnMailbox) {
let (messages, inbox) = message_channel();
let mut turn = Self {
delivery,
messages: messages.clone(),
in_flight: None,
activity,
};
let prompt_results = turn.due(Moment::TurnStart).map(|(message, in_flight)| {
turn.in_flight = Some(in_flight);
message
});
(
turn,
TurnMailbox {
inbox,
messages,
prompt_results,
},
)
}
async fn deliver(&mut self) {
loop {
if let Some(in_flight) = &mut self.in_flight {
let delivered = (&mut in_flight.delivered).await.is_ok();
match (delivered, self.in_flight.take()) {
(true, Some(in_flight)) => self.commit(in_flight),
(false, _) | (true, None) => return,
}
continue;
}
self.activity
.until(|activity| !activity.served_tools_busy())
.await;
let arrived = self.delivery.arrivals();
if let Some((message, in_flight)) = self.due(Moment::MidTurn) {
match self.messages.send_message(message) {
Ok(()) => self.in_flight = Some(in_flight),
Err(_) => return,
}
continue;
}
self.delivery.changed(arrived).await;
}
}
pub(super) fn finish(mut self) -> Option<HeldNotices> {
if let Some(mut in_flight) = self.in_flight.take() {
if in_flight.delivered.try_recv().is_ok() {
self.commit(in_flight);
}
}
let Self { delivery, .. } = self;
delivery.hold()
}
fn due(&mut self, moment: Moment) -> Option<(ParentMessage, InFlight)> {
let lock = notification_delivery::lock();
let batch = self.delivery.collect(&lock);
let due = batch.has_results()
|| match moment {
Moment::TurnStart => self.delivery.has_notices(),
Moment::MidTurn => self.delivery.action_requested(),
};
if !due {
return None;
}
let (model, display) = self.delivery.render(&batch)?;
let (message, delivered) =
ParentMessage::hosted(framed(&model), shown(display), UNDELIVERED.to_owned());
Some((message, InFlight { batch, delivered }))
}
fn commit(&mut self, in_flight: InFlight) {
self.delivery.commit(in_flight.batch, Notices::Offered);
}
}
pub(super) async fn alongside<T>(
delivery: Option<TurnDelivery>,
run: impl Future<Output = T>,
) -> (T, Option<HeldNotices>) {
let Some(mut delivery) = delivery else {
return (run.await, None);
};
tokio::pin!(run);
let ended = tokio::select! {
biased;
ended = &mut run => ended,
() = delivery.deliver() => run.await,
};
(ended, delivery.finish())
}
fn framed(model: &str) -> String {
format!("rho delivered results of background work you started earlier with its tools (not a new task from the user - use them in your current work):\n\n{model}")
}
const UNDELIVERED: &str = "acp: background results were not delivered: the run ended before its next turn; the session's next turn gets them";
fn shown(display: DisplayTranscript) -> Vec<AttachmentEvent> {
let DisplayTranscript(rows) = display;
rows.into_iter()
.filter_map(|row| match row {
DisplayRow::Notification(row) => Some(AttachmentEvent::Message(Box::new(row.card))),
DisplayRow::Notice(text) => Some(AttachmentEvent::Notice(text)),
DisplayRow::Compaction(_) => None,
})
.collect()
}
#[cfg(test)]
#[path = "acp_background_tests.rs"]
mod tests;