The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
chore(agent): remove unused background completions module
Steven Enamakelc98a2722deeb
diff --git a/crates/openhuman-core/src/agent/orchestration/background_completions.rs b/crates/openhuman-core/src/agent/orchestration/background_completions.rsindex 5bdd0627a1..ae393f4dcd 100644--- a/crates/openhuman-core/src/agent/orchestration/background_completions.rs+++ b/crates/openhuman-core/src/agent/orchestration/background_completions.rs@@ -1,270 +1,259 @@-//! Per-session queue of *finished* detached background sub-agents-//! (`spawn_async_subagent`) awaiting delivery back into the chat.+//! Host adapter over the harness `CompletionRouter` for finished detached+//! background sub-agents (`spawn_async_subagent`).//!-//! A detached sub-agent runs fire-and-forget; when it finishes, its result is-//! recorded here keyed by `parent_session`. The delivery subsystem-//! ([`super::background_delivery`]) drains the queue **when the session is-//! idle** (never mid-turn) and runs a single *system* turn on the parent chat-//! thread carrying every result ready at that moment — batched, with each one-//! tagged by its sub-agent process id. This module owns only the queue + the-//! notice formatting.--use std::collections::{HashMap, HashSet, VecDeque};-use std::sync::{Mutex, OnceLock};--/// Terminal disposition of a finished background sub-agent. Drives distinct-/// rendering in [`build_batched_notice`] so a failed / awaiting-input async-/// sub-agent surfaces in chat as such instead of being dropped or mistaken for a-/// success (#4896).-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]-pub(crate) enum BackgroundAgentOutcome {- /// Ran to a usable result (or partial progress framed as such).- #[default]- Completed,- /// The child errored before producing a result.- Failed,- /// The child paused asking the user a question and was not continued.- AwaitingInput,+//! The queue itself is the harness's: `tinyagents_tasks::CompletionRouter`+//! deduplicates by task id, holds tombstones (collected inline, stopped,+//! cancelled parent), counts delivery attempts, hands back the records that+//! gave up, and persists every transition to a per-workspace+//! `JsonlCompletionStore`, so a completion that was never delivered is+//! delivered after a restart. This module is the thin host seam over it:+//!+//! * one router per workspace, opened lazily next to the task ledger+//! (`<workspace>/.openhuman/background_completions.jsonl`);+//! * the router's parent key is the **chat thread id** — delivery is+//! thread-addressed, and a thread-scoped cancel (Stop, delete, purge) is then+//! the router's own `cancel_parent` / `resume_parent`;+//! * the product-specific lifecycle helpers (`record_failure`,+//! `record_awaiting_input`, `mark_collected`, ...) the spawn, wait, cancel and+//! thread paths call.+//!+//! When a parent is idle enough to receive a delivery turn, and the turn itself,+//! stays in [`super::background_delivery`]. The wording is+//! [`super::completion_notice`].++use std::collections::{HashMap, HashSet};+use std::path::{Path, PathBuf};+use std::sync::{Arc, Mutex, OnceLock};+use std::time::Duration;++use tinyagents_tasks::{+ CompletionRecord, CompletionResult, CompletionRouter, CompletionState, CompletionStore,+ InMemoryCompletionStore, JsonlCompletionStore, NotifyMode, RecordOutcome, TombstoneOutcome,+ DEFAULT_MAX_ATTEMPTS,+};++pub(crate) use super::completion_notice::BackgroundAgentOutcome;+use super::completion_notice::BackgroundCompletionFormatter;++/// How long a settled record (delivered / gave up / tombstoned) is kept before+/// compaction drops it. Dropping a settled record also drops its dedupe and its+/// tombstone, so this must outlive any child's interest in its parent.+const SETTLED_RETENTION: Duration = Duration::from_secs(30 * 24 * 60 * 60);++/// Retries for a failed store write before a completion is reported lost.+const RECORD_RETRIES: u32 = 3;++/// Bound on the session -> thread cache. Entries are cheap and re-learned, so+/// overflow simply clears it.+const SESSION_THREADS_CAP: usize = 4096;++/// A workspace's router plus the store it sits on (kept so boot recovery and+/// purge can enumerate parents, which the router itself does not expose).+struct Entry {+ router: Arc<CompletionRouter>,+ store: Arc<dyn CompletionStore>,}-/// One finished background sub-agent's deliverable result.-#[derive(Clone, Debug, PartialEq, Eq)]-pub(crate) struct CompletedBackgroundAgent {- /// Spawn process id (`sub-…`) — the tag the agent uses to reference it.- pub(crate) task_id: String,- /// Sub-agent definition id (e.g. `code_executor`).- pub(crate) agent_id: String,- /// The sub-agent's final output / summary.- pub(crate) summary: String,- /// Parent chat thread id to stream the delivery turn into (captured at- /// spawn). `None` for a headless spawn with no originating thread.- pub(crate) parent_thread_id: Option<String>,- /// Terminal disposition — success, failure, or awaiting-user — so delivery- /// can render failures/awaiting distinctly (#4896).- pub(crate) outcome: BackgroundAgentOutcome,+#[derive(Default)]+struct HostState {+ /// One router per workspace.+ routers: HashMap<PathBuf, Arc<Entry>>,+ /// Which workspace holds a thread's completions. Thread-scoped operations+ /// (Stop, delete) carry no workspace, only a thread id.+ thread_workspaces: HashMap<String, PathBuf>,+ /// Parent session id -> chat thread id, for the idle gate (busy is tracked+ /// by session; delivery by thread).+ session_threads: HashMap<String, String>,+ /// Threads the user stopped and has not yet re-engaged. Closes the+ /// spawn/register race: a child that registers after Stop is rejected.+ stopped_threads: HashSet<String>,}-/// Upper bound on the cancelled-thread tombstone set. A thread id is a one-shot-/// UUID, so only the *recently* cancelled threads can still be racing a late-/// completion; older tombstones are evicted in insertion order. 512 is far more-/// than the number of sub-agents that could realistically be mid-flight when a-/// batch of threads is deleted.-const CANCELLED_TOMBSTONE_CAP: usize = 512;--/// Upper bound on the collected-task tombstone set. A completion records within-/// seconds of the parent collecting it inline, so only recently collected task-/// ids can still be racing a late record; older tombstones are evicted in-/// insertion order.-const COLLECTED_TOMBSTONE_CAP: usize = 512;--/// Cap on the delivery-error text stored in the undelivered-results notice. The-/// notice is a permanent thread message, unlike the transient `chat_error`-/// event that already carries the same string, so an unbounded provider error-/// should not be able to dominate the transcript.-const MAX_PERSISTED_ERROR_CHARS: usize = 500;+fn state() -> std::sync::MutexGuard<'static, HostState> {+ static STATE: OnceLock<Mutex<HostState>> = OnceLock::new();+ STATE+ .get_or_init(|| Mutex::new(HostState::default()))+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+}-/// Shared state behind a single mutex so the cancellation check in-/// [`record_completion`] is atomic against the tombstone+sweep in-/// [`discard_for_thread`] — otherwise the cooperative-abort race could enqueue a-/// completion for a thread that was just deleted (see issue #3711 review).-#[derive(Default)]-struct QueueState {- /// Finished results awaiting idle delivery, keyed by `parent_session`.- pending: HashMap<String, Vec<CompletedBackgroundAgent>>,- /// Threads whose sub-agents were cancelled because the thread was- /// deleted/purged. A completion that lands here *after* the discard sweep- /// (Tokio `abort()` is cooperative — a task already past its last `.await`- /// still runs to `record_completion`) is dropped instead of delivered into- /// a thread that no longer exists.- cancelled_threads: HashSet<String>,- /// Insertion order for `cancelled_threads`, used to bound the set.- cancelled_order: VecDeque<String>,- /// Threads stopped by the user. Unlike deleted threads, these are reopened- /// by the next user chat request, but until then late completions from a- /// cooperatively-aborted child must not start a delivery turn.- stopped_threads: HashSet<String>,- /// Insertion order for `stopped_threads`, used to bound the set.- stopped_order: VecDeque<String>,- /// Detached task ids stopped by the user. Once the thread gate is reopened- /// for a later turn, this keeps a straggling task from the old generation- /// from recording its completion.- stopped_tasks: HashSet<String>,- /// Insertion order for `stopped_tasks`, used to bound the set.- stopped_task_order: VecDeque<String>,- /// Task ids the parent already collected inline via `wait_subagent` and will- /// present in its own turn. A completion for a collected task is dropped by- /// [`record_completion`] (closing the wait/record ordering race) and any- /// already-queued entry is swept by [`mark_collected`], so background- /// delivery never re-answers a result the master already surfaced (the- /// duplicate-response bug).- collected_tasks: HashSet<String>,- /// Insertion order for `collected_tasks`, used to bound the set.- collected_order: VecDeque<String>,+/// Where a workspace's completion log lives, beside the detached-task ledger.+fn completion_store_path(workspace_dir: &Path) -> PathBuf {+ workspace_dir+ .join(".openhuman")+ .join("background_completions.jsonl")}-impl QueueState {- /// Tombstone `thread_id` so any straggler completion for it is dropped.- fn tombstone(&mut self, thread_id: &str) {- if self.cancelled_threads.insert(thread_id.to_string()) {- self.cancelled_order.push_back(thread_id.to_string());- while self.cancelled_order.len() > CANCELLED_TOMBSTONE_CAP {- if let Some(evicted) = self.cancelled_order.pop_front() {- self.cancelled_threads.remove(&evicted);- }- }- }+fn entry_for(workspace_dir: &Path) -> Arc<Entry> {+ let mut st = state();+ if let Some(entry) = st.routers.get(workspace_dir) {+ return entry.clone();}-- fn stop(&mut self, thread_id: &str) {- if self.stopped_threads.insert(thread_id.to_string()) {- self.stopped_order.push_back(thread_id.to_string());- while self.stopped_order.len() > CANCELLED_TOMBSTONE_CAP {- if let Some(evicted) = self.stopped_order.pop_front() {- self.stopped_threads.remove(&evicted);- }- }+ let path = completion_store_path(workspace_dir);+ let store: Arc<dyn CompletionStore> = match JsonlCompletionStore::open(&path) {+ Ok(store) => Arc::new(store),+ Err(error) => {+ // A workspace that cannot be written degrades to an in-memory+ // queue rather than taking background delivery down.+ log::warn!(+ "[background_completions] could not open {}; using an in-memory queue \+ (completions will not survive a restart): {error}",+ path.display()+ );+ Arc::new(InMemoryCompletionStore::new())}- }+ };+ let router = CompletionRouter::new(store.clone())+ .with_formatter(Arc::new(BackgroundCompletionFormatter))+ .with_max_attempts(DEFAULT_MAX_ATTEMPTS);+ let entry = Arc::new(Entry {+ router: Arc::new(router),+ store,+ });+ st.routers.insert(workspace_dir.to_path_buf(), entry.clone());+ log::debug!(+ "[background_completions] opened router workspace_dir={}",+ workspace_dir.display()+ );+ entry+}- fn finish_stop(&mut self, task_ids: &[String]) {- for task_id in task_ids {- if self.stopped_tasks.insert(task_id.clone()) {- self.stopped_task_order.push_back(task_id.clone());- while self.stopped_task_order.len() > COLLECTED_TOMBSTONE_CAP {- if let Some(evicted) = self.stopped_task_order.pop_front() {- self.stopped_tasks.remove(&evicted);- }- }- }- }- }+/// The router for `workspace_dir`, opening it on first use.+pub(crate) fn router_for_workspace(workspace_dir: &Path) -> Arc<CompletionRouter> {+ entry_for(workspace_dir).router.clone()+}- fn resume_thread(&mut self, thread_id: &str) {- if self.stopped_threads.remove(thread_id) {- self.stopped_order.retain(|stopped| stopped != thread_id);- }- }+/// Remember which workspace holds `thread_id`'s completions.+fn note_thread_workspace(thread_id: &str, workspace_dir: &Path) {+ state()+ .thread_workspaces+ .insert(thread_id.to_string(), workspace_dir.to_path_buf());+}- fn mark_stopped_task_if_thread_stopped(&mut self, thread_id: &str, task_id: &str) -> bool {- if !self.stopped_threads.contains(thread_id) {- return false;- }- self.finish_stop(&[task_id.to_string()]);- true- }+/// The router that holds `thread_id`'s completions, if any child of that thread+/// was spawned or recorded in this process.+pub(crate) fn router_for_thread(thread_id: &str) -> Option<Arc<CompletionRouter>> {+ let workspace = state().thread_workspaces.get(thread_id).cloned()?;+ Some(router_for_workspace(&workspace))+}- /// Tombstone `task_id` so a completion that records after the parent- /// collected it inline is dropped rather than delivered again.- fn tombstone_collected(&mut self, task_id: &str) {- if self.collected_tasks.insert(task_id.to_string()) {- self.collected_order.push_back(task_id.to_string());- while self.collected_order.len() > COLLECTED_TOMBSTONE_CAP {- if let Some(evicted) = self.collected_order.pop_front() {- self.collected_tasks.remove(&evicted);- }- }- }+/// Remember that `session_id` is a turn on `thread_id`.+pub(crate) fn note_session_thread(session_id: &str, thread_id: &str) {+ let mut st = state();+ if st.session_threads.len() >= SESSION_THREADS_CAP {+ st.session_threads.clear();}+ st.session_threads+ .insert(session_id.to_string(), thread_id.to_string());}-static QUEUE: OnceLock<Mutex<QueueState>> = OnceLock::new();--fn queue() -> &'static Mutex<QueueState> {- QUEUE.get_or_init(|| Mutex::new(QueueState::default()))+/// The chat thread a session id belongs to: the cached mapping, else the+/// `thread_id` a web-channel session id carries in its JSON body.+pub(crate) fn thread_for_session(session_id: &str) -> Option<String> {+ if let Some(thread) = state().session_threads.get(session_id) {+ return Some(thread.clone());+ }+ if !session_id.starts_with('{') {+ return None;+ }+ serde_json::from_str::<serde_json::Value>(session_id)+ .ok()?+ .get("thread_id")?+ .as_str()+ .map(str::to_owned)}-/// Record a finished background sub-agent for later idle delivery, keyed by-/// `parent_session`. Idempotent on `task_id` within a session.-///-/// Drops the result outright if its parent thread has been tombstoned by-/// [`discard_for_thread`] — closing the race where a detached sub-agent finishes-/// (and records) concurrently with its parent thread being deleted.-pub(crate) fn record_completion(- parent_session: impl Into<String>,+/// Record a finished background sub-agent for idle delivery, keyed by its+/// parent chat thread. Idempotent on `task_id`.+pub(crate) async fn record_completion(+ workspace_dir: &Path,+ parent_session: &str,task_id: impl Into<String>,agent_id: impl Into<String>,summary: impl Into<String>,parent_thread_id: Option<String>,) {record_outcome(+ workspace_dir,parent_session,task_id,agent_id,summary,parent_thread_id,BackgroundAgentOutcome::Completed,- );+ )+ .await;}/// Record a finished background sub-agent carrying an explicit terminal-/// [`BackgroundAgentOutcome`]. This is the general enqueue behind-/// [`record_completion`] (success) and the [`record_failure`] /-/// [`record_awaiting_input`] framing helpers, so a failed or awaiting-input-/// async sub-agent is delivered back into chat too — not only successes (#4896).-/// Same tombstone / idempotency guarantees as [`record_completion`].-pub(crate) fn record_outcome(- parent_session: impl Into<String>,+/// [`BackgroundAgentOutcome`]. The general enqueue behind+/// [`record_completion`] and the [`record_failure`] / [`record_awaiting_input`]+/// framing helpers, so a failed or awaiting-input async sub-agent is delivered+/// back into chat too — not only successes (#4896).+///+/// The router drops the record when its task was tombstoned (collected inline,+/// stopped) or its thread was cancelled (deleted, stopped).+pub(crate) async fn record_outcome(+ workspace_dir: &Path,+ parent_session: &str,task_id: impl Into<String>,agent_id: impl Into<String>,summary: impl Into<String>,parent_thread_id: Option<String>,outcome: BackgroundAgentOutcome,) {- let parent_session = parent_session.into();- let entry = CompletedBackgroundAgent {- task_id: task_id.into(),- agent_id: agent_id.into(),- summary: summary.into(),- parent_thread_id,- outcome,- };- let mut state = queue()- .lock()- .expect("background_completions queue poisoned");- if let Some(thread_id) = entry.parent_thread_id.as_deref() {- if state.cancelled_threads.contains(thread_id) || state.stopped_threads.contains(thread_id)- {- log::debug!(- "[background_completions] dropping completion task_id={} for stopped/cancelled thread_id={}",- entry.task_id,- thread_id- );- return;- }- }- // The parent already collected this result inline (`wait_subagent`) and- // presents it in its own turn, so a background-delivery turn for it would- // just re-answer the same thing. Drop it (closes the wait-before-record- // race; the record-before-wait order is handled by the sweep in- // `mark_collected`).- if state.collected_tasks.contains(&entry.task_id) {- log::debug!(- "[background_completions] dropping completion task_id={} already collected inline",- entry.task_id- );- return;- }- if state.stopped_tasks.contains(&entry.task_id) {- log::debug!(- "[background_completions] dropping completion task_id={} stopped by user",- entry.task_id+ let task_id = task_id.into();+ let Some(thread_id) = parent_thread_id else {+ // Delivery is thread-addressed; a headless spawn has nowhere to land+ // the result. (`spawn_async_subagent` refuses to start one.)+ log::warn!(+ "[background_completions] dropping headless completion task_id={task_id} \+ session={parent_session}");return;+ };+ note_thread_workspace(&thread_id, workspace_dir);+ note_session_thread(parent_session, &thread_id);++ let record = CompletionRecord::new(+ task_id.clone(),+ thread_id.clone(),+ agent_id,+ outcome.status(),+ CompletionResult::text(summary),+ )+ .with_notify_mode(NotifyMode::Followup);+ let router = router_for_workspace(workspace_dir);+ match router.record_with_retries(record, RECORD_RETRIES).await {+ Ok(RecordOutcome::Recorded { .. }) => log::debug!(+ "[background_completions] recorded task_id={task_id} thread_id={thread_id} \+ outcome={outcome:?}"+ ),+ Ok(RecordOutcome::Duplicate) => {+ log::debug!("[background_completions] duplicate ignored task_id={task_id}")+ }+ Ok(RecordOutcome::Suppressed) => log::debug!(+ "[background_completions] dropping completion task_id={task_id} for \+ stopped/cancelled/collected thread_id={thread_id}"+ ),+ Ok(RecordOutcome::IdCollision) => log::warn!(+ "[background_completions] task id already recorded for another thread \+ task_id={task_id} thread_id={thread_id}"+ ),+ Err(error) => log::error!(+ "[background_completions] completion LOST — store write failed \+ task_id={task_id} thread_id={thread_id} error={error}"+ ),}- let pending = state.pending.entry(parent_session).or_default();- if pending.iter().any(|c| c.task_id == entry.task_id) {- return;- }- pending.push(entry);}/// Queue a **failed** async sub-agent for chat delivery (#4896). The summary is/// framed with the `[SUBAGENT_FAILED]` envelope the parent agent is prompted to/// relay, so the user learns the delegated task errored instead of the turn-/// silently finalizing on "Accepted". Enqueues via [`record_outcome`], so it-/// rides the same idle-gated `background_delivery` path as a success.-pub(crate) fn record_failure(- parent_session: impl Into<String>,+/// silently finalizing on "Accepted".+pub(crate) async fn record_failure(+ workspace_dir: &Path,+ parent_session: &str,task_id: impl Into<String>,agent_id: impl Into<String>,error: &str,@@ -273,28 +262,30 @@ pub(crate) fn record_failure(let summary =format!("[SUBAGENT_FAILED] the async sub-agent errored before producing a result: {error}");record_outcome(+ workspace_dir,parent_session,task_id,agent_id,summary,parent_thread_id,BackgroundAgentOutcome::Failed,- );+ )+ .await;}/// Queue an **awaiting-user** async sub-agent for chat delivery (#4896). A/// detached child that pauses to ask a question will not continue on its own, so/// the framed `[SUBAGENT_NEEDS_INPUT]` notice is delivered back into chat for the/// parent agent to relay to (or answer for) the user.-pub(crate) fn record_awaiting_input(- parent_session: impl Into<String>,+pub(crate) async fn record_awaiting_input(+ workspace_dir: &Path,+ parent_session: &str,task_id: impl Into<String>,agent_id: impl Into<String>,question: &str,checkpointed: bool,parent_thread_id: Option<String>,) {- let parent_session = parent_session.into();let task_id = task_id.into();let agent_id = agent_id.into();let summary = crate::agent::orchestration::tools::awaiting_user::awaiting_user_envelope(@@ -305,65 +296,52 @@ pub(crate) fn record_awaiting_input(checkpointed,);record_outcome(+ workspace_dir,parent_session,task_id,agent_id,summary,parent_thread_id,BackgroundAgentOutcome::AwaitingInput,- );-}--/// Is anything waiting to be delivered for this session? Cheap idle-loop check.-pub(crate) fn has_pending(parent_session: &str) -> bool {- queue()- .lock()- .expect("background_completions queue poisoned")- .pending- .get(parent_session)- .is_some_and(|v| !v.is_empty())+ )+ .await;}-/// Number of results pending for a session.-pub(crate) fn pending_count(parent_session: &str) -> usize {- queue()- .lock()- .expect("background_completions queue poisoned")- .pending- .get(parent_session)- .map_or(0, Vec::len)+/// Undelivered completions for `thread_id`, oldest first (read-only; includes+/// records an in-flight delivery currently holds).+pub(crate) fn pending_for(workspace_dir: &Path, thread_id: &str) -> Vec<CompletionRecord> {+ router_for_workspace(workspace_dir).pending_for(thread_id)}-/// Drain **all** results currently ready for this session — the "batch-/// everything ready at that moment" step. Returns them in completion order and-/// clears them so they're never re-delivered.-pub(crate) fn take_pending(parent_session: &str) -> Vec<CompletedBackgroundAgent> {- queue()- .lock()- .expect("background_completions queue poisoned")- .pending- .remove(parent_session)- .unwrap_or_default()+/// Mark `task_id` as collected inline by the parent (via `wait_subagent`) so its+/// background completion is not independently delivered as a second, duplicate+/// answer. The router withdraws an already-recorded completion and drops one+/// that arrives later. Returns whether a pending completion was withdrawn.+pub(crate) fn mark_collected(workspace_dir: &Path, task_id: &str) -> bool {+ let outcome = router_for_workspace(workspace_dir).tombstone(task_id);+ log::debug!("[background_completions] mark_collected task_id={task_id} outcome={outcome:?}");+ matches!(outcome, Ok(TombstoneOutcome::Suppressed))}-/// Drop every queued completion whose `parent_thread_id` is `thread_id`, across-/// **all** sessions, and **tombstone** the thread so any straggler completion-/// that records *after* this sweep (the cooperative-abort race) is dropped by-/// [`record_completion`] rather than delivered into a thread that no longer-/// exists. Called when that thread is deleted. Returns the number of queued-/// completions removed.+/// Drop every queued completion for `thread_id` and everything that finishes+/// for it later. Called when the thread is deleted: the router's cancelled-parent+/// marker is durable, so a straggler that wins the cooperative-abort race — or+/// finishes after a restart — is dropped rather than delivered into a thread that+/// no longer exists. Returns the number of queued completions removed.pub(crate) fn discard_for_thread(thread_id: &str) -> usize {- let mut state = queue()- .lock()- .expect("background_completions queue poisoned");- state.tombstone(thread_id);- let removed = remove_pending_for_thread(&mut state, thread_id);- log::debug!(- "[background_completions] discard_for_thread thread_id={} removed={} sessions_left={}",- thread_id,- removed,- state.pending.len()- );+ let Some(router) = router_for_thread(thread_id) else {+ return 0;+ };+ let removed = router.cancel_parent(thread_id).unwrap_or_else(|error| {+ log::error!(+ "[background_completions] cancel_parent failed thread_id={thread_id} error={error}"+ );+ 0+ });+ let mut st = state();+ st.thread_workspaces.remove(thread_id);+ st.stopped_threads.remove(thread_id);+ log::debug!("[background_completions] discard_for_thread thread_id={thread_id} removed={removed}");removed}@@ -372,245 +350,143 @@ pub(crate) fn discard_for_thread(thread_id: &str) -> usize {////// The Stop-button counterpart of [`discard_for_thread`]: the user halted the/// thread's work, so results that finished but were not yet delivered must not-/// start a fresh delivery turn behind their back. The thread itself stays-/// alive; after cancellation, old task ids are tombstoned while sub-agents-/// spawned by later turns use new ids and deliver normally. Returns the number-/// of queued completions removed.+/// start a fresh delivery turn behind their back. The thread stays alive; the+/// gate lifts at [`resume_stopped_thread`] (the next accepted user turn), while+/// the stopped generation's task ids stay tombstoned+/// ([`finish_stop_for_thread`]). Returns the number of queued completions removed.pub(crate) fn discard_pending_for_thread(thread_id: &str) -> usize {- let mut state = queue()- .lock()- .expect("background_completions queue poisoned");- state.stop(thread_id);- let removed = remove_pending_for_thread(&mut state, thread_id);+ state().stopped_threads.insert(thread_id.to_string());+ let Some(router) = router_for_thread(thread_id) else {+ return 0;+ };+ let removed = router.cancel_parent(thread_id).unwrap_or_else(|error| {+ log::error!(+ "[background_completions] cancel_parent failed thread_id={thread_id} error={error}"+ );+ 0+ });log::debug!(- "[background_completions] discard_pending_for_thread thread_id={} removed={} sessions_left={}",- thread_id,- removed,- state.pending.len()+ "[background_completions] discard_pending_for_thread thread_id={thread_id} removed={removed}");removed}-/// Complete a Stop operation after its registered children have been aborted.-///-/// The thread gate stays in place until [`resume_stopped_thread`] starts a new-/// user turn. That closes the spawn/register race: a child that was spawned-/// before Stop but registered after the registry sweep still cannot enqueue a-/// completion. Task tombstones additionally protect that stopped generation-/// after the next turn reopens the thread.-pub(crate) fn finish_stop_for_thread(_thread_id: &str, task_ids: &[String]) {- let mut state = queue()- .lock()- .expect("background_completions queue poisoned");- state.finish_stop(task_ids);+/// Complete a Stop after its registered children were aborted: tombstone their+/// task ids so a straggler from the stopped generation cannot record once a+/// later user turn reopens the thread.+pub(crate) fn finish_stop_for_thread(thread_id: &str, task_ids: &[String]) {+ let Some(router) = router_for_thread(thread_id) else {+ return;+ };+ for task_id in task_ids {+ if let Err(error) = router.tombstone(task_id) {+ log::warn!(+ "[background_completions] tombstone failed task_id={task_id} error={error}"+ );+ }+ }}/// Reopen a thread's completion gate for a newly accepted user turn.///-/// A Stop gate deliberately outlives registry cancellation, because a detached+/// The Stop gate deliberately outlives registry cancellation, because a detached/// child may be between `tokio::spawn` and `running_subagents::register` when/// Stop is pressed. New task ids remain distinct from the stopped generation.+/// Only a thread this process stopped or cancelled pays for the durable resume+/// marker, so an ordinary chat message writes nothing.pub(crate) fn resume_stopped_thread(thread_id: &str) {- queue()- .lock()- .expect("background_completions queue poisoned")- .resume_thread(thread_id);+ let was_stopped = state().stopped_threads.remove(thread_id);+ if !was_stopped {+ return;+ }+ if let Some(router) = router_for_thread(thread_id) {+ router.resume_parent(thread_id);+ log::debug!("[background_completions] resumed thread_id={thread_id}");+ }}/// Record a child that registers while its parent thread is stopped.////// Registration happens after the detached task is spawned. If Stop races that-/// narrow interval, the registry sweep cannot see the child; marking its task+/// narrow interval the registry sweep cannot see the child; tombstoning its task/// id here keeps it rejected even after a later user turn reopens the thread.-pub(crate) fn mark_stopped_task_if_thread_stopped(thread_id: &str, task_id: &str) -> bool {- queue()- .lock()- .expect("background_completions queue poisoned")- .mark_stopped_task_if_thread_stopped(thread_id, task_id)-}--fn remove_pending_for_thread(state: &mut QueueState, thread_id: &str) -> usize {- let mut removed = 0;- for pending in state.pending.values_mut() {- let before = pending.len();- pending.retain(|c| c.parent_thread_id.as_deref() != Some(thread_id));- removed += before - pending.len();+/// Also notes which workspace holds the thread's completions, so a later+/// thread-scoped Stop or delete can find the router. Returns whether the thread+/// is stopped.+pub(crate) fn mark_stopped_task_if_thread_stopped(+ workspace_dir: &Path,+ thread_id: &str,+ task_id: &str,+) -> bool {+ note_thread_workspace(thread_id, workspace_dir);+ if !state().stopped_threads.contains(thread_id) {+ return false;}- // Drop now-empty session buckets so the map doesn't accumulate keys.- state.pending.retain(|_, v| !v.is_empty());- removed-}--/// Mark `task_id` as collected inline by the parent (via `wait_subagent`) so its-/// background completion is not independently delivered as a second, duplicate-/// answer. Tombstones the id — bounded — so a completion that records *after*-/// this call (the wait-before-record ordering) is dropped by-/// [`record_completion`], and sweeps any entry already queued for it across all-/// sessions (the record-before-wait ordering). Both orderings resolve-/// atomically under the single queue mutex. Returns whether a queued entry was-/// removed.-pub(crate) fn mark_collected(task_id: &str) -> bool {- let mut state = queue()- .lock()- .expect("background_completions queue poisoned");- state.tombstone_collected(task_id);- let mut removed = false;- for pending in state.pending.values_mut() {- let before = pending.len();- pending.retain(|c| c.task_id != task_id);- removed |= pending.len() != before;+ if let Err(error) = router_for_workspace(workspace_dir).tombstone(task_id) {+ log::warn!("[background_completions] tombstone failed task_id={task_id} error={error}");}- // Drop now-empty session buckets so the map doesn't accumulate keys.- state.pending.retain(|_, v| !v.is_empty());- log::debug!(- "[background_completions] mark_collected task_id={task_id} removed_queued={removed}"- );- removed+ true}-/// Wipe every queued completion across all sessions. Called on a full thread-/// purge. Tombstones are left intact (the per-thread protection set by-/// [`discard_for_thread`]); the purge path tombstones each in-flight sub-agent's-/// thread before calling this, so stragglers are still dropped. Returns the-/// number of queued completions removed.+/// Withdraw every queued completion across all open workspaces. Called on a full+/// thread purge; each thread with undelivered results is cancelled durably, so+/// stragglers are still dropped. Returns the number of completions removed.pub(crate) fn clear_all() -> usize {- let mut state = queue()- .lock()- .expect("background_completions queue poisoned");- let removed: usize = state.pending.values().map(Vec::len).sum();- state.pending.clear();- log::debug!("[background_completions] clear_all removed={}", removed);- removed-}--/// The thread id to deliver a batch into — the first record that carries one.-pub(crate) fn batch_thread_id(completed: &[CompletedBackgroundAgent]) -> Option<String> {- completed.iter().find_map(|c| c.parent_thread_id.clone())-}--/// Build the single batched, system-injected notice for a set of finished-/// background sub-agents. Each result is wrapped in a-/// `<background_agent_result id="…">` tag carrying its sub-agent process id, so-/// the agent can reference / present them individually. Returns `None` for an-/// empty batch.-pub(crate) fn build_batched_notice(completed: &[CompletedBackgroundAgent]) -> Option<String> {- if completed.is_empty() {- return None;+ let entries: Vec<Arc<Entry>> = state().routers.values().cloned().collect();+ let mut removed = 0;+ for entry in entries {+ let parents: HashSet<String> = entry+ .store+ .list(None)+ .into_iter()+ .filter(|r| r.state == CompletionState::Pending && !r.parent_key.is_empty())+ .map(|r| r.parent_key)+ .collect();+ for parent in parents {+ removed += entry.router.cancel_parent(&parent).unwrap_or(0);+ }}- let n = completed.len();- let mut out = String::new();- out.push_str(&format!(- "[{n} background sub-agent{} finished while you were busy. Review each result \- below — including any that FAILED or NEED INPUT — and present what is relevant \- to the user (never silently drop a failure or an awaiting-input pause). Each is \- tagged with its sub-agent process id.]\n",- if n == 1 { "" } else { "s" },- ));- out.push_str(&render_results(completed));- Some(out)-}--/// Defang any sequence in untrusted sub-agent output that could forge or-/// terminate one of the envelope tags below.-///-/// A sub-agent summary is arbitrary text: it can carry tool-fetched web-/// content, file contents, or anything else the child produced. Interpolated-/// raw, a summary containing `</background_agent_result>` closes its own-/// envelope early and everything after it reads as if it came from the host-/// rather than from the child — and a forged *opening* tag invents a result-/// that no sub-agent produced. Both matter more now that this text can be-/// persisted into the thread verbatim when delivery gives up, because a stored-/// message is replayed to every later turn with the authority of the-/// transcript rather than being a one-shot prompt.-///-/// Only the exact markers that could impersonate this envelope are escaped, so-/// ordinary prose and code in a summary survive unchanged.-fn neutralize_envelope_markers(summary: &str) -> String {- // Escape the bracket rather than prefixing it: a prefixed `\</tag>` still- // contains the literal marker, so it reads as a real boundary to anything- // scanning the text. `<` removes the character that makes it a tag while- // keeping the content legible and recoverable.- summary- .replace("</background_agent_", "</background_agent_")- .replace("<background_agent_", "<background_agent_")+ log::debug!("[background_completions] clear_all removed={removed}");+ removed}-/// Render each result with its outcome-specific tag. Shared by the normal-/// delivery notice and by the undelivered fallback, so a result reads the same-/// either way and a failure is never dressed up as a completion.-fn render_results(completed: &[CompletedBackgroundAgent]) -> String {- let mut out = String::new();- for c in completed {- // Distinct tag per terminal outcome so a failure / awaiting-input result- // is not presented as a normal completion (#4896).- let (tag, empty_fallback) = match c.outcome {- BackgroundAgentOutcome::Completed => {- ("background_agent_result", "(no output reported)")- }- BackgroundAgentOutcome::Failed => (- "background_agent_failure",- "(failed with no detail reported)",- ),- BackgroundAgentOutcome::AwaitingInput => (- "background_agent_needs_input",- "(the sub-agent paused awaiting user input)",- ),- };- let summary = if c.summary.trim().is_empty() {- empty_fallback.to_string()- } else {- neutralize_envelope_markers(c.summary.trim())- };- out.push_str(&format!(- "\n<{tag} id=\"{}\" agent=\"{}\">\n{}\n</{tag}>\n",- c.task_id, c.agent_id, summary,- ));+/// Boot recovery for a workspace: open its log, drop long-settled records, and+/// return the threads that still hold undelivered completions (a previous+/// process finished the work but never delivered it). Remembers each thread's+/// workspace so the delivery loop can claim them.+pub(crate) fn recover_pending_threads(workspace_dir: &Path) -> Vec<String> {+ let entry = entry_for(workspace_dir);+ if let Err(error) = entry.router.compact(SETTLED_RETENTION) {+ log::warn!("[background_completions] compact failed error={error}");}- out-}--/// Build the notice written **straight into the thread** when the delivery turn-/// has failed too many times to keep retrying.-///-/// Delivery normally runs a system turn so the agent can present a result in-/// context. When that turn cannot succeed, the results still exist and the user-/// is still owed them — so they are persisted verbatim instead, with an-/// `[BACKGROUND_DELIVERY_FAILED]` envelope saying plainly that this is a failed-/// delivery and why. The envelope follows the `[SUBAGENT_FAILED]` precedent-/// (#4896): the user learns the delegated work finished and could not be-/// delivered normally, rather than the result vanishing or arriving as an-/// unexplained raw dump.-pub(crate) fn build_undelivered_notice(- completed: &[CompletedBackgroundAgent],- attempts: u32,- error: &str,-) -> Option<String> {- if completed.is_empty() {- return None;+ let threads: HashSet<String> = entry+ .store+ .list(None)+ .into_iter()+ .filter(|r| {+ r.state == CompletionState::Pending+ && r.notify_mode != NotifyMode::Off+ && !r.parent_key.is_empty()+ })+ .map(|r| r.parent_key)+ .collect();+ let mut threads: Vec<String> = threads+ .into_iter()+ // `pending_for` is the router's view: it drops threads a cancelled-parent+ // marker has since withdrawn.+ .filter(|thread| !entry.router.pending_for(thread).is_empty())+ .collect();+ threads.sort();+ for thread in &threads {+ note_thread_workspace(thread, workspace_dir);}- let n = completed.len();- // The error text is already surfaced to the client on every failed delivery- // (`chat_error` carries it verbatim), so including it here is not a new- // exposure — but a stored message is permanent where that event is- // transient, so bound it and defang it like any other untrusted text.- let error = neutralize_envelope_markers(error);- let error = if error.chars().count() > MAX_PERSISTED_ERROR_CHARS {- let truncated: String = error.chars().take(MAX_PERSISTED_ERROR_CHARS).collect();- format!("{truncated}… (truncated)")- } else {- error- };- let mut out = format!(- "[BACKGROUND_DELIVERY_FAILED] {n} background sub-agent result{} finished, but \- could not be delivered into this conversation after {attempts} attempts. \- Last error: {error}\n\nThe {} shown verbatim below so nothing is lost — it has \- not been reviewed or summarised, because the turn that would have done so is \- the thing that failed.\n",- if n == 1 { "" } else { "s" },- if n == 1 { "result is" } else { "results are" },+ log::info!(+ "[background_completions] boot recovery found {} thread(s) with undelivered completions \+ workspace_dir={}",+ threads.len(),+ workspace_dir.display());- out.push_str(&render_results(completed));- Some(out)+ threads}#[cfg(test)]