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): report the cancel outcome, defer a full-channel abort report, settle restored rows
M3gA-Mind316020bb514d
diff --git a/app/src/features/conversations/aui/SubagentTaskCard.test.tsx b/app/src/features/conversations/aui/SubagentTaskCard.test.tsxindex 4b473a4ef4..e20404650f 100644--- a/app/src/features/conversations/aui/SubagentTaskCard.test.tsx+++ b/app/src/features/conversations/aui/SubagentTaskCard.test.tsx@@ -121,11 +121,14 @@ describe('SubagentTaskCard', () => {// The card has no other signal for a run the core aborted (the aborted task// never reports) or one that already ended: the cancel answer must settle it,// or the spinner and a dead Cancel button stay forever.- it.each([true, false])(- 'settles the card from the core cancel answer (cancelled=%s)',- async cancelled => {+ it.each([+ { cancelled: true, outcome: undefined },+ { cancelled: false, outcome: 'failed' as const },+ ])(+ 'settles the card from the core cancel answer (cancelled=$cancelled)',+ async ({ cancelled, outcome }) => {dispatch.mockClear();- cancel.mockResolvedValueOnce({ cancelled, taskId: 'sub-1' });+ cancel.mockResolvedValueOnce({ cancelled, taskId: 'sub-1', outcome });render(<SubagentTaskCardtype="tool-call"@@ -144,7 +147,7 @@ describe('SubagentTaskCard', () => {fireEvent.click(screen.getByTestId('subagent-cancel-task'));await waitFor(() =>expect(dispatch).toHaveBeenCalledWith(- subagentCancelResolved({ taskId: 'sub-1', cancelled })+ subagentCancelResolved({ taskId: 'sub-1', cancelled, outcome })));expect(cancel).toHaveBeenCalledWith('sub-1');diff --git a/app/src/features/conversations/aui/SubagentTaskCard.tsx b/app/src/features/conversations/aui/SubagentTaskCard.tsxindex 748049c985..dd33abc0d9 100644--- a/app/src/features/conversations/aui/SubagentTaskCard.tsx+++ b/app/src/features/conversations/aui/SubagentTaskCard.tsx@@ -164,8 +164,8 @@ function CancelTaskAction({ taskId }: { taskId: string }) {// The core's answer is the only signal this card gets for a run it just// aborted or that already ended, so settle on it rather than waiting for// a `subagent_failed` that may never come.- .then(({ cancelled }) => {- dispatch(subagentCancelResolved({ taskId, cancelled }));+ .then(({ cancelled, outcome }) => {+ dispatch(subagentCancelResolved({ taskId, cancelled, outcome }));}).catch(() => {setFailed(true);diff --git a/app/src/services/api/subagentApi.ts b/app/src/services/api/subagentApi.tsindex 993f3d178a..05e29c301b 100644--- a/app/src/services/api/subagentApi.ts+++ b/app/src/services/api/subagentApi.ts@@ -13,11 +13,19 @@ import { callCoreRpc } from '../coreRpcClient';const log = debug('subagentApi');+/**+ * How a run had ended when a cancel found nothing to abort: `completed` /+ * `failed` if the core still knew it, `unknown` if it no longer does.+ */+export type SubagentCancelOutcome = 'completed' | 'failed' | 'unknown';+/** Result of a cancel request. Mirrors the Rust handler payload. */-interface SubagentCancelResult {+export interface SubagentCancelResult {/** True if a running sub-agent was aborted; false if it was already done/unknown. */cancelled: boolean;taskId: string;+ /** Present when `cancelled` is false. */+ outcome?: SubagentCancelOutcome;}export const subagentApi = {diff --git a/app/src/store/__tests__/chatRuntimeSlice.test.ts b/app/src/store/__tests__/chatRuntimeSlice.test.tsindex 5efa82db8c..582c4603dc 100644--- a/app/src/store/__tests__/chatRuntimeSlice.test.ts+++ b/app/src/store/__tests__/chatRuntimeSlice.test.ts@@ -21,6 +21,7 @@ import reducer, {setPendingApprovalForThread,setStreamingAssistantForThread,setToolTimelineForThread,+ setTurnTimelinesForThread,streamDeltaReceived,subagentAwaitingUser,subagentCancelResolved,@@ -1460,19 +1461,52 @@ describe('subagent event reducers (Phase 3)', () => {const aborted = reducer(spawn(), subagentCancelResolved({ taskId: 'task-1', cancelled: true }));expect(aborted.toolTimelineByThread['t1'][0].status).toBe('cancelled');- // Not running any more (finished, terminal event missed): stop spinning.- const gone = reducer(spawn(), subagentCancelResolved({ taskId: 'task-1', cancelled: false }));- expect(gone.toolTimelineByThread['t1'][0].status).toBe('success');+ // 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');// Another task's answer leaves this row alone.const other = reducer(spawn(), subagentCancelResolved({ taskId: 'task-2', cancelled: true }));expect(other.toolTimelineByThread['t1'][0].status).toBe('running');});+ it('subagentCancelResolved also settles a row restored into a past-turn timeline', () => {+ const restored = reducer(+ undefined,+ setTurnTimelinesForThread({+ threadId: 't1',+ timelines: {+ 'req-old': [+ {+ id: 't1:subagent:task-1:researcher',+ name: 'subagent:researcher',+ round: 0,+ seq: 0,+ status: 'running',+ subagent: { taskId: 'task-1', agentId: 'researcher', toolCalls: [] },+ },+ ],+ },+ })+ );+ const state = reducer(restored, subagentCancelResolved({ taskId: 'task-1', cancelled: true }));+ expect(state.turnTimelinesByThread['t1']['req-old'][0].status).toBe('cancelled');+ });+it('subagentCancelResolved never rewrites a row that already settled', () => {const row = 't1:subagent:task-1:researcher';let state = reducer(spawn(), subagentDone({ threadId: 't1', rowId: row, success: false }));- state = reducer(state, subagentCancelResolved({ taskId: 'task-1', cancelled: false }));+ state = reducer(+ state,+ subagentCancelResolved({ taskId: 'task-1', cancelled: false, outcome: 'completed' })+ );expect(state.toolTimelineByThread['t1'][0].status).toBe('error');});diff --git a/app/src/store/chatRuntimeSlice.ts b/app/src/store/chatRuntimeSlice.tsindex 596e2c81ba..2d24226d9a 100644--- a/app/src/store/chatRuntimeSlice.ts+++ b/app/src/store/chatRuntimeSlice.ts@@ -1969,27 +1969,43 @@ const chatRuntimeSlice = createSlice({* Settle a delegation card from the core's answer to "Cancel task".** `cancelled: true` — the run was aborted. `cancelled: false` — nothing is- * running under that id any more (it already finished, or the core no- * longer knows it), so the card must stop spinning: its outcome, if any,- * was already delivered into the chat as a follow-up turn. Without this a- * card whose terminal event was missed kept a live spinner and a Cancel- * button that answered "not running" forever. Matched by task id across- * every thread, live and settled, because the card knows no row id.+ * running under that id any more, and `outcome` says how it had ended:+ * `completed` / `failed` as the core recorded it, or `unknown` when the+ * core no longer knows the task. Unknown settles as `cancelled` — the user+ * asked to stop it and nothing is running — never as a success it cannot+ * vouch for. Without this a card whose terminal event was missed kept a+ * live spinner and a Cancel button that answered "not running" forever.+ * Matched by task id across every thread — live, settled, and restored+ * past-turn timelines — because the card knows no row id.*/subagentCancelResolved: (state,- action: PayloadAction<{ taskId: string; cancelled: boolean }>+ action: PayloadAction<{+ taskId: string;+ cancelled: boolean;+ outcome?: 'completed' | 'failed' | 'unknown';+ }>) => {- const { taskId, cancelled } = action.payload;+ const { taskId, cancelled, outcome } = action.payload;+ const status: ToolTimelineEntryStatus = cancelled+ ? 'cancelled'+ : outcome === 'completed'+ ? 'success'+ : outcome === 'failed'+ ? 'error'+ : 'cancelled';+ const matches = (e: ToolTimelineEntry) =>+ e.subagent?.taskId === taskId && isActiveTimelineStatus(e.status);for (const threadId of Object.keys(state.toolTimelineByThread).concat(Object.keys(state.settledTurnsByThread))) {- for (const entry of subagentRows(- state,- threadId,- e => e.subagent?.taskId === taskId && isActiveTimelineStatus(e.status)- )) {- entry.status = cancelled ? 'cancelled' : 'success';+ for (const entry of subagentRows(state, threadId, matches)) {+ entry.status = status;+ }+ }+ for (const timelines of Object.values(state.turnTimelinesByThread)) {+ for (const entry of Object.values(timelines).flat().filter(matches)) {+ entry.status = status;}}},diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents.rsindex 3a7d745dad..fd67c68fea 100644--- a/crates/openhuman-core/src/agent/orchestration/running_subagents.rs+++ b/crates/openhuman-core/src/agent/orchestration/running_subagents.rs@@ -65,6 +65,7 @@ mod tests;pub(crate) use cancel::prune;pub(crate) use cancel::{cancel_all, cancel_by_session_in_workspace, cancel_by_task, cancel_for_thread, stop_for_thread,+ CancelledSubagent,};pub(crate) use registry::{register, status_channel, SubagentResumeRef, SubagentStatus};pub(crate) use resolve::{resume_ref_for_task_in_workspace, task_id_for_session_in_workspace};diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents/cancel.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents/cancel.rsindex 32486d5f18..245297eebb 100644--- a/crates/openhuman-core/src/agent/orchestration/running_subagents/cancel.rs+++ b/crates/openhuman-core/src/agent/orchestration/running_subagents/cancel.rs@@ -21,11 +21,28 @@ pub(crate) struct CancelledSubagent {pub(crate) subagent_session_id: Option<String>,pub(crate) workspace_dir: PathBuf,pub(crate) parent_thread_id: Option<String>,- /// The run had already completed or failed before the cancel arrived. A+ /// How the run had already ended when the cancel arrived, if it had. A/// finished entry stays registered until `sweep_terminal`, so a late- /// "Cancel" still finds it; the caller must not rewrite its outcome as a- /// user cancellation.- pub(crate) already_finished: bool,+ /// "Cancel" still finds it; the caller must not rewrite that outcome as a+ /// user cancellation, and reports it instead.+ pub(crate) already_finished: Option<FinishedOutcome>,+}++/// The terminal outcome of a run that finished before its cancel arrived.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum FinishedOutcome {+ Completed,+ Failed,+}++impl FinishedOutcome {+ /// Wire name in the `subagent_cancel` answer (`outcome`).+ pub(crate) fn as_str(self) -> &'static str {+ match self {+ Self::Completed => "completed",+ Self::Failed => "failed",+ }+ }}/// Abort and drop the sub-agent with `task_id`, returning its metadata so the@@ -37,12 +54,14 @@ pub(crate) struct CancelledSubagent {/// affordance, and the desktop user owns every sub-agent in their own core.pub(crate) fn cancel_by_task(task_id: &str) -> Option<CancelledSubagent> {let cancelled = registry().cancel_trusted(&TaskId::new(task_id)).ok()?;- let already_finished = matches!(- cancelled.status,- SubagentStatus::Completed { .. } | SubagentStatus::Failed { .. }- );+ // `AwaitingUser` is paused, not finished: cancelling it is a real cancel.+ let already_finished = match cancelled.status {+ SubagentStatus::Completed { .. } => Some(FinishedOutcome::Completed),+ SubagentStatus::Failed { .. } => Some(FinishedOutcome::Failed),+ SubagentStatus::Running | SubagentStatus::AwaitingUser { .. } => None,+ };let metadata = cancelled.metadata;- if !already_finished {+ if already_finished.is_none() {record_cancelled(&metadata.workspace_dir, task_id);}log::debug!(diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents_tests.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents_tests.rsindex 1a46d144d6..badfefaf99 100644--- a/crates/openhuman-core/src/agent/orchestration/running_subagents_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/running_subagents_tests.rs@@ -1,3 +1,4 @@+use super::cancel::FinishedOutcome;use super::*;use crate::agent::orchestration::fleet_tools::FleetToolSet;use crate::agent::orchestration::running_subagents::registry::DETACHED_LEDGER_TIMEOUT_MS;@@ -541,7 +542,10 @@ async fn cancel_by_task_returns_metadata_and_removes_entry() {shared_steering_registry().register(task_id.clone(), SteeringHandle::allow_all());let meta = cancel_by_task("task-cbt").expect("known task should cancel");- assert!(!meta.already_finished, "a running task is a real cancel");+ assert_eq!(+ meta.already_finished, None,+ "a running task is a real cancel"+ );assert_eq!(meta.agent_id, "researcher");assert_eq!(meta.parent_session, "session-Z");assert_eq!(meta.parent_thread_id.as_deref(), Some("thread-cbt"));@@ -574,21 +578,21 @@ async fn cancel_by_task_flags_a_run_that_already_finished() {output: "ok".into(),iterations: 6,},- true,+ Some(FinishedOutcome::Completed),),("task-cbt-failed",SubagentStatus::Failed {error: "boom".into(),},- true,+ Some(FinishedOutcome::Failed),),("task-cbt-paused",SubagentStatus::AwaitingUser {question: "which?".into(),},- false,+ None,),];for (task_id, status, finished) in cases {diff --git a/crates/openhuman-core/src/agent/orchestration/subagent_control.rs b/crates/openhuman-core/src/agent/orchestration/subagent_control.rsindex ae2cc100dc..544f10afc8 100644--- a/crates/openhuman-core/src/agent/orchestration/subagent_control.rs+++ b/crates/openhuman-core/src/agent/orchestration/subagent_control.rs@@ -16,7 +16,7 @@use serde_json::{json, Map, Value};-use crate::agent::orchestration::running_subagents::SteerError;+use crate::agent::orchestration::running_subagents::{CancelledSubagent, SteerError};use crate::agent::orchestration::{background_completions, running_subagents, subagent_sessions};use crate::core::all::{ControllerFuture, RegisteredController};use crate::core::{ControllerSchema, FieldSchema, TypeSchema};@@ -63,7 +63,9 @@ fn schema_for(function: &str) -> ControllerSchema {],outputs: vec![json_output("result",- "{ cancelled: bool, taskId: string } — cancelled=false if nothing was running.",+ "{ cancelled: bool, taskId: string, outcome?: \"completed\" | \"failed\" | \"unknown\" } \+ — cancelled=false if nothing was running; outcome then says how the run had \+ ended, or \"unknown\" if the core no longer knows the task.",)],},"subagent_steer" => ControllerSchema {@@ -108,18 +110,25 @@ fn handle_subagent_cancel(params: Map<String, Value>) -> ControllerFuture {"[subagent_control_rpc][{cid}] cancel.entry task_id={task_id}");- let cancelled = match running_subagents::cancel_by_task(&task_id) {+ // `outcome` is set only when nothing was cancelled: how the run ended+ // if the registry still knew it, else "unknown" (never registered, or+ // already swept). The card settles on it instead of assuming success.+ let (cancelled, outcome) = match running_subagents::cancel_by_task(&task_id) {// Finished before the click landed (it stays registered until the// terminal sweep). Its outcome is already recorded and delivered;// announcing a cancellation would overwrite a completed session// with "cancelled by user" and post a false notice into the chat.- Some(meta) if meta.already_finished => {+ Some(CancelledSubagent {+ already_finished: Some(finished),+ agent_id,+ ..+ }) => {log::debug!(target: "subagent_control_rpc",- "[subagent_control_rpc][{cid}] cancel.already_finished task_id={task_id} agent_id={}",- meta.agent_id+ "[subagent_control_rpc][{cid}] cancel.already_finished task_id={task_id} agent_id={agent_id} outcome={}",+ finished.as_str());- false+ (false, Some(finished.as_str()))}Some(meta) => {let summary = match reason.as_deref().map(str::trim).filter(|r| !r.is_empty()) {@@ -154,16 +163,20 @@ fn handle_subagent_cancel(params: Map<String, Value>) -> ControllerFuture {);}}- true+ (true, None)}- None => false,+ None => (false, Some("unknown")),};log::debug!(target: "subagent_control_rpc",- "[subagent_control_rpc][{cid}] cancel.done task_id={task_id} cancelled={cancelled}"+ "[subagent_control_rpc][{cid}] cancel.done task_id={task_id} cancelled={cancelled} outcome={outcome:?}");- to_json(json!({ "cancelled": cancelled, "taskId": task_id }))+ let mut reply = json!({ "cancelled": cancelled, "taskId": task_id });+ if let Some(outcome) = outcome {+ reply["outcome"] = json!(outcome);+ }+ to_json(reply)})}diff --git a/crates/openhuman-core/src/agent/orchestration/subagent_control_tests.rs b/crates/openhuman-core/src/agent/orchestration/subagent_control_tests.rsindex abc3e8f114..cb13fa1196 100644--- a/crates/openhuman-core/src/agent/orchestration/subagent_control_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/subagent_control_tests.rs@@ -40,6 +40,77 @@ async fn cancel_unknown_task_is_a_noop_false() {.or_else(|| out.get("cancelled")).and_then(Value::as_bool);assert_eq!(cancelled, Some(false));+ // Nothing known about the task: the card must not claim it succeeded.+ assert_eq!(field(&out, "outcome"), Some(json!("unknown")));+}++fn field(out: &Value, name: &str) -> Option<Value> {+ out.get("data")+ .and_then(|d| d.get(name))+ .or_else(|| out.get(name))+ .cloned()+}++/// A late Cancel on a run that already finished answers with how it ended and+/// leaves its durable session alone, instead of rewriting it as "cancelled by+/// user". A failed run must come back `failed`, never as a success.+#[tokio::test]+async fn cancel_of_a_finished_run_reports_its_outcome_and_rewrites_nothing() {+ use crate::agent::orchestration::running_subagents::{+ register, status_channel, SubagentStatus,+ };+ use crate::agent::orchestration::subagent_sessions::SubagentSessionStore;+ use std::sync::Arc;+ use tinyagents_harness::run_queue::RunQueue;++ let _lock = crate::config::TEST_ENV_LOCK+ .lock()+ .unwrap_or_else(|e| e.into_inner());+ let workspace = tempfile::tempdir().expect("tempdir");+ for (task_id, status, outcome) in [+ (+ "sub-rpc-done",+ SubagentStatus::Completed {+ output: "ok".into(),+ iterations: 1,+ },+ "completed",+ ),+ (+ "sub-rpc-failed",+ SubagentStatus::Failed {+ error: "boom".into(),+ },+ "failed",+ ),+ ] {+ let (tx, rx) = status_channel();+ register(+ task_id.into(),+ "agent_memory".into(),+ "session-rpc".into(),+ None,+ Some(format!("subsess-{task_id}")),+ workspace.path().to_path_buf(),+ Some("thread-rpc".into()),+ Arc::new(RunQueue::new()),+ tokio::spawn(async {}).abort_handle(),+ rx,+ );+ tx.send(status).expect("status channel open");++ let mut params = Map::new();+ params.insert("taskId".into(), json!(task_id));+ let out = handle_subagent_cancel(params).await.expect("handler ok");+ 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(),+ "a finished run's session must not be rewritten as cancelled"+ );}#[tokio::test]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 763f8cad0c..b47870dee5 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@@ -14,10 +14,13 @@//!//! [`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`. `try_send` because-//! `Drop` cannot await; a full or closed channel only loses the UI update,-//! which is what already happened before this guard existed.+//! still armed, `Drop` sends the missing `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+//! settle anything, so that case is logged and dropped.+use tokio::sync::mpsc::error::TrySendError;use tokio::sync::mpsc::Sender;use crate::agent::progress::AgentProgress;@@ -77,11 +80,34 @@ impl Drop for AbortReport {self.task_id,self.agent_id),- Err(err) => log::warn!(- "[subagent_abort_report] could not report aborted sub-agent task_id={} agent_id={} error={}",+ Err(TrySendError::Full(event)) => {+ let Ok(runtime) = tokio::runtime::Handle::try_current() else {+ log::warn!(+ "[subagent_abort_report] channel full and no runtime to wait on task_id={} agent_id={}",+ self.task_id,+ self.agent_id+ );+ return;+ };+ log::info!(+ "[subagent_abort_report] channel full; deferring report task_id={} agent_id={}",+ self.task_id,+ self.agent_id+ );+ let tx = tx.clone();+ let task_id = self.task_id.clone();+ runtime.spawn(async move {+ if tx.send(event).await.is_err() {+ log::warn!(+ "[subagent_abort_report] deferred report lost: channel closed task_id={task_id}"+ );+ }+ });+ }+ Err(TrySendError::Closed(_)) => log::warn!(+ "[subagent_abort_report] could not report aborted sub-agent: channel closed task_id={} agent_id={}",self.task_id,- self.agent_id,- err+ self.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 9f0f667b40..5cc796e93a 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@@ -54,3 +54,31 @@ async fn a_disarmed_guard_sends_nothing() {fn no_sink_is_a_no_op() {drop(AbortReport::arm(None, "help", "sub-3"));}++/// A busy parent can have the progress channel full at the moment of the+/// abort. The report is the only thing that settles the card, so it must wait+/// for room rather than be dropped.+#[tokio::test]+async fn a_full_channel_still_delivers_the_report_once_there_is_room() {+ let (tx, mut rx) = tokio::sync::mpsc::channel(1);+ tx.send(AgentProgress::TurnStarted)+ .await+ .expect("fill the channel");++ drop(AbortReport::arm(Some(tx), "help", "sub-full"));++ // Drain the event that was filling the channel; the deferred report follows.+ assert!(matches!(rx.recv().await, Some(AgentProgress::TurnStarted)));+ let event = tokio::time::timeout(std::time::Duration::from_secs(5), rx.recv())+ .await+ .expect("deferred report arrives")+ .expect("channel still open");+ assert_eq!(+ failed(event),+ (+ "help".to_string(),+ "sub-full".to_string(),+ ABORTED_ERROR.to_string()+ )+ );+}