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(skill_turbo):PPT 加速通道交付后主气泡无「交付总结」

Fancy1234567d1bce6158051
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index be23e284c6..e6052ec3fa 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -2062,6 +2062,7 @@ class JiuWenSwarmDeepAdapter:
self._stream_event_rail: JiuSwarmStreamEventRail | None = None
self._task_execution_rail: TaskExecutionRail | None = None
self._skill_turbo_prompt_rail: Any = None
+ self._skill_turbo_delivery_summary_rail: Any = None
self._skill_protocol_prompt_rail: Any = None
self._request_summary_rail: Any | None = None
# Track session IDs currently executing on this adapter instance.
@@ -7730,6 +7731,13 @@ class JiuWenSwarmDeepAdapter:
self._build_skill_turbo_prompt_rail,
)
)
+ # SkillTurboDeliverySummaryRail: 外层 tool_result 之后发出 PPT 交付总结
+ rail_infos.append(
+ _RailBuildInfo(
+ "_skill_turbo_delivery_summary_rail",
+ self._build_skill_turbo_delivery_summary_rail,
+ )
+ )
# SkillProtocolPromptRail: 注入技能执行规范(skill_protocol 段),仅 agent 模式挂载。
if isinstance(mode, str) and mode.startswith("agent"):
@@ -10436,6 +10444,36 @@ class JiuWenSwarmDeepAdapter:
logger.warning("[JiuWenSwarmDeepAdapter] SkillTurboPromptRail create failed: %s", exc)
return None
+ @staticmethod
+ def _build_skill_turbo_delivery_summary_rail() -> Any | None:
+ """构建 SkillTurboDeliverySummaryRail: tool_result 后发出 PPT 交付总结。
+
+ 仅在 config.react.skill_turbo.enabled = true 时创建,否则返回 None。
+ """
+ try:
+ config_base = get_config()
+ react_config = config_base.get("react", {}) if isinstance(config_base, dict) else {}
+ skill_turbo_config = react_config.get("skill_turbo", {}) if isinstance(react_config, dict) else {}
+ enabled = skill_turbo_config.get("enabled", False) if isinstance(skill_turbo_config, dict) else False
+ if not enabled:
+ return None
+
+ from jiuwenswarm.server.runtime.skill_turbo.rails.delivery_summary_rail import (
+ SkillTurboDeliverySummaryRail,
+ )
+
+ rail = SkillTurboDeliverySummaryRail()
+ logger.info(
+ "[JiuWenSwarmDeepAdapter] SkillTurboDeliverySummaryRail create success"
+ )
+ return rail
+ except Exception as exc:
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] SkillTurboDeliverySummaryRail create failed: %s",
+ exc,
+ )
+ return None
+
# ──────────── SkillTurbo 集成 ────────────
def build_skill_turbo_config(self) -> dict[str, Any]:
diff --git a/jiuwenswarm/server/runtime/skill_turbo/executor.py b/jiuwenswarm/server/runtime/skill_turbo/executor.py
index 9d70248b14..1c1a195cf2 100644
--- a/jiuwenswarm/server/runtime/skill_turbo/executor.py
+++ b/jiuwenswarm/server/runtime/skill_turbo/executor.py
@@ -3121,13 +3121,17 @@ class SkillTurboExecutor:
node_status = "completed"
info = artifact.get("info") if isinstance(artifact.get("info"), dict) else {}
files = artifact.get("files") if isinstance(artifact.get("files"), list) else []
- self._node_artifacts_holder[subplan.plan_name] = {
+ artifact_entry: dict[str, Any] = {
"task_id": task_id,
"status": node_status,
"info": info,
"files": files,
"finished_at": timestamp,
}
+ delivery_summary = artifact.get("delivery_summary")
+ if isinstance(delivery_summary, str) and delivery_summary.strip():
+ artifact_entry["delivery_summary"] = delivery_summary.strip()
+ self._node_artifacts_holder[subplan.plan_name] = artifact_entry
logger.debug(
"[SkillTurboExecutor] node_artifact collected: plan_name=%s status=%s has_artifact=%s",
subplan.plan_name,
diff --git a/jiuwenswarm/server/runtime/skill_turbo/rails/delivery_summary_rail.py b/jiuwenswarm/server/runtime/skill_turbo/rails/delivery_summary_rail.py
new file mode 100644
index 0000000000..8dd0c38265
--- /dev/null
+++ b/jiuwenswarm/server/runtime/skill_turbo/rails/delivery_summary_rail.py
@@ -0,0 +1,96 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""SkillTurboDeliverySummaryRail — 外层 tool_result 之后发出 PPT 交付总结。
+
+将 PPT 交付总结投递从通用 StreamEventRail 解耦:
+P10 成功时 skill_turbo_tools 把骨架挂到 ContextVar;本 rail 在
+skill_acceleration_exec 的 after_tool_call 中、且晚于 StreamEventRail
+发出 tool_result 之后,再 write_stream(llm_output)。
+
+时序约束(openjiuwen:priority 越小越先执行):
+StreamEventRail.priority=80 先发 tool_result;本 rail priority=90 后发骨架,
+才能落入 RelayClaw 的 pptTurboSummary 收集窗口。
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from openjiuwen.core.single_agent.rail.base import AgentCallbackContext, ToolCallInputs
+from openjiuwen.harness.rails.base import DeepAgentRail
+
+logger = logging.getLogger(__name__)
+
+_SKILL_ACCELERATION_TOOL = "skill_acceleration_exec"
+
+
+class SkillTurboDeliverySummaryRail(DeepAgentRail):
+ """在 skill_acceleration_exec 成功结束后流式发出待投递的 PPT 交付总结。"""
+
+ # 必须 > StreamEventRail(80),保证 tool_result 已发出后再发骨架。
+ priority = 90
+
+ async def after_tool_call(self, ctx: AgentCallbackContext) -> None:
+ if not isinstance(ctx.inputs, ToolCallInputs):
+ return
+
+ tool_name = str(
+ getattr(ctx.inputs, "tool_name", None)
+ or getattr(getattr(ctx.inputs, "tool_call", None), "name", "")
+ or ""
+ ).strip()
+ if tool_name != _SKILL_ACCELERATION_TOOL:
+ return
+
+ try:
+ from jiuwenswarm.server.runtime.skill_turbo.skill_turbo_tools import (
+ clear_pending_ppt_delivery_summary,
+ emit_pending_ppt_delivery_summary,
+ )
+ except Exception:
+ logger.debug(
+ "[SkillTurboDeliverySummaryRail] import delivery summary helpers failed",
+ exc_info=True,
+ )
+ return
+
+ # HITL / 审批中断:尚无真实 tool_result,清掉可能残留的 pending,勿发成功骨架。
+ if _is_tool_interrupt(ctx):
+ clear_pending_ppt_delivery_summary()
+ return
+
+ session = getattr(ctx, "session", None)
+ if session is None:
+ clear_pending_ppt_delivery_summary()
+ logger.debug(
+ "[SkillTurboDeliverySummaryRail] skip emit: session is None"
+ )
+ return
+
+ try:
+ await emit_pending_ppt_delivery_summary(session)
+ except Exception:
+ logger.debug(
+ "[SkillTurboDeliverySummaryRail] emit after tool_result failed",
+ exc_info=True,
+ )
+
+
+def _is_tool_interrupt(ctx: AgentCallbackContext) -> bool:
+ try:
+ from jiuwenswarm.agents.harness.common.rails.stream_event_rail import (
+ extract_tool_interrupt,
+ )
+ except Exception:
+ return False
+
+ tool_result = getattr(ctx.inputs, "tool_result", None) if ctx.inputs else None
+ if extract_tool_interrupt(tool_result) is not None:
+ return True
+ if extract_tool_interrupt(getattr(ctx, "exception", None)) is not None:
+ return True
+ return False
+
+
+__all__ = ["SkillTurboDeliverySummaryRail"]
diff --git a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/delivery.py b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/delivery.py
index ba7a9c0da4..dab728a5a8 100644
--- a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/delivery.py
+++ b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/delivery.py
@@ -6,6 +6,10 @@ from pathlib import Path
from typing import Any
from jiuwenswarm.server.runtime.skill_turbo.plan_node import AbortError, PlanNode
+from jiuwenswarm.server.runtime.skill_turbo.skill_codes.ppt.delivery_summary import (
+ build_delivery_summary_skeleton,
+ is_backup_listing_path,
+)
from jiuwenswarm.server.runtime.skill_turbo.skill_codes.ppt.ppt_common import PptCommon
from jiuwenswarm.server.runtime.skill_turbo.skill_codes.ppt.utils.bash_utils import (
normalize_tool_text,
@@ -123,37 +127,68 @@ class DeliveryNode(PlanNode):
summary = self._build_summary(
delivery_status, pptx_filename, page_count, pages_dir, send_file_status
)
+ delivery_summary = ""
+ if task_completed:
+ outline_text = await self._read_outline_text(inputs, output_dir)
+ delivery_summary = build_delivery_summary_skeleton(
+ pptx_filename=pptx_filename,
+ total_pages=total_pages or page_count,
+ delivery_status=delivery_status,
+ send_file_status=send_file_status,
+ pages_ok=pages_ok,
+ outline_text=outline_text,
+ topic=str(inputs.get("topic") or "").strip(),
+ style_id=str(inputs.get("style_id") or "").strip(),
+ speaker_notes_status=str(inputs.get("speaker_notes_status") or "skipped"),
+ need_speaker_notes=bool(inputs.get("need_speaker_notes")),
+ has_documents=bool(inputs.get("has_documents")),
+ image_map_path=str(inputs.get("image_map_path") or "").strip(),
+ export_status=export_status,
+ )
logger.info(
- "[P10] 交付完成 status=%s send=%s pptx=%s task_completed=%s",
+ "[P10] 交付完成 status=%s send=%s pptx=%s task_completed=%s summary_emitted=%s",
delivery_status,
send_file_status,
pptx_filename,
task_completed,
+ bool(delivery_summary),
)
+ artifact_info = {
+ "delivery_status": delivery_status,
+ "send_file_status": send_file_status,
+ "pptx_filename": pptx_filename,
+ "task_completed": task_completed,
+ "speaker_notes_status": str(inputs.get("speaker_notes_status") or "skipped"),
+ "delivery_summary_emitted": bool(delivery_summary),
+ }
return {
"delivery_status": delivery_status,
"artifact_tag": artifact_tag,
"send_file_status": send_file_status,
"summary": summary,
- # __artifact__ 字段供 SkillTurboExecutor._collect_node_artifact 提取,
- # 记录到 _node_artifacts_holder,最终由 _build_artifact_summary 构建产物摘要,
- # 追加到 skill_acceleration_exec 返回给 DeepAgent 主链路的 tool_result 中。
- # 没有 __artifact__ 时产物摘要为空,LLM 偶发性因看不到产物证据而误调 skill_tool 重跑。
+ "delivery_summary": delivery_summary,
"__artifact__": {
- "info": {
- "delivery_status": delivery_status,
- "send_file_status": send_file_status,
- "pptx_filename": pptx_filename,
- "task_completed": task_completed,
- # prod 新增:演讲备注状态(best-effort,可能 skipped/partial/ok)
- "speaker_notes_status": str(inputs.get("speaker_notes_status") or "skipped"),
- },
+ "info": artifact_info,
"files": [{"path": pptx_path}] if pptx_path else [],
+ "delivery_summary": delivery_summary,
},
}
+ async def _read_outline_text(self, inputs: dict[str, Any], output_dir: str) -> str:
+ outline_path = str(inputs.get("outline_path") or "").strip()
+ if not outline_path and output_dir:
+ outline_path = str(Path(output_dir) / "outline.md")
+ if not outline_path:
+ return ""
+ return await PptCommon.read_file(
+ self,
+ outline_path,
+ required=False,
+ label="outline.md",
+ )
+
async def _send_file(self, pptx_path: str) -> str:
if not self.has_tool("send_file_to_user"):
logger.info("[P10] send_file_to_user 工具不可用,跳过文件发送")
@@ -215,7 +250,9 @@ class DeliveryNode(PlanNode):
raise
files = []
- page_files = [f for f in files if f.startswith("page-") and f.endswith(".pptx.html")]
+ page_files = [
+ f for f in files if f.startswith("page-") and f.endswith(".pptx.html")
+ ]
if page_count <= 0:
return bool(page_files)
return len(page_files) == page_count
@@ -224,7 +261,11 @@ class DeliveryNode(PlanNode):
if result is None:
return []
if isinstance(result, list):
- return [self._basename(self._extract_path_from_item(x)) for x in result]
+ return [
+ name
+ for name in (self._basename(self._extract_path_from_item(x)) for x in result)
+ if name
+ ]
if isinstance(result, dict):
for key in ("entries", "files", "filenames", "items", "result", "matches", "paths"):
v = result.get(key)
@@ -286,6 +327,8 @@ class DeliveryNode(PlanNode):
@staticmethod
def _basename(path: str) -> str:
+ if is_backup_listing_path(path):
+ return ""
path = path.replace("\\", "/").rstrip("/")
return path.rsplit("/", 1)[-1] if "/" in path else path
diff --git a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/delivery_summary.py b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/delivery_summary.py
new file mode 100644
index 0000000000..a74493dc32
--- /dev/null
+++ b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/delivery_summary.py
@@ -0,0 +1,167 @@
+from __future__ import annotations
+
+import re
+from typing import Any
+
+DELIVERY_SUMMARY_START = "以下是完成情况概要:"
+
+_PAGE_HEADING_RE = re.compile(r"^### P(\d+):\s*(.*)$", re.MULTILINE)
+_FIELD_RE = re.compile(r"\*\*(标题|内容概要)\*\*[::]\s*(.+)")
+_STYLE_LABELS = {
+ "business-classic": "商务经典",
+ "tech-minimal": "科技极简",
+ "elegant-narrative": "优雅叙事",
+ "industrial-tech": "工业科技",
+ "custom": "自定义风格",
+}
+
+
+def is_backup_listing_path(path: str) -> bool:
+ parts = str(path or "").replace("\\", "/").strip("/").split("/")
+ return "_backup" in parts
+
+
+def _one_line(value: str) -> str:
+ return re.sub(r"\s+", " ", str(value or "")).strip()
+
+
+def _missing(value: Any, fallback: str = "未提供") -> str:
+ text = _one_line(str(value)) if value is not None else ""
+ return text if text else fallback
+
+
+def parse_outline_pages(outline_text: str) -> list[tuple[int, str, str]]:
+ text = str(outline_text or "")
+ matches = list(_PAGE_HEADING_RE.finditer(text))
+ pages: list[tuple[int, str, str]] = []
+ for index, match in enumerate(matches):
+ end = matches[index + 1].start() if index + 1 < len(matches) else len(text)
+ block = text[match.end():end]
+ fields = {key: _one_line(val) for key, val in _FIELD_RE.findall(block)}
+ title = fields.get("标题") or _one_line(match.group(2)) or "未提供"
+ core = fields.get("内容概要") or "未提供"
+ pages.append((int(match.group(1)), title, core))
+ pages.sort(key=lambda item: item[0])
+ return pages
+
+
+def _narrative_from_outline(outline_text: str) -> str:
+ match = re.search(r"\*\*叙事主线\*\*[::]\s*(.+)", str(outline_text or ""))
+ return _one_line(match.group(1)) if match else ""
+
+
+def _pick_core_pages(
+ pages: list[tuple[int, str, str]],
+ total_pages: int,
+) -> list[tuple[int, str, str]]:
+ if pages:
+ if len(pages) <= 3:
+ return pages
+ middle = pages[len(pages) // 2]
+ picked = [pages[0], middle, pages[-1]]
+ unique: list[tuple[int, str, str]] = []
+ seen: set[int] = set()
+ for item in picked:
+ if item[0] in seen:
+ continue
+ seen.add(item[0])
+ unique.append(item)
+ return unique
+ count = total_pages if total_pages > 0 else 1
+ return [(index, "未提供", "未提供") for index in range(1, min(count, 3) + 1)]
+
+
+def _speaker_notes_line(need_speaker_notes: bool, speaker_notes_status: str) -> str:
+ status = _one_line(speaker_notes_status).lower()
+ if not need_speaker_notes or status in ("", "skipped"):
+ return "未请求演讲备注"
+ if status == "ok":
+ return "已注入演讲备注"
+ if status == "partial":
+ return "部分页演讲备注注入失败"
+ if status in ("failed", "error"):
+ return "演讲备注注入失败,PPTX 已交付"
+ return _missing(speaker_notes_status)
+
+
+def _gate_line(delivery_status: str, export_status: str, pages_ok: bool) -> str:
+ export = _one_line(export_status) or "未提供"
+ pages = "HTML 页数与大纲一致" if pages_ok else "HTML 页数校验未完全对齐"
+ delivery = _one_line(delivery_status) or "未提供"
+ return f"导出 {export};{pages};交付 {delivery}"
+
+
+def build_delivery_summary_skeleton(
+ *,
+ pptx_filename: str,
+ total_pages: int,
+ delivery_status: str,
+ send_file_status: str,
+ pages_ok: bool,
+ outline_text: str = "",
+ topic: str = "",
+ style_id: str = "",
+ speaker_notes_status: str = "",
+ need_speaker_notes: bool = False,
+ has_documents: bool = False,
+ image_map_path: str = "",
+ export_status: str = "",
+) -> str:
+ filename = _missing(pptx_filename)
+ page_count = total_pages if total_pages > 0 else 1
+ pages = parse_outline_pages(outline_text)
+ core_pages = _pick_core_pages(pages, page_count)
+ narrative = _narrative_from_outline(outline_text)
+ style_label = _STYLE_LABELS.get(_one_line(style_id), _missing(style_id))
+ image_strategy = "已按素材配图" if _one_line(image_map_path) else "按无图布局生成"
+ input_source = "用户主题与上传文档" if has_documents else "用户主题与对话要求"
+ if topic:
+ input_source = f"{input_source}({_missing(topic)})"
+ notes_line = _speaker_notes_line(need_speaker_notes, speaker_notes_status)
+ core_lines = "\n".join(
+ f"- P{num}:{_missing(title)} - {_missing(core)}" for num, title, core in core_pages
+ )
+ added = filename if send_file_status == "sent" else f"{filename}(发送状态:{_missing(send_file_status)})"
+ return (
+ f"{DELIVERY_SUMMARY_START}\n"
+ "\n"
+ "✅ 已完成:PPT 生成\n"
+ "\n"
+ f"已处理:生成演示文稿《{filename}》,共 {page_count} 页。\n"
+ f"产物概括:{_missing(narrative, '未提供')}\n"
+ f"门禁校验:{_gate_line(delivery_status, export_status, pages_ok)}\n"
+ "\n"
+ "**📌 本次执行口径**\n"
+ f"📁 输入来源:{input_source}\n"
+ f"📊 页面范围:P1-P{page_count}\n"
+ f"🎨 设计口径:{style_label}\n"
+ f"🖼️ 图片策略:{image_strategy}\n"
+ "⏭️ 未处理内容:无\n"
+ "\n"
+ "**🎯 核心内容**\n"
+ f"{core_lines}\n"
+ "\n"
+ "**⚠️ 重点提醒**\n"
+ "- 版式:加速通道已完成页面生成与导出\n"
+ "- 字体:未提供\n"
+ f"- 备注:{notes_line}\n"
+ "\n"
+ "**📁 文件变更**\n"
+ "\n"
+ "| 类型 | 内容 |\n"
+ "|---|---|\n"
+ f"| 新增 | {added} |\n"
+ "| 更新 | 无 |\n"
+ "| 保留 | 无 |\n"
+ "| 未自动处理 | 无 |\n"
+ "\n"
+ "**✅ 建议校对**\n"
+ "1. 核对封面标题与主题是否一致\n"
+ "2. 核对内页专有名词与关键数据\n"
+ "3. 过一遍页序、备注与图片裁切\n"
+ "\n"
+ "**🔄 你可以继续让我**\n"
+ "- 调整风格或配色\n"
+ "- 压缩或扩写某页内容\n"
+ "- 补充或重写演讲备注\n"
+ )
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 205158cffb..9cbf7ce7cd 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
@@ -394,6 +394,13 @@ class PPTGenRootNode(PlanNode):
):
yield chunk
+ # 交付总结骨架不在此处流式发出:
+ # 1) 此时 P10 after_subplan 已清空 task_id,骨架会与「PPT生成任务流执行完成」等
+ # 无 stream_source_id 的过程尾落入同一缓冲桶,主气泡第一行变成过程尾;
+ # 2) 该 chat.delta 早于外层 skill_acceleration_exec 的 tool_result,进不了
+ # RelayClaw 的 pptTurboSummary 收集窗口(tool_result 时还会被清空)。
+ # 骨架由 P10 写入 artifact → skill_turbo_tools 挂 ContextVar →
+ # SkillTurboDeliverySummaryRail 在外层 tool_result 之后再发 llm_output。
yield {
"node": self.plan_name,
"status": "ok",
diff --git a/jiuwenswarm/server/runtime/skill_turbo/skill_turbo_tools.py b/jiuwenswarm/server/runtime/skill_turbo/skill_turbo_tools.py
index 82bbcb1613..1abb20abed 100644
--- a/jiuwenswarm/server/runtime/skill_turbo/skill_turbo_tools.py
+++ b/jiuwenswarm/server/runtime/skill_turbo/skill_turbo_tools.py
@@ -34,6 +34,12 @@ _SKILL_TURBO_STOP_HINT = (
"work is already done; calling any of them again would duplicate the work."
)
+_PPT_DELIVERY_SUMMARY_POST_TOOL_HINT = (
+ "\n\n[SYSTEM] PPT 交付总结骨架将由系统在本工具结果之后通过流式通道发送给用户,"
+ "无需在本回合重复输出交付总结。禁止 tool_call,禁止再调 "
+ "send_file_to_user / skill_tool / skill_acceleration_exec。"
+)
+
# 工具返回值会先被 AbilityManager 收成 ToolMessage。after_tool_call 再用
# StreamEventRail._tool_interrupted_message(随 prompt 语言中/英)覆写 tool_msg。
# _fix_incomplete_tool_context 认 rail 文案 + 中英文 legacy 模板,故本常量取中文
@@ -43,6 +49,15 @@ _SKILL_TURBO_HITL_PLACEHOLDER = (
"[工具执行被中断] 工具 skill_acceleration_exec 执行过程中被用户打断,没有执行结果。"
)
+# ── 待在外层 tool_result 之后发出的 PPT 交付总结 ──
+# 不可在 ppt_gen_root / 工具执行中途以 chat.delta 发出:那时无 task_id,会与过程尾
+# 同桶;且早于 skill_acceleration_exec 的 tool_result,RelayClaw 收集窗口会清空。
+# 由 SkillTurboDeliverySummaryRail.after_tool_call(晚于 StreamEventRail 发
+# tool_result)读取并发出。
+_pending_ppt_delivery_summary: ContextVar[str | None] = ContextVar(
+ "pending_ppt_delivery_summary", default=None
+)
+
# ── SkillTurbo event_type -> DeepAgent OutputSchema.type 反向映射 ──
# SkillTurbo executor 产出的 payload.event_type 带 "chat." 前缀,而 DeepAgent 主循环 /
# _parse_stream_chunk 期望原始 OutputSchema.type(不带前缀)。直接用 event_type 作 type
@@ -128,6 +143,60 @@ def get_skill_turbo_hitl_tic() -> Any:
return _skill_turbo_hitl_tic.get()
+def set_pending_ppt_delivery_summary(summary: str) -> None:
+ text = str(summary or "").strip()
+ _pending_ppt_delivery_summary.set(text or None)
+
+
+def clear_pending_ppt_delivery_summary() -> None:
+ _pending_ppt_delivery_summary.set(None)
+
+
+def take_pending_ppt_delivery_summary() -> str:
+ text = str(_pending_ppt_delivery_summary.get() or "").strip()
+ _pending_ppt_delivery_summary.set(None)
+ return text
+
+
+async def emit_pending_ppt_delivery_summary(session: "Session") -> bool:
+ """在外层 tool_result 之后发出无 task_id 的交付总结 chat.delta。
+
+ 返回是否实际发出。session 为 None 或骨架非法时静默跳过。
+ """
+ from jiuwenswarm.server.runtime.skill_turbo.skill_codes.ppt.delivery_summary import (
+ DELIVERY_SUMMARY_START,
+ )
+ from openjiuwen.core.session.stream.base import OutputSchema
+
+ summary = take_pending_ppt_delivery_summary()
+ if not summary.startswith(DELIVERY_SUMMARY_START):
+ return False
+ if session is None:
+ logger.warning(
+ "[SkillTurboTool] pending PPT delivery summary dropped: parent session is None"
+ )
+ return False
+ try:
+ await session.write_stream(
+ OutputSchema(
+ type="llm_output",
+ index=0,
+ payload={"content": summary},
+ )
+ )
+ logger.info(
+ "[SkillTurboTool] emitted PPT delivery summary after tool_result chars=%d",
+ len(summary),
+ )
+ return True
+ except Exception:
+ logger.warning(
+ "[SkillTurboTool] emit PPT delivery summary after tool_result failed",
+ exc_info=True,
+ )
+ return False
+
+
def set_current_skill_turbo_adapter(adapter: Any) -> Token:
"""绑定当前 async 上下文的 DeepAdapter 实例,返回 Token 用于 reset。"""
return _current_skill_turbo_adapter.set(adapter)
@@ -265,6 +334,14 @@ def _build_artifact_summary(holder: dict[str, Any]) -> str:
return "\n".join(lines) if len(lines) > 1 else ""
+def _ppt_delivery_summary(artifact_holder: dict[str, Any] | None) -> str:
+ node = (artifact_holder or {}).get("p10_delivery")
+ if not isinstance(node, dict):
+ return ""
+ text = node.get("delivery_summary")
+ return text.strip() if isinstance(text, str) else ""
+
+
def _wrap_skill_turbo_result(
result_dict: dict[str, Any],
artifact_holder: dict[str, Any] | None = None,
@@ -275,13 +352,22 @@ def _wrap_skill_turbo_result(
若此处追加 "finish your turn" 会与之矛盾。
"""
artifact_text = _build_artifact_summary(artifact_holder or {})
+ ppt_summary = _ppt_delivery_summary(artifact_holder)
if result_dict.get("success"):
parts = [result_dict.get("result") or ""]
if artifact_text:
parts.append(artifact_text)
- parts.append(_SKILL_TURBO_STOP_HINT)
+ if ppt_summary:
+ # 骨架不进 tool_result 正文、也不在流水线内提前 chat.delta;
+ # 挂到 ContextVar,由 after_tool_call 在外层 tool_result 之后流式发出。
+ set_pending_ppt_delivery_summary(ppt_summary)
+ parts.append(_PPT_DELIVERY_SUMMARY_POST_TOOL_HINT)
+ else:
+ clear_pending_ppt_delivery_summary()
+ parts.append(_SKILL_TURBO_STOP_HINT)
result_dict["result"] = "\n\n".join(p for p in parts if p)
else:
+ clear_pending_ppt_delivery_summary()
parts = [result_dict.get("error") or ""]
if artifact_text:
parts.append(artifact_text)
diff --git a/tests/unit_tests/server/runtime/skill_turbo/test_ppt_delivery_summary.py b/tests/unit_tests/server/runtime/skill_turbo/test_ppt_delivery_summary.py
new file mode 100644
index 0000000000..fcdf8471f5
--- /dev/null
+++ b/tests/unit_tests/server/runtime/skill_turbo/test_ppt_delivery_summary.py
@@ -0,0 +1,419 @@
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from jiuwenswarm.server.runtime.skill_turbo.skill_codes.ppt.delivery import DeliveryNode
+from jiuwenswarm.server.runtime.skill_turbo.skill_codes.ppt.delivery_summary import (
+ DELIVERY_SUMMARY_START,
+ build_delivery_summary_skeleton,
+ is_backup_listing_path,
+ parse_outline_pages,
+)
+from jiuwenswarm.server.runtime.skill_turbo.skill_codes.ppt.ppt_gen_root import PPTGenRootNode
+from jiuwenswarm.server.runtime.skill_turbo.skill_turbo_tools import (
+ _wrap_skill_turbo_result,
+ clear_pending_ppt_delivery_summary,
+ emit_pending_ppt_delivery_summary,
+ take_pending_ppt_delivery_summary,
+)
+
+_SAMPLE_OUTLINE = """# 大纲:杭州旅游
+
+**受众**:游客
+**总页数**:3
+**叙事主线**:一日游路线与必看景点
+**输入类型**:topic
+**搜索模式**:off
+
+## 页面规划
+
+### P1: 封面
+- **类型**:cover
+- **研究需求**:❌
+- **标题**:杭州一日游
+- **内容概要**:西湖与城市印象
+- **研究查询**:-
+- **数据需求**:-
+
+### P2: 行程
+- **类型**:agenda
+- **研究需求**:❌
+- **标题**:上午西湖下午灵隐
+- **内容概要**:按时间排列的游览顺序
+- **研究查询**:-
+- **数据需求**:-
+
+### P3: 结束
+- **类型**:ending
+- **研究需求**:❌
+- **标题**:感谢聆听
+- **内容概要**:欢迎再次到访
+- **研究查询**:-
+- **数据需求**:-
+"""
+
+
+def test_backup_listing_path_detects_nested_backup_html() -> None:
+ assert is_backup_listing_path("pages/_backup/page-1.pptx.html") is True
+ assert is_backup_listing_path(r"pages\\_backup\\page-1.pptx.html") is True
+ assert is_backup_listing_path("pages/page-1.pptx.html") is False
+ assert is_backup_listing_path("_backup") is True
+
+
+def test_parse_listing_drops_backup_pages() -> None:
+ node = DeliveryNode()
+ files = node._parse_listing(
+ [
+ "pages/page-1.pptx.html",
+ "pages/_backup/page-1.pptx.html",
+ "pages/_backup/page-2.pptx.html",
+ "pages/_backup/page-3.pptx.html",
+ "pages/page-2.pptx.html",
+ "pages/page-3.pptx.html",
+ ]
+ )
+ assert files == ["page-1.pptx.html", "page-2.pptx.html", "page-3.pptx.html"]
+
+
+async def test_check_pages_ignores_backup_html(monkeypatch: pytest.MonkeyPatch) -> None:
+ node = DeliveryNode()
+ monkeypatch.setattr(node, "has_tool", lambda name: name == "glob")
+
+ async def call_tool(_name: str, **_kwargs: Any) -> list[str]:
+ return [
+ "pages/page-1.pptx.html",
+ "pages/_backup/page-1.pptx.html",
+ "pages/_backup/page-2.pptx.html",
+ "pages/_backup/page-3.pptx.html",
+ "pages/page-2.pptx.html",
+ "pages/page-3.pptx.html",
+ ]
+
+ monkeypatch.setattr(node, "call_tool", call_tool)
+ assert await node._check_pages("/tmp/pages", 3) is True
+
+
+def test_parse_outline_pages_reads_titles() -> None:
+ pages = parse_outline_pages(_SAMPLE_OUTLINE)
+ assert pages[0] == (1, "杭州一日游", "西湖与城市印象")
+ assert pages[-1][1] == "感谢聆听"
+
+
+def test_build_delivery_summary_skeleton_uses_literal_start_and_real_pages() -> None:
+ text = build_delivery_summary_skeleton(
+ pptx_filename="杭州旅游.pptx",
+ total_pages=3,
+ delivery_status="ok",
+ send_file_status="sent",
+ pages_ok=True,
+ outline_text=_SAMPLE_OUTLINE,
+ topic="杭州旅游",
+ style_id="business-classic",
+ speaker_notes_status="skipped",
+ need_speaker_notes=False,
+ has_documents=False,
+ image_map_path="",
+ export_status="ok",
+ )
+ assert text.startswith(DELIVERY_SUMMARY_START)
+ assert "《杭州旅游.pptx》" in text
+ assert "共 3 页" in text
+ assert "- P1:杭州一日游 - 西湖与城市印象" in text
+ assert "未请求演讲备注" in text
+ assert "文件位置" not in text
+ assert "D:/" not in text and "C:/" not in text
+
+
+def test_build_delivery_summary_keeps_only_real_pages_when_fewer_than_three() -> None:
+ outline = """### P1: 封面
+- **标题**:仅一页
+- **内容概要**:杭州
+"""
+ text = build_delivery_summary_skeleton(
+ pptx_filename="杭州旅游.pptx",
+ total_pages=1,
+ delivery_status="ok",
+ send_file_status="sent",
+ pages_ok=True,
+ outline_text=outline,
+ topic="杭州旅游",
+ style_id="tech-minimal",
+ export_status="ok",
+ )
+ assert "- P1:仅一页 - 杭州" in text
+ assert "- P2:" not in text
+ assert "- P3:" not in text
+
+
+async def test_p10_emits_skeleton_when_send_succeeds(
+ tmp_path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pptx = tmp_path / "杭州旅游.pptx"
+ pptx.write_bytes(b"dummy-pptx")
+ (tmp_path / "outline.md").write_text(_SAMPLE_OUTLINE, encoding="utf-8")
+ pages_dir = tmp_path / "pages"
+ pages_dir.mkdir()
+ node = DeliveryNode()
+ monkeypatch.setattr(
+ node,
+ "has_tool",
+ lambda name: name in {"send_file_to_user", "glob", "read_file"},
+ )
+
+ async def call_tool(name: str, **kwargs: Any) -> Any:
+ if name == "send_file_to_user":
+ return "成功发送 1 个文件"
+ if name == "glob":
+ return [
+ str(pages_dir / "page-1.pptx.html"),
+ str(pages_dir / "_backup" / "page-1.pptx.html"),
+ ]
+ if name == "read_file":
+ return SimpleNamespace(success=True, data={"content": _SAMPLE_OUTLINE})
+ raise AssertionError(name)
+
+ monkeypatch.setattr(node, "call_tool", call_tool)
+ result = await node._execute(
+ {
+ "output_dir": str(tmp_path),
+ "pages_dir": str(pages_dir),
+ "pptx_path": str(pptx),
+ "pptx_filename": "杭州旅游.pptx",
+ "export_status": "ok",
+ "page_count": 0,
+ "total_pages": 1,
+ "topic": "杭州旅游",
+ "style_id": "business-classic",
+ }
+ )
+ assert result["delivery_status"] == "ok"
+ assert result["send_file_status"] == "sent"
+ assert str(result["delivery_summary"]).startswith(DELIVERY_SUMMARY_START)
+ assert result["__artifact__"]["delivery_summary"].startswith(DELIVERY_SUMMARY_START)
+
+
+async def test_p10_does_not_emit_skeleton_when_send_fails(
+ tmp_path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ pptx = tmp_path / "杭州旅游.pptx"
+ pptx.write_bytes(b"dummy-pptx")
+ node = DeliveryNode()
+ monkeypatch.setattr(node, "has_tool", lambda name: name in {"send_file_to_user", "glob"})
+
+ async def call_tool(name: str, **_kwargs: Any) -> Any:
+ if name == "send_file_to_user":
+ return "发送文件失败"
+ if name == "glob":
+ return ["page-1.pptx.html"]
+ raise AssertionError(name)
+
+ monkeypatch.setattr(node, "call_tool", call_tool)
+ result = await node._execute(
+ {
+ "output_dir": str(tmp_path),
+ "pages_dir": str(tmp_path / "pages"),
+ "pptx_path": str(pptx),
+ "pptx_filename": "杭州旅游.pptx",
+ "export_status": "ok",
+ "page_count": 1,
+ "total_pages": 1,
+ }
+ )
+ assert result["send_file_status"] == "failed"
+ assert result["delivery_summary"] == ""
+
+
+async def test_root_stream_does_not_emit_summary_delta_after_flow_complete(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """骨架不得在计划结束后以无 task_id 的 chat.delta 发出(会与过程尾同桶)。"""
+ root = PPTGenRootNode()
+ summary = f"{DELIVERY_SUMMARY_START}\n\n✅ 已完成:PPT 生成\n"
+
+ async def should_skip(_subplan, _inputs) -> bool:
+ return False
+
+ async def run_subplan_stream(subplan, inputs, results, **_kwargs):
+ if subplan is root._p1:
+ inputs["has_documents"] = True
+ if subplan is root._p3:
+ inputs["doc_parse_ok"] = True
+ if subplan is root._delivery:
+ inputs["delivery_summary"] = summary
+ result = {"node": subplan.plan_name, "status": "ok"}
+ results.append({"node": subplan.plan_name, "status": "ok", "result": result})
+ yield result
+
+ monkeypatch.setattr(root, "should_skip_subplan", should_skip)
+ monkeypatch.setattr(root, "_run_subplan_stream", run_subplan_stream)
+
+ chunks = [chunk async for chunk in root._execute_stream({})]
+ assert chunks[-1]["message"] == "PPT生成任务流执行完成"
+ assert all(chunk.get("event_type") != "chat.delta" for chunk in chunks)
+ assert all(
+ DELIVERY_SUMMARY_START not in str(chunk.get("content") or "")
+ for chunk in chunks
+ )
+
+
+def test_wrap_skill_turbo_result_queues_ppt_skeleton_for_post_tool_emit() -> None:
+ clear_pending_ppt_delivery_summary()
+ skeleton = f"{DELIVERY_SUMMARY_START}\n\n✅ 已完成:PPT 生成\n"
+ wrapped = _wrap_skill_turbo_result(
+ {"success": True, "result": "任务已完成"},
+ {
+ "p10_delivery": {
+ "info": {"send_file_status": "sent", "delivery_summary_emitted": True},
+ "files": [],
+ "delivery_summary": skeleton,
+ }
+ },
+ )
+ assert DELIVERY_SUMMARY_START not in wrapped["result"]
+ assert "流式通道" in wrapped["result"]
+ assert "无需在本回合重复输出" in wrapped["result"]
+ assert "You should now summarize" not in wrapped["result"]
+ assert take_pending_ppt_delivery_summary() == skeleton.strip()
+ assert take_pending_ppt_delivery_summary() == ""
+
+
+def test_wrap_skill_turbo_result_keeps_generic_hint_without_ppt_summary() -> None:
+ clear_pending_ppt_delivery_summary()
+ wrapped = _wrap_skill_turbo_result({"success": True, "result": "任务已完成"}, {})
+ assert "You should now summarize" in wrapped["result"]
+ assert "逐字输出" not in wrapped["result"]
+ assert take_pending_ppt_delivery_summary() == ""
+
+
+async def test_emit_pending_ppt_delivery_summary_writes_llm_output() -> None:
+ clear_pending_ppt_delivery_summary()
+ skeleton = f"{DELIVERY_SUMMARY_START}\n\n✅ 已完成:PPT 生成\n"
+ from jiuwenswarm.server.runtime.skill_turbo.skill_turbo_tools import (
+ set_pending_ppt_delivery_summary,
+ )
+
+ set_pending_ppt_delivery_summary(skeleton)
+ written: list[Any] = []
+
+ class _Session:
+ async def write_stream(self, output: Any) -> None:
+ written.append(output)
+
+ assert await emit_pending_ppt_delivery_summary(_Session()) is True
+ assert len(written) == 1
+ assert written[0].type == "llm_output"
+ assert written[0].payload["content"].startswith(DELIVERY_SUMMARY_START)
+ assert take_pending_ppt_delivery_summary() == ""
+
+
+def _make_tool_call_ctx(
+ *,
+ tool_name: str,
+ tool_result: Any = None,
+ session: Any = None,
+ exception: Exception | None = None,
+) -> Any:
+ from openjiuwen.core.single_agent.rail.base import ToolCallInputs
+
+ return SimpleNamespace(
+ inputs=ToolCallInputs(
+ tool_call=None,
+ tool_name=tool_name,
+ tool_args={},
+ tool_result=tool_result,
+ tool_msg=None,
+ ),
+ session=session,
+ exception=exception,
+ )
+
+
+async def test_delivery_summary_rail_emits_after_skill_acceleration_exec() -> None:
+ from jiuwenswarm.server.runtime.skill_turbo.rails.delivery_summary_rail import (
+ SkillTurboDeliverySummaryRail,
+ )
+ from jiuwenswarm.server.runtime.skill_turbo.skill_turbo_tools import (
+ set_pending_ppt_delivery_summary,
+ )
+
+ clear_pending_ppt_delivery_summary()
+ skeleton = f"{DELIVERY_SUMMARY_START}\n\n✅ 已完成:PPT 生成\n"
+ set_pending_ppt_delivery_summary(skeleton)
+ written: list[Any] = []
+
+ class _Session:
+ async def write_stream(self, output: Any) -> None:
+ written.append(output)
+
+ rail = SkillTurboDeliverySummaryRail()
+ assert rail.priority > 80
+ await rail.after_tool_call(
+ _make_tool_call_ctx(
+ tool_name="skill_acceleration_exec",
+ tool_result={"success": True},
+ session=_Session(),
+ )
+ )
+ assert len(written) == 1
+ assert written[0].payload["content"].startswith(DELIVERY_SUMMARY_START)
+ assert take_pending_ppt_delivery_summary() == ""
+
+
+async def test_delivery_summary_rail_ignores_other_tools() -> None:
+ from jiuwenswarm.server.runtime.skill_turbo.rails.delivery_summary_rail import (
+ SkillTurboDeliverySummaryRail,
+ )
+ from jiuwenswarm.server.runtime.skill_turbo.skill_turbo_tools import (
+ set_pending_ppt_delivery_summary,
+ )
+
+ clear_pending_ppt_delivery_summary()
+ skeleton = f"{DELIVERY_SUMMARY_START}\n\n✅ 已完成:PPT 生成\n"
+ set_pending_ppt_delivery_summary(skeleton)
+
+ await SkillTurboDeliverySummaryRail().after_tool_call(
+ _make_tool_call_ctx(tool_name="bash", tool_result={"ok": True}, session=object())
+ )
+ assert take_pending_ppt_delivery_summary() == skeleton.strip()
+
+
+async def test_delivery_summary_rail_clears_pending_on_tool_interrupt() -> None:
+ from jiuwenswarm.server.runtime.skill_turbo.rails.delivery_summary_rail import (
+ SkillTurboDeliverySummaryRail,
+ )
+ from jiuwenswarm.server.runtime.skill_turbo.skill_turbo_tools import (
+ set_pending_ppt_delivery_summary,
+ )
+
+ class ToolInterruptException(Exception):
+ def __init__(self) -> None:
+ self.request = object()
+
+ clear_pending_ppt_delivery_summary()
+ set_pending_ppt_delivery_summary(f"{DELIVERY_SUMMARY_START}\n\n✅ 已完成\n")
+ written: list[Any] = []
+
+ class _Session:
+ async def write_stream(self, output: Any) -> None:
+ written.append(output)
+
+ await SkillTurboDeliverySummaryRail().after_tool_call(
+ _make_tool_call_ctx(
+ tool_name="skill_acceleration_exec",
+ tool_result=ToolInterruptException(),
+ session=_Session(),
+ )
+ )
+ assert written == []
+ assert take_pending_ppt_delivery_summary() == ""