Skip to content

The agent that grows with you

fix(gateway): hand off a compressed chat from its tip

Teknium7cae602ff817
diff --git a/gateway/run_startup.py b/gateway/run_startup.py
index 70cc9c8cf3d..bc93393af54 100644
--- a/gateway/run_startup.py
+++ b/gateway/run_startup.py
@@ -1882,6 +1882,24 @@ class GatewayStartupMixin:
thread_sessions_per_user=extra.get("thread_sessions_per_user", False), profile=handoff_profile,
)
+ 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
+ # 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)
+
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 =
root) is the profile whose store queued it — load-bearing under multiplex: secondaries live in
@@ -1889,20 +1907,7 @@ class GatewayStartupMixin:
cli_session_id = row["id"]
dest = await self._handoff_resolve_destination(row, profile_name)
session_key = self._handoff_session_key(dest, profile_name)
- # 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)
- # switch_session ends the prior session and reopens the CLI session under the new key.
- switched = await self.async_session_store.switch_session(
- session_key, cli_session_id, preserve_prompt_pin=False,
- )
- 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)
+ await self._handoff_repoint(dest, session_key, cli_session_id)
# 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/tests/gateway/test_handoff_local_receipt.py b/tests/gateway/test_handoff_local_receipt.py
index 5e30132a2b1..8975416bef6 100644
--- a/tests/gateway/test_handoff_local_receipt.py
+++ b/tests/gateway/test_handoff_local_receipt.py
@@ -7,6 +7,7 @@ mismatch``) and its title (a Bot Chat's registry lookup) answered ``not_found``.
build left that way heals when the gateway starts.
"""
import json
+from types import SimpleNamespace
import pytest
@@ -20,9 +21,35 @@ def _home(tmp_path, monkeypatch):
monkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'cli': []}})
+def _compress(authority, sid):
+ """Two real compression splits of the local chat, as its turns publish them."""
+ db, live = authority.db, authority.sessions[sid]
+ store = authority.runner.session_store
+ for parent, child in ((sid, sid + '-c1'), (sid + '-c1', sid + '-c2')):
+ store._record_gateway_session_peer(parent, live.route, live.source)
+ assert db.try_acquire_compression_lock(parent, 'fixture')
+ db.publish_compression_child(parent_session_id=parent, child_session_id=child, source='local',
+ messages=[{'role': 'user', 'content': 'kept'}], compression_lock_holder='fixture')
+ db.release_compression_lock(parent, 'fixture')
+ store._record_gateway_session_peer(child, live.route, live.source)
+
+
+async def _handoff(runner, authority, sid, source):
+ """The handoff watcher's repoint (``GatewayStartupMixin._handoff_repoint``) on the real store."""
+ from gateway.run_startup import GatewayStartupMixin
+ from gateway.session import AsyncSessionStore
+ from hermes_state import AsyncSessionDB
+ route = runner.session_store._generate_session_key(source)
+ gateway = SimpleNamespace(_session_db=AsyncSessionDB(authority.db), session_authority=authority,
+ async_session_store=AsyncSessionStore(runner.session_store))
+ await GatewayStartupMixin._handoff_repoint(gateway, SimpleNamespace(source=source), route, sid)
+ return route
+
+
@pytest.mark.asyncio
[email protected]('compressed', [False, True], ids=['plain', 'compressed'])
@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):
+async def test_a_handed_off_bot_chat_opens_on_its_lane_after_a_restart(tmp_path, handed_off_by, compressed):
from gateway.config import Platform
from gateway.session_authority import initialize_session_authority
from gateway.session_contract import Principal
@@ -38,24 +65,25 @@ 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:
+ _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')
+ warm.authorize(owner, ref, 'session:read') # the receipt now names the tip
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)
+ 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:
- assert warm.register(telegram) == ref
+ # The Desktop that ran /handoff still holds the chat open.
warm.authorize(owner, ref, 'session:control')
- assert transcript_target(warm, ref) == ref.session_id
+ 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.
@@ -67,4 +95,5 @@ async def test_a_handed_off_bot_chat_opens_on_its_lane_after_a_restart(tmp_path,
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'
+ tip = cold.db.get_session(cold.physical_target(ref))
+ assert json.loads(tip['origin_json'])['platform'] == 'telegram'