Skip to content

The agent that grows with you

fix(gateway): a handed-off local chat keeps opening on its new lane

Tekniumc13a612f8f0b
diff --git a/gateway/run_startup.py b/gateway/run_startup.py
index e0f8460c0b2..70cc9c8cf3d 100644
--- a/gateway/run_startup.py
+++ b/gateway/run_startup.py
@@ -1897,6 +1897,12 @@ class GatewayStartupMixin:
)
if switched is None:
raise RuntimeError(f"could not switch session key {session_key} → {cli_session_id}")
+ # The repoint retired the session's local receipt: a viewer still holding it open (the Desktop
+ # that ran /handoff) follows it onto the lane instead of meeting a receipt that is gone (#143286).
+ from gateway.session_authorities import active_authority
+ authority = active_authority(self)
+ if authority is not None and cli_session_id in authority.sessions:
+ authority._publish_route(dest.source, cli_session_id, session_key)
# Evict the cached AIAgent (rebuild against the CLI session_id, like /resume) and clear stale
# running-agent state so the synthetic turn isn't queued behind it.
self._evict_cached_agent(session_key)
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index 3dd8ef66f7a..bf0307e3bda 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -268,6 +268,7 @@ class SessionAuthority:
return sid, entry.session_key
def _publish_route(self, source, sid, route):
+ from gateway.config import Platform
self._require_admission_open()
live = self.sessions.get(sid)
if live is None:
@@ -277,6 +278,11 @@ class SessionAuthority:
for other in self.sessions.values():
if other.history_mount and other.route == route and other is not live:
other.superseded = True
+ 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 = source, route
# The lane itself names *sid* (again): a historic mount becomes its live session.
live.superseded = live.history_mount = False
return SessionRef(self.profile_id, sid)
@@ -1454,6 +1460,8 @@ async def initialize_session_authority(runner, *, profile_id, instance_id, db=No
await asyncio.to_thread(settle_recovered_unattended, db, epoch)
await asyncio.to_thread(backfill_legacy_session_owners, db)
await asyncio.to_thread(backfill_compression_created_sources, db)
+ from gateway.session_local_recovery import release_handed_off_receipts
+ await asyncio.to_thread(release_handed_off_receipts, db, epoch=epoch)
authority = SessionAuthority(runner, profile_id=profile_id, instance_id=instance_id, db=db, epoch=epoch)
# A receipt's compression catch-up (#140060) writes: it commits off the loop too, before the
# authority is published, so the recovery below only reads.
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index 5b727a96e28..40251f0b234 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -610,7 +610,9 @@ class AuthorityConnection:
# 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')
- if 'session:control' in self.actor.capabilities:
+ mounted = self.authority.sessions[ref.session_id].source
+ # Only a local route has a stored creation policy to refresh; a platform lane's turns read the profile.
+ if 'session:control' in self.actor.capabilities and getattr(mounted, 'platform', None) == Platform.LOCAL:
# A client attaching (main's `hermes -c` was a new process) re-reads the config-derived settings
# (CFG-2); a snapshot poll on this attachment does not. Any open still adopts a frozen Bot Chat
# whose earlier open found it busy (Desktop's warm `session.activate` resumes on one connection).
diff --git a/gateway/session_local_recovery.py b/gateway/session_local_recovery.py
index 10d061d54a5..89e434ab1a9 100644
--- a/gateway/session_local_recovery.py
+++ b/gateway/session_local_recovery.py
@@ -388,6 +388,27 @@ def restore_completion_route(runner, session_key):
restore_local_session(authority, parsed['chat_id'])
+def release_handed_off_receipts(db, *, epoch):
+ """Boot heal for #143286: an older build's ``/handoff`` (or a platform ``/resume``) moved a local
+ session onto a messaging lane but kept its local receipt, so every open, pin or rename refused it
+ (``stored identity mismatch``) and its title never resolved. Retire each such receipt, so the row
+ restores from its route like any other platform session. Only rows a messaging lane now holds:
+ any other refused receipt stays as it is, logged when it is touched."""
+ from gateway.session_route_recovery import _messaging_platform
+ from hermes_state_local import moved_receipts, release_receipts
+ from hermes_state_runtime import _epoch
+
+ def write(conn):
+ _epoch(conn, epoch)
+ moved = {owner: (target, source) for owner, (target, source) in moved_receipts(conn).items()
+ if _messaging_platform(source) is not None}
+ release_receipts(conn, moved)
+ return moved
+ for owner, (target, source) in db._execute_write(write).items():
+ logging.getLogger(__name__).info(
+ 'Local session %s was handed off to %s (row %s); released its local receipt', owner, source, target)
+
+
def local_receipt_ids(authority):
from gateway.session_viewer_close import CLOSE_PREFIX
start = len(POLICY_PREFIX) + 1
diff --git a/gateway/session_local_title.py b/gateway/session_local_title.py
index b866ed184d2..f27b3de9683 100644
--- a/gateway/session_local_title.py
+++ b/gateway/session_local_title.py
@@ -12,7 +12,8 @@ from hermes_state_runtime import RuntimeStoreError
def resolve_titled_session(authority, actor, name, *, missing_ok=False):
"""Exact session id first, then title (latest ``"<title> #N"`` continuation wins over
the bare title), projected forward to the compression tip. Only a local session the
- actor may read is returned; a foreign or non-local match is ``not_found`` so another
+ actor may read is returned, or one a messaging lane took over from a local surface
+ (``handed_off_ref``); a foreign or other non-local match is ``not_found`` so another
principal's titles are never confirmed."""
if not isinstance(name, str) or not name.strip():
raise RuntimeStoreError('invalid_params')
@@ -24,7 +25,12 @@ def resolve_titled_session(authority, actor, name, *, missing_ok=False):
if missing_ok:
return None
raise RuntimeStoreError('not_found')
+ from gateway.session_route_recovery import handed_off_ref
+ moved = handed_off_ref(authority, tip['id'])
try:
+ if moved is not None:
+ authority.authorize(actor, moved, 'session:read')
+ return moved
from gateway.session_local_migration import resolve_local_target
ref = resolve_local_target(authority, actor, tip['id'])
except RuntimeStoreError as exc:
diff --git a/gateway/session_route_recovery.py b/gateway/session_route_recovery.py
index 3eaaa8d0fc4..381286ec8e9 100644
--- a/gateway/session_route_recovery.py
+++ b/gateway/session_route_recovery.py
@@ -139,3 +139,17 @@ def messaging_owner_ref(authority, ref):
from gateway.session_contract import SessionRef
owner = authority.logical_owner(ref.session_id)
return ref if owner == ref.session_id else SessionRef(ref.profile_id, owner)
+
+
+def handed_off_ref(authority, session_id):
+ """The mount of *session_id* when it is a local conversation a messaging lane took over
+ (``/handoff``, a platform ``/resume``): created by a local surface, now routed on a lane this
+ authority mounts. Its title stays the conversation's, so ``/resume <title>`` and the Bots roster's
+ registry lookup open it on that lane (#143286). None for any other row."""
+ from gateway.session_contract import SessionRef
+ from hermes_state_local_migration import LEGACY_LOCAL_SOURCES
+ ref = messaging_owner_ref(authority, SessionRef(authority.profile_id, session_id))
+ row = authority.db.get_session(ref.session_id) or {}
+ if row.get('created_source') not in LEGACY_LOCAL_SOURCES or not mountable(authority, ref.session_id):
+ return None
+ return ref
diff --git a/hermes_state_gateway.py b/hermes_state_gateway.py
index 37be384bf8e..a417f0aeb4a 100644
--- a/hermes_state_gateway.py
+++ b/hermes_state_gateway.py
@@ -267,6 +267,12 @@ class SessionGatewayMixin:
query_params,
)
if ancestors:
+ # An explicit repoint moved these rows to this lane: a local receipt guarding one of them
+ # is retired in the same write, or the row would match neither lane (#143286).
+ from hermes_state_local import moved_receipts, release_receipts
+ moved = {row[0] for row in conn.execute(
+ f"{_COMPRESSION_LINEAGE_CTE} SELECT id FROM compression_lineage", (session_id,))}
+ release_receipts(conn, moved_receipts(conn, moved))
return
# The UPDATE silently no-ops on a missing row — insert it with full identity.
if conn.execute("SELECT 1 FROM sessions WHERE id = ? LIMIT 1", (session_id,)).fetchone() is None:
diff --git a/hermes_state_local.py b/hermes_state_local.py
index ca810f57191..a81068e54ce 100644
--- a/hermes_state_local.py
+++ b/hermes_state_local.py
@@ -167,6 +167,30 @@ def retire_local_receipts(conn, session_ids):
conn.executemany('DELETE FROM state_meta WHERE key=?', [(key,) for key in gone])
+def moved_receipts(conn, target_ids=None):
+ """``{owner id: (target id, target source)}`` of local receipts whose current physical target row
+ now carries another lane's route. An explicit repoint (``/handoff``, a platform ``/resume``)
+ rewrote that row's routing identity, so the receipt can never restore it again (the stored
+ identity check in ``gateway.session_local_recovery._checked_entry``). *target_ids* narrows the
+ scan to the rows one repoint rewrote."""
+ rows = conn.execute(
+ "SELECT substr(m.key, ?), s.id, s.source FROM state_meta m JOIN sessions s ON s.id = "
+ "CASE WHEN json_valid(m.value) THEN json_extract(m.value, '$.entry.session_id') END "
+ "WHERE m.key GLOB ? AND s.session_key IS NOT NULL "
+ "AND s.session_key IS NOT json_extract(m.value, '$.route')",
+ (len(POLICY_PREFIX) + 1, POLICY_PREFIX + '*')).fetchall()
+ return {owner: (target, source) for owner, target, source in rows
+ if target_ids is None or target in target_ids}
+
+
+def release_receipts(conn, owners):
+ """Retire *owners*' local receipts (creation policy and legacy binding): the row they guarded now
+ belongs to a messaging lane, which restores it from its route like any other platform session."""
+ from hermes_state_local_migration import LEGACY_PREFIX
+ conn.executemany('DELETE FROM state_meta WHERE key IN (?,?)',
+ [(POLICY_PREFIX + owner, LEGACY_PREFIX + owner) for owner in owners])
+
+
def local_lineage_owner(conn, session_id):
"""The creation id whose receipt lineage holds physical segment *session_id* (a reset or
compression child, which carries the owner as ``chat_id``); *session_id* itself otherwise."""
diff --git a/tests/gateway/test_handoff_local_receipt.py b/tests/gateway/test_handoff_local_receipt.py
new file mode 100644
index 00000000000..5e30132a2b1
--- /dev/null
+++ b/tests/gateway/test_handoff_local_receipt.py
@@ -0,0 +1,70 @@
+"""A local chat handed off to a messaging lane keeps opening there (#143286).
+
+``/handoff`` repoints the platform's route at the local session (``SessionStore.switch_session``),
+which rewrites the row's routing identity. Its local receipt must go with that write, or the row
+matches neither lane: every open, pin or rename refused ``storage_unavailable`` (``stored identity
+mismatch``) and its title (a Bot Chat's registry lookup) answered ``not_found``. A store an older
+build left that way heals when the gateway starts.
+"""
+import json
+
+import pytest
+
+from tests.gateway.test_authority_cold_route_recovery import _Runner, _source
+
+
[email protected](autouse=True)
+def _home(tmp_path, monkeypatch):
+ from gateway import run
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'cli': []}})
+
+
[email protected]('handed_off_by', ['this build', 'an older build'])
+async def test_a_handed_off_bot_chat_opens_on_its_lane_after_a_restart(tmp_path, handed_off_by):
+ from gateway.config import Platform
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_contract import Principal
+ from gateway.session_local import create_local_session
+ from gateway.session_local_recovery import transcript_target
+ from gateway.session_local_title import resolve_titled_session
+ from hermes_state_local import POLICY_PREFIX
+ from hermes_state_local_migration import LEGACY_PREFIX
+
+ 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'}), 'socket')
+ ref = create_local_session(warm, owner, {'request_id': 'bot-chat', 'source': 'gui', 'cwd': str(tmp_path),
+ 'model': 'frozen', 'toolsets': []})
+ warm.db.set_session_title(ref.session_id, 'Bot Chat')
+ keys = (POLICY_PREFIX + ref.session_id, LEGACY_PREFIX + ref.session_id)
+ with warm.db._read_ctx() as conn:
+ receipt = conn.execute('SELECT key, value FROM state_meta WHERE key IN (?,?)', keys).fetchall()
+ assert receipt
+
+ # The handoff watcher's repoint (gateway/run_startup.py ``_process_handoff``), then its synthetic
+ # turn's admission publishing the lane while the Desktop still holds the chat open.
+ telegram = _source()
+ runner.session_store.get_or_create_session(telegram)
+ route = runner.session_store._generate_session_key(telegram)
+ assert runner.session_store.switch_session(route, ref.session_id, preserve_prompt_pin=False)
+ if handed_off_by == 'an older build':
+ warm.db._execute_write(lambda conn: conn.executemany(
+ 'INSERT OR REPLACE INTO state_meta(key, value) VALUES(?,?)', [tuple(row) for row in receipt]))
+ else:
+ assert warm.register(telegram) == ref
+ warm.authorize(owner, ref, 'session:control')
+ assert transcript_target(warm, ref) == ref.session_id
+
+ cold = await initialize_session_authority(_Runner(tmp_path), profile_id='fixture', instance_id='cold')
+ # A browser Webapp viewer: never a native legacy transport, so legacy adoption is not its way in.
+ webapp = Principal('webapp', 'fixture', frozenset({'session:read', 'session:control'}), 'browser')
+ assert resolve_titled_session(cold, webapp, 'Bot Chat') == ref
+ cold.authorize(webapp, ref, 'session:control') # pin, rename, archive
+
+ live = cold.sessions[ref.session_id]
+ assert (live.source.platform, live.route) == (Platform.TELEGRAM, route)
+ with cold.db._read_ctx() as conn:
+ assert conn.execute('SELECT 1 FROM state_meta WHERE key IN (?,?)', keys).fetchone() is None
+ assert json.loads(cold.db.get_session(ref.session_id)['origin_json'])['platform'] == 'telegram'