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(flash): 修复 Turbo 发现、交付收尾与产物后处理
qq_528784339ce0e9274f35
diff --git a/jiuwenswarm/agents/harness/flash/rails/flash_delivery_summary_rail.py b/jiuwenswarm/agents/harness/flash/rails/flash_delivery_summary_rail.pynew file mode 100644index 0000000000..f93eaff24c--- /dev/null+++ b/jiuwenswarm/agents/harness/flash/rails/flash_delivery_summary_rail.py@@ -0,0 +1,223 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Flash 在交付历史落盘、整批工具完成且任务明确结束后收尾。"""++from __future__ import annotations++import json+import logging+from contextvars import ContextVar+from dataclasses import dataclass, field+from typing import Any++from openjiuwen.core.foundation.llm import AssistantMessage+from openjiuwen.core.single_agent.rail.base import (+ AgentCallbackContext,+ ModelCallInputs,+ ToolCallInputs,+)++from jiuwenswarm.agents.harness.common.rails.stream_event_rail import (+ JiuSwarmStreamEventRail,+)+from jiuwenswarm.server.runtime.skill_turbo.rails.delivery_summary_rail import (+ SkillTurboDeliverySummaryRail,+ _is_tool_interrupt,+)+from jiuwenswarm.server.runtime.skill_turbo.skill_turbo_tools import (+ _PPT_DELIVERY_SUMMARY_POST_TOOL_HINT,+ clear_pending_ppt_delivery_summary,+ emit_pending_ppt_delivery_summary,+ set_pending_ppt_delivery_summary,+ take_pending_ppt_delivery_summary,+)++logger = logging.getLogger(__name__)++_TOOL_NAME = "skill_acceleration_exec"+_FINISH_PARAMETER = "finish_request"+_STATE_KEY = "flash_delivery_state"+_TOKEN_KEY = "flash_delivery_state_token"+_DELIVERY_HINT = (+ "\n\n[SYSTEM] This tool's delivery summary has already been sent to the user. "+ "Do not repeat this summary or resend this artifact. This completes only this "+ "tool's task, not necessarily the entire request. Continue any remaining "+ "artifacts or other tasks, using the tools actually provided. Call Turbo "+ "serially for separate artifacts; set finish_request=true only for the final "+ "delivery when no further work remains."+)+++@dataclass+class _DeliveryState:+ """一次请求内共享;并行工具继承同一对象,不保存到 rail 实例。"""++ pending: list[str] = field(default_factory=list)+ delivered: list[str] = field(default_factory=list)+ finish_call_id: str = ""+ completed_call_id: str = ""+ context: Any = None+ context_engine: Any = None+++_delivery_state: ContextVar[_DeliveryState | None] = ContextVar(+ "flash_delivery_state", default=None,+)+++class FlashDeliverySummaryRail(SkillTurboDeliverySummaryRail):+ """复用 Turbo 总结发送入口,仅 Flash 使用确定性收尾。"""++ # SDK priority 降序执行,先发 tool_result / 改写 HITL,再处理总结。+ priority = JiuSwarmStreamEventRail.priority - 1++ async def before_invoke(self, ctx: AgentCallbackContext) -> None:+ state = _DeliveryState()+ ctx.extra[_STATE_KEY] = state+ ctx.extra[_TOKEN_KEY] = _delivery_state.set(state)++ async def before_model_call(self, ctx: AgentCallbackContext) -> None:+ if not isinstance(ctx.inputs, ModelCallInputs):+ return+ # 只改本次模型输入副本,不改变公共 Turbo 的工具卡或调用签名。+ for index, tool in enumerate(ctx.inputs.tools or []):+ if tool.name != _TOOL_NAME:+ continue+ local_tool = tool.model_copy(deep=True)+ if not isinstance(local_tool.parameters, dict):+ continue+ properties = local_tool.parameters.setdefault("properties", {})+ properties[_FINISH_PARAMETER] = {+ "type": "boolean",+ "default": False,+ "description": (+ "Only set true when this delivery completes the ENTIRE user request, "+ "with no remaining artifact, edit, todo update, or other task. "+ "For multiple artifacts, call serially and keep false until the last "+ "delivery. Omitted/false means continue after this tool; do not repeat "+ "the delivery summary already sent by the system."+ ),+ }+ ctx.inputs.tools[index] = local_tool++ async def after_model_call(self, ctx: AgentCallbackContext) -> None:+ state = _delivery_state.get()+ if state is None or not isinstance(ctx.inputs, ModelCallInputs):+ return+ state.finish_call_id = ""+ state.completed_call_id = ""+ calls = getattr(ctx.inputs.response, "tool_calls", None) or []+ for call in calls:+ if call.name != _TOOL_NAME:+ continue+ finish = self._take_finish_parameter(call)+ # 混合批次不作整个请求已完成的推断;由模型继续处理其它结果。+ if finish and len(calls) == 1:+ state.finish_call_id = call.id++ @staticmethod+ def _take_finish_parameter(call: Any) -> bool:+ """在工具调用落入 SDK 历史和执行前剥离 Flash 专用参数。"""+ arguments = call.arguments+ if isinstance(arguments, str):+ try:+ arguments = json.loads(arguments)+ except (TypeError, ValueError):+ return False # 非法参数继续交给 SDK 的既有校验。+ if not isinstance(arguments, dict) or _FINISH_PARAMETER not in arguments:+ return False+ arguments = dict(arguments)+ finish = arguments.pop(_FINISH_PARAMETER) is True+ call.arguments = json.dumps(arguments, ensure_ascii=False)+ return finish++ async def after_tool_call(self, ctx: AgentCallbackContext) -> None:+ if not isinstance(ctx.inputs, ToolCallInputs):+ return+ tool_name = str(+ ctx.inputs.tool_name or getattr(ctx.inputs.tool_call, "name", "") or ""+ ).strip()+ if tool_name != _TOOL_NAME:+ return+ result = ctx.inputs.tool_result+ if (+ _is_tool_interrupt(ctx)+ or ctx.session is None+ or ctx.exception is not None+ ):+ clear_pending_ppt_delivery_summary()+ return+ result_failed = isinstance(result, dict) and result.get("success") is False+ if result_failed or getattr(result, "success", None) is False:+ clear_pending_ppt_delivery_summary()+ return++ # 既有发送接口只返回 bool;保留正文用于模型历史,再原样交回该接口。+ # 取出与回填之间没有 await,缓存仍是当前任务的 ContextVar。+ summary = take_pending_ppt_delivery_summary()+ if not summary:+ return+ set_pending_ppt_delivery_summary(summary)+ if not await emit_pending_ppt_delivery_summary(ctx.session):+ return+ self._scope_delivery_hint(ctx.inputs)++ state = _delivery_state.get()+ if state is not None:+ state.pending.append(summary)+ state.context = ctx.context+ state.context_engine = getattr(ctx.agent, "context_engine", None)+ state.completed_call_id = str(getattr(ctx.inputs.tool_call, "id", "") or "")++ @staticmethod+ def _scope_delivery_hint(inputs: ToolCallInputs) -> None:+ """共享停止提示只适用于当前产物,不能禁止同一请求的下一次交付。"""+ result = inputs.tool_result+ if not isinstance(result, dict):+ return+ content = result.get("result")+ if not isinstance(content, str):+ return+ for hint in _PPT_DELIVERY_SUMMARY_POST_TOOL_HINT.values():+ content = content.replace(hint, _DELIVERY_HINT)+ inputs.tool_result = {**result, "result": content}+ if inputs.tool_msg is not None:+ inputs.tool_msg = inputs.tool_msg.model_copy(update={"content": str(inputs.tool_result)})++ async def after_react_iteration(self, ctx: AgentCallbackContext) -> None:+ # 此时所有 ToolMessage 已追加,SDK 也已检查整批 HITL / workflow 中断。+ state = _delivery_state.get()+ if state is None or not await self._append_history(state):+ return+ if not state.finish_call_id or state.finish_call_id != state.completed_call_id:+ return+ if not ctx.close_steering_if_empty():+ return+ ctx.request_force_finish({+ "output": "\n\n".join(state.delivered), "result_type": "answer",+ })+ logger.info("[FlashDeliverySummaryRail] 全部任务交付完成,历史已追加,批次结束后收尾")++ async def after_invoke(self, ctx: AgentCallbackContext) -> None:+ state = ctx.extra.pop(_STATE_KEY, None)+ token = ctx.extra.pop(_TOKEN_KEY, None)+ try:+ # 中断不触发 after_react_iteration;保留已成功交付的其它工具总结。+ # DeepAgent 的 after_invoke 在外层,用请求内捕获的内层 context 写回。+ if state is not None and await self._append_history(state):+ if state.context_engine is not None:+ await state.context_engine.save_contexts(ctx.session)+ finally:+ if token is not None:+ _delivery_state.reset(token)++ @staticmethod+ async def _append_history(state: _DeliveryState) -> bool:+ if state.context is None or not state.pending:+ return False+ # 已交付工具的 ToolMessage 必须先写入;待审批工具沿用原生恢复/修复链。+ for summary in list(state.pending):+ await state.context.add_messages(AssistantMessage(content=summary))+ state.delivered.append(summary)+ state.pending.remove(summary)+ return Truediff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py b/jiuwenswarm/server/runtime/agent_adapter/interface_flash.pyindex 312501822a..fc97ad8c05 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py@@ -130,6 +130,7 @@ from jiuwenswarm.agents.harness.flash import (from jiuwenswarm.common.config import (get_evolution_review_trigger_enabled,get_skill_create_enabled,+ resolve_string_or_list_config,)from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (JiuWenSwarmDeepAdapter,@@ -154,6 +155,7 @@ from jiuwenswarm.agents.harness.common.rails.permissions.owner_scopes import ()logger = logging.getLogger(__name__)+_FLASH_TURBO_TOOL_NAME = "skill_acceleration_exec"class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):@@ -229,6 +231,10 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):"_runtime_prompt_rail","_response_prompt_rail","_stream_event_rail",+ # 普通工具导出也需触发产物扩展(水印等),独立于 todo / TaskPlan。+ "_flash_artifact_post_process_rail",+ # Turbo 工具会缓存交付总结;保留发送组件,启用仍由父类 Turbo 开关控制。+ "_skill_turbo_delivery_summary_rail","_task_planning_rail","_security_rail","_heartbeat_rail",@@ -688,7 +694,7 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):logger.error("[JiuWenSwarmDeepAdapter] 定时工具注册失败: %s", exc)def _build_progressive_tool_rail(self, config: dict[str, Any]) -> Any:- """Keep the two merged Flash tools visible to the model."""+ """Keep merged Flash tools and enabled Turbo visible to the model."""flash_config = copy.deepcopy(config) if isinstance(config, dict) else {}lazy_config = flash_config.setdefault("tool_lazy_load", {})if not isinstance(lazy_config, dict):@@ -710,6 +716,9 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):for name in ("web_flash", "cron_flash"):if name not in eager_tools:eager_tools.append(name)+ eager_tools = [name for name in eager_tools if name != _FLASH_TURBO_TOOL_NAME]+ if self._flash_turbo_enabled(flash_config):+ eager_tools.append(_FLASH_TURBO_TOOL_NAME)lazy_config["eager_tools"] = eager_toolsreturn super()._build_progressive_tool_rail(flash_config)@@ -767,15 +776,46 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):"""按 flash 白名单过滤后再实例化 rails.父类 ``_build_agent_rails`` 末尾调用本方法;先按 ``_FLASH_RAIL_KEEP`` 白名单- 裁剪 rail_infos,再委托父类 ``_instantiate_rails`` 逐个构建并挂载 standing rails。+ 裁剪 rail_infos,补充独立产物后处理,再委托父类逐个构建并挂载 standing rails。"""rail_infos = self._filter_rail_infos_by_keep(rail_infos)+ rail_infos.append(_RailBuildInfo(+ "_flash_artifact_post_process_rail",+ self._build_flash_artifact_post_process_rail,+ ))rails = super()._instantiate_rails(rail_infos, config_base)selection = self._build_flash_skill_selection_rail(config_base)if selection is not None:rails.extend((selection.load_rail, selection))return rails+ @staticmethod+ def _build_flash_artifact_post_process_rail():+ """复用独立产物后处理组件;Flash 不注入 Code 署名或任务生命周期。"""+ from jiuwenswarm.agents.harness.code.rails.coding_artifact_post_process_rail import (+ CodingArtifactPostProcessRail,+ )++ return CodingArtifactPostProcessRail(coauthor_header_enabled=False)++ def _build_skill_turbo_delivery_summary_rail(self) -> Any | None:+ """仅在 Turbo 开启时装配 Flash 专用的总结与收尾组件。"""+ try:+ config_base = get_config()+ react_config = config_base.get("react", {}) if isinstance(config_base, dict) else {}+ turbo_config = react_config.get("skill_turbo", {}) if isinstance(react_config, dict) else {}+ if not isinstance(turbo_config, dict) or not turbo_config.get("enabled", False):+ return None++ from jiuwenswarm.agents.harness.flash.rails.flash_delivery_summary_rail import (+ FlashDeliverySummaryRail,+ )++ return FlashDeliverySummaryRail()+ except Exception:+ logger.warning("[FlashAdapter] 创建 Turbo 总结组件失败", exc_info=True)+ return None+def _build_flash_skill_selection_rail(self, config_base: dict[str, Any]):"""Optional Flash-only extension; removing its package restores native skills."""try:@@ -1003,7 +1043,7 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):)async def _update_runtime_config(self, runtime_config: Any) -> None:- """每回合 super() 后修正统一 memory 卡的可见性。+ """每回合 super() 后刷新 Turbo 描述并修正统一 memory 卡的可见性。super() 的群聊块只认 stock 五件套(对 flash 全是 no-op),且其恢复分支会把 stock write_memory/edit_memory 加回 flash 会话(统一卡才是 flash 的@@ -1012,6 +1052,39 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):"""await super()._update_runtime_config(runtime_config)self._sync_unified_memory_tool_visibility()+ self._refresh_flash_turbo_description()++ @staticmethod+ def _flash_turbo_enabled(config: dict[str, Any]) -> bool:+ turbo = config.get("skill_turbo", {})+ return (+ isinstance(turbo, dict)+ and bool(turbo.get("enabled", False))+ and _FLASH_TURBO_TOOL_NAME not in resolve_string_or_list_config(+ config.get("disabled_tools")+ )+ )++ def _refresh_flash_turbo_description(self) -> None:+ """Reuse Turbo discovery after request env binding, before SDK snapshots.++ The shared helper caches scans by skill roots with a TTL. Calling it+ here once per request also precedes progressive-tool navigation caching.+ """+ if self._instance is None or not self._flash_turbo_enabled(self._config_cache):+ return+ card = self._instance.ability_manager.get(_FLASH_TURBO_TOOL_NAME)+ if card is None:+ return++ from jiuwenswarm.server.runtime.skill_turbo import skill_turbo_tools++ old_description = card.description+ names = skill_turbo_tools.refresh_skill_acceleration_description()+ # Update the live SDK card too, in case it was copied during registration.+ card.description = skill_turbo_tools.skill_turbo.card.description+ if card.description != old_description:+ logger.info("[FlashTurboDiscovery] supported_skills=%s", names)def _sync_unified_memory_tool_visibility(self) -> None:"""按 TOOL_PERMISSION_CONTEXT 调整统一 memory 工具的可见性/只读。@@ -1085,6 +1158,10 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):)for k, v in self._FLASH_REACT_OVERRIDE.items():base_react[k] = self._deep_merge_react_value(base_react.get(k), v)+ if self._flash_turbo_enabled(base_react):+ lazy_config = base_react.setdefault("tool_lazy_load", {})+ eager_tools = lazy_config.setdefault("eager_tools", [])+ eager_tools.append(_FLASH_TURBO_TOOL_NAME)# eager_tools 是整表替换(设计上 flash 须写全最终名单):部署配置过的# 自定义常驻工具会退到 deferred,这里把差异打出来,避免工具呈现变化# 不可观测。diff --git a/tests/unit_tests/agentserver/test_flash_artifact_post_process.py b/tests/unit_tests/agentserver/test_flash_artifact_post_process.pynew file mode 100644index 0000000000..c07d0872d5--- /dev/null+++ b/tests/unit_tests/agentserver/test_flash_artifact_post_process.py@@ -0,0 +1,232 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Flash ordinary export hooks without restoring TaskExecutionRail."""++from __future__ import annotations++import json+import logging+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import Mock+from uuid import uuid4++import pytest+from openjiuwen.core.foundation.llm import (+ AssistantMessage, ModelClientConfig, ModelRequestConfig, ToolCall,+)+from openjiuwen.core.foundation.llm.schema.message_chunk import AssistantMessageChunk+from openjiuwen.core.foundation.tool import Tool, ToolCard+from openjiuwen.core.runner import Runner+from openjiuwen.core.runner.callback.framework import AsyncCallbackFramework+from openjiuwen.core.session.agent import Session+from openjiuwen.core.single_agent.rail.base import ToolCallInputs+from openjiuwen.harness import create_deep_agent++from jiuwenswarm.agents.harness.code.rails.coding_artifact_post_process_rail import (+ CodingArtifactPostProcessRail,+)+from jiuwenswarm.agents.harness.common.tools.subagent_executor.context_vars import (+ reset_effective_request_workspace_dir, set_effective_request_workspace_dir,+)+from jiuwenswarm.extensions.hook_event import AgentServerHookEvents+from jiuwenswarm.extensions.registry import ExtensionRegistry+from jiuwenswarm.server.runtime.agent_adapter import interface_deep, interface_flash+from jiuwenswarm.server.runtime.agent_adapter.interface_flash import JiuwenSwarmFlashAdapter++_MARKER = "AI生成".encode()+++def _assemble_flash(monkeypatch, *, turbo_enabled=True):+ adapter = object.__new__(JiuwenSwarmFlashAdapter)+ config = adapter._apply_flash_react_override({"react": {+ "skill_turbo": {"enabled": turbo_enabled},+ }})+ monkeypatch.setattr(interface_deep, "get_config", lambda: config)+ monkeypatch.setattr(interface_flash, "get_config", lambda: config)+ adapter._model = adapter._instance = None+ adapter._config_cache = config["react"]+ adapter._config_base_cache = config+ adapter._instance_overrides = {}+ adapter._stream_event_rail = adapter._checkpointer = None+ # Keep the real parent assembly, Flash filtering and artifact builder.+ for name in dir(JiuwenSwarmFlashAdapter):+ if name.startswith("_build_") and name not in {+ "_build_agent_rails", "_build_flash_artifact_post_process_rail",+ }:+ monkeypatch.setattr(adapter, name, Mock(return_value=None))+ monkeypatch.setattr(interface_deep, "_build_context_processor_rail", lambda **_: None)+ monkeypatch.setattr(adapter, "_load_extra_rails_from_env", lambda: [])+ monkeypatch.setattr(adapter, "_bind_checkpointer_to_rails", lambda: None)+ monkeypatch.setattr(adapter, "_filesystem_rail_enabled_for_profile", lambda: False)+ monkeypatch.setattr(adapter, "_task_execution_rail_enabled", lambda: True)+ rails = adapter._build_agent_rails(config["react"], config, mode="flash")+ adapter._build_task_execution_rail.assert_not_called()+ adapter._build_skill_protocol_prompt_rail.assert_not_called()+ artifact_rails = [rail for rail in rails if isinstance(rail, CodingArtifactPostProcessRail)]+ assert artifact_rails == [adapter._flash_artifact_post_process_rail]+ assert not artifact_rails[0]._coauthor_header_enabled+ return adapter, rails+++def extension_registry(monkeypatch):+ registry = ExtensionRegistry(AsyncCallbackFramework(), {}, logging.getLogger(__name__))+ monkeypatch.setattr(ExtensionRegistry, "_instance", registry)+ return registry+++class _Tool(Tool):+ def __init__(self, name, action):+ super().__init__(ToolCard(name=name, description="Local test tool"))+ self.action = action++ async def invoke(self, inputs, **kwargs):+ return self.action(inputs)++ async def stream(self, inputs, **kwargs):+ yield await self.invoke(inputs, **kwargs)+++class _Model:+ def __init__(self):+ self.model_client_config = ModelClientConfig(+ client_provider="OpenAI", api_key="fake", api_base="https://fake.invalid",+ )+ self.model_config = ModelRequestConfig(model_name="fake")+ self.steps = iter(())++ def _reply(self):+ step = next(self.steps, None)+ if step is None:+ return AssistantMessage(content="已交付")+ name, args = step+ return AssistantMessage(content="", tool_calls=[ToolCall(+ id=uuid4().hex, type="function", name=name,+ arguments=json.dumps(args, ensure_ascii=False),+ )])++ async def invoke(self, messages, **kwargs):+ return self._reply()++ async def stream(self, messages, **kwargs):+ reply = self._reply()+ yield AssistantMessageChunk(content=reply.content, tool_calls=reply.tool_calls)++[email protected]("mode", ["invoke", "stream"])[email protected]("turbo_enabled", [True, False])[email protected]("extension_enabled", [True, False])+async def test_export_is_post_processed_before_send_and_reprocessed_after_edit(+ monkeypatch, tmp_path, extension_registry, mode, turbo_enabled, extension_enabled,+):+ _, rails = _assemble_flash(monkeypatch, turbo_enabled=turbo_enabled)+ events = []+ sent = []++ async def watermark(ctx):+ for path in ctx.artifact_paths:+ output = Path(path)+ # A local hook double; dispatch and detection are the real shared code.+ output.write_bytes(output.read_bytes() + _MARKER)+ events.append("watermark")++ if extension_enabled:+ extension_registry.register(AgentServerHookEvents.IMAGE_ARTIFACT_POST_PROCESS, watermark)++ def bash(args):+ events.append(args["command"])+ if args["command"] == "export":+ Path(args["path"]).write_bytes(b"new export")+ # Match the PPT converter's output (Chinese label and absolute path).+ return f"💾 保存 PPTX: {args['path']}\n"++ def send(args):+ assert args["tool_name"] == "send_file_to_user"+ output = Path(args["arguments"]["abs_file_path_list"][0])+ assert output.read_bytes().count(_MARKER) == int(extension_enabled)+ sent.append(output)+ events.append("send")+ return {"success": True, "result": "sent"}++ monkeypatch.setattr("openjiuwen.harness.deep_agent.schedule_image_support_probe", lambda *_: None)+ model = _Model()+ await Runner.start()+ core = create_deep_agent(+ model=model, tools=[_Tool("bash", bash), _Tool("invoke_tool", send)],+ rails=rails, system_prompt="Test", enable_task_loop=False,+ max_iterations=5, workspace=str(tmp_path),+ )+ token = set_effective_request_workspace_dir(str(tmp_path))+ session_id = f"flash-artifact-{uuid4().hex}"+ try:+ await core._ensure_initialized()+ # New version, followed by an overwrite of the same path in a later turn.+ for filename in ("销售复盘.pptx", "销售复盘_v2.pptx", "销售复盘_v2.pptx"):+ path = tmp_path / filename+ events.clear()+ model.steps = iter([+ ("bash", {"command": "export", "path": str(path)}),+ ("bash", {"command": "inspect", "path": str(path)}),+ ("invoke_tool", {"tool_name": "send_file_to_user", "arguments": {+ "abs_file_path_list": [str(path)],+ }}),+ ])+ session = Session(session_id=session_id, card=core.card)+ await session.pre_run(inputs={"query": "修改并发送 PPT"})+ if mode == "stream":+ _ = [chunk async for chunk in core.stream({"query": "修改并发送 PPT"}, session=session)]+ else:+ await core.invoke({"query": "修改并发送 PPT"}, session=session)+ await session.post_run()+ expected = ["export", "watermark", "inspect", "send"] if extension_enabled else [+ "export", "inspect", "send",+ ]+ assert events == expected+ assert len(sent) == 3+ finally:+ reset_effective_request_workspace_dir(token)+ await core.stop()+++async def test_hello_and_turbo_outer_result_do_not_scan_or_post_process(monkeypatch, tmp_path):+ _, rails = _assemble_flash(monkeypatch)+ rail = next(r for r in rails if isinstance(r, CodingArtifactPostProcessRail))+ detector = Mock(side_effect=AssertionError("must not detect artifacts"))+ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.code.rails.coding_artifact_post_process_rail.detect_artifact_paths",+ detector,+ )+ ctx = SimpleNamespace(session=SimpleNamespace(get_session_id=lambda: "flash"), inputs=None)+ await rail.before_invoke(ctx)+ for name in ("todo", "skill_acceleration_exec"):+ ctx.inputs = ToolCallInputs(+ tool_call=SimpleNamespace(id=uuid4().hex), tool_name=name,+ tool_args={}, tool_result={"path": str(tmp_path / "turbo.pptx")}, tool_msg=None,+ )+ await rail.before_tool_call(ctx)+ await rail.after_tool_call(ctx)+ detector.assert_not_called()+ assert rail._tool_start_times == {}+++def test_config_reload_keeps_artifact_instance_without_reregistering(monkeypatch):+ adapter, _ = _assemble_flash(monkeypatch)+ artifact = adapter._flash_artifact_post_process_rail+ for name in (+ "_skill_evolution_rail", "_ttse_rail", "_skill_rail", "_filesystem_rail",+ "_skill_credential_injection_rail", "_skill_active_state_rail", "_context_assemble_rail",+ "_context_processor_rail", "_memory_rail", "_avatar_rail", "_permission_rail",+ "_disabled_tools_rail",+ ):+ setattr(adapter, name, None)+ monkeypatch.setattr(adapter, "_update_permission_rail", Mock())+ # Exercise both real reload methods; unrelated builders return None.+ for enabled in (False, True):+ config = {"skill_turbo": {"enabled": enabled}}+ replacements, removed = adapter._get_current_agent_rails(config, {"react": config})+ assert artifact not in replacements+ assert artifact not in removed+ assert adapter._flash_artifact_post_process_rail is artifactdiff --git a/tests/unit_tests/agentserver/test_flash_turbo_discovery.py b/tests/unit_tests/agentserver/test_flash_turbo_discovery.pynew file mode 100644index 0000000000..da25c862cd--- /dev/null+++ b/tests/unit_tests/agentserver/test_flash_turbo_discovery.py@@ -0,0 +1,236 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Flash Turbo discovery through real rail assembly and SDK model input."""++from __future__ import annotations++import json+from contextlib import contextmanager+from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock+from uuid import uuid4++import pytest+from openjiuwen.core.foundation.llm import AssistantMessage, ModelClientConfig, ModelRequestConfig+from openjiuwen.core.foundation.llm.schema.message_chunk import AssistantMessageChunk+from openjiuwen.core.runner import Runner+from openjiuwen.core.session.agent import Session+from openjiuwen.harness import create_deep_agent++from jiuwenswarm.agents.harness.common.rails.progressive_tool_rail import ProgressiveToolRail+from jiuwenswarm.common import utils+from jiuwenswarm.common.local_env_config import bind_task_env_overlay, reset_task_env_overlay+from jiuwenswarm.server.runtime.agent_adapter import interface_deep, interface_flash+from jiuwenswarm.server.runtime.agent_adapter.interface_flash import JiuwenSwarmFlashAdapter+from jiuwenswarm.server.runtime.skill_turbo import skill_turbo_tools, turbo_package_loader++TURBO_TOOL_NAME = "skill_acceleration_exec"+++@contextmanager+def _skill_env(root=None):+ # Relay supplies these roots in the per-request env, not the process spawn env.+ token = bind_task_env_overlay(+ {} if root is None else {"JIUWENSWARM_SHARED_SKILLS_DIRS": str(root)}+ )+ try:+ yield+ finally:+ reset_task_env_overlay(token)+++def skill_roots(tmp_path, monkeypatch):+ empty = tmp_path / "relay-default-skills"+ empty.mkdir()+ shared = tmp_path / "office-claw-skills"+ turbo = shared / "pptx-craft" / "turbo"+ codes = turbo / "turbo_codes" / "ppt"+ codes.mkdir(parents=True)+ (codes / "ppt_gen_root.py").write_text("root = None\n", encoding="utf-8")+ (turbo / "meta.json").write_text(json.dumps({+ "external_name": "pptx-craft", "description": "生成 PPT", "match_keywords": ["ppt"],+ }), encoding="utf-8")+ monkeypatch.setattr(utils, "get_agent_skills_dir", lambda: empty)+ monkeypatch.setattr(skill_turbo_tools, "_entries_cache", {})+ monkeypatch.setattr(skill_turbo_tools, "_last_good_entries", {})+ monkeypatch.setattr(skill_turbo_tools.skill_turbo.card, "description", "")+ return empty, shared+++def _assemble_flash(monkeypatch, *, enabled=True, disabled=None, lazy=True):+ adapter = object.__new__(JiuwenSwarmFlashAdapter)+ config = adapter._apply_flash_react_override({"react": {+ "skill_turbo": {"enabled": enabled},+ "tool_lazy_load": {"enabled": lazy},+ "disabled_tools": disabled or [],+ }})+ monkeypatch.setattr(interface_deep, "get_config", lambda: config)+ monkeypatch.setattr(interface_flash, "get_config", lambda: config)+ adapter._model = adapter._instance = None+ adapter._config_cache = config["react"]+ adapter._config_base_cache = config+ adapter._instance_overrides = {}+ adapter._stream_event_rail = adapter._checkpointer = None+ adapter._skill_turbo_prompt_rail = None+ real_builders = {+ "_build_agent_rails", "_build_progressive_tool_rail",+ "_build_disabled_tools_rail",+ }+ for name in dir(JiuwenSwarmFlashAdapter):+ if name.startswith("_build_") and name not in real_builders:+ monkeypatch.setattr(adapter, name, Mock(return_value=None))+ monkeypatch.setattr(interface_deep, "_build_context_processor_rail", lambda **_: None)+ monkeypatch.setattr(adapter, "_load_extra_rails_from_env", lambda: [])+ monkeypatch.setattr(adapter, "_bind_checkpointer_to_rails", lambda: None)+ monkeypatch.setattr(adapter, "_filesystem_rail_enabled_for_profile", lambda: False)+ monkeypatch.setattr(adapter, "_task_execution_rail_enabled", lambda: True)+ monkeypatch.setattr(adapter, "_resolve_runtime_language", lambda: "cn")+ monkeypatch.setattr(adapter, "_tool_owner_id", lambda: "flash-discovery-" + uuid4().hex)+ monkeypatch.setattr(adapter, "_get_progressive_active_skill", lambda: None)+ # The parent prepares unrelated memory, model, and channel tools. Keep the+ # real Flash request hook and exercise its ordering before the real SDK.+ monkeypatch.setattr(interface_deep.JiuWenSwarmDeepAdapter, "_update_runtime_config", AsyncMock())+ monkeypatch.setattr(adapter, "_sync_unified_memory_tool_visibility", Mock())+ rails = adapter._build_agent_rails(config["react"], config, mode="flash")+ adapter._build_task_execution_rail.assert_not_called()+ adapter._build_skill_turbo_prompt_rail.assert_not_called()+ adapter._build_skill_protocol_prompt_rail.assert_not_called()+ return adapter, rails+++class _Model:+ def __init__(self):+ self.model_client_config = ModelClientConfig(+ client_provider="OpenAI", api_key="fake", api_base="https://fake.invalid",+ )+ self.model_config = ModelRequestConfig(model_name="fake")+ self.calls = []++ def _record(self, messages, kwargs):+ self.calls.append((list(messages), kwargs.get("tools") or []))++ async def invoke(self, messages, **kwargs):+ self._record(messages, kwargs)+ return AssistantMessage(content="完成测试")++ async def stream(self, messages, **kwargs):+ self._record(messages, kwargs)+ yield AssistantMessageChunk(content="完成测试")++[email protected]("mode", ["invoke", "stream"])[email protected]("lazy", [True, False])+async def test_relay_empty_prewarm_refreshes_before_first_real_model_call(+ monkeypatch, tmp_path, skill_roots, mode, lazy,+):+ _, shared = skill_roots+ with _skill_env():+ initial = skill_turbo_tools._build_tool_description()+ assert "当前内部支持:暂无" in initial+ skill_turbo_tools.skill_turbo.card.description = initial+ adapter, rails = _assemble_flash(monkeypatch, lazy=lazy)++ scans = Mock(wraps=turbo_package_loader.discover_external_turbo_skills)+ monkeypatch.setattr(turbo_package_loader, "discover_external_turbo_skills", scans)+ monkeypatch.setattr("openjiuwen.harness.deep_agent.schedule_image_support_probe", lambda *_: None)+ model = _Model()+ await Runner.start()+ core = create_deep_agent(+ model=model, tools=[], rails=rails, system_prompt="Test",+ enable_task_loop=False, max_iterations=2, workspace=str(tmp_path / "workspace"),+ )+ adapter._instance = core+ try:+ await core._ensure_initialized()+ # Real adapter registration follows the Turbo switch and shared tool registry.+ adapter._init_skill_turbo_tool()+ assert core.ability_manager.get(TURBO_TOOL_NAME) is not None+ for _ in range(2):+ session = Session(session_id=f"relay-flash-{uuid4().hex}", card=core.card)+ with _skill_env(shared):+ await adapter._update_runtime_config(SimpleNamespace(mode="flash"))+ await session.pre_run(inputs={"query": "制作销售复盘 PPT"})+ if mode == "stream":+ _ = [chunk async for chunk in core.stream(+ {"query": "制作销售复盘 PPT"}, session=session,+ )]+ else:+ await core.invoke({"query": "制作销售复盘 PPT"}, session=session)+ await session.post_run()+ assert len(model.calls) == 2+ for messages, tools in model.calls:+ cards = [tool for tool in tools if tool.name == TURBO_TOOL_NAME]+ assert len(cards) == 1+ assert "当前内部支持:pptx-craft" in cards[0].description+ assert "暂无" not in cards[0].description+ assert not any("当前内部支持:暂无" in str(message.content) for message in messages)+ # Do not bring back the full Turbo guide (with legacy todo names).+ assert not any("## 技能加速通道" in str(message.content) for message in messages)+ # The second request reuses the existing roots-keyed TTL cache.+ assert scans.call_count == 1+ finally:+ await core.stop()++[email protected]("enabled,disabled", [+ (False, []), (True, [TURBO_TOOL_NAME]), (True, TURBO_TOOL_NAME),+])+async def test_disabled_turbo_is_not_refreshed_or_exposed(+ monkeypatch, tmp_path, skill_roots, enabled, disabled,+):+ adapter, rails = _assemble_flash(monkeypatch, enabled=enabled, disabled=disabled)+ assert adapter._skill_turbo_prompt_rail is None+ progressive = next(rail for rail in rails if isinstance(rail, ProgressiveToolRail))+ assert TURBO_TOOL_NAME not in progressive.eager_tools+ refresh = Mock(wraps=skill_turbo_tools.refresh_skill_acceleration_description)+ monkeypatch.setattr(skill_turbo_tools, "refresh_skill_acceleration_description", refresh)+ monkeypatch.setattr("openjiuwen.harness.deep_agent.schedule_image_support_probe", lambda *_: None)+ model = _Model()+ await Runner.start()+ core = create_deep_agent(+ model=model, tools=[], rails=rails, system_prompt="Test",+ enable_task_loop=False, max_iterations=2, workspace=str(tmp_path / "workspace"),+ )+ adapter._instance = core+ try:+ await core._ensure_initialized()+ adapter._init_skill_turbo_tool()+ if not enabled:+ assert core.ability_manager.get(TURBO_TOOL_NAME) is None+ with _skill_env(skill_roots[1]):+ await adapter._update_runtime_config(SimpleNamespace(mode="flash"))+ session = Session(session_id=f"flash-off-{uuid4().hex}", card=core.card)+ await session.pre_run(inputs={"query": "制作 PPT"})+ await core.invoke({"query": "制作 PPT"}, session=session)+ await session.post_run()+ refresh.assert_not_called()+ assert model.calls+ for messages, tools in model.calls:+ assert TURBO_TOOL_NAME not in [tool.name for tool in tools]+ assert not any(TURBO_TOOL_NAME in str(message.content) for message in messages)+ finally:+ await core.stop()+++async def test_refresh_updates_a_copied_card_and_skips_missing_or_disabled_tool(+ monkeypatch, skill_roots,+):+ adapter, _ = _assemble_flash(monkeypatch)+ card = skill_turbo_tools.skill_turbo.card.model_copy(deep=True)+ card.description = "stale"+ adapter._instance = SimpleNamespace(ability_manager=SimpleNamespace(get=lambda _: card))+ with _skill_env(skill_roots[1]):+ await adapter._update_runtime_config(SimpleNamespace(mode="flash"))+ assert "当前内部支持:pptx-craft" in card.description+ refresh = Mock(side_effect=AssertionError("must not scan"))+ monkeypatch.setattr(skill_turbo_tools, "refresh_skill_acceleration_description", refresh)+ adapter._config_cache["skill_turbo"]["enabled"] = False+ await adapter._update_runtime_config(SimpleNamespace(mode="flash"))+ adapter._config_cache["skill_turbo"]["enabled"] = True+ adapter._instance.ability_manager.get = lambda _: None+ await adapter._update_runtime_config(SimpleNamespace(mode="flash"))+ refresh.assert_not_called()diff --git a/tests/unit_tests/server/runtime/skill_turbo/test_flash_delivery_summary.py b/tests/unit_tests/server/runtime/skill_turbo/test_flash_delivery_summary.pynew file mode 100644index 0000000000..0bb1346cac--- /dev/null+++ b/tests/unit_tests/server/runtime/skill_turbo/test_flash_delivery_summary.py@@ -0,0 +1,717 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""验证 Flash 实际装配及 SDK 回调链中的 Turbo 总结时序与恢复去重。"""++from __future__ import annotations++import asyncio+import json+from contextlib import asynccontextmanager+from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock+from uuid import uuid4++import pytest+from openjiuwen.core.foundation.llm import (+ AssistantMessage,+ ModelClientConfig,+ ModelRequestConfig,+ ToolCall,+ ToolMessage,+)+from openjiuwen.core.foundation.llm.schema.message_chunk import AssistantMessageChunk+from openjiuwen.core.foundation.tool import Tool, ToolCard+from openjiuwen.core.foundation.tool.schema import ToolInfo+from openjiuwen.core.runner import Runner+from openjiuwen.core.runner.callback import AbortError+from openjiuwen.core.session import InteractiveInput+from openjiuwen.core.session.agent import Session+from openjiuwen.core.session.stream.base import OutputSchema+from openjiuwen.core.single_agent.agent_callback_manager import AgentCallbackManager+from openjiuwen.core.single_agent.interrupt.exception import ToolInterruptException+from openjiuwen.core.single_agent.interrupt.response import InterruptRequest+from openjiuwen.core.single_agent.interrupt.state import (+ INTERRUPTION_KEY,+ RESUME_USER_INPUT_KEY,+ ToolInterruptionState,+)+from openjiuwen.core.single_agent.rail.base import (+ AgentCallbackContext,+ AgentCallbackEvent,+ AgentRail,+ ModelCallInputs,+ ToolCallInputs,+)+from openjiuwen.harness import create_deep_agent++from jiuwenswarm.agents.harness.common.rails.stream_event_rail import JiuSwarmStreamEventRail+from jiuwenswarm.agents.harness.flash.rails.flash_delivery_summary_rail import FlashDeliverySummaryRail+from jiuwenswarm.common.schema.agent import AgentRequest+from jiuwenswarm.common.schema.message import ReqMethod+from jiuwenswarm.server.runtime.agent_adapter import interface_deep, interface_flash+from jiuwenswarm.server.runtime.agent_adapter.interface_flash import JiuwenSwarmFlashAdapter+from jiuwenswarm.server.runtime.skill_turbo import skill_turbo_tools as turbo_tools+from jiuwenswarm.server.runtime.skill_turbo.rails.delivery_summary_rail import (+ SkillTurboDeliverySummaryRail,+)++_MARKER = "【PPT 交付总结】"+_SUMMARY = f"{_MARKER}\n已生成并交付测试 PPT。"+_TOOL = "skill_acceleration_exec"+++def _holder():+ return {+ "p10_delivery": {+ "info": {"send_file_status": "sent", "delivery_status": "ok"},+ "files": [{"path": "test.pptx"}],+ "delivery_summary": _SUMMARY,+ },+ }++[email protected](autouse=True)+def _summary_context(monkeypatch):+ # PPT 技能源在外部仓;这里只替换其标记常量,不替换缓存或发送实现。+ monkeypatch.setattr(turbo_tools, "_ppt_delivery_summary_start", lambda: _MARKER)+ turbo_tools.clear_pending_ppt_delivery_summary()+ turbo_tools.set_skill_turbo_hitl_tic(None)+ yield+ turbo_tools.clear_pending_ppt_delivery_summary()+ turbo_tools.set_skill_turbo_hitl_tic(None)+++def assemble_flash(monkeypatch):+ def assemble(enabled=True):+ config = {"react": {"skill_turbo": {"enabled": enabled}}}+ monkeypatch.setattr(interface_deep, "get_config", lambda: config)+ monkeypatch.setattr(interface_flash, "get_config", lambda: config)+ adapter = object.__new__(JiuwenSwarmFlashAdapter)+ adapter._model = adapter._instance = None+ adapter._config_cache = {}+ adapter._config_base_cache = config+ adapter._instance_overrides = {}+ adapter._skill_turbo_delivery_summary_rail = None++ # 保留真实的声明、Flash 过滤、组件构造和 enabled 门禁;隔离无关组件。+ real_builders = {+ "_build_agent_rails", "_build_stream_event_rail",+ "_build_skill_turbo_delivery_summary_rail",+ }+ for name in dir(JiuwenSwarmFlashAdapter):+ if name.startswith("_build_") and name not in real_builders:+ monkeypatch.setattr(adapter, name, Mock(return_value=None))+ monkeypatch.setattr(interface_deep, "_build_context_processor_rail", lambda **_: None)+ monkeypatch.setattr(adapter, "_load_extra_rails_from_env", lambda: [])+ monkeypatch.setattr(adapter, "_bind_checkpointer_to_rails", lambda: None)+ monkeypatch.setattr(adapter, "_filesystem_rail_enabled_for_profile", lambda: False)+ monkeypatch.setattr(adapter, "_task_execution_rail_enabled", lambda: True)+ rails = adapter._build_agent_rails(config["react"], config, mode="flash")+ adapter._build_task_execution_rail.assert_not_called()+ adapter._build_skill_turbo_prompt_rail.assert_not_called()+ adapter._build_skill_protocol_prompt_rail.assert_not_called()+ return adapter, rails++ return assemble+++class _Session:+ def __init__(self):+ self.events = []++ async def write_stream(self, output):+ self.events.append(output)++ async def post_run(self):+ pass+++@asynccontextmanager+async def _tool_context(rails, session):+ manager = AgentCallbackManager(f"flash-delivery-{uuid4().hex}")+ engine = SimpleNamespace(save_contexts=AsyncMock())+ agent = SimpleNamespace(agent_callback_manager=manager, context_engine=engine)+ # 故意反向注册,顺序必须由真实 SDK priority 决定,不能靠测试手工排序。+ for rail in reversed(rails):+ if isinstance(rail, (JiuSwarmStreamEventRail, SkillTurboDeliverySummaryRail)):+ await manager.register_rail(rail, agent)+ call = ToolCall(id="outer-ppt", type="function", name=_TOOL, arguments='{"finish_request": true}')+ messages = []++ async def add_messages(message):+ messages.append(message)++ ctx = AgentCallbackContext(+ agent=agent, session=session,+ inputs=ModelCallInputs(response=AssistantMessage(content="", tool_calls=[call])),+ context=SimpleNamespace(add_messages=add_messages, get_messages=lambda: messages),+ )+ flash_rail = next((r for r in rails if isinstance(r, FlashDeliverySummaryRail)), None)+ if flash_rail is not None:+ await flash_rail.before_invoke(ctx)+ await flash_rail.after_model_call(ctx)+ ctx.inputs = ToolCallInputs(tool_call=call, tool_name=_TOOL, tool_args={})+ try:+ yield ctx+ finally:+ if flash_rail is not None:+ await flash_rail.after_invoke(ctx)+ await manager.clear()++[email protected]("enabled", [True, False])+def test_flash_assembly_respects_turbo_switch(assemble_flash, enabled):+ adapter, rails = assemble_flash(enabled)+ summaries = [rail for rail in rails if isinstance(rail, SkillTurboDeliverySummaryRail)]+ assert len(summaries) == int(enabled)+ assert adapter._skill_turbo_delivery_summary_rail == (summaries[0] if enabled else None)+ assert sum(isinstance(rail, JiuSwarmStreamEventRail) for rail in rails) == 1+ if enabled:+ # Flash 的时序调整不能污染共享类或父类创建的实例。+ normal = interface_deep.JiuWenSwarmDeepAdapter._build_skill_turbo_delivery_summary_rail()+ assert normal.priority == SkillTurboDeliverySummaryRail.priority+ assert type(normal) is SkillTurboDeliverySummaryRail+ assert type(summaries[0]) is FlashDeliverySummaryRail+ assert summaries[0].priority < JiuSwarmStreamEventRail.priority+++async def test_flash_success_emits_summary_once_after_real_tool_result(assemble_flash):+ adapter, rails = assemble_flash()+ session = _Session()+ async with _tool_context(rails, session) as ctx:+ # 代表内部流水线已经投递文件;外层回调只应补总结,不应重复发文件。+ await session.write_stream(OutputSchema(type="chat.file", index=0, payload={"path": "test.pptx"}))+ ctx.inputs.tool_result = turbo_tools._wrap_skill_turbo_result(+ {"success": True, "result": "任务已完成"}, _holder(),+ )+ await ctx.fire(AgentCallbackEvent.AFTER_TOOL_CALL)+ assert [event.type for event in session.events] == ["chat.file", "tool_result", "llm_output"]+ assert session.events[-1].payload["content"] == _SUMMARY+ assert _SUMMARY not in session.events[-2].payload["tool_result"]["result"]+ assert not ctx.has_force_finish_request+ await ctx.context.add_messages(ToolMessage(content="已交付", tool_call_id="outer-ppt"))+ await ctx.fire(AgentCallbackEvent.AFTER_REACT_ITERATION)+ finish = ctx.consume_force_finish()+ assert finish.result == {"output": _SUMMARY, "result_type": "answer"}+ assert [message.role for message in ctx.context.get_messages()] == ["tool", "assistant"]+ assert ctx.context.get_messages()[-1].content == _SUMMARY+ # 缓存消费后,重复调用总结组件不能再投递同一份正文。+ await adapter._skill_turbo_delivery_summary_rail.after_tool_call(ctx)+ await ctx.fire(AgentCallbackEvent.AFTER_REACT_ITERATION)+ assert len(session.events) == 3+ assert not ctx.has_force_finish_request+ assert turbo_tools.take_pending_ppt_delivery_summary() == ""+++async def test_flash_failed_delivery_does_not_emit_success_summary(assemble_flash):+ _, rails = assemble_flash()+ session = _Session()+ async with _tool_context(rails, session) as ctx:+ turbo_tools.set_pending_ppt_delivery_summary(_SUMMARY)+ ctx.inputs.tool_result = turbo_tools._wrap_skill_turbo_result(+ {"success": False, "error": "PPT 文件发送失败"}, _holder(),+ )+ await ctx.fire(AgentCallbackEvent.AFTER_TOOL_CALL)+ assert [event.type for event in session.events] == ["tool_result"]+ assert session.events[0].payload["tool_result"]["success"] is False+ assert turbo_tools.take_pending_ppt_delivery_summary() == ""+ assert not ctx.has_force_finish_request++[email protected]("interrupt_kind", ["approval_exception", "hitl_result_marker"])+async def test_flash_pause_then_native_resume_emits_one_summary(assemble_flash, interrupt_kind):+ adapter, rails = assemble_flash()+ session = _Session()+ async with _tool_context(rails, session) as ctx:+ interrupt = ToolInterruptException(+ request=InterruptRequest(message="请确认 PPT 操作"),+ tool_call=SimpleNamespace(id="inner-approval", name="ask_user", arguments={}),+ )+ turbo_tools.set_pending_ppt_delivery_summary(_SUMMARY)+ if interrupt_kind == "approval_exception":+ ctx.exception = interrupt+ ctx.inputs.tool_result = {"success": False, "error": "等待审批"}+ else:+ ctx.inputs.tool_result = turbo_tools.build_skill_turbo_hitl_result(interrupt)+ await ctx.fire(AgentCallbackEvent.AFTER_TOOL_CALL)+ assert session.events == []+ assert not ctx.has_force_finish_request+ assert turbo_tools.take_pending_ppt_delivery_summary() == ""+ if interrupt_kind == "hitl_result_marker":+ assert isinstance(ctx.inputs.tool_result, ToolInterruptException)++ # 原生工具恢复成功仍走同一条 after_tool_call 链。+ ctx.exception = None+ ctx.inputs.tool_result = turbo_tools._wrap_skill_turbo_result(+ {"success": True, "result": "任务已完成"}, _holder(),+ )+ await ctx.fire(AgentCallbackEvent.AFTER_TOOL_CALL)+ assert [event.type for event in session.events] == ["tool_result", "llm_output"]+ assert session.events[-1].payload["content"] == _SUMMARY+ assert not ctx.has_force_finish_request+ await ctx.fire(AgentCallbackEvent.AFTER_REACT_ITERATION)+ assert ctx.consume_force_finish().result["output"] == _SUMMARY+ await adapter._skill_turbo_delivery_summary_rail.after_tool_call(ctx)+ assert len(session.events) == 2+ assert not ctx.has_force_finish_request+++async def test_flash_adapter_resume_keeps_existing_summary_single(monkeypatch, assemble_flash):+ adapter, rails = assemble_flash()+ assert adapter._skill_turbo_delivery_summary_rail is not None+ session = _Session()++ # 审批暂停先清残留,再进入绕过外层工具循环的 adapter resume 入口。+ async with _tool_context(rails, session) as ctx:+ turbo_tools.set_pending_ppt_delivery_summary(_SUMMARY)+ ctx.exception = ToolInterruptException(request=InterruptRequest(message="请确认"))+ await ctx.fire(AgentCallbackEvent.AFTER_TOOL_CALL)+ assert session.events == []++ class _Turbo:+ def __init__(self, _config):+ self.artifact_holder = _holder()++ async def resume_stream(self, **_kwargs):+ if False:+ yield None++ monkeypatch.setattr("jiuwenswarm.server.runtime.skill_turbo.agent.SkillTurbo", _Turbo)+ monkeypatch.setattr(adapter, "_clear_pending_skill_turbo_hitl", AsyncMock(return_value=False))+ monkeypatch.setattr(adapter, "_clear_skill_turbo_resume_ctx_via_isolated_session", AsyncMock())+ monkeypatch.setattr(interface_deep, "_skill_turbo_clear_resume_in_flight", AsyncMock())+ monkeypatch.setattr(adapter, "build_skill_turbo_config", lambda: {})+ monkeypatch.setattr(adapter, "_log_and_make_usage_summary_chunk", lambda **_: None)+ monkeypatch.setattr(adapter, "_complete_skill_turbo_outer_todo", AsyncMock(return_value=[]))+ request = AgentRequest(+ request_id="flash-resume", session_id="flash-session", channel_id="web",+ req_method=ReqMethod.CHAT_SEND,+ params={"source": "ask_user_interrupt", "answers": [{"question": "风格"}]},+ )+ stream = adapter._make_skill_turbo_resume_stream(+ request=request, inputs={}, session=session,+ resume_ctx={"plan_code": "test", "pending_tool_call_id": "outer-ppt", "inputs": {}},+ answers=[{"question": "风格", "selected_options": ["商务"]}],+ )+ chunks = [chunk async for chunk in stream]+ payloads = [chunk.payload for chunk in chunks if isinstance(chunk.payload, dict)]+ assert [p["content"] for p in payloads if p.get("event_type") == "chat.delta"] == [_SUMMARY]+ assert [p["content"] for p in payloads if p.get("event_type") == "chat.final"] == [""]+ assert chunks[-1].is_complete is True+ assert turbo_tools.take_pending_ppt_delivery_summary() == ""+ # resume 已输出终稿,之后即使收到外层收尾回调也不能再补一份。+ async with _tool_context(rails, session) as ctx:+ ctx.inputs.tool_result = {"success": True}+ await ctx.fire(AgentCallbackEvent.AFTER_TOOL_CALL)+ assert [event.type for event in session.events] == ["tool_result"]+ assert not ctx.has_force_finish_request+++async def test_flash_duplicate_resume_answer_does_not_start_another_delivery(monkeypatch, assemble_flash):+ adapter, _ = assemble_flash()+ adapter._instance = SimpleNamespace(card=object(), _loop_session=None)+ resume = Mock(side_effect=AssertionError("重复作答不得重新执行交付"))+ monkeypatch.setattr(adapter, "_make_skill_turbo_resume_stream", resume)+ session = SimpleNamespace(post_run=AsyncMock(), update_state=Mock())+ monkeypatch.setattr("openjiuwen.core.session.agent.create_agent_session", lambda **_: session)+ monkeypatch.setattr(interface_deep, "_skill_turbo_set_agent_id", lambda *_a, **_k: None)+ monkeypatch.setattr(interface_deep, "_skill_turbo_load_resume_ctx", AsyncMock(return_value={+ "pending_tool_call_id": "skill_turbo-tc-ask_user-1",+ "plan_code": "test", "resume_in_flight": True,+ }))+ request = AgentRequest(+ request_id="flash-duplicate", channel_id="web", session_id="flash-session",+ req_method=ReqMethod.CHAT_SEND, params={+ "source": "ask_user_interrupt", "request_id": "skill_turbo-tc-ask_user-1",+ "answers": [{"question": "风格", "selected_options": ["商务"]}],+ },+ )+ stream = await adapter._try_skill_turbo_resume(request, {})+ assert stream is not None+ chunks = [chunk async for chunk in stream]+ assert len(chunks) == 1 and chunks[0].is_complete and chunks[0].payload is None+ resume.assert_not_called()++[email protected]("case", ["empty", "invalid", "send_error", "no_session", "unrelated_tool"])+async def test_flash_does_not_finish_without_emitted_summary(assemble_flash, case):+ adapter, rails = assemble_flash()+ session = _Session() if case != "no_session" else None+ if case == "send_error":+ session.write_stream = AsyncMock(side_effect=OSError("写流失败"))+ async with _tool_context(rails, session) as ctx:+ turbo_tools.set_pending_ppt_delivery_summary(+ "" if case == "empty" else "非交付总结" if case == "invalid" else _SUMMARY,+ )+ if case == "unrelated_tool":+ ctx.inputs.tool_name = "web_search"+ await adapter._skill_turbo_delivery_summary_rail.after_tool_call(ctx)+ assert not ctx.has_force_finish_request+++async def test_shared_summary_rail_does_not_finish_normal_agent():+ rail = SkillTurboDeliverySummaryRail()+ session = _Session()+ async with _tool_context([rail], session) as ctx:+ turbo_tools.set_pending_ppt_delivery_summary(_SUMMARY)+ await ctx.fire(AgentCallbackEvent.AFTER_TOOL_CALL)+ assert [event.payload["content"] for event in session.events] == [_SUMMARY]+ assert not ctx.has_force_finish_request+++class _DeliveryTool(Tool):+ def __init__(self, delivery_status):+ super().__init__(ToolCard(name=_TOOL, description="测试 PPT 交付"))+ self.delivery_status = delivery_status+ self.calls = 0++ async def invoke(self, inputs, **kwargs):+ assert "finish_request" not in inputs+ self.calls += 1+ holder = _holder()+ holder["p10_delivery"]["info"]["delivery_status"] = self.delivery_status+ return turbo_tools._wrap_skill_turbo_result(+ {"success": True, "result": "任务已完成"}, holder,+ )++ async def stream(self, inputs, **kwargs):+ yield await self.invoke(inputs, **kwargs)+++class _DeliveryModel:+ def __init__(self, tool):+ self.model_client_config = ModelClientConfig(+ client_provider="OpenAI", api_key="fake", api_base="https://fake.invalid",+ )+ self.model_config = ModelRequestConfig(model_name="fake")+ self.tool = tool+ self.calls = []++ def _reply(self, messages):+ self.calls.append(list(messages))+ if self.tool.calls:+ # 修复前本轮会继续调模型,从而多输出这段文本。+ return AssistantMessage(content="模型后续回复")+ return AssistantMessage(content="", tool_calls=[+ ToolCall(id="outer-ppt", type="function", name=_TOOL, arguments='{"finish_request": true}'),+ ])++ async def invoke(self, messages, **kwargs):+ self._check_finish_schema(kwargs)+ return self._reply(messages)++ async def stream(self, messages, **kwargs):+ self._check_finish_schema(kwargs)+ message = self._reply(messages)+ yield AssistantMessageChunk(content=message.content, tool_calls=message.tool_calls)++ @staticmethod+ def _check_finish_schema(kwargs):+ tool = next(tool for tool in kwargs.get("tools", []) if tool.name == _TOOL)+ assert "finish_request" in tool.parameters.get("properties", {})++[email protected]("mode", ["stream", "invoke"])[email protected]("delivery_status", ["ok", "partial"])[email protected]("max_iterations", [1, 3])+async def test_flash_summary_finishes_real_sdk_loop_and_next_turn_still_works(+ assemble_flash, monkeypatch, tmp_path, mode, delivery_status, max_iterations,+):+ # 不发真实模型请求;禁掉与本测试无关的后台图片能力探测。+ monkeypatch.setattr("openjiuwen.harness.deep_agent.schedule_image_support_probe", lambda *_: None)+ adapter, rails = assemble_flash()+ rails = [r for r in rails if isinstance(r, (JiuSwarmStreamEventRail, SkillTurboDeliverySummaryRail))]+ tool = _DeliveryTool(delivery_status)+ model = _DeliveryModel(tool)+ await Runner.start()+ core = create_deep_agent(+ model=model, tools=[tool], rails=rails, system_prompt="Test",+ enable_task_loop=False, max_iterations=max_iterations, workspace=str(tmp_path),+ )+ session = Session(session_id=f"flash-finish-{uuid4().hex}", card=core.card)+ try:+ # Direct invoke/stream tests must not also start the interaction reader.+ await core._ensure_initialized()+ await session.pre_run(inputs={"query": "生成 PPT"})+ if mode == "stream":+ chunks = [chunk async for chunk in core.stream({"query": "生成 PPT"}, session=session)]+ events = [c for c in chunks if getattr(c, "type", None) in {"tool_result", "llm_output", "answer"}]+ assert [e.type for e in events] == ["tool_result", "llm_output", "answer"]+ assert events[1].payload["content"] == _SUMMARY+ # 用真实 adapter 转换结束帧,确认已有 delta 不会再成为一段正文。+ final = adapter._parse_stream_chunk(+ events[-1], _has_streamed_content=True, _streamed_text=_SUMMARY,+ )+ assert final == {"event_type": "chat.final", "content": ""}+ assert adapter._drain_final_content_to_deltas(+ final, segment_streamed_text=_SUMMARY, chunk_payload=events[-1].payload,+ ) == []+ else:+ result = await core.invoke({"query": "生成 PPT"}, session=session)+ assert result == {"output": _SUMMARY, "result_type": "answer"}+ assert len(model.calls) == 1+ assert tool.calls == 1++ # 同一实例与会话的下一轮必须继续调模型,不能残留结束信号。+ await session.post_run()+ session = Session(session_id=session.get_session_id(), card=core.card)+ await session.pre_run(inputs={"query": "继续聊天"})+ result = await core.invoke({"query": "继续聊天"}, session=session)+ assert result["output"] == "模型后续回复"+ assert len(model.calls) == 2+ assert tool.calls == 1+ assert any(getattr(message, "role", None) == "tool" for message in model.calls[-1])+ summaries = [message for message in model.calls[-1] if message.content == _SUMMARY]+ assert len(summaries) == 1 and summaries[0].role == "assistant"+ tool_index = next(i for i, message in enumerate(model.calls[-1]) if message.role == "tool")+ assert model.calls[-1].index(summaries[0]) > tool_index+ await session.post_run()+ finally:+ await core.stop()+++async def test_finish_parameter_only_changes_flash_model_input():+ rail = FlashDeliverySummaryRail()+ original = ToolInfo(name=_TOOL, parameters={"type": "object", "properties": {"query": {"type": "string"}}})+ other = ToolInfo(name="other", parameters={"type": "object"})+ ctx = AgentCallbackContext(agent=SimpleNamespace(), inputs=ModelCallInputs(tools=[original, other]))+ await rail.before_model_call(ctx)+ assert "finish_request" not in original.parameters.get("properties", {})+ assert ctx.inputs.tools[0].parameters.get("properties", {}).get("finish_request", {}).get("default") is False+ assert ctx.inputs.tools[1] is other++[email protected]("finish", [None, False, "true", 1])+async def test_missing_or_non_boolean_finish_flag_continues(assemble_flash, finish):+ _, rails = assemble_flash()+ rail = next(r for r in rails if isinstance(r, FlashDeliverySummaryRail))+ async with _tool_context(rails, _Session()) as ctx:+ tool_inputs = ctx.inputs+ args = {} if finish is None else {"finish_request": finish}+ tool_inputs.tool_call.arguments = json.dumps(args)+ ctx.inputs = ModelCallInputs(response=AssistantMessage(content="", tool_calls=[tool_inputs.tool_call]))+ await rail.after_model_call(ctx)+ ctx.inputs = tool_inputs+ turbo_tools.set_pending_ppt_delivery_summary(_SUMMARY)+ await rail.after_tool_call(ctx)+ await rail.after_react_iteration(ctx)+ assert not ctx.has_force_finish_request+ assert [m.content for m in ctx.context.get_messages()] == [_SUMMARY]+ assert "finish_request" not in json.loads(tool_inputs.tool_call.arguments)+++async def test_pending_steering_prevents_finish(assemble_flash):+ _, rails = assemble_flash()+ rail = next(r for r in rails if isinstance(r, FlashDeliverySummaryRail))+ async with _tool_context(rails, _Session()) as ctx:+ queue = asyncio.Queue()+ ctx.bind_steering_queue(queue)+ ctx.push_steering("再生成一份 PPT")+ turbo_tools.set_pending_ppt_delivery_summary(_SUMMARY)+ await rail.after_tool_call(ctx)+ await rail.after_react_iteration(ctx)+ assert not ctx.has_force_finish_request+ assert ctx.drain_steering() == ["再生成一份 PPT"]+++async def test_concurrent_requests_keep_separate_delivery_history(assemble_flash):+ _, rails = assemble_flash()+ rail = next(r for r in rails if isinstance(r, FlashDeliverySummaryRail))+ barrier = asyncio.Barrier(2)++ async def deliver(label):+ summary = f"{_SUMMARY}\n{label}"+ async with _tool_context([rail], _Session()) as ctx:+ turbo_tools.set_pending_ppt_delivery_summary(summary)+ await rail.after_tool_call(ctx)+ await barrier.wait()+ await rail.after_react_iteration(ctx)+ assert ctx.consume_force_finish().result.get("output") == summary+ assert [m.content for m in ctx.context.get_messages()] == [summary]++ await asyncio.gather(deliver("会话 A"), deliver("会话 B"))+++async def test_history_write_failure_cannot_finish_request(assemble_flash):+ _, rails = assemble_flash()+ rail = next(r for r in rails if isinstance(r, FlashDeliverySummaryRail))+ async with _tool_context(rails, _Session()) as ctx:+ turbo_tools.set_pending_ppt_delivery_summary(_SUMMARY)+ await rail.after_tool_call(ctx)+ add_messages = ctx.context.add_messages+ ctx.context.add_messages = AsyncMock(side_effect=OSError("历史保存失败"))+ with pytest.raises(OSError, match="历史保存失败"):+ await rail.after_react_iteration(ctx)+ assert not ctx.has_force_finish_request+ ctx.context.add_messages = add_messages+ await rail.after_react_iteration(ctx)+ assert ctx.consume_force_finish().result.get("output") == _SUMMARY+ assert [m.content for m in ctx.context.get_messages()] == [_SUMMARY]+++class _ApprovalTool(Tool):+ def __init__(self):+ super().__init__(ToolCard(name="approval_tool", description="测试审批中断"))++ async def invoke(self, inputs, **kwargs):+ return {"success": True}++ async def stream(self, inputs, **kwargs):+ yield await self.invoke(inputs, **kwargs)+++class _ApprovalRail(AgentRail):+ async def before_tool_call(self, ctx):+ if ctx.inputs.tool_name != "approval_tool" or ctx.extra.get(RESUME_USER_INPUT_KEY) is not None:+ return+ # 与 SDK InterruptRailBase 相同:AbortError 穿过 callback 框架,cause 进入 HITL。+ raise AbortError(+ reason="等待审批",+ cause=ToolInterruptException(+ request=InterruptRequest(message="请审批另一个操作"),+ tool_call=ctx.inputs.tool_call,+ ),+ )+++class _ScriptedDeliveryModel(_DeliveryModel):+ def __init__(self, tool, replies):+ super().__init__(tool)+ self.replies = iter(replies)++ def _reply(self, messages):+ self.calls.append(list(messages))+ return next(self.replies)+++def _ppt_call(call_id, finish):+ return ToolCall(+ id=call_id, type="function", name=_TOOL,+ arguments=json.dumps({"finish_request": finish}),+ )+++@asynccontextmanager+async def _real_delivery_agent(assemble_flash, monkeypatch, tmp_path, replies, extra_tools=(), extra_rails=()):+ monkeypatch.setattr("openjiuwen.harness.deep_agent.schedule_image_support_probe", lambda *_: None)+ _, rails = assemble_flash()+ rails = [r for r in rails if isinstance(r, (JiuSwarmStreamEventRail, SkillTurboDeliverySummaryRail))]+ rails.extend(extra_rails)+ tool = _DeliveryTool("ok")+ model = _ScriptedDeliveryModel(tool, replies)+ await Runner.start()+ core = create_deep_agent(+ model=model, tools=[tool, *extra_tools], rails=rails, system_prompt="Test",+ enable_task_loop=False, max_iterations=4, workspace=str(tmp_path),+ )+ session = Session(session_id=f"flash-review-{uuid4().hex}", card=core.card)+ try:+ await core._ensure_initialized()+ await session.pre_run(inputs={"query": "完成全部任务"})+ yield core, session, tool, model+ await session.post_run()+ finally:+ await core.stop()++[email protected]("mode", ["invoke", "stream"])[email protected]("approval_first", [False, True])+async def test_same_batch_approval_is_saved_with_delivered_summary(+ assemble_flash, monkeypatch, tmp_path, mode, approval_first,+):+ calls = [_ppt_call("ppt-1", True), ToolCall(id="approval-1", type="function", name="approval_tool", arguments="{}")]+ if approval_first:+ calls.reverse()+ replies = [AssistantMessage(content="", tool_calls=calls), AssistantMessage(content="审批后的操作已完成")]+ async with _real_delivery_agent(+ assemble_flash, monkeypatch, tmp_path, replies, [_ApprovalTool()], [_ApprovalRail()],+ ) as (core, session, tool, model):+ if mode == "invoke":+ result = await core.invoke({"query": "生成 PPT 并执行需要审批的操作"}, session=session)+ assert result.get("result_type") == "interrupt"+ else:+ chunks = [c async for c in core.stream({"query": "生成 PPT 并执行需要审批的操作"}, session=session)]+ assert not any(c.type == "answer" for c in chunks)+ assert sum(c.type == "llm_output" and c.payload.get("content") == _SUMMARY for c in chunks) == 1+ interrupt = session.get_state(INTERRUPTION_KEY)+ assert isinstance(interrupt, ToolInterruptionState)+ assert "approval-1" in interrupt.interrupted_tools+ assert len(model.calls) == 1 and tool.calls == 1+ # 重新从 session 持久化快照装载,不能只检查当前内存对象。+ context = await core._react_agent.context_engine.create_context(session=session)+ messages = context.get_messages()+ summary_index = next(i for i, message in enumerate(messages) if message.content == _SUMMARY)+ assert messages[summary_index].role == "assistant"+ assert sum(message.content == _SUMMARY for message in messages) == 1+ tool_indices = [i for i, message in enumerate(messages) if message.role == "tool"]+ assert len(tool_indices) == 1 and summary_index > max(tool_indices)+ assert messages[tool_indices[0]].tool_call_id == "ppt-1"+ # 恢复只执行被中断的工具,不能重发已完成的 PPT 或总结。+ answers = InteractiveInput()+ answers.update("approval-1", {"approved": True})+ result = await core.invoke(answers, session=session)+ assert result.get("result_type") == "answer"+ assert session.get_state(INTERRUPTION_KEY) is None+ assert tool.calls == 1+ assert sum(m.content == _SUMMARY for m in model.calls[-1]) == 1+ tool_messages = [m for m in model.calls[-1] if m.role == "tool"]+ assert {m.tool_call_id for m in tool_messages} == {"ppt-1", "approval-1"}++[email protected]("mode", ["invoke", "stream"])+async def test_two_serial_deliveries_finish_only_after_second(+ assemble_flash, monkeypatch, tmp_path, mode,+):+ replies = [+ AssistantMessage(content="", tool_calls=[_ppt_call("ppt-1", False)]),+ AssistantMessage(content="", tool_calls=[_ppt_call("ppt-2", True)]),+ ]+ async with _real_delivery_agent(+ assemble_flash, monkeypatch, tmp_path, replies,+ ) as (core, session, tool, model):+ if mode == "invoke":+ result = await core.invoke({"query": "串行生成两份 PPT"}, session=session)+ assert result.get("output") == f"{_SUMMARY}\n\n{_SUMMARY}"+ else:+ chunks = [c async for c in core.stream({"query": "串行生成两份 PPT"}, session=session)]+ events = [c for c in chunks if c.type in {"tool_result", "llm_output", "answer"}]+ assert [c.type for c in events] == ["tool_result", "llm_output", "tool_result", "llm_output", "answer"]+ assert tool.calls == 2 and len(model.calls) == 2+ assert sum(m.content == _SUMMARY for m in model.calls[-1]) == 1+ first_result = next(m.content for m in model.calls[-1] if m.role == "tool")+ assert "Continue any remaining" in first_result+ assert "todo_modify" not in first_result+ assert "禁止再调" not in first_result+ context = await core._react_agent.context_engine.create_context(session=session)+ assert sum(m.content == _SUMMARY for m in context.get_messages()) == 2+++async def test_delivery_does_not_truncate_followup_text_task(assemble_flash, monkeypatch, tmp_path):+ replies = [+ AssistantMessage(content="", tool_calls=[_ppt_call("ppt-1", False)]),+ AssistantMessage(content="这是用户另外要求的邮件草稿"),+ ]+ async with _real_delivery_agent(+ assemble_flash, monkeypatch, tmp_path, replies,+ ) as (core, session, tool, model):+ result = await core.invoke({"query": "生成 PPT,再写一封邮件"}, session=session)+ assert result.get("output") == "这是用户另外要求的邮件草稿"+ assert tool.calls == 1 and len(model.calls) == 2+ assert sum(m.content == _SUMMARY for m in model.calls[-1]) == 1