use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use super::outcome::format_child_result;
use crate::focus::ProgressSummarizer;
use crate::multi_agent::mailbox::{MailboxHub, MailboxResult, MailboxStatus};
use crate::multi_agent::path::AgentPath;
use crate::multi_agent::registry::AgentRegistry;
#[derive(Clone, Debug)]
pub struct ChildReport {
pub agent_path: String,
pub status: String,
pub result: Option<String>,
pub message: String,
}
#[derive(Clone, Debug)]
pub enum ChildResultEvent {
Progress {
agent_path: String,
status: String,
summary: Option<String>,
},
Batch {
reports: Vec<ChildReport>,
},
}
impl ChildResultEvent {
pub fn agent_path(&self) -> &str {
match self {
Self::Progress { agent_path, .. } => agent_path,
Self::Batch { reports } => reports
.first()
.map(|r| r.agent_path.as_str())
.unwrap_or_default(),
}
}
}
const MAX_ERROR_REASON_CHARS: usize = 160;
fn strip_ansi(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
if c == '\x1b' && chars.peek() == Some(&'[') {
chars.next();
while let Some(&n) = chars.peek() {
chars.next();
if ('@'..='~').contains(&n) {
break;
}
}
} else {
out.push(c);
}
}
out
}
fn error_reason(result_text: Option<&str>) -> Option<String> {
let line = result_text
.map(strip_ansi)
.as_deref()?
.lines()
.map(|l| {
l.chars()
.map(|c| if c.is_control() { ' ' } else { c })
.collect::<String>()
})
.map(|l| l.trim().to_string())
.find(|l| !l.is_empty())?;
let mut reason: String = line.chars().take(MAX_ERROR_REASON_CHARS).collect();
if line.chars().nth(MAX_ERROR_REASON_CHARS).is_some() {
reason.push('…');
}
Some(reason)
}
pub(crate) const HELD_BATCH_REAP_AFTER: Duration = Duration::from_secs(90);
pub fn spawn_watcher(
mailbox: Arc<MailboxHub>,
registry: Arc<Mutex<AgentRegistry>>,
summarizer: Option<Arc<ProgressSummarizer>>,
child_result_tx: Option<mpsc::UnboundedSender<ChildResultEvent>>,
cancel: CancellationToken,
held_reap_after: Duration,
) -> tokio::task::JoinHandle<()> {
let mut seq_rx = mailbox.subscribe_seq();
tokio::spawn(async move {
let mut batch: Vec<MailboxResult> = Vec::new();
let mut batch_first_at: Option<Instant> = None;
let mut reap_tick = tokio::time::interval(held_reap_after);
reap_tick.tick().await;
loop {
tokio::select! {
biased;
_ = cancel.cancelled() => {
force_handover(&mut batch, ®istry, &child_result_tx);
break;
}
_ = reap_tick.tick() => {
let held = batch_first_at.is_some_and(|t| t.elapsed() >= held_reap_after);
if !held {
continue;
}
let any_working = registry
.lock()
.unwrap()
.list()
.iter()
.any(|e| !e.closing && (e.in_flight || e.queue_len > 0));
if any_working {
continue;
}
tracing::info!(
batch_len = batch.len(),
held_for_secs = batch_first_at.map(|t| t.elapsed().as_secs()),
"watcher: held-batch reaper firing — quiescence unachievable, forcing handover"
);
force_handover(&mut batch, ®istry, &child_result_tx);
batch_first_at = None;
}
result = seq_rx.changed() => {
if result.is_err() {
force_handover(&mut batch, ®istry, &child_result_tx);
break;
}
while let Some(r) = mailbox.try_recv_any() {
if matches!(r.status, MailboxStatus::Closed) {
let already_accounted = batch.iter().any(|b| {
b.agent_path == r.agent_path
&& !matches!(b.status, MailboxStatus::Closed)
});
if already_accounted {
tracing::debug!(
agent = %r.agent_path,
"dropping redundant Closed notification"
);
continue;
}
}
if let Some(tx) = &child_result_tx {
let status = status_str(&r.status);
match (&summarizer, &r.status) {
(_, MailboxStatus::Error) => {
let _ = tx.send(ChildResultEvent::Progress {
agent_path: r.agent_path.to_string(),
status: status.to_string(),
summary: error_reason(r.result.as_deref()),
});
}
(Some(s), MailboxStatus::Ok) => {
let _ = tx.send(ChildResultEvent::Progress {
agent_path: r.agent_path.to_string(),
status: status.to_string(),
summary: None,
});
let task = registry
.lock()
.unwrap()
.get(&r.agent_path)
.and_then(|e| e.task.clone());
let agent_name = r.agent_path.name().to_string();
let agent_path = r.agent_path.to_string();
let status = status.to_string();
let result_text = r.result.clone();
let summarizer = Arc::clone(s);
let tx = tx.clone();
tokio::spawn(async move {
let summary = match summarizer
.summarize(
&agent_name,
&status,
task.as_deref(),
result_text.as_deref(),
)
.await
{
Some(text) => Some(text),
None => {
tracing::debug!(
agent = %agent_path,
"progress summary unavailable — plain notice already sent"
);
return;
}
};
let _ = tx.send(ChildResultEvent::Progress {
agent_path,
status,
summary,
});
});
}
_ => {
let _ = tx.send(ChildResultEvent::Progress {
agent_path: r.agent_path.to_string(),
status: status.to_string(),
summary: None,
});
}
}
}
if batch_first_at.is_none() {
batch_first_at = Some(Instant::now());
}
batch.push(r);
}
{
let reg = registry.lock().unwrap();
let q = reg.quiescent();
if !q {
let snapshot = reg.snapshot();
tracing::info!(
batch_len = batch.len(),
agent_count = snapshot.agents.len(),
agents = ?snapshot.agents.iter().map(|a| {
format!("{}: status={}, tool_calls={}, pending={}", a.path, a.status, a.tool_calls, a.pending_results)
}).collect::<Vec<_>>(),
"watcher: quiescent=false, holding batch"
);
}
}
if batch.is_empty() || !registry.lock().unwrap().quiescent() {
continue;
}
let any_real = batch
.iter()
.any(|b| !matches!(b.status, MailboxStatus::Closed));
if !any_real {
batch.clear();
batch_first_at = None;
continue;
}
let batch_paths: Vec<AgentPath> = {
let mut seen = std::collections::BTreeSet::new();
batch
.iter()
.filter(|r| !matches!(r.status, MailboxStatus::Closed))
.filter(|r| seen.insert(r.agent_path.to_string()))
.map(|r| r.agent_path.clone())
.collect()
};
{
let mut reg = registry.lock().unwrap();
for path in &batch_paths {
reg.note_batch_handed_over(path);
}
}
let reports = batch
.drain(..)
.map(|r| format_child_result(&r))
.collect();
batch_first_at = None;
if let Some(tx) = &child_result_tx {
let _ = tx.send(ChildResultEvent::Batch { reports });
}
}
}
}
})
}
fn status_str(status: &MailboxStatus) -> &'static str {
match status {
MailboxStatus::Ok => "ok",
MailboxStatus::Error => "error",
MailboxStatus::Closed => "closed",
}
}
fn force_handover(
batch: &mut Vec<MailboxResult>,
registry: &Arc<Mutex<AgentRegistry>>,
child_result_tx: &Option<mpsc::UnboundedSender<ChildResultEvent>>,
) {
if batch.is_empty() {
return;
}
let any_real = batch
.iter()
.any(|b| !matches!(b.status, MailboxStatus::Closed));
if !any_real {
batch.clear();
return;
}
let batch_paths: Vec<AgentPath> = {
let mut seen = std::collections::BTreeSet::new();
batch
.iter()
.filter(|r| !matches!(r.status, MailboxStatus::Closed))
.filter(|r| seen.insert(r.agent_path.to_string()))
.map(|r| r.agent_path.clone())
.collect()
};
{
let mut reg = registry.lock().unwrap();
for path in &batch_paths {
reg.note_batch_handed_over(path);
}
}
let reports = batch.drain(..).map(|r| format_child_result(&r)).collect();
if let Some(tx) = child_result_tx {
let _ = tx.send(ChildResultEvent::Batch { reports });
}
}
pub fn spawn_watcher_with_watchdog(
mailbox: Arc<MailboxHub>,
registry: Arc<Mutex<AgentRegistry>>,
summarizer: Option<Arc<ProgressSummarizer>>,
child_result_tx: Option<mpsc::UnboundedSender<ChildResultEvent>>,
cancel: CancellationToken,
held_reap_after: Duration,
) -> tokio::task::JoinHandle<()> {
tokio::spawn(async move {
let mut restart_count: u32 = 0;
loop {
if cancel.is_cancelled() {
break;
}
let handle = spawn_watcher(
mailbox.clone(),
registry.clone(),
summarizer.clone(),
child_result_tx.clone(),
cancel.clone(),
held_reap_after,
);
match handle.await {
Ok(()) => {
break;
}
Err(join_err) if join_err.is_panic() => {
restart_count += 1;
let panic_info = join_err
.try_into_panic()
.ok()
.and_then(|p| {
p.downcast_ref::<&str>()
.map(|s| s.to_string())
.or_else(|| p.downcast_ref::<String>().cloned())
})
.unwrap_or_else(|| "unknown panic".to_string());
tracing::warn!(
restart_count,
panic_info = %panic_info,
"watcher task panicked, restarting"
);
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
Err(join_err) => {
tracing::debug!(error = %join_err, "watcher task join error, exiting watchdog");
break;
}
}
}
if restart_count > 0 {
tracing::info!(restart_count, "watcher watchdog exiting after restarts");
}
})
}
#[cfg(test)]
mod tests;