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 内容页因图表高度链校验失败被丢弃导致的缺页问题
CodehubTTG4f160857f050
diff --git a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_export.py b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_export.pyindex 26c3fb967c..8e513d0c89 100644--- a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_export.py+++ b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_export.py@@ -4,6 +4,7 @@ import loggingimport refrom collections.abc import AsyncIteratorfrom dataclasses import dataclass+from pathlib import Pathfrom typing import Anyfrom jiuwenswarm.server.runtime.skill_turbo.plan_node import AbortError, PlanNode@@ -52,6 +53,24 @@ class ExportPaths:pptx_root: str+def _pptx_exists_status(pptx_path: str) -> str:+ """node stat 失败时的 pathlib 回退:存在且 ≥10KB→ok,>0→partial,否则 failed。"""+ path = Path(pptx_path)+ if path.is_file():+ size = path.stat().st_size+ if size >= 10 * 1024:+ logger.info("[P9] PPTX Python fallback 验证通过 size=%d", size)+ return "ok"+ elif size > 0:+ logger.warning("[P9] PPTX Python fallback 文件过小 size=%d", size)+ return "partial"+ else:+ logger.warning("[P9] PPTX Python fallback 文件大小为 0")+ return "failed"+ logger.warning("[P9] PPTX 文件确认不存在: %s", pptx_path)+ return "failed"++class PPTExportNode(PlanNode):"""P9 — PPTX 导出(对应 SKILL Stage 8)。"""@@ -346,9 +365,19 @@ class PPTExportNode(PlanNode):timeout_seconds=30, required=False, workdir=pptx_root,)if result.exit_code != 0:- logger.warning("[P9] PPTX stat 失败,跳过大小验证")- return "ok"- size = int(result.stdout.strip() or "0")+ logger.warning(+ "[P9] PPTX stat 失败 exit=%d,尝试 Python fallback: %s",+ result.exit_code, pptx_path,+ )+ return _pptx_exists_status(pptx_path)+ stdout_stripped = result.stdout.strip()+ if not stdout_stripped or not stdout_stripped.lstrip('-').isdigit():+ logger.warning(+ "[P9] PPTX stat 输出非数字,尝试 Python fallback: %s",+ stdout_stripped[:200] if stdout_stripped else "(empty)",+ )+ return _pptx_exists_status(pptx_path)+ size = int(stdout_stripped)if size < 10 * 1024:logger.warning("[P9] PPTX 文件过小 size=%d < 10KB", size)return "partial"@@ -357,8 +386,8 @@ class PPTExportNode(PlanNode):except Exception as e:if isinstance(e, AbortError):raise- logger.warning("[P9] PPTX 验证失败: %s", e)- return "ok"+ logger.warning("[P9] PPTX 验证失败,尝试 Python fallback: %s", e)+ return _pptx_exists_status(pptx_path)async def _execute_stream(self, inputs: dict[str, Any]) -> AsyncIterator[dict[str, Any]]:result = await self._execute(inputs)diff --git a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_page_gen.py b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_page_gen.pyindex a7bde94b9a..6f2c25568c 100644--- a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_page_gen.py+++ b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/ppt_page_gen.py@@ -4,7 +4,7 @@ import asyncioimport jsonimport loggingimport re-from collections.abc import AsyncIterator+from collections.abc import AsyncIterator, Callablefrom dataclasses import dataclassfrom typing import Any@@ -521,6 +521,7 @@ def _build_content_template_fill_prompt(designer_md_text: str = "",user_query: str = "",total_pages: int = 0,+ rewrite_hint: str = "",) -> str:"""预设四风格内容页:content-template 预铺后仅填三处占位符。"""user_query_section = ""@@ -552,6 +553,13 @@ def _build_content_template_fill_prompt(if designer_md:designer_section = f"\n## skill designer 约束(仅作用于 `{{PAGE_CONTENT}}`)\n{designer_md}\n"layout_template = _build_content_layout_template(page_type)+ rewrite_section = ""+ if rewrite_hint:+ rewrite_section = (+ "\n## 重写指引(必须修复的问题)\n"+ f"{rewrite_hint}\n"+ "⚠️ 仅修复上述不通过项,不要改动其他正常部分。\n"+ )return (f"{user_query_section}"f"## 任务:填充第 {page_number} 页预设风格 content-template 官方模板\n"@@ -579,6 +587,7 @@ def _build_content_template_fill_prompt(f"{_EDITABLE_LAYERING_RULES}"f"{designer_section}"f"{layout_template}\n"+ f"{rewrite_section}""## 预铺模板 HTML(只填槽,勿重写)\n"f"{seed_html}\n")@@ -791,8 +800,10 @@ _DESIGN_RULES_DIGEST = ("4.2 图表最小高度(强制):图表容器实际渲染高度必须 ≥ 160px(防塌缩下限),""用 `min-h-[160px]` 或 `flex-1` 确保图表区域能初始化渲染;""建议图表可读高度 ≥ 300px,由页面预算保证\n"- "4.2.1 图表高度链(强制):图表外层卡片须 `flex-1 min-h-0 flex flex-col`(或 `flex-[N] min-h-0 flex flex-col`),"- "内层 `#xxx-chart` 用 `flex-1 min-h-0 w-full`;禁止在无 `min-h-0`/`flex-1` 的 flex-col 父容器内单独给 chart div 加 `flex-1`\n"+ "4.2.1 图表高度链(强制):包含 chart div 的最近 `flex flex-col` 祖先容器必须带 `flex-1 min-h-0`(或 `flex-[N] min-h-0`),"+ "chart div 用 `flex-1 min-h-0 w-full` 或 `w-full h-full`;"+ "标准写法 `div.flex-1.min-h-0.flex.flex-col > div#chart-1.w-full.h-full`;"+ "禁止在无 `min-h-0`/`flex-1` 的 flex-col 父容器内放置 chart div\n""4.3 图表颜色(强制):图表数据系列颜色必须来自风格文件的图表配色表,禁止使用相近色;""坐标轴标签用深色,分割线用浅色\n""4.4 图表标签防重叠:建议为 ECharts series 设置 `labelLayout:{moveOverlap:'shiftY'}` 防止同系列标签重叠;"@@ -1261,6 +1272,10 @@ _CHART_WRAPPER_HEIGHT_RE = re.compile(r"\bmin-h-0\b|\bflex-1\b|\bflex-\[\d+\]",re.IGNORECASE,)+_FLEX_GROW_RE = re.compile(+ r"\bflex-1\b|\bflex-\[\d+\]",+ re.IGNORECASE,+)def _chart_wrapper_has_height_chain(wrapper_tag: str) -> bool:@@ -1286,6 +1301,84 @@ def _validate_chart_height_chain(html: str) -> bool:return True+def _inject_class_into_chart_wrappers(+ html: str,+ class_name: str,+ *,+ needs_inject: Callable[[str], bool],+) -> tuple[str, int]:+ """向满足条件的图表 flex-col 包装器注入 class;已含该类则跳过。"""+ if "echarts.init" not in html.lower():+ return html, 0++ chart_divs = list(_CHART_DIV_RE.finditer(html))+ if not chart_divs:+ return html, 0++ repair_offsets: set[tuple[int, int]] = set()+ for chart_match in chart_divs:+ window_start = max(0, chart_match.start() - 2000)+ before = html[window_start:chart_match.start()]+ wrappers = list(_FLEX_COL_DIV_RE.finditer(before))+ if not wrappers:+ continue+ last_wrapper = wrappers[-1]+ if needs_inject(last_wrapper.group(0)):+ abs_start = window_start + last_wrapper.start()+ abs_end = window_start + last_wrapper.end()+ repair_offsets.add((abs_start, abs_end))++ if not repair_offsets:+ return html, 0++ result = html+ injected = 0+ class_re = re.compile(rf"\b{re.escape(class_name)}\b")+ for abs_start, abs_end in sorted(repair_offsets, reverse=True):+ wrapper_tag = result[abs_start:abs_end]+ if class_re.search(wrapper_tag):+ continue+ fixed_tag = re.sub(+ r'(class="[^"]*)"',+ rf'\1 {class_name}"',+ wrapper_tag,+ count=1,+ )+ if fixed_tag == wrapper_tag:+ continue+ result = result[:abs_start] + fixed_tag + result[abs_end:]+ injected += 1++ return result, injected+++def _fix_chart_height_chain(html: str) -> str:+ """写盘前修复图表高度链:缺高度链类时注入 min-h-0,再对缺 flex-1/flex-[N] 的包装器注入 flex-1。"""+ result, count_1 = _inject_class_into_chart_wrappers(+ html,+ "min-h-0",+ needs_inject=lambda tag: not _chart_wrapper_has_height_chain(tag),+ )+ if count_1:+ logger.info(+ "[P8.1] repaired=chart_height_chain 注入 min-h-0 %d 处",+ count_1,+ )++ result, count_2 = _inject_class_into_chart_wrappers(+ result,+ "flex-1",+ needs_inject=lambda tag: not bool(_FLEX_GROW_RE.search(tag)),+ )+ if count_2:+ logger.info(+ "[P8.1] repaired=chart_height_chain 注入 flex-1 %d 处",+ count_2,+ )++ return result++def _extract_backup_timestamp(path: str) -> str:match = re.search(r"_backup[/\\](\d+)[/\\]", path.replace("\\", "/"))return match.group(1) if match else ""@@ -2541,6 +2634,27 @@ _REWRITE_ACTIONS = {"若内容确实需要更多空间,将 `flex-col` 改为更少的子元素或改为 `flex-shrink-0` 自适应高度;""不得用绝对定位、负 margin 或 `overflow-hidden` 掩盖越界"),+ # 页面生成校验失败 reason → 定向重试补救动作+ "invalid_chart_height_chain": (+ "修复图表容器高度链:包含 chart div 的最近 flex-col 祖先容器"+ "必须带 flex-1 min-h-0(或 flex-[N] min-h-0),"+ "标准写法 div.flex-1.min-h-0.flex.flex-col > div#chart-1.w-full.h-full"+ ),+ "invalid_html": "输出完整合法 HTML 文档,须含闭合 </body></html>,禁止截断或夹杂解释文字",+ "invalid_dom": "修复 DOM:消除畸形片段,确保 <main> 位于 .ppt-slide 内",+ "unfilled_placeholders": "填完所有 {{...}} / PAGE_* 占位符,禁止残留未替换标记",+ "seed_not_modified": "必须基于预铺模板填入本页标题、正文与页脚,禁止原样返回 seed",+ "main_tag_changed": "禁止改动 <main> 开标签(class/属性);仅替换 main 内部 PAGE_CONTENT",+ "content_template_chrome_changed": (+ "禁止改动模板 chrome(<head>、header 结构、footer 结构);"+ "仅替换 PAGE_TITLE / PAGE_CONTENT / PAGE_FOOTER 三处占位内容"+ ),+ "empty_page_content": "在 main 内填入本页正文内容,禁止空的 PAGE_CONTENT",+ "page_content_unfilled": "将 {{PAGE_CONTENT}} 替换为本页实际 HTML 内容",+ "title_invalid": "将 PAGE_TITLE 替换为大纲中的真实标题,禁止占位敷衍文案",+ "footer_missing": "保留 footer 结构并填入 PAGE_FOOTER",+ "footer_invalid": "将 PAGE_FOOTER 替换为有效页脚文案,禁止占位敷衍文案",+ "llm_failed": "重新生成完整页面 HTML,确保输出可解析",}@@ -2554,6 +2668,18 @@ def _build_rewrite_hint(failed_items: list[str]) -> str:return "\n".join(lines)+def _build_page_gen_rewrite_hint(reason: str) -> str:+ """定向重试指引:按真实校验 reason 生成,避免一律导向图表高度链。"""+ reason = (reason or "").strip()+ if not reason:+ return (+ "上一轮生成的 HTML 校验失败。"+ "请对照模板填槽/DOM/图表高度链等校验规则修复后重试。"+ )+ body = _build_rewrite_hint([reason])+ return f"上一轮生成的 HTML 校验失败(reason={reason})。\n{body}"++def _extract_page_keywords(research_page: str) -> list[str]:if not research_page:return []@@ -3315,14 +3441,23 @@ class PageWorkerNode(PlanNode):)html = ""+ last_raw_html = ""+ last_fail_reason = ""attempt_count = min(max(gen_retry_round + 1, 1),_MAX_PAGE_GENERATION_ATTEMPTS,)for attempt in range(attempt_count):+ rewrite_hint = ""+ original_html = ""if attempt > 0:logger.info("[P8.1] 页面 %d 第 %d 轮生成重试", page_num, attempt + 1)- html = await self._generate_one(ctx)+ if last_raw_html or last_fail_reason:+ rewrite_hint = _build_page_gen_rewrite_hint(last_fail_reason)+ original_html = last_raw_html+ html, last_raw_html, last_fail_reason = await self._generate_one(+ ctx, rewrite_hint=rewrite_hint, original_html=original_html+ )if html:breakif not html:@@ -3463,11 +3598,16 @@ class PageWorkerNode(PlanNode):"""预设/custom agenda:官方模板预铺 + 仅填 {{}}。"""return await self._generate_structural_template_fill(ctx, "agenda")- async def _generate_content_template_fill(self, ctx: PageGenContext) -> str:- """预设四风格内容页:官方 content-template 预铺 + 仅填三处占位符。"""+ async def _generate_content_template_fill(+ self, ctx: PageGenContext, *, rewrite_hint: str = ""+ ) -> tuple[str, str, str]:+ """预设四风格内容页:官方 content-template 预铺 + 仅填三处占位符。++ 返回 (校验通过的 html 或空串, 最后一次产物 html 或空串, 失败 reason 或空串)。+ """if not ctx.pptx_root:logger.error("[P8.1] 内容页填槽缺少 pptx_root page=%d", ctx.page_num)- return ""+ return "", "", ""template_path = _resolve_style_page_template_path(ctx.pptx_root,@@ -3482,7 +3622,7 @@ class PageWorkerNode(PlanNode):ctx.style_id,template_path,)- return ""+ return "", "", ""try:result = await self.stream_llm_collect(@@ -3498,6 +3638,7 @@ class PageWorkerNode(PlanNode):designer_md_text=ctx.designer_md_text,user_query=ctx.user_query,total_pages=ctx.total_pages,+ rewrite_hint=rewrite_hint,),system_prompt=("你是 PPT 内容页模板填充师。只替换模板中的 PAGE_TITLE、PAGE_CONTENT、PAGE_FOOTER,"@@ -3510,7 +3651,7 @@ class PageWorkerNode(PlanNode):if isinstance(e, AbortError):raiselogger.warning("[P8.1] 内容页填槽 LLM 失败 page=%d: %s", ctx.page_num, e)- return ""+ return "", "", "llm_failed"html = _strip_html_fence(result or "")html = _replace_placeholder_headings(html, ctx.outline_page)@@ -3524,6 +3665,7 @@ class PageWorkerNode(PlanNode):html = _fix_echarts_svg_renderer(html)html = _strip_unsupported_fullpage_overlays(html)html = _strip_chart_header_unit(html)+ html = _fix_chart_height_chain(html)ok, reason = _validate_content_template_fill_output(seed_html, html)if not ok:logger.warning(@@ -3532,21 +3674,29 @@ class PageWorkerNode(PlanNode):ctx.style_id,reason,)- return ""+ return "", html, reasonlogger.info("[P8.1] 内容页官方模板填槽完成 page=%d style=%s",ctx.page_num,ctx.style_id,)- return html+ return html, "", ""++ async def _generate_one(+ self, ctx: PageGenContext, *, rewrite_hint: str = "", original_html: str = ""+ ) -> tuple[str, str, str]:+ """生成单页 HTML,返回 (校验通过的 html 或空串, 最后一次产物 html 或空串, 失败 reason 或空串)。- async def _generate_one(self, ctx: PageGenContext) -> str:- """生成单页 HTML,返回校验通过的 html 或空串。"""+ rewrite_hint / original_html 非空时,prompt 中追加重写指引,用于定向重试。+ """page_type = _detect_page_type(ctx.outline_page)if _uses_structural_template_fill(ctx.style_id, page_type):- return await self._generate_structural_template_fill(ctx, page_type)+ filled = await self._generate_structural_template_fill(ctx, page_type)+ return (filled or "", "", "")if _uses_content_template_fill(ctx.style_id, page_type, ctx.outline_page):- return await self._generate_content_template_fill(ctx)+ return await self._generate_content_template_fill(+ ctx, rewrite_hint=rewrite_hint+ )try:result = await self.stream_llm_collect(@@ -3562,6 +3712,8 @@ class PageWorkerNode(PlanNode):designer_md_text=ctx.designer_md_text,user_query=ctx.user_query,total_pages=ctx.total_pages,+ rewrite_hint=rewrite_hint,+ original_html=original_html,),system_prompt="你是资深演示文稿设计师,直接输出完整 HTML 原文,不输出任何解释。",node_name=f"p8_1_page_{ctx.page_num}",@@ -3571,11 +3723,11 @@ class PageWorkerNode(PlanNode):if isinstance(e, AbortError):raiselogger.warning("[P8.1] 页面 %d 生成 LLM 失败: %s", ctx.page_num, e)- return ""+ return "", "", "llm_failed"html = _strip_html_fence(result or "")if not _is_valid_html(html):logger.warning("[P8.1] 页面 %d HTML 校验失败", ctx.page_num)- return ""+ return "", html, "invalid_html"# 后置校验:替换「第X页」标题占位符为 outline 中的实际标题html = _replace_placeholder_headings(html, ctx.outline_page)html = _apply_visible_page_number_policy(@@ -3588,13 +3740,14 @@ class PageWorkerNode(PlanNode):html = _fix_echarts_svg_renderer(html)html = _strip_unsupported_fullpage_overlays(html)html = _strip_chart_header_unit(html)+ html = _fix_chart_height_chain(html)if not _validate_slide_dom(html):logger.warning("[P8.1] 页面 %d DOM 结构校验失败", ctx.page_num)- return ""+ return "", html, "invalid_dom"if not _validate_chart_height_chain(html):logger.warning("[P8.1] 页面 %d 图表容器高度链校验失败", ctx.page_num)- return ""- return html+ return "", html, "invalid_chart_height_chain"+ return html, "", ""async def _write_file(self, path: str, content: str) -> bool:if not self.has_tool("write_file"):diff --git a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/utils/bash_utils.py b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/utils/bash_utils.pyindex 5a5741cb6c..af919c545a 100644--- a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/utils/bash_utils.py+++ b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/utils/bash_utils.py@@ -1,6 +1,7 @@from __future__ import annotationsimport json+import refrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any@@ -20,6 +21,15 @@ class BashResult:raw: str+_EXIT_CODE_PREFIX_RE = re.compile(r"^Exit code (\d+)\n?", re.IGNORECASE)+++def _parse_exit_code_from_text(text: str) -> int | None:+ """从 ``Exit code N`` 文本前缀解析退出码。"""+ m = _EXIT_CODE_PREFIX_RE.match(text.strip())+ return int(m.group(1)) if m else None++def quote_path(path: str) -> str:normalized = path.replace('"', '\\"')return f'"{normalized}"'@@ -77,6 +87,11 @@ def parse_bash_payload(text: str) -> BashResult:if stripped.startswith("[ERROR]"):return BashResult(exit_code=1, stdout="", stderr=stripped, raw=text)+ parsed_exit = _parse_exit_code_from_text(stripped)+ if parsed_exit is not None:+ stdout = _EXIT_CODE_PREFIX_RE.sub("", stripped, count=1)+ return BashResult(exit_code=parsed_exit, stdout=stdout, stderr="", raw=text)+try:payload = json.loads(stripped)except json.JSONDecodeError:@@ -101,18 +116,25 @@ def _extract_bash_result(raw: Any) -> BashResult | None:此函数兼容多种嵌套结构,提取失败时返回 None 由调用方 fallback。"""data: dict[str, Any] | None = None+ success: bool | None = Noneif hasattr(raw, "data") and isinstance(raw.data, dict):data = raw.data+ if hasattr(raw, "success"):+ success = raw.successelif isinstance(raw, dict):if "data" in raw and isinstance(raw["data"], dict):data = raw["data"]+ success = raw.get("success")elif "result" in raw:inner = raw["result"]if hasattr(inner, "data") and isinstance(inner.data, dict):data = inner.data+ if hasattr(inner, "success"):+ success = inner.successelif isinstance(inner, dict) and "data" in inner and isinstance(inner["data"], dict):data = inner["data"]+ success = inner.get("success")if data is None:return None@@ -128,6 +150,12 @@ def _extract_bash_result(raw: Any) -> BashResult | None:stderr = str(data.get("stderr") or "")if exit_code == 0 and "[ERROR]" in stdout:exit_code = 1+ if exit_code == 0 and success is False:+ exit_code = 1+ if exit_code == 0 and stdout:+ parsed_exit = _parse_exit_code_from_text(stdout)+ if parsed_exit is not None:+ exit_code = parsed_exitreturn BashResult(exit_code=exit_code, stdout=stdout, stderr=stderr, raw=str(raw))