JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat: ACP支持流式输出
zp233314a8dbad01784
diff --git a/jiuwenclaw/app_gateway.py b/jiuwenclaw/app_gateway.pyindex 1ee317dc9c..21da5b5c98 100644--- a/jiuwenclaw/app_gateway.py+++ b/jiuwenclaw/app_gateway.py@@ -27,6 +27,11 @@ from urllib.parse import urlparsefrom dotenv import load_dotenvfrom openjiuwen.core.common.logging import LogManager+from jiuwenclaw.e2a.acp.session_updates import (+ build_acp_final_text_update,+ build_acp_session_update,+ build_acp_usage_update,+)from jiuwenclaw.gateway.route_binding import GatewayRouteBindingfrom jiuwenclaw.jiuwen_core_patch import apply_openai_model_client_patchfrom jiuwenclaw.utils import get_user_workspace_dir, get_env_file, prepare_workspace@@ -129,6 +134,7 @@ class _InboundGatewayServer:_ACP_PENDING_RPC_TIMEOUT_SECONDS = 60.0+_PROMPT_IDLE_FINALIZE_SECONDS = 3.0@dataclass@@ -137,6 +143,7 @@ class _GatewayAcpRequestContext:session_id: strassistant_message_id: str | None = Nonethought_message_id: str | None = None+ idle_finalize_task: asyncio.Task | None = Noneclass AcpRouteHandler:@@ -628,26 +635,35 @@ class GatewayServer:return Falseif msg.type == "event" and msg.event_type == EventType.CHAT_DELTA:- text = str(payload.get("content", "") or "")- if not text:+ update = build_acp_session_update(msg, payload, ctx)+ if update is None:return True- source_chunk_type = str(payload.get("source_chunk_type") or "")- if source_chunk_type == "llm_reasoning":- if not ctx.thought_message_id:- ctx.thought_message_id = f"thought_{uuid_module.uuid4().hex[:12]}"- update = {- "sessionUpdate": "agent_thought_chunk",- "messageId": ctx.thought_message_id,- "content": {"type": "text", "text": text},- }- else:- if not ctx.assistant_message_id:- ctx.assistant_message_id = f"msg_{uuid_module.uuid4().hex[:12]}"- update = {- "sessionUpdate": "agent_message_chunk",- "messageId": ctx.assistant_message_id,- "content": {"type": "text", "text": text},- }+ await self._send_raw_jsonrpc_notification(+ ws,+ "session/update",+ {"sessionId": session_id or ctx.session_id, "update": update},+ )+ usage_update = build_acp_usage_update(payload)+ if usage_update is not None:+ await self._send_raw_jsonrpc_notification(+ ws,+ "session/update",+ {"sessionId": session_id or ctx.session_id, "update": usage_update},+ )+ return True++ if msg.type == "event" and msg.event_type in (+ EventType.CHAT_TOOL_CALL,+ EventType.CHAT_TOOL_RESULT,+ EventType.CHAT_SUBTASK_UPDATE,+ ):+ update = build_acp_session_update(msg, payload, ctx)+ if update is None:+ return True+ task = ctx.idle_finalize_task+ if task is not None:+ task.cancel()+ ctx.idle_finalize_task = Noneawait self._send_raw_jsonrpc_notification(ws,"session/update",@@ -656,41 +672,91 @@ class GatewayServer:return Trueif msg.type == "event" and msg.event_type == EventType.CHAT_FINAL:- content = str(payload.get("content", "") or "")- if content and not ctx.assistant_message_id:- ctx.assistant_message_id = f"msg_{uuid_module.uuid4().hex[:12]}"+ update = build_acp_final_text_update(payload, ctx)+ if update is not None:await self._send_raw_jsonrpc_notification(ws,"session/update",{"sessionId": session_id or ctx.session_id,- "update": {- "sessionUpdate": "agent_message_chunk",- "messageId": ctx.assistant_message_id,- "content": {"type": "text", "text": content},- },+ "update": update,},)- await self._send_raw_jsonrpc_result(ws, ctx.jsonrpc_id, {"stopReason": "end_turn"})- self._acp_request_ctx_by_request_id.pop(str(msg.id), None)- if self._acp_active_prompt_request_by_session.get(ctx.session_id) == str(msg.id):- self._acp_active_prompt_request_by_session.pop(ctx.session_id, None)+ usage_update = build_acp_usage_update(payload)+ if usage_update is not None:+ await self._send_raw_jsonrpc_notification(+ ws,+ "session/update",+ {+ "sessionId": session_id or ctx.session_id,+ "update": usage_update,+ },+ )+ self._schedule_acp_idle_finalize(str(msg.id), ctx, ws)return Trueif msg.type == "event" and msg.event_type == EventType.CHAT_ERROR:+ task = ctx.idle_finalize_task+ if task is not None:+ task.cancel()+ ctx.idle_finalize_task = Noneawait self._send_raw_jsonrpc_error(ws,ctx.jsonrpc_id,-32603,str(payload.get("error") or payload.get("content") or "Agent error"),)- self._acp_request_ctx_by_request_id.pop(str(msg.id), None)- if self._acp_active_prompt_request_by_session.get(ctx.session_id) == str(msg.id):- self._acp_active_prompt_request_by_session.pop(ctx.session_id, None)+ self._clear_acp_request_context(str(msg.id), ctx.session_id)+ return True++ if msg.type == "event" and msg.event_type == EventType.CHAT_PROCESSING_STATUS:+ update = build_acp_session_update(msg, payload, ctx)+ if update is not None:+ await self._send_raw_jsonrpc_notification(+ ws,+ "session/update",+ {"sessionId": session_id or ctx.session_id, "update": update},+ )+ if payload.get("is_processing") is False:+ task = ctx.idle_finalize_task+ if task is not None:+ task.cancel()+ ctx.idle_finalize_task = None+ await self._send_raw_jsonrpc_result(ws, ctx.jsonrpc_id, {"stopReason": "end_turn"})+ self._clear_acp_request_context(str(msg.id), ctx.session_id)return Truereturn False+ def _clear_acp_request_context(self, request_id: str, session_id: str) -> None:+ ctx = self._acp_request_ctx_by_request_id.pop(request_id, None)+ if ctx is not None and ctx.idle_finalize_task is not None:+ ctx.idle_finalize_task.cancel()+ ctx.idle_finalize_task = None+ if self._acp_active_prompt_request_by_session.get(session_id) == request_id:+ self._acp_active_prompt_request_by_session.pop(session_id, None)++ def _schedule_acp_idle_finalize(self, request_id: str, ctx: _GatewayAcpRequestContext, ws: Any) -> None:+ task = ctx.idle_finalize_task+ if task is not None:+ task.cancel()+ ctx.idle_finalize_task = asyncio.create_task(+ self._acp_idle_finalize_after_timeout(request_id, ws),+ name=f"gateway-acp-idle-finalize-{request_id}",+ )++ async def _acp_idle_finalize_after_timeout(self, request_id: str, ws: Any) -> None:+ current_task = asyncio.current_task()+ try:+ await asyncio.sleep(_PROMPT_IDLE_FINALIZE_SECONDS)+ ctx = self._acp_request_ctx_by_request_id.get(request_id)+ if ctx is None or ctx.idle_finalize_task is not current_task:+ return+ await self._send_raw_jsonrpc_result(ws, ctx.jsonrpc_id, {"stopReason": "end_turn"})+ self._clear_acp_request_context(request_id, ctx.session_id)+ except asyncio.CancelledError:+ return+async def _connection_handler(self, ws: Any, path: str | None = None) -> None:raw_path = path if path is not None else getattr(ws, "path", "")parsed = urlparse(raw_path)diff --git a/jiuwenclaw/channel/acp_channel.py b/jiuwenclaw/channel/acp_channel.pyindex ced0f1c348..cd67d0933c 100644--- a/jiuwenclaw/channel/acp_channel.py+++ b/jiuwenclaw/channel/acp_channel.py@@ -12,6 +12,11 @@ from dataclasses import dataclass, fieldfrom typing import Any, Callablefrom jiuwenclaw.channel.base import BaseChannel, RobotMessageRouter+from jiuwenclaw.e2a.acp.session_updates import (+ build_acp_final_text_update,+ build_acp_session_update,+ build_acp_usage_update,+)from jiuwenclaw.e2a.adapters import envelope_from_acp_jsonrpcfrom jiuwenclaw.e2a.constants import (E2A_RESPONSE_KIND_ACP_JSONRPC_ERROR,@@ -685,21 +690,14 @@ class AcpChannel(BaseChannel):text = str(payload.get("content", "") or "")if not text:return False- self._schedule_idle_finalize(str(msg.id), ctx)update = self._build_acp_session_update(msg, payload, ctx)if update is None:return Falseawait self._write_acp_session_update(session_id, update)# 如果 CHAT_DELTA 携带 usage,也发送 usage_update- usage = payload.get("usage")- if isinstance(usage, dict) and usage:- await self._write_acp_session_update(- session_id,- {- "sessionUpdate": "usage_update",- "usage": dict(usage),- },- )+ usage_update = build_acp_usage_update(payload)+ if usage_update is not None:+ await self._write_acp_session_update(session_id, usage_update)return Falseif msg.type == "event" and msg.event_type in (@@ -718,41 +716,14 @@ class AcpChannel(BaseChannel):return Falseif msg.type == "event" and msg.event_type == EventType.CHAT_FINAL:- # ACP 兜底:不要立即发送 end_turn,因为 AgentServer 可能还会发送更多事件- # 只记录内容,等待 is_processing=false 时再发送最终响应- content = str(payload.get("content", "") or "")- if not content:- return False- # 检查 payload.event_type 是否是 reasoning,决定使用哪种 sessionUpdate 类型- payload_event_type = str(payload.get("event_type") or "")- is_reasoning = payload_event_type == "chat.reasoning"- if is_reasoning:- # reasoning 内容作为 thought 发送- if not ctx.thought_message_id:- ctx.thought_message_id = f"thought_{uuid.uuid4().hex[:12]}"- await self._write_acp_session_update(- session_id,- {- "sessionUpdate": "agent_thought_chunk",- "messageId": ctx.thought_message_id,- "content": {"type": "text", "text": content},- },- )- else:- # chat.final 内容不发送 agent_message_chunk,因为 chat.delta 已经发送过了- # 只记录 messageId 用于后续可能的引用- if not ctx.assistant_message_id:- ctx.assistant_message_id = f"msg_{uuid.uuid4().hex[:12]}"- usage = payload.get("usage")- if isinstance(usage, dict) and usage:- await self._write_acp_session_update(- session_id,- {- "sessionUpdate": "usage_update",- "usage": dict(usage),- },- )- # 不发送 end_turn,等待 is_processing=false 时再发送+ # ACP fallback: defer end_turn until processing stops.+ update = build_acp_final_text_update(payload, ctx)+ if update is not None:+ await self._write_acp_session_update(session_id, update)+ usage_update = build_acp_usage_update(payload)+ if usage_update is not None:+ await self._write_acp_session_update(session_id, usage_update)+ self._schedule_idle_finalize(str(msg.id), ctx)return Falseif msg.type == "event" and msg.event_type == EventType.CHAT_ERROR:@@ -837,83 +808,8 @@ class AcpChannel(BaseChannel):payload: dict[str, Any],ctx: _AcpRequestContext,) -> dict[str, Any] | None:- event_type = msg.event_type- if event_type == EventType.CHAT_DELTA:- text = str(payload.get("content", "") or "")- if not text:- return None- source_chunk_type = str(payload.get("source_chunk_type") or "")- # ACP 兜底:检查 payload 中的原始 event_type,如果是 chat.reasoning 则作为 thought 处理- payload_event_type = str(payload.get("event_type") or "")- is_reasoning = (- source_chunk_type == "llm_reasoning"- or payload_event_type == "chat.reasoning"- )+ return build_acp_session_update(msg, payload, ctx)- if is_reasoning:- if not ctx.thought_message_id:- ctx.thought_message_id = f"thought_{uuid.uuid4().hex[:12]}"- return {- "sessionUpdate": "agent_thought_chunk",- "messageId": ctx.thought_message_id,- "content": {"type": "text", "text": text},- }-- if not ctx.assistant_message_id:- ctx.assistant_message_id = f"msg_{uuid.uuid4().hex[:12]}"- return {- "sessionUpdate": "agent_message_chunk",- "messageId": ctx.assistant_message_id,- "content": {"type": "text", "text": text},- }-- if event_type == EventType.CHAT_TOOL_CALL:- tool_call = payload.get("tool_call")- if not isinstance(tool_call, dict):- return None- tool_call_id = str(- tool_call.get("tool_call_id")- or tool_call.get("toolCallId")- or tool_call.get("id")- or ""- )- return {- "sessionUpdate": "tool_call",- "toolCall": {- "id": tool_call_id,- "name": str(tool_call.get("name") or ""),- "arguments": tool_call.get("arguments", {}),- },- }-- if event_type == EventType.CHAT_TOOL_RESULT:- tool_call_id = str(payload.get("tool_call_id") or payload.get("toolCallId") or "")- tool_name = str(payload.get("tool_name") or payload.get("name") or "")- result: Any = payload.get("result")- if result is None:- result = payload.get("content", "")- update = {- "sessionUpdate": "tool_call_update",- "toolCallId": tool_call_id,- "result": result,- }- if tool_name:- update["toolName"] = tool_name- return update-- if event_type == EventType.CHAT_SUBTASK_UPDATE:- return {- "sessionUpdate": "plan",- "plan": dict(payload),- }-- if event_type == EventType.CHAT_PROCESSING_STATUS:- return {- "sessionUpdate": "session_info_update",- "status": "processing" if bool(payload.get("is_processing", True)) else "idle",- }-- return None@staticmethoddef _is_jsonrpc_request(data: Any) -> bool:diff --git a/jiuwenclaw/e2a/acp/__init__.py b/jiuwenclaw/e2a/acp/__init__.pynew file mode 100644index 0000000000..8b20f9a354--- /dev/null+++ b/jiuwenclaw/e2a/acp/__init__.py@@ -0,0 +1,13 @@+from jiuwenclaw.e2a.acp.session_updates import (+ AcpSessionUpdateState,+ build_acp_final_text_update,+ build_acp_session_update,+ build_acp_usage_update,+)++__all__ = [+ "AcpSessionUpdateState",+ "build_acp_final_text_update",+ "build_acp_session_update",+ "build_acp_usage_update",+]diff --git a/jiuwenclaw/e2a/acp/session_updates.py b/jiuwenclaw/e2a/acp/session_updates.pynew file mode 100644index 0000000000..284b68fe0a--- /dev/null+++ b/jiuwenclaw/e2a/acp/session_updates.py@@ -0,0 +1,137 @@+from __future__ import annotations++import uuid+from typing import Any, Protocol++from jiuwenclaw.schema.message import EventType, Message+++class AcpSessionUpdateState(Protocol):+ assistant_message_id: str | None+ thought_message_id: str | None+++def _ensure_assistant_message_id(state: AcpSessionUpdateState) -> str:+ if not state.assistant_message_id:+ state.assistant_message_id = f"msg_{uuid.uuid4().hex[:12]}"+ return str(state.assistant_message_id)+++def _ensure_thought_message_id(state: AcpSessionUpdateState) -> str:+ if not state.thought_message_id:+ state.thought_message_id = f"thought_{uuid.uuid4().hex[:12]}"+ return str(state.thought_message_id)+++def build_acp_session_update(+ msg: Message,+ payload: dict[str, Any],+ state: AcpSessionUpdateState,+) -> dict[str, Any] | None:+ event_type = msg.event_type+ if event_type == EventType.CHAT_DELTA:+ text = str(payload.get("content", "") or "")+ if not text:+ return None+ source_chunk_type = str(payload.get("source_chunk_type") or "")+ payload_event_type = str(payload.get("event_type") or "")+ is_reasoning = (+ source_chunk_type == "llm_reasoning"+ or payload_event_type == "chat.reasoning"+ )++ if is_reasoning:+ return {+ "sessionUpdate": "agent_thought_chunk",+ "messageId": _ensure_thought_message_id(state),+ "content": {"type": "text", "text": text},+ }++ return {+ "sessionUpdate": "agent_message_chunk",+ "messageId": _ensure_assistant_message_id(state),+ "content": {"type": "text", "text": text},+ }++ if event_type == EventType.CHAT_TOOL_CALL:+ tool_call = payload.get("tool_call")+ if not isinstance(tool_call, dict):+ return None+ tool_call_id = str(+ tool_call.get("tool_call_id")+ or tool_call.get("toolCallId")+ or tool_call.get("id")+ or ""+ )+ return {+ "sessionUpdate": "tool_call",+ "toolCall": {+ "id": tool_call_id,+ "name": str(tool_call.get("name") or ""),+ "arguments": tool_call.get("arguments", {}),+ },+ }++ if event_type == EventType.CHAT_TOOL_RESULT:+ tool_call_id = str(payload.get("tool_call_id") or payload.get("toolCallId") or "")+ tool_name = str(payload.get("tool_name") or payload.get("name") or "")+ result: Any = payload.get("result")+ if result is None:+ result = payload.get("content", "")+ update = {+ "sessionUpdate": "tool_call_update",+ "toolCallId": tool_call_id,+ "result": result,+ }+ if tool_name:+ update["toolName"] = tool_name+ return update++ if event_type == EventType.CHAT_SUBTASK_UPDATE:+ return {+ "sessionUpdate": "plan",+ "plan": dict(payload),+ }++ if event_type == EventType.CHAT_PROCESSING_STATUS:+ return {+ "sessionUpdate": "session_info_update",+ "status": "processing" if bool(payload.get("is_processing", True)) else "idle",+ }++ return None+++def build_acp_final_text_update(+ payload: dict[str, Any],+ state: AcpSessionUpdateState,+) -> dict[str, Any] | None:+ text = str(payload.get("content", "") or "")+ if not text:+ return None++ if str(payload.get("event_type") or "") == "chat.reasoning":+ return {+ "sessionUpdate": "agent_thought_chunk",+ "messageId": _ensure_thought_message_id(state),+ "content": {"type": "text", "text": text},+ }++ if state.assistant_message_id:+ return None++ return {+ "sessionUpdate": "agent_message_chunk",+ "messageId": _ensure_assistant_message_id(state),+ "content": {"type": "text", "text": text},+ }+++def build_acp_usage_update(payload: dict[str, Any]) -> dict[str, Any] | None:+ usage = payload.get("usage")+ if not isinstance(usage, dict) or not usage:+ return None+ return {+ "sessionUpdate": "usage_update",+ "usage": dict(usage),+ }diff --git a/jiuwenclaw/gateway/agent_client.py b/jiuwenclaw/gateway/agent_client.pyindex 365085f331..50abc7466c 100644--- a/jiuwenclaw/gateway/agent_client.py+++ b/jiuwenclaw/gateway/agent_client.py@@ -22,6 +22,7 @@ from jiuwenclaw.schema.agent import AgentResponse, AgentResponseChunklogger = logging.getLogger(__name__)+_STREAM_TRAILING_MESSAGE_GRACE_SECONDS = 0.35def _wire_request_id_key(request_id: Any) -> str:@@ -317,8 +318,18 @@ class WebSocketAgentServerClient(AgentServerClient):# 从队列中接收流式响应chunk_count = 0+ saw_complete = Falsewhile True:- data = await queue.get()+ if saw_complete:+ try:+ data = await asyncio.wait_for(+ queue.get(),+ timeout=_STREAM_TRAILING_MESSAGE_GRACE_SECONDS,+ )+ except asyncio.TimeoutError:+ break+ else:+ data = await queue.get()logger.info("[WebSocketAgentServerClient] 收到流式事件 raw: %s", json.dumps(data, ensure_ascii=False))chunk = parse_agent_server_wire_chunk(data)chunk_count += 1@@ -328,7 +339,7 @@ class WebSocketAgentServerClient(AgentServerClient):)yield chunkif chunk.is_complete:- break+ saw_complete = Truelogger.info("[WebSocketAgentServerClient] 流式响应结束: request_id=%s 共 %s 个 chunk", rid, chunk_count)except asyncio.CancelledError:logger.info("[WebSocketAgentServerClient] 流式接收被取消: request_id=%s", rid)diff --git a/tests/unit_tests/channel/test_acp_channel.py b/tests/unit_tests/channel/test_acp_channel.pyindex 1a7b527be5..ecd8293793 100644--- a/tests/unit_tests/channel/test_acp_channel.py+++ b/tests/unit_tests/channel/test_acp_channel.py@@ -376,6 +376,81 @@ async def test_jsonrpc_session_prompt_accepts_text_param(monkeypatch):assert result.get("stopReason") == "end_turn"+async def test_jsonrpc_session_prompt_emits_final_text_as_agent_message_chunk(monkeypatch):+ fake_stdin = FakeStdin(+ [+ json_line(+ {+ "jsonrpc": "2.0",+ "id": 302,+ "method": "session/prompt",+ "params": {+ "sessionId": "sess-final-only",+ "text": "hello from final only",+ },+ }+ ),+ ]+ )+ fake_stdout = FakeStdout()+ channel = AcpChannel(AcpChannelConfig(enabled=True), DummyBus())++ monkeypatch.setattr("sys.stdin", fake_stdin)+ monkeypatch.setattr("sys.stdout", fake_stdout)+ monkeypatch.setattr("jiuwenclaw.channel.acp_channel._ACP_STDOUT", fake_stdout)++ async def _on_message(msg):+ await channel.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"content": "final answer from chat.final"},+ event_type=EventType.CHAT_FINAL,+ )+ )+ await channel.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"is_processing": False},+ event_type=EventType.CHAT_PROCESSING_STATUS,+ )+ )++ channel.on_message(_on_message)+ await channel.start()++ responses = fake_stdout.buffer.json_lines()+ assert len(responses) == 3+ assert responses[0]["method"] == "session/update"+ assert responses[0]["params"]["sessionId"] == "sess-final-only"+ assert responses[0]["params"]["update"]["sessionUpdate"] == "agent_message_chunk"+ assert responses[0]["params"]["update"]["content"] == {+ "type": "text",+ "text": "final answer from chat.final",+ }+ assert responses[1]["params"]["update"] == {+ "sessionUpdate": "session_info_update",+ "status": "idle",+ }+ assert responses[2] == {+ "jsonrpc": "2.0",+ "id": 302,+ "result": {"stopReason": "end_turn"},+ }++@pytest.mark.asyncioasync def test_jsonrpc_session_prompt_merges_session_context(monkeypatch):fake_stdin = FakeStdin(@@ -455,7 +530,7 @@ async def test_jsonrpc_session_prompt_merges_session_context(monkeypatch):@pytest.mark.asyncio-async def test_jsonrpc_session_prompt_auto_finalizes_after_idle(monkeypatch):+async def test_jsonrpc_session_prompt_auto_finalizes_after_idle_after_chat_final(monkeypatch):fake_stdin = FakeStdin([json_line(@@ -490,8 +565,8 @@ async def test_jsonrpc_session_prompt_auto_finalizes_after_idle(monkeypatch):params={},timestamp=time.time(),ok=True,- payload={"content": "partial answer"},- event_type=EventType.CHAT_DELTA,+ payload={"content": "final answer"},+ event_type=EventType.CHAT_FINAL,))@@ -513,6 +588,60 @@ async def test_jsonrpc_session_prompt_auto_finalizes_after_idle(monkeypatch):assert result.get("stopReason") == "end_turn"+async def test_jsonrpc_session_prompt_does_not_auto_finalize_from_delta_only(monkeypatch):+ fake_stdin = FakeStdin(+ [+ json_line(+ {+ "jsonrpc": "2.0",+ "id": 121,+ "method": "session/prompt",+ "params": {+ "sessionId": "sess-delta-only",+ "prompt": [{"type": "text", "text": "hello"}],+ },+ }+ )+ ]+ )+ fake_stdout = FakeStdout()+ channel = AcpChannel(AcpChannelConfig(enabled=True), DummyBus())++ monkeypatch.setattr("sys.stdin", fake_stdin)+ monkeypatch.setattr("sys.stdout", fake_stdout)+ monkeypatch.setattr("jiuwenclaw.channel.acp_channel._ACP_STDOUT", fake_stdout)+ monkeypatch.setattr("jiuwenclaw.channel.acp_channel._PROMPT_IDLE_FINALIZE_SECONDS", 0.01)+ monkeypatch.setattr("jiuwenclaw.channel.acp_channel._STDIN_EOF_GRACE_SECONDS", 0.05)++ async def _on_message(msg):+ await channel.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"content": "partial answer"},+ event_type=EventType.CHAT_DELTA,+ )+ )+ # delta-only 场景不会自动 end_turn;显式停止通道,避免测试等待未完成请求而超时。+ await channel.stop()++ channel.on_message(_on_message)+ await channel.start()++ responses = fake_stdout.buffer.json_lines()+ assert len(responses) == 1+ update = responses[0]["params"]["update"]+ assert update["sessionUpdate"] == "agent_message_chunk"+ assert isinstance(update.get("messageId"), str)+ assert update["content"] == {"type": "text", "text": "partial answer"}++@pytest.mark.asyncioasync def test_jsonrpc_session_cancel_finalizes_active_prompt(monkeypatch):fake_stdin = FakeStdin(diff --git a/tests/unit_tests/gateway/test_app_gateway_acp.py b/tests/unit_tests/gateway/test_app_gateway_acp.pyindex 86fefda0e5..f67afffd42 100644--- a/tests/unit_tests/gateway/test_app_gateway_acp.py+++ b/tests/unit_tests/gateway/test_app_gateway_acp.py@@ -1,3 +1,4 @@+import asyncioimport jsonimport timefrom typing import Any@@ -320,6 +321,19 @@ async def test_gateway_server_handles_acp_jsonrpc_prompt_and_streams_back_jsonrpevent_type=EventType.CHAT_FINAL,))+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"is_processing": False},+ event_type=EventType.CHAT_PROCESSING_STATUS,+ )+ )server.on_message(on_message)@@ -345,6 +359,7 @@ async def test_gateway_server_handles_acp_jsonrpc_prompt_and_streams_back_jsonrpassert seen[0].params["query"] == "hello"assert ws.sent_frames[0]["method"] == "session/update"+ assert ws.sent_frames[1]["method"] == "session/update"assert ws.sent_frames[0]["params"]["sessionId"] == "sess-jsonrpc"assert ws.sent_frames[-1] == {"jsonrpc": "2.0",@@ -353,6 +368,282 @@ async def test_gateway_server_handles_acp_jsonrpc_prompt_and_streams_back_jsonrp}+async def test_gateway_server_emits_agent_message_chunk_from_chat_final_when_no_delta():+ server = build_server()+ ws = FakeWebSocket()++ async def on_message(msg):+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"content": "gateway final only"},+ event_type=EventType.CHAT_FINAL,+ )+ )+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"is_processing": False},+ event_type=EventType.CHAT_PROCESSING_STATUS,+ )+ )++ server.on_message(on_message)++ await server.handle_raw_message_public(+ ws,+ json.dumps(+ {+ "jsonrpc": "2.0",+ "id": 199,+ "method": "session/prompt",+ "params": {+ "sessionId": "sess-gateway-final",+ "text": "hello",+ },+ },+ ensure_ascii=False,+ ),+ )++ assert ws.sent_frames[0]["method"] == "session/update"+ assert ws.sent_frames[0]["params"]["sessionId"] == "sess-gateway-final"+ assert ws.sent_frames[0]["params"]["update"]["sessionUpdate"] == "agent_message_chunk"+ assert ws.sent_frames[0]["params"]["update"]["content"] == {+ "type": "text",+ "text": "gateway final only",+ }+ assert ws.sent_frames[1]["method"] == "session/update"+ assert ws.sent_frames[1]["params"]["update"] == {+ "sessionUpdate": "session_info_update",+ "status": "idle",+ }+ assert ws.sent_frames[2] == {+ "jsonrpc": "2.0",+ "id": 199,+ "result": {"stopReason": "end_turn"},+ }+++async def test_gateway_server_defers_end_turn_until_processing_idle_after_final_and_tool_updates():+ server = build_server()+ ws = FakeWebSocket()++ async def on_message(msg):+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"content": "partial"},+ event_type=EventType.CHAT_DELTA,+ )+ )+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"content": "final"},+ event_type=EventType.CHAT_FINAL,+ )+ )+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={+ "tool_name": "read_file",+ "tool_call_id": "tool-call-9",+ "result": "still running",+ },+ event_type=EventType.CHAT_TOOL_RESULT,+ )+ )+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"is_processing": False},+ event_type=EventType.CHAT_PROCESSING_STATUS,+ )+ )++ server.on_message(on_message)++ await server.handle_raw_message_public(+ ws,+ json.dumps(+ {+ "jsonrpc": "2.0",+ "id": 299,+ "method": "session/prompt",+ "params": {+ "sessionId": "sess-final-tool",+ "text": "hello",+ },+ },+ ensure_ascii=False,+ ),+ )++ assert ws.sent_frames[0]["method"] == "session/update"+ assert ws.sent_frames[0]["params"]["update"]["sessionUpdate"] == "agent_message_chunk"+ assert ws.sent_frames[1]["method"] == "session/update"+ assert ws.sent_frames[1]["params"]["update"] == {+ "sessionUpdate": "tool_call_update",+ "toolCallId": "tool-call-9",+ "toolName": "read_file",+ "result": "still running",+ }+ assert ws.sent_frames[2]["method"] == "session/update"+ assert ws.sent_frames[2]["params"]["update"] == {+ "sessionUpdate": "session_info_update",+ "status": "idle",+ }+ assert ws.sent_frames[3] == {+ "jsonrpc": "2.0",+ "id": 299,+ "result": {"stopReason": "end_turn"},+ }+++async def test_gateway_server_idle_finalize_falls_back_when_processing_status_missing_after_chat_final(monkeypatch):+ import jiuwenclaw.app_gateway as gateway_module++ monkeypatch.setattr(gateway_module, "_PROMPT_IDLE_FINALIZE_SECONDS", 0.01)+ server = build_server()+ ws = FakeWebSocket()++ async def on_message(msg):+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"content": "final answer"},+ event_type=EventType.CHAT_FINAL,+ )+ )++ server.on_message(on_message)++ await server.handle_raw_message_public(+ ws,+ json.dumps(+ {+ "jsonrpc": "2.0",+ "id": 399,+ "method": "session/prompt",+ "params": {+ "sessionId": "sess-idle-fallback",+ "text": "hello",+ },+ },+ ensure_ascii=False,+ ),+ )+ await asyncio.sleep(0.03)++ assert ws.sent_frames[0]["method"] == "session/update"+ assert ws.sent_frames[0]["params"]["update"]["sessionUpdate"] == "agent_message_chunk"+ assert ws.sent_frames[1] == {+ "jsonrpc": "2.0",+ "id": 399,+ "result": {"stopReason": "end_turn"},+ }+++async def test_gateway_server_delta_only_does_not_trigger_idle_finalize(monkeypatch):+ import jiuwenclaw.app_gateway as gateway_module++ monkeypatch.setattr(gateway_module, "_PROMPT_IDLE_FINALIZE_SECONDS", 0.01)+ server = build_server()+ ws = FakeWebSocket()++ async def on_message(msg):+ await server.send(+ Message(+ id=msg.id,+ type="event",+ channel_id="acp",+ session_id=msg.session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={"content": "partial answer"},+ event_type=EventType.CHAT_DELTA,+ )+ )++ server.on_message(on_message)++ await server.handle_raw_message_public(+ ws,+ json.dumps(+ {+ "jsonrpc": "2.0",+ "id": 400,+ "method": "session/prompt",+ "params": {+ "sessionId": "sess-delta-only",+ "text": "hello",+ },+ },+ ensure_ascii=False,+ ),+ )+ await asyncio.sleep(0.03)++ assert len(ws.sent_frames) == 1+ assert ws.sent_frames[0]["jsonrpc"] == "2.0"+ assert ws.sent_frames[0]["method"] == "session/update"+ params = ws.sent_frames[0]["params"]+ assert params["sessionId"] == "sess-delta-only"+ update = params["update"]+ assert update["sessionUpdate"] == "agent_message_chunk"+ assert isinstance(update.get("messageId"), str)+ assert update["content"] == {"type": "text", "text": "partial answer"}++@pytest.mark.asyncioasync def test_gateway_server_handle_raw_message_forwards_request():server = build_server()