Skip to content

The agent that grows with you

fix(acp): recover unknown turns in editor

KoNit-K0bfd5800f5d2
diff --git a/acp_adapter/gateway_commands.py b/acp_adapter/gateway_commands.py
index 924d754111d..fbcde2592b3 100644
--- a/acp_adapter/gateway_commands.py
+++ b/acp_adapter/gateway_commands.py
@@ -69,6 +69,23 @@ async def _rewind_command(agent, session_id, command, arg):
return await _rewind(agent, await agent._client(), session_id, command, arg)
+async def _discard_unknown(agent, session_id, _command, admission_id):
+ """Acknowledge one exact lost turn and refresh its FIFO snapshot."""
+ if not admission_id:
+ return 'Usage: /discard <lost admission id>', None
+ client = await agent._client()
+ snapshot = await client.rpc('session.resume', session_id=session_id)
+ agent._snapshots[session_id] = snapshot
+ lost = next((row for row in snapshot.get('pending', [])
+ if row.get('admission_id') == admission_id and row.get('status') == 'unknown'), None)
+ if lost is None:
+ return (f'No unknown (lost) admission with id {admission_id}; refresh the session and try again.', None)
+ await client.rpc('prompt.resolve_unknown', session_id=session_id, admission_id=admission_id,
+ execution_generation=lost['execution_generation'])
+ agent._snapshots[session_id] = await client.rpc('session.resume', session_id=session_id)
+ return 'Discarded the lost turn. Queued messages can continue.', None
+
+
async def _forward(agent, client, session_id, command, arg):
"""The owner's ``slash.exec`` answer: its report, a turn to submit (a skill body or the turn a
command built, after its notice), or the shared refusal for a command it does not serve."""
@@ -257,6 +274,7 @@ def _tools_text(info):
# "new session + clear screen"; here it is ``/new``'s reset of this session.
ROUTES = {
'branch': ('ACP fork_session', _branch),
+ 'discard': ('prompt.resolve_unknown', _discard_unknown),
'help': ('local', _help),
'steer': ('session.steer', _prompt),
'queue': ('prompt.submit', _prompt),
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.py
index c27749e066d..d70cb2bb5f9 100644
--- a/acp_adapter/gateway_server.py
+++ b/acp_adapter/gateway_server.py
@@ -37,7 +37,10 @@ def _slash_command(text):
return None
from hermes_cli.commands import resolve_command
command = resolve_command(name)
- return command.name if command is not None else None
+ if command is not None:
+ return command.name
+ from acp_adapter.gateway_commands import ROUTES
+ return name if name in ROUTES else None
def _bypass_route():
@@ -576,13 +579,13 @@ class GatewayACPAgent(GatewayReplyMixin, acp.Agent):
raise GatewayClientError("not_found")
if self._has_unknown(session_id) and await self._refresh_unknown_for_prompt(session_id):
return PromptResponse(stop_reason='cancelled')
- if self._has_unknown(session_id):
- raise GatewayClientError(self._unknown_recovery(session_id, submitted=False))
prepared = await self._prepare_submit(session_id, prompt)
if prepared is None:
return PromptResponse(stop_reason='cancelled')
retry_key, input_id, staged = prepared
text, attachments = staged
+ if self._has_unknown(session_id) and (attachments or _slash_command(text) != 'discard'):
+ raise GatewayClientError(self._unknown_recovery(session_id, submitted=False))
answered, text = await self._run_slash(held_id, session_id, text) if not attachments else (False, text)
if answered:
return PromptResponse(stop_reason='end_turn')
@@ -766,8 +769,9 @@ class GatewayACPAgent(GatewayReplyMixin, acp.Agent):
def _unknown_recovery(self, session_id, admission_id=None, *, submitted=True):
"""The refusal for a FIFO blocked by a lost turn, naming the existing recovery control.
- ACP has no discard affordance; the classic chat's fenced ``/discard`` (``prompt.resolve_unknown``)
- acknowledges the exact lost admission without replaying it, and the queue then continues."""
+ The editor's own ``/discard <id>`` (``acp_adapter.gateway_commands._discard_unknown``, the
+ same fenced ``prompt.resolve_unknown`` the classic chat uses) acknowledges the exact lost
+ admission without replaying it, and the queue then continues."""
from hermes_constants import profile_name_for_home
lost = [row["admission_id"] for row in self._snapshots.get(session_id, {}).get("pending", [])
if row.get("status") == "unknown"] or [admission_id]
@@ -775,9 +779,9 @@ class GatewayACPAgent(GatewayReplyMixin, acp.Agent):
command = "hermes" + (f" -p {profile}" if profile not in (None, "default") else "")
state = ("your input is accepted and kept" if submitted else "nothing was submitted")
return (f"unknown_execution: do not resend accepted input; a turn in this session was lost when the "
- f"gateway restarted and its outcome is unknown ({state}). Resolve it in a terminal with "
- f"`{command} chat --cli --resume {session_id}` then "
- + " and ".join(f"`/discard {lost_id}`" for lost_id in lost) + ", then continue here.")
+ f"gateway restarted and its outcome is unknown ({state}). Send "
+ + " and ".join(f"`/discard {lost_id}`" for lost_id in lost)
+ + f" here (or `{command} sessions discard {session_id}` in a terminal), then continue.")
def _has_unknown(self, session_id):
return any(row.get("status") == "unknown"
diff --git a/tests/acp_adapter/test_gateway_queued_unknown.py b/tests/acp_adapter/test_gateway_queued_unknown.py
index ef7abd823ae..097951fb887 100644
--- a/tests/acp_adapter/test_gateway_queued_unknown.py
+++ b/tests/acp_adapter/test_gateway_queued_unknown.py
@@ -1,7 +1,7 @@
"""Editor prompts fail recoverably when their FIFO becomes unknown."""
import asyncio
from contextlib import suppress
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, call
import acp
import pytest
@@ -230,7 +230,7 @@ async def test_resumed_unknown_turn_names_the_existing_discard_recovery():
with pytest.raises(GatewayClientError) as refused:
await agent.prompt([acp.text_block('new input')], 's')
for text in (notice, str(refused.value)):
- assert 'chat --cli --resume s' in text and f'/discard {lost}' in text, text
+ assert 'sessions discard s' in text and f'/discard {lost}' in text, text
assert 'do not resend' in text
assert 'nothing was submitted' in str(refused.value)
# The prompt refreshed the owner's pending rows; no prompt was submitted.
@@ -238,6 +238,39 @@ async def test_resumed_unknown_turn_names_the_existing_discard_recovery():
assert asked == ['session.info', 'session.resume', 'config.set', 'session.resume']
+async def test_resumed_unknown_turn_can_be_discarded_without_leaving_the_editor():
+ # The editor needs the same fenced recovery as classic chat. It must use the
+ # unknown row's generation, not the session's current generation.
+ agent = GatewayACPAgent()
+ agent._gateway = AsyncMock()
+ lost = 'admission-lost-0123456789abcdef'
+ unknown = {'session_id': 's', 'messages': [], 'prompts': [],
+ 'pending': [{'admission_id': lost, 'status': 'unknown', 'execution_generation': 4}]}
+ cleared = {**unknown, 'pending': []}
+ agent._snapshots['s'] = unknown
+ resolved = []
+
+ def rpc(method, **params):
+ if method == 'prompt.resolve_unknown':
+ resolved.append(params)
+ return {'admission_id': lost, 'status': 'terminal', 'outcome': 'interrupted'}
+ return cleared if resolved else unknown
+ agent._gateway.rpc.side_effect = rpc
+
+ response = await agent.prompt([acp.text_block(f'/discard {lost}')], 's')
+
+ assert response.stop_reason == 'end_turn'
+ assert agent._snapshots['s']['pending'] == []
+ # The pre-prompt refresh asks the owner first (another viewer may have resolved it already).
+ assert agent._gateway.rpc.await_args_list == [
+ call('session.resume', session_id='s'),
+ call('session.resume', session_id='s'),
+ call('prompt.resolve_unknown', session_id='s', admission_id=lost, execution_generation=4),
+ call('session.resume', session_id='s'),
+ ]
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize('yield_between', [False, True])
async def test_editor_own_lost_turn_reports_unknown_not_end_turn(yield_between):