Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

show agents as running while their subagents work (#3251)

kt6d4d77c56434
diff --git a/crates/pa-daemon/src/agent_engine/session_engine_impl.rs b/crates/pa-daemon/src/agent_engine/session_engine_impl.rs
index 52e3e8609d..cdc3ccfe51 100644
--- a/crates/pa-daemon/src/agent_engine/session_engine_impl.rs
+++ b/crates/pa-daemon/src/agent_engine/session_engine_impl.rs
@@ -625,6 +625,12 @@ impl SessionEngine for AgentSessionEngine {
AgentSessionEngine::is_quota_parked(self)
}
+ fn has_running_subagents(&self) -> bool {
+ self.children
+ .as_ref()
+ .is_some_and(|children| children.has_running_children())
+ }
+
/// `compact` over the hosted pa-core session: the session summarizes
/// its own branch, persists the entry on its in-memory store, and
/// rebuilds the loop context; the worker persists the durable entry.
diff --git a/crates/pa-daemon/src/agent_messaging/observe.rs b/crates/pa-daemon/src/agent_messaging/observe.rs
index 9020a1c165..2a2dcf93de 100644
--- a/crates/pa-daemon/src/agent_messaging/observe.rs
+++ b/crates/pa-daemon/src/agent_messaging/observe.rs
@@ -231,7 +231,8 @@ pub(super) fn summaries_from_roster(
// A resident session's family status is the busy verdict
// (`activity === "working" || isSessionActive`) split into
// `running`/`idle`; `inactive` names only rows with no
- // resident session.
+ // resident session. A session whose subagents still run
+ // reports `activity: "working"`, so it counts as running.
let status = if !has_live_session {
AgentFamilyStatus::Inactive
} else if session.get("activity").and_then(Value::as_str) == Some("working")
diff --git a/crates/pa-daemon/src/engine.rs b/crates/pa-daemon/src/engine.rs
index 0fb3da4d58..4ebbb6f5dd 100644
--- a/crates/pa-daemon/src/engine.rs
+++ b/crates/pa-daemon/src/engine.rs
@@ -453,6 +453,13 @@ pub trait SessionEngine: Send + Sync {
false
}
+ /// True while any RLM child this session spawned is still running
+ /// (each child counts its own descendants the same way). Scripted
+ /// harness engines spawn no children.
+ fn has_running_subagents(&self) -> bool {
+ false
+ }
+
/// Apply a live model switch (the daemon `set_model` command, TS
/// `session.setModel`): the selection merges over the current one and
/// a built session's agent and provider stream follow the new model on
diff --git a/crates/pa-daemon/src/rlm_children.rs b/crates/pa-daemon/src/rlm_children.rs
index 12f50361ed..e97641474e 100644
--- a/crates/pa-daemon/src/rlm_children.rs
+++ b/crates/pa-daemon/src/rlm_children.rs
@@ -244,6 +244,16 @@ impl ChildRecord {
}
}
+/// Whether any record's settle funnel has not fired yet.
+async fn any_unsettled(children: &[Arc<Mutex<ChildRecord>>]) -> bool {
+ for record in children {
+ if !record.lock().await.settled {
+ return true;
+ }
+ }
+ false
+}
+
/// A deleted child's retained identity (TS `_deletedRlmChildRuns`
/// tombstone, #2388): the delete receipt promised a collectable cancelled
/// envelope, and only the fields that envelope reads survive the registry
@@ -341,6 +351,11 @@ struct SupervisorChildSessionsInner {
/// The parent engine's child-settle hook (goal continuation resume);
/// `None` until the engine wires it.
settle_hook: std::sync::Mutex<Option<Arc<dyn Fn() + Send + Sync>>>,
+ /// Whether any tracked child run is unsettled (the `any_running`
+ /// verdict, re-read at every registry change): a sync read for the
+ /// worker's session summary, and a change feed the worker turns into
+ /// roster pushes.
+ running: tokio::sync::watch::Sender<bool>,
/// The quiescence barrier's wake (TS `waitForRlmQuiescence`,
/// agent-session.ts): `notify_waiters` fires once per settled child
/// run - every settle site funnels through the settle hook below -
@@ -390,6 +405,7 @@ impl SupervisorChildSessions {
deleted_children: std::sync::Mutex::new(std::collections::HashMap::new()),
turn_done: tokio::sync::watch::Sender::new(0),
settle_hook: std::sync::Mutex::new(None),
+ running: tokio::sync::watch::Sender::new(false),
settle_notify: tokio::sync::Notify::new(),
model_refusal_telemetry,
usage_sink: std::sync::Mutex::new(None),
@@ -471,13 +487,21 @@ impl SupervisorChildSessions {
/// settle funnel has not fired - the terminal status flips before
/// the terminal notice is delivered, `run.settled` after).
pub async fn any_running(&self) -> bool {
- let children = self.inner.children.lock().await;
- for record in children.iter() {
- if !record.lock().await.settled {
- return true;
- }
- }
- false
+ self.inner.any_running().await
+ }
+
+ /// The last [`Self::any_running`] verdict, without awaiting the
+ /// registry: the session summary counts this session as working
+ /// while any of its children still runs.
+ #[must_use]
+ pub fn has_running_children(&self) -> bool {
+ *self.inner.running.borrow()
+ }
+
+ /// A feed that changes whenever [`Self::has_running_children`] flips.
+ #[must_use]
+ pub fn subscribe_running(&self) -> tokio::sync::watch::Receiver<bool> {
+ self.inner.running.subscribe()
}
/// Close every tracked child session with the parent session (TS
@@ -804,6 +828,7 @@ impl SupervisorChildSessionsInner {
/// after the terminal notice is delivered.
pub(crate) async fn fire_settle_hook(&self, record: &Arc<Mutex<ChildRecord>>) {
record.lock().await.settled = true;
+ self.refresh_running().await;
self.settle_notify.notify_waiters();
let hook = self
.settle_hook
@@ -814,6 +839,28 @@ impl SupervisorChildSessionsInner {
std::thread::spawn(move || hook());
}
}
+
+ /// Whether any tracked child run's settle funnel has not fired yet.
+ pub(crate) async fn any_running(&self) -> bool {
+ let children = self.children.lock().await;
+ any_unsettled(&children).await
+ }
+
+ /// Re-read [`Self::any_running`] into the `running` feed after a
+ /// registry change (a registration, a settle, a close walk). The read
+ /// and the publish share one hold of the children lock, so racing
+ /// refreshes publish in order and the last one always reflects the
+ /// registry after every change that preceded it.
+ pub(crate) async fn refresh_running(&self) {
+ let children = self.children.lock().await;
+ let running = any_unsettled(&children).await;
+ self.running.send_if_modified(|current| {
+ let changed = *current != running;
+ *current = running;
+ changed
+ });
+ }
+
/// Wait for the parent turn that spawned a task to complete (generation
/// strictly greater than the one captured at spawn admission). Bounded:
/// a turn that never settles releases the child anyway.
diff --git a/crates/pa-daemon/src/rlm_children/host.rs b/crates/pa-daemon/src/rlm_children/host.rs
index 73dc4b4056..0e27fe62fb 100644
--- a/crates/pa-daemon/src/rlm_children/host.rs
+++ b/crates/pa-daemon/src/rlm_children/host.rs
@@ -152,6 +152,7 @@ impl RlmSubagentHost for SupervisorChildSessions {
};
let record = Arc::new(Mutex::new(record));
this.children.lock().await.push(Arc::clone(&record));
+ this.refresh_running().await;
anyhow::Ok((record, created, model))
}
.await;
diff --git a/crates/pa-daemon/src/rlm_children/lifecycle.rs b/crates/pa-daemon/src/rlm_children/lifecycle.rs
index bfa5a7992c..9d0eac12c8 100644
--- a/crates/pa-daemon/src/rlm_children/lifecycle.rs
+++ b/crates/pa-daemon/src/rlm_children/lifecycle.rs
@@ -295,8 +295,10 @@ impl SupervisorChildSessionsInner {
Ok(())
}
- /// Whether the child worker still has work in flight (streaming or
- /// queued). `Err` means the child cannot be reached right now.
+ /// Whether the child worker still has work in flight (streaming,
+ /// queued, or its own children still running - so a child stays
+ /// running while any descendant does). `Err` means the child cannot be
+ /// reached right now.
pub(super) async fn child_busy(&self, active_session_id: &str) -> Result<bool> {
let command = DaemonCommand::GetState {
id: None,
@@ -304,10 +306,9 @@ impl SupervisorChildSessionsInner {
rest: Map::default(),
};
let state = self.command(&command, STATE_TIMEOUT_MS).await?;
- Ok(state
- .get("isStreaming")
- .and_then(Value::as_bool)
- .unwrap_or(false)
+ let flag = |name: &str| state.get(name).and_then(Value::as_bool).unwrap_or(false);
+ Ok(flag("isStreaming")
+ || flag("hasRunningSubagents")
|| state
.get("sessionActions")
.and_then(|actions| actions.get("queuedCount"))
@@ -331,7 +332,8 @@ impl SupervisorChildSessionsInner {
.map(compact_rlm_text))
}
- /// Best-effort bounded wait for one child to go idle. The wait is a
+ /// Best-effort bounded wait for one child and its descendants to go
+ /// idle. The wait is a
/// snapshot helper, not a gate: its timeout is not an error, and the
/// caller re-reads the child's state afterwards (TS collect: "a
/// timeout returns current snapshots, never an error").
@@ -339,9 +341,12 @@ impl SupervisorChildSessionsInner {
if budget.is_zero() {
return;
}
+ // The child's own descendants keep it busy (`child_busy`), so the
+ // wait holds until they settle too.
let command = DaemonCommand::WaitForIdle {
id: None,
active_session_id: active_session_id.to_string(),
+ wait_for_rlm_quiescence: Some(true),
rest: Map::default(),
};
let _ = self
diff --git a/crates/pa-daemon/src/rlm_children/registry.rs b/crates/pa-daemon/src/rlm_children/registry.rs
index f3826ae763..6ef4809983 100644
--- a/crates/pa-daemon/src/rlm_children/registry.rs
+++ b/crates/pa-daemon/src/rlm_children/registry.rs
@@ -229,6 +229,7 @@ impl SupervisorChildSessionsInner {
}
// The walk changed the registry: wake a parked barrier (a closed
// child is settled work, settled here by its removal).
+ self.refresh_running().await;
self.settle_notify.notify_waiters();
match close_error {
Some(error) => Err(error),
diff --git a/crates/pa-daemon/src/rlm_children/watch_tests.rs b/crates/pa-daemon/src/rlm_children/watch_tests.rs
index ec71822a70..cc637d375f 100644
--- a/crates/pa-daemon/src/rlm_children/watch_tests.rs
+++ b/crates/pa-daemon/src/rlm_children/watch_tests.rs
@@ -30,6 +30,7 @@ async fn spawn_fake_supervisor(
kill_tx: mpsc::UnboundedSender<Value>,
kill_behavior: FakeKill,
worker_leaves_after_settle: bool,
+ child_subagents: Arc<FakeChildSubagents>,
) {
let kill_behavior = std::sync::Arc::new(kill_behavior);
let listener = bind_transport(&socket).await.unwrap();
@@ -45,6 +46,7 @@ async fn spawn_fake_supervisor(
let kill_tx = kill_tx.clone();
let kill_behavior = std::sync::Arc::clone(&kill_behavior);
let gone = Arc::clone(&gone);
+ let child_subagents = Arc::clone(&child_subagents);
tokio::spawn(async move {
let (reader, mut writer) = stream.split();
let mut reader = BufReader::new(reader);
@@ -86,6 +88,16 @@ async fn spawn_fake_supervisor(
"wait_for_idle" => {
tokio::time::sleep(std::time::Duration::from_millis(idle_delay_ms))
.await;
+ // The quiescence arm also waits out the
+ // child's own running subagents.
+ if command["waitForRlmQuiescence"] == true {
+ child_subagents
+ .quiescent_waits
+ .fetch_add(1, Ordering::SeqCst);
+ while child_subagents.running.load(Ordering::SeqCst) {
+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;
+ }
+ }
response_success(Some(&id), command_type, None)
}
"get_state" => response_success(
@@ -93,6 +105,7 @@ async fn spawn_fake_supervisor(
command_type,
Some(json!({
"isStreaming": false,
+ "hasRunningSubagents": child_subagents.running.load(Ordering::SeqCst),
"sessionActions": { "queuedCount": 0 },
})),
),
@@ -154,6 +167,34 @@ async fn sessions_with_fake_supervisor(
idle_delay_ms: u64,
kill_behavior: FakeKill,
worker_leaves_after_settle: bool,
+) -> (SupervisorChildSessions, mpsc::UnboundedReceiver<Value>) {
+ sessions_with_fake_child_subagents(
+ follow_up_tx,
+ idle_delay_ms,
+ kill_behavior,
+ worker_leaves_after_settle,
+ Arc::new(FakeChildSubagents::default()),
+ )
+ .await
+}
+
+/// The fake child's own subagents: whether one still runs (the child
+/// reports `hasRunningSubagents`, and a `waitForRlmQuiescence` idle wait
+/// holds until it finishes), and how many such waits started.
+#[derive(Default)]
+struct FakeChildSubagents {
+ running: AtomicBool,
+ quiescent_waits: std::sync::atomic::AtomicUsize,
+}
+
+/// [`sessions_with_fake_supervisor`] whose child reports its own running
+/// subagents from `child_subagents` (a grandchild still running).
+async fn sessions_with_fake_child_subagents(
+ follow_up_tx: mpsc::UnboundedSender<Value>,
+ idle_delay_ms: u64,
+ kill_behavior: FakeKill,
+ worker_leaves_after_settle: bool,
+ child_subagents: Arc<FakeChildSubagents>,
) -> (SupervisorChildSessions, mpsc::UnboundedReceiver<Value>) {
let socket = std::env::temp_dir().join(format!(
"pa-rlm-watch-{}.sock",
@@ -167,6 +208,7 @@ async fn sessions_with_fake_supervisor(
kill_tx,
kill_behavior,
worker_leaves_after_settle,
+ child_subagents,
)
.await;
let link = Arc::new(crate::supervisor_link::SupervisorLink::new(socket));
@@ -285,6 +327,97 @@ async fn a_worker_leaving_inside_the_settle_grace_keeps_the_verdict() {
.is_some_and(|content| content.contains("the child final answer")));
}
+/// A parent counts as running while any descendant runs: the child's own
+/// turn is done, but while it reports a running grandchild the parent's
+/// row stays `running` and the registry keeps the parent's summary busy;
+/// once the grandchild finishes, the child settles and the parent is
+/// quiet again.
+#[tokio::test]
+async fn a_child_with_a_running_grandchild_keeps_the_parent_running() {
+ let (follow_up_tx, _follow_up_rx) = mpsc::unbounded_channel();
+ let grandchild = Arc::new(FakeChildSubagents {
+ running: AtomicBool::new(true),
+ ..FakeChildSubagents::default()
+ });
+ let (sessions, _kill_rx) = sessions_with_fake_child_subagents(
+ follow_up_tx,
+ 0,
+ FakeKill::Success,
+ false,
+ Arc::clone(&grandchild),
+ )
+ .await;
+ assert!(!sessions.has_running_children());
+ let mut running = sessions.subscribe_running();
+ let settled = sessions.settle_notified();
+ spawn_child(&sessions).await;
+ assert!(running.has_changed().unwrap());
+ assert!(*running.borrow_and_update());
+ sessions.notify_turn_done();
+
+ // The child is idle on its own, but its grandchild still runs: the
+ // watcher's idle wait holds for the child's whole subtree.
+ wait_for_quiescent_wait(&grandchild).await;
+ let roster = sessions.list_subagents().await.expect("child roster");
+ assert_eq!(roster[0].status, "running");
+ assert!(sessions.has_running_children());
+
+ grandchild.running.store(false, Ordering::SeqCst);
+ tokio::time::timeout(Duration::from_secs(10), settled)
+ .await
+ .expect("the child settles once its grandchild finished");
+ let roster = sessions.list_subagents().await.expect("child roster");
+ assert_eq!(roster[0].status, "completed");
+ assert!(!sessions.has_running_children());
+ assert!(running.has_changed().unwrap());
+}
+
+/// A `collect` with a timeout waits out a child whose own turn ended but
+/// whose grandchild still runs, instead of answering `running` at once.
+#[tokio::test]
+async fn collect_with_a_timeout_waits_for_a_running_grandchild() {
+ let (follow_up_tx, _follow_up_rx) = mpsc::unbounded_channel();
+ let grandchild = Arc::new(FakeChildSubagents {
+ running: AtomicBool::new(true),
+ ..FakeChildSubagents::default()
+ });
+ let (sessions, _kill_rx) = sessions_with_fake_child_subagents(
+ follow_up_tx,
+ 0,
+ FakeKill::Success,
+ false,
+ Arc::clone(&grandchild),
+ )
+ .await;
+ let handle = spawn_child(&sessions).await;
+ sessions.notify_turn_done();
+ wait_for_quiescent_wait(&grandchild).await;
+
+ let finish = Arc::clone(&grandchild);
+ tokio::spawn(async move {
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ finish.running.store(false, Ordering::SeqCst);
+ });
+ let results = sessions
+ .collect(vec![handle.rlm_child_id.clone()], 10_000)
+ .await
+ .expect("collect the child");
+ assert_eq!(results[0].status, "done");
+ assert!(!grandchild.running.load(Ordering::SeqCst));
+}
+
+/// Wait until the settle watcher parks in the child's subtree idle wait.
+async fn wait_for_quiescent_wait(child_subagents: &FakeChildSubagents) {
+ let deadline = Instant::now() + Duration::from_secs(10);
+ while child_subagents.quiescent_waits.load(Ordering::SeqCst) == 0 {
+ assert!(
+ Instant::now() < deadline,
+ "the watcher never waited for the child's subtree"
+ );
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+}
+
/// One child row exists and is running before the close tests run.
async fn one_running_child(sessions: &SupervisorChildSessions) {
let deadline = Instant::now() + Duration::from_secs(5);
diff --git a/crates/pa-daemon/src/roster_activity.rs b/crates/pa-daemon/src/roster_activity.rs
index 61c5a413f3..18be8ada49 100644
--- a/crates/pa-daemon/src/roster_activity.rs
+++ b/crates/pa-daemon/src/roster_activity.rs
@@ -160,6 +160,25 @@ impl RosterPushQueue {
}
}
+/// The children watcher: a session whose RLM children start or finish
+/// changes its own summary (it stays working while any child runs), so
+/// every flip of the registry's running verdict enqueues a flush request.
+/// The watcher ends when the children registry goes away.
+pub(crate) fn spawn_running_children_watch(
+ children: &crate::rlm_children::SupervisorChildSessions,
+ queue: RosterPushQueue,
+) {
+ if queue.inner.is_none() {
+ return;
+ }
+ let mut running = children.subscribe_running();
+ tokio::spawn(async move {
+ while running.changed().await.is_ok() {
+ queue.push();
+ }
+ });
+}
+
/// The pump watcher (TS `observeRosterEvent`): every trigger frame that
/// flows through the worker's event pump enqueues a flush request. The
/// watcher owns a receiver on the pump's broadcast, so it ends with the
diff --git a/crates/pa-daemon/src/types.rs b/crates/pa-daemon/src/types.rs
index 6dd7b7bde1..13fb62c063 100644
--- a/crates/pa-daemon/src/types.rs
+++ b/crates/pa-daemon/src/types.rs
@@ -85,6 +85,11 @@ pub struct SessionSummary {
/// activity label's `running tools` state.
#[serde(default)]
pub is_running_tools: bool,
+ /// An RLM child of this session (or one of its descendants) is still
+ /// running; the session counts as working even after its own turn
+ /// ended.
+ #[serde(default)]
+ pub has_running_subagents: bool,
pub attached_clients: u32,
pub message_count: u32,
pub session_actions: SessionActionSnapshot,
diff --git a/crates/pa-daemon/src/worker.rs b/crates/pa-daemon/src/worker.rs
index 915f12d387..6b6f1cf2aa 100644
--- a/crates/pa-daemon/src/worker.rs
+++ b/crates/pa-daemon/src/worker.rs
@@ -718,6 +718,15 @@ impl Worker {
roster_push_order: std::sync::Arc::clone(&roster_push_order),
});
crate::roster_activity::spawn_roster_activity_watch(&events, roster_pushes.clone());
+ if let Some(children) = agent_engine
+ .as_ref()
+ .and_then(|engine| engine.children.as_ref())
+ {
+ crate::roster_activity::spawn_running_children_watch(
+ children,
+ roster_pushes.clone(),
+ );
+ }
let runner = TurnRunner {
recovery: Arc::clone(&recovery),
core: Arc::clone(&core),
diff --git a/crates/pa-daemon/src/worker/commands.rs b/crates/pa-daemon/src/worker/commands.rs
index 34dd434c73..38462f1efc 100644
--- a/crates/pa-daemon/src/worker/commands.rs
+++ b/crates/pa-daemon/src/worker/commands.rs
@@ -89,7 +89,7 @@ impl Worker {
response_success(None, "abort_compaction", None)
}
"set_auto_compaction" => self.handle_set_auto_compaction(payload),
- "wait_for_idle" => self.handle_wait_for_idle().await,
+ "wait_for_idle" => self.handle_wait_for_idle(payload).await,
"wait_for_headless_completion" => {
self.handle_wait_for_headless_completion(payload).await
}
diff --git a/crates/pa-daemon/src/worker/lifecycle.rs b/crates/pa-daemon/src/worker/lifecycle.rs
index c7da945490..20645fa489 100644
--- a/crates/pa-daemon/src/worker/lifecycle.rs
+++ b/crates/pa-daemon/src/worker/lifecycle.rs
@@ -654,29 +654,16 @@ impl Worker {
}
}
- pub(crate) async fn handle_wait_for_idle(&self) -> DaemonResponse {
- self.wait_until_idle().await;
- response_success(None, "wait_for_idle", None)
- }
-
- /// `wait_for_headless_completion` (TS daemon command): settle the
- /// headless run first (same idle wait as `wait_for_idle`), then answer
- /// the autonomous-run accounting snapshot (`DaemonAutonomousStatus`).
- /// `waitForRlmQuiescence` (TS `waitForHeadlessCompletion`'s strong arm
- /// over `agent-session.ts` `waitForRlmQuiescence`): the barrier also
- /// owns descendant work - it holds past the parent's idle until every
- /// tracked child run's settle funnel fires (after the terminal notice
- /// is delivered), and the settle loop re-runs the idle wait, so a
- /// settled child's terminal notice (a queued parent turn) drains
- /// inside the barrier exactly like TS's "work may start at the
- /// child-settlement boundary" re-check.
- pub(crate) async fn handle_wait_for_headless_completion(
- &self,
- payload: &Value,
- ) -> DaemonResponse {
- if let Err(response) = self.require_created("wait_for_headless_completion") {
- return response;
- }
+ /// The idle wait, plus `waitForRlmQuiescence` (TS
+ /// `waitForHeadlessCompletion`'s strong arm over `agent-session.ts`
+ /// `waitForRlmQuiescence`): the barrier also owns descendant work - it
+ /// holds past the session's idle until every tracked child run's
+ /// settle funnel fires (after the terminal notice is delivered), and
+ /// the settle loop re-runs the idle wait, so a settled child's
+ /// terminal notice (a queued turn) drains inside the barrier exactly
+ /// like TS's "work may start at the child-settlement boundary"
+ /// re-check.
+ async fn wait_until_quiescent(&self, payload: &Value) {
let children = if payload.get("waitForRlmQuiescence").and_then(Value::as_bool) == Some(true)
{
self.agent_engine
@@ -688,7 +675,7 @@ impl Worker {
loop {
self.wait_until_idle().await;
let Some(children) = children.as_ref() else {
- break;
+ return;
};
// Register the permit before the unsettled-work read: a run
// that settles between the read and the await still wakes
@@ -705,12 +692,34 @@ impl Worker {
// runs before answering, so the barrier holds for the
// new work too instead of completing at the boundary.
if !children.any_running().await {
- break;
+ return;
}
continue;
}
settled.await;
}
+ }
+
+ /// `wait_for_idle`: park until the session is idle;
+ /// `waitForRlmQuiescence` also holds until its RLM children settled
+ /// (the parent-side settle watcher and `collect` wait out a child's
+ /// whole subtree this way).
+ pub(crate) async fn handle_wait_for_idle(&self, payload: &Value) -> DaemonResponse {
+ self.wait_until_quiescent(payload).await;
+ response_success(None, "wait_for_idle", None)
+ }
+
+ /// `wait_for_headless_completion` (TS daemon command): settle the
+ /// headless run first (same idle wait as `wait_for_idle`), then answer
+ /// the autonomous-run accounting snapshot (`DaemonAutonomousStatus`).
+ pub(crate) async fn handle_wait_for_headless_completion(
+ &self,
+ payload: &Value,
+ ) -> DaemonResponse {
+ if let Err(response) = self.require_created("wait_for_headless_completion") {
+ return response;
+ }
+ self.wait_until_quiescent(payload).await;
// The idle wait finished, so no turn holds the accounting state;
// the snapshot read cannot interleave with a running turn.
let status = self
diff --git a/crates/pa-daemon/src/worker/summary.rs b/crates/pa-daemon/src/worker/summary.rs
index 7fff3f280c..5731b332a0 100644
--- a/crates/pa-daemon/src/worker/summary.rs
+++ b/crates/pa-daemon/src/worker/summary.rs
@@ -27,6 +27,7 @@ impl Worker {
self.engine.model_fallback_message(),
self.user_bash.is_running(),
self.engine.is_quota_parked(),
+ self.engine.has_running_subagents(),
);
// The worker's roster-delta counter at snapshot time, and the
// process instance that read it — the pair is one snapshot:
@@ -319,6 +320,7 @@ pub(crate) fn push_roster_delta(context: &RosterPushContext) {
context.engine.model_fallback_message(),
context.user_bash.is_running(),
context.engine.is_quota_parked(),
+ context.engine.has_running_subagents(),
)
};
// The embedded counter is the pre-stamp value read under the order
@@ -360,6 +362,7 @@ pub(crate) fn session_summary(
model_fallback_message: Option<String>,
bash_running: bool,
quota_parked: bool,
+ subagents_running: bool,
) -> SessionSummary {
let store = core.store.as_ref();
let streaming = core.busy;
@@ -404,7 +407,9 @@ pub(crate) fn session_summary(
id: core.active_session_id.clone(),
lifecycle: active_lifecycle(&core.runtime_kind, scalars.message_count == 0, streaming)
.to_string(),
- activity: if streaming || compacting {
+ // Running children keep the session working after its own turn
+ // ended: every status surface classifies this activity.
+ activity: if streaming || compacting || subagents_running {
"working"
} else {
"idle"
@@ -427,6 +432,7 @@ pub(crate) fn session_summary(
is_quota_parked: Some(quota_parked),
is_bash_running: Some(bash_running),
is_running_tools: streaming && !core.running_tool_calls.is_empty(),
+ has_running_subagents: subagents_running,
attached_clients: core.attached_client_ids.len() as u32,
message_count: store.map_or(0, crate::session_store::SessionFile::message_count) as u32,
session_actions: session_snapshot(core),
diff --git a/crates/pa-daemon/src/worker/tests/summary_tests.rs b/crates/pa-daemon/src/worker/tests/summary_tests.rs
index c77350ead3..cf3e65f654 100644
--- a/crates/pa-daemon/src/worker/tests/summary_tests.rs
+++ b/crates/pa-daemon/src/worker/tests/summary_tests.rs
@@ -72,7 +72,7 @@ fn summary_lifecycle_is_message_based() {
assert_eq!(
session_summary(
&empty, "default", None, None, /*bash_running=*/ false,
- /*quota_parked=*/ false
+ /*quota_parked=*/ false, /*subagents_running=*/ false
)
.lifecycle,
"draft"
@@ -82,7 +82,7 @@ fn summary_lifecycle_is_message_based() {
assert_eq!(
session_summary(
&subagent, "default", None, None, /*bash_running=*/ false,
- /*quota_parked=*/ false
+ /*quota_parked=*/ false, /*subagents_running=*/ false
)
.lifecycle,
"live"
@@ -99,7 +99,7 @@ fn summary_lifecycle_is_message_based() {
assert!(
session_summary(
&busy, "default", None, None, /*bash_running=*/ false,
- /*quota_parked=*/ false
+ /*quota_parked=*/ false, /*subagents_running=*/ false
)
.is_running_tools
);
@@ -107,7 +107,7 @@ fn summary_lifecycle_is_message_based() {
assert!(
!session_summary(
&busy, "default", None, None, /*bash_running=*/ false,
- /*quota_parked=*/ false
+ /*quota_parked=*/ false, /*subagents_running=*/ false
)
.is_running_tools
);
@@ -116,7 +116,7 @@ fn summary_lifecycle_is_message_based() {
assert!(
!session_summary(
&busy, "default", None, None, /*bash_running=*/ false,
- /*quota_parked=*/ false
+ /*quota_parked=*/ false, /*subagents_running=*/ false
)
.is_running_tools
);
@@ -124,7 +124,8 @@ fn summary_lifecycle_is_message_based() {
// `session.isBashRunning`).
assert_eq!(
session_summary(
- &busy, "default", None, None, /*bash_running=*/ true, /*quota_parked=*/ false
+ &busy, "default", None, None, /*bash_running=*/ true,
+ /*quota_parked=*/ false, /*subagents_running=*/ false
)
.is_bash_running,
Some(true)
@@ -133,7 +134,7 @@ fn summary_lifecycle_is_message_based() {
assert_eq!(
session_summary(
&busy, "default", None, None, /*bash_running=*/ false,
- /*quota_parked=*/ false
+ /*quota_parked=*/ false, /*subagents_running=*/ false
)
.lifecycle,
"live"
@@ -157,7 +158,8 @@ fn summary_lifecycle_is_message_based() {
None,
None,
/*bash_running=*/ false,
- /*quota_parked=*/ false
+ /*quota_parked=*/ false,
+ /*subagents_running=*/ false
)
.lifecycle,
"live"
@@ -165,6 +167,43 @@ fn summary_lifecycle_is_message_based() {
let _ = std::fs::remove_dir_all(&dir);
}
+/// A session whose own turn ended keeps reporting `working` while any of
+/// its subagents runs (each child counts its own descendants the same
+/// way), so every roster surface classifies it running; with no running
+/// subagents it is idle again. Its own-work flag stays its own.
+#[test]
+fn running_subagents_keep_an_idle_session_working() {
+ let core = SessionCore::test_core(None, "/tmp".to_string());
+ let summary = |subagents_running| {
+ serde_json::to_value(session_summary(
+ &core,
+ "default",
+ None,
+ None,
+ /*bash_running=*/ false,
+ /*quota_parked=*/ false,
+ subagents_running,
+ ))
+ .unwrap()
+ };
+ let classify =
+ |summary: &Value| pa_types::daemon::agent_roster::classify_summary_value(summary, false);
+ let waiting = summary(true);
+ assert_eq!(waiting["activity"], "working");
+ assert_eq!(waiting["hasRunningSubagents"], true);
+ assert_eq!(waiting["isSessionActive"], false);
+ assert_eq!(
+ classify(&waiting),
+ pa_types::daemon::agent_roster::AgentRosterStatus::Running
+ );
+ let done = summary(false);
+ assert_eq!(done["activity"], "idle");
+ assert_eq!(
+ classify(&done),
+ pa_types::daemon::agent_roster::AgentRosterStatus::Idle
+ );
+}
+
/// The live row's `usage` is the whole-file own-usage fold the saved
/// row publishes, including spend before the latest compaction and the
/// compaction's own call.
@@ -223,6 +262,7 @@ fn live_summary_usage_is_the_catalog_fold() {
let core = SessionCore::test_core(Some(store), "/tmp".to_string());
let summary = session_summary(
&core, "default", None, None, /*bash_running=*/ false, /*quota_parked=*/ false,
+ /*subagents_running=*/ false,
);
// The live row equals the saved row, whole-object.
let catalog = crate::session_store::read_session_info(&path)
@@ -269,6 +309,7 @@ fn pathless_summary_usage_folds_the_in_memory_entries() {
let core = SessionCore::test_core(Some(store), "/tmp".to_string());
let summary = session_summary(
&core, "default", None, None, /*bash_running=*/ false, /*quota_parked=*/ false,
+ /*subagents_running=*/ false,
);
assert_eq!(
json!(summary.usage),
diff --git a/crates/pa-daemon/tests/rlm_quiescence_barrier_e2e.rs b/crates/pa-daemon/tests/rlm_quiescence_barrier_e2e.rs
index 60a49bbdd4..f94814dfde 100644
--- a/crates/pa-daemon/tests/rlm_quiescence_barrier_e2e.rs
+++ b/crates/pa-daemon/tests/rlm_quiescence_barrier_e2e.rs
@@ -434,6 +434,36 @@ fn headless_completion_waits_for_rlm_quiescence() {
);
}
+/// `wait_for_idle` with `waitForRlmQuiescence: true` is the same barrier:
+/// the parent's settle watcher waits on a child this way, so a child with
+/// running subagents is not idle until its whole subtree settled.
+#[test]
+fn wait_for_idle_waits_for_rlm_quiescence() {
+ let Some(kernel_python) = kernel_python() else {
+ return;
+ };
+ let mut lane = spawn_held_child_lane(&kernel_python);
+ lane.client.send_command(
+ "w1",
+ &json!({
+ "type": "wait_for_idle",
+ "activeSessionId": lane.parent_id,
+ "waitForRlmQuiescence": true,
+ }),
+ );
+ let idle = lane.client.read_response("w1");
+ assert_eq!(idle["success"], true, "wait_for_idle failed: {idle}");
+ let rows = rlm_children_rows(&mut lane.client, "g1", &lane.parent_id);
+ let child_row = rows
+ .iter()
+ .find(|row| row["id"] == json!(lane.child_id))
+ .expect("the spawned child's roster row");
+ assert_eq!(
+ child_row["status"], "done",
+ "wait_for_idle answered while the child was still running"
+ );
+}
+
/// The barrier reads the run's settlement, not the roster status: the
/// roster flips terminal inside the watcher's settle grace, and the
/// record only settles at the settle funnel - after the grace re-check,
diff --git a/crates/pa-types/src/daemon/agent_roster.rs b/crates/pa-types/src/daemon/agent_roster.rs
index 1f2cb0fa30..528a6388a3 100644
--- a/crates/pa-types/src/daemon/agent_roster.rs
+++ b/crates/pa-types/src/daemon/agent_roster.rs
@@ -189,6 +189,11 @@ pub fn session_activity_detail(summary: &Value, options: &SessionActivityOptions
if active("isBashRunning") {
return "running bash".to_string();
}
+ // The session's own turn ended, but its subagents still work: the
+ // worker reports `activity: "working"` for it, and the label says why.
+ if active("hasRunningSubagents") {
+ return "subagents running".to_string();
+ }
if str_field("lifecycle") == Some("archived") {
return "archived".to_string();
}
@@ -297,6 +302,18 @@ mod tests {
classify_summary_value(&summary, false),
AgentRosterStatus::Running
);
+ // Own turn done, subagents still running: the worker reports the
+ // session as working, so it classifies running.
+ let summary = json!({
+ "activeSessionId": "a1",
+ "activity": "working",
+ "isSessionActive": false,
+ "hasRunningSubagents": true,
+ });
+ assert_eq!(
+ classify_summary_value(&summary, false),
+ AgentRosterStatus::Running
+ );
// No active session id: not resident.
let summary = json!({ "activity": "working" });
assert_eq!(
@@ -388,6 +405,10 @@ mod tests {
detail(json!({ "activity": "working", "isCompacting": true })),
"compacting"
);
+ assert_eq!(
+ detail(json!({ "activity": "working", "hasRunningSubagents": true })),
+ "subagents running"
+ );
assert_eq!(
detail(json!({ "activity": "working", "workerState": "starting" })),
"starting"
diff --git a/crates/pa-types/src/daemon/command.rs b/crates/pa-types/src/daemon/command.rs
index aa5e3f834a..5cad672d75 100644
--- a/crates/pa-types/src/daemon/command.rs
+++ b/crates/pa-types/src/daemon/command.rs
@@ -569,6 +569,10 @@ pub enum DaemonCommand {
#[serde(default, skip_serializing_if = "Option::is_none")]
id: Option<String>,
active_session_id: String,
+ /// Also hold until every RLM child run of the session settled
+ /// (the `wait_for_headless_completion` barrier of the same name).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ wait_for_rlm_quiescence: Option<bool>,
#[serde(flatten)]
rest: JsonMap,
},