Skip to content

The agent that grows with you

fix(cli): settle a viewer's own lost turn instead of detaching it as queued

Tekniuma03a1c068478
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.py
index 89ac8053422..e869492e8e0 100644
--- a/acp_adapter/gateway_server.py
+++ b/acp_adapter/gateway_server.py
@@ -325,6 +325,10 @@ class GatewayACPAgent(acp.Agent):
if self._admissions.get(session_id) == admission_id:
self._admissions.pop(session_id, None)
outcome = terminal.get("outcome")
+ if outcome == "unknown":
+ # Our own lost turn: the same refusal whether session.info or this completion woke us.
+ raise GatewayClientError("unknown_execution: do not resend accepted input; "
+ "resolve the lost turn before continuing")
if outcome == "failed":
raise GatewayClientError("admitted_turn_failed")
return PromptResponse(stop_reason="cancelled" if outcome == "cancelled" else "end_turn")
diff --git a/hermes_cli/gateway_chat_view.py b/hermes_cli/gateway_chat_view.py
index 46ffc43aa43..40ff8086e9c 100644
--- a/hermes_cli/gateway_chat_view.py
+++ b/hermes_cli/gateway_chat_view.py
@@ -249,6 +249,23 @@ class GatewayChatView:
return self.emitter.emit_result({"failed": True, "error": message}, session_id=self.session_id, exit_code=3)
return 3
+ def _finite_block(self, admission):
+ """Why a finite viewer cannot keep waiting for *admission*, or None. Its own lost turn
+ settles as the unknown completion would, so the exit code never depends on frame order;
+ only a still-queued input behind someone else's unknown turn is retained and detached."""
+ own = next((row["status"] for row in self.pending if row["admission_id"] == admission), None)
+ if own == "unknown":
+ self.completions[admission] = {"outcome": "unknown", "text": (
+ "Execution outcome is unknown. Resume this session to inspect the lost turn "
+ "and /discard it; do not resend the input.")}
+ return None
+ if own == "queued" and self.unknown_admissions():
+ return ("Unknown execution blocks this session; your accepted input is retained. "
+ "Resume interactively to resolve the lost turn; do not resend the input.")
+ if self.prompts:
+ return "Input required; detached without cancelling. Resume this session interactively."
+ return None
+
async def _settled_result(self, admission):
"""The structured result the owner committed with this admission's settlement — the same
dict the in-process one-shot got from ``run_conversation`` (best-effort, never raises)."""
@@ -300,14 +317,11 @@ class GatewayChatView:
self.changed.clear()
if self.failure:
raise self.failure
- if self.unknown_admissions() and any(
- row["admission_id"] == admission and row["status"] in {"queued", "unknown"}
- for row in self.pending):
- return self._detach("Unknown execution blocks this session; your accepted input is retained. "
- "Resume interactively to resolve the lost turn; do not resend the input.")
- if self.prompts:
- return self._detach("Input required; detached without cancelling. Resume this session interactively.")
- await self.changed.wait()
+ blocked = self._finite_block(admission)
+ if blocked:
+ return self._detach(blocked)
+ if admission not in self.completions:
+ await self.changed.wait()
terminal = self.completions[admission]
outcome = terminal.get("outcome")
text = terminal.get("text") or terminal.get("content") or ""
diff --git a/tests/acp_adapter/test_adversarial_clarify_disconnect.py b/tests/acp_adapter/test_adversarial_clarify_disconnect.py
deleted file mode 100644
index b9d7ddea920..00000000000
--- a/tests/acp_adapter/test_adversarial_clarify_disconnect.py
+++ /dev/null
@@ -1,21 +0,0 @@
-"""A detached ACP question viewer cannot answer for another viewer."""
-import asyncio
-from unittest.mock import AsyncMock
-
-import pytest
-
-from acp_adapter.gateway_server import GatewayACPAgent
-
-
[email protected]('kind', ['approval', 'clarify'])
-async def test_editor_transport_exception_leaves_shared_question_unanswered(kind):
- agent = GatewayACPAgent()
- agent._conn = AsyncMock()
- agent._conn.request_permission.side_effect = RuntimeError('editor transport detached')
- agent._gateway = AsyncMock()
- agent._permission('s', {'kind': kind, 'prompt_id': 'question', 'execution_generation': 2,
- 'question': 'Which target?', 'command': 'build', 'choices': ['once']})
- await asyncio.gather(*agent._permissions.values())
- agent._gateway.rpc.assert_not_awaited()
- assert agent._failure is None
diff --git a/tests/acp_adapter/test_adversarial_client_session_identity.py b/tests/acp_adapter/test_adversarial_client_session_identity.py
deleted file mode 100644
index 2bae953435b..00000000000
--- a/tests/acp_adapter/test_adversarial_client_session_identity.py
+++ /dev/null
@@ -1,17 +0,0 @@
-from types import SimpleNamespace
-from unittest.mock import AsyncMock, Mock
-import acp
-import pytest
-from acp_adapter.gateway_server import GatewayACPAgent
-
-async def test_compression_preview_addresses_the_editor_retained_physical_alias():
- agent = GatewayACPAgent()
- agent._conn = AsyncMock()
- gateway = AsyncMock()
- agent._client = AsyncMock(return_value=gateway)
- agent._aliases['editor-tip'] = 'logical-root'
- agent._snapshots['logical-root'] = {}
- agent._mutations = SimpleNamespace(apply=AsyncMock(return_value={'status': 'preview', 'lines': ['retained 10 rows']}), acknowledge=Mock())
- await agent.prompt([acp.text_block('/compress --preview')], 'editor-tip')
- assert agent._conn.session_update.await_args.kwargs['session_id'] == 'editor-tip'
diff --git a/tests/acp_adapter/test_gateway_queued_unknown.py b/tests/acp_adapter/test_gateway_queued_unknown.py
index 7234f319599..750616dcee1 100644
--- a/tests/acp_adapter/test_gateway_queued_unknown.py
+++ b/tests/acp_adapter/test_gateway_queued_unknown.py
@@ -49,3 +49,28 @@ async def test_editor_refuses_new_prompt_until_lost_turn_is_resolved():
with pytest.raises(GatewayClientError, match='unknown_execution'):
await asyncio.wait_for(agent.prompt([acp.text_block('new input')], 's'), 5)
agent._gateway.rpc.assert_not_awaited()
+
+
[email protected]('yield_between', [False, True])
+async def test_editor_own_lost_turn_reports_unknown_not_end_turn(yield_between):
+ # The prompt's own started turn is lost: whichever frame wakes the prompt first, the
+ # editor gets the unknown-execution error, never a successful end_turn.
+ agent = GatewayACPAgent()
+ agent._gateway = AsyncMock()
+ agent._snapshots['s'] = {}
+
+ async def lose_worker():
+ await agent._project({'session_id': 's', 'type': 'session.info',
+ 'payload': {'pending': [{'admission_id': 'ours', 'status': 'unknown'}]}})
+ if yield_between:
+ await asyncio.sleep(0.01)
+ await agent._project({'session_id': 's', 'type': 'message.complete', 'admission_id': 'ours',
+ 'payload': {'outcome': 'unknown', 'text': 'Worker execution is unknown.'}})
+
+ agent._gateway.rpc.return_value = {'admission_id': 'ours'}
+ submitted = asyncio.create_task(agent.prompt([acp.text_block('work')], 's'))
+ await asyncio.sleep(0)
+ await lose_worker()
+ with pytest.raises(GatewayClientError, match='unknown_execution'):
+ await asyncio.wait_for(submitted, 5)
diff --git a/tests/hermes_cli/test_gateway_queued_unknown.py b/tests/hermes_cli/test_gateway_queued_unknown.py
index d6eff384ef8..16e59b3a999 100644
--- a/tests/hermes_cli/test_gateway_queued_unknown.py
+++ b/tests/hermes_cli/test_gateway_queued_unknown.py
@@ -68,3 +68,32 @@ async def test_successor_unknown_does_not_replace_completed_prompt():
view = GatewayChatView(Peer(), {'stored_session_id': 's'}, quiet=True)
assert await asyncio.wait_for(view.run('work', oneshot=True), 5) == 0
+
+
[email protected]('yield_between', [False, True])
+async def test_own_lost_turn_exits_from_its_unknown_completion_not_queued_detach(yield_between, capsys):
+ # Worker loss publishes session.info (ours=unknown), then message.complete(outcome=unknown).
+ # Only a still-queued input was "retained"; a started-then-lost turn settles as a failure (1)
+ # whatever the WebSocket framing between the two frames.
+ class Peer:
+ events = asyncio.Queue()
+
+ async def rpc(self, method, **params):
+ if method == 'prompt.receipt':
+ return {'result': {}}
+
+ async def lose_worker():
+ await asyncio.sleep(0.01)
+ self.events.put_nowait({'method': 'event', 'params': {'session_id': 's', 'type': 'session.info',
+ 'admission_id': 'ours', 'payload': {'pending': [{'admission_id': 'ours', 'status': 'unknown'}]}}})
+ if yield_between:
+ await asyncio.sleep(0.01)
+ self.events.put_nowait({'method': 'event', 'params': {'session_id': 's', 'type': 'message.complete',
+ 'admission_id': 'ours', 'payload': {'outcome': 'unknown', 'text': 'Worker execution is unknown.'}}})
+ asyncio.get_running_loop().create_task(lose_worker())
+ return {'admission_id': 'ours'}
+
+ view = GatewayChatView(Peer(), {'stored_session_id': 's'}, quiet=True)
+ assert await asyncio.wait_for(view.run('work', oneshot=True), 5) == 1
+ assert 'accepted input is retained' not in capsys.readouterr().err