Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(background-completions): stop late completions from cancelled threads

Steven Enamakel1c1fb37f4df7
diff --git a/app/src/features/conversations/components/__tests__/WorkerThreadRefCard.test.tsx b/app/src/features/conversations/components/__tests__/WorkerThreadRefCard.test.tsx
index 419d44dd89..42e3a14190 100644
--- a/app/src/features/conversations/components/__tests__/WorkerThreadRefCard.test.tsx
+++ b/app/src/features/conversations/components/__tests__/WorkerThreadRefCard.test.tsx
@@ -1,11 +1,16 @@
import { fireEvent, render, screen } from '@testing-library/react';
import { Provider } from 'react-redux';
-import { describe, expect, it } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { threadApi } from '../../../../services/api/threadApi';
import { store } from '../../../../store';
import { clearThreadInferenceActive } from '../../../../store/threadSlice';
import { WorkerThreadRefCard } from '../WorkerThreadRefCard';
+vi.mock('../../../../services/api/threadApi', () => ({
+ threadApi: { getThreadMessages: vi.fn() },
+}));
+
// Issue #1624: the worker-thread surface card must render a live
// running/completed/failed badge derived from the parent timeline
// entry's status, so users scanning a parent transcript know whether
@@ -71,6 +76,10 @@ describe('WorkerThreadRefCard — status badge', () => {
});
describe('WorkerThreadRefCard — navigation', () => {
+ beforeEach(() => {
+ vi.mocked(threadApi.getThreadMessages).mockResolvedValue({ messages: [], count: 0 });
+ });
+
it('selects the worker thread without marking it as in-flight', () => {
store.dispatch(clearThreadInferenceActive(REF.threadId));
renderInStore(<WorkerThreadRefCard ref={REF} status="running" />);
diff --git a/app/src/services/chatService.ts b/app/src/services/chatService.ts
index e57eee1a1d..4857b2c931 100644
--- a/app/src/services/chatService.ts
+++ b/app/src/services/chatService.ts
@@ -1326,11 +1326,11 @@ export async function chatCancel(threadId: string): Promise<ChatCancelOutcome> {
}
try {
- const result = await callCoreRpc<{ request_id?: unknown }>({
+ const result = await callCoreRpc<{ result?: { request_id?: unknown } }>({
method: 'openhuman.channel_web_cancel',
params: { client_id: clientId, thread_id: threadId },
});
- const turnCancelled = typeof result?.request_id === 'string';
+ const turnCancelled = typeof result?.result?.request_id === 'string';
chatLog('chat_cancel: thread=%s turnCancelled=%s', threadId, turnCancelled);
return { accepted: true, turnCancelled };
} catch (error) {
diff --git a/crates/openhuman-core/src/agent/orchestration/background_completions.rs b/crates/openhuman-core/src/agent/orchestration/background_completions.rs
index 486a6e94af..e8debbf7f5 100644
--- a/crates/openhuman-core/src/agent/orchestration/background_completions.rs
+++ b/crates/openhuman-core/src/agent/orchestration/background_completions.rs
@@ -79,6 +79,12 @@ struct QueueState {
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>,
/// 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
@@ -103,6 +109,21 @@ impl QueueState {
}
}
+ 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);
+ }
+ }
+ }
+ }
+
+ fn resume(&mut self, thread_id: &str) {
+ self.stopped_threads.remove(thread_id);
+ }
+
/// 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) {
@@ -172,9 +193,9 @@ pub(crate) fn record_outcome(
.lock()
.expect("background_completions queue poisoned");
if let Some(thread_id) = entry.parent_thread_id.as_deref() {
- if state.cancelled_threads.contains(thread_id) {
+ if state.cancelled_threads.contains(thread_id) || state.stopped_threads.contains(thread_id) {
log::debug!(
- "[background_completions] dropping completion task_id={} for cancelled thread_id={}",
+ "[background_completions] dropping completion task_id={} for stopped/cancelled thread_id={}",
entry.task_id,
thread_id
);
@@ -320,6 +341,7 @@ 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);
log::debug!(
"[background_completions] discard_pending_for_thread thread_id={} removed={} sessions_left={}",
@@ -330,6 +352,15 @@ pub(crate) fn discard_pending_for_thread(thread_id: &str) -> usize {
removed
}
+/// Reopen a thread that was stopped by the user for work started by a later
+/// user request. Deleted-thread tombstones are deliberately not cleared.
+pub(crate) fn resume_for_thread(thread_id: &str) {
+ let mut state = queue()
+ .lock()
+ .expect("background_completions queue poisoned");
+ state.resume(thread_id);
+}
+
fn remove_pending_for_thread(state: &mut QueueState, thread_id: &str) -> usize {
let mut removed = 0;
for pending in state.pending.values_mut() {
diff --git a/crates/openhuman-core/src/agent/orchestration/background_completions_tests.rs b/crates/openhuman-core/src/agent/orchestration/background_completions_tests.rs
index 4af8da8db4..46bfc29162 100644
--- a/crates/openhuman-core/src/agent/orchestration/background_completions_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/background_completions_tests.rs
@@ -369,7 +369,7 @@ fn record_outcome_preserves_the_outcome_through_a_drain() {
}
#[test]
-fn discard_pending_for_thread_drops_queued_results_but_keeps_the_thread_live() {
+fn discard_pending_for_thread_blocks_late_results_until_the_next_turn() {
let _guard = test_guard();
record_completion(
"sess-stop",
@@ -391,12 +391,23 @@ fn discard_pending_for_thread_drops_queued_results_but_keeps_the_thread_live() {
assert_eq!(pending_count("sess-stop"), 1);
assert_eq!(take_pending("sess-stop")[0].task_id, "sub-stop-keep");
- // ...but, unlike thread deletion, does not tombstone the thread: work
- // started by a later turn on it still delivers.
+ // A late completion from the stopped generation loses the cooperative
+ // abort race and is rejected.
record_completion(
"sess-stop",
"sub-stop-later",
"researcher",
+ "late stopped result",
+ Some("thread-stop-live".into()),
+ );
+ assert_eq!(pending_count("sess-stop"), 0);
+
+ // A later user turn deliberately reopens the thread for new work.
+ resume_for_thread("thread-stop-live");
+ record_completion(
+ "sess-stop",
+ "sub-stop-new-turn",
+ "researcher",
"next turn's result",
Some("thread-stop-live".into()),
);
diff --git a/crates/openhuman-core/src/web_chat/ops/channel_ops.rs b/crates/openhuman-core/src/web_chat/ops/channel_ops.rs
index d44795f5a4..f9f034abdb 100644
--- a/crates/openhuman-core/src/web_chat/ops/channel_ops.rs
+++ b/crates/openhuman-core/src/web_chat/ops/channel_ops.rs
@@ -115,12 +115,15 @@ async fn cancel_chat_inner(
// first, then drop anything already queued for delivery, so no result lands
// in the gap. A scoped cancel names one turn and leaves the rest alone.
let subagents_cancelled = if request_id.is_none() {
- let stopped =
- crate::agent::orchestration::running_subagents::stop_for_thread(thread_id).len();
+ // Gate completion recording before aborting: Tokio abort is
+ // cooperative, so a child already finishing can otherwise enqueue in
+ // the gap between abort and the queue sweep.
let discarded =
crate::agent::orchestration::background_completions::discard_pending_for_thread(
thread_id,
);
+ let stopped =
+ crate::agent::orchestration::running_subagents::stop_for_thread(thread_id).len();
log::info!(
"[web-channel] stop thread_id={} turn={:?} parallel={} subagents_cancelled={} completions_discarded={}",
thread_id,
@@ -164,6 +167,9 @@ pub async fn channel_web_chat(
queue_mode: Option<String>,
metadata: ChatRequestMetadata,
) -> Result<RpcOutcome<Value>, String> {
+ // A Stop gate only suppresses completions from the halted generation. A
+ // later user request deliberately starts a new generation on this thread.
+ crate::agent::orchestration::background_completions::resume_for_thread(thread_id);
let result = start_chat(
client_id,
thread_id,