Skip to content

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

fix(runtime): coalesce mirrored subagent reasoning to keep long PPT streams alive

n9935770281a93cd1fdb4c
diff --git a/jiuwenswarm/agents/harness/common/tools/subagent_compat.py b/jiuwenswarm/agents/harness/common/tools/subagent_compat.py
index bf50f7132c..a57e3ef15e 100644
--- a/jiuwenswarm/agents/harness/common/tools/subagent_compat.py
+++ b/jiuwenswarm/agents/harness/common/tools/subagent_compat.py
@@ -5,6 +5,7 @@
from __future__ import annotations
import logging
+import time
from dataclasses import replace
from typing import Any
@@ -29,15 +30,41 @@ logger = logging.getLogger(__name__)
# becomes chat.final, ``content_chunk`` becomes chat.delta and flips the
# parent's streamed-content flag, ``error`` fails the whole parent turn, and
# the child's own task.* / todo.updated frames would pollute the parent task
-# list — all of those stay on the child session.
-_MIRROR_CHUNK_TYPES = frozenset({"llm_reasoning", "tool_call", "tool_update", "tool_result"})
+# list — all of those stay on the child session. ``tool_update`` is one
+# progress frame per call; RelayClaw drops it outside team mode, so mirroring
+# it only adds parent-socket traffic.
+_MIRROR_CHUNK_TYPES = frozenset({"llm_reasoning", "tool_call", "tool_result"})
# A child task_id would open a phantom task segment on the parent stream.
_MIRROR_STRIP_KEYS = ("task_id", "parent_request_id")
+# Token-level reasoning from several page subagents overflows the parent
+# websocket and trips keepalive. Coalesce the original text, do not summarize.
+_REASONING_FLUSH_CHARS = 200
+_REASONING_FLUSH_INTERVAL_S = 0.3
+_REASONING_FRAME_CAP = 2000
+
+
+def _child_reasoning_text(payload: object) -> str:
+ """Return the reasoning string from an openjiuwen or SkillTurbo chunk."""
+ if not isinstance(payload, dict):
+ return ""
+ content = payload.get("content")
+ if isinstance(content, str) and content:
+ return content
+ output = payload.get("output")
+ if isinstance(output, str):
+ return output
+ return ""
class CompatibleSubagentControl(SubagentControl):
"""Report a restored subagent as idle until its next turn is submitted."""
+ def __init__(self, *args: object, **kwargs: object) -> None:
+ super().__init__(*args, **kwargs)
+ self._mirror_reasoning_text: dict[str, str] = {}
+ self._mirror_reasoning_flushed_at: dict[str, float] = {}
+ self._mirror_reasoning_frames: dict[str, int] = {}
+
async def resume(self, subagent_id: str) -> ResumeResult:
result = await super().resume(subagent_id)
if (
@@ -65,27 +92,53 @@ class CompatibleSubagentControl(SubagentControl):
# control registry constructs instances itself.
mirror_child_stream: bool = False
- async def _on_child_chunk(self, subagent_id: str, chunk: Any) -> None:
- """Replay a child stream chunk onto the parent session stream.
+ def _reasoning_frames_full(self, subagent_id: str) -> bool:
+ sent = self._mirror_reasoning_frames.get(subagent_id, 0)
+ return sent >= _REASONING_FRAME_CAP
- The mirrored frame carries ``stream_source_id = subagent_id`` so hosts
- that route by source (RelayClaw) nest it under the child instead of
- mixing it into the parent bubble. A mirror failure must never break
- the child turn, so write errors are logged and swallowed.
- """
- if not self.mirror_child_stream or self._parent_session is None:
+ def _reasoning_should_flush(self, subagent_id: str, text: str, now: float) -> bool:
+ if len(text) >= _REASONING_FLUSH_CHARS:
+ return True
+ started = self._mirror_reasoning_flushed_at[subagent_id]
+ return now - started >= _REASONING_FLUSH_INTERVAL_S
+
+ async def _flush_child_reasoning(self, subagent_id: str) -> None:
+ text = self._mirror_reasoning_text.pop(subagent_id, "")
+ self._mirror_reasoning_flushed_at[subagent_id] = time.monotonic()
+ if not text or self._reasoning_frames_full(subagent_id):
return
- chunk_type = getattr(chunk, "type", None)
- if chunk_type not in _MIRROR_CHUNK_TYPES:
+ sent = self._mirror_reasoning_frames.get(subagent_id, 0)
+ self._mirror_reasoning_frames[subagent_id] = sent + 1
+ await self._write_mirrored_chunk(subagent_id, "llm_reasoning", {"content": text})
+
+ async def _buffer_child_reasoning(self, subagent_id: str, chunk: Any) -> None:
+ if self._reasoning_frames_full(subagent_id):
return
- raw = getattr(chunk, "payload", None)
- payload = dict(raw) if isinstance(raw, dict) else {"content": str(raw or "")}
+ text = _child_reasoning_text(getattr(chunk, "payload", None))
+ if not text:
+ return
+ merged = self._mirror_reasoning_text.get(subagent_id, "") + text
+ self._mirror_reasoning_text[subagent_id] = merged
+ now = time.monotonic()
+ if subagent_id not in self._mirror_reasoning_flushed_at:
+ self._mirror_reasoning_flushed_at[subagent_id] = now
+ if not self._reasoning_should_flush(subagent_id, merged, now):
+ return
+ await self._flush_child_reasoning(subagent_id)
+
+ async def _write_mirrored_chunk(
+ self,
+ subagent_id: str,
+ chunk_type: str,
+ payload: dict[str, Any],
+ ) -> None:
+ body = dict(payload)
for key in _MIRROR_STRIP_KEYS:
- payload.pop(key, None)
- payload["stream_source_id"] = subagent_id
+ body.pop(key, None)
+ body["stream_source_id"] = subagent_id
try:
await self._parent_session.write_stream(
- OutputSchema(type=chunk_type, index=0, payload=payload)
+ OutputSchema(type=chunk_type, index=0, payload=body)
)
except Exception as exc: # noqa: BLE001 — mirror must not break the child turn
logger.warning(
@@ -95,6 +148,29 @@ class CompatibleSubagentControl(SubagentControl):
exc,
)
+ async def _on_child_chunk(self, subagent_id: str, chunk: Any) -> None:
+ """Replay a child stream chunk onto the parent session stream.
+
+ Reasoning is coalesced per child (200 characters or 300ms) so several
+ page subagents do not flood the parent websocket. Tool calls and
+ results are still copied in full. The mirrored frame carries
+ ``stream_source_id = subagent_id`` so hosts that route by source
+ (RelayClaw) nest it under the child. A mirror failure must never
+ break the child turn.
+ """
+ if not self.mirror_child_stream or self._parent_session is None:
+ return
+ chunk_type = getattr(chunk, "type", None)
+ if chunk_type == "llm_reasoning":
+ await self._buffer_child_reasoning(subagent_id, chunk)
+ return
+ await self._flush_child_reasoning(subagent_id)
+ if chunk_type not in _MIRROR_CHUNK_TYPES:
+ return
+ raw = getattr(chunk, "payload", None)
+ payload = dict(raw) if isinstance(raw, dict) else {"content": str(raw or "")}
+ await self._write_mirrored_chunk(subagent_id, str(chunk_type), payload)
+
def install_subagent_control_compat_patch(*, mirror_child_stream: bool = False) -> None:
"""Use the compatible control for newly created parent-session runtimes."""
diff --git a/tests/unit_tests/agents/harness/test_subagent_compat.py b/tests/unit_tests/agents/harness/test_subagent_compat.py
index 98801809f8..04cde709d7 100644
--- a/tests/unit_tests/agents/harness/test_subagent_compat.py
+++ b/tests/unit_tests/agents/harness/test_subagent_compat.py
@@ -106,6 +106,9 @@ class _ParentSession:
def _mirror_control(session: _ParentSession) -> CompatibleSubagentControl:
control = object.__new__(CompatibleSubagentControl)
control._parent_session = session # pylint: disable=protected-access
+ control._mirror_reasoning_text = {} # pylint: disable=protected-access
+ control._mirror_reasoning_flushed_at = {} # pylint: disable=protected-access
+ control._mirror_reasoning_frames = {} # pylint: disable=protected-access
control.mirror_child_stream = True
return control
@@ -149,3 +152,60 @@ async def test_mirror_write_failure_is_swallowed() -> None:
control = _mirror_control(_ParentSession(fail=True))
await control._on_child_chunk("sub-1", _Chunk("tool_result", {"result": "ok"}))
+
+
+async def test_reasoning_stays_buffered_until_the_next_frame() -> None:
+ session = _ParentSession()
+ control = _mirror_control(session)
+
+ await control._on_child_chunk("sub-1", _Chunk("llm_reasoning", {"output": "先"}))
+ await control._on_child_chunk("sub-1", _Chunk("llm_reasoning", {"content": "看"}))
+ assert session.written == []
+
+ await control._on_child_chunk("sub-1", _Chunk("tool_update", {"tool_update": {"status": "running"}}))
+ await control._on_child_chunk(
+ "sub-1",
+ _Chunk("tool_result", {"result": "全文结果", "task_id": "child-task"}),
+ )
+
+ assert [item[0] for item in session.written] == ["llm_reasoning", "tool_result"]
+ assert session.written[0][1] == {"content": "先看", "stream_source_id": "sub-1"}
+ assert session.written[1][1]["result"] == "全文结果"
+ assert "task_id" not in session.written[1][1]
+
+
+async def test_reasoning_flushes_at_char_threshold_and_interval(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ session = _ParentSession()
+ control = _mirror_control(session)
+ clock = {"now": 1_000.0}
+ monkeypatch.setattr(
+ "jiuwenswarm.agents.harness.common.tools.subagent_compat.time.monotonic",
+ lambda: clock["now"],
+ )
+
+ await control._on_child_chunk("sub-1", _Chunk("llm_reasoning", {"content": "a" * 200}))
+ assert session.written[0][1]["content"] == "a" * 200
+
+ await control._on_child_chunk("sub-2", _Chunk("llm_reasoning", {"content": "短"}))
+ clock["now"] += 0.311
+ await control._on_child_chunk("sub-2", _Chunk("llm_reasoning", {"content": "句"}))
+
+ flushed = [item[1]["content"] for item in session.written if item[0] == "llm_reasoning"]
+ assert flushed == ["a" * 200, "短句"]
+ assert session.written[-1][1]["stream_source_id"] == "sub-2"
+
+
+async def test_reasoning_frame_cap_keeps_tool_frames() -> None:
+ session = _ParentSession()
+ control = _mirror_control(session)
+ control._mirror_reasoning_frames["sub-1"] = 2000 # pylint: disable=protected-access
+
+ await control._on_child_chunk("sub-1", _Chunk("llm_reasoning", {"content": "不再上屏"}))
+ await control._on_child_chunk("sub-1", _Chunk("tool_call", {"tool_call": {"name": "bash"}}))
+
+ assert [item[0] for item in session.written] == ["tool_call"]