Skip to content

The agent that grows with you

fix(gateway): resuming a main-created session keeps its source and end stamp

Teknium3d8ce33aa601
diff --git a/gateway/session_a2a.py b/gateway/session_a2a.py
index e4cad8b11e8..3706741a577 100644
--- a/gateway/session_a2a.py
+++ b/gateway/session_a2a.py
@@ -66,6 +66,10 @@ def storage_source(db, source, session_id, fallback):
# refresh: pickers filter on them (kanban/tool/oneshot hidden, cron in its own section). Interactive
# surfaces keep the transport's ``local``, outside the state-owned stale-open sweeps keyed on cli/tui/acp.
label = receipt['policy']['source']
+ # An adopted pre-authority row (main's cli/tui/gui history) keeps the label main wrote: its
+ # ``sessions list --source``, ``-c`` and stale-open sweeps key on it, as they did before the upgrade.
+ if 'legacy_session_id' in receipt:
+ return label
return fallback if label in {'cli', 'tui', 'gui', 'acp'} else label
diff --git a/hermes_state_local_migration.py b/hermes_state_local_migration.py
index 769b6446bd7..4b44c55b8b7 100644
--- a/hermes_state_local_migration.py
+++ b/hermes_state_local_migration.py
@@ -58,7 +58,9 @@ def bind_legacy_target(db, conn, receipt):
if conn.execute('SELECT 1 FROM state_meta WHERE key=?', (key,)).fetchone():
raise RuntimeStoreError('storage_unavailable')
source = receipt['entry']['origin']
- conn.execute('UPDATE sessions SET ended_at=NULL,end_reason=NULL,session_key=?,chat_id=?,user_id=?,chat_type=?,origin_json=? WHERE id=?',
+ # Binding is a read-side claim: the row keeps main's ``source`` label and its end stamp. The first
+ # admitted turn reopens it (``reopen_local_session``), exactly as the classic surfaces did.
+ conn.execute('UPDATE sessions SET session_key=?,chat_id=?,user_id=?,chat_type=?,origin_json=? WHERE id=?',
(receipt['route'], receipt['session_id'], receipt['principal_id'], 'dm', _json(source), target))
conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)', (key, _json({
'session_id': receipt['session_id'], 'profile_id': receipt['profile_id'],
diff --git a/tests/gateway/test_legacy_session_migration.py b/tests/gateway/test_legacy_session_migration.py
index 92b2a5cc937..af9c21e9a7c 100644
--- a/tests/gateway/test_legacy_session_migration.py
+++ b/tests/gateway/test_legacy_session_migration.py
@@ -50,7 +50,9 @@ async def test_legacy_history_adoption_is_native_owned_atomic_and_retryable(tmp_
receipt = local_receipt(db, ref.session_id)
assert ref.session_id == 'old-cli'
assert receipt['entry']['session_id'] == 'old-cli'
- assert db.get_session('old-cli')['ended_at'] is None
+ # Adoption is a mount: main's end stamp and source label stay until the first admitted turn.
+ assert (db.get_session('old-cli')['ended_at'], db.get_session('old-cli')['end_reason']) == (original['ended_at'], 'cli_exit')
+ assert db.get_session('old-cli')['source'] == 'cli'
assert db.get_session('old-cli')['title'] == original['title']
assert db.get_session('old-cli')['parent_session_id'] == original['parent_session_id']
policy = runner.adapters[Platform.LOCAL].policies[ref.session_id]
@@ -60,6 +62,10 @@ async def test_legacy_history_adoption_is_native_owned_atomic_and_retryable(tmp_
await authority.attach(native, ref)
assert runner.adapters[Platform.LOCAL].policies[ref.session_id] == policy
history = [{'role': 'user', 'content': 'COMPRESSED'}, {'role': 'assistant', 'content': 'RETAINED'}]
+ # Compression runs inside a turn, and the first admitted turn reopens the adopted row.
+ from gateway.session_local_recovery import reopen_local_session
+ reopen_local_session(authority, ref)
+ assert db.get_session('old-cli')['end_reason'] is None
assert db.try_acquire_compression_lock(ref.session_id, 'fixture')
try:
db.publish_compression_child(parent_session_id=ref.session_id, child_session_id='compressed',
diff --git a/tests/gateway/test_legacy_session_row_parity.py b/tests/gateway/test_legacy_session_row_parity.py
new file mode 100644
index 00000000000..0d312eb41a8
--- /dev/null
+++ b/tests/gateway/test_legacy_session_row_parity.py
@@ -0,0 +1,62 @@
+"""Resuming a session main created leaves its row as main would (TUI parity, PR #106742 row 35).
+
+Adoption binds the old transcript to the owner; it must not rewrite the row's ``source`` label
+(``hermes sessions list --source tui``, ``-c`` / ``_resolve_last_session`` key on it) nor clear the
+``end_reason`` / ``ended_at`` stamp on a mere mount. The first admitted turn reopens the row
+(``reopen_local_session``), exactly as main's sidecar did.
+"""
+from types import SimpleNamespace
+
+import pytest
+
+
+async def _owner(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_controls import AuthorityConnection
+
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ 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)
+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)
+ authority = await initialize_session_authority(runner, profile_id=str(tmp_path), instance_id='owner')
+ native = AuthorityConnection(authority, object(), {'provider': 'local', 'user_id': 'native',
+ 'profile_id': str(tmp_path), 'instance_id': 'owner'})
+ return store, authority, native
+
+
[email protected]('label', ['tui', 'cli', 'gui'])
+async def test_resumed_main_session_keeps_source_and_end_stamp(tmp_path, monkeypatch, label):
+ store, authority, native = await _owner(tmp_path, monkeypatch)
+ db = store._db
+ sid = 'old-' + label
+ db.create_session(sid, source=label, model='fake-model', cwd=str(tmp_path))
+ db.append_message(sid, 'user', 'question')
+ db.append_message(sid, 'assistant', 'answer')
+ db.end_session(sid, 'tui_shutdown')
+ before = db.get_session(sid)
+
+ reply = await native.dispatch({'id': 1, 'method': 'session.resume', 'params': {'session_id': sid}})
+ assert 'result' in reply, reply
+ row = db.get_session(sid)
+ assert (row['source'], row['end_reason'], row['ended_at']) == (label, 'tui_shutdown', before['ended_at'])
+
+ # Every turn refreshes the routing peer through the LOCAL transport; the label survives it.
+ live = authority.sessions[sid]
+ store._record_gateway_session_peer(sid, live.route, live.source)
+ store._record_gateway_session_peer(sid, live.route, live.source, include_compression_ancestors=True)
+ assert db.get_session(sid)['source'] == label
+
+ # Main's `-c` / `--resume latest` and `sessions list --source <label>` still find it.
+ assert sid in {r['id'] for r in db.search_sessions(source=[label])}
+
+ # The first admitted turn reopens the row, as main's sidecar did.
+ from gateway.session_local_recovery import reopen_local_session
+ from gateway.session_contract import SessionRef
+ reopen_local_session(authority, SessionRef(authority.profile_id, sid))
+ assert db.get_session(sid)['end_reason'] is None