use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use async_trait::async_trait;
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use tracing::{debug, info, warn};
use aidaemon_core::ChannelVisibility;
use aidaemon_events::ResponseDeliveryState;
use aidaemon_events::conversation::MessageAttachment;
use aidaemon_tools::semantics::UserRole;
use aidaemon_tools::status::StatusUpdate;
use crate::context::ChannelContext;
use crate::hub::{SessionChannelStore, SessionMap};
use crate::owner_wait::OwnerWaitClock;
use crate::ports::{
AgentResponseEnvelope, ChannelAgentRuntime, InboundMessageRequest, InboundMessageTiming,
MidRunIntent, MidRunReading, RunningWork,
};
use crate::stop::StopRequest;
use crate::tasks::{QueueOutcome, QueuedMessage, TaskRegistry};
const STATUS_INTERVAL: Duration = Duration::from_secs(3);
const STATUS_DRAIN: Duration = Duration::from_secs(3);
const CANCELLED: &str = "Task cancelled";
enum TurnStop {
Cancelled,
Inactive { minutes: u64 },
Agent(anyhow::Error),
}
impl std::fmt::Display for TurnStop {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Cancelled => f.write_str(CANCELLED),
Self::Inactive { minutes } => write!(
f,
"Task auto-cancelled due to inactivity ({minutes} minute{} without progress).",
if *minutes == 1 { "" } else { "s" }
),
Self::Agent(error) => write!(f, "{error}"),
}
}
}
pub struct Turn {
pub session_id: String,
pub text: String,
pub attachments: Vec<MessageAttachment>,
pub user_role: UserRole,
pub channel_ctx: ChannelContext,
pub dedup_key: Option<String>,
pub ingress_timing: Option<InboundMessageTiming>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MidRunPlacement {
Steer,
Queue,
}
pub struct Delivered {
pub state: ResponseDeliveryState,
pub message_ids: Vec<String>,
pub error: Option<String>,
}
impl Delivered {
fn from_send(result: anyhow::Result<Vec<String>>, platform: &str) -> Self {
match result {
Ok(message_ids) => Self {
state: ResponseDeliveryState::PlatformAcknowledged,
message_ids,
error: None,
},
Err(error) => {
warn!(platform, %error, "Failed to send a reply");
Self {
state: ResponseDeliveryState::Failed,
message_ids: Vec::new(),
error: Some(format!("{platform}_send_failed")),
}
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TurnEnd {
Delivered,
Empty,
Failed,
Cancelled,
}
#[async_trait]
pub trait TurnSurface: Send + Sync + 'static {
fn platform(&self) -> &'static str;
async fn say(&self, text: &str) -> anyhow::Result<Vec<String>>;
async fn edit(&self, _message_id: &str, _text: &str) -> anyhow::Result<bool> {
Ok(false)
}
fn show_working(&self, stop: CancellationToken, heartbeat: Arc<AtomicU64>, stale_secs: u64);
fn card_sink(&self) -> Option<Arc<dyn crate::live_status::SurfaceSink>> {
None
}
async fn card_kept(&self, _message_id: &str) {}
fn show_status(
&self,
updates: mpsc::Receiver<StatusUpdate>,
_private: bool,
) -> Result<JoinHandle<()>, mpsc::Receiver<StatusUpdate>> {
Err(updates)
}
fn status_settles_before_reply(&self) -> bool {
false
}
async fn deliver(&self, _envelope: &AgentResponseEnvelope, reply: &str) -> Delivered {
Delivered::from_send(self.say(reply).await, self.platform())
}
async fn turn_ended(&self, _ended: TurnEnd) {}
async fn before_queued(&self, queued: QueuedMessage) -> QueuedMessage {
queued
}
}
tokio::task_local! {
static TURN_OVER: TurnOver;
}
#[derive(Clone)]
pub struct TurnOver {
over: CancellationToken,
requested_at: chrono::DateTime<chrono::Utc>,
}
impl Default for TurnOver {
fn default() -> Self {
Self {
over: CancellationToken::new(),
requested_at: chrono::Utc::now(),
}
}
}
impl TurnOver {
pub fn requested_at(&self) -> chrono::DateTime<chrono::Utc> {
self.requested_at
}
pub fn end(&self) {
self.over.cancel();
}
pub fn current() -> Option<Self> {
TURN_OVER.try_with(Clone::clone).ok()
}
pub async fn wait(&self) {
self.over.cancelled().await;
}
pub fn is_over(&self) -> bool {
self.over.is_cancelled()
}
pub async fn within<F: std::future::Future>(&self, future: F) -> F::Output {
TURN_OVER.scope(self.clone(), future).await
}
}
#[derive(Clone)]
struct TurnCard {
live: Arc<tokio::sync::Mutex<crate::live_status::LiveStatus>>,
sink: Arc<dyn crate::live_status::SurfaceSink>,
}
impl TurnCard {
fn new(sink: Arc<dyn crate::live_status::SurfaceSink>) -> Self {
Self {
live: Arc::default(),
sink,
}
}
async fn deliver(
&self,
surface: &dyn TurnSurface,
envelope: &AgentResponseEnvelope,
reply: &str,
) -> Delivered {
surface.deliver(envelope, reply).await
}
async fn close(&self, surface: &dyn TurnSurface) {
let mut live = self.live.lock().await;
live.close(self.sink.as_ref()).await;
if let Some(id) = live.kept_card_message_id() {
surface.card_kept(&id).await;
}
}
}
pub struct TurnStart<'a> {
pub session_id: &'a str,
pub turn: u64,
pub platform: &'static str,
pub text: &'a str,
pub attachments: &'a [MessageAttachment],
pub user_role: UserRole,
pub description: &'a str,
pub channel_ctx: &'a crate::context::ChannelContext,
}
pub struct TurnFinish<'a> {
pub session_id: &'a str,
pub turn: u64,
pub platform: &'static str,
pub end: TurnEnd,
pub reply: &'a str,
pub handed_off: bool,
pub error: Option<&'a str>,
pub model: Option<&'a str>,
}
pub trait TurnObserver: Send + Sync {
fn turn_started(&self, turn: &TurnStart<'_>);
fn followup_started(&self, _session_id: &str, _turn: u64, _description: &str) {}
fn turn_status(&self, session_id: &str, turn: u64, update: &StatusUpdate);
fn turn_finished(&self, turn: &TurnFinish<'_>);
fn run_changed(&self, _change: &RunChange) {}
fn team_changed(&self, _team: &TeamChange) {}
fn board_posted(&self, _post: &BoardPostChange) {}
fn history_marked(&self, _mark: &HistoryMark) {}
fn session_erased(&self, _session_id: &str) {}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HistoryMark {
pub session_id: String,
pub id: String,
pub text: String,
pub at_ms: u64,
pub kind: HistoryMarkKind,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HistoryMarkKind {
FromConversation {
conversation: String,
label: String,
message: String,
in_reply_to: Option<String>,
},
ToConversation {
conversation: String,
label: String,
message: String,
in_reply_to: Option<String>,
},
LeadChange { from: String, to: String },
}
#[derive(Debug, Clone)]
pub struct RunChange {
pub session_id: String,
pub id: String,
pub view: aidaemon_core::card::HelperView,
pub activity: Option<String>,
pub activity_kind: Option<aidaemon_core::card::AgentStepKind>,
pub agent: Option<String>,
pub agent_mark: Option<String>,
pub group: Option<String>,
pub edited: Vec<String>,
pub continues: Option<String>,
pub thread: Option<String>,
pub keeps_session: bool,
pub accepts_mid_run: bool,
pub queued: bool,
pub result: Option<crate::turns::RunResult>,
pub asked: Option<crate::turns::RunAsk>,
pub started_at: chrono::DateTime<chrono::Utc>,
pub ended_at: Option<chrono::DateTime<chrono::Utc>>,
pub step_only: bool,
pub team: Option<RunTeam>,
pub seen_checks: Vec<SeenCheck>,
pub tokens: Option<u64>,
pub wrote: Vec<String>,
pub pulse: RunPulse,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct RunPulse {
pub step_since: Option<chrono::DateTime<chrono::Utc>>,
pub step_open: bool,
pub said: Option<String>,
pub said_at: Option<chrono::DateTime<chrono::Utc>>,
pub background: Vec<RunBackground>,
pub output_at: Option<chrono::DateTime<chrono::Utc>>,
pub input_taken_at: Option<chrono::DateTime<chrono::Utc>>,
}
impl RunPulse {
pub fn answer_after(&self, delivered: chrono::DateTime<chrono::Utc>) -> Option<&str> {
let from = match self.input_taken_at {
Some(taken) if taken > delivered => taken,
Some(_) => return None,
None => delivered,
};
self.said
.as_deref()
.filter(|_| self.said_at.is_some_and(|at| at >= from))
}
pub fn waiting_on_background(&self) -> bool {
!self.step_open && !self.background.is_empty()
}
pub fn shown_since(
&self,
kind: Option<aidaemon_core::card::AgentStepKind>,
) -> Option<chrono::DateTime<chrono::Utc>> {
if self.waiting_on_background() {
return self.background.iter().filter_map(|work| work.since).min();
}
match kind {
None | Some(aidaemon_core::card::AgentStepKind::Wait) => None,
Some(_) => self.step_since,
}
}
pub fn between_steps(&self, kind: Option<aidaemon_core::card::AgentStepKind>) -> bool {
!self.step_open
&& self.background.is_empty()
&& !matches!(kind, None | Some(aidaemon_core::card::AgentStepKind::Wait))
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct RunBackground {
pub what: Option<String>,
pub since: Option<chrono::DateTime<chrono::Utc>>,
}
impl RunBackground {
pub fn new(what: Option<String>, since: Option<chrono::DateTime<chrono::Utc>>) -> Self {
Self { what, since }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SeenCheck {
pub program: String,
pub subcommand: Option<String>,
pub passed: Option<bool>,
pub failures: u32,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RunTeam {
pub tree: String,
pub peer: String,
pub lead_run: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TeamChange {
pub session_id: String,
pub tree: String,
pub lead_agent: String,
pub members: Vec<TeamMember>,
pub posts: u64,
pub overlaps: Vec<TeamOverlap>,
pub questions: Vec<TeamQuestion>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TeamQuestion {
pub seq: u64,
pub from: String,
pub question: String,
pub options: Vec<String>,
pub lead_run: Option<String>,
pub answered: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TeamOverlap {
pub files: Vec<String>,
pub peers: Vec<String>,
pub lead_run: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TeamWait {
Member(String),
Board,
Conversation(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TeamWorkspace {
ReadOnly,
Isolated,
Scoped,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TeamMember {
pub peer: String,
pub parent: Option<String>,
pub agent: String,
pub title: String,
pub state: TeamMemberState,
pub run: Option<String>,
pub workspace: TeamWorkspace,
pub branch: Option<String>,
pub started_at_ms: Option<u64>,
pub ended_at_ms: Option<u64>,
pub waiting_on: Option<TeamWait>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TeamMemberState {
Queued,
Running,
Completed,
Failed,
Cancelled,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BoardPostChange {
pub session_id: String,
pub tree: String,
pub seq: u64,
pub from: String,
pub to: Option<String>,
pub topic: String,
pub body: String,
pub untrusted: bool,
pub at_ms: Option<u64>,
pub lead_run: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RunAsk {
pub text: String,
pub by_owner: bool,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RunResult {
pub text: String,
pub claims: Option<RunClaims>,
pub mismatches: Vec<RunMismatch>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RunClaims {
pub summary: String,
pub changed_files: Vec<String>,
pub checks: Vec<(String, bool)>,
pub open_questions: Vec<String>,
pub needs_owner: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RunMismatch {
ChangeNotSeen { path: String },
ChangeNotClaimed { path: String },
CheckNotRun { command: String },
CheckFailed { command: String },
}
#[derive(Clone, Default)]
pub struct TurnWatch(Arc<std::sync::RwLock<Option<Arc<dyn TurnObserver>>>>);
impl TurnWatch {
pub fn set(&self, observer: Arc<dyn TurnObserver>) {
*self.0.write().unwrap_or_else(|p| p.into_inner()) = Some(observer);
}
pub fn observer(&self) -> Option<Arc<dyn TurnObserver>> {
self.0.read().unwrap_or_else(|p| p.into_inner()).clone()
}
}
#[derive(Clone)]
pub struct TurnDeps {
pub agent: Arc<dyn ChannelAgentRuntime>,
pub session_map: SessionMap,
pub sessions: Arc<dyn SessionChannelStore>,
pub task_registry: Arc<TaskRegistry>,
pub watchdog_stale_threshold_secs: u64,
pub watch: TurnWatch,
}
type QueuedNotices = std::collections::HashMap<String, Vec<(String, String)>>;
#[derive(Clone)]
pub struct TurnRunner {
pub(crate) deps: TurnDeps,
queued_notices: Arc<std::sync::Mutex<QueuedNotices>>,
live: crate::mid_run::LiveWork,
}
const MID_RUN_READ_LIMIT: Duration = Duration::from_secs(15);
impl TurnRunner {
pub fn new(deps: TurnDeps) -> Self {
Self {
deps,
queued_notices: Arc::default(),
live: crate::mid_run::LiveWork::default(),
}
}
fn remember_queued_notice(&self, session_id: &str, text: &str, message_id: String) {
if let Ok(mut notices) = self.queued_notices.lock() {
notices
.entry(session_id.to_string())
.or_default()
.push((text.to_string(), message_id));
}
}
fn take_queued_notice(&self, session_id: &str, text: &str) -> Option<String> {
let mut notices = self.queued_notices.lock().ok()?;
let session = notices.get_mut(session_id)?;
let at = session.iter().position(|(queued, _)| queued == text)?;
let (_, message_id) = session.remove(at);
if session.is_empty() {
notices.remove(session_id);
}
Some(message_id)
}
fn forget_queued_notices(&self, session_id: &str) {
if let Ok(mut notices) = self.queued_notices.lock() {
notices.remove(session_id);
}
}
pub async fn register_chat(
&self,
session_id: &str,
channel_name: &str,
context: &crate::context::ChannelContext,
) {
self.register_session(session_id, channel_name).await;
let shared = !matches!(
context.visibility,
aidaemon_core::ChannelVisibility::Private | aidaemon_core::ChannelVisibility::Internal
);
let _ = self
.deps
.sessions
.chat_seen(session_id, channel_name, shared)
.await;
}
pub async fn register_session(&self, session_id: &str, channel_name: &str) {
self.deps
.session_map
.write()
.await
.insert(session_id.to_string(), channel_name.to_string());
let _ = self
.deps
.sessions
.save_session_channel(session_id, channel_name)
.await;
}
pub async fn submit(&self, surface: Arc<dyn TurnSurface>, turn: Turn) {
self.submit_placed(surface, turn, None).await;
}
pub async fn submit_placed(
&self,
surface: Arc<dyn TurnSurface>,
turn: Turn,
placement: Option<MidRunPlacement>,
) {
if is_cancel_word(&turn.text) {
let reply = self
.cancel(&turn.session_id, turn.user_role, StopRequest::Bare)
.await;
let _ = surface.say(&reply).await;
self.record_exchange(&turn, &reply).await;
return;
}
let registry = &self.deps.task_registry;
let session_id = turn.session_id.clone();
let dedup_key = turn.dedup_key.as_deref();
if self.deps.agent.needs_missing_model(&session_id).await {
if registry.mark_seen(&session_id, &turn.text, dedup_key).await {
let _ = surface.say(crate::ports::NO_MODEL_LINE).await;
self.record_exchange(&turn, crate::ports::NO_MODEL_LINE)
.await;
}
return;
}
if !registry.has_running_task(&session_id).await
&& turn.channel_ctx.in_run.is_none()
&& !turn.channel_ctx.fresh_agent_session
{
match self.read_between_runs(&turn).await {
Some(BetweenRuns::Stop { request, also_asks }) => {
if !registry.mark_seen(&session_id, &turn.text, dedup_key).await {
return;
}
let reply = self.cancel(&session_id, turn.user_role, request).await;
if !also_asks {
let _ = surface.say(&reply).await;
self.record_exchange(&turn, &reply).await;
return;
}
registry
.unmark_seen(&session_id, &turn.text, dedup_key)
.await;
}
Some(BetweenRuns::Status) => {
if registry.mark_seen(&session_id, &turn.text, dedup_key).await {
let answer = crate::mid_run::running_work_reply(
&self.running_work(&session_id).await,
);
let reply = crate::presentation::prepare_chat_message(&answer);
let _ = surface.say(&reply).await;
self.record_exchange(&turn, &reply).await;
}
return;
}
None => {}
}
}
if registry.has_running_task(&session_id).await {
let directed_to_agent =
turn.channel_ctx.in_run.is_some() || turn.channel_ctx.fresh_agent_session;
let mut steerable = !directed_to_agent;
let mut unread = false;
let reading = if directed_to_agent {
None
} else {
match placement {
Some(MidRunPlacement::Steer) => None,
Some(MidRunPlacement::Queue) => {
steerable = false;
None
}
None => {
let reading = self.read_mid_run(&turn).await;
if reading.is_none() {
unread = Self::mid_run_readable(&turn);
}
reading
}
}
};
match reading {
Some(
reading @ MidRunReading {
intent: MidRunIntent::StopsWork,
..
},
) => {
if !registry.mark_seen(&session_id, &turn.text, dedup_key).await {
return;
}
let reply = self
.cancel(&session_id, turn.user_role, stop_request(&reading))
.await;
if !reading.also_asks {
let _ = surface.say(&reply).await;
self.record_exchange(&turn, &reply).await;
return;
}
registry
.unmark_seen(&session_id, &turn.text, dedup_key)
.await;
steerable = false;
}
Some(MidRunReading {
intent: MidRunIntent::AboutRunningWork,
..
}) => {
if registry.mark_seen(&session_id, &turn.text, dedup_key).await {
let answer = crate::mid_run::running_work_reply(
&self.running_work(&session_id).await,
);
let reply = crate::presentation::prepare_chat_message(&answer);
let _ = surface.say(&reply).await;
self.record_exchange(&turn, &reply).await;
}
return;
}
Some(MidRunReading {
intent: MidRunIntent::Unrelated,
..
}) => steerable = false,
Some(MidRunReading {
intent: MidRunIntent::ChangesWork,
..
})
| None => {}
}
let mut queued = QueuedMessage::new(
&turn.text,
turn.user_role,
turn.channel_ctx.clone(),
turn.attachments.clone(),
);
if matches!(placement, Some(MidRunPlacement::Queue)) {
queued = queued.placed_for_later();
} else if !steerable {
queued = queued.not_steerable();
}
if placement.is_some() {
queued = queued.listed_by_client();
}
if let Some(timing) = turn.ingress_timing.clone() {
queued = queued.with_ingress_timing(timing);
}
match registry
.queue_message_if_running(&session_id, queued, dedup_key)
.await
{
QueueOutcome::Queued(position) => {
if position <= 3 {
let notice = if steerable && crate::owner_wait::approval_open(&session_id) {
Some(crate::presentation::after_approval_notice())
} else if unread {
Some(crate::mid_run::unread_message_notice(
&self.running_work(&session_id).await,
))
} else if placement.is_some() {
None
} else {
Some(crate::presentation::queued_message_notice(
!turn.attachments.is_empty() || !steerable,
))
};
if let Some(notice) = notice
&& let Ok(ids) = surface.say(¬ice).await
&& let [message_id] = ids.as_slice()
{
self.remember_queued_notice(
&session_id,
&turn.text,
message_id.clone(),
);
}
}
return;
}
QueueOutcome::Duplicate => {
debug!(session_id, "Dropped duplicate queued message");
return;
}
QueueOutcome::NoRunningTask => {
info!(
session_id,
"Task finished during queue attempt — processing message directly"
);
}
}
}
if !registry.mark_seen(&session_id, &turn.text, dedup_key).await {
debug!(
session_id,
"Dropped duplicate message (direct processing race)"
);
return;
}
let runner = self.clone();
tokio::spawn(async move { runner.run(surface, turn).await });
}
async fn running_work(&self, session_id: &str) -> RunningWork {
let listed = crate::stop::running_work(
&self.deps.task_registry,
self.deps.agent.as_ref(),
session_id,
)
.await;
let now = chrono::Utc::now();
let mut work = self.running_turn(session_id, now).await;
work.running = listed.items(now);
work
}
async fn running_turn(
&self,
session_id: &str,
now: chrono::DateTime<chrono::Utc>,
) -> RunningWork {
let running = self
.deps
.task_registry
.list_for_session(session_id)
.await
.into_iter()
.find(|entry| matches!(entry.status, crate::tasks::TaskStatus::Running));
let (request, elapsed) = running.map_or_else(
|| (String::new(), Duration::ZERO),
|entry| {
let elapsed = (now - entry.started_at).to_std().unwrap_or_default();
(entry.description, elapsed)
},
);
let runs = self.deps.agent.chat_runs(session_id).await;
self.live.snapshot(session_id, &request, elapsed, runs)
}
fn mid_run_readable(turn: &Turn) -> bool {
turn.user_role == UserRole::Owner
&& turn.attachments.is_empty()
&& !turn.text.trim().is_empty()
}
async fn read_mid_run(&self, turn: &Turn) -> Option<MidRunReading> {
if !Self::mid_run_readable(turn) {
return None;
}
let work = self.running_work(&turn.session_id).await;
let reading = tokio::time::timeout(
MID_RUN_READ_LIMIT,
self.deps
.agent
.read_mid_run_message(&turn.session_id, &turn.text, &work),
)
.await
.ok()
.flatten();
info!(
session_id = %turn.session_id,
intent = ?reading.as_ref().map(|r| r.intent),
"Read a message sent mid-run"
);
reading
}
async fn cancel(&self, session_id: &str, role: UserRole, request: StopRequest) -> String {
if role != UserRole::Owner {
return "Only the owner can cancel running work in this session.".to_string();
}
crate::stop::stop(
&self.deps.task_registry,
self.deps.agent.as_ref(),
session_id,
request,
)
.await
}
async fn record_exchange(&self, turn: &Turn, reply: &str) {
self.deps
.agent
.record_control_exchange(
&turn.session_id,
&turn.text,
turn.user_role,
&turn.channel_ctx,
reply,
)
.await;
}
async fn read_between_runs(&self, turn: &Turn) -> Option<BetweenRuns> {
if turn.user_role != UserRole::Owner
|| !turn.attachments.is_empty()
|| turn.text.trim().is_empty()
{
return None;
}
let list = crate::stop::running_work(
&self.deps.task_registry,
self.deps.agent.as_ref(),
&turn.session_id,
)
.await;
if list.entries.is_empty() {
return None;
}
let work = RunningWork {
running: list.items(chrono::Utc::now()),
..RunningWork::default()
};
let reading = tokio::time::timeout(
MID_RUN_READ_LIMIT,
self.deps
.agent
.read_mid_run_message(&turn.session_id, &turn.text, &work),
)
.await
.ok()
.flatten()?;
info!(
session_id = %turn.session_id,
intent = ?reading.intent,
"Read a message sent while background work runs"
);
match reading.intent {
MidRunIntent::StopsWork => Some(BetweenRuns::Stop {
request: stop_request(&reading),
also_asks: reading.also_asks,
}),
MidRunIntent::AboutRunningWork => Some(BetweenRuns::Status),
MidRunIntent::ChangesWork | MidRunIntent::Unrelated => None,
}
}
pub async fn run(self, surface: Arc<dyn TurnSurface>, first: Turn) {
let registry = Arc::clone(&self.deps.task_registry);
let agent = Arc::clone(&self.deps.agent);
let stale_secs = self.deps.watchdog_stale_threshold_secs;
let session_id = first.session_id;
let mut text = first.text;
let mut attachments = first.attachments;
let mut role = first.user_role;
let mut channel_ctx = first.channel_ctx;
let mut timing = first.ingress_timing;
let indicator = Arc::new(std::sync::Mutex::new(CancellationToken::new()));
let _indicator_guard = CancelOnDrop(indicator.clone());
loop {
let owner_wait = OwnerWaitClock::default();
let description = crate::presentation::word_preview(&text, 80);
let (task_id, cancel) = registry.register(&session_id, &description).await;
let observer = self.deps.watch.observer();
if let Some(observer) = observer.as_ref() {
observer.turn_started(&TurnStart {
session_id: &session_id,
turn: task_id,
platform: surface.platform(),
text: &text,
attachments: &attachments,
user_role: role,
description: &description,
channel_ctx: &channel_ctx,
});
}
self.live.begin(&session_id, task_id);
let heartbeat = Arc::new(AtomicU64::new(now_secs()));
registry.set_heartbeat(task_id, heartbeat.clone()).await;
let working = CancellationToken::new();
if let Ok(mut slot) = indicator.lock() {
*slot = working.clone();
}
surface.show_working(working.clone(), heartbeat.clone(), stale_secs);
registry.set_typing_cancel(task_id, working.clone()).await;
let (status_tx, mut run_updates) = mpsc::channel::<StatusUpdate>(16);
let (shown_tx, status_rx) = mpsc::channel::<StatusUpdate>(16);
{
let live = self.live.clone();
let session_id = session_id.clone();
let observer = observer.clone();
tokio::spawn(async move {
while let Some(update) = run_updates.recv().await {
if matches!(
update,
StatusUpdate::ReplyText(_) | StatusUpdate::MessageTaken { .. }
) {
if let Some(observer) = observer.as_ref() {
observer.turn_status(&session_id, task_id, &update);
}
continue;
}
live.record(&session_id, task_id, &update);
if let Some(observer) = observer.as_ref() {
observer.turn_status(&session_id, task_id, &update);
}
let _ = shown_tx.send(update).await;
}
});
}
let private = channel_ctx.visibility == ChannelVisibility::Private;
let card = surface.card_sink().map(TurnCard::new);
let settle = CancellationToken::new();
let status_task = match &card {
Some(card) => tokio::spawn(show_on_card(
surface.clone(),
card.clone(),
status_rx,
private,
settle.clone(),
)),
None => surface
.show_status(status_rx, private)
.unwrap_or_else(|updates| throttled_status(surface.clone(), updates, private)),
};
let turn_over = TurnOver::default();
let over_when_dropped = turn_over.over.clone().drop_guard();
if let Some(timing) = timing.as_mut() {
timing.mark_dispatched_now();
}
let result = tokio::select! {
result = turn_over.within(OwnerWaitClock::within(
Some(owner_wait.clone()),
agent.handle_inbound_message(InboundMessageRequest {
session_id: session_id.clone(),
user_text: text.clone(),
attachments: attachments.clone(),
status_tx: Some(status_tx),
user_role: role,
channel_ctx: channel_ctx.clone(),
heartbeat: Some(heartbeat.clone()),
ingress_timing: timing.clone(),
}),
)) => result.map_err(TurnStop::Agent),
_ = cancel.cancelled() => Err(TurnStop::Cancelled),
stale_mins = wait_for_stale_heartbeat(heartbeat.clone(), stale_secs, 4), if stale_secs > 0 => {
Err(TurnStop::Inactive { minutes: stale_mins })
},
};
working.cancel();
self.live.end(&session_id, task_id);
let mut status_task = status_task;
let run_finished = matches!(
&result,
Ok(envelope) if envelope.disposition
!= aidaemon_events::AssistantResponseDisposition::BackgroundHandoff
);
if card.is_some() {
settle.cancel();
let _ = tokio::time::timeout(STATUS_DRAIN, &mut status_task).await;
} else if run_finished && surface.status_settles_before_reply() {
let _ = tokio::time::timeout(STATUS_DRAIN, &mut status_task).await;
}
status_task.abort();
let error = match result {
Ok(envelope) => {
let platform = surface.platform();
let _ = agent
.record_response_delivery(
&session_id,
envelope.delivery(
platform,
ResponseDeliveryState::Queued,
Vec::new(),
None,
),
)
.await;
let reply = crate::presentation::prepare_chat_message(&envelope.text);
let tasks: Vec<(u64, String)> = registry
.list_for_session(&session_id)
.await
.into_iter()
.map(|entry| (entry.id, entry.description))
.collect();
let reply = crate::presentation::render_task_numbers(&reply, &tasks);
let empty = reply.trim().is_empty();
let delivered = if empty {
Delivered {
state: ResponseDeliveryState::PlatformAcknowledged,
message_ids: Vec::new(),
error: None,
}
} else {
match &card {
Some(card) => card.deliver(surface.as_ref(), &envelope, &reply).await,
None => surface.deliver(&envelope, &reply).await,
}
};
let _ = agent
.record_response_delivery(
&session_id,
envelope.delivery(
platform,
delivered.state,
delivered.message_ids,
delivered.error,
),
)
.await;
let end = if empty {
TurnEnd::Empty
} else {
TurnEnd::Delivered
};
if let Some(observer) = observer.as_ref() {
observer.turn_finished(&TurnFinish {
session_id: &session_id,
turn: task_id,
platform,
end,
reply: if empty { "" } else { &reply },
handed_off: envelope.disposition
== aidaemon_events::AssistantResponseDisposition::BackgroundHandoff,
error: None,
model: envelope.model.as_deref(),
});
}
if let Some(card) = &card {
card.close(surface.as_ref()).await;
}
surface.turn_ended(end).await;
None
}
Err(stop) => {
let message = stop.to_string();
let cancelled = matches!(stop, TurnStop::Cancelled);
match &stop {
TurnStop::Cancelled => info!("Task #{} cancelled", task_id),
TurnStop::Inactive { .. } => {
info!("Task #{} auto-cancelled by stale watchdog", task_id);
let _ = surface.say(&format!("⚠️ {message}")).await;
}
TurnStop::Agent(error) => {
warn!("Agent error: {}", error);
let _ = surface.say(&format!("Error: {message}")).await;
}
}
if let Some(card) = &card {
card.close(surface.as_ref()).await;
}
surface
.turn_ended(if cancelled {
TurnEnd::Cancelled
} else {
TurnEnd::Failed
})
.await;
if let Some(observer) = observer.as_ref() {
observer.turn_finished(&TurnFinish {
session_id: &session_id,
turn: task_id,
platform: surface.platform(),
end: if cancelled {
TurnEnd::Cancelled
} else {
TurnEnd::Failed
},
reply: "",
handed_off: false,
error: Some(&message),
model: None,
});
}
Some((message, cancelled))
}
};
drop(over_when_dropped);
if let Some((error, cancelled)) = error.as_ref() {
let status = if *cancelled {
aidaemon_events::TaskStatus::Cancelled
} else {
aidaemon_events::TaskStatus::Failed
};
if let Err(terminalize_error) = agent
.terminalize_supervised_task(&session_id, status, error.clone())
.await
{
warn!(%terminalize_error, "Failed to persist supervised task termination");
}
}
let Some(queued) = registry
.finalize_and_drain(
task_id,
&session_id,
error.as_ref().map(|(message, _)| message.as_str()),
)
.await
else {
self.forget_queued_notices(&session_id);
break;
};
tokio::time::sleep(Duration::from_millis(100)).await;
let notice = self.take_queued_notice(&session_id, &queued.text);
let queued = surface.before_queued(queued).await;
let preview = crate::presentation::word_preview(&queued.text, 50);
info!(session_id, "Processing queued message: {}", preview);
let starting = crate::presentation::queued_message_starting(&queued.text);
let edited = match notice {
Some(message_id) => matches!(surface.edit(&message_id, &starting).await, Ok(true)),
None => false,
};
if !edited && !queued.listed_by_client {
let _ = surface.say(&starting).await;
}
text = queued.text;
role = queued.user_role;
channel_ctx = queued.channel_ctx;
attachments = queued.attachments;
timing = queued.ingress_timing;
}
}
}
struct CancelOnDrop(Arc<std::sync::Mutex<CancellationToken>>);
impl Drop for CancelOnDrop {
fn drop(&mut self) {
if let Ok(token) = self.0.lock() {
token.cancel();
}
}
}
fn now_secs() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
pub fn is_cancel_word(text: &str) -> bool {
matches!(
text.trim().to_lowercase().as_str(),
"cancel" | "stop" | "abort"
)
}
enum BetweenRuns {
Stop {
request: StopRequest,
also_asks: bool,
},
Status,
}
fn stop_request(reading: &MidRunReading) -> StopRequest {
if reading.stop.is_empty() {
StopRequest::Bare
} else {
StopRequest::Numbers(reading.stop.clone())
}
}
fn throttled_status(
surface: Arc<dyn TurnSurface>,
mut updates: mpsc::Receiver<StatusUpdate>,
private: bool,
) -> JoinHandle<()> {
tokio::spawn(async move {
let mut last_sent: Option<tokio::time::Instant> = None;
while let Some(update) = updates.recv().await {
let immediate = update.requires_immediate_delivery();
if !private && !immediate {
continue;
}
let now = tokio::time::Instant::now();
if !immediate && last_sent.is_some_and(|at| now.duration_since(at) < STATUS_INTERVAL) {
continue;
}
let Some(line) = status_line(&update) else {
continue;
};
let _ = surface.say(&line).await;
last_sent = Some(tokio::time::Instant::now());
}
})
}
async fn show_on_card(
surface: Arc<dyn TurnSurface>,
card: TurnCard,
mut updates: mpsc::Receiver<StatusUpdate>,
private: bool,
settle: CancellationToken,
) {
let mut last_sent: Option<tokio::time::Instant> = None;
let mut tick = tokio::time::interval(Duration::from_secs(5));
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
let mut last = false;
let backlog = tokio::select! {
biased;
_ = settle.cancelled() => {
last = true;
let mut backlog = Vec::new();
while let Ok(next) = updates.try_recv() {
backlog.push(next);
}
backlog
}
first = updates.recv() => {
let Some(first) = first else { break };
let mut backlog = vec![first];
while let Ok(next) = updates.try_recv() {
backlog.push(next);
}
backlog
}
_ = tick.tick() => Vec::new(),
};
let mut show_now = last;
for update in backlog {
if update.requires_immediate_delivery() {
if let Some(line) = status_line(&update) {
let _ = surface.say(&line).await;
}
continue;
}
if private {
show_now |= card.live.lock().await.note(&update);
}
}
let due = last_sent.is_none_or(|at| at.elapsed() >= STATUS_INTERVAL);
if private && (show_now || due) {
let sent = card
.live
.lock()
.await
.flush_if_changed(card.sink.as_ref())
.await;
if sent {
last_sent = Some(tokio::time::Instant::now());
}
}
if last {
break;
}
}
}
pub fn status_line(update: &StatusUpdate) -> Option<String> {
let text = status_text(update)?;
Some(match update {
StatusUpdate::UserActionRequired { .. } | StatusUpdate::Checklist(_) => text,
_ => format!("_{text}_"),
})
}
pub fn status_text(update: &StatusUpdate) -> Option<String> {
use aidaemon_core::card::Step;
let progress = |text: String| text;
Some(match update {
StatusUpdate::Thinking(_)
| StatusUpdate::ReplyText(_)
| StatusUpdate::MessageTaken { .. } => return None,
StatusUpdate::ToolStart { kind, .. } if !kind.says_what() => return None,
StatusUpdate::ToolStart { kind, .. } => progress(format!("{}…", kind.words())),
StatusUpdate::ToolProgress { chunk, .. } => {
let preview: String = chunk.chars().take(100).collect();
let more = if chunk.chars().count() > 100 {
"…"
} else {
""
};
progress(format!("📤 {preview}{more}"))
}
StatusUpdate::UserActionRequired { message } => message.clone(),
StatusUpdate::ToolComplete { .. } => return None,
StatusUpdate::ToolCancellable { .. } => return None,
StatusUpdate::ProgressSummary {
elapsed_mins,
summary,
} => progress(format!("📊 Progress ({elapsed_mins} min): {summary}")),
StatusUpdate::IterationWarning { current, threshold } => progress(format!(
"⚠️ Approaching soft limit: {current} of {threshold} iterations"
)),
StatusUpdate::PlanCreated {
description,
total_steps,
..
} => progress(format!(
"📋 Plan created: {description} ({total_steps} steps)"
)),
StatusUpdate::PlanStepStart {
step_index,
total_steps,
description,
..
} => progress(format!(
"▶️ Step {}/{total_steps}: {description}",
step_index + 1
)),
StatusUpdate::PlanStepComplete {
step_index,
total_steps,
description,
summary,
..
} => {
let base = format!(
"✅ Step {}/{total_steps} done: {description}",
step_index + 1
);
match summary {
Some(summary) => progress(format!("{base} - {summary}")),
None => progress(base),
}
}
StatusUpdate::PlanStepFailed {
step_index,
description,
error,
..
} => progress(format!(
"❌ Step {} failed: {description} - {error}",
step_index + 1
)),
StatusUpdate::PlanComplete {
description,
total_steps,
duration_secs,
..
} => progress(format!(
"🎉 Plan complete: {description} ({total_steps} steps in {}m {}s)",
duration_secs / 60,
duration_secs % 60
)),
StatusUpdate::PlanAbandoned { description, .. } => {
progress(format!("🚫 Plan abandoned: {description}"))
}
StatusUpdate::PlanRevised {
description,
reason,
new_total_steps,
..
} => progress(format!(
"🔄 Plan revised: {description} ({new_total_steps} steps) - {reason}"
)),
StatusUpdate::Checklist(plan) => plan.text.clone(),
StatusUpdate::Helper(helper) => progress(crate::live_status::render_card(
&crate::live_status::CardView {
helpers: vec![(helper.clone(), None)],
..Default::default()
},
)?),
StatusUpdate::StepHandedOff { kind, .. } => progress(Step::HandedOff(*kind).words()),
StatusUpdate::CommandOutput { lines, .. } => {
progress(Step::Output { lines: *lines }.words())
}
StatusUpdate::Finished { by_me, total } => progress(crate::live_status::finished_block(
by_me.as_deref(),
total.as_deref(),
)?),
})
}
pub fn repeat_while_working<F, Fut>(
every: Duration,
stop: CancellationToken,
heartbeat: Arc<AtomicU64>,
stale_secs: u64,
mut send: F,
) where
F: FnMut() -> Fut + Send + 'static,
Fut: std::future::Future<Output = ()> + Send,
{
tokio::spawn(async move {
let deadline = tokio::time::Instant::now() + Duration::from_secs(30 * 60);
loop {
send().await;
tokio::select! {
_ = tokio::time::sleep(every) => {
if stale_secs > 0
&& now_secs().saturating_sub(heartbeat.load(Ordering::Relaxed)) > stale_secs
{
break;
}
if tokio::time::Instant::now() >= deadline {
warn!("Working indicator reached its 30-minute limit");
break;
}
}
_ = stop.cancelled() => break,
}
}
});
}
pub async fn wait_for_stale_heartbeat(
heartbeat: Arc<AtomicU64>,
stale_threshold_secs: u64,
check_interval_secs: u64,
) -> u64 {
debug_assert!(stale_threshold_secs > 0);
loop {
tokio::time::sleep(Duration::from_secs(check_interval_secs.max(1))).await;
let last_hb = heartbeat.load(Ordering::Relaxed);
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
if now.saturating_sub(last_hb) > stale_threshold_secs {
return now.saturating_sub(last_hb) / 60;
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn how_a_turn_stopped_is_typed_not_read_from_its_text() {
let stop = super::TurnStop::Agent(anyhow::anyhow!(super::CANCELLED));
assert!(!matches!(stop, super::TurnStop::Cancelled));
assert_eq!(
super::TurnStop::Inactive { minutes: 1 }.to_string(),
"Task auto-cancelled due to inactivity (1 minute without progress)."
);
}
use super::*;
#[tokio::test]
async fn stale_heartbeat_returns_minutes() {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let heartbeat = Arc::new(AtomicU64::new(now.saturating_sub(125)));
let mins = tokio::time::timeout(
Duration::from_secs(3),
wait_for_stale_heartbeat(heartbeat, 60, 1),
)
.await
.expect("stale heartbeat should resolve quickly");
assert!(mins >= 2);
}
struct ScriptedAgent {
release: tokio::sync::Notify,
reading: std::sync::Mutex<Option<MidRunReading>>,
work: std::sync::Mutex<Vec<crate::ports::ChatWork>>,
recorded: std::sync::Mutex<Vec<(String, String)>>,
turns: std::sync::Mutex<Vec<String>>,
}
#[async_trait]
impl crate::ports::AgentIngress for ScriptedAgent {
async fn handle_inbound_message(
&self,
request: InboundMessageRequest,
) -> anyhow::Result<AgentResponseEnvelope> {
self.turns.lock().unwrap().push(request.user_text.clone());
if let Some(status) = request.status_tx.as_ref() {
let _ = status
.send(StatusUpdate::tool_start(
"terminal",
"installing the blog",
aidaemon_core::card::ActivityKind::Run,
))
.await;
}
self.release.notified().await;
Ok(AgentResponseEnvelope {
response_id: "r".into(),
task_id: "t".into(),
turn_id: None,
text: "Done.".into(),
referenced_receipts: Vec::new(),
disposition: Default::default(),
model: None,
})
}
}
#[async_trait]
impl ChannelAgentRuntime for ScriptedAgent {
async fn read_mid_run_message(
&self,
_session_id: &str,
_text: &str,
_work: &RunningWork,
) -> Option<MidRunReading> {
self.reading.lock().unwrap().clone()
}
async fn record_control_exchange(
&self,
_session_id: &str,
owner_text: &str,
_user_role: UserRole,
_channel_ctx: &crate::context::ChannelContext,
reply: &str,
) {
self.recorded
.lock()
.unwrap()
.push((owner_text.to_string(), reply.to_string()));
}
async fn chat_work(&self, _session_id: &str) -> crate::ports::ChatWorkView {
crate::ports::ChatWorkView {
current_request: None,
items: self.work.lock().unwrap().clone(),
}
}
async fn chat_runs(&self, _session_id: &str) -> crate::ports::ChatRuns {
let runs = self
.work
.lock()
.unwrap()
.iter()
.filter_map(|item| {
Some(crate::ports::ChatRun {
id: item.run.clone()?,
view: aidaemon_core::card::HelperView::running(
item.title.trim_start_matches("Sub-agent: "),
true,
Some(aidaemon_core::card::Step::Doing(
aidaemon_core::card::ActivityKind::Run,
)),
),
running_for: Duration::from_secs(60),
started_at: chrono::Utc::now(),
ended_at: None,
activity: None,
activity_kind: None,
agent: None,
agent_mark: None,
group: None,
edited: Vec::new(),
continues: None,
thread: None,
keeps_session: false,
accepts_mid_run: false,
queued: false,
result: None,
asked: None,
this_request: false,
team: None,
seen_checks: Vec::new(),
tokens: None,
wrote: Vec::new(),
pulse: Default::default(),
})
})
.collect();
crate::ports::ChatRuns { runs, plan: None }
}
async fn stop_chat_work(&self, _session_id: &str, key: &str) -> bool {
let mut work = self.work.lock().unwrap();
work.retain(|item| item.key != key);
true
}
async fn terminalize_supervised_task(
&self,
_: &str,
_: aidaemon_events::TaskStatus,
_: String,
) -> anyhow::Result<Option<String>> {
Ok(None)
}
async fn cancel_active_finite_work_for_session(&self, _: &str) -> Vec<String> {
Vec::new()
}
async fn current_model(&self) -> String {
String::new()
}
async fn context_debug_settings(
&self,
_: &str,
_: &str,
) -> (bool, usize, usize, usize, Option<i64>) {
(false, 0, 0, 0, None)
}
async fn set_model(&self, _: String) {}
async fn list_models(&self) -> anyhow::Result<Vec<String>> {
Ok(Vec::new())
}
async fn clear_model_override(&self) {}
async fn clear_session_context(&self, _: &str) -> anyhow::Result<()> {
Ok(())
}
async fn clear_session(&self, _: &str) -> anyhow::Result<()> {
Ok(())
}
}
struct NoSessions;
impl SessionChannelStore for NoSessions {}
#[derive(Default)]
struct Said(std::sync::Mutex<Vec<String>>);
#[async_trait]
impl TurnSurface for Said {
fn platform(&self) -> &'static str {
"test"
}
async fn say(&self, text: &str) -> anyhow::Result<Vec<String>> {
self.0.lock().unwrap().push(text.to_string());
Ok(Vec::new())
}
fn show_working(&self, _: CancellationToken, _: Arc<AtomicU64>, _: u64) {}
}
fn owner_turn(text: &str, key: &str) -> Turn {
Turn {
session_id: "test:mid-run".into(),
text: text.into(),
attachments: Vec::new(),
user_role: UserRole::Owner,
channel_ctx: ChannelContext::private("test"),
dedup_key: Some(key.into()),
ingress_timing: None,
}
}
#[tokio::test]
async fn messages_a_restart_left_waiting_run_in_order() {
let agent = Arc::new(ScriptedAgent {
release: tokio::sync::Notify::new(),
reading: std::sync::Mutex::new(None),
work: std::sync::Mutex::new(Vec::new()),
recorded: Default::default(),
turns: Default::default(),
});
let registry = Arc::new(TaskRegistry::new(10));
let runner = TurnRunner::new(TurnDeps {
agent: agent.clone(),
session_map: Arc::default(),
sessions: Arc::new(NoSessions),
task_registry: registry.clone(),
watchdog_stale_threshold_secs: 0,
watch: TurnWatch::default(),
});
let session = "test:restored";
let waiting = |text: &str| {
crate::tasks::QueuedMessage::new(
text,
UserRole::Owner,
ChannelContext::private("test"),
Vec::new(),
)
.placed_for_later()
};
let snapshot: crate::tasks::QueueSnapshot = [(
session.to_string(),
vec![waiting("first"), waiting("second")],
)]
.into();
assert_eq!(registry.restore_queues(snapshot).await, vec![session]);
let surface = Arc::new(Said::default());
let run = tokio::spawn(runner.clone().run_restored(surface, session));
for expected in 1..=2 {
for _ in 0..400 {
if agent.turns.lock().unwrap().len() == expected {
break;
}
tokio::time::sleep(Duration::from_millis(5)).await;
}
agent.release.notify_one();
}
run.await.unwrap();
assert_eq!(agent.turns.lock().unwrap().as_slice(), ["first", "second"]);
assert_eq!(registry.queue_len(session).await, 0);
}
#[tokio::test]
async fn a_mid_run_message_is_answered_joined_or_kept_by_its_reading() {
let agent = Arc::new(ScriptedAgent {
release: tokio::sync::Notify::new(),
reading: std::sync::Mutex::new(None),
work: std::sync::Mutex::new(Vec::new()),
recorded: Default::default(),
turns: Default::default(),
});
let registry = Arc::new(TaskRegistry::new(10));
let runner = TurnRunner::new(TurnDeps {
agent: agent.clone(),
session_map: Arc::default(),
sessions: Arc::new(NoSessions),
task_registry: registry.clone(),
watchdog_stale_threshold_secs: 0,
watch: TurnWatch::default(),
});
let surface = Arc::new(Said::default());
let session = "test:mid-run";
runner
.submit(surface.clone(), owner_turn("Set up two demo sites", "m1"))
.await;
for _ in 0..200 {
if registry.has_running_task(session).await
&& runner.running_work(session).await.last_step.is_some()
{
break;
}
tokio::time::sleep(Duration::from_millis(5)).await;
}
let set = |reading: Option<MidRunReading>| *agent.reading.lock().unwrap() = reading;
let last = |surface: &Said| {
surface
.0
.lock()
.unwrap()
.last()
.cloned()
.unwrap_or_default()
};
set(Some(MidRunReading {
intent: MidRunIntent::AboutRunningWork,
stop: Vec::new(),
also_asks: false,
}));
runner
.submit(surface.clone(), owner_turn("How is it going so far?", "m2"))
.await;
let reply = last(&surface);
assert!(
reply.starts_with("Still working on \"Set up two demo sites\""),
"{reply}"
);
assert!(reply.contains("Latest step: Running a command"), "{reply}");
runner
.submit(
surface.clone(),
owner_turn("Send me the screenshots now.", "m3"),
)
.await;
let reply = last(&surface);
assert!(
reply.starts_with("Still working on \"Set up two demo sites\""),
"{reply}"
);
assert_eq!(registry.queue_len(session).await, 0);
set(Some(MidRunReading {
intent: MidRunIntent::Unrelated,
stop: Vec::new(),
also_asks: false,
}));
runner
.submit(
surface.clone(),
owner_turn("What is the capital of Peru?", "m4"),
)
.await;
assert_eq!(
last(&surface),
crate::presentation::queued_message_notice(true)
);
let ctx = ChannelContext::private("test");
assert!(
registry
.take_steering_messages(session, UserRole::Owner, &ctx)
.await
.is_empty()
);
registry.clear_queue(session).await;
for (reading, key) in [
(
Some(MidRunReading {
intent: MidRunIntent::ChangesWork,
stop: Vec::new(),
also_asks: false,
}),
"m5",
),
(None, "m6"),
] {
let unread = reading.is_none();
set(reading);
runner
.submit(surface.clone(), owner_turn("how's it going?", key))
.await;
let notice = last(&surface);
assert!(
notice.starts_with(&crate::presentation::queued_message_notice(false)),
"{notice}"
);
assert_eq!(
notice.contains("Still working on \"Set up two demo sites\""),
unread,
"{notice}"
);
assert_eq!(
notice.contains("Latest step: Running a command"),
unread,
"{notice}"
);
let taken = registry
.take_steering_messages(session, UserRole::Owner, &ctx)
.await;
assert_eq!(taken.len(), 1);
}
set(Some(MidRunReading {
intent: MidRunIntent::AboutRunningWork,
stop: Vec::new(),
also_asks: false,
}));
let said_before = surface.0.lock().unwrap().len();
runner
.submit_placed(
surface.clone(),
owner_turn("How is it going so far?", "m7"),
Some(MidRunPlacement::Queue),
)
.await;
assert_eq!(surface.0.lock().unwrap().len(), said_before);
assert!(
registry
.take_steering_messages(session, UserRole::Owner, &ctx)
.await
.is_empty()
);
assert_eq!(registry.queue_len(session).await, 1);
registry.clear_queue(session).await;
runner
.submit_placed(
surface.clone(),
owner_turn("Use the staging server instead", "m8"),
Some(MidRunPlacement::Steer),
)
.await;
assert_eq!(surface.0.lock().unwrap().len(), said_before);
let taken = registry
.take_steering_messages(session, UserRole::Owner, &ctx)
.await;
assert_eq!(taken.len(), 1);
runner
.submit_placed(
surface.clone(),
owner_turn("Then list the files", "m9"),
Some(MidRunPlacement::Queue),
)
.await;
agent.release.notify_one();
for _ in 0..200 {
if agent
.turns
.lock()
.unwrap()
.iter()
.any(|t| t == "Then list the files")
{
break;
}
tokio::time::sleep(Duration::from_millis(5)).await;
}
assert!(
agent
.turns
.lock()
.unwrap()
.iter()
.any(|t| t == "Then list the files"),
"the placed message ran as a turn"
);
assert!(
!surface
.0
.lock()
.unwrap()
.iter()
.any(|said| said.starts_with("▶️ Now on")),
"{:?}",
surface.0.lock().unwrap()
);
agent.release.notify_one();
}
struct CardAgent {
updates: Vec<StatusUpdate>,
reply: &'static str,
disposition: aidaemon_events::AssistantResponseDisposition,
log: Arc<std::sync::Mutex<Vec<String>>>,
}
#[async_trait]
impl crate::ports::AgentIngress for CardAgent {
async fn handle_inbound_message(
&self,
request: InboundMessageRequest,
) -> anyhow::Result<AgentResponseEnvelope> {
if let Some(turn) = TurnOver::current() {
let log = self.log.clone();
tokio::spawn(async move {
turn.wait().await;
log.lock().unwrap().push("background work ended".into());
});
}
if let Some(status) = request.status_tx.as_ref() {
for update in &self.updates {
let _ = status.send(update.clone()).await;
}
}
Ok(AgentResponseEnvelope {
response_id: "r".into(),
task_id: "t".into(),
turn_id: None,
text: self.reply.into(),
referenced_receipts: Vec::new(),
disposition: self.disposition,
model: None,
})
}
}
#[async_trait]
impl ChannelAgentRuntime for CardAgent {
async fn terminalize_supervised_task(
&self,
_: &str,
_: aidaemon_events::TaskStatus,
_: String,
) -> anyhow::Result<Option<String>> {
Ok(None)
}
async fn cancel_active_finite_work_for_session(&self, _: &str) -> Vec<String> {
Vec::new()
}
async fn current_model(&self) -> String {
String::new()
}
async fn context_debug_settings(
&self,
_: &str,
_: &str,
) -> (bool, usize, usize, usize, Option<i64>) {
(false, 0, 0, 0, None)
}
async fn set_model(&self, _: String) {}
async fn list_models(&self) -> anyhow::Result<Vec<String>> {
Ok(Vec::new())
}
async fn clear_model_override(&self) {}
async fn clear_session_context(&self, _: &str) -> anyhow::Result<()> {
Ok(())
}
async fn clear_session(&self, _: &str) -> anyhow::Result<()> {
Ok(())
}
}
struct CardChat {
log: Arc<std::sync::Mutex<Vec<String>>>,
}
#[async_trait]
impl crate::live_status::SurfaceSink for CardChat {
async fn create(&self, text: &str) -> anyhow::Result<Option<String>> {
self.log.lock().unwrap().push(format!("card:{text}"));
Ok(Some("card-1".into()))
}
async fn edit(&self, _: &str, text: &str) -> anyhow::Result<bool> {
self.log.lock().unwrap().push(format!("card:{text}"));
Ok(true)
}
async fn delete(&self, _: &str) -> anyhow::Result<bool> {
self.log.lock().unwrap().push("card deleted".into());
Ok(true)
}
}
struct CardSurface(Arc<CardChat>);
#[async_trait]
impl TurnSurface for CardSurface {
fn platform(&self) -> &'static str {
"test"
}
async fn say(&self, text: &str) -> anyhow::Result<Vec<String>> {
self.0.log.lock().unwrap().push(format!("say:{text}"));
Ok(vec!["reply-1".into()])
}
fn show_working(&self, _: CancellationToken, _: Arc<AtomicU64>, _: u64) {}
fn card_sink(&self) -> Option<Arc<dyn crate::live_status::SurfaceSink>> {
Some(self.0.clone())
}
async fn card_kept(&self, id: &str) {
self.0.log.lock().unwrap().push(format!("card kept {id}"));
}
}
async fn run_card_turn(
updates: Vec<StatusUpdate>,
reply: &'static str,
disposition: aidaemon_events::AssistantResponseDisposition,
) -> Vec<String> {
let log = Arc::new(std::sync::Mutex::new(Vec::new()));
let agent = Arc::new(CardAgent {
updates,
reply,
disposition,
log: log.clone(),
});
let runner = TurnRunner::new(TurnDeps {
agent,
session_map: Arc::default(),
sessions: Arc::new(NoSessions),
task_registry: Arc::new(TaskRegistry::new(10)),
watchdog_stale_threshold_secs: 0,
watch: TurnWatch::default(),
});
let surface = Arc::new(CardSurface(Arc::new(CardChat { log: log.clone() })));
runner
.run(surface, owner_turn("Count both files", "m1"))
.await;
for _ in 0..200 {
if log
.lock()
.unwrap()
.iter()
.any(|e| e == "background work ended")
{
break;
}
tokio::time::sleep(Duration::from_millis(5)).await;
}
log.lock().unwrap().clone()
}
fn helper(label: &str, phase: aidaemon_core::card::RunPhase) -> StatusUpdate {
StatusUpdate::Helper(aidaemon_core::card::HelperView {
run: None,
phase,
..aidaemon_core::card::HelperView::running(label, false, None)
})
}
#[tokio::test]
async fn the_runner_ends_each_card_by_its_typed_state() {
use aidaemon_core::card::{ActivityKind, RunPhase};
let log = run_card_turn(
vec![
StatusUpdate::tool_start("spawn", "", ActivityKind::Delegate),
helper("Count lines", RunPhase::Running),
helper("Count words", RunPhase::Running),
helper("Count lines", RunPhase::Succeeded),
helper("Count words", RunPhase::Succeeded),
],
"Lines: 12. Words: 80.",
Default::default(),
)
.await;
let reply = log.iter().position(|e| e == "say:Lines: 12. Words: 80.");
let settled = log.iter().rposition(|e| {
e == "card:✅ A helper finished: Count lines\n\n✅ A helper finished: Count words"
});
let kept = log.iter().position(|e| e == "card kept card-1");
assert!(
settled.is_some() && reply.is_some() && kept > reply,
"{log:#?}"
);
assert!(!log.contains(&"card deleted".to_string()), "{log:#?}");
let log = run_card_turn(
vec![StatusUpdate::tool_start("read", "", ActivityKind::Read)],
"It says hello.",
Default::default(),
)
.await;
let reply = log.iter().position(|e| e == "say:It says hello.");
let deleted = log.iter().position(|e| e == "card deleted");
assert!(reply.is_some() && deleted > reply, "{log:#?}");
assert!(!log.iter().any(|e| e.starts_with("card kept")), "{log:#?}");
}
#[tokio::test]
async fn a_handoffs_ack_comes_before_the_work_ends() {
use aidaemon_core::card::HelperView;
use aidaemon_events::AssistantResponseDisposition::BackgroundHandoff;
let log = run_card_turn(
vec![StatusUpdate::Helper(HelperView::running(
"Slow count",
true,
None,
))],
"Started in the background: Slow count.",
BackgroundHandoff,
)
.await;
let ack = log
.iter()
.position(|e| e == "say:Started in the background: Slow count.");
let kept = log.iter().position(|e| e == "card kept card-1");
let ended = log.iter().position(|e| e == "background work ended");
assert!(ack.is_some() && kept > ack && ended > kept, "{log:#?}");
assert!(
!log.iter().any(|e| e.starts_with("card became")),
"{log:#?}"
);
let log = run_card_turn(
vec![StatusUpdate::step_handed_off(
"running the installer",
aidaemon_core::card::ActivityKind::Run,
)],
"Started the install in the background.",
BackgroundHandoff,
)
.await;
let ack = log
.iter()
.position(|e| e == "say:Started the install in the background.");
let deleted = log.iter().position(|e| e == "card deleted");
let ended = log.iter().position(|e| e == "background work ended");
assert!(
ack.is_some() && deleted > ack && ended > deleted,
"{log:#?}"
);
assert!(
!log.contains(&"card:Started the install in the background.".to_string()),
"{log:#?}"
);
}
#[test]
fn cancel_words_are_whole_messages() {
assert!(is_cancel_word("Stop"));
assert!(is_cancel_word(" cancel "));
assert!(!is_cancel_word("stop the server"));
assert!(!is_cancel_word("don't stop"));
}
#[tokio::test]
async fn a_bare_stop_stops_every_job_of_one_request_and_names_them() {
let agent = Arc::new(ScriptedAgent {
release: tokio::sync::Notify::new(),
reading: std::sync::Mutex::new(None),
work: std::sync::Mutex::new(two_counting_jobs()),
recorded: Default::default(),
turns: Default::default(),
});
let registry = Arc::new(TaskRegistry::new(10));
let runner = TurnRunner::new(TurnDeps {
agent: agent.clone(),
session_map: Arc::default(),
sessions: Arc::new(NoSessions),
task_registry: registry.clone(),
watchdog_stale_threshold_secs: 0,
watch: TurnWatch::default(),
});
let surface = Arc::new(Said::default());
runner
.submit(surface.clone(), owner_turn("stop", "s1"))
.await;
let reply = surface.0.lock().unwrap().last().cloned().unwrap();
assert_eq!(
reply,
"⏹️ Stopped:\n• Sub-agent: Counting agent A\n• Background command: count to 300"
);
assert!(agent.work.lock().unwrap().is_empty());
runner
.submit(surface.clone(), owner_turn("stop", "s2"))
.await;
assert_eq!(
surface.0.lock().unwrap().last().cloned().unwrap(),
"Nothing is running in this chat right now."
);
*agent.work.lock().unwrap() = two_counting_jobs();
*agent.reading.lock().unwrap() = Some(MidRunReading {
intent: MidRunIntent::StopsWork,
stop: Vec::new(),
also_asks: false,
});
runner
.submit(
surface.clone(),
owner_turn("Stop both counting agents now.", "s3"),
)
.await;
assert!(!registry.has_running_task("test:mid-run").await);
let reply = surface.0.lock().unwrap().last().cloned().unwrap();
assert!(reply.contains("• Sub-agent: Counting agent A"), "{reply}");
assert!(
reply.contains("• Background command: count to 300"),
"{reply}"
);
assert!(agent.work.lock().unwrap().is_empty());
}
#[tokio::test]
async fn a_stop_is_kept_in_history_and_what_else_it_asks_runs_as_a_turn() {
let agent = Arc::new(ScriptedAgent {
release: tokio::sync::Notify::new(),
reading: std::sync::Mutex::new(Some(MidRunReading {
intent: MidRunIntent::StopsWork,
stop: Vec::new(),
also_asks: false,
})),
work: std::sync::Mutex::new(two_counting_jobs()),
recorded: Default::default(),
turns: Default::default(),
});
let runner = TurnRunner::new(TurnDeps {
agent: agent.clone(),
session_map: Arc::default(),
sessions: Arc::new(NoSessions),
task_registry: Arc::new(TaskRegistry::new(10)),
watchdog_stale_threshold_secs: 0,
watch: TurnWatch::default(),
});
let surface = Arc::new(Said::default());
runner
.submit(surface.clone(), owner_turn("Stop the counting jobs.", "k1"))
.await;
let recorded = agent.recorded.lock().unwrap().clone();
assert_eq!(recorded.len(), 1, "{recorded:?}");
assert_eq!(recorded[0].0, "Stop the counting jobs.");
assert!(recorded[0].1.starts_with("⏹️ Stopped:"), "{recorded:?}");
assert!(agent.turns.lock().unwrap().is_empty());
*agent.work.lock().unwrap() = two_counting_jobs();
*agent.reading.lock().unwrap() = Some(MidRunReading {
intent: MidRunIntent::StopsWork,
stop: Vec::new(),
also_asks: true,
});
agent.release.notify_one();
runner
.submit(
surface.clone(),
owner_turn("Stop it and delete what it made.", "k2"),
)
.await;
assert!(agent.work.lock().unwrap().is_empty());
assert_eq!(agent.recorded.lock().unwrap().len(), 1);
for _ in 0..200 {
if !agent.turns.lock().unwrap().is_empty() {
break;
}
tokio::time::sleep(Duration::from_millis(5)).await;
}
assert_eq!(
agent.turns.lock().unwrap().as_slice(),
["Stop it and delete what it made."]
);
}
#[tokio::test]
async fn a_status_question_between_runs_gets_the_typed_status() {
let agent = Arc::new(ScriptedAgent {
release: tokio::sync::Notify::new(),
reading: std::sync::Mutex::new(Some(MidRunReading {
intent: MidRunIntent::AboutRunningWork,
stop: Vec::new(),
also_asks: false,
})),
work: std::sync::Mutex::new(two_counting_jobs()),
recorded: Default::default(),
turns: Default::default(),
});
let registry = Arc::new(TaskRegistry::new(10));
let runner = TurnRunner::new(TurnDeps {
agent: agent.clone(),
session_map: Arc::default(),
sessions: Arc::new(NoSessions),
task_registry: registry.clone(),
watchdog_stale_threshold_secs: 0,
watch: TurnWatch::default(),
});
let session = "test:mid-run";
let surface = Arc::new(Said::default());
runner
.submit(surface.clone(), owner_turn("how's it going?", "b1"))
.await;
assert!(!registry.has_running_task(session).await);
let reply = surface.0.lock().unwrap().last().cloned().unwrap();
assert!(reply.starts_with("Working in the background:"), "{reply}");
assert!(
reply.contains("\n• Counting agent A: Running a command (1m so far)"),
"{reply}"
);
assert!(
reply.contains("\n• Background command: count to 300 (50s so far)"),
"{reply}"
);
assert!(!reply.contains("how's it going"), "{reply}");
*agent.reading.lock().unwrap() = Some(MidRunReading {
intent: MidRunIntent::Unrelated,
stop: Vec::new(),
also_asks: false,
});
runner
.submit(
surface.clone(),
owner_turn("What is the capital of Peru?", "b2"),
)
.await;
for _ in 0..200 {
if registry.has_running_task(session).await {
break;
}
tokio::time::sleep(Duration::from_millis(5)).await;
}
assert!(registry.has_running_task(session).await);
agent.release.notify_one();
}
#[tokio::test]
async fn a_bare_stop_over_two_requests_asks_which() {
let mut work = two_counting_jobs();
work[1].request = Some("req-2".into());
let agent = Arc::new(ScriptedAgent {
release: tokio::sync::Notify::new(),
reading: std::sync::Mutex::new(None),
work: std::sync::Mutex::new(work),
recorded: Default::default(),
turns: Default::default(),
});
let registry = TaskRegistry::new(10);
let reply =
crate::stop::stop(®istry, agent.as_ref(), "test:mid-run", StopRequest::Bare).await;
assert!(
reply.starts_with("Work from more than one request is running:"),
"{reply}"
);
assert!(reply.contains("/cancel all"), "{reply}");
assert_eq!(agent.work.lock().unwrap().len(), 2);
let list = crate::stop::running_work(®istry, agent.as_ref(), "test:mid-run").await;
let job = list.entries[1].number;
let reply = crate::stop::stop(
®istry,
agent.as_ref(),
"test:mid-run",
StopRequest::Numbers(vec![job]),
)
.await;
assert_eq!(reply, "⏹️ Stopped:\n• Background command: count to 300");
assert_eq!(agent.work.lock().unwrap().len(), 1);
}
#[tokio::test]
async fn clearing_stops_every_sub_agent_and_command() {
let agent = Arc::new(ScriptedAgent {
release: tokio::sync::Notify::new(),
reading: std::sync::Mutex::new(None),
work: std::sync::Mutex::new(two_counting_jobs()),
recorded: Default::default(),
turns: Default::default(),
});
let registry = TaskRegistry::new(10);
let stopped =
crate::stop::stop_background_work(®istry, agent.as_ref(), "test:mid-run").await;
assert_eq!(stopped.len(), 2);
let named = crate::stop::stopped_list(&stopped);
assert!(named.starts_with("⏹️ Stopped:\n• "), "{named}");
for title in &stopped {
assert!(named.contains(title.as_str()), "{named}");
}
assert!(agent.work.lock().unwrap().is_empty());
}
#[tokio::test]
async fn tasks_lists_a_helpers_latest_step() {
let mut work = two_counting_jobs();
work[0].step = Some(aidaemon_core::card::Step::Output { lines: 14 });
let agent = ScriptedAgent {
release: tokio::sync::Notify::new(),
reading: std::sync::Mutex::new(None),
work: std::sync::Mutex::new(work),
recorded: Default::default(),
turns: Default::default(),
};
let registry = TaskRegistry::new(10);
let running = crate::stop::running_work(®istry, &agent, "s1").await;
let tasks = crate::slash::render_tasks(&running, &[], chrono::Utc::now(), None);
assert!(
tasks.contains(
"Sub-agent: Counting agent A – Running a command · 14 lines of output so far ("
),
"{tasks}"
);
assert!(
tasks.contains("Background command: count to 300 ("),
"{tasks}"
);
}
fn two_counting_jobs() -> Vec<crate::ports::ChatWork> {
let now = chrono::Utc::now();
vec![
crate::ports::ChatWork {
key: "agent:1".into(),
kind: crate::ports::ChatWorkKind::SubAgent,
title: "Sub-agent: Counting agent A".into(),
started_at: now - chrono::Duration::seconds(60),
request: Some("req-1".into()),
step: None,
run: Some("helper:a".into()),
},
crate::ports::ChatWork {
key: "job:0:4242".into(),
kind: crate::ports::ChatWorkKind::BackgroundJob,
title: "Background command: count to 300".into(),
started_at: now - chrono::Duration::seconds(50),
request: Some("req-1".into()),
step: None,
run: None,
},
]
}
}
#[cfg(test)]
mod command_output_card_tests {
use super::status_text;
use aidaemon_tools::status::StatusUpdate;
#[test]
fn a_card_never_shows_a_commands_output() {
let update = StatusUpdate::CommandOutput {
name: "terminal".into(),
lines: 3,
tail: Some("SYNTHETIC-OUTPUT-LINE".into()),
};
let shown = status_text(&update).unwrap_or_default();
assert!(!shown.contains("SYNTHETIC-OUTPUT-LINE"), "{shown}");
}
}