Skip to content

The agent that grows with you

fix(acp): compressed editor chats reopen from the session picker

Teknium6ff664ee19e9
diff --git a/acp_adapter/catalog.py b/acp_adapter/catalog.py
index 9a5610d3bd3..c61445b43e0 100644
--- a/acp_adapter/catalog.py
+++ b/acp_adapter/catalog.py
@@ -15,10 +15,23 @@ def read_catalog_rows(path):
return {str(row["id"]): dict(row) for row in db.list_sessions_rich(source="acp", limit=1000)}
+def logical_session_id(path, session_id):
+ """The authority's logical id for an id an editor already holds: compression advances the
+ physical transcript, never the session identity (``SessionAuthority.logical_owner``)."""
+ path = Path(path)
+ if not path.exists():
+ return session_id
+ with SessionDB(db_path=path, read_only=True) as db:
+ lineage = db.get_compression_lineage(session_id)
+ return lineage[0] if lineage else session_id
+
+
def catalog_sessions(path, cwd=None):
normalized = _normalize_cwd_for_compare(cwd) if cwd else None
results = []
for sid, row in read_catalog_rows(path).items():
+ # The listing projects a compressed chat's tip; the editor must hold the logical id.
+ sid = row.get("_lineage_root_id") or sid
count = int(row.get("message_count") or 0)
session_cwd = row.get('cwd') or _parse_model_config(row.get("model_config")).get("cwd", ".")
if count <= 0 or (normalized and _normalize_cwd_for_compare(session_cwd) != normalized):
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.py
index 80c8fa2f6f1..d41c0f26c22 100644
--- a/acp_adapter/gateway_server.py
+++ b/acp_adapter/gateway_server.py
@@ -81,6 +81,8 @@ class GatewayACPAgent(acp.Agent):
self._submitting = set()
self._pending_cancels = set()
self._tool_args = {}
+ # Editor-held compression-tip id -> logical session id (see ``_resume``).
+ self._aliases = {}
from hermes_cli.gateway_mutations import PreparedMutations
self._mutations = PreparedMutations()
@@ -133,13 +135,22 @@ class GatewayACPAgent(acp.Agent):
self._snapshots[snapshot["session_id"]] = snapshot
return NewSessionResponse(session_id=snapshot["session_id"])
- async def _resume(self, cwd, session_id, mcp_servers):
+ def _editor_id(self, session_id):
+ return next((held for held, sid in self._aliases.items() if sid == session_id), session_id)
+
+ async def _resume(self, cwd, held_id, mcp_servers):
client = await self._client()
+ from acp_adapter.catalog import logical_session_id
+ session_id = await asyncio.to_thread(logical_session_id, self._home / "state.db", held_id)
+ # The latest load names the id this editor addresses the conversation by.
+ self._aliases = {held: sid for held, sid in self._aliases.items() if sid != session_id}
+ if session_id != held_id:
+ self._aliases[held_id] = session_id
info = await client.rpc("session.info", session_id=session_id)
if "cwd" in info and _normalize_cwd_for_compare(info["cwd"]) != _normalize_cwd_for_compare(_translate_acp_cwd(cwd)):
raise GatewayClientError("cwd_policy_conflict")
if "cwd" not in info and self._conn:
- await self._conn.session_update(session_id=session_id, update=acp.update_agent_message_text(
+ await self._conn.session_update(session_id=held_id, update=acp.update_agent_message_text(
"Attached to the gateway's existing session policy; editor cwd is not applied.\n"))
resume_params = {}
if mcp_servers:
@@ -152,7 +163,7 @@ class GatewayACPAgent(acp.Agent):
from acp_adapter.server import _history_replay_updates
if self._conn:
for update in _history_replay_updates(snapshot["messages"]):
- await self._conn.session_update(session_id=session_id, update=update)
+ await self._conn.session_update(session_id=held_id, update=update)
for pending in snapshot.get("prompts", []):
self._permission(session_id, pending)
return snapshot
@@ -192,6 +203,7 @@ class GatewayACPAgent(acp.Agent):
raise
async def cancel(self, session_id, **kwargs):
+ session_id = self._aliases.get(session_id, session_id)
if session_id not in self._snapshots:
raise GatewayClientError("not_found")
admission_id = self._admissions.get(session_id)
@@ -203,6 +215,7 @@ class GatewayACPAgent(acp.Agent):
async def fork_session(self, cwd, session_id, mcp_servers=None, **kwargs):
from acp.schema import ForkSessionResponse
+ session_id = self._aliases.get(session_id, session_id)
client = await self._client()
info = await client.rpc('session.info', session_id=session_id)
if (mcp_servers or _normalize_cwd_for_compare(info.get('cwd', '')) !=
@@ -216,6 +229,7 @@ class GatewayACPAgent(acp.Agent):
async def set_session_model(self, model_id, session_id, **kwargs):
from acp.schema import SetSessionModelResponse
+ session_id = self._aliases.get(session_id, session_id)
client = await self._client()
payload = {'model': model_id}
await self._mutations.apply(client, session_id, 'model', payload)
@@ -241,6 +255,7 @@ class GatewayACPAgent(acp.Agent):
return ListSessionsResponse(sessions=page, next_cursor=page[-1].session_id if len(rows) > 50 else None)
async def prompt(self, prompt, session_id, **kwargs):
+ held_id, session_id = session_id, self._aliases.get(session_id, session_id)
if session_id not in self._snapshots:
raise GatewayClientError("not_found")
from acp_adapter.content import _content_blocks_to_openai_user_content
@@ -255,7 +270,7 @@ class GatewayACPAgent(acp.Agent):
result = await self._mutations.apply(client, session_id, operation, payload)
if result.get('status') == 'preview':
# Read-only report: nothing changed, so the editor's snapshot is still current.
- await self._conn.session_update(session_id=session_id,
+ await self._conn.session_update(session_id=held_id,
update=acp.update_agent_message_text('\n'.join(result['lines']) + '\n'))
else:
self._snapshots[session_id] = await client.rpc('session.resume', session_id=session_id)
@@ -323,7 +338,8 @@ class GatewayACPAgent(acp.Agent):
self._changed.notify_all()
async def _project(self, event):
- sid, kind, payload = event["session_id"], event.get("type"), event.get("payload", {})
+ kind, payload = event.get("type"), event.get("payload", {})
+ sid, editor_id = event["session_id"], self._editor_id(event["session_id"])
aid = event.get("admission_id")
if kind == "session.replay_gap":
raise GatewayClientError("session_replay_gap")
@@ -342,7 +358,7 @@ class GatewayACPAgent(acp.Agent):
args = coerce_tool_args(payload.get("args"))
self._tool_args[(sid, payload["tool_call_id"])] = (tool_name, args)
if self._conn:
- await self._conn.session_update(session_id=sid,
+ await self._conn.session_update(session_id=editor_id,
update=build_tool_start(payload["tool_call_id"], tool_name, args))
return
if kind == "tool.complete":
@@ -350,7 +366,7 @@ class GatewayACPAgent(acp.Agent):
name, args = self._tool_args.pop((sid, payload["tool_call_id"]), (tool_name, {}))
result = payload.get("result")
if self._conn:
- await self._conn.session_update(session_id=sid, update=build_tool_complete(
+ await self._conn.session_update(session_id=editor_id, update=build_tool_complete(
payload["tool_call_id"], name, result=result if isinstance(result, str) else None,
function_args=args))
return
@@ -358,7 +374,7 @@ class GatewayACPAgent(acp.Agent):
text = payload.get("text", "")
self._streamed[aid] = self._streamed.get(aid, "") + text
if text and self._conn:
- await self._conn.session_update(session_id=sid, update=acp.update_agent_message_text(text))
+ await self._conn.session_update(session_id=editor_id, update=acp.update_agent_message_text(text))
elif kind == "message.complete":
from agent.conversation_loop import INTERRUPT_WAITING_FOR_MODEL_PREFIX
@@ -369,7 +385,7 @@ class GatewayACPAgent(acp.Agent):
prefix = self._streamed.pop(aid, "")
remainder = text[len(prefix):] if text.startswith(prefix) else text
if remainder and self._conn:
- await self._conn.session_update(session_id=sid, update=acp.update_agent_message_text(remainder))
+ await self._conn.session_update(session_id=editor_id, update=acp.update_agent_message_text(remainder))
async with self._changed:
self._terminals[aid] = payload
if len(self._terminals) > 256:
@@ -398,7 +414,7 @@ class GatewayACPAgent(acp.Agent):
tool_call = build_acp_edit_tool_call(EditProposal(**prompt['edit']))
else:
tool_call = _build_permission_tool_call(prompt.get('command', ''), prompt.get('description', ''))
- response = await self._conn.request_permission(session_id=session_id,
+ response = await self._conn.request_permission(session_id=self._editor_id(session_id),
tool_call=tool_call, options=options)
# Transport loss/cancel is not a denial: the canonical waiter belongs
# to the execution and may still be answered by another viewer.
diff --git a/tests/acp_adapter/test_gateway_compressed_reopen.py b/tests/acp_adapter/test_gateway_compressed_reopen.py
new file mode 100644
index 00000000000..fba7f426742
--- /dev/null
+++ b/tests/acp_adapter/test_gateway_compressed_reopen.py
@@ -0,0 +1,86 @@
+"""A compressed editor chat reopens under its logical id (real authority + SQLite, real dispatch).
+
+Compression advances the physical transcript to a new row; the authority's policy, FIFO and live
+session stay keyed by the logical (root) id. The picker and an editor-held tip id must both land
+on that logical id before the first ``session.info``, never on the tip's (absent) policy.
+"""
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+
+
+class _Bridge:
+ """``GatewayClient.rpc`` over a real ``AuthorityConnection.dispatch`` (no socket)."""
+
+ def __init__(self, connection):
+ self.connection, self.events = connection, asyncio.Queue()
+
+ async def rpc(self, method, **params):
+ from hermes_cli.gateway_client import GatewayClientError
+ reply = await self.connection.dispatch({'id': 1, 'method': method, 'params': params})
+ if 'error' in reply:
+ raise GatewayClientError(reply['error']['message'])
+ return reply['result']
+
+
+class _Editor:
+ def __init__(self):
+ self.updates = []
+
+ async def session_update(self, session_id, update, **kwargs):
+ self.updates.append(session_id)
+
+
+async def test_compressed_acp_chat_lists_and_reopens_under_its_logical_id(tmp_path, monkeypatch):
+ from gateway import run
+ from gateway.config import GatewayConfig
+ from gateway.session import SessionStore
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_controls import AuthorityConnection
+ from gateway.session_local import create_local_session
+ from acp_adapter.gateway_server import GatewayACPAgent
+
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'acp': []}})
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False,
+ _cached_agent_for=lambda route: None)
+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)
+ authority = await initialize_session_authority(runner, profile_id='fixture', instance_id='owner')
+ db = authority.db
+ try:
+ connection = AuthorityConnection(authority, object(), {'user_id': 'human', 'profile_id': 'fixture'})
+ ref = create_local_session(authority, connection.actor, {
+ 'request_id': 'editor', 'source': 'acp', 'cwd': str(tmp_path), 'model': 'frozen', 'toolsets': []})
+ db.append_message(ref.session_id, 'user', 'before compression')
+ assert db.try_acquire_compression_lock(ref.session_id, 'fixture')
+ db.publish_compression_child(
+ parent_session_id=ref.session_id, child_session_id='compressed-tip', source='acp',
+ messages=[{'role': 'user', 'content': 'summary'}, {'role': 'assistant', 'content': 'retained'}],
+ compression_lock_holder='fixture')
+ db.release_compression_lock(ref.session_id, 'fixture')
+
+ agent = GatewayACPAgent()
+ agent._home = tmp_path
+ agent._gateway, agent._conn = _Bridge(connection), _Editor()
+ listed = [row.session_id for row in (await agent.list_sessions(cwd=str(tmp_path))).sessions]
+ assert listed == [ref.session_id], 'the picker must offer the logical id, not the physical tip'
+ await agent.load_session(cwd=str(tmp_path), session_id=listed[0], mcp_servers=[])
+ assert list(agent._snapshots) == [ref.session_id]
+
+ # An editor that saved the tip id before this fix still reopens the same conversation,
+ # and every update it sees stays addressed to the id it holds.
+ held = GatewayACPAgent()
+ held._home = tmp_path
+ held._gateway, held._conn = _Bridge(connection), _Editor()
+ await held.load_session(cwd=str(tmp_path), session_id='compressed-tip', mcp_servers=[])
+ assert list(held._snapshots) == [ref.session_id]
+ assert set(held._conn.updates) == {'compressed-tip'}
+ await held._project({'session_id': ref.session_id, 'type': 'message.delta', 'admission_id': 'a',
+ 'payload': {'text': 'live'}})
+ assert held._conn.updates[-1] == 'compressed-tip'
+ await held.cancel('compressed-tip') # resolves to the logical owner instead of not_found
+ finally:
+ store.close_all_db_handles()