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(skill_turbo): 修复流式输出 Markdown 围栏粘连导致执行情况展示异常
n993577028d0e66f0aafdb
diff --git a/jiuwenswarm/server/runtime/skill_turbo/executor.py b/jiuwenswarm/server/runtime/skill_turbo/executor.pyindex 96f24d6f54..fc3da55450 100644--- a/jiuwenswarm/server/runtime/skill_turbo/executor.py+++ b/jiuwenswarm/server/runtime/skill_turbo/executor.py@@ -56,6 +56,10 @@ from jiuwenswarm.server.runtime.skill_turbo.permission_bridge import ()from jiuwenswarm.server.utils.stream_utils import parse_stream_chunkfrom jiuwenswarm.server.runtime.skill_turbo.json_utils import extract_llm_json+from jiuwenswarm.server.runtime.skill_turbo.markdown_stream import (+ markdown_stream_incoming,+ terminate_dangling_markdown_fence,+)from jiuwenswarm.server.runtime.skill_turbo.fallback_handler import FallbackContractErrorfrom jiuwenswarm.server.runtime.skill_turbo.interactive_ask import (resolve_interactive_ask_from_inputs,@@ -368,6 +372,9 @@ class _StreamBufferState:"""buckets: dict[tuple[str | None, str], _StreamBufferBucket] = field(default_factory=dict)+ # Survives bucket pop/flush so the next chat.delta can be separated from a+ # fence that already went out (frontend concatenates adjacent streamText).+ last_emitted: dict[tuple[str | None, str], str] = field(default_factory=dict)def get_bucket(self, source_id: str | None, event_type: str@@ -791,20 +798,30 @@ class SkillTurboExecutor:yield flushedbucket = buffer_state.get_bucket(source_id, event_type)+ bucket_key = (source_id, event_type)+ piece = markdown_stream_incoming(+ buffer_state.last_emitted.get(bucket_key, ""),+ str(content),+ )+ buffer_state.last_emitted[bucket_key] = piece# 首个 chunk 立即发送,保证低首字延迟(与 subagent_executor 一致)if not bucket.first_chunk_sent:bucket.first_chunk_sent = True+ if piece != str(content) and isinstance(chunk.payload, dict):+ chunk.payload = {**chunk.payload, "content": piece}+ if bucket.plan_name is None:+ bucket.plan_name = payload.get("plan_name")yield chunkcontinue# 累加到缓冲桶- bucket.parts.append(str(content))+ bucket.parts.append(piece)bucket.since = bucket.since or time.monotonic()if bucket.plan_name is None:bucket.plan_name = payload.get("plan_name")- # 60s 到期 flush+ # 到期 flushif time.monotonic() - bucket.since >= _SKILL_TURBO_STREAM_FLUSH_INTERVAL_SECONDS:async for flushed in self._flush_bucket_chunks(buffer_state, (source_id, event_type), request_id, channel_id@@ -2341,9 +2358,10 @@ class SkillTurboExecutor:if bucket is None or not bucket.parts:return- merged_content = "".join(bucket.parts)+ merged_content = terminate_dangling_markdown_fence("".join(bucket.parts))if not merged_content:return+ buffer_state.last_emitted[bucket_key] = merged_contentpayload: dict[str, Any] = {"event_type": event_type,diff --git a/jiuwenswarm/server/runtime/skill_turbo/markdown_stream.py b/jiuwenswarm/server/runtime/skill_turbo/markdown_stream.pynew file mode 100644index 0000000000..00e718b477--- /dev/null+++ b/jiuwenswarm/server/runtime/skill_turbo/markdown_stream.py@@ -0,0 +1,85 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Protect user-visible SkillTurbo markdown from glued/unclosed fences.++LLM JSON often arrives as ```json ... ```. Consecutive chat.delta pieces are+concatenated without a separator. A closing fence plus the next opening fence+becomes one line of six backticks (``````json), which CommonMark does not treat+as a closer. The rest of the execution log is then swallowed into one <pre>.+"""++from __future__ import annotations++import re++# Whole first line must be a single language tag (no spaces), so English progress+# text like "Processing results..." is not treated as ``` + json continuation.+_FENCE_INFO_CONTINUATION = re.compile(r"^[A-Za-z][A-Za-z0-9_+-]*\s*$")+++def _looks_like_fence_line(line: str) -> bool:+ stripped = line.lstrip(" ")+ return stripped.startswith("```") or stripped.startswith("~~~")+++def _fence_info(line: str) -> str | None:+ """Return the info string after a fence marker, or None if not a fence line."""+ stripped = line.lstrip(" ")+ if stripped.startswith("```"):+ i = 0+ while i < len(stripped) and stripped[i] == "`":+ i += 1+ return stripped[i:]+ if stripped.startswith("~~~"):+ i = 0+ while i < len(stripped) and stripped[i] == "~":+ i += 1+ return stripped[i:]+ return None+++def _is_fence_info_continuation(last_line: str, incoming: str) -> bool:+ """True when last_line is a marker-only fence and incoming is a language tag.++ Streaming often splits ```json into ``` then json. A newline between those+ tokens would break the opening fence.+ """+ info = _fence_info(last_line)+ if info is None or info.strip():+ return False+ first_line = incoming.split("\n", 1)[0]+ return bool(_FENCE_INFO_CONTINUATION.match(first_line))+++def terminate_dangling_markdown_fence(content: str) -> str:+ """Append a newline when content ends on a completed fence line.++ Marker-only fences (``` with no info yet) are left unchanged so a following+ ``json`` token can still complete the opening fence.+ """+ if not content or content.endswith("\n"):+ return content+ last_line = content.rsplit("\n", 1)[-1]+ info = _fence_info(last_line)+ if info is None:+ return content+ if not info.strip():+ return content+ return content + "\n"+++def markdown_stream_incoming(previous: str, incoming: str) -> str:+ """Prefix incoming with a newline when concatenating would glue a fence."""+ if not previous or not incoming:+ return incoming+ if previous.endswith("\n") or incoming.startswith("\n"):+ return incoming+ last_line = previous.rsplit("\n", 1)[-1]+ first_line = incoming.split("\n", 1)[0]+ if _looks_like_fence_line(first_line):+ return "\n" + incoming+ if _looks_like_fence_line(last_line) and not _is_fence_info_continuation(+ last_line, incoming+ ):+ return "\n" + incoming+ return incomingdiff --git a/tests/unit_tests/server/runtime/skill_turbo/test_markdown_stream_fence.py b/tests/unit_tests/server/runtime/skill_turbo/test_markdown_stream_fence.pynew file mode 100644index 0000000000..35bf851fab--- /dev/null+++ b/tests/unit_tests/server/runtime/skill_turbo/test_markdown_stream_fence.py@@ -0,0 +1,50 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++from jiuwenswarm.server.runtime.skill_turbo.markdown_stream import (+ markdown_stream_incoming,+ terminate_dangling_markdown_fence,+)+++def test_glued_json_fences_get_a_separating_newline():+ previous = '{"material_richness":"empty"}\n```'+ incoming = '```json\n{"entity":"Beiersdorf"}'+ joined = previous + markdown_stream_incoming(previous, incoming)+ assert "``````json" not in joined+ assert "```\n```json" in joined+++def test_progress_text_is_not_stuck_on_closing_fence():+ previous = "```"+ incoming = "未发现附件,已提取部分需求信息,后续将补充确认"+ joined = previous + markdown_stream_incoming(previous, incoming)+ assert "```未发现附件" not in joined+ assert "```\n未发现附件" in joined+++def test_english_progress_text_is_not_stuck_on_closing_fence():+ previous = '{"step":"search"}\n```'+ incoming = "Processing results..."+ joined = previous + markdown_stream_incoming(previous, incoming)+ assert "```Processing" not in joined+ assert "```\nProcessing results..." in joined+++def test_streaming_json_info_string_stays_on_fence_line():+ previous = "```"+ incoming = "json\n{"+ assert markdown_stream_incoming(previous, incoming) == incoming+ assert previous + incoming == "```json\n{"+++def test_ordinary_json_tokens_stay_glued():+ previous = '{"topic": "'+ incoming = 'Beiersdorf 2025年度报告"}'+ assert markdown_stream_incoming(previous, incoming) == incoming+++def test_terminate_completed_fence_but_not_marker_only():+ assert terminate_dangling_markdown_fence("```json") == "```json\n"+ assert terminate_dangling_markdown_fence("```") == "```"+ assert terminate_dangling_markdown_fence("hello") == "hello"+ assert terminate_dangling_markdown_fence("```\n") == "```\n"