use std::time::Instant;
use rho_sdk::{BoundaryInputRequest, InputBoundary, Session, UserInput};
use tokio::sync::mpsc;
use crate::{
app::{
background_delivery::{BackgroundDelivery, BackgroundSources, HeldNotices, Notices},
boundary_sources::BoundarySource,
},
display_transcript::DisplayTranscript,
session::SessionPersistence,
};
pub(super) struct Delegation {
requests: mpsc::Receiver<BoundaryInputRequest>,
delivery: BackgroundDelivery,
prompt_started: Instant,
background_wait: BackgroundWait,
displays: Option<mpsc::UnboundedSender<(UserInput, DisplayTranscript)>>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum BackgroundWait {
HoldPrompt,
HostWakes,
HostTurns,
}
impl BackgroundWait {
pub(crate) fn of(children: super::ChildAgents, idle_turns: super::IdleTurns) -> Self {
match (children, idle_turns) {
(super::ChildAgents::HostThreads, _) => Self::HostWakes,
(super::ChildAgents::InProcess, super::IdleTurns::Host) => Self::HostTurns,
(super::ChildAgents::InProcess, super::IdleTurns::Never) => Self::HoldPrompt,
}
}
}
impl Delegation {
pub(super) fn attach(
session: &Session,
sources: BackgroundSources<'_>,
wait: BackgroundWait,
storage: Option<&crate::session::Session>,
persistence: SessionPersistence,
held: &mut Option<HeldNotices>,
) -> Result<Self, rho_sdk::Error> {
let (source, requests) = rho_sdk::boundary_input_channel();
session.set_boundary_inputs(Some(source))?;
let session_id = session.id().to_string();
if let Some(manager) = sources.subagents {
manager.bind_parent_session(session_id.clone(), storage, persistence);
}
Ok(Self {
requests,
delivery: BackgroundDelivery::bind(session_id, sources, held.take()),
prompt_started: Instant::now(),
background_wait: wait,
displays: None,
})
}
pub(super) fn offered_displays(&mut self) -> OfferedDisplays {
let (sender, receiver) = mpsc::unbounded_channel();
self.displays = Some(sender);
OfferedDisplays { receiver }
}
pub(super) async fn drive<T>(host: &mut Self, run: impl std::future::Future<Output = T>) -> T {
let service = host.serve();
tokio::pin!(service);
let result = tokio::select! {
biased;
() = &mut service => unreachable!(),
result = run => result,
};
let _ = futures_util::poll!(&mut service);
result
}
pub(super) fn hold_notices(self) -> Option<HeldNotices> {
self.delivery.hold()
}
async fn serve(&mut self) {
while let Some(request) = self.requests.recv().await {
self.respond(request).await;
}
std::future::pending().await
}
async fn respond(&mut self, request: BoundaryInputRequest) {
let boundary = request.boundary();
let (receipt, reservation, notices) = loop {
let arrived = self.delivery.arrivals();
{
let delivery = crate::app::notification_delivery::lock();
let batch = self.delivery.collect(&delivery);
let due = batch.has_results()
|| self.delivery.action_requested()
|| boundary == InputBoundary::BeforeProvider;
if due || !self.has_outstanding_work() {
let notices = match (due, self.background_wait) {
(true, _)
| (false, BackgroundWait::HoldPrompt | BackgroundWait::HostWakes) => {
Notices::Offered
}
(false, BackgroundWait::HostTurns) => Notices::Kept,
};
let rendered = match notices {
Notices::Offered => self.delivery.render(&batch),
Notices::Kept => None,
};
let input = rendered.map(|(model, display)| {
let input = UserInput::text(model);
if let Some(sink) = &self.displays {
let _ = sink.send((input.clone(), display));
}
input
});
break (request.respond(input), batch, notices);
}
}
self.delivery.changed(arrived).await;
};
if receipt.await {
self.delivery.commit(reservation, notices);
}
}
fn has_outstanding_work(&self) -> bool {
let holds = match self.background_wait {
BackgroundWait::HoldPrompt => true,
BackgroundWait::HostWakes | BackgroundWait::HostTurns => false,
};
let started = self.prompt_started;
self.delivery.sources().iter().any(|source| match source {
BoundarySource::Subagents { manager, session } => match self.background_wait {
BackgroundWait::HoldPrompt | BackgroundWait::HostWakes => {
manager.has_active_or_pending_notification(session)
}
BackgroundWait::HostTurns => false,
},
BoundarySource::Workflows { tracker, session } => {
tracker.has_pending_notification(session)
|| (holds && tracker.has_live_started_since(session, started))
}
BoundarySource::Processes(processes) => {
processes.has_pending_notification()
|| (holds && processes.has_live_task_started_since(started))
}
BoundarySource::Surfaces(surfaces) => surfaces.has_action(),
BoundarySource::PullRequests(inbox) => inbox.has_news(),
BoundarySource::Peers(inbox) => inbox.has_notices(),
BoundarySource::Answers(inbox) => inbox.has_answers(),
})
}
}
pub(super) struct OfferedDisplays {
receiver: mpsc::UnboundedReceiver<(UserInput, DisplayTranscript)>,
}
impl OfferedDisplays {
pub(super) fn applied(&mut self, input: &UserInput) -> Option<DisplayTranscript> {
while let Ok((offered, display)) = self.receiver.try_recv() {
if offered == *input {
return Some(display);
}
}
None
}
}
#[cfg(test)]
#[path = "delegation_tests.rs"]
mod tests;