Skip to content

The agent that grows with you

fix(gateway): give producer-admitted relay turns their typing and reactions back

Victor Kyriazakos02438db863e1
diff --git a/gateway/platforms/webhook_ingress.py b/gateway/platforms/webhook_ingress.py
index db9bfa788b2..0c6c8a9c8ea 100644
--- a/gateway/platforms/webhook_ingress.py
+++ b/gateway/platforms/webhook_ingress.py
@@ -134,7 +134,7 @@ async def admit_producer(adapter, event):
webhook = adapter.platform == Platform.WEBHOOK
hooks = [name for name in ('pre_gateway_dispatch', POST_ADMISSION_HOOK) if has_hook(name)]
if not (webhook or hooks):
- return await authority.admit_native(event)
+ return await _admit_native(authority, event)
from gateway.session_authority import native_write_started
payload, principal = await _prepared(authority, event)
writing = native_write_started.set(False)
@@ -181,7 +181,14 @@ async def _admit_once(authority, event, webhook, hooks, committed):
if consumed:
await _release_preparation(authority, committed[0])
return None
- return await authority.admit_native(admitted)
+ return await _admit_native(authority, admitted)
+
+
+async def _admit_native(authority, event):
+ # No adapter task brackets a producer's turn: the executor runs its adapter lifecycle (typing,
+ # processing hooks) once the row starts executing (``session_producer_lifecycle``).
+ event._producer_delivery = True
+ return await authority.admit_native(event)
# Producer deliveries in flight by (profile, principal, provider id) -> [lock, holder + waiters]. This
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index b9e544c071f..1629fa5b5a4 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -20,6 +20,7 @@ from gateway.session_contract import (
)
from gateway.session_events import SessionEvents
from gateway.session_pending_controls import PendingControls
+from gateway.session_producer_lifecycle import drop_producer_turn, mark_producer_admission
from hermes_state_runtime import (
STEERING, RuntimeStoreError, admit_session_input, begin_runtime_epoch,
cancel_session_input, claim_session_input, get_session_admission,
@@ -616,6 +617,7 @@ class SessionAuthority:
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``)
+ mark_producer_admission(self, event, row)
self._publish_pending(ref)
return self._receipt(row)
@@ -830,6 +832,7 @@ class SessionAuthority:
# Published once: a later exact retry re-collects media but never repeats the completion.
self.cancel_obligations.discard(admission_id)
self.native_waiters.discard(admission_id)
+ drop_producer_turn(self, admission_id)
waiter = self.waiters.pop(admission_id, None)
if waiter is not None and not waiter.done():
waiter.set_result(None)
@@ -1386,6 +1389,7 @@ class SessionAuthority:
if settled is None:
# Uncommitted (unknown or discarded): the user is not told an answer the FIFO lost.
self.pending_deliveries.pop(admission_id, None)
+ drop_producer_turn(self, admission_id)
from gateway.session_ingress import waiter_replies
waiter_replies(self).pop(admission_id, None)
# Taken on every exit, so a turn that never settled leaves no reset for a later one.
diff --git a/gateway/session_ingress.py b/gateway/session_ingress.py
index 38d11d7edd7..a386bc33442 100644
--- a/gateway/session_ingress.py
+++ b/gateway/session_ingress.py
@@ -2,11 +2,12 @@
import asyncio
import logging
from contextvars import ContextVar
-from contextlib import nullcontext
+from contextlib import asynccontextmanager, nullcontext
from dataclasses import replace
-from gateway.platforms.event import MessageEvent
+from gateway.platforms.event import MessageEvent, ProcessingOutcome
from gateway.session_envelope import restore_native
+from gateway.session_producer_lifecycle import close_producer_turn, producer_turn
from hermes_state_runtime import RuntimeStoreError
logger = logging.getLogger(__name__)
@@ -285,7 +286,7 @@ async def execute_admission(authority, ref, row):
event._turn_marker_handoff = True
handed = False
try:
- with await _execution_scope(authority, home):
+ async with _admission_scope(authority, home, row, event, captured):
if is_api:
# Committed media resolves under the owning profile's home, like admission did.
prepared = prepare_api_execution(authority, ref, row['payload'])
@@ -353,6 +354,15 @@ def _launch_body_if_launch_owner(authority):
return launch_body()
+@asynccontextmanager
+async def _admission_scope(authority, home, row, event, captured):
+ """The execution scope, inside the adapter lifecycle the executor owns for a producer-admitted
+ turn (``session_producer_lifecycle``; a no-op for every other admission)."""
+ async with producer_turn(authority, row, event, captured):
+ with await _execution_scope(authority, home):
+ yield
+
+
async def _execution_scope(authority, home):
"""Under multiplex, owner-side execution runs under the OWNING profile's home (agent build,
config, secrets, state.db), never the launch profile's ambient scope; native provenance
@@ -394,11 +404,14 @@ async def deliver_settled(authority, admission_id):
if held is not None:
# Fenced unknown: no answer is owed, so no later boot may deliver one either.
await _release_turn_marker(authority, held)
+ # Settled with nothing (left) to send: its reply streamed, or it had none.
+ await close_producer_turn(authority, admission_id, ProcessingOutcome.SUCCESS)
return
adapter, event, session_key, response, home = delivery
+ delivered = False
try:
with await _execution_scope(authority, home):
- await deliver_response(adapter, event, session_key, response)
+ delivered = await deliver_response(adapter, event, session_key, response)
except Exception:
logger.exception('Delivery of settled admission %s failed', admission_id)
finally:
@@ -406,13 +419,17 @@ async def deliver_settled(authority, admission_id):
authority.pending_deliveries.pop(admission_id, None)
# The ledgered send already released the marker; an empty or failed send owes no more.
await _release_turn_marker(authority, event)
+ await close_producer_turn(
+ authority, admission_id, ProcessingOutcome.SUCCESS if delivered else ProcessingOutcome.FAILURE)
async def deliver_response(adapter, event, session_key, response):
+ """Send a turn's reply; whether it was delivered (``_process_message_background``'s verdict:
+ nothing to send, or at least one send that succeeded)."""
from gateway.platforms.base import _thread_metadata_for_event, _mark_notify_metadata
text, ttl = adapter._unwrap_ephemeral(response)
if not text:
- return
+ return True
extracted = await adapter._extract_response_content(text, event, session_key, is_ephemeral_response=ttl > 0)
metadata = _mark_notify_metadata(_thread_metadata_for_event(event))
results = []
@@ -421,6 +438,7 @@ async def deliver_response(adapter, event, session_key, response):
metadata, ttl > 0, ttl, results.append)
await adapter._deliver_attachments(event, extracted, metadata, anything_sent=bool(results),
record_delivery=results.append)
+ return any(getattr(result, 'success', False) for result in results if result is not None)
async def dispatch_shared_busy(adapter, event, session_key, *, durable=False):
diff --git a/gateway/session_producer_lifecycle.py b/gateway/session_producer_lifecycle.py
new file mode 100644
index 00000000000..62e04048656
--- /dev/null
+++ b/gateway/session_producer_lifecycle.py
@@ -0,0 +1,127 @@
+"""The adapter processing lifecycle of a producer-admitted turn (relay, webhook: ``admit_producer``).
+
+A chat message an adapter hands to ``handle_message`` is bracketed by
+``BasePlatformAdapter._process_message_background``: the typing refresh, ``on_processing_start``,
+and ``on_processing_complete`` once its reply was sent. A producer delivery is only committed at
+ingress (off the transport reader, acknowledged on the commit) and the authority's drain runs it, so
+no adapter task brackets it. The executor does, for those admissions only (a messaging admission's
+own adapter task already brackets it):
+
+- opened when the admission starts executing, not when it commits: a delivery queued behind a
+ running turn is acknowledged when it runs, as the in-band queue's are (``run_turn_followup_ack``);
+- typing lives as long as execution, so it stops before the reply is sent (#117300 pauses it there);
+- the outcome is reported once: an interrupted turn as CANCELLED and a failed one as FAILURE when
+ execution ends; a completed one after its settlement, by the reply's send (``deliver_settled``),
+ or as FAILURE when settlement dropped the reply (``drop_producer_turn``).
+"""
+import asyncio
+from contextlib import asynccontextmanager
+
+from gateway.platforms.event import ProcessingOutcome
+
+
+def _turns(authority):
+ """admission id -> None (committed by a producer, not started) or its open ``_Bracket``."""
+ turns = getattr(authority, 'producer_turns', None)
+ if turns is None:
+ turns = authority.producer_turns = {}
+ return turns
+
+
+def mark_producer_admission(authority, event, row):
+ """``SessionAuthority._admitted``, in the commit's own tracked task: a producer's freshly queued
+ row is the executor's to bracket. A re-send of a row already running or settled is not marked."""
+ if getattr(event, '_producer_delivery', False) and row['status'] == 'queued':
+ _turns(authority).setdefault(row['admission_id'], None)
+
+
+class _Bracket:
+ def __init__(self, adapter, event, hooks):
+ from gateway.platforms.base import _thread_metadata_for_event
+ self.adapter, self.event, self.hooks = adapter, event, hooks
+ self.metadata = _thread_metadata_for_event(event)
+ self.stop = asyncio.Event()
+ self.typing = None
+ self.closed = False
+
+ async def stop_typing(self):
+ task, self.typing = self.typing, None
+ if task is not None:
+ self.stop.set()
+ await self.adapter._stop_typing_refresh(self.event.source.chat_id, task, metadata=self.metadata)
+
+ async def close(self, outcome):
+ if self.closed:
+ return
+ self.closed = True
+ await self.stop_typing()
+ if self.hooks:
+ await self.adapter._run_processing_hook('on_processing_complete', self.event, outcome)
+
+
+async def _open(authority, row, event):
+ """The bracket of a producer-admitted row starting to execute, else None: an adapter that
+ renders neither typing nor the processing hooks (a webhook) is left alone."""
+ turns = _turns(authority)
+ if row['admission_id'] not in turns:
+ return None
+ from gateway.platforms.base import BasePlatformAdapter
+ from gateway.run_turn_followup_ack import _followup_processing_hooks_apply
+ adapter = authority.runner._adapter_for_source(event.source)
+ typing = adapter is not None and type(adapter).send_typing is not BasePlatformAdapter.send_typing
+ hooks = _followup_processing_hooks_apply(adapter, event)
+ if not (typing or hooks):
+ turns.pop(row['admission_id'], None)
+ return None
+ bracket = turns[row['admission_id']] = _Bracket(adapter, event, hooks)
+ if typing:
+ # None for a heartbeat or ``typing_indicator: false``, as on the adapter path.
+ bracket.typing = adapter._start_typing_refresh(event, bracket.stop, bracket.metadata)
+ if hooks:
+ await adapter._run_processing_hook('on_processing_start', event)
+ return bracket
+
+
+def _executed_outcome(captured):
+ """The outcome settlement will commit (``session_results.prepare_result``), as a hook outcome."""
+ result = captured.get('terminal_result', captured.get('result')) or {}
+ if result.get('interrupted'):
+ return ProcessingOutcome.CANCELLED
+ if result.get('failed') or result.get('error'):
+ return ProcessingOutcome.FAILURE
+ return ProcessingOutcome.SUCCESS
+
+
+@asynccontextmanager
+async def producer_turn(authority, row, event, captured):
+ """Around ``execute_admission``'s run of *row*: ``captured`` is its ``execution_result``."""
+ bracket = await _open(authority, row, event)
+ if bracket is None:
+ yield
+ return
+ outcome = ProcessingOutcome.FAILURE
+ try:
+ yield
+ outcome = _executed_outcome(captured)
+ finally:
+ await bracket.stop_typing()
+ if outcome is not ProcessingOutcome.SUCCESS:
+ await close_producer_turn(authority, row['admission_id'], outcome)
+
+
+async def close_producer_turn(authority, admission_id, outcome):
+ """Report a settled producer turn's outcome (once; a no-op for any other admission)."""
+ bracket = _turns(authority).pop(admission_id, None)
+ if bracket is not None:
+ await bracket.close(outcome)
+
+
+def drop_producer_turn(authority, admission_id):
+ """The admission settled without its reply (unknown, discarded) or was cancelled before it ran:
+ a started turn reports FAILURE, off the caller's path."""
+ bracket = _turns(authority).pop(admission_id, None)
+ if bracket is None or bracket.closed:
+ return
+ task = asyncio.get_running_loop().create_task(bracket.close(ProcessingOutcome.FAILURE))
+ bracket.adapter._background_tasks.add(task)
+ task.add_done_callback(bracket.adapter._background_tasks.discard)
diff --git a/tests/gateway/relay/test_relay_native_turn_lifecycle.py b/tests/gateway/relay/test_relay_native_turn_lifecycle.py
new file mode 100644
index 00000000000..2e9fe28eb60
--- /dev/null
+++ b/tests/gateway/relay/test_relay_native_turn_lifecycle.py
@@ -0,0 +1,313 @@
+"""A relay chat message admitted natively (``admit_producer``) gets the adapter processing lifecycle.
+
+``RelayAdapter._on_inbound`` commits a non-command message through ``admit_relay_delivery`` and the
+session authority's drain runs it, so ``BasePlatformAdapter._process_message_background`` (the
+typing refresh, ``on_processing_start`` and ``on_processing_complete``) never brackets it. The turn
+executor owns that bracket for producer deliveries: opened when the admission starts executing
+(a message queued behind a running turn is acknowledged when it runs), typing stopped when
+execution ends, and the outcome reaction swapped once the turn settled and its reply was sent.
+
+Real ``GatewayRunner`` + session authority + ``RelayAdapter`` + ``WebSocketRelayTransport`` against
+a fixture connector; only the model call (``_handle_message_with_agent``) is stubbed.
+"""
+import asyncio
+import json
+from contextlib import asynccontextmanager
+
+import pytest
+
+from gateway.config import GatewayConfig, Platform, PlatformConfig
+from gateway.run import GatewayRunner
+from gateway.session_results import execution_result, record_unexecuted_failure
+from tests.waiting import async_wait_until
+
+websockets = pytest.importorskip('websockets')
+
+EYES, OK, FAIL = 'πŸ‘€', 'βœ…', '❌'
+
+
+@asynccontextmanager
+async def _relay(runner, *, refusing_chats=()):
+ """A real relay transport + adapter fronting Slack (``react`` advertised) against a fixture
+ connector that answers every outbound frame; every ``send`` to a chat in ``refusing_chats`` is
+ refused. Yields ``(send, outgoing, adapter)``."""
+ from gateway.relay.adapter import RelayAdapter
+ from gateway.relay.descriptor import CapabilityDescriptor
+ from gateway.relay.ws_transport import WebSocketRelayTransport
+
+ outgoing, ready = [], asyncio.Queue()
+ descriptor = CapabilityDescriptor(1, 'slack', 'Fixture', 4096, False, True, True, 'plain', 'chars',
+ supported_ops=('send', 'edit', 'typing', 'react'))
+
+ async def connector(ws):
+ await ws.recv() # hello
+ await ws.send(json.dumps({'type': 'descriptor', 'descriptor': json.loads(descriptor.to_json())}) + '\n')
+ await ready.put(ws)
+ async for line in ws:
+ frame = json.loads(line)
+ outgoing.append(frame)
+ if frame['type'] == 'outbound':
+ refused = frame['action'].get('op') == 'send' and frame['action'].get('chat_id') in refusing_chats
+ result = {'success': False, 'error': 'refused'} if refused else {'success': True, 'message_id': 'sent'}
+ await ws.send(json.dumps({'type': 'outbound_result', 'requestId': frame['requestId'],
+ 'result': result}) + '\n')
+
+ async with websockets.serve(connector, '127.0.0.1', 0) as server:
+ transport = WebSocketRelayTransport(
+ f'ws://127.0.0.1:{server.sockets[0].getsockname()[1]}/relay', 'slack', 'fixture-bot',
+ gateway_id='fixture-gateway', upgrade_secret='fixture-secret', reconnect=False)
+ adapter = RelayAdapter(PlatformConfig(enabled=True), descriptor, transport)
+ adapter.gateway_runner = runner
+ runner.adapters[Platform.RELAY] = adapter
+ runner._wire_adapter_handlers(adapter)
+ try:
+ assert await adapter.connect()
+ ws = await asyncio.wait_for(ready.get(), 5)
+
+ async def send(message_id, chat_id, text, thread_id=None):
+ source = {'platform': 'slack', 'chat_type': 'dm', 'chat_id': chat_id, 'user_id': 'U-' + chat_id}
+ if thread_id is not None:
+ source['thread_id'] = thread_id # a reply in that message's thread: its session
+ event = {'text': text, 'message_id': message_id, 'source': source}
+ await ws.send(json.dumps({'type': 'inbound', 'event': event, 'bufferId': 'buf-' + message_id}) + '\n')
+
+ yield send, outgoing, adapter
+ finally:
+ await adapter.disconnect()
+
+
+@asynccontextmanager
+async def _gateway(tmp_path, instance, **relay):
+ from gateway.session_authority import initialize_session_authority
+ runner = GatewayRunner(GatewayConfig(sessions_dir=tmp_path / 'sessions'))
+ authority = await initialize_session_authority(runner, profile_id='default', instance_id=instance)
+ try:
+ async with _relay(runner, **relay) as (send, outgoing, adapter):
+ yield runner, authority, send, outgoing, adapter
+ finally:
+ authority.db.close()
+
+
+def _stub_model(runner, monkeypatch, behaviours=None):
+ """Replace the model turn: ``behaviours[text]`` (async, gets the event) decides the reply, else
+ ``'reply <text>'``. Returns the list of executed texts."""
+ executed = []
+
+ async def turn(event, *_args, **_kwargs):
+ executed.append(event.text)
+ behaviour = (behaviours or {}).get(event.text)
+ if behaviour is not None:
+ return await behaviour(event)
+ execution_result.get()['result'] = {'final_response': 'reply ' + event.text, 'messages': []}
+ return 'reply ' + event.text
+
+ monkeypatch.setattr(runner, '_handle_message_with_agent', turn)
+ return executed
+
+
+def _actions(outgoing):
+ return [f['action'] for f in outgoing if f.get('type') == 'outbound']
+
+
+def _reacts(outgoing, message_id):
+ return [(a['emoji'], a['remove']) for a in _actions(outgoing)
+ if a.get('op') == 'react' and a.get('message_id') == message_id]
+
+
+def _index(outgoing, predicate):
+ actions = _actions(outgoing)
+ return next(i for i, a in enumerate(actions) if predicate(a))
+
+
+def _last_index(outgoing, predicate):
+ actions = _actions(outgoing)
+ return max(i for i, a in enumerate(actions) if predicate(a))
+
+
+def _heartbeats(outgoing, chat_id):
+ return [a for a in _actions(outgoing)
+ if a.get('op') == 'typing' and a.get('chat_id') == chat_id and a.get('content') != '']
+
+
+def _is_reply(text):
+ return lambda a: a.get('op') == 'send' and a.get('content') == text
+
+
+def _settled(outgoing, message_id, final):
+ return lambda: _reacts(outgoing, message_id)[-1:] == [final]
+
+
+def _typing_cleared_after_last_heartbeat(outgoing, chat_id):
+ actions = _actions(outgoing)
+ typing = [i for i, a in enumerate(actions) if a.get('op') == 'typing' and a.get('chat_id') == chat_id]
+ return bool(typing) and actions[typing[-1]].get('content') == ''
+
+
+def _typing_refreshes():
+ return [task for task in asyncio.all_tasks() if not task.done()
+ and getattr(task.get_coro(), '__qualname__', '').endswith('._keep_typing')]
+
+
+async def test_toolless_chat_message_shows_typing_and_reactions_around_its_reply(tmp_path, monkeypatch):
+ async with _gateway(tmp_path, 'relay-lifecycle-ok') as (runner, _authority, send, outgoing, _adapter):
+ async def wait_for_typing(event):
+ # The status is visible WHILE the turn runs (no tools, so nothing else sends one).
+ await async_wait_until(lambda: _heartbeats(outgoing, 'D1'), timeout=10, what='typing during the turn')
+ execution_result.get()['result'] = {'final_response': 'hi there', 'messages': []}
+ return 'hi there'
+
+ executed = _stub_model(runner, monkeypatch, {'hello': wait_for_typing})
+ await send('1700000000.000100', 'D1', 'hello')
+ await async_wait_until(_settled(outgoing, '1700000000.000100', (OK, False)), timeout=20,
+ what='the success reaction')
+ assert executed == ['hello']
+ assert _reacts(outgoing, '1700000000.000100') == [(EYES, False), (EYES, True), (OK, False)]
+ reply = _index(outgoing, _is_reply('hi there'))
+ assert _index(outgoing, lambda a: a.get('op') == 'react' and not a['remove']) < reply
+ # The outcome follows the delivered reply.
+ assert _last_index(outgoing, lambda a: a.get('op') == 'react') > reply
+ await async_wait_until(lambda: _typing_cleared_after_last_heartbeat(outgoing, 'D1'), timeout=10,
+ what='the Slack status cleared')
+ # No status refresh outlives the turn (a leaked one keeps Slack's "is working" up).
+ await async_wait_until(lambda: not _typing_refreshes(), timeout=10, what='the typing refresh stopped')
+
+
+async def _raise(_event):
+ raise RuntimeError('model exploded')
+
+
+async def _recorded_failure(_event):
+ # The real agent-exception path (``run_turn_persistence``): a failed result plus the apology.
+ return record_unexecuted_failure('Sorry, that failed.')
+
+
[email protected]('behaviour', [_raise, _recorded_failure], ids=['raised', 'recorded'])
+async def test_a_failed_turn_swaps_in_the_failure_reaction_and_clears_typing(tmp_path, monkeypatch, behaviour):
+ async with _gateway(tmp_path, 'relay-lifecycle-fail') as (runner, _authority, send, outgoing, _adapter):
+ _stub_model(runner, monkeypatch, {'boom': behaviour})
+ await send('1700000000.000200', 'D2', 'boom')
+ await async_wait_until(_settled(outgoing, '1700000000.000200', (FAIL, False)), timeout=20,
+ what='the failure reaction')
+ assert _reacts(outgoing, '1700000000.000200') == [(EYES, False), (EYES, True), (FAIL, False)]
+ await async_wait_until(lambda: _typing_cleared_after_last_heartbeat(outgoing, 'D2'), timeout=10,
+ what='the Slack status cleared')
+
+
+async def test_a_refused_reply_is_a_failure(tmp_path, monkeypatch):
+ async with _gateway(tmp_path, 'relay-lifecycle-refused', refusing_chats=('D25',)) as (
+ runner, _authority, send, outgoing, _adapter):
+ _stub_model(runner, monkeypatch)
+ await send('1700000000.000250', 'D25', 'nope')
+ await async_wait_until(_settled(outgoing, '1700000000.000250', (FAIL, False)), timeout=20,
+ what='the failure reaction')
+ assert _reacts(outgoing, '1700000000.000250') == [(EYES, False), (EYES, True), (FAIL, False)]
+
+
+async def test_an_interrupted_turn_only_removes_the_in_progress_reaction(tmp_path, monkeypatch):
+ async def interrupted(_event):
+ execution_result.get()['result'] = {'final_response': '', 'messages': [], 'interrupted': True}
+
+ async with _gateway(tmp_path, 'relay-lifecycle-stop') as (runner, _authority, send, outgoing, _adapter):
+ executed = _stub_model(runner, monkeypatch, {'long job': interrupted})
+ await send('1700000000.000300', 'D3', 'long job')
+ await async_wait_until(lambda: (EYES, True) in _reacts(outgoing, '1700000000.000300'), timeout=20,
+ what='the in-progress reaction removed')
+ # Settled: a later message in its thread runs, so the interrupted one's bracket is closed.
+ await send('1700000000.000301', 'D3', 'after', thread_id='1700000000.000300')
+ await async_wait_until(_settled(outgoing, '1700000000.000301', (OK, False)), timeout=20,
+ what='the next turn settled')
+ assert executed == ['long job', 'after']
+ assert _reacts(outgoing, '1700000000.000300') == [(EYES, False), (EYES, True)]
+ await async_wait_until(lambda: _typing_cleared_after_last_heartbeat(outgoing, 'D3'), timeout=10,
+ what='the Slack status cleared')
+
+
+async def test_a_follow_up_queued_behind_a_running_turn_is_acknowledged_when_it_starts(tmp_path, monkeypatch):
+ release = asyncio.Event()
+
+ async def held(_event):
+ await release.wait()
+ execution_result.get()['result'] = {'final_response': 'first done', 'messages': []}
+ return 'first done'
+
+ async with _gateway(tmp_path, 'relay-lifecycle-queue') as (runner, authority, send, outgoing, _adapter):
+ executed = _stub_model(runner, monkeypatch, {'first': held})
+ await send('1700000000.000400', 'D4', 'first')
+ await async_wait_until(lambda: _reacts(outgoing, '1700000000.000400') == [(EYES, False)], timeout=20,
+ what='the first message acknowledged')
+ await send('1700000000.000401', 'D4', 'second', thread_id='1700000000.000400')
+ await async_wait_until(
+ lambda: authority.db._read_all("SELECT 1 FROM session_admissions WHERE request_id='1700000000.000401'"),
+ timeout=20, what='the follow-up committed')
+ # Committed behind the running turn, not started: no acknowledgement yet.
+ assert _reacts(outgoing, '1700000000.000401') == []
+ assert executed == ['first']
+ release.set()
+ await async_wait_until(_settled(outgoing, '1700000000.000401', (OK, False)), timeout=20,
+ what='the follow-up settled')
+ assert executed == ['first', 'second']
+ assert _reacts(outgoing, '1700000000.000400') == [(EYES, False), (EYES, True), (OK, False)]
+ assert _reacts(outgoing, '1700000000.000401') == [(EYES, False), (EYES, True), (OK, False)]
+ # It is acknowledged once it starts, after the turn ahead of it answered.
+ assert _index(outgoing, _is_reply('first done')) < _index(
+ outgoing, lambda a: a.get('op') == 'react' and a['message_id'] == '1700000000.000401')
+
+
+async def test_a_slash_command_keeps_its_single_adapter_lifecycle(tmp_path, monkeypatch):
+ async with _gateway(tmp_path, 'relay-lifecycle-command') as (runner, _authority, send, outgoing, _adapter):
+ _stub_model(runner, monkeypatch)
+ await send('1700000000.000500', 'D5', '/help')
+ await async_wait_until(_settled(outgoing, '1700000000.000500', (OK, False)), timeout=20,
+ what='the command lifecycle')
+ assert _reacts(outgoing, '1700000000.000500') == [(EYES, False), (EYES, True), (OK, False)]
+
+
+async def test_pre_gateway_dispatch_still_fires_once_and_the_turn_is_acknowledged(tmp_path, monkeypatch):
+ from hermes_cli.plugins import get_plugin_manager
+ fired = []
+
+ async def hook(event, **_kwargs):
+ fired.append(event.message_id)
+
+ manager = get_plugin_manager()
+ manager._discovered = True
+ manager._hooks.setdefault('pre_gateway_dispatch', []).append(hook)
+ async with _gateway(tmp_path, 'relay-lifecycle-hook') as (runner, _authority, send, outgoing, _adapter):
+ executed = _stub_model(runner, monkeypatch)
+ await send('1700000000.000600', 'D6', 'hooked')
+ await async_wait_until(_settled(outgoing, '1700000000.000600', (OK, False)), timeout=20,
+ what='the success reaction')
+ assert executed == ['hooked']
+ assert fired == ['1700000000.000600']
+ assert _reacts(outgoing, '1700000000.000600') == [(EYES, False), (EYES, True), (OK, False)]
+
+
+async def test_a_scheduled_wake_on_the_chat_shows_no_reaction_or_typing(tmp_path, monkeypatch):
+ from gateway.session_automation import admit_route_wake
+
+ async with _gateway(tmp_path, 'relay-lifecycle-wake') as (runner, _authority, send, outgoing, adapter):
+ executed = _stub_model(runner, monkeypatch)
+ await send('1700000000.000700', 'D7', 'hello')
+ await async_wait_until(_settled(outgoing, '1700000000.000700', (OK, False)), timeout=20,
+ what='the human turn settled')
+ await async_wait_until(lambda: _typing_cleared_after_last_heartbeat(outgoing, 'D7'), timeout=10,
+ what='the Slack status cleared')
+ before_reacts = [a for a in _actions(outgoing) if a.get('op') == 'react']
+ before_typing = len(_heartbeats(outgoing, 'D7'))
+ entry = next(e for e in runner.session_store._entries.values()
+ if e.origin is not None and e.origin.chat_id == 'D7')
+ assert await admit_route_wake(runner, adapter, entry.origin, 'scheduled tick', 'loop') is True
+ await async_wait_until(lambda: 'scheduled tick' in executed, timeout=20, what='the wake ran')
+ await async_wait_until(lambda: any(_is_reply('reply scheduled tick')(a) for a in _actions(outgoing)),
+ timeout=20, what='the wake answered')
+ # A bracket would have reacted and refreshed typing when the wake started, before its reply.
+ assert [a for a in _actions(outgoing) if a.get('op') == 'react'] == before_reacts
+ assert len(_heartbeats(outgoing, 'D7')) == before_typing