Skip to content

The agent that grows with you

fix(gateway): a busy redirect re-anchors the running turn's reply to the redirecting message

teknium1bd3eb4132259
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py
index a20670f7b40..115c29a0eaa 100644
--- a/gateway/platforms/base.py
+++ b/gateway/platforms/base.py
@@ -155,6 +155,9 @@ def _mark_notify_metadata(metadata: dict | None) -> dict:
def _reply_anchor_for_event(event) -> str | None:
"""Return reply_to id for platforms that need reply semantics."""
+ override = getattr(event, "reply_anchor_override", None)
+ if override is not None:
+ return override # the turn was redirected onto another message (#115001)
source = getattr(event, "source", None)
platform = _platform_name(getattr(source, "platform", None))
thread_id = getattr(source, "thread_id", None)
diff --git a/gateway/platforms/event.py b/gateway/platforms/event.py
index ccc84ebc67e..38fba3109ea 100644
--- a/gateway/platforms/event.py
+++ b/gateway/platforms/event.py
@@ -52,6 +52,11 @@ class MessageEvent:
# refused first reply then reads as delivered). Reply routing is unaffected: the reply anchor
# still comes from this event.
ledger_message_id: Optional[str] = None
+ # Reply anchor for the final send when the answer is to a DIFFERENT message than the one that
+ # opened the turn: a successful busy redirect turns the running turn onto the redirecting
+ # message, so its reply must quote that message (#115001). ``_reply_anchor_for_event``
+ # honours this over ``message_id``; None = derive from the event as usual.
+ reply_anchor_override: Optional[str] = None
# Platform update id (Telegram ``update_id``): ``/restart`` records it so the new gateway
# advances past it even if PTB's shutdown ACK times out.
platform_update_id: Optional[int] = None
diff --git a/gateway/run_busy.py b/gateway/run_busy.py
index 3065ff90102..aecd7b23472 100644
--- a/gateway/run_busy.py
+++ b/gateway/run_busy.py
@@ -600,8 +600,8 @@ class GatewayBusySessionMixin:
and getattr(running_agent, "_supports_active_turn_redirect", False) is True
and hasattr(running_agent, "redirect")
):
- redirected = self._try_agent_verb(
- running_agent, "redirect", (event.text or "").strip(), session_key, event=event
+ redirected = self._redirect_active_turn(
+ running_agent, (event.text or "").strip(), session_key, event
)
return self._BusySteerOutcome(
effective_mode=effective_mode, demoted_for_subagents=demoted_for_subagents,
@@ -626,6 +626,29 @@ class GatewayBusySessionMixin:
logger.warning("Gateway %s failed for session %s: %s", verb, session_key, exc)
return False
+ def _redirect_active_turn(self, running_agent, text: str, session_key: str, event: MessageEvent) -> bool:
+ """``redirect()`` the running turn onto *event* and re-anchor its delivery to that message.
+
+ The turn's reply anchor and ledger identity were bound to the message that OPENED it, and
+ the final send is bracketed against that event; after a successful redirect the answer is
+ to *event*, so the reply must quote it (#115001). Both redirect entry points (busy
+ interrupt mode and the priority path) go through here.
+ """
+ if not self._try_agent_verb(running_agent, "redirect", text, session_key, event=event):
+ return False
+ turn = self._session_state(session_key).turn
+ if turn.agent is not running_agent:
+ return True # a newer turn already owns the slot; never re-anchor it
+ anchor = self._reply_anchor_for_event(event)
+ inbound_id = str(event.message_id) if event.message_id else None
+ if turn.event is not None and turn.event is not event:
+ turn.event.reply_anchor_override = anchor
+ turn.event.ledger_message_id = inbound_id
+ if turn.ctx is not None:
+ turn.ctx.event_message_id = anchor
+ turn.ctx.inbound_message_id = inbound_id
+ return True
+
async def _interrupt_running_agent_for_busy_event(self, event: MessageEvent, adapter, running_agent) -> None:
"""Interrupt mode: abort in-flight tool calls; the agent loop exits at its next check point."""
from gateway.run import _build_media_placeholder
diff --git a/gateway/run_inbound.py b/gateway/run_inbound.py
index c4c4fea7831..4ca82c962c5 100644
--- a/gateway/run_inbound.py
+++ b/gateway/run_inbound.py
@@ -655,14 +655,9 @@ class GatewayInboundMixin:
# runtime supports it; media/voice and older runtimes use the interrupt path below.
_can_redirect = getattr(running_agent, "_supports_active_turn_redirect", False) is True
if self._hm_text_only(event) and _can_redirect and hasattr(running_agent, "redirect"):
- try:
- if running_agent.redirect(
- self._steer_text_with_origin((event.text or "").strip(), event)
- ):
- logger.debug("PRIORITY redirect for session %s", _quick_key)
- return
- except Exception as exc:
- logger.warning("PRIORITY redirect failed for session %s: %s", _quick_key, exc)
+ if self._redirect_active_turn(running_agent, (event.text or "").strip(), _quick_key, event):
+ logger.debug("PRIORITY redirect for session %s", _quick_key)
+ return
logger.debug("PRIORITY interrupt for session %s", _quick_key)
_interrupt_text = event.text
if self._pending_event_audio_paths(event):
@@ -1331,6 +1326,7 @@ class GatewayInboundMixin:
if _active_session_lease is not None:
_claim_state.turn.lease = _active_session_lease
_claim_state.turn.agent = _AGENT_PENDING_SENTINEL
+ _claim_state.turn.event = event
_claim_state.turn.started_ts = time.time()
self._persist_active_agents()
_run_generation = self._begin_session_run_generation(_quick_key)
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index c63af307303..4e7d9963744 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -3245,7 +3245,8 @@ class GatewayTurnMixin:
session_key or "", run_generation,
)
return
- self._session_state(session_key).turn.agent = agent_holder[0]
+ turn_state = self._session_state(session_key).turn
+ turn_state.agent, turn_state.ctx = agent_holder[0], turn_ctx
if self._draining:
self._update_runtime_status("draining")
diff --git a/gateway/session_state.py b/gateway/session_state.py
index 35a069dc940..9e36c35e4b5 100644
--- a/gateway/session_state.py
+++ b/gateway/session_state.py
@@ -20,6 +20,10 @@ class TurnState:
``clear()``: ``_release_turn_lease`` owns it (release exactly once)."""
agent: Any = None # running AIAgent (or _AGENT_PENDING_SENTINEL); None = idle
+ # The MessageEvent that opened the running turn and the live TurnContext: a successful busy
+ # redirect re-anchors both to the redirecting message (#115001).
+ event: Any = None
+ ctx: Any = None
started_ts: float = 0.0 # 0.0 = not running
lease: Any = None # cross-process active-session slot lease
busy_ack_ts: float = 0.0 # debounce; 0.0 = never acked
@@ -30,7 +34,7 @@ class TurnState:
def clear(self) -> None:
"""Reset the per-turn slot. The caller pops ``lease`` first to release it."""
- self.agent = self.lease = None
+ self.agent = self.lease = self.event = self.ctx = None
self.started_ts = self.busy_ack_ts = 0.0
diff --git a/tests/gateway/test_busy_redirect_anchor.py b/tests/gateway/test_busy_redirect_anchor.py
new file mode 100644
index 00000000000..d4b9df18cba
--- /dev/null
+++ b/tests/gateway/test_busy_redirect_anchor.py
@@ -0,0 +1,76 @@
+"""A successful busy redirect re-anchors the running turn's reply to the redirecting message.
+
+The turn's reply anchor and ledger identity are bound to the message that OPENED it and the
+final send is bracketed against that event, so before this a redirected turn answered B while
+its reply still quoted A (#115001, Repro A). Both redirect entry points — the interrupt-mode
+busy path and the priority path — must move the anchor; a refused redirect must not.
+"""
+
+import pytest
+
+from gateway.config import GatewayConfig, Platform
+from gateway.platforms.base import _reply_anchor_for_event
+from gateway.platforms.event import MessageEvent
+from gateway.run import GatewayRunner
+from gateway.session import SessionSource
+from gateway.turn_context import TurnContext
+
+
+class Receiver:
+ _supports_active_turn_redirect = True
+
+ def __init__(self, accept=True):
+ self.accept = accept
+
+ def redirect(self, text):
+ return self.accept
+
+
+def _running_turn(runner, key, receiver):
+ source = SessionSource(platform=Platform.TELEGRAM, chat_id="c1", user_id="u1", chat_type="dm")
+ opening = MessageEvent(text="What is the weather in Shanghai?", source=source, message_id="A")
+ ctx = TurnContext(session_key=key, event_message_id="A", inbound_message_id="A")
+ turn = runner._session_state(key).turn
+ turn.agent, turn.event, turn.ctx = receiver, opening, ctx
+ redirecting = MessageEvent(text="What day is tomorrow?", source=source, message_id="B")
+ return opening, ctx, redirecting, source
+
+
[email protected]("route", ["busy_interrupt", "priority"])
+async def test_successful_redirect_moves_the_turn_reply_anchor_to_the_redirecting_message(route):
+ runner = GatewayRunner(config=GatewayConfig())
+ receiver = Receiver()
+ opening, ctx, redirecting, source = _running_turn(runner, "key", receiver)
+
+ if route == "priority":
+ await runner._hm_busy_interrupt(redirecting, source, receiver, "key")
+ else:
+ outcome = await runner._resolve_busy_steer_or_redirect(redirecting, "key", "interrupt", receiver)
+ assert outcome.redirected is True
+
+ # The final send is bracketed against the OPENING event: it now quotes B and is ledgered as B.
+ assert _reply_anchor_for_event(opening) == "B"
+ assert opening.ledger_message_id == "B"
+ # The queued-first-response lane reads the TurnContext anchor: it follows too.
+ assert (ctx.event_message_id, ctx.inbound_message_id) == ("B", "B")
+ # A's own identity is untouched (the ledger keys on ledger_message_id, not on this).
+ assert opening.message_id == "A"
+
+
+async def test_refused_or_foreign_redirect_leaves_the_anchor_on_the_opening_message():
+ runner = GatewayRunner(config=GatewayConfig())
+ refusing = Receiver(accept=False)
+ opening, ctx, redirecting, _ = _running_turn(runner, "key", refusing)
+ outcome = await runner._resolve_busy_steer_or_redirect(redirecting, "key", "interrupt", refusing)
+ assert outcome.redirected is False
+ assert _reply_anchor_for_event(opening) == "A" and opening.ledger_message_id is None
+ assert ctx.event_message_id == "A"
+
+ # A redirect that lands on an agent which no longer owns the slot (a newer turn claimed it)
+ # must not re-anchor the newer turn.
+ displaced = Receiver()
+ opening2, ctx2, redirecting2, _ = _running_turn(runner, "key2", Receiver())
+ assert await runner._resolve_busy_steer_or_redirect(redirecting2, "key2", "interrupt", displaced)
+ assert _reply_anchor_for_event(opening2) == "A" and ctx2.event_message_id == "A"