Skip to content

The agent that grows with you

fix: mounting a finalized local session no longer reopens it; the first admitted turn does

Teknium4e6efa0eaab2
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index da77c44ae55..6f37bb4cb81 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -472,6 +472,10 @@ class SessionAuthority:
else:
from gateway.session_operator import check_local_input
check_local_input(self, ref, first)
+ # The first real turn reopens a finalized row (#85303): mounts are reads, and
+ # SessionStore would route a stamped row as stale onto a FRESH session.
+ from gateway.session_local_recovery import reopen_local_session
+ reopen_local_session(self, ref)
if first is not None and 'native_text_v1' in first['payload']:
from gateway.session_envelope import check_native_route
await check_native_route(self.runner, first['payload'], self.physical_target(ref), live.source,
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index 12216f466fd..5e1c01b9d63 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -315,11 +315,10 @@ class AuthorityConnection:
self.authority.authorize(self.actor, ref, 'session:control')
from gateway.session_local_mcp import resume_editor_mcp
resume_editor_mcp(self.authority, ref, params['editor'])
- # A resume by id/title is the user asking for THIS conversation to continue; a stamped
- # tui_shutdown / ws_disconnect row would otherwise be routed as stale on the next submit.
+ # Read-only mount (#85303): an ended row stays ended until the first admitted turn
+ # reopens it (``reopen_local_session`` in the drain), so opening a finished chat
+ # never re-lights DB-derived liveness with no new activity.
self.authority.authorize(self.actor, ref, 'session:read')
- from gateway.session_local_recovery import reopen_local_session
- reopen_local_session(self.authority, ref)
snapshot = await self.authority.attach(self.actor, ref)
self.subscriptions[ref.session_id] = snapshot.subscription_id
# Only local routes have a frozen local launch policy to project.
diff --git a/gateway/session_local_recovery.py b/gateway/session_local_recovery.py
index eaf258b047c..087c5c1bd59 100644
--- a/gateway/session_local_recovery.py
+++ b/gateway/session_local_recovery.py
@@ -120,13 +120,15 @@ def local_history(authority, ref):
def reopen_local_session(authority, ref):
- """An explicit resume makes a local session live again.
-
- A TUI shutdown / WS disconnect / idle eviction stamps ``end_reason`` on the physical row.
- ``SessionStore`` reads any stamped row as a stale route (#54878) and, since those reasons are
- not recoverable, answers the next submit with a FRESH session — the resumed client keeps waiting
- on an id that never emits again. The classic resumes clear the stamp (``oneshot._load_resume_target``,
- tui_gateway ``_resume_cold``); the authority must too. Only the lineage tip is reopened: a
+ """The first admitted turn makes a finalized local session live again (#85303).
+
+ Mounting (``session.resume``) is a read and leaves ``ended_at``/``end_reason`` alone; the drain
+ calls this after the turn's local preflight, before execution routes it. A TUI shutdown / WS
+ disconnect / idle eviction stamps ``end_reason`` on the physical row. ``SessionStore`` reads any
+ stamped row as a stale route (#54878) and, since those reasons are not recoverable, answers the
+ turn with a FRESH session — the client keeps waiting on an id that never emits again. The classic
+ surfaces clear the stamp on the first real turn (tui_gateway ``_reopen_if_finalized``); the
+ authority must too. Only the lineage tip is reopened: a
compression parent or reset predecessor is never the physical target.
"""
live = authority.sessions.get(ref.session_id)
diff --git a/tests/gateway/test_session_local_reopen_on_turn.py b/tests/gateway/test_session_local_reopen_on_turn.py
new file mode 100644
index 00000000000..4d59f3a82f0
--- /dev/null
+++ b/tests/gateway/test_session_local_reopen_on_turn.py
@@ -0,0 +1,64 @@
+"""Mounting a finalized local session is a read; the first admitted turn reopens it (#85303)."""
+from types import SimpleNamespace
+
+import pytest
+
+from gateway.session_contract import Submission
+from gateway.session_controls import AuthorityConnection
+
+
+async def _ended_local_session(tmp_path, monkeypatch):
+ from gateway import run
+ from gateway.config import GatewayConfig
+ from gateway.session import SessionStore
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_local import create_local_session
+
+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'cli': []}})
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False,
+ _cached_agent_for=lambda route: None, _adapter_for_source=lambda source: None)
+ authority = await initialize_session_authority(runner, profile_id=str(tmp_path), instance_id='fixture')
+ connection = AuthorityConnection(authority, object(), {'user_id': 'owner'})
+ ref = create_local_session(authority, connection.actor, {'request_id': 'r', 'source': 'tui',
+ 'cwd': str(tmp_path), 'model': 'm', 'toolsets': []})
+ authority.db.append_message(ref.session_id, 'user', 'earlier turn')
+ authority.db.end_session(ref.session_id, 'tui_shutdown')
+ return authority, connection, ref
+
+
+async def test_resuming_a_finalized_local_session_leaves_it_ended(tmp_path, monkeypatch):
+ authority, connection, ref = await _ended_local_session(tmp_path, monkeypatch)
+ try:
+ reply = await connection.dispatch({'id': 1, 'method': 'session.resume',
+ 'params': {'session_id': ref.session_id}})
+ assert reply['result']['messages'][0]['content'] == 'earlier turn', reply
+ row = authority.db.get_session(ref.session_id)
+ assert (row['end_reason'], row['ended_at'] is not None) == ('tui_shutdown', True), \
+ 'a mount with no new activity must not re-light a finalized row'
+ finally:
+ await connection.close()
+ authority.db.close()
+
+
+async def test_first_admitted_turn_reopens_a_finalized_local_session_before_execution(tmp_path, monkeypatch):
+ authority, connection, ref = await _ended_local_session(tmp_path, monkeypatch)
+ seen = []
+
+ async def execute(authority, ref, row):
+ current = authority.db.get_session(ref.session_id)
+ seen.append((current['ended_at'], current['end_reason']))
+ return 'ok'
+
+ monkeypatch.setattr('gateway.session_finite.execute_finite_admission', execute)
+ try:
+ await authority.submit(connection.actor, Submission('turn', ref, {'text': 'continue'}, 'queue'))
+ await authority.sessions[ref.session_id].task
+ # SessionStore routes a stamped row as stale and answers with a FRESH session, so the
+ # turn must find the row live before the runner ever routes it.
+ assert seen == [(None, None)]
+ finally:
+ await connection.close()
+ authority.db.close()