Skip to content

The agent that grows with you

fix(acp): a dismissed clarify card skips, and an unanswered prompt is offered again on reattach

Teknium03c1bb79790d
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.py
index dd61c2f3575..ccb3b2edd98 100644
--- a/acp_adapter/gateway_server.py
+++ b/acp_adapter/gateway_server.py
@@ -672,12 +672,24 @@ class GatewayACPAgent(acp.Agent):
return
key = (session_id, prompt["prompt_id"], prompt["execution_generation"])
if key not in self._permissions:
- self._permissions[key] = asyncio.create_task(answer(session_id, prompt))
+ task = asyncio.create_task(answer(session_id, prompt))
+ self._permissions[key] = task
+ task.add_done_callback(lambda done: self._retire_unanswered(key, done))
+
+ def _retire_unanswered(self, key, task):
+ """A card whose response the owner did not accept (editor cancel, transport loss, lost
+ respond RPC) gives up its key, so the next snapshot that still lists the prompt (reattach,
+ ``session/load``) shows a NEW card. An earlier answer is never replayed. An accepted one
+ keeps its key until ``*.settled``, so a replayed request raises no second card."""
+ if self._permissions.get(key) is task and (task.cancelled() or task.exception() is not None
+ or task.result() is not True):
+ del self._permissions[key]
async def _answer_clarify(self, session_id, prompt):
from acp.schema import AllowedOutcome
from acp_adapter.elicitation import (
- ELICITATION_METHOD, build_clarify_elicitation, build_clarify_permission, elicited_answer,
+ ELICITATION_METHOD, SKIP_OPTION, build_clarify_elicitation, build_clarify_permission,
+ elicited_answer,
)
editor_id = self._editor_id(session_id)
try:
@@ -688,16 +700,20 @@ class GatewayACPAgent(acp.Agent):
tool_call, options, answers = build_clarify_permission(prompt)
response = await self._conn.request_permission(
session_id=editor_id, tool_call=tool_call, options=options)
+ # A dismissed card (also what ACP answers for the editor's own Stop) is the Skip a
+ # form decline sends; only an unknown option id is no answer.
answer = (answers.get(response.outcome.option_id)
- if isinstance(response.outcome, AllowedOutcome) else None)
- # No answer (transport loss, editor cancel) leaves the canonical waiter to other viewers.
+ if isinstance(response.outcome, AllowedOutcome) else answers[SKIP_OPTION])
+ # No answer (editor transport loss) leaves the canonical waiter to other viewers.
if answer is None:
- return
+ return False
await self._gateway.rpc("clarify.respond", session_id=session_id, prompt_id=prompt["prompt_id"],
execution_generation=prompt["execution_generation"], answer=answer)
+ return True
except Exception:
# Boundary: as for approvals, a detached editor or expired prompt is not an answer.
logger.info("ACP clarify viewer detached or control expired", exc_info=True)
+ return False
async def _answer_permission(self, session_id, prompt):
from acp.schema import AllowedOutcome
@@ -719,16 +735,18 @@ class GatewayACPAgent(acp.Agent):
# Transport loss/cancel is not a denial: the canonical waiter belongs
# to the execution and may still be answered by another viewer.
if not isinstance(response.outcome, AllowedOutcome):
- return
+ return False
if response.outcome.option_id not in {option.option_id for option in options}:
- return
+ return False
await self._gateway.rpc("approval.respond", session_id=session_id,
prompt_id=prompt["prompt_id"], execution_generation=prompt["execution_generation"],
choice=_OPTION_ID_TO_HERMES[response.outcome.option_id])
+ return True
except Exception:
# Boundary: a detached viewer or expired control is not a denial; the canonical
# waiter stays answerable by another viewer, so nothing propagates.
logger.info("ACP permission viewer detached or control expired", exc_info=True)
+ return False
async def aclose(self):
for task in self._permissions.values():
diff --git a/tests/acp_adapter/test_gateway_editor_clarify.py b/tests/acp_adapter/test_gateway_editor_clarify.py
index 1bc434cd3b9..bfae2f6656d 100644
--- a/tests/acp_adapter/test_gateway_editor_clarify.py
+++ b/tests/acp_adapter/test_gateway_editor_clarify.py
@@ -67,3 +67,33 @@ async def test_editor_answers_canonical_clarify_through_clarify_respond(
await asyncio.sleep(.05)
tool_results = [m for messages in model_peer.requests for m in messages if m["role"] == "tool"]
assert any("green" in json.dumps(m) for m in tool_results), tool_results
+
+
+async def test_dismissed_clarify_card_releases_the_turn_with_skip(daemon, tmp_path, model_peer):
+ """A card-only editor that dismisses the question (or answers it ``cancelled`` for its own
+ Stop) sends the Skip a form decline sends; the turn does not sit out ``clarify_timeout``."""
+ from tests.gateway.fixtures.authority_clarify_peer import ModelPeer as ClarifyPeer
+
+ model_peer.RequestHandlerClass = ClarifyPeer
+ async with viewer(daemon) as ws:
+ sid = (await ws.rpc("session.create", request_id="acp-dismiss", source="cli", cwd=str(tmp_path)))["session_id"]
+ async with editor(daemon, tmp_path) as acp:
+ assert "result" in await acp.rpc("initialize", protocolVersion=1, clientCapabilities={})
+ assert "result" in await acp.rpc("session/load", cwd=str(tmp_path), sessionId=sid, mcpServers=[])
+ turn = asyncio.create_task(acp.rpc("session/prompt", sessionId=sid,
+ prompt=[{"type": "text", "text": "Ask my color"}]))
+ async with asyncio.timeout(30):
+ while not any(f.get("method") == "session/request_permission" for f in acp.frames):
+ assert not turn.done(), turn.result()
+ await asyncio.sleep(.05)
+ request = next(f for f in acp.frames if f.get("method") == "session/request_permission")
+ acp.process.stdin.write(json.dumps({"jsonrpc": "2.0", "id": request["id"],
+ "result": {"outcome": {"outcome": "cancelled"}}}).encode() + b"\n")
+ await acp.process.stdin.drain()
+ reply = await asyncio.wait_for(turn, 30)
+ assert reply.get("result", {}).get("stopReason") == "end_turn", reply
+ assert (await ws.rpc("session.resume", session_id=sid))["prompts"] == []
+ (result,) = {m["content"] for messages in model_peer.requests for m in messages if m["role"] == "tool"}
+ assert [r["user_response"] for r in json.loads(result)["responses"]] == [None], result
diff --git a/tests/acp_adapter/test_gateway_prompt_reoffer.py b/tests/acp_adapter/test_gateway_prompt_reoffer.py
new file mode 100644
index 00000000000..3669421ab31
--- /dev/null
+++ b/tests/acp_adapter/test_gateway_prompt_reoffer.py
@@ -0,0 +1,79 @@
+"""A shared prompt whose ACP card got no accepted answer is shown again on reattach, never auto-answered."""
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+from acp.schema import AllowedOutcome, DeniedOutcome
+
+from acp_adapter.gateway_server import GatewayACPAgent
+from hermes_cli.gateway_client import GatewayClientError
+
+APPROVAL = {"kind": "approval", "prompt_id": "p-1", "execution_generation": 3, "command": "rm -r x",
+ "description": "remove", "choices": ["once", "deny"]}
+CLARIFY = {"kind": "clarify", "prompt_id": "q-1", "execution_generation": 3, "question": "Pick a color",
+ "choices": ["blue", "green"], "multi_select": False}
+
+
+class Editor:
+ """Card-only editor: answers each card from a script (an outcome or a raised transport loss)."""
+
+ def __init__(self, script):
+ self.script, self.cards = list(script), []
+
+ async def request_permission(self, session_id, tool_call, options):
+ self.cards.append([option.option_id for option in options])
+ step = self.script.pop(0)
+ if isinstance(step, Exception):
+ raise step
+ return SimpleNamespace(outcome=step)
+
+
+class Gateway:
+ """The owner: still lists the prompt on every resume; the first respond RPC may be lost."""
+
+ def __init__(self, prompt, lose_first_respond):
+ self.prompt, self.lose, self.responses = prompt, lose_first_respond, []
+
+ async def rpc(self, method, **params):
+ if method == "session.resume":
+ return {"session_id": params["session_id"], "prompts": [self.prompt], "pending": []}
+ self.responses.append((method, params.get("choice", params.get("answer"))))
+ if self.lose:
+ self.lose = False
+ raise GatewayClientError("Gateway disconnected")
+ return {"status": "resolved"}
+
+
+async def _settle(agent):
+ for _ in range(5):
+ await asyncio.gather(*agent._permissions.values(), return_exceptions=True)
+ await asyncio.sleep(0)
+
+
[email protected]("prompt, first, lose_first_respond, accept", [
+ (APPROVAL, DeniedOutcome(outcome="cancelled"), False, ("allow_once", "approval.respond", "once")),
+ (APPROVAL, ConnectionError("editor transport lost"), False, ("allow_once", "approval.respond", "once")),
+ (APPROVAL, AllowedOutcome(outcome="selected", option_id="allow_once"), True, ("deny", "approval.respond", "deny")),
+ (CLARIFY, ConnectionError("editor transport lost"), False, ("choice-1", "clarify.respond", "green")),
+ (CLARIFY, AllowedOutcome(outcome="selected", option_id="choice-0"), True, ("choice-1", "clarify.respond", "green")),
+], ids=["approval-editor-cancel", "approval-transport-loss", "approval-lost-respond",
+ "clarify-transport-loss", "clarify-lost-respond"])
+async def test_unaccepted_card_is_reoffered_on_reattach_without_replaying_its_answer(
+ prompt, first, lose_first_respond, accept):
+ option, method, value = accept
+ editor = Editor([first, AllowedOutcome(outcome="selected", option_id=option)])
+ gateway = Gateway(prompt, lose_first_respond)
+ agent = GatewayACPAgent()
+ agent._conn, agent._gateway, agent._snapshots["s"] = editor, gateway, {}
+ agent._permission("s", prompt) # the live request
+ await _settle(agent)
+ sent_first = list(gateway.responses)
+ await agent._reattach(gateway) # replacement connection / editor session/load: still pending
+ await _settle(agent)
+ assert len(editor.cards) == 2, "the unanswered prompt must be shown again"
+ # The earlier answer is never auto-sent again; only the user's fresh choice reaches the owner.
+ assert gateway.responses == sent_first + [(method, value)]
+ await agent._reattach(gateway) # accepted now: the owner's settle retires it, never a third card
+ await _settle(agent)
+ assert len(editor.cards) == 2