use std::{
collections::HashMap,
sync::{atomic::AtomicU64, Arc, Mutex, MutexGuard, PoisonError},
};
use agent_client_protocol::v2::schema as v2;
use agent_client_protocol::{v2::ConnectionTo as V2ConnectionTo, Client, Error as AcpError};
use rho_protocol::{
methods::JobList, BackgroundItem, BackgroundStatus, BackgroundWork, JobListParams, SessionId,
SessionOptions,
};
use tokio::{sync::oneshot, task::JoinHandle};
use super::{
background::subagent_idle,
child_inputs::ChildInputs,
child_jobs::{started_by, StartedChild},
child_kind::ChildKind,
port::V2Port,
relay::{Relay, Show},
requests,
};
use crate::app::{
acp::{
host_features::{HostFeatures, Toggles},
inputs::{AskGate, Asking},
updates::Updates,
},
daemon_client::Daemon,
};
pub(super) fn child_id(run: &str, session: Option<&SessionId>) -> String {
session.map_or_else(|| run.to_owned(), |session| session.as_str().to_owned())
}
pub(super) struct Subagents {
daemon: Arc<Daemon>,
features: Mutex<HostFeatures>,
children: Mutex<HashMap<String, Child>>,
placeholders: Arc<AtomicU64>,
}
struct Child {
parent: String,
kind: ChildKind,
relay: Option<JoinHandle<()>>,
state: Arc<Mutex<ChildState>>,
}
#[derive(Default)]
pub(super) struct ChildState {
pub(super) told: Option<Told>,
pub(super) ended: Option<BackgroundStatus>,
pub(super) unrelayed: bool,
pub(super) released: bool,
}
impl ChildState {
pub(super) fn settled(&self) -> Option<v2::StateUpdate> {
match (self.told, self.unrelayed, self.ended) {
(Some(Told::Idle), _, _) => None,
(_, true, Some(status)) => Some(subagent_idle(status)),
(_, _, _) => None,
}
}
}
impl Drop for Child {
fn drop(&mut self) {
if let Some(relay) = self.relay.take() {
relay.abort();
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Resumed {
Replayed,
Current,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum ChildReplay {
History,
Live,
}
impl Subagents {
pub(super) fn new(daemon: Arc<Daemon>, placeholders: Arc<AtomicU64>) -> Self {
Self {
daemon,
features: Mutex::default(),
children: Mutex::default(),
placeholders,
}
}
pub(super) fn negotiated(&self, features: HostFeatures) {
*lock(&self.features) = features;
}
pub(super) fn announced(&self, parent: &v2::SessionId, child: &v2::SessionId, kind: ChildKind) {
lock(&self.children)
.entry(child.0.to_string())
.or_insert_with(|| Child {
parent: parent.0.to_string(),
kind,
relay: None,
state: Arc::default(),
});
}
pub(super) fn is_child(&self, session: &str) -> bool {
lock(&self.children).contains_key(session)
}
pub(super) fn is_child_of(&self, parent: &str, child: &str) -> bool {
lock(&self.children)
.get(child)
.is_some_and(|known| known.parent == parent)
}
pub(super) fn follow(
&self,
cx: &V2ConnectionTo<Client>,
parent: &v2::SessionId,
work: &[BackgroundWork],
) {
for (child, session) in sessions(work) {
self.relay(cx, parent, child, session, Show::Live, Asking::now());
}
}
pub(super) fn linked(
&self,
cx: &V2ConnectionTo<Client>,
parent: &v2::SessionId,
child: String,
session: SessionId,
) {
let relayed = lock(&self.children).get(&child).is_some_and(|known| {
known
.relay
.as_ref()
.is_some_and(|relay| !relay.is_finished() || !known.kind.follows_again())
});
if !relayed {
self.relay(cx, parent, child, session, Show::Live, Asking::now());
}
}
pub(super) fn announce(
&self,
cx: &V2ConnectionTo<Client>,
parent: &v2::SessionId,
child: &v2::SessionId,
kind: ChildKind,
title: Option<String>,
) {
self.announced(parent, child, kind);
let announced = v2::SubagentUpdate::new(child.clone());
let announced = match title {
Some(title) => announced.title(title),
None => announced,
};
send(cx, parent, v2::SessionUpdate::SubagentUpdate(announced));
}
pub(super) fn ended(
&self,
cx: &V2ConnectionTo<Client>,
parent: &v2::SessionId,
child: &str,
status: BackgroundStatus,
) {
let Some(state) = lock(&self.children)
.get(child)
.map(|known| Arc::clone(&known.state))
else {
return;
};
let mut state = lock(&state);
state.ended = Some(status);
if let Some(idle) = state.settled() {
let child = v2::SessionId::new(child);
tell(cx, parent, &child, &mut state, Told::Idle, idle);
}
}
pub(super) fn release(&self, parent: &str) {
let released: Vec<Child> = {
let mut children = lock(&self.children);
let ids: Vec<String> = children
.iter()
.filter(|(_, child)| child.parent == parent)
.map(|(id, _)| id.clone())
.collect();
ids.iter().filter_map(|id| children.remove(id)).collect()
};
for child in &released {
lock(&child.state).released = true;
}
drop(released);
}
pub(super) async fn resume(
&self,
cx: &V2ConnectionTo<Client>,
parent: &v2::SessionId,
work: &[BackgroundWork],
resumed: Resumed,
) -> AskGate {
let (gate, asking) = Asking::after();
let mut relayable: HashMap<String, SessionId> = sessions(work).collect();
for started in self.started_by(parent).await {
let id = v2::SessionId::new(started.session.as_str());
self.announce(cx, parent, &id, ChildKind::Started, started.title);
relayable.insert(id.0.to_string(), started.session);
}
let announced: Vec<String> = lock(&self.children)
.iter()
.filter(|(_, child)| child.parent == parent.0.as_ref())
.map(|(id, _)| id.clone())
.collect();
let mut caught_up = Vec::new();
for child in announced {
match (relayable.get(&child), resumed) {
(Some(session), Resumed::Replayed) => {
let (told, waited) = oneshot::channel();
let history = Show::History {
port: V2Port::child(cx.clone(), ChildReplay::History),
caught_up: told,
};
self.relay(cx, parent, child, session.clone(), history, asking.clone());
caught_up.push(waited);
}
(Some(session), Resumed::Current) => {
self.relay(
cx,
parent,
child,
session.clone(),
Show::Skip,
asking.clone(),
);
}
(None, Resumed::Replayed) => {
send(cx, &v2::SessionId::new(child), replay_complete());
}
(None, Resumed::Current) => {}
}
}
for waited in caught_up {
let _ = waited.await;
}
gate
}
async fn started_by(&self, parent: &v2::SessionId) -> Vec<StartedChild> {
match self.daemon.request::<JobList>(&JobListParams {}).await {
Ok(response) => started_by(&response.jobs, &SessionId::new(parent.0.as_ref())),
Err(error) => {
tracing::debug!(%error, "could not list the sessions a session started");
Vec::new()
}
}
}
fn relay(
&self,
cx: &V2ConnectionTo<Client>,
parent: &v2::SessionId,
child: String,
session: SessionId,
show: Show,
asking: Asking,
) {
let mut children = lock(&self.children);
let Some(known) = children.get_mut(&child) else {
return;
};
let child = v2::SessionId::new(child);
let show = match &known.relay {
Some(relay) if !relay.is_finished() => {
show.over(cx, &child);
return;
}
Some(_) => match show {
Show::Live => Show::Skip,
show @ (Show::Skip | Show::History { .. }) => show,
},
None => show,
};
let state = Arc::clone(&known.state);
lock(&state).unrelayed = false;
let features = *lock(&self.features);
let port = Arc::new(V2Port::child(cx.clone(), ChildReplay::Live));
let inputs = known.kind.asks_host().then(|| {
ChildInputs::new(
Arc::clone(&self.daemon),
session.clone(),
&child,
Arc::clone(&port),
features,
Arc::clone(&self.placeholders),
asking,
)
});
let relay = Relay {
daemon: Arc::clone(&self.daemon),
kind: known.kind,
state,
port,
show,
parent: parent.clone(),
child,
session,
updates: Updates::new(features),
position: None,
pending: None,
inputs,
};
known.relay = Some(tokio::spawn(relay.run()));
}
}
fn sessions(work: &[BackgroundWork]) -> impl Iterator<Item = (String, SessionId)> + '_ {
work.iter()
.filter(|work| work.status.is_running())
.filter_map(|work| match &work.item {
BackgroundItem::Subagent {
run,
session: Some(session),
} => Some((child_id(run, Some(session)), session.clone())),
_ => None,
})
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Told {
Running,
RequiresAction,
Idle,
Unknown,
}
pub(super) fn tell(
cx: &V2ConnectionTo<Client>,
parent: &v2::SessionId,
child: &v2::SessionId,
state: &mut ChildState,
told: Told,
update: v2::StateUpdate,
) {
if state.released || state.told == Some(told) {
return;
}
state.told = Some(told);
send(cx, child, v2::SessionUpdate::StateUpdate(update.clone()));
let mirror = v2::SubagentUpdate::new(child.clone()).state(update);
send(cx, parent, v2::SessionUpdate::SubagentUpdate(mirror));
}
pub(super) fn child_options(options: &SessionOptions) -> Result<v2::SessionUpdate, AcpError> {
let options = requests::setup(options, Toggles::Select)?
.config_options
.into_iter()
.map(|mut option| {
if let v2::SessionConfigKind::Select(select) = &mut option.kind {
let current = select.current_value.clone();
let choices = match &select.options {
v2::SessionConfigSelectOptions::Grouped(groups) => {
groups.iter().flat_map(|group| &group.options).collect()
}
v2::SessionConfigSelectOptions::Ungrouped(choices) => choices.iter().collect(),
_ => Vec::new(),
};
let kept: Vec<_> = choices
.into_iter()
.filter(|choice| choice.value == current)
.cloned()
.collect();
if kept.is_empty() {
tracing::warn!(
option = %option.config_id.0,
"a subagent's option offers no choice for its current value"
);
} else {
select.options = kept.into();
}
}
option
})
.collect();
Ok(v2::SessionUpdate::ConfigOptionUpdate(
v2::ConfigOptionUpdate::new(options),
))
}
pub(super) fn replay_complete() -> v2::SessionUpdate {
v2::SessionUpdate::ReplayComplete(v2::ReplayComplete::new())
}
pub(super) fn send(
cx: &V2ConnectionTo<Client>,
session: &v2::SessionId,
update: v2::SessionUpdate,
) {
let notification = v2::UpdateSessionNotification::new(session.clone(), update);
if let Err(error) = cx.send_notification(notification) {
tracing::debug!(%error, "could not send a subagent's update over ACP v2");
}
}
pub(super) fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
#[cfg(test)]
#[path = "subagents_tests.rs"]
mod tests;