The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): every mount of a moved chat stays read-only-able and follows it to a new chat
Tekniumb9201974045b
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex be501c7bb42..e14caa9b57f 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -279,13 +279,18 @@ class SessionAuthority:# *sid* takes the route over: new here, moved onto it, or back after another conversation had it.took_over = live is None or live.route != route or live.supersededif live is None:+ from gateway.session_route_recovery import mount+ live = self.sessions[sid] = mount(self, sid, source, route)+ elif live.route != route:+ # *sid* moved lanes: ``/handoff`` or a platform ``/resume`` took a local conversation over+ # (its repoint retired the local receipt), or a ``/resume`` moved it on to another chat.+ # Its open viewers follow it, so a turn or a Stop through this mount reaches the lane that+ # holds it now, never the conversation that replaced it on the old one (#143286).from gateway.session_route_recovery import moved_local- live = self.sessions[sid] = LiveSession(source, route, handed_off=moved_local(self, sid, source))- elif (live.source is not None and live.source.platform == Platform.LOCAL- and source.platform != Platform.LOCAL):- # A local conversation a messaging lane took over (``/handoff``): its repoint retired the- # local receipt, so its open viewers follow it onto the lane (#143286).- live.source, live.route, live.handed_off = source, route, True+ left_local = live.source is not None and live.source.platform == Platform.LOCAL+ live.handed_off = (live.handed_off or (left_local and source.platform != Platform.LOCAL)+ or moved_local(self, sid, source))+ live.source, live.route = source, routeif took_over:# The lane moved on to *sid*: a cold history mount or a chat handed off earlier that is# still on its route is now another conversation's, so it goes read-only@@ -651,7 +656,9 @@ class SessionAuthority:check_local_input(self, SessionRef(self.profile_id, sid), row, source=source)self._require_admission_open()- self.sessions.setdefault(sid, LiveSession(source, route))+ if sid not in self.sessions: # ``mount``: a moved local chat keeps ``handed_off`` here too+ from gateway.session_route_recovery import mount+ self.sessions[sid] = mount(self, sid, source, route)if any(row['status'] == 'unknown' for row in rows):raise RuntimeStoreError('unknown_execution')self._schedule(SessionRef(self.profile_id, sid))diff --git a/gateway/session_automation.py b/gateway/session_automation.pyindex f47a6b7b4f1..33beaeab36c 100644--- a/gateway/session_automation.py+++ b/gateway/session_automation.py@@ -485,7 +485,6 @@ async def admit_automation(authority, adapter, event, identity, replaces=None):own transaction, so neither lands without the other."""authority._require_admission_open()payload, entry = snapshot_automation(authority, adapter, event, identity)- from gateway.session_authority import LiveSessionsid = (payload.get('local_automation_v1') or payload['native_text_v1']['automation'])['owner']ref = SessionRef(authority.profile_id, sid)source, envelope = event.source, payload.get('native_text_v1')@@ -494,7 +493,9 @@ async def admit_automation(authority, adapter, event, identity, replaces=None):# drain resolves no adapter for this session after a restart.from gateway.session_envelope import restore_native_sourcesource = restore_native_source(payload, authority.runner)- authority.sessions.setdefault(ref.session_id, LiveSession(source, entry.session_key))+ if ref.session_id not in authority.sessions: # the route's conversation may be a moved local chat+ from gateway.session_route_recovery import mount+ authority.sessions[ref.session_id] = mount(authority, ref.session_id, source, entry.session_key)from functools import partialfrom gateway.session_runtime_workers import tracked_writeadmitted, replaced = partial(authority._admitted, ref, event), []diff --git a/gateway/session_route_recovery.py b/gateway/session_route_recovery.pyindex 8452378fc80..6839fd576af 100644--- a/gateway/session_route_recovery.py+++ b/gateway/session_route_recovery.py@@ -110,7 +110,6 @@ def _mount_plan(authority, sid):def restore_routed_session(authority, sid):"""Publish *sid* as its lane would after a restart; None when this row is not one a route or amessaging-platform row can stand for."""- from gateway.session_authority import LiveSessionfrom gateway.session_contract import SessionRefplan = _mount_plan(authority, sid)if plan is None:@@ -121,11 +120,20 @@ def restore_routed_session(authority, sid):# Re-pin the persisted receiving bot so delivery after a restart goes through it or nowhere,# never the default bot by heuristic (gateway/AGENTS.md § Identity survives the process).source = authority.runner._restored_source(entry)- authority.sessions.setdefault(sid, LiveSession(source, route, superseded=superseded, history_mount=True,- handed_off=moved_local(authority, sid, source)))+ authority.sessions.setdefault(sid, mount(authority, sid, source, route, superseded=superseded,+ history_mount=True))return SessionRef(authority.profile_id, sid)+def mount(authority, sid, source, route, **flags):+ """The live entry of *sid* on *route*, however it is mounted (the lane's inbound, startup recovery+ of its queued input, a cold open, an automation wake): ``handed_off`` comes from the row+ (``moved_local``), so a moved local conversation goes read-only once its lane takes up another+ one, whichever path mounted it first (#143286)."""+ from gateway.session_authority import LiveSession+ return LiveSession(source, route, handed_off=moved_local(authority, sid, source), **flags)++def moved_local(authority, sid, source):"""*sid* is a local conversation (created by a local surface) published on a messaging lane:``/handoff`` or a platform ``/resume`` moved it there. That provenance is the row's, not thediff --git a/tests/gateway/test_handoff_local_receipt.py b/tests/gateway/test_handoff_local_receipt.pyindex 97c54f59458..7c8511e5fe7 100644--- a/tests/gateway/test_handoff_local_receipt.py+++ b/tests/gateway/test_handoff_local_receipt.py@@ -448,6 +448,118 @@ async def test_a_moved_conversation_is_read_only_once_its_lane_is_taken_over(tmpassert authority.agent(head) is None # never the lane's running agent+async def test_a_moved_conversation_mounted_by_startup_recovery_is_read_only_once_its_lane_is_taken_over(+ tmp_path, monkeypatch):+ """Bot Chat A moves onto a Telegram chat and stays there for months: its idle local routing entry+ is pruned (``session_store_max_age_days``). A restart finds the lane's input still queued, so+ startup recovery is what mounts A, and the lane's next inbound reuses that mount. Once another+ chat is handed off to the lane, A is its history: a viewer's turn would run as that chat's."""+ from datetime import datetime, timedelta+ from gateway.config import GatewayConfig, Platform, PlatformConfig+ from gateway.platforms.event import MessageEvent+ from gateway.run import GatewayRunner+ from gateway.run_runtime import recover_profile_native_sessions+ from gateway.session_authority import initialize_session_authority+ from gateway.session_contract import Principal+ from gateway.session_ingress_context import native_callback, register_transport_home+ from gateway.session_local import create_local_session+ from hermes_state_runtime import RuntimeStoreError+ from tests.gateway.test_command_bypass_active_session import _StubAdapter+ monkeypatch.setenv('TELEGRAM_ALLOWED_USERS', '42')+ monkeypatch.setattr('gateway.run._hermes_home', tmp_path)+ monkeypatch.setattr('hermes_state.DEFAULT_DB_PATH', tmp_path / 'state.db')++ def boot():+ runner = GatewayRunner(GatewayConfig(multiplex_profiles=False, sessions_dir=tmp_path / 'sessions'))+ adapter = _StubAdapter(PlatformConfig(enabled=True, token='fixture'), Platform.TELEGRAM)+ adapter.gateway_runner, runner.adapters = runner, {Platform.TELEGRAM: adapter}+ register_transport_home(runner, None, tmp_path)+ return runner, adapter.build_source(chat_id='42', chat_type='dm', user_id='42')++ def chat(authority, title):+ ref = create_local_session(authority, owner, {'request_id': title, 'source': 'gui', 'cwd': str(tmp_path),+ 'model': 'frozen', 'toolsets': []})+ authority.db.set_session_title(ref.session_id, title)+ return ref++ runner, telegram = boot()+ warm = await initialize_session_authority(runner, profile_id=str(tmp_path), instance_id='warm')+ warm._schedule = lambda ref: None+ owner = Principal('owner', warm.profile_id, frozenset({'session:create', 'session:read', 'session:control',+ 'session:submit'}), 'socket')+ a = chat(warm, 'Chat A')+ route = await _handoff(runner, warm, a.session_id, telegram)+ queued = MessageEvent(text='still queued at the restart', source=telegram, message_id='queued')+ with native_callback(runner, queued, tmp_path):+ assert (await warm.admit_native(queued)).ref == a+ store = runner.session_store+ for entry in store._entries.values():+ if entry.session_key != route:+ entry.updated_at = datetime.now() - timedelta(days=120)+ assert store.prune_old_entries(90) == 1+ store.close_all_db_handles()++ runner, telegram = boot()+ try:+ cold = await initialize_session_authority(runner, profile_id=warm.profile_id, instance_id='restarted')+ cold._schedule = lambda ref: None+ assert await recover_profile_native_sessions(runner, cold) == {a.session_id: 'ready'}+ cold.register(telegram)+ cold.authorize(owner, a, 'session:submit') # the lane's conversation: writable there+ await _handoff(runner, cold, chat(cold, 'Chat B').session_id, telegram)+ cold.authorize(owner, a, 'session:read')+ for capability in ('session:submit', 'session:control'):+ with pytest.raises(RuntimeStoreError, match='session_superseded'):+ cold.authorize(owner, a, capability)+ finally:+ runner.session_store.close_all_db_handles()+++async def test_a_moved_conversation_resumed_on_another_chat_moves_there(tmp_path):+ """Bot Chat A moves onto Telegram chat 4242, chat B is handed off there in turn (A is that chat's+ history now), then an admin's ``/resume --all Chat A`` brings A to chat 77. Its mount follows it:+ a turn or a Stop through it acts on chat 77, never on B, which holds 4242; and once chat 77 moves+ on (its ``/new``) A is that chat's history, read-only again."""+ from gateway.platforms.event import MessageEvent+ from gateway.session_authority import initialize_session_authority+ from gateway.session_contract import Principal+ from gateway.session_local import create_local_session+ from hermes_state_runtime import RuntimeStoreError+ runner = _Runner(tmp_path)+ warm = await initialize_session_authority(runner, profile_id='fixture', instance_id='warm')+ owner = Principal('owner', 'fixture', frozenset({'session:create', 'session:read', 'session:control',+ 'session:submit'}), 'socket')++ def chat(title):+ ref = create_local_session(warm, owner, {'request_id': title, 'source': 'gui', 'cwd': str(tmp_path),+ 'model': 'frozen', 'toolsets': []})+ warm.db.set_session_title(ref.session_id, title)+ return ref++ first, second = _source(), _source(chat_id='77')+ a = chat('Chat A')+ await _handoff(runner, warm, a.session_id, first)+ await _handoff(runner, warm, chat('Chat B').session_id, first)+ with pytest.raises(RuntimeStoreError, match='session_superseded'):+ warm.authorize(owner, a, 'session:submit')+ await _resume_gateway(runner, warm)._handle_resume_command(+ MessageEvent(text='/resume --all Chat A', source=second))+ route = runner.session_store._generate_session_key(second)+ assert runner.session_store.lookup_by_session_key(route).session_id == a.session_id+ warm.register(second) # that chat's next inbound+ warm.authorize(owner, a, 'session:submit')+ live = warm.sessions[a.session_id]+ assert (live.source.chat_id, live.route) == ('77', route)++ runner.session_store.reset_session(route)+ warm.register(second)+ for capability in ('session:submit', 'session:control'):+ with pytest.raises(RuntimeStoreError, match='session_superseded'):+ warm.authorize(owner, a, capability)++@pytest.mark.asyncioasync def test_a_moved_receipt_with_a_malformed_lineage_never_stops_the_boot(tmp_path, monkeypatch):from gateway.session_authority import initialize_session_authority