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(stage):保持左边气泡和右边的stage一致

n9935770287d40884f3ce3
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index 3c0651e1b4..ac6bd75ee1 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -145,7 +145,6 @@ STREAM_SOURCE_ID_FIELD = "stream_source_id"
_INTERRUPT_OUTPUT_ATTACH_RETRY_COUNT = 20
_INTERRUPT_OUTPUT_ATTACH_RETRY_INTERVAL_SECONDS = 0.05
-
# SkillTurbo 内部工具 id 后缀(如 BashTool_skill_turbo)。外层 ReAct 工具结果不含此后缀。
_SKILL_TURBO_TOOL_ID_SUFFIX = "_skill_turbo"
@@ -17586,7 +17585,6 @@ class JiuWenSwarmDeepAdapter:
continue
chunk_type = chunk.type
-
if chunk_type == "llm_usage":
logger.info(f"[JiuWenSwarmDeepAdapter] llm_usage chunk: {chunk}")
usage_meta = (
diff --git a/jiuwenswarm/server/runtime/skill_turbo/executor.py b/jiuwenswarm/server/runtime/skill_turbo/executor.py
index 4665132b7e..54ffa4b8dc 100644
--- a/jiuwenswarm/server/runtime/skill_turbo/executor.py
+++ b/jiuwenswarm/server/runtime/skill_turbo/executor.py
@@ -192,6 +192,9 @@ _SKILL_TURBO_STREAM_FLUSH_INTERVAL_SECONDS: float = 3.0
# 需要缓冲的事件类型
_BUFFERABLE_EVENT_TYPES: frozenset[str] = frozenset({"chat.delta", "chat.reasoning"})
+# 主回答气泡进度横幅:由 PPT root 标记,经过 Executor 时立即发送;
+# 父会话包装层识别后会移除该内部字段。
+_BUBBLE_PROGRESS_FIELD = "_bubble_progress"
# Request上下文
_request_id_var: ContextVar[str] = ContextVar("skill_turbo_request_id", default="")
@@ -509,6 +512,11 @@ class SkillTurboExecutor:
# 当前任务状态(用于跨协程共享当前 task_id,解决 asyncio.create_task 复制 ContextVar 的问题)
self._current_task_id_holder: dict[str, str | None] = {"task_id": None}
self._task_states_holder: dict[str, dict[str, Any]] = {}
+ # PPT 开始横幅必须先于 task.start 进入输出流。before_subplan 先把
+ # start/update 暂存于此,等 start 横幅入队后再 flush,避免
+ # produce_node_output 与 drain_session_stream 双排空时 start 反超横幅。
+ self._deferred_task_lifecycle_events: list[dict[str, Any]] = []
+ self._task_event_drain_lock = asyncio.Lock()
# 节点产物记录 holder:plan_name → 产物 dict。
# 运行期在 _after_subplan_execute 中累积,仅在中断前/流末 finally 落盘,
@@ -769,6 +777,20 @@ class SkillTurboExecutor:
plan_failed = True
plan_error = str(payload.get("error") or "") or None
+ # PPT stage 的开始/完成横幅属于主回答气泡。它们必须保持在
+ # task.start 之前 / task.complete 之后立即发送,不能进入通用
+ # chat.delta 缓冲桶,否则跨阶段 flush 时会被当前 task 栈误归组,
+ # 或在右侧 task_progress 已推进后仍滞留旧 Stage。
+ if event_type == "chat.delta" and payload.get(
+ _BUBBLE_PROGRESS_FIELD, False
+ ):
+ async for flushed in self._flush_all_buffer_chunks(
+ buffer_state, request_id, channel_id
+ ):
+ yield flushed
+ yield chunk
+ continue
+
# 非缓冲事件类型:先 flush 所有缓冲,再透传当前事件
if event_type not in _BUFFERABLE_EVENT_TYPES:
async for flushed in self._flush_all_buffer_chunks(
@@ -2227,33 +2249,65 @@ class SkillTurboExecutor:
session = _session_var.get()
async def enqueue_chunk(chunk: Any) -> None:
- async for task_chunk in self._drain_task_event_chunks():
- await output_queue.put(task_chunk)
- current_task_id = self._current_task_id()
+ is_bubble = isinstance(chunk, dict) and bool(
+ chunk.get(_BUBBLE_PROGRESS_FIELD)
+ )
+ bubble_done = bool(chunk.get("_bubble_progress_done")) if is_bubble else False
- # 处理 fallback_stream 返回的 dict 格式(包含 event_type)
- if isinstance(chunk, dict) and "event_type" in chunk:
- await output_queue.put(
- self._make_event_chunk(request_id, channel_id, chunk, current_task_id)
- )
- else:
- await output_queue.put(
- self._make_node_delta_chunk(request_id, channel_id, node, chunk, current_task_id)
+ async with self._task_event_drain_lock:
+ if is_bubble and not bubble_done:
+ # 先排空上一阶段残留的 complete/update,再发开始横幅。
+ # 本阶段的 task.start 仍由 before_subplan 延期,等横幅入队后再 flush。
+ self._flush_deferred_task_lifecycle_events()
+ async for task_chunk in self._drain_task_event_chunks():
+ await output_queue.put(task_chunk)
+ await output_queue.put(
+ self._make_node_delta_chunk(
+ request_id, channel_id, node, chunk, None
+ )
+ )
+ return
+
+ self._flush_deferred_task_lifecycle_events()
+ async for task_chunk in self._drain_task_event_chunks():
+ await output_queue.put(task_chunk)
+
+ current_task_id = (
+ None if is_bubble else self._current_task_id()
)
+ if isinstance(chunk, dict) and "event_type" in chunk:
+ await output_queue.put(
+ self._make_event_chunk(
+ request_id, channel_id, chunk, current_task_id
+ )
+ )
+ else:
+ await output_queue.put(
+ self._make_node_delta_chunk(
+ request_id, channel_id, node, chunk, current_task_id
+ )
+ )
async def drain_session_stream() -> None:
if session is None:
return
async for stream_chunk in session.stream_iterator():
# 先发送 task 事件(确保 task.start 在 chat 事件之前)
- async for task_chunk in self._drain_task_event_chunks():
- await output_queue.put(task_chunk)
- payload = parse_stream_chunk(stream_chunk)
- if payload is None:
- continue
- await output_queue.put(
- self._make_session_event_chunk(request_id, channel_id, payload, self._current_task_id())
- )
+ async with self._task_event_drain_lock:
+ self._flush_deferred_task_lifecycle_events()
+ async for task_chunk in self._drain_task_event_chunks():
+ await output_queue.put(task_chunk)
+ payload = parse_stream_chunk(stream_chunk)
+ if payload is None:
+ continue
+ await output_queue.put(
+ self._make_session_event_chunk(
+ request_id,
+ channel_id,
+ payload,
+ self._current_task_id(),
+ )
+ )
async def produce_node_output() -> None:
try:
@@ -2262,8 +2316,10 @@ class SkillTurboExecutor:
))
async for chunk in node.run_stream(inputs):
await enqueue_chunk(chunk)
- async for task_chunk in self._drain_task_event_chunks():
- await output_queue.put(task_chunk)
+ async with self._task_event_drain_lock:
+ self._flush_deferred_task_lifecycle_events()
+ async for task_chunk in self._drain_task_event_chunks():
+ await output_queue.put(task_chunk)
await output_queue.put(self._make_node_finished_chunk(
request_id, channel_id, node, self._current_task_id()
))
@@ -2286,6 +2342,7 @@ class SkillTurboExecutor:
"[SkillTurboExecutor] _execute_node_stream FallbackLimitExceededError: %s",
item,
)
+ self._flush_deferred_task_lifecycle_events()
async for task_chunk in self._drain_task_event_chunks():
yield task_chunk
raise item
@@ -2317,10 +2374,12 @@ class SkillTurboExecutor:
"[SkillTurboExecutor] _execute_node_stream propagate HITL AbortError: %s",
item,
)
+ self._flush_deferred_task_lifecycle_events()
async for task_chunk in self._drain_task_event_chunks():
yield task_chunk
raise item
logger.error("[SkillTurboExecutor] _execute_node_stream error: %s", item)
+ self._flush_deferred_task_lifecycle_events()
async for task_chunk in self._drain_task_event_chunks():
yield task_chunk
yield self._make_node_error_chunk(
@@ -2556,7 +2615,14 @@ class SkillTurboExecutor:
# 提取实际内容和正确的 plan_name
actual_content = content
plan_name = node.plan_name # 默认使用传入的 node
- data_payload = content if isinstance(content, dict) else None
+ data_payload = dict(content) if isinstance(content, dict) else None
+ bubble_progress = bool(
+ data_payload.pop(_BUBBLE_PROGRESS_FIELD, False)
+ if data_payload is not None
+ else False
+ )
+ if data_payload is not None:
+ data_payload.pop("_bubble_progress_done", None)
if isinstance(content, dict):
# 从 chunk 中提取正确的 plan_name(如果存在),并转为显示名
@@ -2578,9 +2644,8 @@ class SkillTurboExecutor:
if chunk_status in ("progress", "ok") and actual_content:
actual_content = actual_content.rstrip("\n") + "\n"
- # 将 data_payload 中的 current_node 转为显示名(浅拷贝避免修改原始 chunk)
+ # 将 data_payload 中的 current_node 转为显示名(已浅拷贝,避免修改原始 chunk)
if data_payload is not None and "current_node" in data_payload:
- data_payload = dict(data_payload)
data_payload["current_node"] = self._display_name(data_payload["current_node"])
payload = {
@@ -2590,7 +2655,10 @@ class SkillTurboExecutor:
}
if data_payload is not None:
payload["data"] = data_payload
- if task_id:
+ if bubble_progress:
+ payload[_BUBBLE_PROGRESS_FIELD] = True
+ # 气泡进度横幅绝不能带 task_id,否则可能被归入左上 taskRuns。
+ if task_id and not bubble_progress:
payload["task_id"] = task_id
return self._make_chunk(request_id, channel_id, payload)
@@ -2645,6 +2713,17 @@ class SkillTurboExecutor:
self._normalize_task_event_type(task_event)
yield self._make_task_event_chunk(task_event)
+ def _flush_deferred_task_lifecycle_events(self) -> None:
+ """将延期的 task.start/update 追加到 FIFO,供下一次 drain 发送。"""
+ if not self._deferred_task_lifecycle_events:
+ return
+ events_queue = _task_events_queue_var.get()
+ if events_queue is None:
+ self._deferred_task_lifecycle_events.clear()
+ return
+ events_queue.extend(self._deferred_task_lifecycle_events)
+ self._deferred_task_lifecycle_events.clear()
+
@staticmethod
def _normalize_task_event_type(task_event: dict[str, Any]) -> None:
payload = task_event.get("payload", {})
@@ -2665,6 +2744,7 @@ class SkillTurboExecutor:
# 清空实例属性(新请求开始)
self._task_states_holder.clear()
+ self._deferred_task_lifecycle_events.clear()
self._current_task_id_holder["task_id"] = None
saved = self._take_resume_task_states()
@@ -2770,6 +2850,13 @@ class SkillTurboExecutor:
)
return
+ events_queue.append(self._build_task_update_event(task_states))
+
+ @staticmethod
+ def _build_task_update_event(
+ task_states: dict[str, dict[str, Any]]
+ ) -> dict[str, Any]:
+ """构建 task.update 事件(不入队)。"""
# 深拷贝任务状态(避免后续修改影响已发送的事件);按 index 排序保证前端稳定
all_tasks = sorted(
(copy.deepcopy(state) for state in task_states.values()),
@@ -2814,14 +2901,12 @@ class SkillTurboExecutor:
status_preview,
)
- # 添加到事件队列
- task_update_event = {
+ return {
"request_id": _request_id_var.get(),
"channel_id": _channel_id_var.get(),
"payload": payload,
"is_complete": False,
}
- events_queue.append(task_update_event)
async def _should_skip_subplan_execute(
self,
@@ -2961,10 +3046,13 @@ class SkillTurboExecutor:
subplan.depth,
)
- events_queue.append(
+ # 延期到开始横幅入队后再写入 FIFO,避免双协程排空时 start 抢在横幅前。
+ self._deferred_task_lifecycle_events.append(
self._build_task_start_event(subplan, task_id, task_state, task_states, timestamp)
)
- await self._emit_task_update_event()
+ self._deferred_task_lifecycle_events.append(
+ self._build_task_update_event(task_states)
+ )
async def _after_subplan_execute(
self,
@@ -3051,6 +3139,10 @@ class SkillTurboExecutor:
result_or_error if is_error else None,
)
+ # 子节点若未 yield 任何 chunk 就结束,enqueue_chunk 不会触发 flush;
+ # 必须先释放延期的 task.start,再入队 complete,避免 complete 抢在 start 前。
+ self._flush_deferred_task_lifecycle_events()
+
events_queue.append(
self._build_task_complete_event(
TaskCompleteEventData(
diff --git a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_gen_root.py b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_gen_root.py
index 9cbf7ce7cd..613e441368 100644
--- a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_gen_root.py
+++ b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_gen_root.py
@@ -233,6 +233,29 @@ class PPTGenRootNode(PlanNode):
_merge_subplan_result(inputs, last_chunk)
_append_subplan_step(results, subplan, last_chunk)
+ def _stage_progress_banner(
+ self,
+ subplan: PlanNode,
+ *,
+ index: int,
+ total_steps: int,
+ done: bool,
+ ) -> dict[str, Any]:
+ verb = "完成执行" if done else "开始执行"
+ return {
+ "node": self.plan_name,
+ "status": "progress",
+ "message": f"{verb} {subplan.plan_name}({index}/{total_steps})",
+ "current_node": subplan.plan_name,
+ "step": index,
+ "total_steps": total_steps,
+ # 横幅属于主回答气泡,不属于 stage taskRuns。Executor 识别该标记后
+ # 立即发送,并把 task.start 推迟到横幅之后,避免双协程排空时
+ # task.start 反超横幅、左下气泡停滞在旧 Stage。
+ "_bubble_progress": True,
+ "_bubble_progress_done": bool(done),
+ }
+
async def _run_subplan_stream(
self,
subplan: PlanNode,
@@ -249,31 +272,27 @@ class PPTGenRootNode(PlanNode):
yield chunk
return
+ # 横幅刻意放在 task.start 之前、task.complete 之后:它们应进入左下
+ # 主回答气泡,而 stage 内部输出仍由 task 上下文路由到左上任务区域。
if not await self.should_suppress_subplan_start_banner(subplan, inputs):
- yield {
- "node": self.plan_name,
- "status": "progress",
- "message": f"开始执行 {subplan.plan_name}({index}/{total_steps})",
- "current_node": subplan.plan_name,
- "step": index,
- "total_steps": total_steps,
- }
+ yield self._stage_progress_banner(
+ subplan, index=index, total_steps=total_steps, done=False
+ )
last_chunk: Any = None
- async for chunk in self.execute_subplan_stream(subplan, inputs):
- last_chunk = chunk
- yield chunk
+ stream = self.execute_subplan_stream(subplan, inputs)
+ try:
+ async for chunk in stream:
+ last_chunk = chunk
+ yield chunk
+ finally:
+ await stream.aclose()
_merge_subplan_result(inputs, last_chunk)
_append_subplan_step(results, subplan, last_chunk)
- yield {
- "node": self.plan_name,
- "status": "progress",
- "message": f"完成执行 {subplan.plan_name}({index}/{total_steps})",
- "current_node": subplan.plan_name,
- "step": index,
- "total_steps": total_steps,
- }
+ yield self._stage_progress_banner(
+ subplan, index=index, total_steps=total_steps, done=True
+ )
async def _skip_p3_subplan_stream(
self,
@@ -290,36 +309,31 @@ class PPTGenRootNode(PlanNode):
yield chunk
return
+ skip_result: dict[str, Any] = {
+ "node": self._p3.plan_name,
+ "status": "ok",
+ "message": _P3_SKIP_MESSAGE,
+ "skipped": True,
+ **_P3_SKIP_FIELDS,
+ }
if not await self.should_suppress_subplan_start_banner(self._p3, inputs):
- yield {
- "node": self.plan_name,
- "status": "progress",
- "message": f"开始执行 {self._p3.plan_name}({index}/{total_steps})",
- "current_node": self._p3.plan_name,
- "step": index,
- "total_steps": total_steps,
- }
+ yield self._stage_progress_banner(
+ self._p3, index=index, total_steps=total_steps, done=False
+ )
- last_chunk: Any = None
- async for chunk in self.skip_subplan_stream(
- self._p3,
- inputs,
- message=_P3_SKIP_MESSAGE,
- extra=_P3_SKIP_FIELDS,
- ):
- last_chunk = chunk
- yield chunk
+ if self._before_subplan_execute is not None:
+ await self._before_subplan_execute(self._p3, inputs)
+ try:
+ yield skip_result
+ finally:
+ if self._after_subplan_execute is not None:
+ await self._after_subplan_execute(self._p3, inputs, skip_result)
- _merge_subplan_result(inputs, last_chunk)
- _append_subplan_step(results, self._p3, last_chunk)
- yield {
- "node": self.plan_name,
- "status": "progress",
- "message": f"完成执行 {self._p3.plan_name}({index}/{total_steps})",
- "current_node": self._p3.plan_name,
- "step": index,
- "total_steps": total_steps,
- }
+ _merge_subplan_result(inputs, skip_result)
+ _append_subplan_step(results, self._p3, skip_result)
+ yield self._stage_progress_banner(
+ self._p3, index=index, total_steps=total_steps, done=True
+ )
async def _run_p3_and_p2_stream(
self,
diff --git a/jiuwenswarm/server/runtime/skill_turbo/skill_turbo_tools.py b/jiuwenswarm/server/runtime/skill_turbo/skill_turbo_tools.py
index ea89bac41d..d142145d13 100644
--- a/jiuwenswarm/server/runtime/skill_turbo/skill_turbo_tools.py
+++ b/jiuwenswarm/server/runtime/skill_turbo/skill_turbo_tools.py
@@ -73,6 +73,7 @@ _SKILL_TURBO_EVENT_TYPE_TO_OUTPUT_TYPE: dict[str, str] = {
"chat.tool_calls.delta": "tool_calls.delta",
"chat.error": "error",
}
+_BUBBLE_PROGRESS_FIELD = "_bubble_progress"
# ── 不转发给父会话的事件类型 ──
# plan/node 生命周期事件:前端无对应 handler,DeepAgent 也无显式处理。
@@ -107,6 +108,18 @@ def _without_inner_task_routing(payload: dict[str, Any]) -> dict[str, Any]:
return cleaned
+def _prepare_parent_stream_output(
+ event_type: str, payload: dict[str, Any]
+) -> tuple[str, dict[str, Any]]:
+ """Map a SkillTurbo event to the parent stream without delaying bubble progress."""
+ if event_type == "chat.delta" and payload.get(_BUBBLE_PROGRESS_FIELD):
+ cleaned = dict(payload)
+ cleaned.pop(_BUBBLE_PROGRESS_FIELD, None)
+ cleaned.pop("task_id", None)
+ return "content_chunk", cleaned
+ return _SKILL_TURBO_EVENT_TYPE_TO_OUTPUT_TYPE.get(event_type, event_type), payload
+
+
# ── ContextVar:在 before_tool_call 中注入,供工具函数读取 ──
_current_skill_turbo_adapter: ContextVar[Any] = ContextVar(
"current_skill_turbo_adapter", default=None
@@ -754,7 +767,9 @@ async def skill_turbo(query: str) -> dict[str, Any] | str:
# SkillTurbo executor 产出的 event_type 带 "chat." 前缀(如 "chat.tool_call"),
# 但 DeepAgent 的 _parse_stream_chunk 期望原始 OutputSchema.type(如 "tool_call")。
# 若直接用 event_type 作 type,会因类型不匹配被静默丢弃,需反向映射回原始 type。
- output_type = _SKILL_TURBO_EVENT_TYPE_TO_OUTPUT_TYPE.get(event_type, event_type)
+ output_type, payload = _prepare_parent_stream_output(
+ event_type, payload
+ )
output = OutputSchema(
type=output_type,
index=0,
diff --git a/tests/unit_tests/agentserver/test_skill_turbo_tools.py b/tests/unit_tests/agentserver/test_skill_turbo_tools.py
index 6165629225..8ada979a0d 100644
--- a/tests/unit_tests/agentserver/test_skill_turbo_tools.py
+++ b/tests/unit_tests/agentserver/test_skill_turbo_tools.py
@@ -10,6 +10,7 @@ import pytest
from jiuwenswarm.server.runtime.skill_turbo.plan_node import AbortError
from jiuwenswarm.server.runtime.skill_turbo.skill_turbo_tools import (
+ _prepare_parent_stream_output,
_without_inner_task_routing,
reset_skill_turbo_outer_todo_active,
set_skill_turbo_outer_todo_active,
@@ -61,6 +62,34 @@ def test_without_inner_task_routing_preserves_stage_content() -> None:
assert payload["task_id"] == "task_6d61d336"
+def test_bubble_progress_uses_immediate_parent_content_chunk() -> None:
+ payload = {
+ "event_type": "chat.delta",
+ "content": "开始执行 Stage 8: 深度研究(8/14)",
+ "task_id": "task_research",
+ "_bubble_progress": True,
+ }
+
+ output_type, forwarded = _prepare_parent_stream_output("chat.delta", payload)
+
+ assert output_type == "content_chunk"
+ assert forwarded == {
+ "event_type": "chat.delta",
+ "content": "开始执行 Stage 8: 深度研究(8/14)",
+ }
+ assert payload["_bubble_progress"] is True
+ assert payload["task_id"] == "task_research"
+
+
+def test_regular_delta_keeps_parent_llm_output_path() -> None:
+ payload = {"event_type": "chat.delta", "content": "正在准备图片..."}
+
+ output_type, forwarded = _prepare_parent_stream_output("chat.delta", payload)
+
+ assert output_type == "llm_output"
+ assert forwarded is payload
+
+
@pytest.mark.asyncio
async def test_load_resume_ctx_failure_still_post_runs_turbo_session(_skill_turbo_runtime) -> None:
adapter, turbo_session = _skill_turbo_runtime
diff --git a/tests/unit_tests/server/runtime/skill_turbo/test_ppt_document_parse.py b/tests/unit_tests/server/runtime/skill_turbo/test_ppt_document_parse.py
index a8edd3f4c9..913430b8ee 100644
--- a/tests/unit_tests/server/runtime/skill_turbo/test_ppt_document_parse.py
+++ b/tests/unit_tests/server/runtime/skill_turbo/test_ppt_document_parse.py
@@ -18,6 +18,7 @@ from jiuwenswarm.server.runtime.skill_turbo.skill_codes.ppt.document_parse impor
from jiuwenswarm.server.runtime.skill_turbo.skill_codes.ppt.ppt_gen_root import (
PPTGenRootNode,
)
+from jiuwenswarm.server.runtime.skill_turbo.skill_codes.ppt import ppt_gen_root
from jiuwenswarm.server.runtime.skill_turbo.validator import PlanCodeValidator
@@ -30,6 +31,15 @@ def test_document_parse_passes_builtin_skill_validation() -> None:
assert validator.validate(source) == []
+def test_ppt_gen_root_passes_builtin_skill_validation() -> None:
+ source = Path(ppt_gen_root.__file__).read_text(encoding="utf-8")
+ validator = PlanCodeValidator.for_builtin_skill_code(
+ ["jiuwenswarm.server.runtime.skill_turbo.skill_codes"]
+ )
+
+ assert validator.validate(source) == []
+
+
def test_pdf_is_delegated_to_read_file() -> None:
assert is_non_text_file_path("report.pdf") is False
assert validate_read_file_result("report.pdf", "extracted PDF text") == (True, None)
diff --git a/tests/unit_tests/server/runtime/skill_turbo/test_resume_skip_completed.py b/tests/unit_tests/server/runtime/skill_turbo/test_resume_skip_completed.py
index 86a86ac590..c1ccf56e11 100644
--- a/tests/unit_tests/server/runtime/skill_turbo/test_resume_skip_completed.py
+++ b/tests/unit_tests/server/runtime/skill_turbo/test_resume_skip_completed.py
@@ -5,7 +5,7 @@
from __future__ import annotations
from typing import Any
-from unittest.mock import MagicMock
+from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -124,6 +124,185 @@ def _make_executor() -> SkillTurboExecutor:
return SkillTurboExecutor(environment=env)
+def test_bubble_progress_marker_is_internal_executor_metadata() -> None:
+ ex = _make_executor()
+ node = _LeafNode("ppt_gen_root", depth=0)
+
+ chunk = ex._make_node_delta_chunk(
+ "request-1",
+ "channel-1",
+ node,
+ {
+ "node": "ppt_gen_root",
+ "status": "progress",
+ "message": "开始执行 Stage 1(1/14)",
+ "_bubble_progress": True,
+ },
+ None,
+ )
+
+ assert chunk.payload["_bubble_progress"] is True
+ assert "_bubble_progress" not in chunk.payload["data"]
+
+
+async def test_deferred_task_start_flushes_after_start_banner() -> None:
+ """开始横幅入队后才释放延期的 task.start,避免 start 反超横幅。"""
+ from jiuwenswarm.server.runtime.skill_turbo import executor as executor_mod
+
+ ex = _make_executor()
+ queue: list[dict] = []
+ token = executor_mod._task_events_queue_var.set(queue)
+ try:
+ subplan = _LeafNode("stage_x", depth=1)
+ task_states = {
+ "task_1": {
+ "task_id": "task_1",
+ "task_name": "stage_x",
+ "status": "pending",
+ "task_index": 1,
+ }
+ }
+ ex._task_states_holder.update(task_states)
+ ex._get_or_create_task_state = lambda sp, states: ("task_1", states["task_1"]) # type: ignore[method-assign]
+
+ await ex._before_subplan_execute(subplan, {})
+ assert queue == []
+ assert len(ex._deferred_task_lifecycle_events) == 2
+ assert (
+ ex._deferred_task_lifecycle_events[0]["payload"].get("event_type")
+ == "task.start"
+ or "task_id" in ex._deferred_task_lifecycle_events[0]["payload"]
+ )
+
+ ex._flush_deferred_task_lifecycle_events()
+ assert len(ex._deferred_task_lifecycle_events) == 0
+ assert len(queue) == 2
+ assert queue[0]["payload"].get("event_type") in (None, "task.start") or queue[
+ 0
+ ]["payload"].get("task_id") == "task_1"
+ assert queue[1]["payload"]["event_type"] == "task.update"
+ finally:
+ executor_mod._task_events_queue_var.reset(token)
+
+
+async def test_after_subplan_flushes_deferred_start_before_complete() -> None:
+ """无中间 chunk 时,after 必须先 flush deferred start,再入队 complete。"""
+ from jiuwenswarm.server.runtime.skill_turbo import executor as executor_mod
+
+ ex = _make_executor()
+ queue: list[dict] = []
+ token_queue = executor_mod._task_events_queue_var.set(queue)
+ token_ctx = executor_mod._current_task_context_var.set(
+ {"task_id": "task_1", "start_time": 1.0}
+ )
+ try:
+ subplan = _LeafNode("stage_x", depth=1)
+ task_states = {
+ "task_1": {
+ "task_id": "task_1",
+ "task_name": "stage_x",
+ "status": "pending",
+ "task_index": 1,
+ }
+ }
+ ex._task_states_holder.update(task_states)
+ ex._get_or_create_task_state = lambda sp, states: ("task_1", states["task_1"]) # type: ignore[method-assign]
+
+ await ex._before_subplan_execute(subplan, {})
+ assert queue == []
+ assert len(ex._deferred_task_lifecycle_events) == 2
+
+ await ex._after_subplan_execute(subplan, {}, {"status": "ok"})
+ assert len(ex._deferred_task_lifecycle_events) == 0
+ event_types = [
+ evt.get("payload", {}).get("event_type")
+ or ("task.start" if "task_id" in evt.get("payload", {}) and "status" not in evt.get("payload", {}) else None)
+ for evt in queue
+ ]
+ # start (+update) must precede complete (+update)
+ start_idx = next(
+ i
+ for i, evt in enumerate(queue)
+ if evt.get("payload", {}).get("task_id") == "task_1"
+ and "status" not in evt.get("payload", {})
+ and evt.get("payload", {}).get("event_type") != "task.update"
+ )
+ complete_idx = next(
+ i
+ for i, evt in enumerate(queue)
+ if evt.get("payload", {}).get("event_type") == "task.complete"
+ or (
+ evt.get("payload", {}).get("task_id") == "task_1"
+ and evt.get("payload", {}).get("status") in ("completed", "failed")
+ )
+ )
+ assert start_idx < complete_idx, event_types
+ finally:
+ executor_mod._current_task_context_var.reset(token_ctx)
+ executor_mod._task_events_queue_var.reset(token_queue)
+
+
+async def test_bubble_progress_bypasses_delta_buffer(monkeypatch) -> None:
+ """横幅单独即时发送,不能与已缓冲的 stage 文本合并。"""
+ ex = _make_executor()
+ root = _LeafNode("ppt_gen_root", depth=0)
+ ex._env.register_tools = AsyncMock()
+
+ monkeypatch.setattr(ex, "_merge_env_config_to_inputs", lambda inputs: inputs)
+ monkeypatch.setattr(ex, "_build_tool_loader_context", lambda *args, **kwargs: {})
+ monkeypatch.setattr(ex, "_setup_execution_context", lambda *args, **kwargs: {})
+ monkeypatch.setattr(ex, "_clear_stale_node_artifacts", AsyncMock())
+ monkeypatch.setattr(ex, "_prepare_root_node", lambda _code: root)
+ monkeypatch.setattr(ex, "_initialize_pending_tasks", AsyncMock())
+ monkeypatch.setattr(ex, "_reset_execution_context", lambda _tokens: None)
+ monkeypatch.setattr(ex, "_finish_trace", AsyncMock())
+
+ async def no_task_events():
+ return
+ yield # pragma: no cover - async generator marker
+
+ async def node_stream(*_args, **_kwargs):
+ yield ex._make_chunk(
+ "request-1", "channel-1", {"event_type": "chat.delta", "content": "A"}
+ )
+ yield ex._make_chunk(
+ "request-1", "channel-1", {"event_type": "chat.delta", "content": "B"}
+ )
+ yield ex._make_chunk(
+ "request-1",
+ "channel-1",
+ {
+ "event_type": "chat.delta",
+ "content": "C",
+ "_bubble_progress": True,
+ },
+ )
+
+ monkeypatch.setattr(ex, "_drain_task_event_chunks", no_task_events)
+ monkeypatch.setattr(ex, "_execute_node_stream", node_stream)
+
+ chunks = [
+ chunk
+ async for chunk in ex.execute_plan_stream(
+ "from fake import root", {}, "request-1", "channel-1"
+ )
+ ]
+ deltas = [
+ chunk.payload
+ for chunk in chunks
+ if isinstance(chunk.payload, dict)
+ and chunk.payload.get("event_type") == "chat.delta"
+ ]
+
+ assert [payload["content"] for payload in deltas] == ["A", "B", "C"]
+ assert "_bubble_progress" not in deltas[0]
+ assert "_bubble_progress" not in deltas[1]
+ assert deltas[2]["_bubble_progress"] is True
+
+
class TestExecutorShouldSkipSubplanExecute:
@pytest.mark.asyncio
async def test_resume_skips_completed_depth1_only(self):
@@ -348,6 +527,135 @@ class TestPPTGenRootResumeProgressSilence:
assert child.run_stream_calls == 1
assert any(msg.startswith("完成执行") for msg in messages)
+ @pytest.mark.asyncio
+ async def test_progress_banners_outside_before_and_after_hooks(self):
+ """横幅位于 task 生命周期外,保持在左下主回答气泡展示。"""
+ from jiuwenswarm.server.runtime.skill_turbo.skill_codes.ppt.ppt_gen_root import (
+ PPTGenRootNode,
+ )
+
+ root = PPTGenRootNode()
+ child = _LeafNode("p5_content_plan", depth=1)
+ events: list[str] = []
+
+ async def should_skip(_sp: PlanNode, _inp: dict[str, Any]) -> bool:
+ return False
+
+ async def before(_sp: PlanNode, _inp: dict[str, Any]) -> None:
+ events.append("before")
+
+ async def after(_sp: PlanNode, _inp: dict[str, Any], _result: Any) -> None:
+ events.append("after")
+
+ root.set_runtime_callbacks(
+ should_skip_subplan_execute=should_skip,
+ before_subplan_execute=before,
+ after_subplan_execute=after,
+ )
+
+ results: list[dict[str, Any]] = []
+ async for chunk in root._run_subplan_stream(
+ child, {}, results, index=6, total_steps=14
+ ):
+ msg = chunk.get("message")
+ if isinstance(msg, str) and msg.startswith("开始执行"):
+ events.append("start_banner")
+ elif isinstance(msg, str) and msg.startswith("完成执行"):
+ events.append("complete_banner")
+ elif chunk.get("ran") is True:
+ events.append("body")
+
+ assert events == [
+ "start_banner",
+ "before",
+ "body",
+ "after",
+ "complete_banner",
+ ]
+
+ @pytest.mark.asyncio
+ async def test_skip_p3_banners_between_before_and_after_hooks(self):
+ from jiuwenswarm.server.runtime.skill_turbo.skill_codes.ppt.ppt_gen_root import (
+ PPTGenRootNode,
+ _P3_SKIP_MESSAGE,
+ )
+
+ root = PPTGenRootNode()
+ events: list[str] = []
+
+ async def should_skip(_sp: PlanNode, _inp: dict[str, Any]) -> bool:
+ return False
+
+ async def before(_sp: PlanNode, _inp: dict[str, Any]) -> None:
+ events.append("before")
+
+ async def after(_sp: PlanNode, _inp: dict[str, Any], _result: Any) -> None:
+ events.append("after")
+
+ root.set_runtime_callbacks(
+ should_skip_subplan_execute=should_skip,
+ before_subplan_execute=before,
+ after_subplan_execute=after,
+ )
+
+ results: list[dict[str, Any]] = []
+ async for chunk in root._skip_p3_subplan_stream(
+ {}, results, index=3, total_steps=14
+ ):
+ msg = chunk.get("message")
+ if isinstance(msg, str) and msg.startswith("开始执行"):
+ events.append("start_banner")
+ elif msg == _P3_SKIP_MESSAGE:
+ events.append("skip_body")
+ elif isinstance(msg, str) and msg.startswith("完成执行"):
+ events.append("complete_banner")
+
+ assert events == [
+ "start_banner",
+ "before",
+ "skip_body",
+ "after",
+ "complete_banner",
+ ]
+
+ @pytest.mark.asyncio
+ async def test_start_banner_close_does_not_open_task_context(self):
+ """开始横幅处关闭流时 task.start 尚未发生,无需清理 task。"""
+ from jiuwenswarm.server.runtime.skill_turbo.skill_codes.ppt.ppt_gen_root import (
+ PPTGenRootNode,
+ )
+
+ root = PPTGenRootNode()
+ child = _LeafNode("p5_content_plan", depth=1)
+ events: list[str] = []
+
+ async def should_skip(_sp: PlanNode, _inp: dict[str, Any]) -> bool:
+ return False
+
+ async def before(_sp: PlanNode, _inp: dict[str, Any]) -> None:
+ events.append("before")
+
+ async def after(_sp: PlanNode, _inp: dict[str, Any], _result: Any) -> None:
+ events.append("after")
+
+ root.set_runtime_callbacks(
+ should_skip_subplan_execute=should_skip,
+ before_subplan_execute=before,
+ after_subplan_execute=after,
+ )
+
+ stream = root._run_subplan_stream(
+ child, {}, [], index=6, total_steps=14
+ )
+ first = await anext(stream)
+ assert first["message"].startswith("开始执行")
+ assert first["_bubble_progress"] is True
+
+ await stream.aclose()
+
+ assert events == []
+ assert child.run_stream_calls == 0
+
@pytest.mark.asyncio
async def test_silent_resume_skip_falls_back_when_skip_disagrees(self):
from jiuwenswarm.server.runtime.skill_turbo.skill_codes.ppt.ppt_gen_root import (