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
fix(subagents): keep the abort guard armed through terminal delivery; E2E-test cancel
M3gA-Mind8b48d1b6f04e
diff --git a/app/src/store/__tests__/chatRuntimeSlice.test.ts b/app/src/store/__tests__/chatRuntimeSlice.test.tsindex 582c4603dc..e578b6d2a3 100644--- a/app/src/store/__tests__/chatRuntimeSlice.test.ts+++ b/app/src/store/__tests__/chatRuntimeSlice.test.ts@@ -15,6 +15,7 @@ import reducer, {endInferenceTurn,hydrateRuntimeFromRunLedger,hydrateRuntimeFromSnapshot,+ isActiveTimelineStatus,markInferenceTurnStreaming,removeArtifactForThread,setInferenceStatusForThread,@@ -1459,18 +1460,28 @@ describe('subagent event reducers (Phase 3)', () => {it('subagentCancelResolved settles a spinning row by task id from the cancel answer', () => {// Aborted: the run was cancelled.const aborted = reducer(spawn(), subagentCancelResolved({ taskId: 'task-1', cancelled: true }));- expect(aborted.toolTimelineByThread['t1'][0].status).toBe('cancelled');+ const row = aborted.toolTimelineByThread['t1'][0];+ expect(row.status).toBe('cancelled');+ // Consumers decide "still running?" from these, not the raw strings: the+ // settled row and its nested activity must both read as inactive.+ expect(isActiveTimelineStatus(row.status)).toBe(false);+ expect(row.subagent?.status).toBe('cancelled');+ expect(isActiveTimelineStatus(row.subagent?.status)).toBe(false);// Not running any more: settle on how the core says it ended — never// assume success. A failed run stays failed; an unknown one reads as// cancelled (the user asked to stop it and nothing is running).- const settle = (outcome?: 'completed' | 'failed' | 'unknown') =>- reducer(spawn(), subagentCancelResolved({ taskId: 'task-1', cancelled: false, outcome }))- .toolTimelineByThread['t1'][0].status;- expect(settle('completed')).toBe('success');- expect(settle('failed')).toBe('error');- expect(settle('unknown')).toBe('cancelled');- expect(settle(undefined)).toBe('cancelled');+ const settle = (outcome?: 'completed' | 'failed' | 'unknown') => {+ const r = reducer(+ spawn(),+ subagentCancelResolved({ taskId: 'task-1', cancelled: false, outcome })+ ).toolTimelineByThread['t1'][0];+ return [r.status, r.subagent?.status];+ };+ expect(settle('completed')).toEqual(['success', 'completed']);+ expect(settle('failed')).toEqual(['error', 'failed']);+ expect(settle('unknown')).toEqual(['cancelled', 'cancelled']);+ expect(settle(undefined)).toEqual(['cancelled', 'cancelled']);// Another task's answer leaves this row alone.const other = reducer(spawn(), subagentCancelResolved({ taskId: 'task-2', cancelled: true }));diff --git a/app/src/store/chatRuntimeSlice.ts b/app/src/store/chatRuntimeSlice.tsindex 2d24226d9a..4ff43974f9 100644--- a/app/src/store/chatRuntimeSlice.ts+++ b/app/src/store/chatRuntimeSlice.ts@@ -1994,19 +1994,23 @@ const chatRuntimeSlice = createSlice({: outcome === 'failed'? 'error': 'cancelled';+ // The nested activity drives the card's own transcript status, so it+ // settles with the row (its vocabulary: completed / failed / cancelled).+ const activityStatus =+ status === 'success' ? 'completed' : status === 'error' ? 'failed' : 'cancelled';const matches = (e: ToolTimelineEntry) =>e.subagent?.taskId === taskId && isActiveTimelineStatus(e.status);+ const settle = (entry: ToolTimelineEntry) => {+ entry.status = status;+ if (entry.subagent) entry.subagent.status = activityStatus;+ };for (const threadId of Object.keys(state.toolTimelineByThread).concat(Object.keys(state.settledTurnsByThread))) {- for (const entry of subagentRows(state, threadId, matches)) {- entry.status = status;- }+ subagentRows(state, threadId, matches).forEach(settle);}for (const timelines of Object.values(state.turnTimelinesByThread)) {- for (const entry of Object.values(timelines).flat().filter(matches)) {- entry.status = status;- }+ Object.values(timelines).flat().filter(matches).forEach(settle);}},subagentIterationStarted: (diff --git a/crates/openhuman-core/src/agent/orchestration/subagent_control_tests.rs b/crates/openhuman-core/src/agent/orchestration/subagent_control_tests.rsindex cb13fa1196..1bc6d8647a 100644--- a/crates/openhuman-core/src/agent/orchestration/subagent_control_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/subagent_control_tests.rs@@ -67,6 +67,12 @@ async fn cancel_of_a_finished_run_reports_its_outcome_and_rewrites_nothing() {.lock().unwrap_or_else(|e| e.into_inner());let workspace = tempfile::tempdir().expect("tempdir");+ // Snapshot the durable session store before and after: a real cancel+ // would `mark_failed` the session and rewrite this file.+ let store = SubagentSessionStore::new(workspace.path().to_path_buf());+ std::fs::create_dir_all(store.path().parent().expect("store has a parent")).expect("mkdir");+ let before = "[]";+ std::fs::write(store.path(), before).expect("seed store");for (task_id, status, outcome) in [("sub-rpc-done",@@ -105,10 +111,9 @@ async fn cancel_of_a_finished_run_reports_its_outcome_and_rewrites_nothing() {assert_eq!(field(&out, "cancelled"), Some(json!(false)), "{task_id}");assert_eq!(field(&out, "outcome"), Some(json!(outcome)), "{task_id}");}- assert!(- !SubagentSessionStore::new(workspace.path().to_path_buf())- .path()- .exists(),+ assert_eq!(+ std::fs::read_to_string(store.path()).expect("store still readable"),+ before,"a finished run's session must not be rewritten as cancelled");}diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rsindex 3867e7704f..58d7db2693 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs@@ -389,7 +389,6 @@ impl SpawnAsyncSubagentTool {let background_agent_id = definition.id.clone();let background_task_id = task_id.clone();let background_parent_session = parent_session.clone();- let background_progress = progress_sink.clone();let background_worker_thread_id = worker_thread_id.clone();let background_store = store.clone();let background_subagent_session_id = durable_session.subagent_session_id.clone();@@ -449,7 +448,6 @@ impl SpawnAsyncSubagentTool {options,).await;- abort_report.disarm();match result {Ok(outcome) => {let emit_lifecycle_effects = outcome.should_emit_lifecycle_effects();@@ -507,29 +505,27 @@ impl SpawnAsyncSubagentTool {outcome.output.chars().count(),outcome.iterations,);- if let Some(ref tx) = background_progress {- let _ = tx- .send(AgentProgress::SubagentCompleted {- agent_id: outcome.agent_id,- task_id: outcome.task_id,- elapsed_ms: outcome.elapsed.as_millis() as u64,- iterations: outcome.iterations as u32,- output_chars: outcome.output.chars().count(),- output: outcome.output.clone(),- // Detached by construction:- // this tool takes- // `detached_child()`, so this- // child's spend never reached- // the parent turn's ledger and- // `chat_done` does not contain- // it. See the field's docs.- usage: Some(outcome.usage),- worktree_path: None,- changed_files: Vec::new(),- dirty_status: None,- })- .await;- }+ abort_report+ .deliver(AgentProgress::SubagentCompleted {+ agent_id: outcome.agent_id,+ task_id: outcome.task_id,+ elapsed_ms: outcome.elapsed.as_millis() as u64,+ iterations: outcome.iterations as u32,+ output_chars: outcome.output.chars().count(),+ output: outcome.output.clone(),+ // Detached by construction:+ // this tool takes+ // `detached_child()`, so this+ // child's spend never reached+ // the parent turn's ledger and+ // `chat_done` does not contain+ // it. See the field's docs.+ usage: Some(outcome.usage),+ worktree_path: None,+ changed_files: Vec::new(),+ dirty_status: None,+ })+ .await;}}SubagentRunStatus::Incomplete { ref reason } => {@@ -587,29 +583,27 @@ impl SpawnAsyncSubagentTool {outcome.output.chars().count(),outcome.iterations,);- if let Some(ref tx) = background_progress {- let _ = tx- .send(AgentProgress::SubagentCompleted {- agent_id: outcome.agent_id,- task_id: outcome.task_id,- elapsed_ms: outcome.elapsed.as_millis() as u64,- iterations: outcome.iterations as u32,- output_chars: outcome.output.chars().count(),- output: outcome.output.clone(),- // Detached by construction:- // this tool takes- // `detached_child()`, so this- // child's spend never reached- // the parent turn's ledger and- // `chat_done` does not contain- // it. See the field's docs.- usage: Some(outcome.usage),- worktree_path: None,- changed_files: Vec::new(),- dirty_status: None,- })- .await;- }+ abort_report+ .deliver(AgentProgress::SubagentCompleted {+ agent_id: outcome.agent_id,+ task_id: outcome.task_id,+ elapsed_ms: outcome.elapsed.as_millis() as u64,+ iterations: outcome.iterations as u32,+ output_chars: outcome.output.chars().count(),+ output: outcome.output.clone(),+ // Detached by construction:+ // this tool takes+ // `detached_child()`, so this+ // child's spend never reached+ // the parent turn's ledger and+ // `chat_done` does not contain+ // it. See the field's docs.+ usage: Some(outcome.usage),+ worktree_path: None,+ changed_files: Vec::new(),+ dirty_status: None,+ })+ .await;}}SubagentRunStatus::Cancelled => {@@ -646,15 +640,13 @@ impl SpawnAsyncSubagentTool {outcome.agent_id.clone(),error.clone(),);- if let Some(ref tx) = background_progress {- let _ = tx- .send(AgentProgress::SubagentFailed {- agent_id: outcome.agent_id,- task_id: outcome.task_id,- error,- })- .await;- }+ abort_report+ .deliver(AgentProgress::SubagentFailed {+ agent_id: outcome.agent_id,+ task_id: outcome.task_id,+ error,+ })+ .await;}}SubagentRunStatus::AwaitingUser {@@ -700,20 +692,18 @@ impl SpawnAsyncSubagentTool {outcome.agent_id.clone(),question.clone(),);- if let Some(ref tx) = background_progress {- let _ = tx- .send(AgentProgress::SubagentAwaitingUser {- agent_id: outcome.agent_id,- task_id: outcome.task_id,- question: question.clone(),- worker_thread_id: background_worker_thread_id- .clone(),- checkpoint_path: checkpoint- .as_ref()- .map(|path| path.to_string_lossy().to_string()),- })- .await;- }+ abort_report+ .deliver(AgentProgress::SubagentAwaitingUser {+ agent_id: outcome.agent_id,+ task_id: outcome.task_id,+ question: question.clone(),+ worker_thread_id: background_worker_thread_id+ .clone(),+ checkpoint_path: checkpoint+ .as_ref()+ .map(|path| path.to_string_lossy().to_string()),+ })+ .await;}}}@@ -755,17 +745,16 @@ impl SpawnAsyncSubagentTool {background_agent_id.clone(),error.clone(),);- if let Some(ref tx) = background_progress {- let _ = tx- .send(AgentProgress::SubagentFailed {- agent_id: background_agent_id,- task_id: background_task_id,- error,- })- .await;- }+ abort_report+ .deliver(AgentProgress::SubagentFailed {+ agent_id: background_agent_id,+ task_id: background_task_id,+ error,+ })+ .await;}}+ abort_report.disarm();}),));diff --git a/crates/openhuman-core/src/agent/orchestration/tools/subagent_abort_report.rs b/crates/openhuman-core/src/agent/orchestration/tools/subagent_abort_report.rsindex b47870dee5..85c1ab060b 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/subagent_abort_report.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/subagent_abort_report.rs@@ -12,9 +12,13 @@//! `Cancelled` branch. Nothing was sent, and the card spun forever with a//! "Cancel task" button that could no longer do anything.//!-//! [`AbortReport`] is armed around the run and disarmed once the run returns-//! (every branch after that reports itself). If the future is dropped while-//! still armed, `Drop` sends the missing `SubagentFailed`. `Drop` cannot await,+//! [`AbortReport`] is armed for the whole detached task and disarmed only when+//! it ends. The task's own terminal event goes through [`AbortReport::deliver`],+//! which remembers it while the send is in flight: an abort that lands during+//! that send (a late Cancel on a run that just finished aborts too — the+//! registry cannot tell) re-sends the *real* outcome instead of losing it. If+//! the future is dropped before any terminal event, `Drop` sends a synthetic+//! `SubagentFailed`. `Drop` cannot await,//! so it tries `try_send` first; if the channel is momentarily full it hands//! the event to a spawned task that waits for room, because this event is the//! only thing that settles the card. A closed channel has no reader left to@@ -34,6 +38,11 @@ pub(crate) struct AbortReport {agent_id: String,task_id: String,armed: bool,+ /// The terminal event being sent right now, re-sent by `Drop` if the send+ /// is aborted.+ pending: Option<AgentProgress>,+ /// A terminal event already reached the channel; nothing left to report.+ delivered: bool,}impl AbortReport {@@ -47,10 +56,24 @@ impl AbortReport {agent_id: agent_id.to_string(),task_id: task_id.to_string(),armed: true,+ pending: None,+ delivered: false,}}- /// The run returned; its own branches report the outcome from here on.+ /// Send the task's own terminal event, guarded: if this send is aborted,+ /// `Drop` delivers the same event instead of a synthetic failure.+ pub(crate) async fn deliver(&mut self, event: AgentProgress) {+ let Some(tx) = self.progress.clone() else {+ return;+ };+ self.pending = Some(event.clone());+ let _ = tx.send(event).await;+ self.pending = None;+ self.delivered = true;+ }++ /// The task ended normally; nothing is left for `Drop` to report.pub(crate) fn disarm(&mut self) {self.armed = false;}@@ -58,7 +81,7 @@ impl AbortReport {impl Drop for AbortReport {fn drop(&mut self) {- if !self.armed {+ if !self.armed || self.delivered {return;}let Some(tx) = self.progress.as_ref() else {@@ -69,11 +92,14 @@ impl Drop for AbortReport {);return;};- let event = AgentProgress::SubagentFailed {- agent_id: self.agent_id.clone(),- task_id: self.task_id.clone(),- error: ABORTED_ERROR.to_string(),- };+ let event = self+ .pending+ .take()+ .unwrap_or_else(|| AgentProgress::SubagentFailed {+ agent_id: self.agent_id.clone(),+ task_id: self.task_id.clone(),+ error: ABORTED_ERROR.to_string(),+ });match tx.try_send(event) {Ok(()) => log::info!("[subagent_abort_report] reported aborted sub-agent task_id={} agent_id={}",diff --git a/crates/openhuman-core/src/agent/orchestration/tools/subagent_abort_report_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/subagent_abort_report_tests.rsindex 5cc796e93a..394764f1c0 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/subagent_abort_report_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/subagent_abort_report_tests.rs@@ -82,3 +82,65 @@ async fn a_full_channel_still_delivers_the_report_once_there_is_room() {));}++fn completed(task_id: &str) -> AgentProgress {+ AgentProgress::SubagentCompleted {+ agent_id: "agent_memory".into(),+ task_id: task_id.into(),+ elapsed_ms: 1,+ iterations: 1,+ output_chars: 2,+ output: "ok".into(),+ usage: None,+ worktree_path: None,+ changed_files: Vec::new(),+ dirty_status: None,+ }+}++/// A late Cancel aborts a run that has already finished and is still waiting+/// to send its completion (the registry cannot tell). The guard must deliver+/// that real completion, not a synthetic failure and not nothing.+#[tokio::test]+async fn an_abort_during_delivery_resends_the_real_outcome() {+ let (tx, mut rx) = tokio::sync::mpsc::channel(1);+ tx.send(AgentProgress::TurnStarted)+ .await+ .expect("fill the channel");+ let (sending_tx, sending_rx) = tokio::sync::oneshot::channel();+ let task = tokio::spawn(async move {+ let mut report = AbortReport::arm(Some(tx), "agent_memory", "sub-late");+ let _ = sending_tx.send(());+ report.deliver(completed("sub-late")).await; // blocks: channel full+ report.disarm();+ });+ sending_rx.await.expect("task reached delivery");+ tokio::task::yield_now().await;+ task.abort();+ let _ = task.await;++ assert!(matches!(rx.recv().await, Some(AgentProgress::TurnStarted)));+ let event = tokio::time::timeout(std::time::Duration::from_secs(5), rx.recv())+ .await+ .expect("the real outcome arrives")+ .expect("channel open");+ assert!(+ matches!(event, AgentProgress::SubagentCompleted { ref task_id, .. } if task_id == "sub-late"),+ "expected the real completion, got {event:?}"+ );+}++/// Once the terminal event reached the channel, nothing more is reported —+/// even if the task is dropped before it disarms.+#[tokio::test]+async fn a_delivered_outcome_is_not_reported_twice() {+ let (tx, mut rx) = tokio::sync::mpsc::channel(4);+ let mut report = AbortReport::arm(Some(tx), "agent_memory", "sub-once");+ report.deliver(completed("sub-once")).await;+ drop(report);+ assert!(matches!(+ rx.recv().await,+ Some(AgentProgress::SubagentCompleted { .. })+ ));+ assert!(rx.recv().await.is_none(), "no second, synthetic report");+}diff --git a/scripts/ci/check-openhuman-rust-layout.mjs b/scripts/ci/check-openhuman-rust-layout.mjsindex f8a9b44c49..e00ca6fdf0 100644--- a/scripts/ci/check-openhuman-rust-layout.mjs+++ b/scripts/ci/check-openhuman-rust-layout.mjs@@ -26,7 +26,9 @@ const LEGACY_LIMITS = new Map([// visibility change in `subagent_sessions`, which is follow-up, not this PR.["crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs",- 821,+ // 821 -> 809: the terminal progress sends go through `AbortReport::deliver`+ // (one call instead of an `if let` around `tx.send`). Pinned at the new size.+ 809,],// `spawn_subagent_tool_impl.rs` had its entry DELETED, not lowered: the// parameter schema moved to `spawn_subagent_parameters.rs` and the file isdiff --git a/tests/agent_harness_e2e.rs b/tests/agent_harness_e2e.rsindex 6a212a12ac..916d91d8d3 100644--- a/tests/agent_harness_e2e.rs+++ b/tests/agent_harness_e2e.rs@@ -5084,3 +5084,122 @@ async fn thread_goal_is_set_read_back_and_completed_across_turns_inner() {stack.shutdown();}++/// Cancelling a running background sub-agent settles its card, end to end.+///+/// Cancel aborts the detached task, and an aborted future never reaches its own+/// `Cancelled` branch — so before `AbortReport` the client got no terminal event+/// and the delegation card spun forever. This drives the production path: a+/// real `spawn_async_subagent` child held mid-model-call by the canary barrier,+/// cancelled over the `openhuman.subagent_cancel` JSON-RPC, and observed on the+/// same SSE stream the app renders from (`subagent_failed` is what settles the+/// card's row). A second cancel then gets the RPC's "nothing running" answer+/// with `outcome: "unknown"`, which the card settles on without claiming+/// success.+#[test]+fn cancelling_a_running_background_subagent_settles_it() {+ run_on_agent_stack(+ "cancelling_a_running_background_subagent_settles_it",+ cancelling_a_running_background_subagent_settles_it_inner,+ );+}++async fn cancelling_a_running_background_subagent_settles_it_inner() {+ let _lock = env_lock();+ // The second canary never arrives, so the worker's model call is held for+ // `CANARY_BARRIER_WAIT`: long enough to cancel it while it is running.+ arm_canary_barrier(&["CANCEL_E2E_CANARY", "CANCEL_E2E_NEVER"]);+ reset_script(vec![+ tool_calls_completion(&[(+ "spawn_async_subagent",+ json!({ "agent_id": "researcher", "prompt": "Find CANCEL_E2E_CANARY" }),+ )]),+ text_completion("Spawned a worker; its result will arrive later."),+ text_completion("worker would have finished here"),+ ]);+ let stack = boot_stack().await;+ let mut events = spawn_sse_collector(format!(+ "{}/events?client_id=harness-cancel",+ stack.rpc_base+ ))+ .await;+ send_web_chat(+ &stack.rpc_base,+ 900,+ "harness-cancel",+ "thread-cancel",+ "delegate, then cancel it",+ )+ .await;++ let spawned = wait_for_event(&mut events, "subagent_spawned", Duration::from_secs(120)).await;+ let task_id = spawned+ .get("skill_id")+ .and_then(Value::as_str)+ .unwrap_or_else(|| panic!("subagent_spawned carries the task id: {spawned}"))+ .to_string();++ // Cancel only once the worker is really in flight (its own model request+ // is parked on the barrier), so this is a live run, not a queued one.+ let deadline = std::time::Instant::now() + Duration::from_secs(60);+ while with_captured(|c| {+ !c.iter()+ .filter_map(|r| canary_worker_request(r.get("body")?))+ .any(|canary| canary == "CANCEL_E2E_CANARY")+ }) {+ assert!(+ std::time::Instant::now() < deadline,+ "the worker never issued its request"+ );+ tokio::time::sleep(Duration::from_millis(50)).await;+ }++ let reply = post_json_rpc(+ &stack.rpc_base,+ 901,+ "openhuman.subagent_cancel",+ json!({ "taskId": task_id }),+ )+ .await;+ let result = assert_no_jsonrpc_error(&reply, "subagent_cancel");+ let payload = result.get("data").unwrap_or(result);+ assert_eq!(+ payload.get("cancelled").and_then(Value::as_bool),+ Some(true),+ "a running child is really cancelled: {reply}"+ );+ assert!(+ payload.get("outcome").is_none(),+ "a real cancel carries no outcome: {reply}"+ );++ // The aborted child still reports: this is the event that settles the card.+ let failed = wait_for_event(&mut events, "subagent_failed", Duration::from_secs(30)).await;+ assert_eq!(+ failed.get("skill_id").and_then(Value::as_str),+ Some(task_id.as_str()),+ "subagent_failed must name the cancelled task: {failed}"+ );++ // Nothing runs under that id any more: the card settles on this answer.+ let again = post_json_rpc(+ &stack.rpc_base,+ 902,+ "openhuman.subagent_cancel",+ json!({ "taskId": task_id }),+ )+ .await;+ let result = assert_no_jsonrpc_error(&again, "second subagent_cancel");+ let payload = result.get("data").unwrap_or(result);+ assert_eq!(+ payload.get("cancelled").and_then(Value::as_bool),+ Some(false)+ );+ assert_eq!(+ payload.get("outcome").and_then(Value::as_str),+ Some("unknown"),+ "a cancel that finds nothing reports the outcome, never success: {again}"+ );++ disarm_canary_barrier();+}