Skip to content

The agent that grows with you

fix(gateway): a background result of the app's turn on an old conversation reaches the app

Tekniume2dd482a70cf
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.py
index 5af54565ae1..340cd2bc251 100644
--- a/gateway/run_notifications.py
+++ b/gateway/run_notifications.py
@@ -857,6 +857,9 @@ class GatewayNotificationsMixin(GatewayUpdateNotificationsMixin, GatewayNotifica
Platform.RELAY adapter fronts N logical platforms; native wins), literal ``p.value`` scan as
fallback for minimal runner stubs / exotic platform strings when the resolver can't run."""
from gateway.delivery import resolve_delivery_transport
+ from gateway.session_detached import detached_route_of
+ if detached_route_of(source): # an old conversation's app viewers (gateway/session_detached.py)
+ return self._delivery_adapter_for(source)
if source is not None:
owner = self._transport_owner(source)
if owner is not None:
diff --git a/gateway/session_automation.py b/gateway/session_automation.py
index 93d94fcce69..9ad69bc4590 100644
--- a/gateway/session_automation.py
+++ b/gateway/session_automation.py
@@ -277,8 +277,9 @@ def _owned_by(db, session_id, current):
def _owner(runner, event, authority):
+ from gateway.session_detached import route_entry
route = event.metadata.get('gateway_session_key') or runner.session_store._generate_session_key(event.source)
- entry = runner.session_store.lookup_by_session_key(route)
+ entry = route_entry(authority, route)
if entry is None or entry.suspended:
raise RuntimeStoreError('not_found')
if runner.session_store._generate_session_key(event.source) != route:
@@ -364,7 +365,8 @@ def snapshot_automation(authority, adapter, event, identity):
notification = (automation_notification_metadata(event.metadata) | automation_display_metadata(event.metadata)
| _tick_metadata(event.metadata))
entry = _owner(runner, event, authority)
- if event.source.platform == Platform.LOCAL:
+ from gateway.session_detached import detached_route_of
+ if event.source.platform == Platform.LOCAL or detached_route_of(event.source):
return snapshot_local_automation(authority, adapter, event, identity, entry)
from gateway.session_envelope import restore_native
owner = authority.logical_owner(entry.session_id)
@@ -422,13 +424,26 @@ def check_automation_route(runner, payload, session_id, available_source, adapte
return event.source, entry.session_key
-def snapshot_local_automation(authority, adapter, event, identity, entry):
+def _local_automation_owner(authority, adapter, event, entry):
+ """``(ref, live)`` a local automation lands on. A conversation its chat moved past takes its
+ results as a Desktop session does (gateway/session_detached.py): its app viewers get them."""
+ from gateway.session_detached import detached_live, detached_route_of
+ if detached_route_of(event.source):
+ found = detached_live(authority, entry.session_key)
+ if found is None or authority.runner._adapter_for_source(found[1].source) is not adapter:
+ raise RuntimeStoreError('permission_denied')
+ return found
from gateway.session_local_recovery import restore_local_session
ref = restore_local_session(authority, event.source.chat_id)
live = authority.sessions[ref.session_id]
if (live.source is not event.source or not adapter.authorize_source(event.source)
or authority.runner._adapter_for_source(live.source) is not adapter):
raise RuntimeStoreError('permission_denied')
+ return ref, live
+
+
+def snapshot_local_automation(authority, adapter, event, identity, entry):
+ ref, _live = _local_automation_owner(authority, adapter, event, entry)
descriptor = {'identity': identity, 'owner': ref.session_id,
'route': entry.session_key, 'target': entry.session_id}
descriptor.update(automation_notification_metadata(event.metadata))
@@ -456,7 +471,8 @@ def check_local_automation(authority, ref, row, *, route=None):
or descriptor['owner'] != ref.session_id or descriptor['route'] != route
or descriptor['identity'] != row['request_id']):
raise RuntimeStoreError('permission_denied')
- entry = authority.runner.session_store.lookup_by_session_key(route)
+ from gateway.session_detached import route_entry
+ entry = route_entry(authority, route)
if (entry is None or entry.suspended or (entry.session_id != descriptor['target']
and authority.db.get_compression_tip(descriptor['target']) != entry.session_id)):
raise RuntimeStoreError('admission_conflict')
@@ -466,7 +482,8 @@ def restore_local_automation(authority, ref, row):
check_local_automation(authority, ref, row)
live = authority.sessions[ref.session_id]
descriptor = row['payload']['local_automation_v1']
- entry = authority.runner.session_store.lookup_by_session_key(live.route)
+ from gateway.session_detached import route_entry
+ entry = route_entry(authority, live.route)
event = MessageEvent(text=row['payload']['text'], source=live.source, internal=True,
message_id=descriptor['identity'], metadata={'gateway_session_key': live.route,
'gateway_session_id': entry.session_id})
diff --git a/gateway/session_detached.py b/gateway/session_detached.py
index f81c0a2fcb0..040e1ef0d88 100644
--- a/gateway/session_detached.py
+++ b/gateway/session_detached.py
@@ -174,6 +174,26 @@ def recover_detached_sessions(authority, pending):
return scheduled
+def detached_live(authority, route):
+ """``(ref, live)`` of the conversation still live on detached key *route*, else None."""
+ from gateway.session_contract import SessionRef
+ session_id = detached_session_id(route)
+ live = authority.sessions.get(session_id) if session_id else None
+ if live is None or live.route != route:
+ return None
+ return SessionRef(authority.profile_id, session_id), live
+
+
+def route_entry(authority, route):
+ """The routing entry *route* names: the store's, or a detached key's live conversation (a
+ background result it started finds it there, never on the chat's route)."""
+ store = authority.runner.session_store
+ entry = store.lookup_by_session_key(route)
+ if entry is None and (found := detached_live(authority, route)) is not None:
+ return detached_entry(store, found[1].source)
+ return entry
+
+
def detached_entry(store, source):
"""The routing entry a detached *source* resolves to: its own conversation, at the compression
tip a turn writes to. Never stored: the chat's route stays the only one this conversation has."""
diff --git a/tests/gateway/test_detached_conversation_lifecycle.py b/tests/gateway/test_detached_conversation_lifecycle.py
index 58a94ec495b..a797c07b9c7 100644
--- a/tests/gateway/test_detached_conversation_lifecycle.py
+++ b/tests/gateway/test_detached_conversation_lifecycle.py
@@ -125,3 +125,45 @@ async def test_the_chats_resume_drops_the_agent_the_app_cached_for_the_old_conve
await _chat(adapter, source, sent, '/resume First chat')
assert authority.sessions[ref_a.session_id].route == lane
assert key not in runner._agent_cache
+
+
[email protected]('viewer', [False, True], ids=['no-viewer', 'app-viewing'])
+async def test_a_background_result_of_the_old_conversation_reaches_the_app_not_the_chat(monkeypatch, viewer):
+ """A process the app's turn on A started finishes: its result lands in A (a note in its history
+ with no viewer, a turn of A with the app watching), never in the chat, and is not retried."""
+ import time
+ from gateway.session import build_session_context
+ from gateway.session_context import get_session_env
+ from hermes_state_runtime import list_session_admissions
+ runner, _adapter, authority, _source, sent, ran, _gates, _lane, ref_a = await _moved_on(monkeypatch)
+ assert await _app_turn(authority, ref_a, 'start a job') == ('terminal', 'completed')
+ live = authority.sessions[ref_a.session_id]
+ if viewer:
+ await authority.attach(_app(), ref_a)
+ entry = runner.session_store.get_or_create_session(live.source)
+ with runner._session_env_scope(build_session_context(live.source, runner.config, entry)):
+ # What the process registry records for a process the turn starts.
+ env = {name: get_session_env(f'HERMES_SESSION_{name}') for name in ('KEY', 'PLATFORM', 'CHAT_ID', 'CHAT_TYPE')}
+ evt = {'type': 'completion', 'event_id': 'e1', 'session_id': 'proc_1', 'started_at': time.time(),
+ 'session_key': env['KEY'], 'parent_session_id': ref_a.session_id, 'command': 'sleep 1',
+ 'exit_code': 0, 'output': 'done', 'platform': env['PLATFORM'], 'chat_id': env['CHAT_ID'],
+ 'chat_type': env['CHAT_TYPE'], 'user_id': '42'}
+ chat_before, ran_before = len(sent), len(ran)
+
+ assert await runner._inject_watch_notification('[process proc_1 finished]', evt) is True
+
+ def settled():
+ rows = list_session_admissions(authority.db, session_id=ref_a.session_id, pending_only=False)
+ return [row for row in rows if row['principal_id'] == 'automation:' + live.route
+ and row['status'] == 'terminal']
+ rows = await async_wait_until(settled, timeout=10, what="the result's admission on A")
+ assert rows[0]['outcome'] == 'completed'
+ if viewer:
+ await async_wait_until(lambda: len(ran) > ran_before, what='the result turn')
+ assert [turn[1:] for turn in ran[ran_before:]] == [(ref_a.session_id, live.route)]
+ else:
+ assert ran[ran_before:] == []
+ assert any('[process proc_1 finished]' in str(message.get('content'))
+ for message in authority.db.get_messages(ref_a.session_id))
+ assert sent[chat_before:] == [], f'the chat got the old conversation\'s result: {sent[chat_before:]}'