Skip to content

The agent that grows with you

fix(delegation): stopping a turn no longer kills background subagents

Teknium3ae67dc3d6fb
diff --git a/acp_adapter/server.py b/acp_adapter/server.py
index 0befc4ca49f..56b34bef423 100644
--- a/acp_adapter/server.py
+++ b/acp_adapter/server.py
@@ -653,11 +653,7 @@ class HermesACPAgent(SlashCommandsMixin, acp.Agent):
state.cancel_event.set()
try:
if state.agent:
- request_hard_interrupt(state.agent)
- # Background delegations are detached from the turn's fan-out; they end with the cancel.
- from tools.async_delegation import interrupt_for_session
- interrupt_for_session(parent_session_id=str(getattr(state.agent, "session_id", "") or ""),
- reason="acp_cancel")
+ request_hard_interrupt(state.agent) # this turn only: background delegations keep running
except Exception:
logger.debug("Failed to interrupt ACP session %s", session_id, exc_info=True)
logger.info("Cancelled session %s", session_id)
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index ea19e1ede2a..3dd8ef66f7a 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -896,14 +896,11 @@ class SessionAuthority:
self.pending_stops[ref.session_id] = generation
if agent is not None:
self.delivered_stops[ref.session_id] = generation
- # Main's Stop: hard-cancel (aborts compression too) and end the session's own background
- # delegations (spawned by this session only: a viewer must not kill other gateway work).
+ # Stop hard-cancels this turn (aborts compression too). Background delegations are not the
+ # turn: they keep running and report back; `/stop` and session close/reset end them.
from agent.interrupt_compat import request_hard_interrupt
- from tools.async_delegation import interrupt_for_session
if agent is not None:
request_hard_interrupt(agent)
- for parent in dict.fromkeys((ref.session_id, self.physical_target(ref))):
- interrupt_for_session(session_key=live.route, parent_session_id=parent, reason='user_stop')
return self._handle(ref)
def _classic_turn_holds(self, route):
diff --git a/tests/gateway/test_canonical_stop_hard_cancel.py b/tests/gateway/test_canonical_stop_hard_cancel.py
index 4a454783425..981358f7770 100644
--- a/tests/gateway/test_canonical_stop_hard_cancel.py
+++ b/tests/gateway/test_canonical_stop_hard_cancel.py
@@ -1,4 +1,5 @@
-"""Canonical Stop (Desktop, Ink, classic CLI view, ACP) is main's Stop: hard-cancel + end the session's delegations."""
+"""Canonical Stop (Desktop, Ink, classic CLI view, ACP) hard-cancels the turn and leaves background delegations
+running: a background subagent is independent of the chat that spawned it (Teknium ruling); `/stop` ends them."""
import asyncio
from unittest.mock import MagicMock
@@ -31,7 +32,7 @@ def _delegation(ad, monkeypatch, parent):
@pytest.mark.asyncio
@pytest.mark.parametrize('when', ['adopted', 'before_adoption'])
-async def test_canonical_stop_hard_cancels_and_ends_the_sessions_delegations(tmp_path, monkeypatch, when):
+async def test_canonical_stop_hard_cancels_the_turn_and_keeps_background_delegations(tmp_path, monkeypatch, when):
from gateway import session_finite
from tools import async_delegation as ad
@@ -58,5 +59,5 @@ async def test_canonical_stop_hard_cancels_and_ends_the_sessions_delegations(tmp
stopped.set()
await asyncio.wait_for(authority.sessions['s'].task, 5)
assert agent.stops == ['hard'], f'canonical Stop delivered {agent.stops}; main hard-cancels'
- assert own.called, "the session's background delegation kept running after Stop"
+ assert not own.called, "Stop of the turn ended the session's background delegation"
assert not foreign.called, "Stop ended another session's delegation"
diff --git a/tools/AGENTS.md b/tools/AGENTS.md
index 7aa9bd35cd6..3af6842bb27 100644
--- a/tools/AGENTS.md
+++ b/tools/AGENTS.md
@@ -167,10 +167,12 @@ processes are killed at its teardown and their notices are suppressed in the par
the result as `orphaned_processes`, exited-but-never-read notify processes as `unread_completions` (`_ChildRun.account_background_processes`, before `cleanup` kills them). **Child kernels:** a child's `execute_code` kernels are keyed `<parent-owner>::child::<child-session-id>`, pinned against the `max_session_kernels` LRU cap while the child runs and disposed by `cleanup` (`code_kernel.shutdown_kernels_for_delegated_child`) — never let a finished child's kernel squat the cap. **output_schema:** a miss after the one retry keeps `status: completed` with the raw text in `summary` plus `schema_valid: false` / `schema_errors` / `schema_note` — never discard a child's result. **Durability:** background
delegation is process-local; work that must survive restart uses `cronjob` or
`terminal(background=True, notify_on_complete=True)`. `heartbeat=N` on the same spawn emits a `heartbeat` event (type on the completion queue; delta output only, `HEARTBEAT_MIN_SECONDS` floor, one daemon timer thread for all sessions in `process_registry.py::ProcessRegistry._heartbeat_loop`) — every surface that renders `watch_match` must render `heartbeat` (`process_registry_notifications.py`, `gateway/run.py::_drain_gateway_watch_events`, `tui_gateway/session_notifications.py::_DEDUP_EXTRA_FIELDS`). **Stop fan-out:** a turn's hard interrupt reaches only
-`_active_children`; background units are detached at dispatch, so every stop surface (gateway `/stop` busy AND
-idle paths, TUI `session.interrupt`, ACP `cancel`, CLI `/stop` via `interrupt_all`) calls
-`async_delegation.interrupt_for_session` too. Depth>0 delegations are always synchronous
-(`_model_background_value`), so the stop recurses through the child's own `_active_children` fan-out; an
+`_active_children`; background units are detached at dispatch and survive it on purpose (Teknium ruling: a
+background subagent, `/review` included, is independent of the chat that spawned it). Turn stops — Ctrl+C,
+Esc, the Desktop/TUI Stop button, a message that interrupts, `session.interrupt`, ACP `cancel` — never call
+`async_delegation.interrupt_for_session`. Only the explicit `/stop` command (gateway busy AND idle paths, CLI
+and Desktop process stop) and session close/reset end them. Depth>0 delegations are always synchronous
+(`_model_background_value`), so a stop recurses through the child's own `_active_children` fan-out; an
interrupted entry's `summary` is the child's last real assistant text (`_build_result_entry`). API: `website/docs/developer-guide/subagent-lifecycle-api.md`.
## Tests
diff --git a/tui_gateway/session_lifecycle.py b/tui_gateway/session_lifecycle.py
index bc14a1e8ba3..32af14072b0 100644
--- a/tui_gateway/session_lifecycle.py
+++ b/tui_gateway/session_lifecycle.py
@@ -815,14 +815,6 @@ def _interrupt_session_turn(
if should_interrupt:
from agent.interrupt_compat import request_hard_interrupt
request_hard_interrupt(session.get("agent"))
- # Background delegations are detached from the turn's interrupt fan-out; a stop ends them too
- # (own UI sid + spawner id only — a viewer tab must not kill gateway work). Each returns as an
- # interrupted completion with its partial output.
- with contextlib.suppress(Exception):
- from tools.async_delegation import interrupt_for_session
- interrupt_for_session(
- origin_ui_session_id=_lifecycle_own_sid(session, sid), reason="user_stop",
- parent_session_id=str(getattr(session.get("agent"), "session_id", "") or ""))
if not run_thread_alive and not compressing:
with session["history_lock"]:
if session.get("running"):
diff --git a/website/docs/user-guide/features/delegation.md b/website/docs/user-guide/features/delegation.md
index 27abe023e68..46a4a4f11bf 100644
--- a/website/docs/user-guide/features/delegation.md
+++ b/website/docs/user-guide/features/delegation.md
@@ -212,7 +212,7 @@ The dispatch handle lists each unit (`units[].delegation_id`, `group`, `task_ind
- **Thread pool:** Uses `ThreadPoolExecutor` with the configured concurrency limit as max workers
- **Progress display:** In CLI mode, a tree-view shows tool calls from each subagent in real-time with per-task completion lines. In gateway mode, progress is batched and relayed to the parent's progress callback. CLI and TUI completion notices use task-first titles such as `Subagent Task Completed: Review changes`; multi-task groups use the group name and task count. Unsuccessful or incomplete work gets a corresponding status label. These compact notices do not replace the full results delivered to the parent agent.
- **Result ordering:** Within a unit, results are sorted by task index to match input order regardless of completion order; `TASK i/N` labels index the whole call
-- **Cancellation:** Follow-up messages do not cancel a top-level background batch. `/stop` (gateway `/stop`, CLI `/stop`, the Desktop/TUI Stop button, an ACP cancel) or closing/resetting the owning session ends its background children and every synchronous descendant beneath them; each stopped child still returns as a completion with `status="interrupted"` and its partial output
+- **Cancellation:** Follow-up messages and stopping the current turn (Ctrl+C, Esc, the Desktop/TUI Stop button, an ACP cancel) do not cancel a top-level background batch. The `/stop` command (gateway or CLI) or closing/resetting the owning session ends its background children and every synchronous descendant beneath them; each stopped child still returns as a completion with `status="interrupted"` and its partial output
Synchronous single-task delegation from an orchestrator runs directly without thread pool overhead.
@@ -628,7 +628,7 @@ that must survive an owner restart.
:::warning Background completion durability is not durable execution
Top-level model-facing `delegate_task` calls run in the background automatically where the session supports later delivery. Hermes returns a handle immediately, and the result re-enters the conversation after the child or batch finishes. Orchestrator subagents wait for their workers in the current turn because they must synthesize those results before returning. Stateless request/response endpoints fall back to synchronous execution when they cannot deliver a detached result later.
-- Normal follow-up messages do not cancel background children. `/stop` on any surface (gateway `/stop` — also when the session is idle after the dispatching turn ended — CLI `/stop`, the Desktop/TUI Stop button, an ACP cancel) ends the session's running background delegations, and closing or resetting the owning session does the same.
+- Normal follow-up messages do not cancel background children, and neither does stopping the current turn: Ctrl+C, Esc, the Desktop/TUI Stop button and an ACP cancel end only the turn. The `/stop` command (gateway `/stop` — also when the session is idle after the dispatching turn ended — or CLI `/stop`) ends the session's running background delegations, and closing or resetting the owning session does the same.
- Explicit session close/reset interrupts that session's background children. In the CLI and TUI, the gateway owns the session and the client only views it: when the last viewer exits or runs `/new` (a TUI resume switch counts too), the gateway interrupts that session's background children at once and refuses new ones for it until a viewer opens the session again. A plain detach cancels nothing: closing Desktop, a dropped connection, or exiting while another viewer is still attached leaves the work running. Background processes (`terminal(background=True)`) keep running either way.
- A completion for a CLI or TUI session — a background child's result (including an interrupted one), or a `notify_on_complete` process exit or watch-pattern notice — that reaches the head of the session's queue while no viewer is attached does not start a turn. It is written into the session as a note, and the next turn reads it (for example after `hermes chat --resume`). If a viewer is attached by then, including one that came back after the completion arrived, the completion runs as a turn as before. Messaging chats have no viewers and are unchanged: their completions still start a turn.
- A Hermes process restart does **not** resume a running child. Its attempt becomes `unknown` because Hermes cannot prove which side effects happened.