The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a handoff carries the conversation the user is looking at
Tekniumcaa164db0597
diff --git a/gateway/run_startup.py b/gateway/run_startup.pyindex bc93393af54..9d6c0e8a10f 100644--- a/gateway/run_startup.py+++ b/gateway/run_startup.py@@ -1884,21 +1884,25 @@ class GatewayStartupMixin:async def _handoff_repoint(self, dest, session_key: str, cli_session_id: str) -> None:"""Point the destination route at the handed-off conversation; ``switch_session`` ends the- route's prior session and reopens this one. A compressed chat continues on its tip: repoint- there, 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)."""- db = self._session_db- target = (await db.get_compression_tip(cli_session_id) if db is not None else None) or cli_session_id+ route's prior session and reopens this one. A handoff carries the conversation the user is+ looking at: a local chat's latest ``/new`` segment, then that segment's compression tip+ (``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)# 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}")- from gateway.session_authorities import active_authority- authority = active_authority(self)- owner = authority.logical_owner(target) if authority is not None else None- if owner is not None and owner in authority.sessions:- authority._publish_route(dest.source, owner, session_key)+ 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:"""Execute one handoff row; raises on failure (caller marks failed). ``profile_name`` (None =diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 72c3d0fe197..3dcf5b92015 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -275,18 +275,21 @@ class SessionAuthority:from gateway.config import Platformself._require_admission_open()live = self.sessions.get(sid)+ took_over = live is None or live.route != routeif live is None:live = self.sessions[sid] = LiveSession(source, route)- # 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 or other.handed_off) and other.route == route and other is not live:- other.superseded = Trueelif (live.source is not None and live.source.platform == Platform.LOCALand 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, live.handed_off = source, route, True+ if took_over:+ # The lane moved on to *sid*: a cold history mount or a chat handed off earlier that is+ # still on its route is now another conversation's, so it goes read-only+ # (gateway/session_route_recovery.py): a Stop or turn through it would act on *sid*.+ for other in self.sessions.values():+ if (other.history_mount or other.handed_off) and other.route == route and other is not live:+ other.superseded = True# The lane itself names *sid* (again): a historic mount becomes its live session.live.superseded = live.history_mount = Falsereturn SessionRef(self.profile_id, sid)@@ -1466,6 +1469,8 @@ async def initialize_session_authority(runner, *, profile_id, instance_id, db=Noawait asyncio.to_thread(backfill_compression_created_sources, db)from gateway.session_local_recovery import release_handed_off_receiptsawait asyncio.to_thread(release_handed_off_receipts, db, epoch=epoch)+ from gateway.session_bot import release_superseded_bot_chat_at_boot+ await asyncio.to_thread(release_superseded_bot_chat_at_boot, db, runner.session_store)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_bot.py b/gateway/session_bot.pyindex a9ea922f366..87b39c4af30 100644--- a/gateway/session_bot.py+++ b/gateway/session_bot.py@@ -239,24 +239,32 @@ 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 release_superseded_bot_chat(db, store, route, session_id):+ """The lane on *route* moved off *session_id* (its ``/new``, a reset, another ``/resume`` or+ ``/handoff``). A Bot Chat handed off there (``/handoff``) is that lane's history now: free the+ canonical title at once (``_displace_bot_chat``), so the Bots roster and its registry lookup both+ stop naming it and the next click or delivery mints a fresh Bot Chat (#143286). Every route+ transition calls this, and so does boot (an older build's transition)."""+ from gateway.session_route_recovery import _messaging_platform+ from hermes_state_local_migration import LEGACY_LOCAL_SOURCES+ root = (db.get_compression_lineage(session_id) or [session_id])[0]+ row = db.get_session(root)+ if (row is None or row.get('title') != 'Bot Chat' or row.get('created_source') not in LEGACY_LOCAL_SOURCES+ or _messaging_platform(row.get('source')) is None):+ return+ with store._lock:+ entry = store._entry_locked(route)+ if entry is None or (db.get_compression_lineage(entry.session_id) or [entry.session_id])[0] == root:+ return # the lane still holds it+ if _displace_bot_chat(db, root):+ logger.info("Bot Chat %s was handed off to %s and that lane moved on: moved it aside", root, route)+++def release_superseded_bot_chat_at_boot(db, store):+ row = db.get_session_by_title('Bot Chat')+ if row is not None:+ tip = db.get_session(db.get_compression_tip(row['id']) or row['id']) or row+ release_superseded_bot_chat(db, store, tip.get('session_key'), row['id'])def _kept_local_history(db, row):diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex 2494a38ad98..40251f0b234 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -480,10 +480,6 @@ class AuthorityConnection:from hermes_state_local import local_receiptpolicy = restore_policy(local_receipt(self.authority.db, ref.session_id)['policy'])await asyncio.to_thread(accept_launch_hooks, policy)- if title == 'Bot Chat':- # Only once the replacement is committed: a refused create leaves the old chat as it was.- from gateway.session_bot import move_aside_superseded_bot_chat- await move_aside_superseded_bot_chat(self.authority)if title:await tracked_write(self.authority, partial(title_new_session, self.authority, ref, title))if hidden:diff --git a/gateway/session_local_recovery.py b/gateway/session_local_recovery.pyindex 89e434ab1a9..2a9188cc88a 100644--- a/gateway/session_local_recovery.py+++ b/gateway/session_local_recovery.py@@ -392,17 +392,18 @@ def release_handed_off_receipts(db, *, epoch):"""Boot heal for #143286: an older build's ``/handoff`` (or a platform ``/resume``) moved a localsession 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."""+ restores from its route like any other platform session, and move the rest of its conversation+ there with it (``hand_off_conversations``). Only receipts whose CURRENT target 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_local import hand_off_conversations, moved_receiptsfrom hermes_state_runtime import _epochdef 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)+ hand_off_conversations(conn, moved)return movedfor owner, (target, source) in db._execute_write(write).items():logging.getLogger(__name__).info(diff --git a/gateway/session_local_title.py b/gateway/session_local_title.pyindex c5a6a4d90a3..f27b3de9683 100644--- a/gateway/session_local_title.py+++ b/gateway/session_local_title.py@@ -25,14 +25,8 @@ def resolve_titled_session(authority, actor, name, *, missing_ok=False):if missing_ok:return Noneraise RuntimeStoreError('not_found')- from gateway.session_route_recovery import handed_off_ref, superseded_hand_off+ from gateway.session_route_recovery import handed_off_refmoved = 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_recovery.py b/gateway/session_recovery.pyindex 187827d20ae..005f1cb8874 100644--- a/gateway/session_recovery.py+++ b/gateway/session_recovery.py@@ -300,6 +300,8 @@ class SessionRecoveryMixin:promote(session_id, reason)else:db.end_session(session_id, reason)+ from gateway.session_bot import release_superseded_bot_chat+ release_superseded_bot_chat(db, self, session_key, session_id)# Stop the departed conversation's schedule in its owning profile, even when# the in-memory watch still holds a pre-reset session id.heartbeat_key = f"heartbeat:{session_id}"diff --git a/gateway/session_route_recovery.py b/gateway/session_route_recovery.pyindex 37c7daf7ff2..32613809ca6 100644--- a/gateway/session_route_recovery.py+++ b/gateway/session_route_recovery.py@@ -163,3 +163,17 @@ def superseded_hand_off(authority, ref):# 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)+++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+ the lane, as its receipt did. When the head is a later ``/new`` segment, that mount is the+ conversation's earlier history there, superseded once the head publishes (#143286)."""+ held = authority.sessions.get(local_owner) if local_owner else None+ if held is None or held.source is None or held.source.platform != Platform.LOCAL:+ held = None+ elif local_owner != owner:+ held.source, held.route, held.handed_off = source, route, True+ if held is not None or owner in authority.sessions:+ authority._publish_route(source, owner, route)diff --git a/hermes_state_gateway.py b/hermes_state_gateway.pyindex 0b61e3a3731..3556599b64e 100644--- a/hermes_state_gateway.py+++ b/hermes_state_gateway.py@@ -267,14 +267,14 @@ 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).+ # An explicit repoint moved these rows to this lane: the local conversation whose receipt+ # names one of them goes with it in the same write, or it would match neither lane (#143286).from gateway.session_route_recovery import _messaging_platform- from hermes_state_local import moved_receipts, release_receipts+ from hermes_state_local import hand_off_conversations, moved_receiptsmoved = {row[0] for row in conn.execute(f"{_COMPRESSION_LINEAGE_CTE} SELECT id FROM compression_lineage", (session_id,))}- release_receipts(conn, [owner for owner, (_row, label) in moved_receipts(conn, moved).items()- if _messaging_platform(label) is not None])+ hand_off_conversations(conn, {owner: found for owner, found in moved_receipts(conn, moved).items()+ if _messaging_platform(found[1]) 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.pyindex 3fae8756dae..39f9485de21 100644--- a/hermes_state_local.py+++ b/hermes_state_local.py@@ -168,19 +168,19 @@ def retire_local_receipts(conn, session_ids):def moved_receipts(conn, target_ids=None):- """``{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+ """``{owner id: (moved row id, its 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 the conversation again+ (the stored identity check in ``gateway.session_local_recovery._checked_entry``). Only the+ current target counts: an earlier ``/new`` segment that moved leaves the conversation the+ receipt guards local, and releasing it would strand that transcript. *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 IN ("- "CASE WHEN json_valid(m.value) THEN json_extract(m.value, '$.entry.session_id') END, substr(m.key, ?)) "- "WHERE m.key GLOB ? AND json_valid(m.value) AND s.session_key IS NOT NULL "+ "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 CASE WHEN json_valid(m.value) THEN json_extract(m.value, '$.route') END",- (start, start, POLICY_PREFIX + '*')).fetchall()+ (len(POLICY_PREFIX) + 1, POLICY_PREFIX + '*')).fetchall()return {owner: (target, source) for owner, target, source in rowsif target_ids is None or target in target_ids}@@ -193,6 +193,74 @@ def release_receipts(conn, owners):[(POLICY_PREFIX + owner, LEGACY_PREFIX + owner) for owner in owners])+def handoff_head(db, session_id):+ """``(local owner or None, row)`` a ``/handoff`` of *session_id* moves: the conversation the user+ is looking at. A local conversation continues from its receipt's current target (its latest+ ``/new`` segment, then that segment's compression tip), never from an earlier segment; any other+ row from its compression tip."""+ with db._read_ctx() as conn:+ owner = local_lineage_owner(conn, session_id)+ saved = conn.execute('SELECT value FROM state_meta WHERE key=?', (POLICY_PREFIX + owner,)).fetchone()+ target = _policy_target(saved[0]) if saved else None+ start = target or session_id+ return (owner if target else None), db.get_compression_tip(start) or start+++_LANE_IDENTITY = 'session_key, source, user_id, chat_id, chat_type, thread_id, display_name, origin_json, transport_profile'+++def hand_off_conversations(conn, moved):+ """Retire the receipts in *moved* (``moved_receipts``: a messaging lane took over each one's+ current target) and move the rest of each conversation onto that lane with it. Its earlier+ ``/new`` segments take the lane's identity, so they open there as read-only history (a lane+ moved past them) instead of staying local rows no receipt restores; the conversation's title+ follows its head, which the lane continues as its own conversation."""+ for owner, (target, _source) in moved.items():+ saved = conn.execute('SELECT value FROM state_meta WHERE key=?', (POLICY_PREFIX + owner,)).fetchone()+ lineage = (_receipt(saved[0]) or {}).get('lineage') if saved else None+ segments = [sid for sid in dict.fromkeys([owner, *(lineage if isinstance(lineage, list) else ())])+ if isinstance(sid, str)]+ conn.execute(f'UPDATE sessions SET ({_LANE_IDENTITY}) = (SELECT {_LANE_IDENTITY} FROM sessions WHERE id=?) '+ 'WHERE id IN (SELECT value FROM json_each(?)) AND id != ?', (target, json.dumps(segments), target))+ _title_follows_head(conn, owner, _segment_root(conn, segments, target))+ release_receipts(conn, moved)+++def _receipt(raw):+ try:+ value = json.loads(raw)+ except (TypeError, ValueError):+ return None+ return value if isinstance(value, dict) else None+++def _segment_root(conn, segments, target):+ """The first row of *target*'s ``/new`` segment: back through the compressions behind it."""+ if target not in segments:+ return target+ index = segments.index(target)+ while index > 0 and (row := conn.execute('SELECT end_reason FROM sessions WHERE id=?',+ (segments[index - 1],)).fetchone()) and row[0] == 'compression':+ index -= 1+ return segments[index]+++_TITLE_RANK = {'derived': 0, 'llm': 1, 'user': 2}+++def _title_follows_head(conn, owner, head):+ """The conversation's name (a Bot Chat's registry title included) moves to its head, over a title+ the segment only got generated; a name the user gave the segment itself stays."""+ row = conn.execute('SELECT title, title_source, hidden FROM sessions WHERE id=?', (owner,)).fetchone()+ if head == owner or row is None or not row[0]:+ return+ kept = conn.execute('SELECT title, title_source FROM sessions WHERE id=?', (head,)).fetchone()+ if kept is None or (kept[0] and _TITLE_RANK.get(kept[1], 0) >= _TITLE_RANK.get(row[1], 0)):+ return+ conn.execute('UPDATE sessions SET title=NULL WHERE id IN (?,?)', (owner, head))+ conn.execute('UPDATE sessions SET title=?, title_source=?, hidden=? WHERE id=?', (*row, head))++def local_lineage_owner(conn, session_id):"""The creation id whose receipt lineage holds physical segment *session_id* (a reset orcompression 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.pyindex 056b76c678a..1401a7081c0 100644--- a/tests/gateway/test_handoff_local_receipt.py+++ b/tests/gateway/test_handoff_local_receipt.py@@ -46,20 +46,30 @@ async def _handoff(runner, authority, sid, source):return route+def _as_an_older_build(monkeypatch):+ """An older build's repoint: the row's routing identity moves, its local receipt stays."""+ import hermes_state_local+ for name in ('hand_off_conversations', 'release_receipts'):+ monkeypatch.setattr(hermes_state_local, name, lambda *_args: None, raising=False)++@pytest.mark.asyncio@pytest.mark.parametrize('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, 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."""+async def test_a_handed_off_bot_chat_opens_on_its_lane_after_a_restart(tmp_path, monkeypatch, handed_off_by, history):+ """``reset``: a local ``/new`` moved the chat to a new segment and its receipt names that one. A+ handoff carries the conversation the user is looking at: the lane continues the post-``/new``+ segment (the title follows it), and the earlier segment is that lane's read-only history, never a+ local row no receipt restores."""from gateway.config import Platformfrom gateway.session_authority import initialize_session_authority- from gateway.session_contract import Principal+ from gateway.session_contract import Principal, SessionReffrom gateway.session_local import create_local_sessionfrom gateway.session_local_recovery import transcript_targetfrom gateway.session_local_title import resolve_titled_session- from hermes_state_local import POLICY_PREFIX+ from hermes_state_local import POLICY_PREFIX, local_receiptfrom hermes_state_local_migration import LEGACY_PREFIX+ from hermes_state_runtime import RuntimeStoreErrorrunner = _Runner(tmp_path)warm = await initialize_session_authority(runner, profile_id='fixture', instance_id='warm')@@ -69,6 +79,8 @@ async def test_a_handed_off_bot_chat_opens_on_its_lane_after_a_restart(tmp_path,warm.db.set_session_title(ref.session_id, 'Bot Chat')if history == 'reset':runner.session_store.reset_session(warm.sessions[ref.session_id].route)+ # Its first turn there gets the segment a generated title of its own.+ warm.db.set_auto_title(local_receipt(warm.db, ref.session_id)['entry']['session_id'], 'Generated', source='llm')if history == 'compressed':_compress(warm, ref.session_id)runner = _Runner(tmp_path) # a restart records the steps on the receipt (#140060)@@ -76,31 +88,71 @@ async def test_a_handed_off_bot_chat_opens_on_its_lane_after_a_restart(tmp_path,warm.authorize(owner, ref, 'session:read') # the receipt now names the tipkeys = (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+ assert conn.execute('SELECT 1 FROM state_meta WHERE key IN (?,?)', keys).fetchone()+ # The lane's conversation: the reset segment the receipt now names, else the chat itself.+ head = SessionRef('fixture', local_receipt(warm.db, ref.session_id)['entry']['session_id']+ if history == 'reset' else ref.session_id)telegram = _source()- route = await _handoff(runner, warm, ref.session_id, telegram)- 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:+ with monkeypatch.context() as patch:+ if handed_off_by == 'an older build':+ _as_an_older_build(patch)+ route = await _handoff(runner, warm, ref.session_id, telegram)+ assert warm.logical_owner(runner.session_store.lookup_by_session_key(route).session_id) == head.session_id+ if handed_off_by == 'this build':# The Desktop that ran /handoff still holds the chat open.- warm.authorize(owner, ref, 'session:control')- assert transcript_target(warm, ref) == warm.physical_target(ref)+ warm.authorize(owner, ref, 'session:read')+ if history == 'reset': # its pre-/new segment is the lane's history now+ with pytest.raises(RuntimeStoreError, match='session_superseded'):+ warm.authorize(owner, ref, 'session:control')+ else:+ warm.authorize(owner, ref, 'session:control')+ assert transcript_target(warm, ref) == warm.physical_target(ref)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+ assert resolve_titled_session(cold, webapp, 'Bot Chat') == head+ cold.authorize(webapp, head, 'session:control') # pin, rename, archive- live = cold.sessions[ref.session_id]+ live = cold.sessions[head.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- tip = cold.db.get_session(cold.physical_target(ref))+ tip = cold.db.get_session(cold.physical_target(head))assert json.loads(tip['origin_json'])['platform'] == 'telegram'+ if history == 'reset': # the earlier segment opens read-only on that lane+ cold.authorize(webapp, ref, 'session:read')+ assert cold.sessions[ref.session_id].route == route+ with pytest.raises(RuntimeStoreError, match='session_superseded'):+ cold.authorize(webapp, ref, 'session:control')+++async def test_a_receipt_whose_current_segment_is_still_local_is_never_released(tmp_path, monkeypatch):+ """An older build handed off a chat's FIRST segment after a local ``/new``: that row moved, but+ the receipt names the post-``/new`` segment, still local. Releasing it would leave that+ transcript reachable from nowhere, so the boot heal keeps it and the conversation still opens."""+ from gateway.session_authority import initialize_session_authority+ from gateway.session_contract import Principal+ from gateway.session_local import create_local_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': 'chat', 'source': 'gui', 'cwd': str(tmp_path),+ 'model': 'frozen', 'toolsets': []})+ runner.session_store.reset_session(warm.sessions[ref.session_id].route)+ head = local_receipt(warm.db, ref.session_id)['entry']['session_id']+ store, telegram = runner.session_store, _source()+ with monkeypatch.context() as patch: # the older build's watcher: switch_session(route, <the id>)+ _as_an_older_build(patch)+ store.get_or_create_session(telegram)+ store.switch_session(store._generate_session_key(telegram), ref.session_id, preserve_prompt_pin=False)++ cold = await initialize_session_authority(_Runner(tmp_path), profile_id='fixture', instance_id='cold')+ assert local_receipt(cold.db, ref.session_id)['entry']['session_id'] == head+ assert cold.db.get_session(head)['source'] == 'gui'async def _handed_off_bot_chat(tmp_path):@@ -137,19 +189,41 @@ async def test_a_handed_off_bot_chat_stays_the_bots_chat_while_its_lane_holds_itassert cold.db.get_session(ref.session_id)['title'] == 'Bot Chat'+async def _bot_row(authority, actor):+ """What the Desktop Bots row reads for the profile: the roster's ``canonical_session`` (the+ ``profiles.list`` reader of that profile's store) and the registry lookup ``session.list+ title="Bot Chat"`` its click runs. ``canonical-chat.ts`` refuses to mint when the lookup is+ empty but the roster names a chat, so the two must agree."""+ from pathlib import Path+ from gateway.session_controls import AuthorityConnection+ from tui_gateway.server import _profile_session_fields+ from tui_gateway.profile_roster_cache import invalidate+ invalidate()+ roster = {}+ _profile_session_fields(roster, Path(authority.db.db_path).parent)+ canonical = roster['canonical_session']+ listed = await AuthorityConnection(authority, object(), {'user_id': actor.subject}).list_sessions(+ None, {'title': 'Bot Chat', 'include_hidden': True, 'limit': 50})+ found = [row['id'] for row in listed['sessions']]+ assert (canonical and canonical['id']) == (found[0] if found else None), (canonical, found)+ return found[0] if found else None++@pytest.mark.asyncio@pytest.mark.parametrize('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."""+ """After the platform's own ``/new`` the handed-off chat is that lane's history: the canonical+ title moves aside at once, so the Bots row's roster and its registry lookup agree at every step+ (warm, cold) and its click mints a fresh Bot Chat; the Desktop still viewing the old one is+ read-only (its route names the new conversation)."""from gateway.session_authority import initialize_session_authorityfrom gateway.session_bot import _targetfrom gateway.session_controls import AuthorityConnection- from gateway.session_local_title import resolve_titled_sessionfrom hermes_state_runtime import RuntimeStoreErrorrunner, warm, owner, ref, telegram, route = await _handed_off_bot_chat(tmp_path)+ assert await _bot_row(warm, owner) == ref.session_idrunner.session_store.reset_session(route) # Telegram's /new+ assert await _bot_row(warm, owner) is Nonenewer = warm.register(telegram)assert newer != ref and warm.sessions[newer.session_id].route == routeassert warm.sessions[ref.session_id].superseded and warm.agent(ref) is None@@ -160,24 +234,49 @@ async def test_a_handed_off_bot_chat_whose_lane_moved_on_is_moved_aside(tmp_pathcold = 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})- with pytest.raises(RuntimeStoreError): # a refused create leaves the old chat as it was- await connection.create(None, {'title': 'Bot Chat', 'request_id': 'bot-chat-bad', 'source': 'gui',- 'cwd': str(tmp_path / 'missing'), 'model': 'frozen', 'toolsets': []})- assert cold.db.get_session_by_title('Bot Chat')['id'] == ref.session_id- opened = await connection.create(None, {'title': 'Bot Chat', 'request_id': 'bot-chat-2', 'source': 'gui',- 'cwd': str(tmp_path), 'model': 'frozen', 'toolsets': [], 'hidden': True})+ assert await _bot_row(cold, owner) is None+ if door == 'Desktop create': # the click: nothing found, so it mints+ opened = await AuthorityConnection(cold, object(), {'user_id': owner.subject}).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+ else: # the bot's own delivery, as the Desktop's principal (whose roster reads it)+ from gateway.session_contract import Principal+ desktop = AuthorityConnection(cold, object(), {'user_id': owner.subject}).actor+ fresh = (await _target(cold, Principal(desktop.subject, 'fixture', owner.capabilities, 'socket')))[0].session_idassert fresh not in (ref.session_id, newer.session_id)- assert cold.db.get_session_by_title('Bot Chat')['id'] == fresh+ assert await _bot_row(cold, owner) == freshmoved = cold.db.get_session(ref.session_id)assert moved['title'] == f'Bot Chat (telegram {ref.session_id})' and not moved['hidden']+async def test_a_second_chat_handed_off_to_the_same_home_chat_supersedes_the_first(tmp_path):+ """Desktop A handed off its Bot Chat H to the Telegram home chat; Desktop B then hands off its+ own open chat Y there. The lane names Y now: H is history, read-only for the Desktop still+ viewing it (a Stop or turn through it would act on Y), and its canonical title moves aside."""+ from gateway.session_authority import initialize_session_authority+ from gateway.session_local import create_local_session+ from hermes_state_runtime import RuntimeStoreError+ runner, warm, owner, ref, telegram, route = await _handed_off_bot_chat(tmp_path)+ other = create_local_session(warm, owner, {'request_id': 'other-chat', 'source': 'gui', 'cwd': str(tmp_path),+ 'model': 'frozen', 'toolsets': []})+ warm.authorize(owner, other, 'session:control')+ assert await _handoff(runner, warm, other.session_id, telegram) == route+ assert warm.logical_owner(runner.session_store.lookup_by_session_key(route).session_id) == other.session_id+ warm.authorize(owner, other, 'session:submit')+ with pytest.raises(RuntimeStoreError, match='session_superseded'):+ warm.authorize(owner, ref, 'session:submit')+ assert warm.agent(ref) is None+ assert await _bot_row(warm, owner) is None++ cold = await initialize_session_authority(_Runner(tmp_path), profile_id='fixture', instance_id='cold')+ cold.authorize(owner, other, 'session:control')+ cold.authorize(owner, ref, 'session:read')+ with pytest.raises(RuntimeStoreError, match='session_superseded'):+ cold.authorize(owner, ref, 'session:control')++def _serve(tmp_path, monkeypatch):"""A multiplexed gateway's homes: the default profile and a named ``bot`` profile, each with itsown ``state.db``; ``bot`` delivers to a Telegram home channel."""