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(team): preserve whitespace-only stream deltas for Markdown tables

liutao9b61b9369f9a
diff --git a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py
index 69799ab715..c77866e7b2 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py
@@ -49,6 +49,15 @@ from jiuwenswarm.server.runtime.session.session_metadata import (
from jiuwenswarm.server.runtime.session.session_history import append_history_record
from jiuwenswarm.agents.harness.team.handlers.team_monitor_handler import TeamMonitorHandler
from jiuwenswarm.server.utils.stream_utils import parse_stream_chunk
+
+
+def _parse_team_stream_chunk(chunk: Any, *, _has_streamed_content: bool = False) -> dict[str, Any] | None:
+ """Team stream parser: keep formatting-only deltas (newlines) for Markdown tables."""
+ return parse_stream_chunk(
+ chunk,
+ _has_streamed_content=_has_streamed_content,
+ preserve_whitespace=True,
+ )
from jiuwenswarm.common.schema.agent import AgentResponseChunk
from jiuwenswarm.server.runtime.agent_adapter.evolution_helpers import (
EvolutionProgressStatus,
@@ -2648,7 +2657,7 @@ async def _consume_stream_with_query(
# _is_leader_output returns True.
if _team_hide_teammate_enabled() and not is_leader:
continue
- parsed = parse_stream_chunk(chunk)
+ parsed = _parse_team_stream_chunk(chunk)
if parsed is not None:
# Time to first token: the first frame actually produced by a
# model (reasoning counts — on a thinking model it comes first).
@@ -3369,7 +3378,7 @@ async def _watch_team_evolution_and_push(
channel_id,
session_id,
events,
- parse_stream_chunk=parse_stream_chunk,
+ parse_stream_chunk=_parse_team_stream_chunk,
broadcast_event=_broadcast_event,
)
diff --git a/jiuwenswarm/server/utils/stream_utils.py b/jiuwenswarm/server/utils/stream_utils.py
index d8a1079ea3..e92a535581 100644
--- a/jiuwenswarm/server/utils/stream_utils.py
+++ b/jiuwenswarm/server/utils/stream_utils.py
@@ -70,7 +70,34 @@ def _propagate_stream_source_id(src_payload: Any) -> dict[str, Any]:
return {}
-def parse_stream_chunk(chunk: Any, *, _has_streamed_content: bool = False) -> dict[str, Any] | None:
+def _is_absent_stream_text(
+ content: Any,
+ *,
+ preserve_whitespace: bool = False,
+) -> bool:
+ """Return True when streaming text should be skipped.
+
+ Default keeps historical strip() behavior. Team mode sets
+ ``preserve_whitespace=True`` so formatting-only chunks (``\\n``,
+ ``\\n\\n``, spaces) are kept — required for Markdown tables.
+ """
+ if content is None:
+ return True
+ if not isinstance(content, str):
+ content = str(content)
+ if content == "":
+ return True
+ if preserve_whitespace:
+ return False
+ return not content.strip()
+
+
+def parse_stream_chunk(
+ chunk: Any,
+ *,
+ _has_streamed_content: bool = False,
+ preserve_whitespace: bool = False,
+) -> dict[str, Any] | None:
"""Parse agent output chunk to frontend-consumable payload dict.
统一处理所有 SDK 输出格式,包括:
@@ -82,6 +109,7 @@ def parse_stream_chunk(chunk: Any, *, _has_streamed_content: bool = False) -> di
Args:
chunk: Output chunk from agent runner
_has_streamed_content: Whether content has been streamed (for backward compatibility)
+ preserve_whitespace: When True, keep formatting-only text chunks (team stream).
Returns:
Parsed payload dict with event_type, or None if chunk should be skipped
@@ -90,16 +118,22 @@ def parse_stream_chunk(chunk: Any, *, _has_streamed_content: bool = False) -> di
return None
if isinstance(chunk, dict):
- return _parse_dict_chunk(chunk, _has_streamed_content)
+ return _parse_dict_chunk(
+ chunk, _has_streamed_content, preserve_whitespace=preserve_whitespace
+ )
if hasattr(chunk, "type") and hasattr(chunk, "payload"):
- return _parse_typed_chunk(chunk, _has_streamed_content)
+ return _parse_typed_chunk(
+ chunk, _has_streamed_content, preserve_whitespace=preserve_whitespace
+ )
if hasattr(chunk, "event_type"):
return _parse_event_typed_chunk(chunk)
if hasattr(chunk, "payload") and hasattr(chunk, "request_id"):
- return _parse_response_chunk(chunk, _has_streamed_content)
+ return _parse_response_chunk(
+ chunk, _has_streamed_content, preserve_whitespace=preserve_whitespace
+ )
return {
"event_type": "chat.delta",
@@ -107,7 +141,12 @@ def parse_stream_chunk(chunk: Any, *, _has_streamed_content: bool = False) -> di
}
-def _parse_dict_chunk(chunk: dict[str, Any], _has_streamed_content: bool) -> dict[str, Any] | None:
+def _parse_dict_chunk(
+ chunk: dict[str, Any],
+ _has_streamed_content: bool,
+ *,
+ preserve_whitespace: bool = False,
+) -> dict[str, Any] | None:
"""Parse dict chunk."""
if "event_type" in chunk:
if chunk.get("event_type") == "chat.tracer_agent":
@@ -133,7 +172,7 @@ def _parse_dict_chunk(chunk: dict[str, Any], _has_streamed_content: bool) -> dic
if "content" in chunk:
content = chunk.get("content", "")
- if not content or not content.strip():
+ if _is_absent_stream_text(content, preserve_whitespace=preserve_whitespace):
return None
return {
"event_type": "chat.delta" if not _has_streamed_content else "chat.final",
@@ -158,7 +197,7 @@ def _parse_dict_chunk(chunk: dict[str, Any], _has_streamed_content: bool) -> dic
"error": output.get("output", ""),
}
output = chunk.get("output", "")
- if not output or not output.strip():
+ if _is_absent_stream_text(output, preserve_whitespace=preserve_whitespace):
return None
return {
"event_type": "chat.delta" if not _has_streamed_content else "chat.final",
@@ -177,7 +216,12 @@ def _serialize_chunk_recursive(obj: Any) -> Any:
return _serialize_value(obj)
-def _parse_typed_chunk(chunk: Any, _has_streamed_content: bool) -> dict[str, Any] | None:
+def _parse_typed_chunk(
+ chunk: Any,
+ _has_streamed_content: bool,
+ *,
+ preserve_whitespace: bool = False,
+) -> dict[str, Any] | None:
"""Parse OutputSchema-like chunk with type and payload attributes."""
chunk_type = getattr(chunk, "type", "")
payload = getattr(chunk, "payload", {})
@@ -341,7 +385,7 @@ def _parse_typed_chunk(chunk: Any, _has_streamed_content: bool) -> dict[str, Any
if isinstance(payload, dict)
else str(payload)
)
- if not content or not content.strip():
+ if _is_absent_stream_text(content, preserve_whitespace=preserve_whitespace):
return None
return {
"event_type": "chat.delta",
@@ -355,7 +399,7 @@ def _parse_typed_chunk(chunk: Any, _has_streamed_content: bool) -> dict[str, Any
if isinstance(payload, dict)
else str(payload)
)
- if not content or not content.strip():
+ if _is_absent_stream_text(content, preserve_whitespace=preserve_whitespace):
return None
return {
"event_type": "chat.reasoning",
@@ -369,7 +413,7 @@ def _parse_typed_chunk(chunk: Any, _has_streamed_content: bool) -> dict[str, Any
if isinstance(payload, dict)
else str(payload)
)
- if not content or not content.strip():
+ if _is_absent_stream_text(content, preserve_whitespace=preserve_whitespace):
return None
return {
"event_type": "chat.delta",
@@ -903,7 +947,12 @@ def _serialize_value(value: Any) -> Any:
return value
-def _parse_response_chunk(chunk: Any, _has_streamed_content: bool) -> dict[str, Any] | None:
+def _parse_response_chunk(
+ chunk: Any,
+ _has_streamed_content: bool,
+ *,
+ preserve_whitespace: bool = False,
+) -> dict[str, Any] | None:
"""Parse AgentResponseChunk-like object."""
payload = getattr(chunk, "payload", None)
@@ -928,15 +977,27 @@ def _parse_response_chunk(chunk: Any, _has_streamed_content: bool) -> dict[str,
"event_type": "chat.error",
"error": output.get("output", ""),
}
+ content = payload.get("output", "")
+ # Default: keep historical no-filter behavior for AgentResponseChunk.
+ # Team (preserve_whitespace=True): only drop absent/empty text.
+ if preserve_whitespace and _is_absent_stream_text(
+ content, preserve_whitespace=True
+ ):
+ return None
return {
"event_type": "chat.delta" if not _has_streamed_content else "chat.final",
- "content": payload.get("output", ""),
+ "content": content,
}
if "content" in payload:
+ content = payload.get("content", "")
+ if preserve_whitespace and _is_absent_stream_text(
+ content, preserve_whitespace=True
+ ):
+ return None
return {
"event_type": "chat.delta" if not _has_streamed_content else "chat.final",
- "content": payload.get("content", ""),
+ "content": content,
}
return payload
diff --git a/tests/unit_tests/agentserver/test_team_stream_whitespace.py b/tests/unit_tests/agentserver/test_team_stream_whitespace.py
new file mode 100644
index 0000000000..240f56c8a1
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_team_stream_whitespace.py
@@ -0,0 +1,73 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Team stream path preserves formatting whitespace for Markdown tables.
+
+Team mode calls ``parse_stream_chunk(..., preserve_whitespace=True)`` via
+``_parse_team_stream_chunk``. Default callers keep historical strip() behavior.
+"""
+
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from jiuwenswarm.server.utils.stream_utils import parse_stream_chunk
+
+
+ ("chunk_type", "content", "event_type"),
+ [
+ ("llm_output", " ", "chat.delta"),
+ ("llm_output", "\n", "chat.delta"),
+ ("llm_output", "\n\n", "chat.delta"),
+ ("content_chunk", "\n\n", "chat.delta"),
+ ("llm_reasoning", " ", "chat.reasoning"),
+ ],
+)
+def test_preserve_whitespace_keeps_formatting_chunks(
+ chunk_type: str,
+ content: str,
+ event_type: str,
+) -> None:
+ chunk = SimpleNamespace(type=chunk_type, payload={"content": content})
+ parsed = parse_stream_chunk(chunk, preserve_whitespace=True)
+
+ assert parsed is not None
+ assert parsed["event_type"] == event_type
+ assert parsed["content"] == content
+
+
+def test_default_parse_stream_chunk_still_drops_whitespace_only() -> None:
+ chunk = SimpleNamespace(type="llm_output", payload={"content": "\n\n"})
+ assert parse_stream_chunk(chunk) is None
+ assert parse_stream_chunk(chunk, preserve_whitespace=False) is None
+
+
+def test_preserve_whitespace_still_skips_empty_string() -> None:
+ chunk = SimpleNamespace(type="llm_output", payload={"content": ""})
+ assert parse_stream_chunk(chunk, preserve_whitespace=True) is None
+
+
+def test_response_chunk_default_does_not_filter_whitespace() -> None:
+ """AgentResponseChunk historically forwarded empty/whitespace; keep that default."""
+ chunk = SimpleNamespace(request_id="r1", payload={"content": "\n\n"})
+ parsed = parse_stream_chunk(chunk)
+ assert parsed is not None
+ assert parsed["content"] == "\n\n"
+
+
+def test_response_chunk_team_keeps_whitespace_drops_empty() -> None:
+ ws = SimpleNamespace(request_id="r1", payload={"content": "\n\n"})
+ empty = SimpleNamespace(request_id="r1", payload={"content": ""})
+ assert parse_stream_chunk(ws, preserve_whitespace=True)["content"] == "\n\n"
+ assert parse_stream_chunk(empty, preserve_whitespace=True) is None
+
+
+def test_team_helpers_wires_preserve_whitespace() -> None:
+ """Guard against regressing the team call-site without importing heavy deps."""
+ source = Path("jiuwenswarm/server/runtime/agent_adapter/team_helpers.py").read_text(
+ encoding="utf-8"
+ )
+ assert "preserve_whitespace=True" in source
+ assert "_parse_team_stream_chunk" in source
+ assert "parsed = _parse_team_stream_chunk(chunk)" in source