Skip to content

The agent that grows with you

fix(gateway): a handed-off Bot Chat stays the bot's chat until its lane moves on

Tekniumfab8848987fb
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index bf0307e3bda..72c3d0fe197 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -80,6 +80,10 @@ class LiveSession:
# Mounted by that cold path (not published by its lane): the lane publishing ANOTHER conversation
# on the same route later supersedes it too.
history_mount: bool = False
+ # A local conversation a messaging lane took over (``/handoff``): its viewers follow it onto the
+ # lane, and once that lane publishes another conversation (``/new``) it is superseded like a
+ # history mount, whatever the lane published since (#143286).
+ handed_off: bool = False
# The background-review guard of a cold ``/refine`` (gateway/session_refine.py): its side agent is
# per call, so the run token lives here; a second /refine joins it and the next turn cancels it.
review: SimpleNamespace = field(default_factory=SimpleNamespace)
@@ -276,13 +280,13 @@ class SessionAuthority:
# The lane moved on to *sid*: a cold history mount still on its route is now another
# conversation's, so it goes read-only (gateway/session_route_recovery.py).
for other in self.sessions.values():
- if other.history_mount and other.route == route and other is not live:
+ if (other.history_mount or other.handed_off) 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
+ live.source, live.route, live.handed_off = source, route, True
# 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)
diff --git a/gateway/session_bot.py b/gateway/session_bot.py
index 5c887b80403..a9ea922f366 100644
--- a/gateway/session_bot.py
+++ b/gateway/session_bot.py
@@ -180,7 +180,7 @@ def _home(authority, actor, profile):
async def _target(authority, actor):
- ref = None
+ ref = lane = None
row = authority.db.get_session_by_title('Bot Chat')
if row is None or (displaced := displaceable_bot_chat(authority, row)) is not None:
# None: a concurrent delivery created it first. A title held by an API conversation no FIFO
@@ -193,11 +193,15 @@ async def _target(authority, actor):
if target is None:
raise RuntimeStoreError('not_found')
from gateway.session_local_migration import resolve_local_target
- ref = resolve_local_target(authority, actor, target['id'])
+ from gateway.session_route_recovery import handed_off_ref
+ # A Bot Chat handed off to a messaging lane stays the bot's chat there: delivery follows it.
+ ref = lane = handed_off_ref(authority, target['id'])
+ if ref is None:
+ ref = resolve_local_target(authority, actor, target['id'])
authority.authorize(actor, ref, 'session:submit')
live = authority.sessions[ref.session_id]
entry = authority.runner.session_store.lookup_by_session_key(live.route)
- if live.source.platform != Platform.LOCAL or entry is None:
+ if (live.source.platform != Platform.LOCAL and lane is None) or entry is None:
raise RuntimeStoreError('admission_conflict')
return ref, live, entry
@@ -216,6 +220,11 @@ def displaceable_bot_chat(authority, row):
return None # every delivery asks: a bound local chat answers from its own row, with no read
db = authority.db
tip = db.get_session(db.get_compression_tip(row['id']) or row['id'])
+ from gateway.session_route_recovery import handed_off_ref, superseded_hand_off
+ if tip is not None and (lane := handed_off_ref(authority, tip['id'])) is not None:
+ # Handed off (``/handoff``): still the bot's chat while its lane holds it; history once that
+ # lane moved on (``/new``), so a fresh Bot Chat takes the title (#143286).
+ return row['id'] if superseded_hand_off(authority, lane) else None
for candidate in (row, tip):
if candidate is None or str(candidate.get('chat_id') or '').startswith('local-'):
return None
@@ -230,6 +239,26 @@ def displaceable_bot_chat(authority, row):
return row['id']
+def superseded_bot_chat(authority):
+ """The id of a handed-off Bot Chat whose lane has moved on (``displaceable_bot_chat`` names it),
+ else None: Desktop's titled create moves it aside before minting the fresh canonical chat."""
+ from gateway.session_route_recovery import handed_off_ref
+ row = authority.db.get_session_by_title('Bot Chat')
+ if row is None or (displaced := displaceable_bot_chat(authority, row)) is None:
+ return None
+ tip = authority.db.get_compression_tip(row['id']) or row['id']
+ return displaced if handed_off_ref(authority, tip) is not None else None
+
+
+async def move_aside_superseded_bot_chat(authority):
+ """Free the canonical title from a handed-off Bot Chat whose lane moved on; the caller holds the
+ titled-create lock. Its history stays, renamed and visible (``_displace_bot_chat``)."""
+ from gateway.session_runtime_workers import tracked_write
+ if (sid := superseded_bot_chat(authority)) is not None:
+ logger.info("Bot Chat %s was handed off and its lane moved on: moving it aside", sid)
+ await tracked_write(authority, partial(_displace_bot_chat, authority.db, sid))
+
+
def _kept_local_history(db, row):
"""Whether an unbound row is local history the Bot Chat door must leave in place: a CLI, TUI
or Desktop row a native open adopts, or one a login stamped as its owner. A local-source row
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index 40251f0b234..f5c839b8b2c 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -445,6 +445,9 @@ class AuthorityConnection:
if type(hidden) is not bool:
raise RuntimeStoreError('invalid_params', field='hidden', detail='must be a boolean')
ref = title and resolve_titled_session(self.authority, self.actor, title, missing_ok=True)
+ if not ref and title == 'Bot Chat':
+ from gateway.session_bot import move_aside_superseded_bot_chat
+ await move_aside_superseded_bot_chat(self.authority)
if (not ref and title == 'Bot Chat'
and not any(params.get(name) is True for name in BYPASS_FIELDS)
and staged_creation_follows(self.authority, self.actor, params.get('request_id'))):
diff --git a/gateway/session_local_title.py b/gateway/session_local_title.py
index f27b3de9683..c5a6a4d90a3 100644
--- a/gateway/session_local_title.py
+++ b/gateway/session_local_title.py
@@ -25,8 +25,14 @@ 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
+ from gateway.session_route_recovery import handed_off_ref, superseded_hand_off
moved = handed_off_ref(authority, tip['id'])
+ if moved is not None and name == 'Bot Chat' and superseded_hand_off(authority, moved):
+ # Bot Mode's canonical chat is the one its bot can still write to: a handed-off Bot Chat
+ # whose lane moved on is history, moved aside by the next create (``session_bot``).
+ if missing_ok:
+ return None
+ raise RuntimeStoreError('not_found')
try:
if moved is not None:
authority.authorize(actor, moved, 'session:read')
diff --git a/gateway/session_route_recovery.py b/gateway/session_route_recovery.py
index 381286ec8e9..37c7daf7ff2 100644
--- a/gateway/session_route_recovery.py
+++ b/gateway/session_route_recovery.py
@@ -153,3 +153,13 @@ def handed_off_ref(authority, session_id):
if row.get('created_source') not in LEGACY_LOCAL_SOURCES or not mountable(authority, ref.session_id):
return None
return ref
+
+
+def superseded_hand_off(authority, ref):
+ """Whether the lane that took over *ref* (a ``handed_off_ref``) has since moved on to another
+ conversation (``/new``, a reset): the chat is history now, read-only on that lane."""
+ live = authority.sessions.get(ref.session_id)
+ route = (authority.db.get_session(ref.session_id) or {}).get('session_key')
+ # The routing entry moves at the platform's /new; the lane publishes its new conversation (and so
+ # supersedes a mounted one) only at its next inbound.
+ return bool(live is not None and live.superseded) or _names_another_conversation(authority, ref.session_id, route)
diff --git a/hermes_state_gateway.py b/hermes_state_gateway.py
index a417f0aeb4a..0b61e3a3731 100644
--- a/hermes_state_gateway.py
+++ b/hermes_state_gateway.py
@@ -269,10 +269,12 @@ class SessionGatewayMixin:
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 gateway.session_route_recovery import _messaging_platform
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))
+ release_receipts(conn, [owner for owner, (_row, label) in moved_receipts(conn, moved).items()
+ if _messaging_platform(label) is not None])
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 a81068e54ce..2222f1070b0 100644
--- a/hermes_state_local.py
+++ b/hermes_state_local.py
@@ -168,17 +168,19 @@ def retire_local_receipts(conn, session_ids):
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."""
+ """``{owner id: (moved row id, its source)}`` of local receipts whose current physical target row,
+ or whose owner row (the conversation's first segment, which a ``/new`` reset leaves behind), 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 the conversation again (the stored
+ identity check in ``gateway.session_local_recovery._checked_entry``, the lineage check in
+ ``validate_local_lineage``). *target_ids* narrows the scan to the rows one repoint rewrote."""
+ start = len(POLICY_PREFIX) + 1
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 "
+ "SELECT substr(m.key, ?), s.id, s.source FROM state_meta m JOIN sessions s ON s.id IN ("
+ "CASE WHEN json_valid(m.value) THEN json_extract(m.value, '$.entry.session_id') END, substr(m.key, ?)) "
"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()
+ (start, start, POLICY_PREFIX + '*')).fetchall()
return {owner: (target, source) for owner, target, source in rows
if target_ids is None or target in target_ids}
diff --git a/tests/gateway/test_handoff_local_receipt.py b/tests/gateway/test_handoff_local_receipt.py
index 6dc1039500d..85f2a8bc03f 100644
--- a/tests/gateway/test_handoff_local_receipt.py
+++ b/tests/gateway/test_handoff_local_receipt.py
@@ -18,7 +18,7 @@ from tests.gateway.test_authority_cold_route_recovery import _Runner, _source
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': []}})
+ monkeypatch.setattr(run, '_load_gateway_config', lambda *_path: {'platform_toolsets': {'cli': []}, 'model': {'default': 'fixture'}})
def _compress(authority, sid):
@@ -47,9 +47,11 @@ async def _handoff(runner, authority, sid, source):
@pytest.mark.asyncio
[email protected]('compressed', [False, True], ids=['plain', 'compressed'])
[email protected]('history', ['plain', 'compressed', 'reset'])
@pytest.mark.parametrize('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, compressed):
+async def test_a_handed_off_bot_chat_opens_on_its_lane_after_a_restart(tmp_path, handed_off_by, history):
+ """``reset``: a ``/new`` left the chat's first segment behind and its receipt names the new one;
+ the conversation's own id (what a platform ``/resume <title>`` or a resumed CLI hands off) moves."""
from gateway.config import Platform
from gateway.session_authority import initialize_session_authority
from gateway.session_contract import Principal
@@ -65,7 +67,9 @@ async def test_a_handed_off_bot_chat_opens_on_its_lane_after_a_restart(tmp_path,
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')
- if compressed:
+ if history == 'reset':
+ runner.session_store.reset_session(warm.sessions[ref.session_id].route)
+ if history == 'compressed':
_compress(warm, ref.session_id)
runner = _Runner(tmp_path) # a restart records the steps on the receipt (#140060)
warm = await initialize_session_authority(runner, profile_id='fixture', instance_id='adopted')
@@ -99,6 +103,77 @@ async def test_a_handed_off_bot_chat_opens_on_its_lane_after_a_restart(tmp_path,
assert json.loads(tip['origin_json'])['platform'] == 'telegram'
+async def _handed_off_bot_chat(tmp_path):
+ """A Bot Chat the Desktop minted and a ``/handoff`` moved to Telegram, still open in that Desktop."""
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_contract import Principal
+ from gateway.session_local import create_local_session
+ 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')
+ 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')
+ telegram = _source()
+ route = await _handoff(runner, warm, ref.session_id, telegram)
+ warm.authorize(owner, ref, 'session:control')
+ return runner, warm, owner, ref, telegram, route
+
+
+async def test_a_handed_off_bot_chat_stays_the_bots_chat_while_its_lane_holds_it(tmp_path):
+ """Bot Mode's one canonical chat per profile: a Bot or cron delivery after the restart goes to
+ the handed-off Bot Chat on its lane; it is never renamed aside for a freshly minted one."""
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_bot import _target, displaceable_bot_chat
+ from gateway.session_local_title import resolve_titled_session
+ _runner, _warm, owner, ref, _telegram, route = await _handed_off_bot_chat(tmp_path)
+ cold = await initialize_session_authority(_Runner(tmp_path), profile_id='fixture', instance_id='cold')
+ assert displaceable_bot_chat(cold, cold.db.get_session_by_title('Bot Chat')) is None
+ target, live, entry = await _target(cold, owner)
+ assert target == ref and live.route == route == entry.session_key
+ assert resolve_titled_session(cold, owner, 'Bot Chat') == ref
+ assert cold.db.get_session(ref.session_id)['title'] == 'Bot Chat'
+
+
[email protected]('door', ['Desktop create', 'Bot delivery'])
+async def test_a_handed_off_bot_chat_whose_lane_moved_on_is_moved_aside(tmp_path, door):
+ """After the platform's own ``/new`` the handed-off chat is that lane's history: the Desktop
+ still viewing it is read-only (its route names the new conversation), and after a restart the
+ bot row no longer adopts it: it is renamed aside and a fresh Bot Chat is minted."""
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_bot import _target
+ from gateway.session_controls import AuthorityConnection
+ from gateway.session_local_title import resolve_titled_session
+ from hermes_state_runtime import RuntimeStoreError
+ runner, warm, owner, ref, telegram, route = await _handed_off_bot_chat(tmp_path)
+ runner.session_store.reset_session(route) # Telegram's /new
+ newer = warm.register(telegram)
+ assert newer != ref and warm.sessions[newer.session_id].route == route
+ assert warm.sessions[ref.session_id].superseded and warm.agent(ref) is None
+ with pytest.raises(RuntimeStoreError, match='session_superseded'):
+ warm.authorize(owner, ref, 'session:control')
+
+ cold_runner = _Runner(tmp_path)
+ cold = await initialize_session_authority(cold_runner, profile_id='fixture', instance_id='cold')
+ cold_runner._adapter_for_source = lambda source: cold_runner.adapters.get(source.platform)
+ cold_runner._cached_agent_for = lambda route: None
+ assert resolve_titled_session(cold, owner, 'Bot Chat', missing_ok=True) is None
+ if door == 'Desktop create':
+ connection = AuthorityConnection(cold, object(), {'user_id': owner.subject})
+ opened = await connection.create(None, {'title': 'Bot Chat', 'request_id': 'bot-chat-2', 'source': 'gui',
+ 'cwd': str(tmp_path), 'model': 'frozen', 'toolsets': [], 'hidden': True})
+ fresh = opened['session_id']
+ else:
+ fresh = (await _target(cold, owner))[0].session_id
+ assert fresh not in (ref.session_id, newer.session_id)
+ assert cold.db.get_session_by_title('Bot Chat')['id'] == fresh
+ moved = cold.db.get_session(ref.session_id)
+ assert moved['title'] == f'Bot Chat (telegram {ref.session_id})' and not moved['hidden']
+
+
def _serve(tmp_path, monkeypatch):
"""A multiplexed gateway's homes: the default profile and a named ``bot`` profile, each with its
own ``state.db``; ``bot`` delivers to a Telegram home channel."""