The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a result the chat started on an old conversation lands in it once the app used it
Tekniumeb8e189575f2
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.pyindex e92893d34c5..527785ed3c0 100644--- a/gateway/run_notifications.py+++ b/gateway/run_notifications.py@@ -913,9 +913,11 @@ class GatewayNotificationsMixin(GatewayUpdateNotificationsMixin, GatewayNotificagateway route or a refused notice pinned to a permanently-gone session (``_watch_pin_gone``).Not transactional: a crash after acceptance can replay (at-least-once)."""+ from gateway.session_detached import follow_detached_pinfrom gateway.session_local_recovery import restore_completion_routefrom gateway.wake import WakeNotAccepted, adapter_supports_push, admit_internal_eventrestore_completion_route(self, str(evt.get("session_key") or "")) # watch notices and heartbeats too+ queued, evt = evt, await follow_detached_pin(self, evt) # the drain reads its verdict off *queued*source = await asyncio.to_thread(self._build_process_event_source, evt)if not source:# API-server sessions bind the RAW X-Hermes-Session-Id key, not a structured ``agent:...`` key.@@ -998,7 +1000,7 @@ class GatewayNotificationsMixin(GatewayUpdateNotificationsMixin, GatewayNotificaif pin_gone and not raise_not_accepted:return Noneif not raise_not_accepted:- evt["_refusal_permanent"] = exc.permanent # the drain counts only permanent refusals+ queued["_refusal_permanent"] = exc.permanent # the drain counts only permanent refusalslogger.warning("Watch notification not admitted for %s chat=%s: %s",platform_name, source.chat_id, exc)# Durable callers refund the claim; ordinary watch callers just requeue.@@ -1272,6 +1274,8 @@ class GatewayNotificationsMixin(GatewayUpdateNotificationsMixin, GatewayNotificaif not should_surface_notification(evt):return None # Suppressed noise is terminal, not a consumed process result.restore_completion_route(self, str(evt.get("session_key") or ""))+ from gateway.session_detached import follow_detached_pin+ evt = await follow_detached_pin(self, evt)identity = self._completion_delivery_identity(evt)claim = self._CompletionClaim()accepted = identity_claimed = refused = Falsediff --git a/gateway/session_automation.py b/gateway/session_automation.pyindex 626e033e7d9..ee43c7b5d6b 100644--- a/gateway/session_automation.py+++ b/gateway/session_automation.py@@ -28,7 +28,8 @@ def completion_admission(runner, event):authority = active_authority(runner)if authority is None:return None- entry = runner.session_store.lookup_by_session_key(str(event.get('session_key') or ''))+ from gateway.session_detached import route_entry+ entry = route_entry(authority, str(event.get('session_key') or ''))if entry is None:return Nonefrom hermes_state_runtime import list_session_admissions@@ -46,10 +47,11 @@ async def deliver_heartbeat(runner, event):way in withdraws it once it is in, and a tick checked after it sees it. True when admitted, Noneto drop it, False to requeue the original event."""from gateway.run import _format_gateway_process_notification+ from gateway.session_detached import follow_detached_pinasync with _heartbeat_lock(runner):for _attempt in range(2):try:- prepared = await prepare_heartbeat(runner, event)+ prepared = await prepare_heartbeat(runner, await follow_detached_pin(runner, event))except Exception:# One tick's failure must not drop the rest of the drained events.logger.exception("Heartbeat preparation error; the tick is requeued")diff --git a/gateway/session_detached.py b/gateway/session_detached.pyindex 76b6ff87640..4845a46a081 100644--- a/gateway/session_detached.py+++ b/gateway/session_detached.py@@ -189,6 +189,46 @@ def own_detached_key(key, session_id) -> bool:return isinstance(key, str) and detached_session_id(key) == session_id+async def follow_detached_pin(runner, evt):+ """*evt* (a background result) on its pinned conversation's detached key, else *evt* itself.++ The chat's turn on a conversation started it, and the chat has moved on since, but the+ conversation is still open: the app used it after the chat's ``/new`` (a row the ``/new`` left+ ended stays a boundary, and its result is dropped once). The result lands in that conversation,+ for its app viewers, never in the chat's current one, and is never refused there on every retry+ (#141562). A conversation not mounted (a restart) mounts off the chat first."""+ key = str(evt.get('session_key') or '')+ pinned = str(evt.get('parent_session_id') or '').strip()+ from gateway.session_authorities import all_authorities+ if not key or not pinned or detached_session_id(key) or not all_authorities(runner):+ return evt+ store = runner.session_store+ authority = _route_authority(runner, store, key)+ entry = store.lookup_by_session_key(key) if authority is not None else None+ if authority is None or entry is None:+ return evt+ verdict, _owner, target = await runner._classify_completion_owner(pinned, key)+ session_id = authority.logical_owner(target) if verdict == 'deliver' else None+ if session_id is None or session_id == authority.logical_owner(entry.session_id):+ return evt+ row = authority.db.get_session(target)+ if row is None or row.get('ended_at'):+ return evt+ if session_id not in authority.sessions:+ from gateway.session_authorities import owner_scope+ from gateway.session_route_recovery import restore_routed_session+ from hermes_state_runtime import RuntimeStoreError+ try:+ with owner_scope(authority):+ restore_routed_session(authority, session_id)+ except RuntimeStoreError: # draining: the drain retries it+ return evt+ live = authority.sessions.get(session_id)+ if live is None or live.route != detached_key(key, session_id):+ return evt+ return {**evt, 'session_key': live.route}++def detached_live_source(runner, key):"""The source of the conversation still live on detached key *key*, else None."""from gateway.session_authorities import active_authoritydiff --git a/tests/gateway/test_detached_conversation_results.py b/tests/gateway/test_detached_conversation_results.pyindex b4f3b9a5cd6..62f13a4634b 100644--- a/tests/gateway/test_detached_conversation_results.py+++ b/tests/gateway/test_detached_conversation_results.py@@ -6,11 +6,12 @@ DiscordAdapter (``send`` recorded), SessionAuthority, drain and SessionStore oveagent run is the stand-in of ``test_authority_lane_moves_on``."""import asyncio+import timefrom pathlib import Pathimport pytest-from tests.gateway.test_authority_lane_moves_on import _chat+from tests.gateway.test_authority_lane_moves_on import _app_turn, _chatfrom tests.gateway.test_detached_conversation_lifecycle import _moved_onfrom tests.waiting import async_wait_until@@ -55,3 +56,40 @@ async def test_a_note_into_the_old_conversation_leaves_the_row_the_chats_new_endawait asyncio.wait_for(authority.sessions[a].task, 10)assert ran[ran_before:] == []assert authority.db.get_session(a)['end_reason'] == 'session_reset'+++def _chat_started(kind, lane, a):+ """A result of work the chat's own turn on A started before its ``/new``: pinned to A, on the chat's route."""+ if kind == 'delegation':+ return {'type': 'async_delegation', 'delegation_id': 'deleg-1', 'session_key': lane,+ 'parent_session_id': a, 'dispatched_at': 1.0, 'summary': 'delegated result', 'status': 'completed'}+ return {'type': 'completion', 'event_id': 'c-1', 'session_id': 'proc_chat', 'started_at': 1000.0,+ 'session_key': lane, 'parent_session_id': a, 'command': 'make', 'exit_code': 0, 'output': 'built',+ 'platform': 'discord', 'chat_id': '42', 'chat_type': 'dm', 'user_id': '42', 'emitted_at': time.time()}++[email protected]('kind', ['delegation', 'process'])+async def test_a_result_the_chat_started_on_the_old_conversation_lands_in_it_once_the_app_used_it(monkeypatch, kind):+ """N2b: the app's turn reopened A after the chat's ``/new``. A result of work the chat's turn on A+ started lands in A once (a note, no viewer), never in the chat, and is not refused on every retry."""+ import tools.async_delegation as ad+ runner, _adapter, authority, _source, sent, ran, _gates, lane, ref_a = await _moved_on(monkeypatch)+ a = ref_a.session_id+ assert await _app_turn(authority, ref_a, 'app on A') == ('terminal', 'completed')+ evt = _chat_started(kind, lane, a)+ chat_before, ran_before = len(sent), len(ran)+ if kind == 'delegation':+ ad._persist_dispatch(evt)+ ad._persist_completion(evt, {'status': 'completed', 'summary': evt['summary']})+ results = [await runner._deliver_completion_notification('delegated result', dict(evt)) for _ in range(2)]+ assert results == [True, None]+ assert ad.get_durable_delegation('deleg-1')['delivery_state'] == 'delivered'+ text = 'delegated result'+ else:+ assert await runner._inject_watch_notification('[process proc_chat finished]', evt) is True+ assert '_refusal_permanent' not in evt+ text = '[process proc_chat finished]'+ await async_wait_until(lambda: _noted(authority, a, text), timeout=10, what='the result in A')+ assert ran[ran_before:] == []+ assert sent[chat_before:] == [], f'the chat got the old conversation\'s result: {sent[chat_before:]}'