Skip to content

The agent that grows with you

fix(gateway): /discard finds the lost turn of a conversation brought back by /resume

Tekniuma3e9c589be6c
diff --git a/gateway/slash_commands_session.py b/gateway/slash_commands_session.py
index 91abfce9d73..e5d40a4cfcd 100644
--- a/gateway/slash_commands_session.py
+++ b/gateway/slash_commands_session.py
@@ -184,8 +184,15 @@ class GatewaySessionCommandsMixin:
authority = active_authority(self)
session_key = self._session_key_for_source(event.source)
sid = authority.logical_owner(self.session_store.peek_session_id(session_key)) if authority else None
- if not sid or sid not in authority.sessions:
+ if not sid:
return t("gateway.discard.nothing")
+ if sid not in authority.sessions:
+ # A conversation /resume brought back after a restart is the chat's route but not yet
+ # live: publish it through the same route seam an inbound message uses (review #141357).
+ from functools import partial
+ from gateway.session_runtime_workers import tracked_write
+ sid = authority._publish_route(
+ event.source, *await tracked_write(authority, partial(authority._reserve_route, event.source))).session_id
return await discard_lost_turns(authority, sid)
async def _handle_reset_command(self, event: MessageEvent) -> str | EphemeralReply:
diff --git a/tests/gateway/test_messaging_discard_reach.py b/tests/gateway/test_messaging_discard_reach.py
index 57bc0daa893..ffd4cf53672 100644
--- a/tests/gateway/test_messaging_discard_reach.py
+++ b/tests/gateway/test_messaging_discard_reach.py
@@ -3,6 +3,9 @@
Slack has no native ``/discard`` (its slash cap), so the pause notice must name ``/hermes discard``;
a conversation brought back by ``/resume`` after a restart is not in the owner's live map, and
``/discard`` must still find its lost turn. Real runner dispatch and SQLite; transport stubbed."""
+import asyncio
+
+import pytest
def test_slack_pause_notice_names_the_registered_umbrella_command():
@@ -18,3 +21,65 @@ def test_slack_pause_notice_names_the_registered_umbrella_command():
live = SimpleNamespace(source=SessionSource(platform=platform, chat_id='D42'), pause_notified=False)
notice = pause_notice(SimpleNamespace(sessions={'s': live}), SessionRef('p', 's'), 'unknown_execution')
assert expected in notice, notice
+
+
+async def test_discard_after_resume_into_a_cold_conversation_resolves_its_lost_turn(tmp_path, monkeypatch):
+ from gateway.config import GatewayConfig, Platform, PlatformConfig
+ from gateway.platforms.base import SendResult
+ from gateway.platforms.event import MessageEvent
+ from gateway.run import GatewayRunner
+ from gateway.run_runtime import recover_profile_native_sessions
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_ingress_context import native_callback, register_transport_home
+ from hermes_constants import get_hermes_home
+ from hermes_state_runtime import claim_session_input, get_session_admission
+ from tests.gateway.test_command_bypass_active_session import _StubAdapter
+
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ monkeypatch.setenv('TELEGRAM_ALLOWED_USERS', '42')
+ monkeypatch.setattr('gateway.run._hermes_home', tmp_path)
+ runner = GatewayRunner(GatewayConfig(multiplex_profiles=False, sessions_dir=tmp_path / 'sessions'))
+ adapter = _StubAdapter(PlatformConfig(enabled=True, token='fixture', typing_indicator=False), Platform.TELEGRAM)
+ sent = []
+
+ async def send(chat_id, content, **kwargs):
+ sent.append(content)
+ return SendResult(success=True, message_id=str(len(sent)))
+ monkeypatch.setattr(adapter, 'send', send)
+ adapter.gateway_runner = runner
+ runner.adapters = {Platform.TELEGRAM: adapter}
+ runner._wire_adapter_handlers(adapter)
+ register_transport_home(runner, None, tmp_path)
+ source = adapter.build_source(chat_id='42', chat_type='dm', user_id='42')
+ first = await initialize_session_authority(runner, profile_id=str(tmp_path), instance_id='old')
+ first._schedule = lambda ref: None
+ previous = first.register(source).session_id
+ first.db.append_message(previous, 'user', 'older conversation')
+ runner.session_store.get_or_create_session(source, force_new=True)
+ head = MessageEvent(text='lost human input', source=source, message_id='head')
+ with native_callback(runner, head, get_hermes_home()):
+ receipt = await first.admit_native(head)
+ sid = receipt.ref.session_id
+ claimed = claim_session_input(first.db, epoch=first.epoch, session_id=sid)
+ key = runner._session_key_for_source(source)
+ try:
+ # A restart fences the turn unknown; /resume moves away, a second restart, /resume back:
+ # the historical conversation is the chat's route again but not in the owner's live map.
+ recovered = await initialize_session_authority(runner, profile_id=str(tmp_path), instance_id='mid')
+ recovered._schedule = lambda ref: None
+ await recover_profile_native_sessions(runner, recovered)
+ await runner._handle_message(MessageEvent(text='/resume ' + previous, source=source, message_id='away'))
+ second = await initialize_session_authority(runner, profile_id=str(tmp_path), instance_id='third')
+ second._schedule = lambda ref: None
+ await recover_profile_native_sessions(runner, second)
+ await runner._handle_message(MessageEvent(text='/resume ' + sid, source=source, message_id='back'))
+ assert runner.session_store.peek_session_id(key) == sid and sid not in second.sessions
+ assert get_session_admission(second.db, admission_id=claimed['admission_id'])['status'] == 'unknown'
+ await adapter.handle_message(MessageEvent(text='/discard', source=source, message_id='discard'))
+ if adapter._background_tasks:
+ await asyncio.wait_for(asyncio.gather(*list(adapter._background_tasks)), 10)
+ row = get_session_admission(second.db, admission_id=claimed['admission_id'])
+ assert (row['status'], row['outcome']) == ('terminal', 'interrupted'), (row, sent)
+ finally:
+ runner.session_store.close_all_db_handles()