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): settle the delegation card when a background sub-agent is cancelled
M3gA-Mind2310e803d9f7
diff --git a/app/src/features/conversations/aui/SubagentTaskCard.test.tsx b/app/src/features/conversations/aui/SubagentTaskCard.test.tsxindex 08faabf971..4b473a4ef4 100644--- a/app/src/features/conversations/aui/SubagentTaskCard.test.tsx+++ b/app/src/features/conversations/aui/SubagentTaskCard.test.tsx@@ -1,7 +1,7 @@-import { fireEvent, render, screen } from '@testing-library/react';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';import { describe, expect, it, vi } from 'vitest';-import type { SubagentActivity } from '../../../store/chatRuntimeSlice';+import { type SubagentActivity, subagentCancelResolved } from '../../../store/chatRuntimeSlice';import { SubagentTaskCard } from './SubagentTaskCard';// The nested transcript's MessagePrimitive needs a ThreadPrimitive.Viewport.@@ -16,6 +16,12 @@ vi.mock('@assistant-ui/react', async importActual => ({useAui: () => ({ thread: { append } }),}));+const dispatch = vi.hoisted(() => vi.fn());+vi.mock('../../../store/hooks', () => ({ useAppDispatch: () => dispatch }));++const cancel = vi.hoisted(() => vi.fn());+vi.mock('../../../services/api/subagentApi', () => ({ subagentApi: { cancel } }));+const activity: SubagentActivity = {taskId: 'sub-1',agentId: 'researcher',@@ -111,4 +117,37 @@ describe('SubagentTaskCard', () => {});expect(screen.getByTestId('subagent-answer-sent')).toBeInTheDocument();});++ // 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 => {+ dispatch.mockClear();+ cancel.mockResolvedValueOnce({ cancelled, taskId: 'sub-1' });+ render(+ <SubagentTaskCard+ type="tool-call"+ toolName="task"+ toolCallId="sub-1"+ args={{ progress: activity } as never}+ argsText="{}"+ result={undefined}+ status={{ type: 'running' }}+ addResult={() => {}}+ resume={() => {}}+ respondToApproval={async () => {}}+ />+ );++ fireEvent.click(screen.getByTestId('subagent-cancel-task'));+ await waitFor(() =>+ expect(dispatch).toHaveBeenCalledWith(+ subagentCancelResolved({ taskId: 'sub-1', cancelled })+ )+ );+ expect(cancel).toHaveBeenCalledWith('sub-1');+ }+ );});diff --git a/app/src/features/conversations/aui/SubagentTaskCard.tsx b/app/src/features/conversations/aui/SubagentTaskCard.tsxindex c151e4e714..748049c985 100644--- a/app/src/features/conversations/aui/SubagentTaskCard.tsx+++ b/app/src/features/conversations/aui/SubagentTaskCard.tsx@@ -32,7 +32,8 @@ import WorktreeActions from '../../../components/worktree/WorktreeActions';import { useT } from '../../../lib/i18n/I18nContext';import { subagentMessages } from '../../../providers/assistantUiMessages';import { subagentApi } from '../../../services/api/subagentApi';-import type { SubagentActivity } from '../../../store/chatRuntimeSlice';+import { type SubagentActivity, subagentCancelResolved } from '../../../store/chatRuntimeSlice';+import { useAppDispatch } from '../../../store/hooks';import { basename } from '../../../utils/pathUtils';function asSubagentActivity(value: unknown): SubagentActivity | undefined {@@ -151,6 +152,7 @@ function AwaitingUserActions({ activity }: { activity: SubagentActivity }) {*/function CancelTaskAction({ taskId }: { taskId: string }) {const { t } = useT();+ const dispatch = useAppDispatch();const [cancelling, setCancelling] = useState(false);const [failed, setFailed] = useState(false);@@ -159,13 +161,19 @@ function CancelTaskAction({ taskId }: { taskId: string }) {setCancelling(true);void subagentApi.cancel(taskId)+ // 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 }));+ }).catch(() => {setFailed(true);}).finally(() => {setCancelling(false);});- }, [taskId]);+ }, [dispatch, taskId]);return (<div className="flex flex-col gap-1">diff --git a/app/src/store/__tests__/chatRuntimeSlice.test.ts b/app/src/store/__tests__/chatRuntimeSlice.test.tsindex 6007a3d259..5efa82db8c 100644--- a/app/src/store/__tests__/chatRuntimeSlice.test.ts+++ b/app/src/store/__tests__/chatRuntimeSlice.test.ts@@ -23,6 +23,7 @@ import reducer, {setToolTimelineForThread,streamDeltaReceived,subagentAwaitingUser,+ subagentCancelResolved,subagentDone,subagentIterationStarted,subagentSpawned,@@ -1454,6 +1455,27 @@ describe('subagent event reducers (Phase 3)', () => {expect(again.toolTimelineByThread['t1'][0].status).toBe('success');});+ 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');++ // 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');++ // 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 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 }));+ expect(state.toolTimelineByThread['t1'][0].status).toBe('error');+ });+it('subagentSpawned is idempotent — a redelivered event does not duplicate the row', () => {let state = spawn();const before = state.toolTimelineByThread['t1'].length;diff --git a/app/src/store/chatRuntimeSlice.ts b/app/src/store/chatRuntimeSlice.tsindex e292a61208..596e2c81ba 100644--- a/app/src/store/chatRuntimeSlice.ts+++ b/app/src/store/chatRuntimeSlice.ts@@ -1965,6 +1965,34 @@ const chatRuntimeSlice = createSlice({if (isDirty !== undefined) s.isDirty = isDirty;}},+ /**+ * 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.+ */+ subagentCancelResolved: (+ state,+ action: PayloadAction<{ taskId: string; cancelled: boolean }>+ ) => {+ const { taskId, cancelled } = action.payload;+ 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';+ }+ }+ },subagentIterationStarted: (state,action: PayloadAction<{@@ -2850,6 +2878,7 @@ export const {streamDeltaReceived,subagentAwaitingUser,subagentDone,+ subagentCancelResolved,subagentIterationStarted,subagentSpawned,subagentToolCallReceived,diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents/cancel.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents/cancel.rsindex c127ca83a6..32486d5f18 100644--- a/crates/openhuman-core/src/agent/orchestration/running_subagents/cancel.rs+++ b/crates/openhuman-core/src/agent/orchestration/running_subagents/cancel.rs@@ -7,7 +7,7 @@ use std::path::{Path, PathBuf};use tinyagents_harness::ids::TaskId;-use super::registry::registry;+use super::registry::{registry, SubagentStatus};use super::resolve::{task_id_for_session, task_id_for_session_in_workspace};use super::task_ledger::record_cancelled;@@ -21,6 +21,11 @@ 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+ /// 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,}/// Abort and drop the sub-agent with `task_id`, returning its metadata so the@@ -32,8 +37,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 { .. }+ );let metadata = cancelled.metadata;- record_cancelled(&metadata.workspace_dir, task_id);+ if !already_finished {+ record_cancelled(&metadata.workspace_dir, task_id);+ }log::debug!("[running_subagents] cancel_by_task task_id={} agent_id={} parent_thread_id={:?} live_entries={}",task_id,@@ -49,6 +60,7 @@ pub(crate) fn cancel_by_task(task_id: &str) -> Option<CancelledSubagent> {subagent_session_id: metadata.subagent_session_id,workspace_dir: metadata.workspace_dir,parent_thread_id: metadata.parent_thread_id,+ already_finished,})}diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents_tests.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents_tests.rsindex 2de5a5f64b..1a46d144d6 100644--- a/crates/openhuman-core/src/agent/orchestration/running_subagents_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/running_subagents_tests.rs@@ -541,6 +541,7 @@ 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.agent_id, "researcher");assert_eq!(meta.parent_session, "session-Z");assert_eq!(meta.parent_thread_id.as_deref(), Some("thread-cbt"));@@ -559,6 +560,45 @@ async fn cancel_by_task_returns_metadata_and_removes_entry() {assert!(cancel_by_task("never-existed").is_none());}+/// A finished run stays registered until the terminal sweep, so a late+/// "Cancel" still finds it. It must come back flagged, so the RPC does not+/// rewrite a completed session as "cancelled by user" — while a run paused on+/// the user is still a real cancel.+#[tokio::test]+async fn cancel_by_task_flags_a_run_that_already_finished() {+ let _guard = test_guard();+ let cases = [+ (+ "task-cbt-done",+ SubagentStatus::Completed {+ output: "ok".into(),+ iterations: 6,+ },+ true,+ ),+ (+ "task-cbt-failed",+ SubagentStatus::Failed {+ error: "boom".into(),+ },+ true,+ ),+ (+ "task-cbt-paused",+ SubagentStatus::AwaitingUser {+ question: "which?".into(),+ },+ false,+ ),+ ];+ for (task_id, status, finished) in cases {+ let tx = register_test(task_id, "session-F", run_queue());+ tx.send(status).expect("status channel open");+ let meta = cancel_by_task(task_id).expect("registered task is found");+ assert_eq!(meta.already_finished, finished, "{task_id}");+ }+}+#[tokio::test]async fn cancel_all_clears_everything() {let _guard = test_guard();diff --git a/crates/openhuman-core/src/agent/orchestration/subagent_control.rs b/crates/openhuman-core/src/agent/orchestration/subagent_control.rsindex f76d2ffd68..ae2cc100dc 100644--- a/crates/openhuman-core/src/agent/orchestration/subagent_control.rs+++ b/crates/openhuman-core/src/agent/orchestration/subagent_control.rs@@ -109,6 +109,18 @@ fn handle_subagent_cancel(params: Map<String, Value>) -> ControllerFuture {);let cancelled = 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 => {+ log::debug!(+ target: "subagent_control_rpc",+ "[subagent_control_rpc][{cid}] cancel.already_finished task_id={task_id} agent_id={}",+ meta.agent_id+ );+ false+ }Some(meta) => {let summary = match reason.as_deref().map(str::trim).filter(|r| !r.is_empty()) {Some(r) => format!(diff --git a/crates/openhuman-core/src/agent/orchestration/tools.rs b/crates/openhuman-core/src/agent/orchestration/tools.rsindex a5cad62ba5..b3b7942796 100644--- a/crates/openhuman-core/src/agent/orchestration/tools.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools.rs@@ -48,6 +48,8 @@ mod spawn_subagent;pub mod spawn_worker_thread;#[path = "tools/steer_subagent.rs"]mod steer_subagent;+#[path = "tools/subagent_abort_report.rs"]+mod subagent_abort_report;#[cfg(test)]#[path = "tools/tools_e2e_tests.rs"]mod tools_e2e_tests;diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent.rsindex 6a05bcfa79..45e74bd4d6 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent.rs@@ -4,6 +4,7 @@//! accepted. Completion/failure is reported through normal sub-agent lifecycle//! events and, when possible, persisted in the child worker thread.+use super::subagent_abort_report::AbortReport;use crate::agent::harness::definition::AgentDefinitionRegistry;use crate::agent::messages::ChatMessage;use crate::agent::orchestration::fleet_tools::FleetToolSet;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 d099e9e17f..3867e7704f 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@@ -417,13 +417,13 @@ impl SpawnAsyncSubagentTool {register_parent_thread_id.as_deref().unwrap_or("none"));let background_prompt = add_background_contract(&prompt);- // The detached child starts on a fresh task. Its explicit carrier keeps- // authority, origin, thread, and workspace while deliberately dropping- // the originating turn's accounting, dispatch refusal, and cancellation.- // Approval/origin and workspace policy remain task-local until B2h- // moves the security boundary onto this carrier, so propagation below- // is a staging bridge for those two scopes only.+ // The detached child starts on a fresh task. Its explicit carrier keeps authority, origin,+ // thread, and workspace while deliberately dropping the originating turn's accounting,+ // dispatch refusal, and cancellation. Approval/origin and workspace policy remain+ // task-local until B2h moves the security boundary onto this carrier, so propagation+ // below is a staging bridge for those two scopes only.let detached_run_context = detached_parent.data.child();+ let mut abort_report = AbortReport::arm(progress_sink.clone(), &definition.id, &task_id);let join = tokio::spawn(crate::agent::turn_origin::propagate(crate::agent::turn_workspace::propagate(async move {let options = SubagentRunOptions {@@ -449,7 +449,7 @@ impl SpawnAsyncSubagentTool {options,).await;-+ abort_report.disarm();match result {Ok(outcome) => {let emit_lifecycle_effects = outcome.should_emit_lifecycle_effects();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.rsnew file mode 100644index 0000000000..763f8cad0c--- /dev/null+++ b/crates/openhuman-core/src/agent/orchestration/tools/subagent_abort_report.rs@@ -0,0 +1,92 @@+//! Report a detached sub-agent that was aborted before it could report itself.+//!+//! A background sub-agent (`spawn_async_subagent`) sends its own terminal+//! `SubagentCompleted` / `SubagentFailed` on the parent's progress channel, and+//! that one event settles everything downstream: the web bridge emits+//! `subagent_failed` to the chat card, the turn-state mirror marks the saved+//! `subagent:*` row, and the run ledger records the end.+//!+//! Cancelling it does not go through that path. `DetachedTaskRegistry`'s+//! `take_and_cancel` (Cancel, Stop, thread delete) aborts the tokio task, so+//! the future is dropped at its current `.await` and never reaches its own+//! `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`. `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.++use tokio::sync::mpsc::Sender;++use crate::agent::progress::AgentProgress;++/// Error text carried by the synthesised `SubagentFailed`.+pub(crate) const ABORTED_ERROR: &str = "sub-agent was cancelled";++/// Sends `SubagentFailed` for `task_id` if dropped while armed.+pub(crate) struct AbortReport {+ progress: Option<Sender<AgentProgress>>,+ agent_id: String,+ task_id: String,+ armed: bool,+}++impl AbortReport {+ pub(crate) fn arm(+ progress: Option<Sender<AgentProgress>>,+ agent_id: &str,+ task_id: &str,+ ) -> Self {+ Self {+ progress,+ agent_id: agent_id.to_string(),+ task_id: task_id.to_string(),+ armed: true,+ }+ }++ /// The run returned; its own branches report the outcome from here on.+ pub(crate) fn disarm(&mut self) {+ self.armed = false;+ }+}++impl Drop for AbortReport {+ fn drop(&mut self) {+ if !self.armed {+ return;+ }+ let Some(tx) = self.progress.as_ref() else {+ log::debug!(+ "[subagent_abort_report] aborted without a progress sink task_id={} agent_id={}",+ self.task_id,+ self.agent_id+ );+ return;+ };+ let event = 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={}",+ self.task_id,+ self.agent_id+ ),+ Err(err) => log::warn!(+ "[subagent_abort_report] could not report aborted sub-agent task_id={} agent_id={} error={}",+ self.task_id,+ self.agent_id,+ err+ ),+ }+ }+}++#[cfg(test)]+#[path = "subagent_abort_report_tests.rs"]+mod tests;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.rsnew file mode 100644index 0000000000..9f0f667b40--- /dev/null+++ b/crates/openhuman-core/src/agent/orchestration/tools/subagent_abort_report_tests.rs@@ -0,0 +1,56 @@+use super::*;++fn failed(event: AgentProgress) -> (String, String, String) {+ match event {+ AgentProgress::SubagentFailed {+ agent_id,+ task_id,+ error,+ } => (agent_id, task_id, error),+ other => panic!("expected SubagentFailed, got {other:?}"),+ }+}++/// The bug: an aborted background task is dropped mid-`.await`, so it never+/// reports. Aborting a real spawned task that holds an armed guard must still+/// deliver `SubagentFailed` on the parent's channel.+#[tokio::test]+async fn an_aborted_task_still_reports_failed() {+ let (tx, mut rx) = tokio::sync::mpsc::channel(4);+ let (started_tx, started_rx) = tokio::sync::oneshot::channel();+ let task = tokio::spawn(async move {+ let _report = AbortReport::arm(Some(tx), "agent_memory", "sub-1");+ let _ = started_tx.send(());+ std::future::pending::<()>().await;+ });+ started_rx.await.expect("task started");+ task.abort();+ let _ = task.await;++ let event = rx.recv().await.expect("an aborted task must report");+ assert_eq!(+ failed(event),+ (+ "agent_memory".to_string(),+ "sub-1".to_string(),+ ABORTED_ERROR.to_string()+ )+ );+}++/// A run that returned reports its own outcome; the guard must stay silent so+/// the card is not settled twice (or settled as failed after a success).+#[tokio::test]+async fn a_disarmed_guard_sends_nothing() {+ let (tx, mut rx) = tokio::sync::mpsc::channel(4);+ let mut report = AbortReport::arm(Some(tx), "help", "sub-2");+ report.disarm();+ drop(report);+ assert!(rx.recv().await.is_none(), "disarmed guard must not report");+}++/// No progress sink (a run with no chat attached) is a no-op, not a panic.+#[test]+fn no_sink_is_a_no_op() {+ drop(AbortReport::arm(None, "help", "sub-3"));+}