The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a Stop from the chat or the app reaches the app's turn after the chat resumes its conversation
Tekniumc66bf2c5e476
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 5f1d9b28d3f..4c28bf36964 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -291,9 +291,10 @@ class SessionAuthority:forget_detached(self, left)def agent(self, ref):+ from gateway.session_detached import running_keylive = self.sessions[ref.session_id]lookup = getattr(self.runner, '_resident_agent_for', None) or self.runner._cached_agent_for- return lookup(live.route)+ return lookup(running_key(self.runner, live.route, ref.session_id))def _pending_rows(self, ref):"""Pending admissions as the event stream presents them: a settlement committed but not yet@@ -942,9 +943,10 @@ class SessionAuthority:"""The route's running slot holds a real agent (not the claim's pending sentinel), so theStop above reached the turn's own agent, not a cached one it may still replace."""from gateway.run import _AGENT_PENDING_SENTINEL+ from gateway.session_detached import running_keylive = self.sessions[ref.session_id]running = getattr(self.runner, '_running_agents', None) or {}- agent = running.get(live.route)+ agent = running.get(running_key(self.runner, live.route, ref.session_id))return agent is not None and agent is not _AGENT_PENDING_SENTINELdef steer_agent(self, ref, generation, text):diff --git a/gateway/session_detached.py b/gateway/session_detached.pyindex 3f3405dcc17..f81c0a2fcb0 100644--- a/gateway/session_detached.py+++ b/gateway/session_detached.py@@ -90,6 +90,21 @@ def drop_owner_hints(store, key) -> None:hints.pop(session_id, None)+def running_key(runner, route, session_id) -> str:+ """The key a turn of *session_id* runs under: its detached key while a turn that started there+ still runs (the chat took the conversation back meanwhile), so a Stop from the chat or the app+ reaches it; else *route*."""+ key = detached_key(route, session_id)+ return key if key in (getattr(runner, '_running_agents', None) or {}) else route+++def chat_running_key(runner, route, entry) -> str:+ """``running_key`` for the conversation the chat's *route* names (*entry*, its routing entry)."""+ from gateway.session_authorities import active_authority+ authority = active_authority(runner)+ return route if authority is None else running_key(runner, route, authority.logical_owner(entry.session_id))++def session_env_source(runner, source):"""The source a turn's session variables (``HERMES_SESSION_PLATFORM``, ``_CHAT_ID``, ...) name.A conversation its chat moved past binds the local view a Desktop session's turn bindsdiff --git a/gateway/slash_commands.py b/gateway/slash_commands.pyindex a4f6feb393f..00877b04f95 100644--- a/gateway/slash_commands.py+++ b/gateway/slash_commands.py@@ -440,13 +440,16 @@ class GatewaySlashCommandsMixin(await self._interrupt_and_clear_session(key, source, interrupt_reason=_INTERRUPT_REASON_STOP,invalidation_reason=invalidation_reason)- agent = self._running_agents.get(session_key)+ # A turn the app started while the chat was elsewhere still runs on its own key (/resume).+ from gateway.session_detached import chat_running_key+ run_key = chat_running_key(self, session_key, session_entry)+ agent = self._running_agents.get(run_key)if agent is _AGENT_PENDING_SENTINEL: # force-clean the sentinel so the session is unlocked- await _stop(session_key, "stop_command_pending")- logger.info("STOP (pending) for session %s — sentinel cleared", session_key)+ await _stop(run_key, "stop_command_pending")+ logger.info("STOP (pending) for session %s — sentinel cleared", run_key)return EphemeralReply(t("gateway.stop.stopped_pending"))if agent: # force-clean the session lock so a truly hung agent doesn't keep it forever- await _stop(session_key, "stop_command_handler")+ await _stop(run_key, "stop_command_handler")return EphemeralReply(t("gateway.stop.stopped"))# No run under the caller's own key: a live turn in THIS chat may still carry a differentlydiff --git a/tests/gateway/test_detached_conversation_lifecycle.py b/tests/gateway/test_detached_conversation_lifecycle.pyindex 1600984fbf3..58a94ec495b 100644--- a/tests/gateway/test_detached_conversation_lifecycle.py+++ b/tests/gateway/test_detached_conversation_lifecycle.py@@ -5,11 +5,12 @@ reaches the chat, and the old one stays fully usable from the apps. Real Gateway(``send`` recorded), SessionAuthority, drain and SessionStore over a real SessionDB; the agent run isthe stand-in of ``test_authority_lane_moves_on``."""+import asynciofrom types import SimpleNamespaceimport pytest-from tests.gateway.test_authority_lane_moves_on import _app_turn, _chat, _gateway+from tests.gateway.test_authority_lane_moves_on import _app, _app_turn, _chat, _gatewayfrom tests.waiting import async_wait_until@@ -81,6 +82,37 @@ async def test_the_old_conversation_is_live_again_once_the_app_uses_it(monkeypatassert (row['ended_at'], row['end_reason']) == (None, None)+async def test_a_stop_from_either_side_reaches_the_apps_turn_after_the_chat_resumes_it(monkeypatch):+ """F5: the app's turn on A is running when the chat ``/resume``s A. That turn keeps its own key;+ the app's Stop and the chat's /stop both still reach it."""+ from gateway.platforms.event import MessageEvent+ from gateway.session_contract import Submission+ runner, adapter, authority, source, sent, ran, gates, lane, ref_a = await _moved_on(monkeypatch)+ stops = []+ agent = SimpleNamespace(interrupt=lambda *a, **k: stops.append('interrupt'), session_id=ref_a.session_id)+ prepare = runner._hmwa_prepare_turn++ async def adopting(event, source, session_entry, session_key, *args):+ if event.text == 'slow app turn':+ runner._running_agents[session_key] = agent # the turn's agent, as a real build installs it+ return await prepare(event, source, session_entry, session_key, *args)+ monkeypatch.setattr(runner, '_hmwa_prepare_turn', adopting)+ gates['slow app turn'] = asyncio.Event()+ await authority.submit(_app(), Submission('slow', ref_a, {'text': 'slow app turn'}, 'queue'))+ await async_wait_until(lambda: ran and ran[-1][0] == 'slow app turn', what='the app turn to start')+ await _chat(adapter, source, sent, '/resume First chat')+ assert authority.sessions[ref_a.session_id].route == lane++ assert authority._runs_own_agent(ref_a) and authority.agent(ref_a) is agent # the app's Stop target+ before = len(sent)+ await adapter.handle_message(MessageEvent(text='/stop', source=source, message_id='stop'))+ await async_wait_until(lambda: len(sent) > before, what='the /stop reply')+ from agent.i18n import t+ assert sent[before:] != [t('gateway.stop.no_active')] and stops+ gates['slow app turn'].set()++@pytest.mark.asyncioasync def test_the_chats_resume_drops_the_agent_the_app_cached_for_the_old_conversation(monkeypatch):"""F6: the agent cached under A's detached key goes when the chat takes A back, instead of being