The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a secondary profile's old conversation keeps its history, and the chat taking it back drops its app agent
Teknium0f0f8e6db284
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex df00fe27181..9313c6abf06 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -280,12 +280,15 @@ class SessionAuthority:*sid*'s own mount moves onto the route: a detached one comes back, a local one ``/handoff``took over or one another chat held (a cross-chat ``/resume``) follows it, so its open viewers'turns and Stops reach the chat that holds it now (#143286)."""- from gateway.session_detached import detach+ from gateway.session_detached import detach, forget_detachedfor other_sid, other in self.sessions.items():if other.route == route and other_sid != sid:detach(self, other, other_sid)if (live := self.sessions.get(sid)) is not None and live.route != route:+ left = live.route if live.detached else Nonelive.source, live.route = source, route+ if left is not None:+ forget_detached(self, left)def agent(self, ref):live = self.sessions[ref.session_id]diff --git a/gateway/session_detached.py b/gateway/session_detached.pyindex b67a8491d2c..e86cfc59154 100644--- a/gateway/session_detached.py+++ b/gateway/session_detached.py@@ -71,6 +71,23 @@ def lane_source(source):return replace_source(source, detached_route=None)+def forget_detached(authority, key) -> None:+ """*key* names no live conversation any more (it came back onto its chat, or retired): its+ cached agent commits and goes, as at any boundary (a later idle eviction would commit it while the+ conversation runs elsewhere), and the store forgets the ids it owned (``detached_entry``)."""+ runner = authority.runner+ evict = getattr(runner, '_evict_cached_agent_at_boundary', None)+ if evict is not None:+ evict(key)+ drop_owner_hints(runner.session_store, key)+++def drop_owner_hints(store, key) -> None:+ hints = getattr(store, '_session_owner_hints', None) or {}+ for session_id in [sid for sid, owner in list(hints.items()) if owner == key]:+ hints.pop(session_id, None)++def _route_authority(runner, store, route):"""The authority owning *route*: its key names the profile, whatever scope the writer runs in."""from gateway.session_authorities import authority_for_home@@ -137,6 +154,10 @@ def detached_entry(store, source):db = store._db_for_key(key)row = db.get_session(session_id) if db is not None else Nonetip = (db.get_compression_tip(session_id) if db is not None else None) or session_id+ # No route names it, so its by-id reads and writes (history, transcript, compression) find their+ # profile's store through the key; ``forget_detached`` drops these.+ hints = store._lazy('_session_owner_hints', dict)+ hints[session_id] = hints[tip] = keynow = datetime.now()# Never a new conversation (that would fire session:start and first-contact notes).started = datetime.fromtimestamp(row['started_at']) if row and row.get('started_at') else now - timedelta(seconds=1)diff --git a/gateway/session_mutations.py b/gateway/session_mutations.pyindex 4cd3176fb66..78cb0cf4b63 100644--- a/gateway/session_mutations.py+++ b/gateway/session_mutations.py@@ -427,6 +427,9 @@ def retire_live_sessions(authority, session_ids, *, require_fence=False):evict = getattr(authority.runner, '_evict_cached_agent', None)if callable(evict):evict(candidate.route)+ if candidate.detached: # the ids its key owned in the store (session_detached.detached_entry)+ from gateway.session_detached import drop_owner_hints+ drop_owner_hints(authority.runner.session_store, candidate.route)from gateway.session_local_mcp import release_editor_mcprelease_editor_mcp(authority, session_ids)from gateway.session_worker_construct import release_session_prefilldiff --git a/tests/gateway/test_detached_conversation_lifecycle.py b/tests/gateway/test_detached_conversation_lifecycle.pyindex e97906cbc81..caa310d98cb 100644--- a/tests/gateway/test_detached_conversation_lifecycle.py+++ b/tests/gateway/test_detached_conversation_lifecycle.py@@ -5,12 +5,26 @@ 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``."""+from types import SimpleNamespace+import pytestfrom tests.gateway.test_authority_lane_moves_on import _app_turn, _chat, _gatewayfrom tests.waiting import async_wait_until+async def _moved_on(monkeypatch):+ """Chat 42 talked in A (open in an app), then ``/new`` and a message in B."""+ runner, adapter, authority, source, sent, ran, gates = await _gateway(monkeypatch)+ lane = runner.session_store._generate_session_key(source)+ await _chat(adapter, source, sent, 'hello')+ ref_a = authority.register(source)+ authority.db.set_session_title(ref_a.session_id, 'First chat')+ await _chat(adapter, source, sent, '/new')+ await _chat(adapter, source, sent, 'hello again')+ return runner, adapter, authority, source, sent, ran, gates, lane, ref_a++@pytest.mark.asyncioasync def test_the_chats_context_exhaustion_reset_moves_the_old_conversation_off_the_chat(monkeypatch):"""F1: the auto-reset after context exhaustion rotates the chat to B without a /new. The app's@@ -37,3 +51,17 @@ async def test_the_chats_context_exhaustion_reset_moves_the_old_conversation_offassert await _app_turn(authority, ref_a, 'app prompt on A') == ('terminal', 'completed')assert ran[-1][:2] == ('app prompt on A', ref_a.session_id) and ran[-1][2] != laneassert sent[chat_replies:] == [], f'the chat got the old conversation\'s reply: {sent[chat_replies:]}'+++async 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+ reused or committing memory at a later idle eviction while A runs in the chat."""+ runner, adapter, authority, source, sent, _ran, _gates, lane, ref_a = await _moved_on(monkeypatch)+ key = authority.sessions[ref_a.session_id].route+ assert key != lane+ with runner._agent_cache_lock:+ runner._agent_cache[key] = (SimpleNamespace(_last_activity_ts=0, session_id=ref_a.session_id), ('sig',))+ await _chat(adapter, source, sent, '/resume First chat')+ assert authority.sessions[ref_a.session_id].route == lane+ assert key not in runner._agent_cachediff --git a/tests/gateway/test_multiplex_session_db_profile_scope.py b/tests/gateway/test_multiplex_session_db_profile_scope.pyindex 0e79164f299..3a9c262a54a 100644--- a/tests/gateway/test_multiplex_session_db_profile_scope.py+++ b/tests/gateway/test_multiplex_session_db_profile_scope.py@@ -882,3 +882,25 @@ def test_profile_named_main_keeps_its_own_namespace_and_store(multiplex_homes):assert Path(store._db_for_key(default_key).db_path) == root / "state.db"finally:reset_hermes_home_override(scope)+++def test_a_conversation_its_chat_moved_past_keeps_its_profile_history(multiplex_homes):+ """#144840 review F2: a secondary profile's conversation its chat moved past is found by id in+ that profile's store, so its turn loads its history and writes its transcript there."""+ from gateway.session_detached import detached_key+ from gateway.session_identity import replace_source+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override+ root, profile = multiplex_homes+ store = _multiplex_store(root)+ token = set_hermes_home_override(str(profile))+ try:+ entry = store.get_or_create_session(_profile_source())+ a = entry.session_id+ store.append_to_transcript(a, {'role': 'user', 'content': 'first turn in A'})+ store.reset_session(entry.session_key) # the chat's /new+ detached = replace_source(_profile_source(), detached_route=detached_key(entry.session_key, a))+ resolved = store.get_or_create_session(detached)+ assert [m.get('content') for m in store.load_transcript(resolved.session_id)] == ['first turn in A']+ assert store._db_for_session_id(a).db_path == store._db_for_key(detached.detached_route).db_path+ finally:+ reset_hermes_home_override(token)