The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a late queued steer goes back to its queue, never into a follow-up
unsupportedpastels94458ebba1d8
diff --git a/agent/interrupt_control.py b/agent/interrupt_control.pyindex 695288fbfac..6e4930ee69f 100644--- a/agent/interrupt_control.py+++ b/agent/interrupt_control.py@@ -400,6 +400,15 @@ class InterruptControlMixin:self._steer_last_drain = (text, parts) # requeue_drained_steer restores its ticketsreturn text+ def _drain_leftover_steer(self) -> Optional[str]:+ """The turn finalizer's drain: return and clear the ticketless steers (they become the next user+ turn) and keep each ticketed one buffered. A transfer is never a follow-up a restart may discard:+ settlement withdraws it and its admission goes back to its own queue place."""+ with _ic_lock(self, "_pending_steer_lock"):+ parts = _steer_parts(self)+ _set_steer_parts(self, [part for part in parts if part[0] is not None])+ return "\n".join(text for ticket, text in parts if ticket is None) or None+def withdraw_steer(self, ticket) -> bool:"""Settle one ``steer(text, ticket=...)`` by identity (the gateway's transfer of a queued prompt):True when no drain handed it to the turn, either still buffered (taken out now; every other steerdiff --git a/agent/turn_finalizer.py b/agent/turn_finalizer.pyindex 9fd39ec52d1..c882efb7d61 100644--- a/agent/turn_finalizer.py+++ b/agent/turn_finalizer.py@@ -743,8 +743,9 @@ def finalize_turn(if _cleanup_errors:result["cleanup_errors"] = _cleanup_errors# A /steer landing after the final assistant turn has no tool batch to drain into;- # hand it back so it becomes the next user turn instead of being lost.- _leftover_steer = agent._drain_pending_steer()+ # hand it back so it becomes the next user turn instead of being lost. A gateway transfer+ # (ticketed) stays buffered: the claim's settlement returns it to its own queue place.+ _leftover_steer = (getattr(agent, "_drain_leftover_steer", None) or agent._drain_pending_steer)()if _leftover_steer:result["pending_steer"] = _leftover_steeragent._response_was_previewed = Falsediff --git a/tests/agent/test_steer.py b/tests/agent/test_steer.pyindex 1962b9b5bc9..2cd5b998804 100644--- a/tests/agent/test_steer.py+++ b/tests/agent/test_steer.py@@ -112,6 +112,16 @@ class TestSteerDrain:assert agent.withdraw_steer("t") is Trueassert agent._pending_steer == "note"+ def test_the_leftover_drain_hands_back_only_ticketless_steers(self):+ agent = _bare_agent()+ agent.steer("typed /steer")+ agent.steer("queued prompt", ticket="t")+ assert agent._drain_leftover_steer() == "typed /steer"+ assert agent._pending_steer == "queued prompt"+ assert agent._drain_leftover_steer() is None+ assert agent.withdraw_steer("t") is True+ assert agent._pending_steer is None+def test_a_hard_stop_drops_a_ticket_unread(self):agent = _bare_agent()agent.steer("queued prompt", ticket="t")diff --git a/tests/agent/test_turn_finalizer_cleanup_guard.py b/tests/agent/test_turn_finalizer_cleanup_guard.pyindex c1df0b33ec4..ab73cedc873 100644--- a/tests/agent/test_turn_finalizer_cleanup_guard.py+++ b/tests/agent/test_turn_finalizer_cleanup_guard.py@@ -161,6 +161,15 @@ def test_single_cleanup_step_raises_does_not_skip_others(step):assert len(result["cleanup_errors"]) == 1+def test_a_ticketed_steer_stays_out_of_the_leftover_follow_up():+ """A gateway transfer still buffered when the turn ends is not this turn's leftover steer: the+ finalizer hands back only ticketless steers, so settlement returns the transfer to its queue."""+ agent = _StubAgent(raise_in=())+ agent._drain_leftover_steer = lambda: "typed /steer"+ agent._drain_pending_steer = lambda: "typed /steer\nqueued prompt"+ assert _run(agent)["pending_steer"] == "typed /steer"++def test_clean_turn_has_no_cleanup_errors_key():agent = _StubAgent(raise_in=())result = _run(agent)diff --git a/tests/gateway/test_prompt_queued_transfer.py b/tests/gateway/test_prompt_queued_transfer.pyindex 08c797565d0..a75392f2250 100644--- a/tests/gateway/test_prompt_queued_transfer.py+++ b/tests/gateway/test_prompt_queued_transfer.py@@ -174,6 +174,72 @@ async def test_each_transfer_settles_by_its_own_identity_whatever_text_another_cassert agent._pending_steer is None+def _runner_authority(tmp_path, monkeypatch):+ """``_authority`` whose runner is a real ``GatewayRunner``, so its follow-up handling reads the same+ ``_draining`` a restart sets."""+ from types import SimpleNamespace+ from gateway.run import GatewayRunner+ from gateway.session_authority import LiveSession, SessionAuthority+ from hermes_state import SessionDB+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ db = SessionDB(db_path=tmp_path / 'state.db')+ db.create_session('s', source='gui')+ runner = object.__new__(GatewayRunner)+ vars(runner).update(_draining=False, _restart_requested=True, config=SimpleNamespace(multiplex_profiles=False),+ _adapter_for_source=lambda source: None)+ authority = SessionAuthority(runner, profile_id='owned', instance_id='current', db=db,+ epoch=begin_runtime_epoch(db, instance_id='current'))+ authority.sessions['s'] = LiveSession(SimpleNamespace(platform=None, user_id='human'), 'route')+ return db, authority, runner++[email protected]('draining', [False, True])+async def test_a_late_transfer_is_never_a_follow_up_that_a_restart_can_discard(tmp_path, monkeypatch, caplog, draining):+ """Reviewer repro (round 3): the transfer lands after the turn's last drain, and the gateway may begin+ draining for a restart before the turn ends. The turn's leftover steer must not carry it: a restart+ discards that follow-up while settlement recorded it steered. It goes back to its own queue place."""+ import logging+ caplog.set_level(logging.INFO)+ db, authority, runner = _runner_authority(tmp_path, monkeypatch)+ agent, claimed, release, handled, follow_ups = BufferedAgent(), asyncio.Event(), asyncio.Event(), [], []++ async def handle_message(event): # the real ingress up to here; no model+ handled.append(event.text)+ authority.adopt_agent('s', authority.executing['s'], agent)+ claimed.set()+ await asyncio.wait_for(release.wait(), 30)+ result = {'final_response': 'done', 'messages': []}+ # The leftover drain agent/turn_finalizer.py runs (an agent without one drains everything).+ leftover = (getattr(agent, '_drain_leftover_steer', None) or agent._drain_pending_steer)()+ if leftover:+ result['pending_steer'] = leftover+ follow_ups.append((await runner._run_agent_drain_pending(result, None, event.source, 'k'))[1])+ return 'done'+ runner._handle_message = handle_message+ with db:+ await _submit(authority, 'running')+ await asyncio.wait_for(claimed.wait(), 30)+ queued = await _submit(authority, 'follow-up')+ assert 'error' not in await _call(_connection(authority), 'prompt.steer_queued', admission_id=queued.admission_id)+ runner._draining = draining # a restart begins while the turn's last model call streams+ release.set()++ def settled():+ task = authority.sessions['s'].task+ return _ledger(db)[1][1] != 'started' and (task is None or task.done())+ await async_wait_until(settled, timeout=30, what='the transfer settled and the queue went idle')+ assert follow_ups[0] is None, 'a transferred prompt never rides the leftover-steer follow-up'+ assert not [r for r in caplog.records if 'Discarding pending follow-up' in r.getMessage()]+ assert ('follow-up', 'terminal', 'steered') not in _ledger(db)+ # Back in its FIFO place: it runs once as its own admission, or, while the owner drains for its+ # restart (it claims nothing new), it waits queued for the next owner.+ if draining:+ assert (_ledger(db)[1], handled) == (('follow-up', 'queued', None), ['running'])+ else:+ assert (_ledger(db)[1], handled) == (('follow-up', 'terminal', 'completed'), ['running', 'follow-up'])++@pytest.mark.asyncioasync def test_a_transfer_stays_listed_as_steering_until_its_claim_settles(tmp_path, monkeypatch):"""Reviewer repro (returned prompt stays hidden): a pending snapshot taken while a steer is in