Skip to content

The agent that grows with you

fix(gateway): queue messaging slash-command turns behind the chat's waiting messages

David Dudok de Wita75e83b176df
diff --git a/gateway/run_busy.py b/gateway/run_busy.py
index 843d9cb9bb4..329f34836b7 100644
--- a/gateway/run_busy.py
+++ b/gateway/run_busy.py
@@ -12,6 +12,7 @@ from typing import TYPE_CHECKING
import asyncio
import contextlib
import contextvars
+import functools
import json
import os
import time
@@ -919,6 +920,11 @@ class GatewayBusySessionMixin:
adapter = self._delivery_adapter_for(event.source)
if not adapter:
return False # let default path handle it
+ _skill, _skill_reply = await self._busy_skill_turn(event, event.source, session_key, adapter)
+ if _skill:
+ if _skill_reply:
+ await self._send_busy_reply(event, adapter, _skill_reply)
+ return True
# Internal synthetic events (delegation / background completions) must never interrupt or
# steer; they surface as a NEW turn when idle. Plugin events carry untrusted payload text, so
# queue them through the FIFO (security metadata kept apart).
@@ -1149,7 +1155,7 @@ class GatewayBusySessionMixin:
await _busy_accepted()
adapter = self._delivery_adapter_for(source)
if adapter:
- self._enqueue_fifo(quick_key, MessageEvent(
+ queued = MessageEvent(
text=queued_text, message_type=event.message_type if has_media else MessageType.TEXT,
source=event.source, raw_message=event.raw_message, message_id=event.message_id,
media_urls=list(getattr(event, "media_urls", []) or []),
@@ -1161,7 +1167,9 @@ class GatewayBusySessionMixin:
reply_to_is_own_message=event.reply_to_is_own_message, auto_skill=event.auto_skill,
channel_prompt=event.channel_prompt, channel_context=event.channel_context,
internal=event.internal, timestamp=event.timestamp,
- ), adapter)
+ )
+ if await self._queue_command_turn(quick_key, event, queued, adapter, t("gateway.queue.queued")):
+ return None # its commit sends the ack
depth = self._queue_depth(quick_key, adapter=adapter)
return t("gateway.queue.queued") + (t("gateway.queue.queued_depth", depth=depth) if depth > 1 else "")
@@ -1176,21 +1184,21 @@ class GatewayBusySessionMixin:
_steer_state = self._peek_session_state(quick_key)
running_agent = _steer_state.turn.agent if _steer_state else None
- def _queue_fallback(reply: str) -> str:
+ async def _queue_fallback(reply: str) -> Optional[str]:
# Turn-boundary fallback: queue the steer text as its own follow-up turn.
adapter = self._delivery_adapter_for(source)
- if adapter:
- self._enqueue_fifo(quick_key, MessageEvent(
- text=steer_text, message_type=MessageType.TEXT, source=event.source,
- message_id=event.message_id, channel_prompt=event.channel_prompt,
- channel_context=event.channel_context,
- ), adapter)
+ if adapter and await self._queue_command_turn(quick_key, event, MessageEvent(
+ text=steer_text, message_type=MessageType.TEXT, source=event.source,
+ message_id=event.message_id, channel_prompt=event.channel_prompt,
+ channel_context=event.channel_context,
+ ), adapter, reply):
+ return None # its commit sends the reply
return reply
if running_agent is _AGENT_PENDING_SENTINEL:
- return _queue_fallback(t("gateway.steer.queued_starting"))
+ return await _queue_fallback(t("gateway.steer.queued_starting"))
if not running_agent or not hasattr(running_agent, "steer"):
- return _queue_fallback(t("gateway.steer.queued_no_agent"))
+ return await _queue_fallback(t("gateway.steer.queued_no_agent"))
try:
accepted = self._steer_running_agent(running_agent, self._steer_text_with_origin(steer_text, event))
except Exception as exc:
@@ -1204,6 +1212,109 @@ class GatewayBusySessionMixin:
else t("gateway.steer.target_run"))
return t("gateway.steer.queued", target=target, preview=preview)
+ # A slash command that becomes a turn (``/queue``, the ``/steer`` fallback, ``/plan``, ``/learn``,
+ # a skill or bundle) joins the routed session authority's durable FIFO exactly like text, so it
+ # runs after the turns already admitted. The in-process slot would run it inside the current
+ # turn, ahead of them. Before its commit it is never read as live typing (busy preempt,
+ # plaintext approval, prompt replies: ``_fifo_only``), and a /stop or /new after the command
+ # drops it (``_stop_epoch``); once admitted, no prompt reads it either (``executing_admission``).
+
+ def _command_turn_admitted(self, event: MessageEvent, session_key: str) -> bool:
+ """Whether *event*, a turn a slash command produced, goes to the authority's FIFO. Text that is
+ still a command, an internal event, an executing admission and a turn carrying a one-turn
+ model (``/moa``, which would otherwise land on whichever admitted turn runs next) stay
+ in-process, as without an authority."""
+ from gateway.session_authorities import active_authority
+ from gateway.session_ingress import executing_admission
+ if active_authority(self) is None or executing_admission.get() or event.internal or event.get_command():
+ return False
+ state = self._peek_session_state(session_key)
+ return not (state is not None and state.conversation.one_turn_restore)
+
+ def _route_stop_epoch(self, session_key: str) -> int:
+ """How many messaging /stop and /new reached *session_key* (``_hm_stop_owner_turn``)."""
+ return (getattr(self, "_route_stop_epochs", None) or {}).get(session_key, 0)
+
+ def _bump_route_stop_epoch(self, session_key: str) -> None:
+ epochs = self.__dict__.setdefault("_route_stop_epochs", {})
+ epochs[session_key] = epochs.get(session_key, 0) + 1
+
+ @staticmethod
+ def _as_fifo_turn(event: MessageEvent, stop_epoch: int) -> MessageEvent:
+ if event.message_type == MessageType.COMMAND: # the admitted payload is plain text
+ event.message_type = MessageType.TEXT
+ event._fifo_only, event._stop_epoch = True, stop_epoch
+ return event
+
+ async def _admit_command_turn(self, event: MessageEvent, source, session_key: str,
+ stop_epoch: Optional[int] = None) -> tuple[bool, Optional[str]]:
+ """Inline admission (the idle path, a mid-run skill reaching the runner): ``(True, reply)``
+ like ``_hm_authority_admission``, else ``(False, None)`` to stay in-process."""
+ if not self._command_turn_admitted(event, session_key):
+ return False, None
+ epoch = self._route_stop_epoch(session_key) if stop_epoch is None else stop_epoch
+ return await self._hm_authority_admission(self._as_fifo_turn(event, epoch), source, session_key, False)
+
+ async def _queue_command_turn(self, session_key: str, command: MessageEvent, event: MessageEvent, adapter,
+ ack: Optional[str] = None, stop_epoch: Optional[int] = None) -> bool:
+ """A turn of its own after the current run. True: committed in the background like a busy
+ text follow-up (``dispatch_shared_busy``), and ``ack`` is sent once the row commits, never
+ on the transport's earlier release or a refusal. False: the in-process slot (no authority),
+ and the caller answers with ``ack`` itself."""
+ if not self._command_turn_admitted(event, session_key):
+ self._enqueue_fifo(session_key, event, adapter)
+ return False
+ from gateway.session_ingress import dispatch_shared_busy
+ from gateway.session_ingress_context import carry_callback
+ carry_callback(command, event) # the native or relay callback authenticated the command's event
+ epoch = self._route_stop_epoch(session_key) if stop_epoch is None else stop_epoch
+ if ack:
+ event._on_commit = functools.partial(self._send_after_commit, adapter, event, ack)
+ await dispatch_shared_busy(adapter, self._as_fifo_turn(event, epoch), session_key)
+ return True
+
+ def _send_after_commit(self, adapter, event: MessageEvent, text: str) -> None:
+ async def send():
+ try:
+ await self._send_busy_reply(event, adapter, text)
+ except Exception:
+ logger.warning("Queued-turn acknowledgement failed", exc_info=True)
+ task = asyncio.get_running_loop().create_task(send())
+ adapter._background_tasks.add(task)
+ task.add_done_callback(adapter._background_tasks.discard)
+
+ async def _busy_skill_turn(self, event: MessageEvent, source, session_key: str, adapter=None) -> tuple[bool, Optional[str]]:
+ """A mid-run ``/<skill>`` or ``/<bundle>`` under a session authority, rewritten as on the idle
+ path and queued as a turn: ``(True, reply)`` when handled (``reply`` refuses it, or is the
+ turn's reply when admitted inline; with ``adapter``, the busy handler's, it is committed in
+ the background). ``(False, None)`` leaves a plugin, quick or unknown command to the busy path.
+ It keeps the /stop and /new epoch it arrived under across the (slow) rewrite."""
+ from gateway.session_authorities import active_authority
+ from gateway.session_ingress import executing_admission
+ from hermes_cli.commands import is_gateway_known_command
+ command = event.get_command()
+ if (not command or event.internal or active_authority(self) is None or executing_admission.get()
+ or command in self._hm_quick_commands() or is_gateway_known_command(command)):
+ return False, None
+ epoch_key = self._session_key_for_source(source)
+ epoch = self._route_stop_epoch(epoch_key)
+
+ def rewrite(): # disk-bound skill scan and load, off the loop (#111091)
+ from agent.skill_bundles import resolve_bundle_command_key
+ from agent.skill_commands import resolve_skill_command_key
+ if resolve_bundle_command_key(command) is None and resolve_skill_command_key(command) is None:
+ return False, None
+ return True, self._hm_skill_slash_rewrite(event, source, session_key, command)
+ skill, reply = await self._run_in_executor_with_context(rewrite)
+ if not skill or reply is not None:
+ return skill, reply
+ if adapter is None:
+ return await self._admit_command_turn(event, source, session_key, epoch)
+ if not self._command_turn_admitted(event, session_key):
+ return False, None
+ await self._queue_command_turn(session_key, event, event, adapter, stop_epoch=epoch)
+ return True, None
+
async def _busy_goal_command(self, event: MessageEvent, quick_key: str, source):
# Control verbs are safe mid-run (state only); setting new goal text is rejected so we don't
# race a second continuation against the current turn. wait/gate take an argument.
diff --git a/gateway/run_inbound.py b/gateway/run_inbound.py
index 3870749dae6..7347c4e78e3 100644
--- a/gateway/run_inbound.py
+++ b/gateway/run_inbound.py
@@ -206,6 +206,8 @@ class GatewayInboundMixin(GatewayInboundHooksMixin, GatewayPluginInjectionMixin)
if is_internal:
return event, source, True
+ if getattr(event, "_fifo_only", False): # a slash command's queued turn: its command passed ingress
+ return event, source, False
# scale-to-zero: only real user-originated inbound stamps the last-inbound clock;
# counting internal/system events would keep a genuinely idle gateway awake.
@@ -614,6 +616,7 @@ class GatewayInboundMixin(GatewayInboundHooksMixin, GatewayPluginInjectionMixin)
``messaging:*`` rows of this route's logical owner first (automation wakes, LOCAL/API input
and ``unknown`` rows are untouched; settled silently, no pause notice), then interrupts the
claimed generation: a turn still constructing its agent latches the Stop for adopt_agent."""
+ self._bump_route_stop_epoch(_quick_key) # a command's turn not committed yet never commits
from gateway.session_authorities import active_authority
authority = active_authority(self)
sid = authority.logical_owner(self.session_store.peek_session_id(_quick_key)) if authority else None
@@ -746,6 +749,8 @@ class GatewayInboundMixin(GatewayInboundHooksMixin, GatewayPluginInjectionMixin)
self._queue_or_replace_pending_event(_quick_key, event)
return None
_handled, _result = await self._hm_busy_slash_or_photo(event, source, _quick_key)
+ if not _handled:
+ _handled, _result = await self._busy_skill_turn(event, source, _quick_key)
if _handled:
return _result
@@ -1125,8 +1130,10 @@ class GatewayInboundMixin(GatewayInboundHooksMixin, GatewayPluginInjectionMixin)
self, event: MessageEvent, source: SessionSource, _quick_key: str
) -> Optional[str]:
"""Replies owned by in-flight work: pending /update prompt, clarify, slash-confirm.
- Only events that may control the gateway (``allow_gateway_control``) can answer them."""
- if not event.allow_gateway_control:
+ Only events that may control the gateway (``allow_gateway_control``) can answer them, never
+ an admitted turn: it was offered here before its commit, or a slash command queued it."""
+ from gateway.session_ingress import executing_admission
+ if not event.allow_gateway_control or getattr(event, "_fifo_only", False) or executing_admission.get():
return None
_reply = self._hm_update_prompt_reply(event, _quick_key)
if _reply is None:
@@ -1152,6 +1159,8 @@ class GatewayInboundMixin(GatewayInboundHooksMixin, GatewayPluginInjectionMixin)
_result = await self._run_in_executor_with_context(
self._hm_skill_slash_rewrite, event, source, _quick_key, command)
_handled = _result is not None
+ if not _handled and command: # rewritten into a turn: the authority's FIFO, like text
+ _handled, _result = await self._admit_command_turn(event, source, _quick_key)
return _handled, _result
def _hm_rescue_orphaned_fifo(
@@ -1206,13 +1215,16 @@ class GatewayInboundMixin(GatewayInboundHooksMixin, GatewayPluginInjectionMixin)
# its whole request timeout.
# A bare "yes"/"no" to a blocking dangerous-command approval answers it (#46866):
# never an interrupt (read as deny) nor a queued turn (auto-deny deadlock).
- if self._is_session_running(_quick_key) and (
+ # A turn a slash command produced (``/queue yes``) is never live typing.
+ if self._is_session_running(_quick_key) and not getattr(event, "_fifo_only", False) and (
await self._route_plaintext_approval_while_busy(event, _quick_key)
or await self._hm_busy_preempt(event, source, _quick_key)):
return True, None
_consumed, _consumer_reply = await self._hm_post_admission_consume(event, source, _quick_key)
if _consumed:
return True, _consumer_reply
+ if getattr(event, "_fifo_only", False) and event._stop_epoch != self._route_stop_epoch(_quick_key):
+ return True, None # a /stop or /new came after its command, as it clears the slot
return True, await admit_message(authority, event)
if (authority is None and not is_internal and not event.get_command()
and getattr(self, 'session_authority', None) is not None):
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index 91a635057c6..42ed3a7bc16 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -510,6 +510,8 @@ class SessionAuthority:
def _admitted(self, ref, event, row):
if event is not None:
event._gateway_accepted = True
+ if row['status'] == 'queued' and (committed := getattr(event, '_on_commit', None)) is not None:
+ committed() # a queued slash command's ack follows its commit (``_queue_command_turn``)
self._publish_pending(ref)
return self._receipt(row)
diff --git a/tests/gateway/test_messaging_slash_command_fifo.py b/tests/gateway/test_messaging_slash_command_fifo.py
new file mode 100644
index 00000000000..9638b7d8b8f
--- /dev/null
+++ b/tests/gateway/test_messaging_slash_command_fifo.py
@@ -0,0 +1,354 @@
+"""A slash command that becomes a turn (``/queue``, ``/steer``, ``/plan``, a skill) joins the chat's
+durable FIFO like text, so it runs after the turns already admitted, never inside the running one.
+
+Real GatewayRunner, DiscordAdapter, SessionAuthority and drain over SQLite. The turn body
+(``_handle_message_with_agent``) is a stand-in; the running turn calls the real post-run drain
+step ``_run_agent_drain_pending``, so anything left in the in-process slot shows up "inside A".
+"""
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+
+from tests.waiting import async_wait_until
+
+
+def _owner(monkeypatch, mode=None):
+ from gateway.config import GatewayConfig, Platform, PlatformConfig
+ from gateway.platforms.base import SendResult
+ from gateway.run import GatewayRunner
+ from plugins.platforms.discord.adapter import DiscordAdapter
+
+ monkeypatch.setenv('DISCORD_ALLOWED_USERS', '42')
+ runner = GatewayRunner(GatewayConfig())
+ if mode is not None:
+ runner._busy_input_mode = mode
+ adapter = DiscordAdapter(PlatformConfig(enabled=True, token='fixture-token', typing_indicator=False))
+ sent = []
+
+ async def send(chat_id, content, reply_to=None, metadata=None):
+ sent.append(content)
+ return SendResult(success=True, message_id=f's{len(sent)}')
+ monkeypatch.setattr(adapter, 'send', send)
+ adapter.gateway_runner = runner
+ runner.adapters = {Platform.DISCORD: adapter}
+ monkeypatch.setattr(runner, '_read_user_config', lambda: {'approvals': {'destructive_slash_confirm': False}})
+ return runner, adapter, sent
+
+
+class _Agent:
+ interrupted = False
+
+ def interrupt(self, *args, **kwargs):
+ self.interrupted = True
+
+
+def _skill(monkeypatch):
+ """One installed skill, ``/demo``, without a skills directory."""
+ import agent.skill_bundles as bundles
+ import agent.skill_commands as skills
+ from agent import skill_utils
+
+ monkeypatch.setattr(skills, 'get_skill_commands', lambda: {'/demo': {'name': 'demo'}})
+ monkeypatch.setattr(skills, 'resolve_skill_command_key', lambda command, **_: '/demo' if command == 'demo' else None)
+ monkeypatch.setattr(skills, 'split_stacked_skill_commands', lambda rest, **_: ([], rest))
+ monkeypatch.setattr(skills, 'build_skill_invocation_message', lambda key, text='', **_: f'[demo skill] {text}')
+ monkeypatch.setattr(bundles, 'resolve_bundle_command_key', lambda command: None)
+ monkeypatch.setattr(skill_utils, 'get_disabled_skill_names', lambda **_: set())
+
+
+async def _start_a(monkeypatch, mode=None, *, agent=True):
+ """A runs (executed by the drain) and waits for ``finish``. ``order`` records each turn as
+ ``(message_id, where)``: True when the drain executed it as an admission, 'inside A' when it
+ ran from the in-process slot inside the running turn. Without ``agent`` A stays on the
+ pending sentinel (an agent still being built)."""
+ from gateway.platforms.event import MessageEvent
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_ingress import executing_admission
+ from gateway.session_results import execution_result
+
+ runner, adapter, sent = _owner(monkeypatch, mode)
+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='owner')
+ runner._wire_adapter_handlers(adapter)
+ source = adapter.build_source(chat_id='42', chat_type='dm', user_id='42')
+ rig = SimpleNamespace(runner=runner, adapter=adapter, sent=sent, authority=authority, source=source,
+ key=runner.session_store._generate_session_key(source), order=[],
+ running=asyncio.Event(), finish=asyncio.Event())
+
+ async def turn(event, source, quick_key, run_generation):
+ rig.order.append((event.message_id, executing_admission.get()))
+ result = {'final_response': 'reply ' + str(event.message_id), 'messages': []}
+ if event.message_id == 'A':
+ if agent:
+ runner._session_state(quick_key).turn.agent = _Agent()
+ rig.running.set()
+ await rig.finish.wait()
+ pending_event, pending = await runner._run_agent_drain_pending(
+ result, runner._delivery_adapter_for(source), source, quick_key)
+ if pending_event is not None or pending:
+ rig.order.append((getattr(pending_event, 'message_id', pending), 'inside A'))
+ captured = execution_result.get()
+ if captured is not None:
+ captured['result'] = result
+ return result['final_response']
+ monkeypatch.setattr(runner, '_handle_message_with_agent', turn)
+ await adapter.handle_message(MessageEvent(text='A', source=source, message_id='A'))
+ await asyncio.wait_for(rig.running.wait(), 10)
+ return rig
+
+
+def _rows(rig):
+ from hermes_state_runtime import list_session_admissions
+ sid = rig.runner.session_store.peek_session_id(rig.key)
+ return [row['request_id'] for row in list_session_admissions(rig.authority.db, session_id=sid, pending_only=False)]
+
+
+async def _run_a_then(monkeypatch, mode, command, *, before_finish=None, settled=lambda: False):
+ """A runs; B (plain text) is admitted behind it; then *command* arrives. Returns the turns."""
+ from gateway.platforms.event import MessageEvent, MessageType
+
+ rig = await _start_a(monkeypatch, mode)
+ await rig.adapter.handle_message(MessageEvent(text='B', source=rig.source, message_id='B'))
+ await async_wait_until(lambda: len(_rows(rig)) >= 2, what='B admitted behind A')
+ await rig.adapter.handle_message(MessageEvent(text=command, message_type=MessageType.COMMAND,
+ source=rig.source, message_id='C'))
+ await async_wait_until(lambda: rig.sent or len(_rows(rig)) >= 3 or rig.adapter._pending_messages,
+ what='the command to be queued')
+ if before_finish is not None:
+ await before_finish(rig)
+ rig.finish.set()
+ order = rig.order
+ await async_wait_until(lambda: [m for m, _ in order].count('C') or settled(), timeout=15, what='C to run')
+ await async_wait_until(lambda: ('B', True) in order or settled(), timeout=15, what='B to run')
+ return order
+
+
[email protected]('mode,command', [('queue', '/queue C'), ('interrupt', '/queue C'),
+ ('queue', '/steer C')]) # _Agent cannot steer: the queue fallback
+async def test_busy_queue_runs_after_the_turn_already_admitted(monkeypatch, mode, command):
+ order = await _run_a_then(monkeypatch, mode, command)
+ assert order == [('A', True), ('B', True), ('C', True)], order
+
+
+async def test_busy_skill_slash_runs_after_the_turn_already_admitted(monkeypatch):
+ _skill(monkeypatch)
+ order = await _run_a_then(monkeypatch, 'queue', '/demo C')
+ assert order == [('A', True), ('B', True), ('C', True)], order
+
+
[email protected]('command', ['/queue C', '/steer C', '/plan C'])
+async def test_idle_rewrite_waits_behind_a_queued_row(monkeypatch, command):
+ """Between turns (slot released, the drain has not claimed B yet), a slash command rewritten
+ into a turn is admitted behind B instead of running in-process ahead of it."""
+ from gateway.platforms.event import MessageEvent, MessageType
+ from gateway.session_authority import SessionAuthority, initialize_session_authority
+ from gateway.session_contract import SessionRef
+ from gateway.session_ingress import admit_message, executing_admission
+ from gateway.session_ingress_context import native_callback
+ from gateway.session_results import execution_result
+ from hermes_constants import get_hermes_home
+ from hermes_state_runtime import list_session_admissions
+
+ runner, adapter, _sent = _owner(monkeypatch)
+ real_schedule = SessionAuthority._schedule
+ monkeypatch.setattr(SessionAuthority, '_schedule', lambda self, ref: None)
+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='owner')
+ runner._wire_adapter_handlers(adapter)
+ source = adapter.build_source(chat_id='42', chat_type='dm', user_id='42')
+ order = []
+
+ async def turn(event, source, quick_key, run_generation):
+ order.append((event.message_id, executing_admission.get()))
+ captured = execution_result.get()
+ if captured is not None:
+ captured['result'] = {'final_response': 'ok', 'messages': []}
+ return 'ok'
+ monkeypatch.setattr(runner, '_handle_message_with_agent', turn)
+ follow_up = MessageEvent(text='B', source=source, message_id='B')
+ with native_callback(runner, follow_up, get_hermes_home()):
+ waiter = asyncio.create_task(admit_message(authority, follow_up))
+ await async_wait_until(lambda: authority.waiters)
+ owner = runner.session_store.peek_session_id(runner.session_store._generate_session_key(source))
+ cmd = MessageEvent(text=command, message_type=MessageType.COMMAND, source=source, message_id='C')
+ with native_callback(runner, cmd, get_hermes_home()):
+ task = asyncio.create_task(runner._handle_message(cmd))
+ await async_wait_until(lambda: order or len(list_session_admissions(authority.db, session_id=owner)) >= 2,
+ what=f'{command} to run or be admitted')
+ monkeypatch.setattr(SessionAuthority, '_schedule', real_schedule)
+ authority._schedule(SessionRef(authority.profile_id, owner))
+ await asyncio.wait_for(task, 15)
+ waiter.cancel()
+ assert order == [('B', True), ('C', True)], f'{command} did not wait behind the queued B: {order}'
+
+
[email protected]('prompt', ['slash-confirm', 'update', 'clarify'])
+async def test_an_admitted_turn_never_answers_a_pending_prompt(monkeypatch, prompt):
+ """A prompt that opened after ``/queue yes`` was admitted (a destructive slash-confirm, an
+ /update prompt, a clarify) never takes the executing turn as its answer: the turn runs. A
+ restart replays the row as a plain restored event, which is checked directly."""
+ from tools import clarify_gateway, slash_confirm
+ from gateway.platforms.event import MessageEvent
+ from gateway.session_ingress import executing_admission
+
+ answered = []
+
+ async def confirm(choice):
+ answered.append(choice)
+ return 'confirmed'
+ opened = []
+ monkeypatch.setattr(clarify_gateway, 'get_pending_for_session',
+ lambda key, **_: SimpleNamespace(clarify_id='q', response=None) if opened else None)
+ monkeypatch.setattr(clarify_gateway, 'attempt_text_response_for_session',
+ lambda key, text: answered.append(text) or clarify_gateway.TEXT_RESOLVED)
+
+ async def open_prompt(rig):
+ opened.append(prompt)
+ if prompt == 'slash-confirm':
+ slash_confirm.register(rig.key, 'confirm-1', 'undo', confirm)
+ elif prompt == 'update':
+ rig.runner._session_state(rig.key).persistent.update_prompt_pending = True
+ monkeypatch.setattr(rig.runner, '_hm_write_update_response', lambda text: answered.append(text))
+ token = executing_admission.set(True) # restart recovery: a restored row, no in-memory marker
+ try:
+ replayed = MessageEvent(text='yes', source=rig.source, message_id='R')
+ assert await rig.runner._hm_pending_reply_intercepts(replayed, rig.source, rig.key) is None
+ finally:
+ executing_admission.reset(token)
+ order = await _run_a_then(monkeypatch, 'queue', '/queue yes', before_finish=open_prompt,
+ settled=lambda: answered)
+ assert answered == [] and 'C' in [m for m, _ in order], (answered, order)
+
+
[email protected]('command', ['/queue C', '/steer C']) # no agent can steer: the queue fallback
+async def test_queued_turn_keeps_the_relay_callback(monkeypatch, command):
+ """The rebuilt turn carries the command's authenticated relay callback, so a relay-fronted chat
+ can queue; the strict identity check in ``capture_provenance`` still holds."""
+ from pathlib import Path
+ from unittest.mock import AsyncMock
+ from gateway import session_ingress_context as ctx
+ from gateway.config import Platform
+ from gateway.platforms.event import MessageEvent, MessageType
+ from gateway.run_busy import GatewayBusySessionMixin
+ from gateway.session import SessionSource
+
+ accepted, transport, home = [], object(), Path.cwd()
+
+ class Runner(GatewayBusySessionMixin):
+ session_authority = object()
+
+ def _peek_session_state(self, key):
+ return None
+
+ def _delivery_adapter_for(self, source):
+ return adapter
+
+ def _queue_depth(self, *args, **kwargs):
+ return 0
+ runner = Runner()
+
+ async def handler(event): # the observer's message handler: native callback, then provenance
+ with ctx.native_callback(runner, event, home):
+ ctx.capture_provenance(runner, event)
+ accepted.append(event.text)
+ adapter = SimpleNamespace(_transport=transport, _background_tasks=set(), gateway_runner=None, name='relay',
+ _message_handler=handler, _release_turn_marker=AsyncMock(),
+ _unwrap_ephemeral=lambda response: (response, 0))
+ monkeypatch.setattr(ctx, '_binding', lambda *a: (adapter, home, home, {'relay': 'seal'}))
+ source = SessionSource(platform=Platform.TELEGRAM, chat_id='42', user_id='42', chat_type='dm',
+ delivered_via_upstream_relay=True)
+ original = MessageEvent(text=command, message_type=MessageType.COMMAND, source=source, message_id='C')
+ method = runner._busy_queue_command if command.startswith('/queue') else runner._busy_steer_command
+ with ctx.relay_callback(transport, original), ctx.native_callback(runner, original, home):
+ await method(original, 'chat', source)
+ assert accepted == ['C']
+
+
[email protected]('caller', ['adapter', 'runner'])
[email protected]('kind', ['skill', 'bundle'])
+async def test_stop_during_a_busy_skill_rewrite_drops_it(monkeypatch, caller, kind):
+ """A /stop that lands while a mid-run skill or bundle command is still being rewritten (a slow
+ cold skill scan) drops it, as it clears the in-process slot: it never commits afterwards.
+ ``adapter``: the adapter's busy handler; ``runner``: the runner's busy path (no adapter guard)."""
+ import threading
+ import agent.skill_bundles as bundles
+ from gateway.platforms.event import MessageEvent, MessageType
+
+ _skill(monkeypatch)
+ started, gate = threading.Event(), threading.Event()
+
+ def slow(text):
+ started.set()
+ gate.wait(10)
+ return f'[{kind}] {text}'
+ if kind == 'skill':
+ import agent.skill_commands as skills
+ monkeypatch.setattr(skills, 'build_skill_invocation_message', lambda key, text='', **_: slow(text))
+ else:
+ monkeypatch.setattr(bundles, 'resolve_bundle_command_key', lambda command: '/demo' if command == 'demo' else None)
+ monkeypatch.setattr(bundles, 'build_bundle_invocation_message', lambda key, args, **_: (slow(args), [], []))
+ rig = await _start_a(monkeypatch, 'queue')
+ command = MessageEvent(text='/demo C', message_type=MessageType.COMMAND, source=rig.source, message_id='C')
+ task = asyncio.create_task(rig.adapter.handle_message(command) if caller == 'adapter'
+ else rig.runner._handle_message(command))
+ await async_wait_until(lambda: started.is_set() or task.done(), what='the rewrite to start')
+ await rig.adapter.handle_message(MessageEvent(text='/stop', message_type=MessageType.COMMAND,
+ source=rig.source, message_id='S'))
+ gate.set()
+ await asyncio.wait_for(task, 15)
+ rig.finish.set()
+ assert 'C' not in _rows(rig) and 'C' not in [m for m, _ in rig.order], (_rows(rig), rig.order)
+
+
[email protected]('command,agent,ack', [('/queue C', True, 'gateway.queue.queued'),
+ ('/steer C', True, 'gateway.steer.queued_no_agent'),
+ ('/steer C', False, 'gateway.steer.queued_starting')])
+async def test_queued_ack_follows_the_commit(monkeypatch, command, agent, ack):
+ """The busy sender may be released before the row commits (#140454 releases it once the input
+ waits behind an earlier one of its chat). The "Queued" reply follows the commit, not that
+ release: none before it, one once it lands."""
+ from agent.i18n import t
+ import gateway.session_ingress as ingress
+ from gateway.platforms.event import MessageEvent, MessageType
+
+ real, held = ingress.admit_message, asyncio.Event()
+
+ async def released_early(authority, event):
+ accepted = ingress.busy_acceptance.get()
+ if event.message_id == 'C' and accepted is not None:
+ accepted.set_result(None)
+ await held.wait()
+ return await real(authority, event)
+ monkeypatch.setattr(ingress, 'admit_message', released_early)
+ rig = await _start_a(monkeypatch, 'queue', agent=agent)
+ await rig.adapter.handle_message(MessageEvent(text=command, message_type=MessageType.COMMAND,
+ source=rig.source, message_id='C'))
+ assert t(ack) not in rig.sent and 'C' not in _rows(rig), rig.sent
+ held.set()
+ await async_wait_until(lambda: t(ack) in rig.sent, what='the ack after the commit')
+ assert 'C' in _rows(rig) and rig.sent.count(t(ack)) == 1, rig.sent
+ rig.finish.set()
+
+
+async def test_queued_approval_word_is_a_turn_never_an_approval(monkeypatch):
+ """Keep working: ``/queue yes`` queues a user turn; it never answers a blocking dangerous-command
+ approval the way a typed "yes" does."""
+ from tools import approval
+
+ approved = []
+ monkeypatch.setattr(approval, 'has_blocking_approval', lambda key: True)
+
+ async def approve(self, event):
+ approved.append(event.text)
+ return 'approved'
+ from gateway.run import GatewayRunner
+ monkeypatch.setattr(GatewayRunner, '_handle_approve_command', approve)
+ order = await _run_a_then(monkeypatch, 'queue', '/queue yes')
+ assert approved == [] and 'C' in [m for m, _ in order], (approved, order)