The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: ACP projects every gateway delivery shape exactly once
Tekniumaca168456dcd
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.pyindex e869492e8e0..a6a1d416369 100644--- a/acp_adapter/gateway_server.py+++ b/acp_adapter/gateway_server.py@@ -63,6 +63,12 @@ def _stage_user_content(content):return "\n".join(texts), attachments+def _text(payload):+ """Reply text of a message frame; ``text`` may be present and null (a suppressed delivery)."""+ text = payload.get("text")+ return text if isinstance(text, str) else ""++class GatewayACPAgent(acp.Agent):def __init__(self):self._conn = None@@ -74,6 +80,8 @@ class GatewayACPAgent(acp.Agent):self._event_task = Noneself._terminals = {}self._streamed = {}+ # Admission -> closed reply segments already shown (interim commentary, pre-tool deltas).+ self._segments = {}self._changed = asyncio.Condition()self._failure = Noneself._permissions = {}@@ -392,6 +400,9 @@ class GatewayACPAgent(acp.Agent):# In-process turns publish ``tool_name``; managed workers publish ``name``.tool_name = payload.get("tool_name") or payload.get("name") or "tool"if kind == "tool.start":+ # Deltas before a tool call are commentary the final reply does not repeat: close+ # that segment so ``message.complete`` measures only the final's own stream.+ self._close_segment(aid)from acp_adapter.tools import build_tool_start, coerce_tool_argsargs = coerce_tool_args(payload.get("args"))self._tool_args[(sid, payload["tool_call_id"])] = (tool_name, args)@@ -409,19 +420,22 @@ class GatewayACPAgent(acp.Agent):function_args=args))returnif kind == "message.delta":- text = payload.get("text", "")+ text = _text(payload)self._streamed[aid] = self._streamed.get(aid, "") + textif text and self._conn:await self._conn.session_update(session_id=editor_id, update=acp.update_agent_message_text(text))+ elif kind == "message.interim":+ # Commentary the owner could not stream (``already_streamed`` false) reaches viewers+ # only here; streamed commentary is already on screen. Either way it is its own segment.+ self._close_segment(aid)+ text = _text(payload)+ if not payload.get("already_streamed") and text.strip():+ self._segments.setdefault(aid, []).append(text)+ if self._conn:+ await self._conn.session_update(session_id=editor_id,+ update=acp.update_agent_message_text(text + "\n\n"))elif kind == "message.complete":- from agent.conversation_loop import INTERRUPT_WAITING_FOR_MODEL_PREFIX-- text = payload.get("text", "")- # Local interrupt status is metadata; ACP carries it in stop_reason.- if payload.get("outcome") == "cancelled" and text.startswith(INTERRUPT_WAITING_FOR_MODEL_PREFIX):- text = ""- prefix = self._streamed.pop(aid, "")- remainder = text[len(prefix):] if text.startswith(prefix) else text+ remainder = self._final_remainder(aid, payload)if remainder and self._conn:await self._conn.session_update(session_id=editor_id, update=acp.update_agent_message_text(remainder))async with self._changed:@@ -430,6 +444,33 @@ class GatewayACPAgent(acp.Agent):self._terminals.pop(next(iter(self._terminals)))self._changed.notify_all()+ def _close_segment(self, aid):+ streamed = self._streamed.pop(aid, "")+ if streamed.strip():+ self._segments.setdefault(aid, []).append(streamed)++ def _final_remainder(self, aid, payload):+ """The part of the settled reply the editor has not been shown yet (exactly-once text)."""+ from agent.conversation_loop import INTERRUPT_WAITING_FOR_MODEL_PREFIX++ text = _text(payload)+ streamed = self._streamed.pop(aid, "")+ shown = self._segments.pop(aid, [])+ # Local interrupt status is metadata; ACP carries it in stop_reason.+ if not text or (payload.get("outcome") == "cancelled"+ and text.startswith(INTERRUPT_WAITING_FOR_MODEL_PREFIX)):+ return ""+ if payload.get("response_reused") is True and (streamed or shown):+ # The owner names the final as the reply already painted (never inferred from text).+ return ""+ if text.startswith(streamed):+ remainder = text[len(streamed):]+ # An unstreamed final the owner already published as an interim segment.+ return "" if not streamed and text.strip() in {s.strip() for s in shown} else remainder+ if text.strip() == streamed.strip():+ return ""+ return "\n\n" + text+def _permission(self, session_id, prompt):answer = {"approval": self._answer_permission, "clarify": self._answer_clarify}.get(prompt.get("kind"))if answer is None or self._conn is None:diff --git a/tests/acp_adapter/test_gateway_delivery_shapes.py b/tests/acp_adapter/test_gateway_delivery_shapes.pynew file mode 100644index 00000000000..c81f234f27f--- /dev/null+++ b/tests/acp_adapter/test_gateway_delivery_shapes.py@@ -0,0 +1,75 @@+"""Every delivery shape the owner publishes reaches the editor exactly once, through one live pump."""+import asyncio+from unittest.mock import AsyncMock++import acp+import pytest++from acp_adapter.gateway_server import GatewayACPAgent++COMMENTARY, FINAL = "Let me check the file. ", "FINAL-ANSWER-OMEGA"+SHAPES = {+ # The owner could not stream: the answer arrives only as message.interim, the completion is empty.+ "interim_only": [("message.interim", {"text": FINAL, "already_streamed": False}),+ ("message.complete", {"outcome": "completed", "text": ""})],+ # A suppressed second delivery: the completion's text is present and null.+ "streamed_null_completion": [("message.delta", {"text": FINAL}),+ ("message.complete", {"outcome": "completed", "text": None})],+ # Commentary deltas close at the tool call; the final repeats only its own stream.+ "commentary_tool_final": [("message.delta", {"text": COMMENTARY}),+ ("tool.start", {"tool_call_id": "t1", "tool_name": "terminal", "args": {}}),+ ("tool.complete", {"tool_call_id": "t1", "tool_name": "terminal", "result": "ok"}),+ ("message.delta", {"text": FINAL}),+ ("message.complete", {"outcome": "completed", "text": FINAL})],+ # The owner reuses the reply streamed before a housekeeping tool as the final (``response_reused``).+ "reused_after_tool": [("message.delta", {"text": FINAL}),+ ("tool.start", {"tool_call_id": "t1", "tool_name": "memory", "args": {}}),+ ("tool.complete", {"tool_call_id": "t1", "tool_name": "memory", "result": "ok"}),+ ("message.complete", {"outcome": "completed", "text": FINAL, "response_reused": True})],+}+++class Gateway:+ def __init__(self):+ self.events = asyncio.Queue()+ self.rpc = AsyncMock()+ self.seq = 0++ def publish(self, admission_id, kind, payload):+ self.seq += 1+ self.events.put_nowait({"params": {"session_id": "s", "type": kind, "admission_id": admission_id,+ "replay_epoch": "e", "seq": self.seq, "payload": payload}})+++def editor_text(conn):+ return "".join(call.kwargs["update"].content.text for call in conn.session_update.await_args_list+ if getattr(getattr(call.kwargs["update"], "content", None), "text", None) is not None)++[email protected]("shape", sorted(SHAPES))+async def test_each_delivery_shape_reaches_the_editor_once_and_the_pump_survives(shape):+ agent = GatewayACPAgent()+ agent._gateway = gateway = Gateway()+ agent._conn = AsyncMock()+ agent._snapshots["s"] = {"replay_epoch": "e", "last_sequence": 0}+ agent._event_task = asyncio.create_task(agent._events())+ try:+ for admission_id, frames, prompt in (("a1", SHAPES[shape], "first"),+ ("a2", [("message.complete", {"outcome": "completed",+ "text": "SECOND"})], "second")):+ agent._conn.session_update.reset_mock()+ gateway.rpc.return_value = {"admission_id": admission_id}+ for kind, payload in frames:+ gateway.publish(admission_id, kind, payload)+ response = await asyncio.wait_for(agent.prompt([acp.text_block(prompt)], "s"), 5)+ assert response.stop_reason == "end_turn"+ assert agent._failure is None+ text = editor_text(agent._conn)+ if admission_id == "a1":+ assert text.count(FINAL) == 1, text+ assert text.count(COMMENTARY) == (shape == "commentary_tool_final"), text+ else:+ assert text == "SECOND"+ finally:+ agent._event_task.cancel()