Skip to content

The agent that grows with you

fix(gateway): the authority busy preempt runs main's busy resolution and ack

Tekniumb47c5f6c6ad0
diff --git a/gateway/run_busy.py b/gateway/run_busy.py
index bf6d7d9ed27..e25a32a08e0 100644
--- a/gateway/run_busy.py
+++ b/gateway/run_busy.py
@@ -856,10 +856,9 @@ class GatewayBusySessionMixin:
_busy_state = self._peek_session_state(session_key)
running_agent = _busy_state.turn.agent if _busy_state else None
_steer = await self._resolve_busy_steer_or_redirect(event, session_key, effective_mode, running_agent)
- effective_mode, redirected = _steer.effective_mode, _steer.redirected
# Queue as the next turn — skipped after a successful steer/redirect (the text is already in
# the run and must NOT replay). FIFO gives each text its own turn (raw merge would join them).
- if not _steer.steered and not redirected:
+ if not _steer.steered and not _steer.redirected:
self._queue_or_replace_pending_event(session_key, event)
# Store the message so it's processed as the next turn after the current run finishes (or is
# interrupted). Skip this for a successful steer — the text already landed inside the run and must
@@ -870,6 +869,14 @@ class GatewayBusySessionMixin:
# messages sent while the agent was busy (interrupt mode, or a steer that fell back to queue)
# arrived as one mashed-together turn (#43066 sub-bug 2). The FIFO path gives each text its own turn
# in arrival order while still preserving photo-burst / album merge semantics for media.
+ await self._busy_interrupt_and_ack(event, session_key, adapter, _busy_state, running_agent, _steer)
+ return True
+
+ async def _busy_interrupt_and_ack(self, event, session_key, adapter, _busy_state, running_agent, _steer) -> None:
+ """Interrupt-mode abort (voice transcribed) and the busy ack, after the steer/redirect resolution.
+ Shared by the in-process busy handler and the session authority's busy preempt."""
+ from gateway.run import _AGENT_PENDING_SENTINEL
+ effective_mode, redirected = _steer.effective_mode, _steer.redirected
is_queue_mode = effective_mode == "queue"
is_steer_mode = effective_mode == "steer"
is_redirect_mode = effective_mode == "interrupt" and redirected
@@ -883,15 +890,15 @@ class GatewayBusySessionMixin:
# stamps the "last ack" timestamp.
if os.environ.get("HERMES_GATEWAY_BUSY_ACK_ENABLED", "true").lower() != "true":
logger.debug("Busy ack suppressed for session %s", session_key)
- return True # input still processed, just no ack sent
+ return # input still processed, just no ack sent
# Debounce (30s) before the config-heavy display lookup.
now = time.time()
if now - (_busy_state.turn.busy_ack_ts if _busy_state else 0) < 30:
- return True # interrupt sent (if not queue), ack already delivered recently
+ return # interrupt sent (if not queue), ack already delivered recently
if is_steer_mode and not self._busy_steer_ack_enabled(event, session_key):
- return True
+ return
self._session_state(session_key).turn.busy_ack_ts = now
@@ -902,7 +909,6 @@ class GatewayBusySessionMixin:
demoted_for_compression=_steer.demoted_for_compression,
)
await self._send_busy_ack_reply(event, adapter, message)
- return True
# Slash name → handler method is ``_handle_<name>_command`` (``-`` → ``_``) except these.
_COMMAND_HANDLER_ALIASES = {"bg": "_handle_background_command", "sethome": "_handle_set_home_command"}
diff --git a/gateway/run_inbound.py b/gateway/run_inbound.py
index 08e91e14707..846838e6f68 100644
--- a/gateway/run_inbound.py
+++ b/gateway/run_inbound.py
@@ -688,41 +688,23 @@ class GatewayInboundMixin(GatewayInboundHooksMixin, GatewayPluginInjectionMixin)
running_agent.interrupt(_interrupt_text)
async def _hm_busy_preempt(self, event: MessageEvent, source: SessionSource, _quick_key: str) -> bool:
- """busy_input_mode for a follow-up the durable FIFO is about to admit. Returns True when the
- text already landed inside the running turn (steer / redirect), so it must NOT also be
- admitted as its own turn; False when the caller should admit it (queue mode, a demotion,
- or an interrupt — the ended turn lets the FIFO run the follow-up next)."""
+ """busy_input_mode for a follow-up the durable FIFO is about to admit, through main's own busy
+ resolution (voice transcribed into steer/interrupt, steer folded into the turn, busy ack).
+ Returns True when the text already landed inside the running turn (steer / redirect), so it
+ must NOT also be admitted as its own turn; False when the caller should admit it (queue mode,
+ a demotion, or an interrupt — the ended turn lets the FIFO run the follow-up next)."""
from gateway.run import _AGENT_PENDING_SENTINEL
mode = self._effective_busy_input_mode(source)
state = self._peek_session_state(_quick_key)
running_agent = state.turn.agent if state else None
- if (mode == "queue" or self._draining or running_agent is None
- or running_agent is _AGENT_PENDING_SENTINEL or not self._hm_text_only(event)):
- return False
- text = (event.text or "").strip()
- if not text:
- return False
- if mode == "steer":
- if hasattr(running_agent, "steer"):
- try:
- return bool(self._steer_running_agent(running_agent, self._steer_text_with_origin(text, event)))
- except Exception as exc:
- logger.warning("PRIORITY steer failed for session %s: %s", _quick_key, exc, exc_info=True)
- return False
- if self._agent_has_active_subagents(running_agent):
- logger.info("PRIORITY interrupt demoted to queue for session %s because the running agent has active subagents (#30170)", _quick_key)
- return False
- if await self._session_has_compression_in_flight(_quick_key):
- logger.info("PRIORITY interrupt demoted to queue for session %s because context compression is in flight (#56391)", _quick_key)
+ adapter = self._delivery_adapter_for(source)
+ if (self._draining or adapter is None or running_agent is None or running_agent is _AGENT_PENDING_SENTINEL
+ or (event.message_type == MessageType.TEXT and mode != "steer"
+ and self._effective_busy_text_mode(source) == "queue")):
return False
- if (getattr(running_agent, "_supports_active_turn_redirect", False) is True and hasattr(running_agent, "redirect")
- and self._redirect_active_turn(running_agent, text, _quick_key, event)):
- logger.debug("PRIORITY redirect for session %s", _quick_key)
- return True
- # No redirect: end the running turn; the follow-up is admitted and runs as the next turn.
- logger.debug("PRIORITY interrupt for session %s", _quick_key)
- running_agent.interrupt()
- return False
+ outcome = await self._resolve_busy_steer_or_redirect(event, _quick_key, mode, running_agent)
+ await self._busy_interrupt_and_ack(event, _quick_key, adapter, state, running_agent, outcome)
+ return bool(outcome.steered or outcome.redirected)
async def _hm_handle_running_session_message(
self, event: MessageEvent, source: SessionSource, _quick_key: str
diff --git a/tests/gateway/test_authority_busy_preempt_parity.py b/tests/gateway/test_authority_busy_preempt_parity.py
new file mode 100644
index 00000000000..2bffebcebe4
--- /dev/null
+++ b/tests/gateway/test_authority_busy_preempt_parity.py
@@ -0,0 +1,110 @@
+"""The authority's busy preempt keeps main's busy handler: voice steers, steer folds, busy ack."""
+import asyncio
+
+import pytest
+
+from gateway.config import GatewayConfig, Platform, PlatformConfig
+from gateway.platforms.base import SendResult
+from gateway.platforms.event import MessageEvent, MessageType
+from gateway.run import GatewayRunner
+from gateway.session_authority import SessionAuthority, initialize_session_authority
+from hermes_state_runtime import list_session_admissions
+
+
+
+class _RunningAgent:
+ def __init__(self):
+ self.steers, self.interrupts = [], []
+
+ def steer(self, text):
+ self.steers.append(text)
+ return True
+
+ def interrupt(self, *args):
+ self.interrupts.append(args)
+
+ def get_activity_summary(self):
+ return {}
+
+
+async def _setup(tmp_path, monkeypatch, mode):
+ from plugins.platforms.whatsapp.adapter import WhatsAppAdapter
+ monkeypatch.setenv('WHATSAPP_ALLOWED_USERS', '15551234567')
+ monkeypatch.setattr(SessionAuthority, '_schedule', lambda self, ref: None)
+ runner = GatewayRunner(GatewayConfig(sessions_dir=tmp_path / 'sessions'))
+ adapter = WhatsAppAdapter(PlatformConfig(enabled=True, extra={'session_path': str(tmp_path / 'wa')}))
+ adapter.gateway_runner, runner.adapters = runner, {Platform.WHATSAPP: adapter}
+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='busy')
+ runner._wire_adapter_handlers(adapter)
+ sent = []
+
+ async def send(chat_id, content, **_):
+ sent.append(content)
+ return SendResult(success=True, message_id='s')
+
+ monkeypatch.setattr(adapter, 'send', send)
+ monkeypatch.setattr(runner, '_effective_busy_input_mode', lambda source: mode)
+ source = adapter.build_source(chat_id=CHAT, user_id=CHAT, chat_type='group')
+ key = runner._session_key_for_source(source)
+ agent = _RunningAgent()
+ turn = runner._session_state(key).turn
+ turn.agent = agent
+ turn.event = MessageEvent(text='unaddressed chatter', source=source, message_id='t0', reply_expected=False)
+ return runner, authority, source, agent, sent, turn
+
+
+def _admitted(authority):
+ return [row for sid in authority.sessions
+ for row in list_session_admissions(authority.db, session_id=sid, pending_only=False)]
+
+
+async def test_busy_voice_note_steers_with_transcript_folds_and_acks(tmp_path, monkeypatch):
+ runner, authority, source, agent, sent, turn = await _setup(tmp_path, monkeypatch, 'steer')
+
+ async def transcribe(event, adapter, source, text, **_):
+ return 'TRANSCRIBED voice follow-up', ['TRANSCRIBED voice follow-up']
+
+ monkeypatch.setattr(runner, '_transcribe_and_echo_pending_voice', transcribe)
+ monkeypatch.setattr(runner, '_pending_event_audio_paths', lambda event: list(event.media_urls))
+ voice = tmp_path / 'note.ogg'
+ voice.write_bytes(b'OggS')
+ try:
+ handled = asyncio.ensure_future(runner._handle_message(MessageEvent(
+ text='', message_type=MessageType.VOICE, source=source, message_id='v1', reply_expected=True,
+ media_urls=[str(voice)], media_types=['audio/ogg'])))
+ done, _ = await asyncio.wait({handled}, timeout=10)
+ handled.cancel()
+ assert done, 'the voice note was admitted as a turn behind the running one instead of steering'
+ assert len(agent.steers) == 1 and agent.steers[0].endswith('TRANSCRIBED voice follow-up'), agent.steers
+ assert turn.event.reply_expected is True # addressed steer folded: a silence marker can't end it
+ assert sent, 'no busy ack'
+ assert _admitted(authority) == [] # steered text is inside the run, never replayed
+ finally:
+ authority.db.close()
+
+
+async def test_busy_voice_note_interrupts_with_transcript_in_interrupt_mode(tmp_path, monkeypatch):
+ runner, authority, source, agent, sent, _turn = await _setup(tmp_path, monkeypatch, 'interrupt')
+
+ async def transcribe(event, adapter, source, text, **_):
+ return 'TRANSCRIBED stop that', ['TRANSCRIBED stop that']
+
+ monkeypatch.setattr(runner, '_transcribe_and_echo_pending_voice', transcribe)
+ monkeypatch.setattr(runner, '_pending_event_audio_paths', lambda event: list(event.media_urls))
+ monkeypatch.setattr(runner, '_handle_message_with_agent', lambda *a, **k: None)
+ voice = tmp_path / 'note.ogg'
+ voice.write_bytes(b'OggS')
+ try:
+ task = asyncio.ensure_future(runner._handle_message(MessageEvent(
+ text='', message_type=MessageType.VOICE, source=source, message_id='v2',
+ media_urls=[str(voice)], media_types=['audio/ogg'])))
+ from tests.waiting import async_wait_until
+ await async_wait_until(lambda: _admitted(authority), timeout=10, what='the voice note admitted')
+ task.cancel()
+ assert agent.interrupts == [('TRANSCRIBED stop that',)], agent.interrupts
+ assert sent, 'no busy ack'
+ finally:
+ authority.db.close()