Skip to content

The agent that grows with you

fix(gateway): a delivery racing the lane's /new mints the fresh Bot Chat; a platform /resume carries the conversation's head

Teknium869fec03c048
diff --git a/gateway/run_startup.py b/gateway/run_startup.py
index 9d6c0e8a10f..af9fbfda053 100644
--- a/gateway/run_startup.py
+++ b/gateway/run_startup.py
@@ -1889,19 +1889,14 @@ class GatewayStartupMixin:
(``handoff_head``), so its whole chain moves onto the lane together with the local receipt
that guards it, and a viewer still holding it open (the Desktop that ran /handoff) follows
it (#143286)."""
- from gateway.session_authorities import active_authority
- from hermes_state_local import handoff_head
- authority = active_authority(self)
- db = authority.db if authority is not None else getattr(self._session_db, '_db', self._session_db)
- local_owner, target = (None, cli_session_id) if db is None else await asyncio.to_thread(
- handoff_head, db, cli_session_id)
+ from gateway.session_route_recovery import conversation_head, follow_hand_off
+ authority, local_owner, target = await conversation_head(self, cli_session_id)
# Ensure a session_store entry exists for this key; switch_session then re-points it.
await self.async_session_store.get_or_create_session(dest.source)
switched = await self.async_session_store.switch_session(session_key, target, preserve_prompt_pin=False)
if switched is None:
raise RuntimeError(f"could not switch session key {session_key} → {target}")
if authority is not None:
- from gateway.session_route_recovery import follow_hand_off
follow_hand_off(authority, dest.source, session_key, authority.logical_owner(target), local_owner)
async def _process_handoff(self, row: dict[str, Any], profile_name: Optional[str] = None) -> None:
diff --git a/gateway/session_bot.py b/gateway/session_bot.py
index 03cfd1a4f9f..6e16c8b635f 100644
--- a/gateway/session_bot.py
+++ b/gateway/session_bot.py
@@ -186,8 +186,12 @@ async def _target(authority, actor):
# None: a concurrent delivery created it first. A title held by an API conversation no FIFO
# can own is moved aside first, under the same lock (MSG-21, #140769).
ref = await _create_bot_chat(authority, actor, displace=None if row is None else displaced)
+ if ref is None and (row := authority.db.get_session_by_title('Bot Chat')) is None:
+ # Moved aside since it was read: a lane's /new frees a handed-off Bot Chat's title off the
+ # titled-create lock (``release_superseded_bot_chat``). None again: a concurrent delivery minted.
+ if (ref := await _create_bot_chat(authority, actor)) is None:
+ row = authority.db.get_session_by_title('Bot Chat')
if ref is None:
- row = authority.db.get_session_by_title('Bot Chat')
tip = authority.db.get_compression_tip(row['id'])
target = authority.db.get_session(tip)
if target is None:
@@ -336,7 +340,11 @@ async def _create_bot_chat(authority, actor, *, displace=None):
if displace is None or held['id'] != displace or displaceable_bot_chat(authority, held) != displace:
return None
logger.warning("Bot Chat title held by %s, a conversation no FIFO can own: moving it aside", displace)
- if not await tracked_write(authority, partial(_displace_bot_chat, authority.db, displace)):
+ # False: the title moved since the check. A lane's ``/new`` frees a handed-off Bot Chat's
+ # title from the store's worker thread, outside this lock (``release_superseded_bot_chat``):
+ # nobody holds it then, so this delivery mints the replacement.
+ if (not await tracked_write(authority, partial(_displace_bot_chat, authority.db, displace))
+ and authority.db.get_session_by_title('Bot Chat') is not None):
return None
# The Bot Chat follows its profile whoever mints it (a Bot or cron delivery, a peer DM),
# the same contract Desktop's create asks for. A later profile change reaches it.
diff --git a/gateway/session_route_recovery.py b/gateway/session_route_recovery.py
index 32613809ca6..7e99cb06688 100644
--- a/gateway/session_route_recovery.py
+++ b/gateway/session_route_recovery.py
@@ -165,6 +165,21 @@ def superseded_hand_off(authority, ref):
return bool(live is not None and live.superseded) or _names_another_conversation(authority, ref.session_id, route)
+async def conversation_head(runner, session_id):
+ """``(authority, local owner or None, row id)`` a repoint of *session_id* onto a messaging lane
+ carries (``/handoff``, a platform ``/resume``): a local conversation's current head
+ (``hermes_state_local.handoff_head``), never an earlier ``/new`` segment, which would move that
+ history onto the lane while the live conversation stays local, its receipt released (#143286)."""
+ import asyncio
+ from gateway.session_authorities import active_authority
+ from hermes_state_local import handoff_head
+ authority = active_authority(runner)
+ db = authority.db if authority is not None else getattr(runner._session_db, '_db', runner._session_db)
+ if db is None:
+ return authority, None, session_id
+ return (authority, *await asyncio.to_thread(handoff_head, db, session_id))
+
+
def follow_hand_off(authority, source, route, owner, local_owner):
"""After ``/handoff`` repointed *route* at *owner* (the lane's logical id of the conversation's
head): the local mount a viewer still holds (*local_owner*, the Desktop that ran it) moves onto
diff --git a/gateway/slash_commands_session.py b/gateway/slash_commands_session.py
index e46c41f946b..02c2f7c6e70 100644
--- a/gateway/slash_commands_session.py
+++ b/gateway/slash_commands_session.py
@@ -1076,6 +1076,12 @@ class GatewaySessionCommandsMixin:
if isinstance(resolved, str):
return resolved
target_id, name = resolved
+ # A local conversation moves onto this lane from its current head, as /handoff carries it: a
+ # title naming its first segment (a local /new moved on) would strand the live one (#143286).
+ from gateway.session_route_recovery import conversation_head, follow_hand_off
+ authority, local_owner, head = await conversation_head(self, target_id)
+ if local_owner is not None:
+ target_id = head
denied = await self._resume_access_denied_reply(source, target_id, name, allow_all, allow_cross_room)
if denied is not None:
return denied
@@ -1088,6 +1094,8 @@ class GatewaySessionCommandsMixin:
)
if not new_entry:
return t("gateway.resume.switch_failed")
+ if local_owner is not None and authority is not None: # a Desktop still viewing it follows it
+ follow_hand_off(authority, source, session_key, authority.logical_owner(target_id), local_owner)
# Conversation boundary: all conversation-scoped state + security state in one funnel call.
# Conversation boundary: clear ALL conversation-scoped per-session state (model/reasoning overrides
# #10702, one-turn restores, model notes, last-resolved cache #58403, /queue overflow) + security
diff --git a/tests/gateway/test_handoff_local_receipt.py b/tests/gateway/test_handoff_local_receipt.py
index 8cd93401e61..4204bd83868 100644
--- a/tests/gateway/test_handoff_local_receipt.py
+++ b/tests/gateway/test_handoff_local_receipt.py
@@ -309,6 +309,82 @@ async def test_the_bots_own_bot_chat_after_a_reset_handoff_and_the_lanes_new_is_
assert warm.db.get_session_by_title('Bot Chat')['id'] == fresh
[email protected]('lands', ['after the title read', 'before the displace write'])
+async def test_a_delivery_racing_the_lanes_new_mints_the_fresh_bot_chat(tmp_path, monkeypatch, lands):
+ """The lane's ``/new`` frees the handed-off Bot Chat's title from the store's worker thread,
+ outside the titled-create lock. A delivery it lands in the middle of still lands in exactly one
+ canonical Bot Chat, a fresh one, instead of failing on the title that vanished under it."""
+ from gateway import session_bot
+ runner, warm, owner, ref, _telegram, route = await _handed_off_bot_chat(tmp_path)
+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)
+ runner._cached_agent_for = lambda route: None
+ release, displaceable = session_bot.release_superseded_bot_chat, session_bot.displaceable_bot_chat
+ if lands == 'before the displace write': # the /new switched the lane; its rename is still pending
+ monkeypatch.setattr(session_bot, 'release_superseded_bot_chat', lambda *_args: None)
+ runner.session_store.reset_session(route)
+ seen = []
+
+ def racing(authority, row):
+ found = displaceable(authority, row)
+ seen.append(found)
+ if lands == 'after the title read' and len(seen) == 1:
+ runner.session_store.reset_session(route) # the lane held it when the delivery read it
+ elif lands == 'before the displace write' and len(seen) == 2: # under the lock
+ release(warm.db, runner.session_store, route, ref.session_id)
+ return found
+ monkeypatch.setattr(session_bot, 'displaceable_bot_chat', racing)
+ fresh = (await session_bot._target(warm, owner))[0].session_id
+ assert fresh != ref.session_id
+ assert warm.db.get_session_by_title('Bot Chat')['id'] == fresh
+ assert warm.db.get_session(ref.session_id)['title'] == f'Bot Chat (telegram {ref.session_id})'
+
+
+def _resume_gateway(runner, authority):
+ """The platform's ``/resume`` handler (``GatewayRunner._handle_resume_command``) on the real store,
+ run by an admin (``--all`` widens it to every titled conversation)."""
+ from gateway.run import GatewayRunner
+ from hermes_state import AsyncSessionDB
+ gateway = object.__new__(GatewayRunner)
+ gateway.adapters, gateway.config, gateway._voice_mode, gateway._running_agents = {}, runner.config, {}, {}
+ gateway._session_db, gateway.session_store = AsyncSessionDB(authority.db), runner.session_store
+ gateway.session_authority = authority
+ gateway._is_user_authorized = gateway._resume_caller_is_admin = lambda _source: True
+ return gateway
+
+
+async def test_a_platform_resume_of_a_local_conversation_continues_its_current_head(tmp_path):
+ """Bot Chat X, then a local ``/new`` (the receipt names the new segment X2), then an admin's
+ ``/resume --all Bot Chat`` on Telegram: the title still names X, the first segment. The lane
+ continues the conversation's head, as ``/handoff`` carries it, so X2 never stays a local row
+ whose receipt was released (refused ``storage_unavailable`` after a restart)."""
+ from gateway.platforms.event import MessageEvent
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_contract import Principal, SessionRef
+ from gateway.session_local import create_local_session
+ from gateway.session_local_title import resolve_titled_session
+ from hermes_state_local import local_receipt
+ 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')
+ runner.session_store.reset_session(warm.sessions[ref.session_id].route)
+ head = SessionRef('fixture', local_receipt(warm.db, ref.session_id)['entry']['session_id'])
+ telegram = _source()
+ reply = await _resume_gateway(runner, warm)._handle_resume_command(
+ MessageEvent(text='/resume --all Bot Chat', source=telegram))
+ route = runner.session_store._generate_session_key(telegram)
+ assert runner.session_store.lookup_by_session_key(route).session_id == head.session_id, reply
+
+ cold = await initialize_session_authority(_Runner(tmp_path), profile_id='fixture', instance_id='cold')
+ cold.authorize(owner, head, 'session:control')
+ assert resolve_titled_session(cold, owner, 'Bot Chat') == head
+ assert cold.sessions[head.session_id].route == route
+
+
@pytest.mark.asyncio
async def test_a_moved_receipt_with_a_malformed_lineage_never_stops_the_boot(tmp_path, monkeypatch):
from gateway.session_authority import initialize_session_authority