The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a secondary profile's old conversation finds its live source through its key
Teknium731670093001
diff --git a/gateway/session_automation.py b/gateway/session_automation.pyindex ee43c7b5d6b..f19db6fcc84 100644--- a/gateway/session_automation.py+++ b/gateway/session_automation.py@@ -434,7 +434,8 @@ def _local_automation_owner(authority, adapter, event, entry):from gateway.session_detached import detached_live, detached_route_ofif 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:+ if (found is None or found[1].source is not event.source or not adapter.authorize_source(event.source)+ or authority.runner._adapter_for_source(found[1].source) is not adapter):raise RuntimeStoreError('permission_denied')return foundfrom gateway.session_local_recovery import restore_local_sessiondiff --git a/gateway/session_detached.py b/gateway/session_detached.pyindex 4845a46a081..d8c33f6df65 100644--- a/gateway/session_detached.py+++ b/gateway/session_detached.py@@ -59,9 +59,10 @@ def detach(authority, live, session_id) -> None:returnfrom gateway.session_identity import replace_sourcefrom gateway.session_local_recovery import local_adapter- local_adapter(authority) # its delivery; a messaging-only gateway has none yet+ adapter = local_adapter(authority) # its delivery; a messaging-only gateway has none yetlive.route = detached_key(live.route, session_id)live.source = replace_source(live.source, detached_route=live.route)+ adapter.register_source(live.source) # what admits its background results (``authorize_source``)def lane_source(source):@@ -230,9 +231,10 @@ async def follow_detached_pin(runner, evt):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_authority- authority = active_authority(runner) if detached_session_id(key) else None+ """The source of the conversation still live on detached key *key*, else None. The key's+ namespace names the owning profile: this runs before any profile scope is bound+ (``_completion_event_scope`` derives the scope from it)."""+ authority = _route_authority(runner, runner.session_store, key) if detached_session_id(key) else Nonefound = detached_live(authority, key) if authority is not None else Nonereturn found[1].source if found is not None else Nonediff --git a/gateway/session_local.py b/gateway/session_local.pyindex 0a2ec7cdf79..065036f4813 100644--- a/gateway/session_local.py+++ b/gateway/session_local.py@@ -30,8 +30,15 @@ class LocalSessionAdapter(BasePlatformAdapter):self.sources = {}self.policies = {}+ @staticmethod+ def _source_key(source):+ # A conversation its chat moved past keeps the chat's id, which every other one of that chat+ # shares: its own key names it (gateway/session_detached.py).+ from gateway.session_detached import detached_route_of+ return detached_route_of(source) or source.chat_id+def authorize_source(self, source):- saved = self.sources.get(source.chat_id)+ saved = self.sources.get(self._source_key(source))if saved is None:return Falseoriginal, identity = saved@@ -43,7 +50,7 @@ class LocalSessionAdapter(BasePlatformAdapter):return source.platform, source.chat_id, source.user_id, source.profile, source.chat_typedef register_source(self, source):- self.sources[source.chat_id] = source, self._identity(source)+ self.sources[self._source_key(source)] = source, self._identity(source)async def connect(self, *, is_reconnect=False):return Truediff --git a/tests/gateway/test_detached_conversation_results.py b/tests/gateway/test_detached_conversation_results.pyindex 62f13a4634b..4901fad9cbc 100644--- a/tests/gateway/test_detached_conversation_results.py+++ b/tests/gateway/test_detached_conversation_results.py@@ -93,3 +93,54 @@ async def test_a_result_the_chat_started_on_the_old_conversation_lands_in_it_oncawait 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:]}'+++async def test_a_secondary_profiles_old_conversation_gets_its_result_after_the_source_cache_forgot_it(+ tmp_path, monkeypatch):+ """N3, two profiles in one process: a process the app's turn on a ``fitness`` conversation A+ started finishes after the runner's bounded source cache dropped A. Its key names the profile, so+ the event resolves A's live source and binds ``fitness``'s scope, unscoped as the drain starts,+ and the result is written into A in ``fitness``'s store."""+ import hermes_state+ from gateway.config import GatewayConfig, Platform+ from gateway.run import GatewayRunner+ from gateway.session import SessionSource+ from gateway.session_authorities import SessionAuthorities+ from gateway.session_authority import LiveSession, initialize_session_authority+ from gateway.session_detached import detach+ from hermes_constants import get_hermes_home+ from hermes_state import SessionDB+ root = tmp_path / 'hermes'+ profile = root / 'profiles' / 'fitness'+ profile.mkdir(parents=True)+ (profile / 'config.yaml').write_text('{}\n', encoding='utf-8')+ monkeypatch.setenv('HERMES_HOME', str(root))+ monkeypatch.setattr(hermes_state, 'DEFAULT_DB_PATH', hermes_state._IMPORT_DEFAULT_DB_PATH)+ runner = GatewayRunner(GatewayConfig(multiplex_profiles=True))+ launch = await initialize_session_authority(runner, profile_id=str(root), instance_id='owner',+ db=SessionDB(root / 'state.db'))+ fitness = await initialize_session_authority(runner, profile_id=str(profile), instance_id='owner',+ db=SessionDB(profile / 'state.db'), register=False)+ runner.session_authorities = SessionAuthorities(root, multiplexed=True)+ runner.session_authorities.add(root, launch)+ runner.session_authorities.add(profile, fitness, name='fitness')+ source = SessionSource(platform=Platform.TELEGRAM, chat_id='555', chat_type='dm', user_id='u1', profile='fitness')+ route = runner.session_store._generate_session_key(source)+ assert route.startswith('agent:fitness:')+ a = 'conversation-a'+ fitness.db.create_session(a, source='telegram', session_key=route)+ live = fitness.sessions[a] = LiveSession(source, route)+ detach(fitness, live, a) # the chat moved on; the app keeps A+ evt = {'type': 'completion', 'event_id': 'c-1', 'session_id': 'proc_1', 'started_at': 1000.0,+ 'session_key': live.route, 'parent_session_id': a, 'command': 'make', 'exit_code': 0,+ 'output': 'built', 'platform': 'local', 'chat_id': a, 'chat_type': 'dm', 'user_id': 'u1',+ 'emitted_at': time.time()}+ runner._session_sources.clear()++ assert runner._build_process_event_source(evt) is live.source+ async with runner._completion_event_scope(evt):+ assert Path(get_hermes_home()) == profile+ assert await runner._inject_watch_notification('[process proc_1 finished]', evt) is True+ await async_wait_until(lambda: _noted(fitness, a, '[process proc_1 finished]'), timeout=10,+ what="the result in fitness's A")