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:skillTurbo askuser恢复时,跳过已执行任务
Chenchong_RD66fc0e5724a0
diff --git a/jiuwenswarm/server/runtime/skill_turbo/agent.py b/jiuwenswarm/server/runtime/skill_turbo/agent.pyindex 5248feaeeb..edc89cbc8d 100644--- a/jiuwenswarm/server/runtime/skill_turbo/agent.py+++ b/jiuwenswarm/server/runtime/skill_turbo/agent.py@@ -115,9 +115,11 @@ class SkillTurbo:- 用户审批回复(``ConfirmPayload`` / dict / etc.)- 可选 ``task_states``:中断时任务快照,resume 复用同一套 ``task_id``- 二次执行时 ``SkillTurboExecutor`` 重放到同一 tool_call_id,将 ``user_input``- 注入 ctx.extra[RESUME_USER_INPUT_KEY],``PermissionInterruptRail`` 据此- 给出 approve / reject。+ 二次执行时 ``SkillTurboExecutor`` 从根节点重放;``task_states`` 中已+ ``completed`` 的二层 Stage 短路跳过真实执行(bash/LLM),仅从+ ``in_progress`` 节点起完整重入。重放到同一 tool_call_id 时将+ ``user_input`` 注入 ctx.extra[RESUME_USER_INPUT_KEY],+ ``PermissionInterruptRail`` 据此给出 approve / reject。"""self._executor.set_pending_resume(expected_tool_call_id=pending_tool_call_id,diff --git a/jiuwenswarm/server/runtime/skill_turbo/executor.py b/jiuwenswarm/server/runtime/skill_turbo/executor.pyindex 963ebbbc4f..57ac63521d 100644--- a/jiuwenswarm/server/runtime/skill_turbo/executor.py+++ b/jiuwenswarm/server/runtime/skill_turbo/executor.py@@ -385,7 +385,9 @@ class SkillTurboExecutor:# resume 模式下,adapter 在 run_stream 入口注入;executor 在 use_tool# 命中目标 tool_call_id 时一次性消费。self._pending_resume: dict[str, Any] | None = None-+ # HITL resume 重放:对 task_states 已 completed 的二层 stage 跳过真实执行+ self._resume_replay: bool = False+# 当前任务状态(用于跨协程共享当前 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]] = {}@@ -584,12 +586,15 @@ class SkillTurboExecutor:# 新一轮 SkillTurbo 执行:清除上轮残留的 node_artifacts,避免全新任务误复用旧产物。# holder 此时必为空(每次请求新建 Executor),清的是 session 中持久化的旧记录。- await self._clear_stale_node_artifacts()+ # HITL resume 重放时保留产物(执行跳过主要靠 resume inputs;清盘会误伤可复用记录)。+ if not self._resume_replay:+ await self._clear_stale_node_artifacts()logger.info(- "[SkillTurboExecutor] execute_plan_stream start plan_code_len=%s input_keys=%s",+ "[SkillTurboExecutor] execute_plan_stream start plan_code_len=%s input_keys=%s resume_replay=%s",len(plan_code),list(merged_inputs.keys()),+ self._resume_replay,)# plan.started 必须最先发出,前端依赖它创建本次规划流的根节点。yield self._make_plan_started_chunk(request_id, channel_id)@@ -763,6 +768,7 @@ class SkillTurboExecutor:await self._persist_node_artifacts(session)self._reset_execution_context(context_tokens)self._execution_inputs = {}+ self._resume_replay = Falseawait self._finish_trace(start)def _build_permission_rail(self) -> Any | None:@@ -1261,6 +1267,7 @@ class SkillTurboExecutor:"""if not expected_tool_call_id:return+ self._resume_replay = Trueself._pending_resume = {"expected_tool_call_id": expected_tool_call_id,"user_input": user_input,@@ -2571,6 +2578,36 @@ class SkillTurboExecutor:}events_queue.append(task_update_event)+ async def _should_skip_subplan_execute(+ self,+ subplan: PlanNode,+ inputs: dict[str, Any],+ ) -> bool:+ """HITL resume 重放时,跳过已 completed 的二层 Stage 真实执行。++ in_progress / pending 节点仍完整重入,以便命中同一 tool_call_id 注入 answers。+ """+ del inputs # 接口与 PlanNode 回调一致;跳过判定只依赖 task_states+ if not self._resume_replay:+ return False+ if subplan.depth != 1:+ return False+ task_states = self._live_task_states()+ if not task_states:+ return False+ found = self._find_task_state_by_plan_name(subplan.plan_name, task_states)+ if found is None:+ return False+ _task_id, task_state = found+ if task_state.get("status") != "completed":+ return False+ logger.info(+ "[SkillTurboExecutor] resume skip execute completed stage plan_name=%s task_id=%s",+ subplan.plan_name,+ _task_id,+ )+ return True+async def _before_subplan_execute(self, subplan: PlanNode, inputs: dict[str, Any]) -> None:@@ -2609,8 +2646,9 @@ class SkillTurboExecutor:timestamp = time.time()self._set_current_task_context(subplan, task_id, timestamp)- # HITL resume 会从根节点重放 plan。已 completed 的 stage 若再标成- # in_progress,会与快照里仍 in_progress 的中断 stage 同时“运行”。+ # HITL resume 会从根节点重放 plan:已 completed 的 stage 跳过真实执行+ # (见 ``_should_skip_subplan_execute``),此处仅跳过 task.start UI,+ # 避免与快照里仍 in_progress 的中断 stage 同时“运行”。if task_state.get("status") == "completed":logger.info("[SkillTurboExecutor] skip task.start for already-completed stage "@@ -3065,6 +3103,7 @@ class SkillTurboExecutor:log=self._log_from_node,before_subplan_execute=self._before_subplan_execute,after_subplan_execute=self._after_subplan_execute,+ should_skip_subplan_execute=self._should_skip_subplan_execute,)@staticmethoddiff --git a/jiuwenswarm/server/runtime/skill_turbo/plan_node.py b/jiuwenswarm/server/runtime/skill_turbo/plan_node.pyindex b8e103b203..17f6879089 100644--- a/jiuwenswarm/server/runtime/skill_turbo/plan_node.py+++ b/jiuwenswarm/server/runtime/skill_turbo/plan_node.py@@ -78,7 +78,11 @@ class PlanNode(ABC):self._after_subplan_execute: (Callable[[PlanNode, dict[str, Any], Any], Awaitable[None]] | None) = None-+ # HITL resume:已 completed 的二层 stage 短路跳过真实执行+ self._should_skip_subplan_execute: (+ Callable[[PlanNode, dict[str, Any]], Awaitable[bool]] | None+ ) = None+def _update_subplans_depth(self) -> None:"""递归更新所有子节点的深度。@@ -104,6 +108,9 @@ class PlanNode(ABC):log: Callable[[PlanNode, str, str, tuple[Any, ...]], None] | None = None,before_subplan_execute: Callable[[PlanNode, dict[str, Any]], Awaitable[None]] | None = None,after_subplan_execute: Callable[[PlanNode, dict[str, Any], Any], Awaitable[None]] | None = None,+ should_skip_subplan_execute: (+ Callable[[PlanNode, dict[str, Any]], Awaitable[bool]] | None+ ) = None,) -> None:self._has_tool_callback = has_toolself._call_tool_callback = use_tool@@ -115,6 +122,7 @@ class PlanNode(ABC):self._log_callback = logself._before_subplan_execute = before_subplan_executeself._after_subplan_execute = after_subplan_execute+ self._should_skip_subplan_execute = should_skip_subplan_executefor node in self.sub_plans:node.set_runtime_callbacks(has_tool=has_tool,@@ -127,6 +135,7 @@ class PlanNode(ABC):log=log,before_subplan_execute=before_subplan_execute,after_subplan_execute=after_subplan_execute,+ should_skip_subplan_execute=should_skip_subplan_execute,)def log(self, level: str, message: str, *args: Any) -> None:@@ -349,6 +358,31 @@ class PlanNode(ABC):async for chunk in self._fallback_stream_callback(self, inputs, e):yield chunk+ @staticmethod+ def _resume_skip_result(subplan: "PlanNode") -> dict[str, Any]:+ return {+ "node": subplan.plan_name,+ "status": "ok",+ "message": "resume skip completed stage",+ "skipped": True,+ "resume_skip": True,+ }++ async def _maybe_skip_subplan_execute(+ self,+ subplan: "PlanNode",+ inputs: dict[str, Any],+ ) -> dict[str, Any] | None:+ """若回调判定应跳过真实执行,触发 after 并返回 skip result;否则返回 None。"""+ if self._should_skip_subplan_execute is None:+ return None+ if not await self._should_skip_subplan_execute(subplan, inputs):+ return None+ result = self._resume_skip_result(subplan)+ if self._after_subplan_execute is not None:+ await self._after_subplan_execute(subplan, inputs, result)+ return result+async def execute_subplan(self, subplan: PlanNode, inputs: dict[str, Any]) -> Any:"""执行子节点,带有回调钩子。@@ -364,6 +398,10 @@ class PlanNode(ABC):if self._before_subplan_execute is not None:await self._before_subplan_execute(subplan, inputs)+ skipped = await self._maybe_skip_subplan_execute(subplan, inputs)+ if skipped is not None:+ return skipped+try:result = await subplan.run(inputs)@@ -453,6 +491,10 @@ class PlanNode(ABC):if self._before_subplan_execute is not None:await self._before_subplan_execute(subplan, inputs)+ skipped = await self._maybe_skip_subplan_execute(subplan, inputs)+ if skipped is not None:+ return+last_chunk: Any = Noneerror: Exception | None = Nonehitl_interrupt = Falsediff --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.pyindex e0b0b18fa7..22f0e76bf1 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@@ -29,16 +29,25 @@ _P3_SKIP_FIELDS = {}+_MERGE_SKIP_KEYS = frozenset(+ {+ "node",+ "status",+ "message",+ "content",+ "skipped",+ "resume_skip",+ }+)++def _merge_subplan_result(inputs: dict[str, Any], result: Any) -> None:if not isinstance(result, dict):return- inputs.update(- {- key: value- for key, value in result.items()- if key not in {"node", "status", "message", "content"}- }- )+ for key, value in result.items():+ if key in _MERGE_SKIP_KEYS:+ continue+ inputs[key] = valuedef _result_status(result: Any) -> str: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.pynew file mode 100644index 0000000000..eb9eac6afa--- /dev/null+++ b/tests/unit_tests/server/runtime/skill_turbo/test_resume_skip_completed.py@@ -0,0 +1,180 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""HITL resume: skip real execution of completed depth-1 stages."""++from __future__ import annotations++from typing import Any+from unittest.mock import MagicMock++import pytest++from jiuwenswarm.server.runtime.skill_turbo.executor import SkillTurboExecutor+from jiuwenswarm.server.runtime.skill_turbo.plan_node import PlanNode+from jiuwenswarm.server.runtime.skill_turbo.skill_codes.ppt.ppt_gen_root import (+ _merge_subplan_result,+)+++class _LeafNode(PlanNode):+ def __init__(self, plan_name: str, depth: int = 1) -> None:+ super().__init__(plan_name=plan_name, instruction=plan_name, sub_plans=[], depth=depth)+ self.run_calls = 0+ self.run_stream_calls = 0++ async def _execute(self, inputs: dict[str, Any]) -> Any:+ self.run_calls += 1+ return {"node": self.plan_name, "status": "ok", "ran": True}++ async def _execute_stream(self, inputs: dict[str, Any]):+ self.run_stream_calls += 1+ yield {"node": self.plan_name, "status": "ok", "ran": True}+++class TestPlanNodeResumeSkip:+ @pytest.mark.asyncio+ async def test_execute_subplan_skips_run_when_callback_true(self):+ parent = _LeafNode("root", depth=0)+ child = _LeafNode("p0_pipeline_init", depth=1)+ before_n = after_n = 0++ async def before(_sp: PlanNode, _inp: dict[str, Any]) -> None:+ nonlocal before_n+ before_n += 1++ async def after(_sp: PlanNode, _inp: dict[str, Any], result: Any) -> None:+ nonlocal after_n+ after_n += 1+ assert result.get("resume_skip") is True+ assert result.get("skipped") is True++ async def should_skip(_sp: PlanNode, _inp: dict[str, Any]) -> bool:+ return True++ parent.set_runtime_callbacks(+ before_subplan_execute=before,+ after_subplan_execute=after,+ should_skip_subplan_execute=should_skip,+ )++ result = await parent.execute_subplan(child, {})+ assert child.run_calls == 0+ assert before_n == 1 and after_n == 1+ assert result["resume_skip"] is True+ assert result["message"] == "resume skip completed stage"++ @pytest.mark.asyncio+ async def test_execute_subplan_stream_skips_run_stream(self):+ parent = _LeafNode("root", depth=0)+ child = _LeafNode("p1_intent_classify", depth=1)+ after_n = 0++ async def after(_sp: PlanNode, _inp: dict[str, Any], result: Any) -> None:+ nonlocal after_n+ after_n += 1+ assert result.get("resume_skip") is True++ async def should_skip(_sp: PlanNode, _inp: dict[str, Any]) -> bool:+ return True++ parent.set_runtime_callbacks(+ after_subplan_execute=after,+ should_skip_subplan_execute=should_skip,+ )++ chunks = [c async for c in parent.execute_subplan_stream(child, {})]+ assert chunks == []+ assert child.run_stream_calls == 0+ assert after_n == 1++ @pytest.mark.asyncio+ async def test_execute_subplan_runs_when_callback_false(self):+ parent = _LeafNode("root", depth=0)+ child = _LeafNode("p2_requirement_collect", depth=1)++ async def should_skip(_sp: PlanNode, _inp: dict[str, Any]) -> bool:+ return False++ parent.set_runtime_callbacks(should_skip_subplan_execute=should_skip)+ result = await parent.execute_subplan(child, {})+ assert child.run_calls == 1+ assert result.get("ran") is True+++def _make_executor() -> SkillTurboExecutor:+ env = MagicMock()+ env.config = {}+ env.skill_code_import_prefixes = (+ "jiuwenswarm.server.runtime.skill_turbo.skill_codes",+ )+ return SkillTurboExecutor(environment=env)+++class TestExecutorShouldSkipSubplanExecute:+ @pytest.mark.asyncio+ async def test_resume_skips_completed_depth1_only(self):+ ex = _make_executor()+ ex._resume_replay = True+ ex._task_states_holder = {+ "task_p0": {+ "task_id": "task_p0",+ "task_content": "p0_pipeline_init",+ "status": "completed",+ },+ "task_p1": {+ "task_id": "task_p1",+ "task_content": "p1_intent_classify",+ "status": "completed",+ },+ "task_p3": {+ "task_id": "task_p3",+ "task_content": "p3_document_parse",+ "status": "completed",+ },+ "task_p2": {+ "task_id": "task_p2",+ "task_content": "p2_requirement_collect",+ "status": "in_progress",+ },+ }++ p0 = _LeafNode("p0_pipeline_init", depth=1)+ p2 = _LeafNode("p2_requirement_collect", depth=1)+ deep = _LeafNode("p0_child", depth=2)++ assert await ex._should_skip_subplan_execute(p0, {}) is True+ assert await ex._should_skip_subplan_execute(p2, {}) is False+ assert await ex._should_skip_subplan_execute(deep, {}) is False++ @pytest.mark.asyncio+ async def test_non_resume_never_skips(self):+ ex = _make_executor()+ ex._resume_replay = False+ ex._task_states_holder = {+ "task_p0": {+ "task_id": "task_p0",+ "task_content": "p0_pipeline_init",+ "status": "completed",+ },+ }+ p0 = _LeafNode("p0_pipeline_init", depth=1)+ assert await ex._should_skip_subplan_execute(p0, {}) is False+++class TestMergeSubplanResultIgnoresSkipFields:+ def test_ignores_skipped_and_resume_skip(self):+ inputs: dict[str, Any] = {"query": "keep"}+ _merge_subplan_result(+ inputs,+ {+ "node": "p0_pipeline_init",+ "status": "ok",+ "message": "resume skip completed stage",+ "skipped": True,+ "resume_skip": True,+ "useful": 1,+ },+ )+ assert inputs == {"query": "keep", "useful": 1}+ assert "skipped" not in inputs+ assert "resume_skip" not in inputs