The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): canonical Stop hard-cancels and ends the session's delegations
Teknium659e55ac71dc
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex d1ada043b0a..a8b24a4bc9f 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -622,17 +622,28 @@ class SessionAuthority:handle = self._handle(ref)if handle.execution_generation != generation:raise RuntimeStoreError('stale_generation')+ live, agent = self.sessions[ref.session_id], Noneif handle.execution_state == 'running':- adopted_generation, agent = self.adopted.get(ref.session_id, (None, None))- if adopted_generation != generation:- agent = self.agent(ref)- if agent is not None:- agent.interrupt()- self.delivered_stops[ref.session_id] = generation- if adopted_generation != generation and not self._runs_own_agent(ref):- # Accepted for this exact claim before its turn adopted an agent: whatever agent- # the turn adopts for this generation must not run the work as if no Stop arrived.- self.pending_stops[ref.session_id] = generation+ # Latches are written under the lock adopt_agent takes on the executor thread, BEFORE the+ # agent is called: an adoption racing the call consumes them. The agent is called outside it.+ with live.event_stream.lock:+ adopted_generation, agent = self.adopted.get(ref.session_id, (None, None))+ if adopted_generation != generation:+ agent = self.agent(ref)+ if not self._runs_own_agent(ref):+ # Accepted for this exact claim before its turn adopted an agent: whatever agent+ # the turn adopts for this generation must not run the work as if no Stop arrived.+ 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).+ 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 _runs_own_agent(self, ref):@@ -674,7 +685,8 @@ class SessionAuthority:clear()if self.pending_stops.get(session_id) == generation:del self.pending_stops[session_id]- agent.interrupt()+ from agent.interrupt_compat import request_hard_interrupt+ request_hard_interrupt(agent)latched, steers = self.pending_steers.pop(session_id, (None, ()))for text in steers if latched == generation else ():agent.steer(text)diff --git a/tests/gateway/test_canonical_stop_hard_cancel.py b/tests/gateway/test_canonical_stop_hard_cancel.pynew file mode 100644index 00000000000..4a454783425--- /dev/null+++ b/tests/gateway/test_canonical_stop_hard_cancel.py@@ -0,0 +1,62 @@+"""Canonical Stop (Desktop, Ink, classic CLI view, ACP) is main's Stop: hard-cancel + end the session's delegations."""+import asyncio+from unittest.mock import MagicMock++import pytest++from tests.gateway.test_session_authority_cancel_settlement import ACTOR, REF, _authority, _submit, _wire_turn_agent+++class Agent:+ def __init__(self):+ self.stops = []++ def interrupt(self, *args, **kwargs):+ self.stops.append('hard' if kwargs.get('hard_cancel') else 'soft')++ def hard_interrupt(self, message=None, *, tool_reason=None):+ self.stops.append('hard')++ def clear_interrupt(self, *args, **kwargs):+ pass+++def _delegation(ad, monkeypatch, parent):+ fn = MagicMock()+ monkeypatch.setitem(ad._records, 'd-' + parent, {+ 'delegation_id': 'd-' + parent, 'status': 'running', 'session_key': 'other-route',+ 'origin_ui_session_id': 'other', 'parent_session_id': parent, 'interrupt_fn': fn})+ return fn++[email protected]('when', ['adopted', 'before_adoption'])+async def test_canonical_stop_hard_cancels_and_ends_the_sessions_delegations(tmp_path, monkeypatch, when):+ from gateway import session_finite+ from tools import async_delegation as ad++ db, authority = _authority(tmp_path, monkeypatch)+ authority.runner._cached_agent_for = {}.get+ agent = Agent()+ own, foreign = _delegation(ad, monkeypatch, 's'), _delegation(ad, monkeypatch, 'unrelated')+ claimed, stopped = asyncio.Event(), asyncio.Event()++ async def execute(authority, ref, row):+ if when == 'adopted':+ _wire_turn_agent(authority, row['generation'], agent)+ claimed.set()+ await asyncio.wait_for(stopped.wait(), 5)+ if when == 'before_adoption': # the Stop latched; the agent this generation adopts fires it hard+ _wire_turn_agent(authority, row['generation'], agent)+ return 'done'+ monkeypatch.setattr(session_finite, 'execute_finite_admission', execute)++ with db:+ await _submit(authority, 'turn')+ await asyncio.wait_for(claimed.wait(), 5)+ await authority.interrupt(ACTOR, REF, authority._handle(REF).execution_generation)+ 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 foreign.called, "Stop ended another session's delegation"