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(deepresearch): 停止-恢复闭环消费侧修复(竞速交付/阶段恢复/认领收紧/止损)
KevinLLLoveb833a69e3226
diff --git a/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py b/jiuwenswarm/agents/harness/common/rails/ask_user_rail.pyindex ecaca5c765..0c0fda739a 100644--- a/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py@@ -446,6 +446,26 @@ class StructuredAskUserRail(AskUserRail):"treating as skipped",exc,)+ # 修复点2:解析失败时用户原始输入不能凭空丢弃。用户回了纯文本+ # (如"继续")时把原文随 reject 文案注入 LLM 历史,模型得以+ # 知晓用户实际说了什么并据此推进,而不是当作"未答"处理。+ # 优先取 decode 后的文本(去掉意外 JSON 引号层),非 str 时+ # 回退到原始输入的字符串形式(覆盖 JSON 标量/数组/畸形对象)。+ if isinstance(decoded, str):+ raw_text = decoded.strip()+ elif isinstance(user_input, str):+ raw_text = user_input.strip()+ else:+ raw_text = ""+ if raw_text:+ return self.reject(+ tool_result=(+ "用户的回复未符合结构化问答格式,未提取到结构化答案。"+ f"用户回复原文:{raw_text}。"+ "请基于用户原话理解其意图并继续推进任务,"+ "不要重复发起相同提问。"+ )+ )return self.reject(tool_result=self._build_skipped_tool_result())machine_payload = response.to_dict(include_original_request=False)diff --git a/jiuwenswarm/agents/harness/common/rails/deepresearch_execution_rail.py b/jiuwenswarm/agents/harness/common/rails/deepresearch_execution_rail.pyindex d83d400100..ef10e6b40a 100644--- a/jiuwenswarm/agents/harness/common/rails/deepresearch_execution_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/deepresearch_execution_rail.py@@ -5,8 +5,11 @@from __future__ import annotationsimport copy+import json+import loggingfrom typing import Any, Mapping+from openjiuwen.core.foundation.llm import ToolMessagefrom openjiuwen.core.single_agent.interrupt.exception import ToolInterruptExceptionfrom openjiuwen.core.single_agent.interrupt.state import RESUME_USER_INPUT_KEYfrom openjiuwen.core.single_agent.rail.base import AgentCallbackContext, ToolCallInputs@@ -15,10 +18,15 @@ from openjiuwen.harness.rails.base import DeepAgentRailfrom openjiuwen.harness.rails.interrupt.ask_user_rail import AskUserRequestfrom jiuwenswarm.agents.harness.common.tools.deepresearch.execution import (+ _IN_FLIGHT_PHASES,+ _query_matches_stopped_claim,EXECUTION_SCHEMA,bind_deepresearch_execution_context,reset_deepresearch_execution_context,)+from jiuwenswarm.agents.harness.common.tools.deepresearch.tools import (+ _probe_resumable_checkpoint,+)from jiuwenswarm.common.schema.ask_user import ask_user_response_schemafrom jiuwenswarm.perf.context import (extract_session_id_from_callback,@@ -30,6 +38,8 @@ DEEPRESEARCH_EXECUTION_ALIAS_KEY = "deepresearch_execution_aliases"_TOKENS_KEY = "__deepresearch_execution_context_tokens__"_TOOL_NAME = "deepresearch_execute"+logger = logging.getLogger(__name__)+def _tool_name(ctx: AgentCallbackContext) -> str:if not isinstance(ctx.inputs, ToolCallInputs):@@ -87,6 +97,102 @@ def _workflow_id(session: Any, tool_call_id: str) -> str:return _load_aliases(session).get(tool_call_id, tool_call_id)+# 修复点3.2:error 相位入桥候选。取消转译的 stopped 写入(phase=new)+# 被同 revision 的 error 覆盖写吞掉时,旧 state 实际存有可恢复停止快照,+# error 候选仍可桥回复用。cancelled 是用户显式放弃的死终态,不入候选。+_BRIDGE_CANDIDATE_PHASES = _IN_FLIGHT_PHASES | {"new", "error"}+++def _tool_args(ctx: AgentCallbackContext) -> dict[str, Any]:+ if not isinstance(ctx.inputs, ToolCallInputs):+ return {}+ args = getattr(ctx.inputs.tool_call, "arguments", None)+ if isinstance(args, str):+ try:+ args = json.loads(args)+ except (TypeError, ValueError):+ return {}+ return dict(args) if isinstance(args, Mapping) else {}+++def _bridge_stale_workflow(+ session: Any,+ tool_call_id: str,+ states: Mapping[str, Mapping[str, Any]],+ query: str,+ conversation_id: str,+) -> str:+ """state miss 兜底桥:新 tool_call_id 桥回旧 workflow state。++ 硬中断(用户停止/进程被杀)会把 in-flight state 遗留在旧+ tool_call_id 下;模型重试换了新 tool_call_id 时 state 读不到,+ 昂贵研究会被全新重跑。这里过五守卫 + 探针门后写 alias 桥接+ 新旧 id,使本次调用复用旧 state 直通续跑。返回桥接到的+ workflow_id,未桥接返回空串。++ 守卫:① state miss(调用方保证);② 候选 phase ∈ in-flight ∪+ new ∪ error(wait_feedback/wait_outline 卡由交互卡 id 自带 alias,+ 不入候选;cancelled 是显式放弃的死终态,不入候选);③ query 与+ 停止认领同口径;④ 显式 conversation_id 不抢别的会话;⑤ 过滤后+ 唯一。探针门:in-flight 与 error 候选须存在优雅停止快照(in-flight+ 防活子进程交叉写坏;error 可能是子进程失败退出无快照可恢复)才桥;+ new 相位候选免门(停止终态已返回,子进程必已退出)。+ """+ if tool_call_id in states:+ return ""+ incoming_cid = str(conversation_id or "").strip()+ candidates: list[tuple[str, Mapping[str, Any], str]] = []+ for workflow_id, state in states.items():+ phase = str(state.get("phase") or "")+ if phase not in _BRIDGE_CANDIDATE_PHASES:+ continue+ if not _query_matches_stopped_claim(query, state):+ continue+ state_cid = str(state.get("conversation_id") or "").strip()+ if incoming_cid and incoming_cid != state_cid:+ continue+ candidates.append((workflow_id, state, phase))+ verified: list[tuple[str, Mapping[str, Any], str]] = []+ for workflow_id, state, phase in candidates:+ if phase != "new":+ state_cid = str(state.get("conversation_id") or "").strip()+ probe = _probe_resumable_checkpoint(state_cid) if state_cid else None+ if not (isinstance(probe, Mapping) and probe.get("stopped")):+ logger.warning(+ "[deepresearch_execution_rail] bridge rejected: "+ "candidate state has no stopped snapshot; "+ "tool_call_id=%s workflow_id=%s phase=%s",+ tool_call_id,+ workflow_id,+ phase,+ )+ continue+ verified.append((workflow_id, state, phase))+ if not verified:+ return ""+ if len(verified) > 1:+ logger.warning(+ "[deepresearch_execution_rail] bridge rejected: multiple "+ "candidate states; tool_call_id=%s candidates=%s",+ tool_call_id,+ sorted(workflow_id for workflow_id, _, _ in verified),+ )+ return ""+ workflow_id, state, phase = verified[0]+ aliases = _load_aliases(session)+ aliases[tool_call_id] = workflow_id+ _save_aliases(session, aliases)+ logger.info(+ "[deepresearch_execution_rail] bridged tool_call_id=%s to stale "+ "workflow_id=%s phase=%s conversation_id=%s",+ tool_call_id,+ workflow_id,+ phase,+ str(state.get("conversation_id") or ""),+ )+ return workflow_id++def _interaction_tool_call(tool_call: Any, interaction_id: str) -> Any:model_copy = getattr(tool_call, "model_copy", None)cloned = model_copy(deep=True) if callable(model_copy) else copy.deepcopy(tool_call)@@ -97,7 +203,23 @@ def _interaction_tool_call(tool_call: Any, interaction_id: str) -> Any:def _resume_input(ctx: AgentCallbackContext, tool_call_id: str) -> Any:value = getattr(ctx, "extra", {}).get(RESUME_USER_INPUT_KEY)if isinstance(value, InteractiveInput):- return value.user_inputs.get(tool_call_id)+ user_inputs = value.user_inputs+ if tool_call_id in user_inputs:+ return user_inputs[tool_call_id]+ # 键断裂兜底:作答可能挂在历史卡片 id 下(如优雅停止前子进程+ # 下发的 ask_user 卡)。恢复会话时 pending 中断调用通常只有本+ # 工具一个;若作答恰好唯一则取之,避免确认丢失被误判为无效+ # 结果("AskUser response must be an object")。+ if len(user_inputs) == 1:+ only_key = next(iter(user_inputs))+ logger.warning(+ "[deepresearch_execution_rail] resume key mismatch: "+ "expected=%s got=%s; using the only user input",+ tool_call_id,+ only_key,+ )+ return user_inputs[only_key]+ return Noneif isinstance(value, Mapping) and tool_call_id in value:return value[tool_call_id]return value@@ -137,6 +259,17 @@ class DeepResearchExecutionRail(DeepAgentRail):tool_call_id = _tool_call_id(ctx)workflow_id = _workflow_id(ctx.session, tool_call_id)states = _load_states(ctx.session)+ if workflow_id not in states:+ # state miss 兜底桥:硬中断丢失 conversation_id 后模型换新+ # tool_call_id 重试时,桥回旧 workflow state 直通续跑。+ args = _tool_args(ctx)+ workflow_id = _bridge_stale_workflow(+ ctx.session,+ tool_call_id,+ states,+ query=str(args.get("query") or ""),+ conversation_id=str(args.get("conversation_id") or ""),+ ) or workflow_iddef save_state(state: dict[str, Any]) -> None:current = _load_states(ctx.session)@@ -201,7 +334,49 @@ class DeepResearchExecutionRail(DeepAgentRail):interaction_id,),)- ctx.inputs.tool_msg = None+ # 修复点1a:interaction 占位 JSON 不再裸入 LLM 历史。tool_msg+ # 置 None 会回落到原始 result[1](完整占位 JSON,泄露内部+ # state/revision 等实现细节),改为面向模型的口径;TIE 改写+ # 保持不变,打断/恢复流程不受影响。tool_call_id 必须用原始+ # 调用 id,与 assistant 消息中的 tool_calls 对齐。+ ctx.inputs.tool_msg = ToolMessage(+ content=(+ "DeepResearch 已暂停并向用户发起结构化问答,正在等待"+ "用户答复。用户答复后本工具将自动恢复执行并返回后续"+ "结果;请勿代替用户作答,也无需重复调用本工具轮询进度。"+ ),+ tool_call_id=tool_call_id,+ )+ return++ if payload.get("kind") == "stopped":+ # 优雅停止:保留执行状态(execution 已把 phase 回落为 new 并+ # 保留 conversation_id),不弹终态清理;下一次调用凭 probe+ # 认领停止快照直通续跑。也不 force finish——外层请求正被+ # 用户停止,无需再产出回答。+ # 修复11:stopped 结果完整 JSON(含内部 state/revision 与+ # "请再次调用本工具恢复"邀请文案)不再裸入 LLM 历史——+ # 生产事故中模型读到该邀请后自主重启了已被用户停止的+ # 研究。改写为禁止自动重启的面向模型口径,且不含+ # conversation_id(切断模型拿 cid 直通重启的最短路径);+ # 用户明确要求继续时模型凭原主题 query 重调,修复9' 的+ # 扫库认领会自动认领停止快照。恢复入口双指引(2026-10-15+ # 19:52 回归实证:停止后新请求中 execute 被 ProgressiveToolRail+ # 过滤,单 execute 指引是死信,模型绕行 stream start 全新+ # 起跑丢快照——stream 侧已同口径扫库认领)。+ ctx.inputs.tool_msg = ToolMessage(+ content=(+ "DeepResearch 任务已被用户停止,执行进度已保存。"+ "请勿代替用户决定继续,也不要自动重新调用研究工具;"+ "仅当用户明确要求继续该研究时才恢复执行:优先再次"+ "调用 deepresearch_execute(传入原研究主题即可自动"+ "认领停止快照);若该工具当前不可见,可调用"+ " deepresearch_stream(action='start',传入原研究"+ "主题,同样会自动认领)。恢复将从停止处继续,已完成"+ "阶段不会重跑。"+ ),+ tool_call_id=tool_call_id,+ )returnstates.pop(workflow_id, None)diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.pyindex 19e7fe5b99..c3db754b62 100644--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py@@ -12,7 +12,7 @@ import timeimport uuidfrom contextvars import ContextVar, Tokenfrom dataclasses import dataclass-from typing import Any, Callable, Mapping+from typing import Any, Awaitable, Callable, Mappingfrom openjiuwen.core.foundation.tool import tool@@ -24,12 +24,15 @@ from jiuwenswarm.common.schema.ask_user import ()from jiuwenswarm.perf.context import DeepResearchReportType-from .stream_router import _format_outline_card_markdown+from .stream_router import _format_outline_card_markdown, stage_for_resume_nodefrom .tools import (_call_deepresearch_stream_impl,+ _deepresearch_stage_hint_ctx,_get_cached_outline_json,_get_route,_probe_resumable_checkpoint,+ _scan_resumable_checkpoint_by_query,+ salvage_deepresearch_report,)from .usage import normalize_workflow_llm_token_usage@@ -37,7 +40,9 @@ logger = logging.getLogger(__name__)EXECUTION_SCHEMA = "openjiuwen.deepresearch.execute.v1"_STATE_SCHEMA_VERSION = 1-_IN_FLIGHT_PHASES = frozenset({"starting", "resuming_feedback", "resuming_outline"})+_IN_FLIGHT_PHASES = frozenset(+ {"starting", "resuming_feedback", "resuming_outline", "resuming_stopped"}+)_QUESTION_NUMBER_PREFIX = re.compile(r"^\s*\d+[.、)]\s*")_OUTLINE_SECTION = re.compile(r"^\s*###\s+P\d+\s*:\s*(.+?)\s*$", re.MULTILINE)_JSON_FENCE = re.compile(r"^\s*```(?:json)?\s*(.*?)\s*```\s*$", re.DOTALL | re.IGNORECASE)@@ -753,6 +758,41 @@ def _terminal_error()+def _stopped_result(+ context: DeepResearchExecutionContext,+ state: Mapping[str, Any],+ conversation_id: str,+) -> dict[str, Any]:+ """优雅停止终态:phase 回落 new 并保留 conversation_id。++ 下一次调用可凭 probe/扫库认领停止快照直通 resume node='stopped',+ 已完成节点不重跑。修复11:文案禁止模型在用户停止后自主重启+ (仅用户明确要求继续时才重调,凭原主题 query 即可被修复9' 的+ 扫库认领接住);content 不含 conversation_id(与 rail 改写口径+ 对齐——cid 是模型直通重启的最短路径,rail 挂载与否不应影响+ 该防线;认领与恢复靠 query + 归属守卫,cid 的功能载体是+ state 而非 content 文本)。恢复入口给双指引:execute 优先,+ 其不可见时(停止后新请求 skill 激活态重置,execute 被+ ProgressiveToolRail 过滤)回落 deepresearch_stream action='start'+ ——stream 侧已同口径扫库认领(2026-10-15 19:52 回归实证:单+ execute 指引是死信,模型绕行 stream 全新起跑丢快照)。+ """+ state = _persist(context, state, "new", conversation_id=conversation_id)+ return _result(+ "stopped",+ state,+ content=(+ "DeepResearch 任务已被用户停止,执行进度已保存。"+ "请勿代替用户决定继续,也不要自动重新调用本工具;仅当用户"+ "明确要求继续该研究时才恢复执行:优先再次调用 "+ "deepresearch_execute(传入原研究主题即可自动认领停止快照),"+ "若该工具当前不可见则调用 deepresearch_stream(action='start',"+ "传入原研究主题,同样会自动认领)。届时将从停止处恢复,已完成"+ "阶段不会重跑。"+ ),+ )++async def _handle_outcome(context: DeepResearchExecutionContext,state: dict[str, Any],@@ -884,9 +924,17 @@ async def _handle_outcome(if workflow_usage is not None:result_fields["workflow_llm_token_usage"] = workflow_usagereturn _result("completed", state, **result_fields)- if status == "cancelled":- state = _persist(context, state, "cancelled", conversation_id=conversation_id)- return _result("cancelled", state, content="DeepResearch 任务已取消。")+ if status in {"cancelled", "stopped"}:+ # 两种来源、同一处置——均按优雅停止口径收尾(phase 回落 new 并保留+ # conversation_id,下一次调用可凭 probe 认领停止快照直通 resume+ # node='stopped',已完成节点不重跑):+ # - stopped:子进程优雅停止终态,checkpoint 已落盘;+ # - cancelled:取消信号晚于子进程优雅退出的竞态变体(防御分支,+ # 现网 runner 已不下发 cancelled 终态帧),同样意味着 checkpoint+ # 已落盘,按可续跑处理可消除竞速路径产生歧义 cancelled 死终态的+ # 源头。此后存续的 cancelled 终态只剩用户在交互卡上显式放弃一种+ # 含义(走 phase 路径,不经过本分支)。+ return _stopped_result(context, state, conversation_id)error_code = str(outcome.get("error_code") or "deepresearch_failed")error = str(outcome.get("error") or "DeepResearch 执行失败。")diagnostics: dict[str, Any] = {}@@ -905,6 +953,124 @@ async def _handle_outcome()+async def _resume_stopped_conversation(+ context: DeepResearchExecutionContext,+ state: dict[str, Any],+ claimed_cid: str,+ probe_node: str = "",+) -> dict[str, Any]:+ """认领优雅停止快照后直通续跑:不弹任何交互卡。++ 旧会话被用户停止时 checkpoint 已保留执行进度,resume node='stopped'+ 从被停止的节点继续,已完成的节点不重跑。probe_node 为被停止节点+ (停止快照的 pending_node),据此推导前端进度条起始阶段,避免续跑时+ 进度列表回退到第一步误导用户以为从头重跑。+ """+ state = _persist(context, state, "resuming_stopped", conversation_id=claimed_cid)+ stage_hint = stage_for_resume_node(probe_node) if probe_node else None+ token = _deepresearch_stage_hint_ctx.set(stage_hint)+ try:+ outcome = await _call_sdk(+ context,+ action="resume",+ conversation_id=claimed_cid,+ node="stopped",+ file_name=str(state.get("file_name") or ""),+ report_type=state.get("requested_report_type"),+ )+ finally:+ _deepresearch_stage_hint_ctx.reset(token)+ return await _handle_outcome(+ context,+ state,+ outcome,+ action="resume",+ node="stopped",+ )+++async def _guard_user_stop(+ context: DeepResearchExecutionContext,+ state: Mapping[str, Any],+ awaitable: Awaitable[Any],+) -> Any:+ """工具级用户停止守卫(修复点1b)。++ 外部 task.cancel() 在工具 await 点注入 CancelledError 时,转译为+ stopped 业务终态(phase 回落 new 并保留 conversation_id):历史中+ 呈现可续跑口径并保留 checkpoint 认领能力,而不是落入 ability_manager+ 的通用 [Interrupted] 分支(拿不到 conversation_id,模型无从引导用户+ 续跑)。CancelledError 被吞掉后 ReAct 循环正常收敛;会话级取消仍由+ react_agent 的外部取消处理器兜底。+ """+ try:+ return await awaitable+ except asyncio.CancelledError:+ conversation_id = str(state.get("conversation_id") or "")+ logger.info(+ "[deepresearch_execute] cancelled by user, translating to "+ "stopped tool_call_id=%s conversation_id=%s",+ context.tool_call_id,+ conversation_id,+ )+ return _stopped_result(context, state, conversation_id)+++def _query_matches_stopped_claim(query: str, state: Mapping[str, Any]) -> bool:+ """停止快照认领守卫:入参 query 为空或与原研究主题一致才续跑。++ 用户已换研究主题时不认领旧停止会话,由调用方走全新会话。+ """+ incoming = str(query or "").strip()+ if not incoming:+ return True+ original = str(state.get("query") or "").strip()+ if not original:+ return True+ return incoming == original+++def _is_claimable_stopped_probe(+ probe: Mapping[str, Any] | None,+ query: str,+ state: Mapping[str, Any],+) -> bool:+ """停止快照可认领判定:probe 命中、处于 stopped、且研究主题未变。++ in-flight 与 error 两个相位入口共用(G.CTL.03 收敛四条件表达式)。+ """+ return bool(+ probe+ and probe.get("stopped")+ and _query_matches_stopped_claim(query, state)+ )+++async def _run_sdk_step(+ context: DeepResearchExecutionContext,+ state: dict[str, Any],+ *,+ action: str,+ node: str = "",+ **sdk_kwargs: Any,+) -> dict[str, Any]:+ """SDK 调用 + 结果处理的组合协程(修复点3.1:单守卫结构)。++ 调用方只在外层包一层 _guard_user_stop:取消无论落在 _call_sdk 窗口+ 还是 _handle_outcome 内部的选项生成段(唯一 await 点),都由同一+ 守卫转译为 stopped 终态,转译结果直接作为工具返回值返回。旧的双+ 守卫串联结构中,守卫#1 转译出的 stopped dict 不带 status 字段,+ 会被守卫#2 内的 _handle_outcome 误判为无效 outcome 落 error 相位,+ 与同一 revision 上的 new 写入形成双写竞争(生产日志同毫秒出现+ phase=new rev=4 与 phase=error rev=4 双写的根因)。+ """+ if node:+ sdk_kwargs = dict(sdk_kwargs)+ sdk_kwargs["node"] = node+ outcome = await _call_sdk(context, action=action, **sdk_kwargs)+ return await _handle_outcome(context, state, outcome, action=action, node=node)++@tool(name="deepresearch_execute",description=(@@ -917,7 +1083,13 @@ async def _handle_outcome("that was interrupted while waiting for outline review: when its ""generated outline is still cached, the outline review card is shown ""immediately and the original conversation is resumed after the user "- "answers, instead of restarting the research from scratch."+ "answers, instead of restarting the research from scratch. It also "+ "claims a conversation the user gracefully stopped: the run resumes "+ "from where it stopped without re-executing completed stages. After "+ "a user stop, never restart or resume the research on your own "+ "initiative; only call this tool again when the user explicitly "+ "asks to continue that stopped research, passing the original "+ "research query so the stopped snapshot is claimed automatically."),)async def deepresearch_execute(@@ -964,6 +1136,35 @@ async def deepresearch_execute()phase = str(state.get("phase") or "new")if phase in _IN_FLIGHT_PHASES:+ # 用户手动停止会使上次执行没有终态返回(CancelledError 直接冒泡,+ # state 停留在 in-flight 相位)。checkpointer 存在优雅停止快照且本次+ # 仍是同一研究主题时,认领直通续跑而不是报 execution_uncertain 拒绝。+ in_flight_cid = str(state.get("conversation_id") or "").strip()+ in_flight_probe = (+ _probe_resumable_checkpoint(in_flight_cid)+ if in_flight_cid+ else None+ )+ if in_flight_cid and _is_claimable_stopped_probe(+ in_flight_probe, query, state+ ):+ logger.info(+ "[deepresearch_execute] claimed stopped conversation from "+ "in-flight phase tool_call_id=%s phase=%s conversation_id=%s",+ context.tool_call_id,+ phase,+ in_flight_cid,+ )+ return await _guard_user_stop(+ context,+ state,+ _resume_stopped_conversation(+ context,+ state,+ in_flight_cid,+ probe_node=str(in_flight_probe.get("node") or ""),+ ),+ )return _terminal_error(context,state,@@ -973,25 +1174,160 @@ async def deepresearch_execute("本次未再次调用研究引擎。"),)- if phase in {"completed", "cancelled", "error"}:- kind = phase if phase != "error" else "error"- return _result(kind, state, content="DeepResearch 任务已经结束。")+ if phase in {"completed", "cancelled"}:+ return _result(phase, state, content="DeepResearch 任务已经结束。")+ if phase == "error":+ # 修复点3.2:error 相位 claim-or-fresh。3.1 修复前取消转译的+ # stopped 写入(phase=new)会被同一 revision 上的 error 覆盖写+ # 吞掉,error 相位下可能实际存有可恢复的停止快照。带+ # conversation_id 先 probe:有停止快照且研究主题未变则认领直通+ # 续跑(已完成节点不重跑);无快照才判死。completed/cancelled+ # 保持死终态不认领。+ error_cid = str(state.get("conversation_id") or "").strip()+ error_probe = (+ _probe_resumable_checkpoint(error_cid) if error_cid else None+ )+ if error_cid and _is_claimable_stopped_probe(error_probe, query, state):+ logger.info(+ "[deepresearch_execute] claimed stopped conversation from "+ "error phase tool_call_id=%s conversation_id=%s",+ context.tool_call_id,+ error_cid,+ )+ return await _guard_user_stop(+ context,+ state,+ _resume_stopped_conversation(+ context,+ state,+ error_cid,+ probe_node=str(error_probe.get("node") or ""),+ ),+ )+ # 修复7:error 相位死路(无可恢复快照)同样先尝试止损交付已落盘+ # 的报告(同主题追问场景),失败才判死。+ if error_cid and _query_matches_stopped_claim(query, state):+ salvage = await salvage_deepresearch_report(+ conversation_id=error_cid,+ file_name=str(state.get("file_name") or file_name),+ )+ if salvage is not None:+ state = _persist(+ context, state, "completed", conversation_id=error_cid+ )+ logger.info(+ "[deepresearch_execute] salvaged completed report from "+ "error phase tool_call_id=%s conversation_id=%s",+ context.tool_call_id,+ error_cid,+ )+ return _result(+ "completed",+ state,+ content=_completion_content(+ state, salvage.get("html_style_status")+ ),+ )+ return _result(+ "error",+ state,+ content="DeepResearch 任务已经结束,请重新发起。",+ )if phase == "new":claimed_cid = str(state.get("conversation_id") or "").strip()probe = (_probe_resumable_checkpoint(claimed_cid) if claimed_cid else None)+ if probe is None:+ # 修复9':LLM 传参 conversation_id 不可信(实机事故:两次幻觉+ # id 均在认领入口失效,probe 落空后直接全新起跑,丢弃已停止+ # 会话的全部研究成果)。cid 落空时不放弃认领——按本次研究+ # 主题扫库兜底:以快照 search_context.original_query 与本次+ # query 完全一致为认领条件(换主题不认领旧会话),rowid 倒序+ # 最新会话优先。命中后以扫出的 cid 重走下方 probe 认领分支+ # (含 stopped 直通续跑与交互卡重弹),认领仍失败时下方+ # salvage 止损也改用扫出的 cid 定位报告。+ scan_query = str(query or state.get("query") or "").strip()+ # 同步 SQLite 扫库经 to_thread 卸载,避免阻塞事件循环+ # (contextvar 经 copy_context 随线程传播,扫库内 _get_route+ # 归属校验线程内安全)。+ scan = (+ await asyncio.to_thread(+ _scan_resumable_checkpoint_by_query, scan_query+ )+ if scan_query+ else None+ )+ if scan is not None:+ scanned_cid = str(scan.get("conversation_id") or "")+ if scanned_cid and scanned_cid != claimed_cid:+ claimed_cid = scanned_cid+ probe = {+ key: value+ for key, value in scan.items()+ if key != "conversation_id"+ }+ incoming_query = str(query or "").strip()+ if incoming_query:+ # 扫库已确认快照主题与本次 query 完全一致;同步+ # 刷新 state.query,使下方认领分支的主题守卫+ # (_query_matches_stopped_claim)通过。+ state = dict(state, query=incoming_query)+ logger.info(+ "[deepresearch_execute] claimed conversation by "+ "query scan (llm conversation_id untrusted) "+ "tool_call_id=%s conversation_id=%s node=%s "+ "stopped=%s",+ context.tool_call_id,+ claimed_cid,+ probe.get("node"),+ bool(probe.get("stopped")),+ )probe_node = str(probe.get("node") or "") if probe else ""- if claimed_cid and probe_node == "feedback_handler":+ stopped_probe = bool(probe and probe.get("stopped"))+ if (+ claimed_cid+ and stopped_probe+ and _query_matches_stopped_claim(query, state)+ ):+ # 认领成功:旧会话被用户优雅停止(checkpoint 保留进度),不弹+ # 交互卡直通 resume node='stopped',从被停止节点继续,已完成+ # 节点不重跑。+ logger.info(+ "[deepresearch_execute] claimed stopped conversation "+ "tool_call_id=%s conversation_id=%s node=%s",+ context.tool_call_id,+ claimed_cid,+ probe_node,+ )+ return await _guard_user_stop(+ context,+ state,+ _resume_stopped_conversation(+ context,+ state,+ claimed_cid,+ probe_node=probe_node,+ ),+ )+ if (+ claimed_cid+ and not stopped_probe+ and probe_node == "feedback_handler"+ ):# 认领成功:旧会话停在研究问题确认阶段(含跨进程重启),从# checkpointer.db 恢复问题清单出反馈卡;用户答复后从原会话 resume。questions = _split_questions(probe.get("questions"))if questions:- options = await _generate_options(+ options = await _guard_user_stop(context,- str(state.get("query") or ""),- questions,+ state,+ _generate_options(+ context,+ str(state.get("query") or ""),+ questions,+ ),)cards = [{@@ -1026,19 +1362,36 @@ async def deepresearch_execute(claimed_outline = (probe.get("outline_json")if probe_node == "outline_interaction"+ and not stopped_probeelse None)+ claim_source = "db" if isinstance(claimed_outline, dict) else ""if not isinstance(claimed_outline, dict):- claimed_outline = (- _get_cached_outline_json(_get_route(), claimed_cid)- if claimed_cid- else {}- )+ # 修复5:缓存兜底仅在 DB 确认存在 outline_interaction 可恢复中断+ # 时启用(probe 命中但快照缺 outline_json 的场景)。probe 未命中+ # (会话已正常完结被清理/快照损坏/不存在)时一律不信内存缓存:+ # 事故中 probe=None 却用残留缓存大纲弹卡,用户确认后 resume 无+ # 快照可恢复而全新起跑,6 秒崩溃并删除该会话全部数据。+ if (+ claimed_cid+ and probe_node == "outline_interaction"+ and not stopped_probe+ ):+ cached_outline = _get_cached_outline_json(+ _get_route(), claimed_cid+ )+ if isinstance(cached_outline, dict):+ claimed_outline = cached_outline+ claim_source = "cache"+ else:+ # 停止快照未被认领(含换主题)时,缓存兜底同样不得复用旧会话+ # 大纲,否则会把旧主题的大纲弹给新研究。+ claimed_outline = {}claimed_sections = claimed_outline.get("sections")if claimed_cid and isinstance(claimed_sections, list) and claimed_sections:- # 认领成功:旧会话已生成大纲且停在大纲确认,直接复用 checkpointer.db- # (或内存缓存兜底)中的大纲出审阅卡片,跳过 start 重跑;用户答复后- # 从原会话 resume。+ # 认领成功:旧会话已生成大纲且停在大纲确认(DB 快照或其缓存+ # 兜底),复用大纲出审阅卡片,跳过 start 重跑;用户答复后从原+ # 会话 resume。outline_text = (_format_outline_card_markdown(claimed_outline)or "大纲已生成,请确认是否继续研究。"@@ -1053,9 +1406,11 @@ async def deepresearch_execute()logger.info("[deepresearch_execute] claimed interrupted conversation "- "tool_call_id=%s conversation_id=%s node=outline_interaction",+ "tool_call_id=%s conversation_id=%s node=outline_interaction "+ "source=%s",context.tool_call_id,claimed_cid,+ claim_source or "db",)return _result("interaction",@@ -1063,23 +1418,74 @@ async def deepresearch_execute(interaction=_outline_review_interaction(outline_text),)if claimed_cid:+ # 修复7:认领失败先止损——报告若已随此前运行落盘(收尾阶段被+ # 停/交付前崩溃后快照已清理),且用户仍在追问同一主题,直接+ # 交付已有报告,不重跑研究。+ if _query_matches_stopped_claim(query, state):+ salvage = await salvage_deepresearch_report(+ conversation_id=claimed_cid,+ file_name=str(state.get("file_name") or file_name),+ )+ if salvage is not None:+ state = _persist(+ context, state, "completed", conversation_id=claimed_cid+ )+ logger.info(+ "[deepresearch_execute] salvaged completed report "+ "tool_call_id=%s conversation_id=%s",+ context.tool_call_id,+ claimed_cid,+ )+ return _result(+ "completed",+ state,+ content=_completion_content(+ state, salvage.get("html_style_status")+ ),+ )# 认领失败:checkpointer.db 与内存缓存均无该会话可恢复的中断状态- # (已完结/已清理/不存在),绝不复用中断会话的 id 发起新跑,换成- # 全新 id 从头执行。+ # (已完结/已清理/不存在),或旧会话为停止快照但用户已更换主题;+ # 绝不复用旧会话的 id 发起新跑,换成全新 id 从头执行。换主题时+ # 同步刷新 state.query,确保新跑研究的是新主题而非旧主题。+ if stopped_probe and not _query_matches_stopped_claim(query, state):+ logger.info(+ "[deepresearch_execute] stopped snapshot not claimed: "+ "query changed, starting fresh conversation "+ "tool_call_id=%s conversation_id=%s",+ context.tool_call_id,+ claimed_cid,+ )+ else:+ logger.warning(+ "[deepresearch_execute] claim failed, starting fresh "+ "conversation: no resumable checkpoint in checkpointer.db "+ "tool_call_id=%s conversation_id=%s probe=%s",+ context.tool_call_id,+ claimed_cid,+ f"node={probe_node}" if probe else "none",+ )state = _persist(- context, state, "starting", conversation_id=str(uuid.uuid4())+ context,+ state,+ "starting",+ conversation_id=str(uuid.uuid4()),+ query=str(query or state.get("query") or "").strip(),)else:state = _persist(context, state, "starting")- outcome = await _call_sdk(+ return await _guard_user_stop(context,- action="start",- query=str(state.get("query") or query),- conversation_id=str(state.get("conversation_id") or ""),- file_name=str(state.get("file_name") or file_name),- report_type=state.get("requested_report_type"),+ state,+ _run_sdk_step(+ context,+ state,+ action="start",+ query=str(state.get("query") or query),+ conversation_id=str(state.get("conversation_id") or ""),+ file_name=str(state.get("file_name") or file_name),+ report_type=state.get("requested_report_type"),+ ),)- return await _handle_outcome(context, state, outcome, action="start")if phase == "wait_feedback":terminal_status = _terminal_interaction_status(context.user_input)if terminal_status:@@ -1103,22 +1509,20 @@ async def deepresearch_execute(content=f"研究方向反馈无效:{exc}",)state = _persist(context, state, "resuming_feedback")- outcome = await _call_sdk(- context,- action="resume",- conversation_id=str(state.get("conversation_id") or ""),- node="feedback_handler",- feedback=feedback,- interaction_result=interaction_result,- file_name=str(state.get("file_name") or file_name),- report_type=state.get("requested_report_type"),- )- return await _handle_outcome(+ return await _guard_user_stop(context,state,- outcome,- action="resume",- node="feedback_handler",+ _run_sdk_step(+ context,+ state,+ action="resume",+ node="feedback_handler",+ conversation_id=str(state.get("conversation_id") or ""),+ feedback=feedback,+ interaction_result=interaction_result,+ file_name=str(state.get("file_name") or file_name),+ report_type=state.get("requested_report_type"),+ ),)if phase == "wait_outline":terminal_status = _terminal_interaction_status(context.user_input)@@ -1140,22 +1544,20 @@ async def deepresearch_execute(content=f"大纲审阅结果无效:{exc}",)state = _persist(context, state, "resuming_outline")- outcome = await _call_sdk(- context,- action="resume",- conversation_id=str(state.get("conversation_id") or ""),- node="outline_interaction",- feedback=feedback,- interaction_result=interaction_result,- file_name=str(state.get("file_name") or file_name),- report_type=state.get("requested_report_type"),- )- return await _handle_outcome(+ return await _guard_user_stop(context,state,- outcome,- action="resume",- node="outline_interaction",+ _run_sdk_step(+ context,+ state,+ action="resume",+ node="outline_interaction",+ conversation_id=str(state.get("conversation_id") or ""),+ feedback=feedback,+ interaction_result=interaction_result,+ file_name=str(state.get("file_name") or file_name),+ report_type=state.get("requested_report_type"),+ ),)return _terminal_error(context,diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/stream_router.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/stream_router.pyindex 8c6b556582..29dc93bd6f 100644--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/stream_router.py+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/stream_router.py@@ -118,6 +118,28 @@ _NODE_STAGE: dict[str, int] = {}+def stage_for_resume_node(node: str) -> int:+ """resume node='stopped' 续跑时按被停止节点推导前端进度条起始阶段。++ 实机现象(2026-10-14):停止后续跑,_consume_stream 的阶段阶梯从 0+ 重攀,前端进度列表重置回第一步"研究主题澄清"转圈,误导用户以为从头+ 重跑。停止快照的 pending_node 即被停止节点,据此推导续跑起始阶段:+ 该阶段进行中,之前的阶段全部已完成。++ 映射口径与直播流一致:最终报告节点(reporter/source_tracer 等)在+ 章节全部完成后流出 chunk 时即开启 stage 4(route_chunk 的+ start_final_report_processing 分支),故停止在这些节点 → 续跑从+ stage 4 恢复;注意不能直接用 _NODE_STAGE(该表出于延迟落帧逻辑将+ 最终报告节点映射为 3)。brief_sub_reporter 同理:直播流在全部章节+ 完成前停留在 stage 3,故中途停止于该节点 → 续跑从 stage 3 恢复。+ 未映射节点(start/end/agent_team 等非业务节点)回退 3——停止几乎+ 总发生在长耗时研究阶段。+ """+ if node in FINAL_REPORT_NODES:+ return 4+ return _NODE_STAGE.get(node) or 3++@dataclassclass RouterState:"""路由器跨 chunk 状态:追踪每个节点的 start/done + 累积 report + 捕获中断信息。"""@@ -1099,7 +1121,21 @@ def route_chunk(chunk: dict, state: RouterState) -> list[dict]:else:frames.extend(node_frames)if agent == "brief_sub_reporter" and completes_node:- frames.extend(start_final_report_processing(state))+ # 对齐专业版口径:全部章节完成后才开启 stage 4。首个章节完成时+ # 其余章节仍在并行写作,提前跳"报告交付"会误导用户(暂停前+ # stage4 转圈、续跑却回到 stage3 的口径不一致即源于此)。章节+ # 总数由 deepsearch 在 stream_meta.section_total 透传;总数未知+ # (旧生产端未透传)时退回旧口径——首个完成即开启,保证不因+ # 版本偏差把进度卡死在 stage 3。+ _remember_expected_sections(state, chunk)+ if section_idx != "0":+ state.completed_section_indices.add(section_idx)+ total_known = (+ state.expected_section_total > 0+ or bool(state.authoritative_section_indices)+ )+ if not total_known or _all_sections_completed(state):+ frames.extend(start_final_report_processing(state))return framesreasoning = _chunk_reasoning_content(chunk, content)diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.pyindex b9b6c75142..02433cbe6f 100644--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py@@ -53,6 +53,7 @@ from jiuwenswarm.agents.harness.common.tools.deepresearch.stream_router import (complete_final_report_processing,is_outline_status_placeholder,route_chunk,+ stage_for_resume_node,start_final_report_processing,)from jiuwenswarm.agents.harness.common.tools.deepresearch.tls import (@@ -89,6 +90,15 @@ logger = logging.getLogger(__name__)DEEPRESEARCH_CONFIG_PROTOCOL_VERSION = 1DEEPRESEARCH_CONFIG_MAX_BYTES = 64 * 1024+DEEPRESEARCH_STOP_FRAME_PROTOCOL_VERSION = 1+DEEPRESEARCH_GRACEFUL_STOP_TIMEOUT_SECONDS = 30.0+# 修复A:停止-完成竞速交付报告的超时上限。markdown 产物管线含 HTML 样式+# 生成可能较慢;超时放弃交付时,professional 报告仍有 raw_report.md 修复7+# 止损兜底("继续"时认领失败 salvage 交付)。+DEEPRESEARCH_RACE_DELIVERY_TIMEOUT_SECONDS = 60.0+# 修复A:子进程退出后,帧感知排空读完管道剩余缓冲(至 EOF)的有界窗口。+# 真实管道在子进程退出后毫秒级 EOF;窗口只防异常管道/测试桩永久不 EOF。+DEEPRESEARCH_DRAIN_EOF_GRACE_SECONDS = 2.0DEEPRESEARCH_STDOUT_PENDING_MAX_BYTES = 16 * 1024 * 1024DEEPRESEARCH_STDERR_TAIL_MAX_BYTES = 20_000DEEPRESEARCH_ERROR_TEXT_MAX_CHARS = 2048@@ -179,6 +189,7 @@ _PROTOCOL_STATUS_VALUES = frozenset("pending","resuming","started",+ "stopped",})_SECRET_CONFIG_KEY_MARKERS = (@@ -211,6 +222,12 @@ _deepresearch_route_ctx: contextvars.ContextVar[dict[str, object] | None] = (_deepresearch_router_state_ctx: contextvars.ContextVar[object | None] = (contextvars.ContextVar("jiuwenswarm_deepresearch_router_state", default=None))+# 停止续跑(resume node='stopped')的前端进度起始阶段提示:认领侧+# (execution.py)按被停止节点推导后经本上下文传入 _consume_stream,+# 避免进度列表错误回退到第一步(详见 stream_router.stage_for_resume_node)。+_deepresearch_stage_hint_ctx: contextvars.ContextVar[int | None] = (+ contextvars.ContextVar("jiuwenswarm_deepresearch_stage_hint", default=None)+)_OUTLINE_TITLE_CACHES: dict[tuple[str, str, str], dict[str, dict[str, str]]] = {}@@ -583,6 +600,11 @@ def _build_deepresearch_request_config(}config = _build_deepresearch_config(source)config["DEEPSEARCH_HITL"] = "true" if interactive_ask else "false"+ # 宿主会话归属标识:随 config frame 注入 runner,SDK StartNode 写入+ # 会话 config 随快照落盘;认领侧(probe/扫库)校验归属防跨会话误认领。+ host_session_id = str(_get_route().get("session_id") or "").strip()+ if host_session_id:+ config["DEEPSEARCH_HOST_SESSION_ID"] = host_session_idreturn config@@ -925,18 +947,30 @@ def _validate_stream_json_shape(value: Any) -> bool:return True+async def _close_deepresearch_stdin(proc: Any) -> None:+ stdin = getattr(proc, "stdin", None)+ if stdin is None:+ return+ with suppress(Exception):+ stdin.close()+ wait_closed = getattr(stdin, "wait_closed", None)+ if callable(wait_closed):+ with suppress(Exception):+ await wait_closed()++async def _write_deepresearch_config(proc: Any, frame: bytes) -> None:if proc.stdin is None:raise RuntimeError("DeepResearch config stdin is unavailable")try:proc.stdin.write(frame)await proc.stdin.drain()- finally:- proc.stdin.close()- wait_closed = getattr(proc.stdin, "wait_closed", None)- if callable(wait_closed):- with suppress(BrokenPipeError, ConnectionResetError):- await wait_closed()+ except BaseException:+ # 写失败时子进程多半已死:关闭管道避免句柄泄漏。+ await _close_deepresearch_stdin(proc)+ raise+ # 写成功时保持 stdin 打开:run/resume 期间随时可写停止帧+ # (run_deepsearch.py 的停止帧监听线程依赖该通道做优雅停止)。async def _await_cleanup_task(task: asyncio.Task[Any]) -> None:@@ -970,6 +1004,137 @@ async def _stop_deepresearch_process(proc: Any, timeout: float = 10.0) -> None:await proc.wait()+def _capture_completed_frame(line: bytes, captured: dict[str, Any]) -> None:+ """修复A:从停止排空窗口的输出行中捕获 completed 终局帧。++ 仅捕获带 response_content 的 completed 帧(自然完成竞速的唯一存活+ 报告载体);stopped/error/interrupted 终态帧由既有路径处理,不捕获。+ 多个 completed 帧时保留最后一个。+ """+ try:+ chunk = json.loads(line.decode("utf-8").strip())+ except (UnicodeDecodeError, json.JSONDecodeError, RecursionError):+ return+ if not isinstance(chunk, dict):+ return+ status_value = chunk.get("__deepsearch_status__") or chunk.get("status")+ if status_value != "completed":+ return+ final_result = chunk.get("final_result")+ if not isinstance(final_result, dict):+ return+ response_content = final_result.get("response_content")+ if not isinstance(response_content, str) or not response_content:+ return+ captured.clear()+ captured.update(chunk)+++async def _drain_stream_while_stopping(+ stream: Any, captured: dict[str, Any] | None = None+) -> None:+ """停止等待期间持续排空子进程输出,防止管道写满阻塞落盘退出。++ 帧感知(修复A):停止-完成竞速窗口内,子进程可能在停止信号生效前按+ 自然完成路径输出 completed 终局帧(含报告全文)。原盲排空把该帧连同+ 报告一起丢弃——快照又按 workflow_completed 清理,报告彻底丢失。排空+ 同时逐行解析 NDJSON,捕获 completed 帧写入 captured,供调用方在+ 优雅停止完成后照常交付。captured 为 None 时保持纯排空行为。+ """+ read = getattr(stream, "read", None)+ if not callable(read):+ return+ pending = bytearray()+ while True:+ try:+ chunk = await read(64 * 1024)+ except (OSError, ValueError):+ return+ if not chunk:+ return+ if captured is None:+ continue+ pending.extend(chunk)+ if len(pending) > DEEPRESEARCH_STDOUT_PENDING_MAX_BYTES:+ # 无换行的异常输出:丢弃已有内容防止无界膨胀,继续排空。+ pending.clear()+ continue+ while True:+ newline = pending.find(b"\n")+ if newline < 0:+ break+ line = bytes(pending[:newline])+ del pending[: newline + 1]+ _capture_completed_frame(line, captured)+++async def _request_graceful_stop(+ proc: Any,+ timeout: float = DEEPRESEARCH_GRACEFUL_STOP_TIMEOUT_SECONDS,+ *,+ captured: dict[str, Any] | None = None,+) -> None:+ """优雅停止三步走:发停止帧 → 等子进程落盘退出 → 超时硬杀兜底。++ 停止帧是 ``{"version":1,"action":"stop"}`` 换行 JSON,子进程后台线程+ 收到后调用 ``request_stop()``,工作流在节点边界抛 StopRequested,+ 异常保存分支落盘 checkpoint 并输出 stopped 终态后正常退出。++ captured 非空时,排空任务同时捕获停止-完成竞速窗口内自然完成输出+ 的 completed 终局帧(修复A),供调用方交付报告。+ """+ stdin = getattr(proc, "stdin", None)+ if stdin is not None and getattr(proc, "returncode", None) is None:+ frame = (+ json.dumps(+ {+ "version": DEEPRESEARCH_STOP_FRAME_PROTOCOL_VERSION,+ "action": "stop",+ },+ ensure_ascii=False,+ )+ + "\n"+ ).encode("utf-8")+ try:+ stdin.write(frame)+ await stdin.drain()+ except (OSError, ValueError):+ # 子进程已退出或管道断开:跳过等待,直接走硬停止兜底。+ logger.info(+ "[deepresearch_stream] stop frame not delivered "+ "(child gone or pipe closed); falling back to hard stop"+ )+ if getattr(proc, "returncode", None) is None:+ # 调用方已被取消,原消费循环不再读 stdout:必须持续排空,+ # 否则子进程写 stopped 终态时管道满写阻塞,永远无法落盘退出。+ drain_task = asyncio.create_task(+ _drain_stream_while_stopping(proc.stdout, captured)+ )+ try:+ await asyncio.wait_for(proc.wait(), timeout=timeout)+ except asyncio.TimeoutError:+ logger.warning(+ "[deepresearch_stream] graceful stop timed out after %ss; "+ "falling back to hard stop",+ timeout,+ )+ finally:+ # 子进程已退出(或超时走硬停止)。帧感知排空时管道中可能仍有+ # 未读完的竞速 completed 帧:子进程退出后管道必达 EOF,给+ # drain 一个有界窗口读完剩余缓冲;纯排空(captured=None)与+ # 异常管道/测试桩永久不 EOF 的场景由超时+取消兜底,清理路径+ # 不会挂起。+ if captured is not None:+ with suppress(asyncio.TimeoutError, asyncio.CancelledError):+ await asyncio.wait_for(+ asyncio.shield(drain_task),+ timeout=DEEPRESEARCH_DRAIN_EOF_GRACE_SECONDS,+ )+ drain_task.cancel()+ await _await_cleanup_task(drain_task)+ await _stop_deepresearch_process(proc)++async def _iter_ndjson_lines(stream: Any,read_size: int = 64 * 1024,@@ -1353,17 +1518,188 @@ def _decode_checkpoint_blob(raw: Any) -> Any:return None-def _probe_resumable_checkpoint(conversation_id: str) -> dict[str, Any] | None:- """Probe checkpointer.db for an interrupted DeepResearch conversation.+_CHECKPOINT_ERROR_STATUS = "__error__"+# 扫库认领候选窗口上限:宽松取值,防 LIMIT 过紧把本会话目标挤出窗口+# (服务级全局单库,窗口内可能混有其他会话快照)造成漏认领。+_SCAN_CHECKPOINT_KEY_LIMIT = 500+# 与 deepsearch stop_control.STOP_REQUESTED_MARKER 保持一致:StopRequested+# 经 __reduce__ 降级为携带该标记的 RuntimeError 后跨进程可反序列化。+_CHECKPOINT_STOP_MARKER = "deepresearch task stopped by user"- Reads only the pending interrupt node plus the search-context fields- needed to re-present an interaction card after a process restart.- Returns None whenever the conversation has no resumable interrupt, so a- failed probe simply falls back to a fresh start.++def _is_stop_requested_exception(exc: Any) -> bool:+ """识别 pending_node.exception 中的停止请求(类型名或消息标记)。++ CancelledError 同样按可续跑快照处理:SDK 在取消路径会为被取消节点+ 写入 __error__+CancelledError 快照,恢复语义与用户停止一致(从中断+ 节点续跑,已完成节点不重跑)。"""- cid = str(conversation_id or "").strip()- if not cid:+ if not isinstance(exc, BaseException):+ return False+ if type(exc).__name__ == "StopRequested":+ return True+ if type(exc).__name__ == "CancelledError":+ return True+ return _CHECKPOINT_STOP_MARKER in str(exc)+++def _parse_resumable_snapshot(graph_state: Any) -> dict[str, Any] | None:+ """解析 graph 快照的 pending_node,判定可续跑状态(stopped/interrupt)。++ 两遍扫描:停止快照优先。用户已在某个后续环节手动停止时,+ pending_node 中可能残留早期交互(如 outline_interaction)的+ stale interrupt 条目;若 interrupt 优先,会把已停止的会话错认+ 为中断认领,拉回早期交互重弹卡。先全量识别停止快照,未命中+ 才认领 interrupt。++ 返回 {"node", "stopped": True}(停止快照,调用方直接 resume+ node='stopped' 无需重弹卡)或 {"node"}(interrupt 快照);+ 无可续跑状态返回 None。+ """+ pending_nodes = getattr(graph_state, "pending_node", None) or {}+ for node_name, pending in pending_nodes.items():+ if str(getattr(pending, "status", "")) != _CHECKPOINT_ERROR_STATUS:+ continue+ # 停止快照:StopRequested 异常经 __reduce__ 降级为带停止+ # 标记的 RuntimeError,父进程无需安装 deepsearch 包即可识别。+ exceptions = getattr(pending, "exception", None) or []+ if any(_is_stop_requested_exception(exc) for exc in exceptions):+ return {"node": str(node_name), "stopped": True}+ for node_name, pending in pending_nodes.items():+ if str(getattr(pending, "status", "")) == _CHECKPOINT_INTERRUPT_STATUS:+ return {"node": str(node_name)}+ return None+++def _read_snapshot_workflow_state(cursor: Any, cid: str) -> Mapping[str, Any]:+ """读取并解码会话 workflow_state 快照;不可用返回空 Mapping。++ 归属字段(global_state.config.host_session_id)与重弹卡字段+ (global_state.search_context)同源于 workflow_state,单次解码即可+ 同时供归属校验与 search_context 读取(旧实现两处各解码一次,+ 扫库/probe 每候选重复解码两遍)。+ """+ workflow_state = _decode_checkpoint_blob(+ _read_checkpoint_kv_value(+ cursor,+ f"{cid}:workflow:{_CHECKPOINT_WORKFLOW_ID}:workflow_state_blobs",+ )+ )+ return workflow_state if isinstance(workflow_state, Mapping) else {}+++def _snapshot_global_state(+ workflow_state: Mapping[str, Any],+) -> Mapping[str, Any]:+ global_state = workflow_state.get("global_state")+ return global_state if isinstance(global_state, Mapping) else {}+++def _global_state_search_context(+ global_state: Mapping[str, Any],+) -> Mapping[str, Any]:+ candidate = global_state.get("search_context")+ return candidate if isinstance(candidate, Mapping) else {}+++def _global_state_host_session_id(+ global_state: Mapping[str, Any],+) -> str | None:+ """读取快照 global_state.config.host_session_id;字段缺失返回 None。++ 归属字段由宿主随 config frame 注入(DEEPSEARCH_HOST_SESSION_ID),+ SDK StartNode 白名单写入会话 config 随快照落盘;resume 不重跑+ StartNode,故归属始终保持原始创建者。+ """+ config = global_state.get("config")+ if not isinstance(config, Mapping) or "host_session_id" not in config:return None+ return str(config.get("host_session_id") or "")+++def _owner_matches_current_session(owner: str | None) -> tuple[bool, str]:+ """快照归属判定:防跨会话/跨用户误认领陈旧快照。++ 实机事故(2026-10-13 20:42):新会话跑同 query,扫库兜底命中 10-10+ 陈旧快照,误判"用户在继续那次研究"而 resume,快照冻结的旧模型配置+ 与当前进程脱钩,5 个章节子代理零 LLM 空转,13.4s 失败。checkpointer+ 为服务级全局单库且快照无宿主身份字段,故认领侧必须显式校验归属。++ 返回 (matches, reason):+ - owner == 当前宿主会话 → (True, "match") 正常认领+ - owner 缺失/为空 → (False, "missing_owner") 旧快照一律拒绝(拍板)+ - owner 与当前不同 → (False, "ownership_mismatch") 跨会话拒绝+ - 当前请求无 session_id → (False, "requester_unverifiable") 严格拒绝+ """+ current = str(_get_route().get("session_id") or "").strip()+ if not current:+ return False, "requester_unverifiable"+ if owner is None or not owner.strip():+ return False, "missing_owner"+ if owner.strip() != current:+ return False, "ownership_mismatch"+ return True, "match"+++def _log_ownership_reject(+ source: str, cid: str, reason: str, node: object, query: object = None+) -> None:+ """归属拒绝观察哨:与 scan-claim matched 同风格,供实机审计。"""+ if query is None:+ logger.warning(+ "deepresearch ownership rejected source=%s conversation_id=%s "+ "reason=%s node=%s",+ source,+ cid,+ reason,+ node,+ )+ else:+ logger.warning(+ "deepresearch ownership rejected source=%s conversation_id=%s "+ "reason=%s node=%s query=%r",+ source,+ cid,+ reason,+ node,+ query,+ )+++def _extract_interaction_fields(+ search_context: Mapping[str, Any],+) -> dict[str, Any]:+ """从 search_context 提取重弹交互卡所需字段(questions/outline_json)。"""+ result: dict[str, Any] = {}+ questions = search_context.get("questions")+ if isinstance(questions, str) and questions.strip():+ result["questions"] = [+ question.strip()+ for question in _QUESTION_PARAGRAPH_SPLIT.split(questions.strip())+ if question.strip()+ ]+ outline = search_context.get("current_outline")+ sections = []+ for section in getattr(outline, "sections", None) or []:+ sections.append(+ {+ "title": str(getattr(section, "title", "") or ""),+ "is_core_section": bool(+ getattr(section, "is_core_section", False)+ ),+ }+ )+ if outline is not None and sections:+ result["outline_json"] = {+ "title": str(getattr(outline, "title", "") or ""),+ "thought": str(getattr(outline, "thought", "") or ""),+ "sections": sections,+ }+ return result+++def _open_checkpoint_db_ro() -> sqlite3.Connection | None:+ """以只读模式打开 checkpointer.db,不可用返回 None。"""root = _resolve_skill_root()if not root:return None@@ -1371,11 +1707,28 @@ def _probe_resumable_checkpoint(conversation_id: str) -> dict[str, Any] | None:if not os.path.isfile(db_path):return Nonetry:- connection = sqlite3.connect(- f"file:{db_path}?mode=ro", uri=True, timeout=1.0- )+ return sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=1.0)except sqlite3.Error:return None+++def _probe_resumable_checkpoint(conversation_id: str) -> dict[str, Any] | None:+ """Probe checkpointer.db for an interrupted DeepResearch conversation.++ Reads only the pending interrupt node plus the search-context fields+ needed to re-present an interaction card after a process restart.+ Also recognizes graceful-stop snapshots (``__error__`` pending nodes+ whose exception is a stop request) so the caller can resume them+ directly with ``node='stopped'`` without re-presenting any card.+ Returns None whenever the conversation has no resumable state, so a+ failed probe simply falls back to a fresh start.+ """+ cid = str(conversation_id or "").strip()+ if not cid:+ return None+ connection = _open_checkpoint_db_ro()+ if connection is None:+ return Nonetry:cursor = connection.cursor()graph_state = _decode_checkpoint_blob(@@ -1384,55 +1737,33 @@ def _probe_resumable_checkpoint(conversation_id: str) -> dict[str, Any] | None:f"{cid}:workflow-graph:{_CHECKPOINT_WORKFLOW_ID}:checkpoint_data_value",))- pending_nodes = getattr(graph_state, "pending_node", None) or {}- node = ""- for node_name, pending in pending_nodes.items():- if (- str(getattr(pending, "status", ""))- == _CHECKPOINT_INTERRUPT_STATUS- ):- node = str(node_name)- break- if not node:+ if graph_state is None:return None- result: dict[str, Any] = {"node": node}- workflow_state = _decode_checkpoint_blob(- _read_checkpoint_kv_value(- cursor,- f"{cid}:workflow:{_CHECKPOINT_WORKFLOW_ID}:workflow_state_blobs",- )+ snapshot = _parse_resumable_snapshot(graph_state)+ if snapshot is None:+ return None+ # workflow_state 单次解码:归属字段与 search_context 同源共用。+ global_state = _snapshot_global_state(+ _read_snapshot_workflow_state(cursor, cid))- search_context: Mapping[str, Any] = {}- if isinstance(workflow_state, Mapping):- global_state = workflow_state.get("global_state")- if isinstance(global_state, Mapping):- candidate = global_state.get("search_context")- if isinstance(candidate, Mapping):- search_context = candidate- questions = search_context.get("questions")- if isinstance(questions, str) and questions.strip():- result["questions"] = [- question.strip()- for question in _QUESTION_PARAGRAPH_SPLIT.split(questions.strip())- if question.strip()- ]- outline = search_context.get("current_outline")- sections = []- for section in getattr(outline, "sections", None) or []:- sections.append(- {- "title": str(getattr(section, "title", "") or ""),- "is_core_section": bool(- getattr(section, "is_core_section", False)- ),- }+ # 归属校验:快照 host_session_id 必须等于当前宿主会话,否则拒绝+ # 认领(不匹配/旧快照缺字段均拒绝,防 LLM 幻觉 cid 撞别家会话)。+ matches, reason = _owner_matches_current_session(+ _global_state_host_session_id(global_state)+ )+ if not matches:+ _log_ownership_reject("probe", cid, reason, snapshot.get("node"))+ return None+ if snapshot.get("stopped"):+ # 优雅停止快照:无需重弹交互卡,由调用方直接 resume node='stopped'+ # (node 仅用于日志诊断)。+ return snapshot+ result: dict[str, Any] = dict(snapshot)+ result.update(+ _extract_interaction_fields(+ _global_state_search_context(global_state))- if outline is not None and sections:- result["outline_json"] = {- "title": str(getattr(outline, "title", "") or ""),- "thought": str(getattr(outline, "thought", "") or ""),- "sections": sections,- }+ )return resultexcept Exception: # pylint: disable=broad-exception-caughtreturn None@@ -1441,6 +1772,117 @@ def _probe_resumable_checkpoint(conversation_id: str) -> dict[str, Any] | None:connection.close()+def _scan_resumable_checkpoint_by_query(query: str) -> dict[str, Any] | None:+ """修复9':不信任 LLM 传参 cid,按入参 query 扫库认领可续跑会话。++ LLM 续跑传参可能幻觉 conversation_id(实机事故:两次幻觉 id 均在+ 认领入口失效,probe 落空后直接全新起跑,丢弃已停止会话的全部研究+ 成果)。本函数在 probe(cid) 落空时兜底:枚举 kv_store 全部 graph+ 快照键(rowid 倒序——kv_store 无时间戳列,rowid 随插入递增,最新+ 落盘快照即用户最近操作的会话,优先认领),逐键解码判定可续跑状态,+ 以 workflow_state 的 search_context.original_query 与入参 query+ 完全一致作为认领条件(换主题不认领旧会话),并校验快照+ config.host_session_id 归属当前宿主会话(不匹配/旧快照缺字段均+ 跳过该候选,防跨会话误认领)。++ 注意匹配语义与 probe 场景的差异:probe 时 cid 是可靠线索、query+ 仅作意图确认(原 query 为空即认领);扫库时 query 是唯一线索,+ original_query 缺失或不同一律不认领,避免认错会话。++ 返回 {"conversation_id", "node", "stopped"}(interrupt 命中时附加+ questions/outline_json 重弹卡字段),未命中返回 None。单键解码+ 失败不阻断扫描。+ """+ incoming = str(query or "").strip()+ if not incoming:+ return None+ connection = _open_checkpoint_db_ro()+ if connection is None:+ return None+ try:+ cursor = connection.cursor()+ # 性能护栏:扫库现挂 stream action='start' 热路径(每次全新起跑+ # 前都会扫一遍),LIMIT 截断无界全表扫描。窗口取宽松值——服务级+ # 全局单库下窗口内可能混有其他会话快照,过紧会把本会话目标挤出+ # 窗口造成漏认领(退回"丢全部研究成果"事故),500 个候选足够+ # 容纳单机会话积压。+ cursor.execute(+ "SELECT key FROM kv_store WHERE key LIKE ? "+ "ORDER BY rowid DESC LIMIT ?",+ (+ f"%:workflow-graph:{_CHECKPOINT_WORKFLOW_ID}"+ ":checkpoint_data_value",+ _SCAN_CHECKPOINT_KEY_LIMIT,+ ),+ )+ keys = [str(row[0] or "") for row in cursor.fetchall()]+ for key in keys:+ cid = key.split(":workflow-graph:", 1)[0].strip()+ if not cid:+ continue+ # 先轻后重:workflow_state(单次解码,归属+主题双过滤)先行,+ # foreign/换主题候选不再解码重量级 graph 快照(旧实现每候选+ # 必解码 graph,且 workflow_state 被归属与 search_context+ # 两处重复解码)。+ global_state = _snapshot_global_state(+ _read_snapshot_workflow_state(cursor, cid)+ )+ # 主题过滤先行(与旧实现口径一致:换主题静默跳过,不打观察哨)。+ original = str(+ _global_state_search_context(global_state).get(+ "original_query"+ )+ or ""+ ).strip()+ if original != incoming:+ continue+ # 归属校验:query 一致不代表是本会话的研究(实机事故:新会话同+ # query 命中陈旧快照误认领);owner 不匹配/缺失继续扫下一个候选。+ # (先轻后重重排后归属拒绝发生在 graph 解码前,观察哨日志的+ # node 字段为空——拒绝原因与 cid 不受影响。)+ matches, reason = _owner_matches_current_session(+ _global_state_host_session_id(global_state)+ )+ if not matches:+ _log_ownership_reject("scan", cid, reason, "", incoming)+ continue+ # 双过滤通过才解码重量级 graph 快照,判定可续跑状态。+ graph_state = _decode_checkpoint_blob(+ _read_checkpoint_kv_value(cursor, key)+ )+ if graph_state is None:+ continue+ snapshot = _parse_resumable_snapshot(graph_state)+ if snapshot is None:+ continue+ result: dict[str, Any] = {"conversation_id": cid, **snapshot}+ if not snapshot.get("stopped"):+ result.update(+ _extract_interaction_fields(+ _global_state_search_context(global_state)+ )+ )+ # 审计观察哨:扫库认领命中即记录命中对象与快照新旧,便于实机+ # 排查"认错陈旧/跨会话快照"类事故(扫库是 probe 落空后的兜底+ # 路径,主路径不应走到这里;命中陈旧对象往往意味着停止快照+ # 被误删或 probe cid 脱钩)。+ logger.warning(+ "deepresearch scan-claim matched conversation_id=%s node=%s "+ "stopped=%s query=%r",+ cid,+ snapshot.get("node"),+ bool(snapshot.get("stopped")),+ incoming,+ )+ return result+ return None+ except Exception: # pylint: disable=broad-exception-caught+ return None+ finally:+ with suppress(sqlite3.Error):+ connection.close()++def _get_effective_request_output_dir() -> Path:route = _deepresearch_route_ctx.get() or {}output_dir = route.get("output_dir")@@ -2015,6 +2457,65 @@ def _has_completed_final_pipeline_node(state: RouterState) -> bool:)+def _claim_interrupted_prompt(+ node: str, marker: Mapping[str, Any], query: str+) -> str:+ """合成 interrupted outcome 的 prompt:按 node 取交互正文,缺省回落 query。"""+ if node == "outline_interaction" and isinstance(marker.get("outline"), dict):+ formatted = _format_outline_card_markdown(marker["outline"])+ return formatted or json.dumps(marker["outline"], ensure_ascii=False)+ questions = marker.get("questions")+ if isinstance(questions, list) and questions:+ return "\n\n".join(str(question) for question in questions)+ return str(query or "").strip() or "请输入反馈"+++async def _claim_start_snapshot(query: str) -> dict[str, Any] | None:+ """stream action='start' 的扫库认领兜底入口。++ 同步 SQLite 扫描经 to_thread 卸载避免阻塞事件循环(contextvar 经+ copy_context 随线程传播,_get_route 归属校验线程内安全);同时作为+ 测试桩点——execute 侧用例默认把本函数打桩为未命中,防止真实扫库+ 读开发机共享 checkpointer.db 造成机器相关行为(扫库逻辑本身由+ _scan_resumable_checkpoint_by_query 的专项用例覆盖)。+ """+ if not str(query or "").strip():+ return None+ return await asyncio.to_thread(_scan_resumable_checkpoint_by_query, query)+++def _synthesize_claim_interrupted_outcome(+ claim: Mapping[str, Any], route: Mapping[str, Any], query: str+) -> dict[str, Any]:+ """扫库认领交互中断快照时本地合成 interrupted 终局(不经子进程)。++ 停止可能落在交互卡待答复期间(快照为 __interrupt__ 而非停止态):+ 交互内容已由扫库从 workflow_state 带出,直接合成标准 interrupted+ outcome 交外层模型重弹卡,避免空反馈拉起子进程再中断一圈。+ """+ cid = str(claim.get("conversation_id") or "")+ node = str(claim.get("node") or "")+ marker: dict[str, Any] = {}+ questions = claim.get("questions")+ if isinstance(questions, list) and questions:+ marker["questions"] = questions+ outline_json = claim.get("outline_json")+ if isinstance(outline_json, dict):+ marker["outline"] = outline_json+ # 与流式 interrupt 路径同款缓存:outline 编辑回传与 execute 认领+ # 兜底都依赖该缓存(缺 sections 时下游 fail-closed)。+ _cache_outline_json(route, cid, outline_json)+ return {+ "status": "interrupted",+ "conversation_id": cid,+ "node_id": node,+ "marker": marker,+ "prompt": _claim_interrupted_prompt(node, marker, query),+ "resume_hint": _build_interrupted_resume_hint(node, cid),+ "skill_execution_ms": 0,+ }++async def _call_deepresearch_stream_impl(*, _router_state: object | None = None, **kwargs: Any) -> str:@@ -2032,7 +2533,12 @@ async def _call_deepresearch_stream_impl("Run or resume DeepResearch through the isolated external skill runner. ""Progress is pushed to the current Gateway route; only a terminal ""interrupted, completed, or structured error outcome is returned. "- "action='start' launches a new research run and requires query; "+ "action='start' launches a new research run and requires query "+ "(if a stopped or interaction-paused snapshot for the same topic "+ "exists in this session, it is claimed automatically: a stopped "+ "snapshot resumes from where it stopped without re-running "+ "completed stages, and an interaction-paused snapshot returns the "+ "pending interaction); ""action='resume' continues an interrupted conversation and requires ""the conversation_id and node from that interrupted outcome. When the ""outcome status is 'interrupted', the workflow is paused waiting for "@@ -2042,7 +2548,11 @@ async def _call_deepresearch_stream_impl("answer encoded as interaction_result for outline_interaction). ""Follow outcome.resume_hint for the exact resume arguments and ""accepted values. Never answer the interaction on the user's behalf "- "or resume without the user's input."+ "or resume without the user's input. When the outcome status is "+ "'stopped', the run was gracefully stopped by the user and "+ "checkpointed: to continue it from where it stopped, resume with "+ "action='resume', the same conversation_id, and node='stopped' "+ "(no feedback needed); completed stages are not re-executed."),)async def deepresearch_stream( # pylint: disable=huawei-too-many-arguments@@ -2085,6 +2595,51 @@ async def deepresearch_stream( # pylint: disable=huawei-too-many-argumentsensure_ascii=False,)+ # 认领停止快照时按 claim node 推导的阶段提示(消费点 set/reset);+ # 其余路径保持 None。+ claim_stage_hint: int | None = None+ if action == "start":+ # 停止恢复兜底(2026-10-15 19:52 回归实证):停止后新请求中 skill+ # 激活态随请求重建而重置,deepresearch_execute 被+ # ProgressiveToolRail 过滤(stopped 文案指引的唯一入口成为死信),+ # 外层模型经 invoke_tool 摸到本工具 action='start' → 绕过认领全新+ # 起跑,丢弃停止快照从头重跑。此处与 execute 同口径兜底:按 query+ # 扫库认领(含归属守卫与主题一致校验),命中停止快照直通改写为+ # resume node='stopped'(已完成节点不重跑);命中交互中断快照+ # (停止落在卡片待答复期间)本地合成 interrupted outcome 重弹卡。+ claim = await _claim_start_snapshot(query)+ if claim is not None:+ claim_cid = str(claim.get("conversation_id") or "")+ if claim.get("stopped") and claim_cid:+ logger.info(+ "[deepresearch_stream] start claimed stopped conversation "+ "conversation_id=%s node=%s",+ claim_cid,+ claim.get("node"),+ )+ action = "resume"+ conversation_id = claim_cid+ node = "stopped"+ # 与 execute 认领路径(execution.py resuming_stopped)同口径+ # 推导阶段提示:否则 _consume_stream 的 resuming 分支取默认+ # stage=1,前端会显示"回到 stage1 从头重跑"(2026-10-16 日志+ # 实证:brief_html_reporter 暂停续跑后 stage1 转圈 2 分 45+ # 秒直跳全部完成)。暂存到局部变量,消费点再 set/reset。+ claim_stage_hint = stage_for_resume_node(+ str(claim.get("node") or "")+ )+ elif claim_cid:+ logger.info(+ "[deepresearch_stream] start claimed interrupted "+ "conversation conversation_id=%s node=%s",+ claim_cid,+ claim.get("node"),+ )+ return json.dumps(+ _synthesize_claim_interrupted_outcome(claim, route, query),+ ensure_ascii=False,+ )+if action == "start":argv = [str(python_bin),@@ -2271,20 +2826,66 @@ async def deepresearch_stream( # pylint: disable=huawei-too-many-argumentsawait _await_cleanup_task(cleanup)raiseawait _write_deepresearch_config(proc, config_frame)- outcome = await _consume_stream(- proc=proc,- route=route,- action=action,- node=node,- query=query,- conversation_id=conversation_id,- file_name=file_name,- secrets=_config_secret_values(config),- skill_started_ns=skill_started_ns,+ # 认领停止快照的续跑消费段设置阶段提示(仅在消费窗口内生效,+ # finally 复位避免向同上下文后续调用泄漏陈旧 hint)。+ stage_hint_token = (+ _deepresearch_stage_hint_ctx.set(claim_stage_hint)+ if claim_stage_hint is not None+ else None)+ try:+ outcome = await _consume_stream(+ proc=proc,+ route=route,+ action=action,+ node=node,+ query=query,+ conversation_id=conversation_id,+ file_name=file_name,+ secrets=_config_secret_values(config),+ skill_started_ns=skill_started_ns,+ )+ finally:+ if stage_hint_token is not None:+ _deepresearch_stage_hint_ctx.reset(stage_hint_token)except asyncio.CancelledError:- cleanup = asyncio.create_task(_stop_deepresearch_process(proc))+ # 用户停止:先优雅停止(发帧→等落盘→超时兜底),保留 checkpoint+ # 供 resume --node stopped 恢复,不回退到并行调研阶段重跑。+ captured: dict[str, Any] = {}+ cleanup = asyncio.create_task(+ _request_graceful_stop(proc, captured=captured)+ )await _await_cleanup_task(cleanup)+ if captured:+ # 修复A:停止-完成竞速——子进程在停止信号生效前已自然完成,+ # completed 帧被帧感知排空捕获。快照已按 workflow_completed+ # 清理,续跑无可恢复状态,必须在此把报告交付给用户。+ try:+ await asyncio.wait_for(+ _deliver_race_completed_report(+ route=route,+ chunk=captured,+ file_name=file_name,+ conversation_id=conversation_id,+ secrets=_config_secret_values(config),+ ),+ timeout=DEEPRESEARCH_RACE_DELIVERY_TIMEOUT_SECONDS,+ )+ except asyncio.TimeoutError:+ logger.warning(+ "[deepresearch_stream] race-completed delivery timed "+ "out after %ss",+ DEEPRESEARCH_RACE_DELIVERY_TIMEOUT_SECONDS,+ )+ # CancelledError 是 BaseException 子类,不会落入下方+ # except Exception,自动向上传播保持取消语义,无需显式+ # except 分支(G.ERR.13)。+ except Exception as exc: # pylint: disable=broad-exception-caught+ logger.warning(+ "[deepresearch_stream] race-completed delivery failed "+ "type=%s",+ type(exc).__name__,+ )raiseexcept _StreamProtocolInvalid:outcome = _stream_protocol_error()@@ -2333,13 +2934,28 @@ async def deepresearch_stream( # pylint: disable=huawei-too-many-argumentsif stderr_text:outcome["stderr_tail"] = stderr_textif (- outcome.get("status") in {"completed", "interrupted", "error"}+ outcome.get("status") in {"completed", "interrupted", "error", "stopped"}and isinstance(outcome.get("timing"), dict)):outcome["skill_execution_ms"] = max(0,(time.monotonic_ns() - skill_started_ns) // 1_000_000,)+ if outcome.get("status") == "stopped":+ outcome["resume_hint"] = {+ "action": "resume",+ "node": "stopped",+ "conversation_id": str(+ outcome.get("conversation_id") or conversation_id+ ),+ "guidance": (+ "The research run was gracefully stopped by the user and its "+ "progress is checkpointed. To continue the same run from "+ "where it stopped, use action='resume', this conversation_id, "+ "and node='stopped' (no feedback needed); completed stages "+ "will not be re-executed. Otherwise, start a new run."+ ),+ }if outcome.get("status") in {"completed", "error", "cancelled"}:_clear_outline_title_cache(route, outcome.get("conversation_id", conversation_id)@@ -2390,6 +3006,377 @@ async def _finish_stderr_task(task: asyncio.Task[Any]) -> None:await task+_DEEPRESEARCH_SALVAGE_MIN_REPORT_CHARS = 64+++def _locate_salvage_report(conversation_id: str) -> dict[str, Any] | None:+ """修复7:定位子进程落盘的 raw_report.md 止损产物。++ 子进程在报告生成后、发出 completed 终局帧之前,会把+ ``final_result.response_content`` 原文写入+ ``<skill_root>/data/<cid>.raw_report.md``(保留 [checked_citation:N]+ 锚点)。子进程在交付前崩溃/被停时,该文件是唯一存活的报告载体。+ 返回 {"response_content", "citation_artifacts"};不可止损返回 None。+ """+ cid = str(conversation_id or "").strip()+ if not cid:+ return None+ root = _resolve_skill_root()+ if not root:+ return None+ data_dir = Path(root) / "data"+ raw_path = data_dir / f"{cid}.raw_report.md"+ try:+ if raw_path.stat().st_size > DEEPRESEARCH_STREAM_JSON_MAX_TEXT_CHARS:+ return None+ content = raw_path.read_text(encoding="utf-8")+ except (OSError, UnicodeError):+ return None+ if len(content.strip()) < _DEEPRESEARCH_SALVAGE_MIN_REPORT_CHARS:+ return None+ citation_artifacts: dict[str, str] = {+ "raw_report_path": str(raw_path).replace("\\", "/")+ }+ preview_path = data_dir / f"{cid}.citations.preview.json"+ try:+ if preview_path.is_file():+ citation_artifacts["citations_preview_path"] = str(+ preview_path+ ).replace("\\", "/")+ except OSError:+ pass+ return {+ "response_content": content,+ "citation_artifacts": citation_artifacts,+ }+++async def _deliver_salvaged_report(+ *,+ route: dict[str, object],+ conversation_id: str,+ file_name: str,+ send: Callable[[dict[str, Any]], Awaitable[bool]],+ reason: str,+) -> dict[str, Any] | None:+ """修复7:从 raw_report.md 止损交付报告。++ 子进程异常终局(error / completed 缺 response_content)但报告已落盘+ 时,复用正常完成路径的产物管线(清理引文锚点 + HTML 样式/离线兜底)+ 把报告交付给用户,返回 completed outcome;不可止损(无文件/产物写+ 失败/推送失败)返回 None,调用方回退原始错误。+ """+ located = _locate_salvage_report(conversation_id)+ if located is None:+ return None+ if not route.get("session_id") or not route.get("channel_id"):+ return None+ final_result = {+ "response_content": located["response_content"],+ "response_content_type": "text/markdown",+ }+ try:+ (+ artifacts,+ html_style_status,+ html_style_phase,+ html_style_reason_code,+ ) = await _write_report_artifacts_stream(+ final_result,+ file_name,+ conversation_id,+ located["citation_artifacts"],+ )+ except Exception as exc: # pylint: disable=broad-exception-caught+ logger.warning(+ "[deepresearch_stream] salvage artifact write failed type=%s",+ type(exc).__name__,+ )+ return None+ artifact_mime_types = {"md": "text/markdown", "html": "text/html"}+ files = [+ {+ "path": value,+ "name": Path(value).name,+ "mime_type": artifact_mime_types.get(key),+ }+ for key, value in artifacts.items()+ if key in artifact_mime_types+ ]+ if not files:+ return None+ file_payload: dict[str, Any] = {"event_type": "chat.file", "files": files}+ markdown_index = list(artifacts).index("md") if "md" in artifacts else 0+ bundle = _build_related_artifact_bundle(+ located["citation_artifacts"], markdown_index+ )+ if bundle:+ file_payload["metadata"] = {"artifactBundle": bundle}+ if not await send(file_payload):+ return None+ logger.warning(+ "[deepresearch_stream] salvaged report from raw_report.md "+ "conversation_id=%s reason=%s",+ conversation_id,+ reason,+ )+ outcome: dict[str, Any] = {+ "status": "completed",+ "conversation_id": conversation_id,+ "report_delivered": True,+ "salvaged_report": True,+ }+ if html_style_status in {"applied", "fallback"}:+ outcome["html_style_status"] = html_style_status+ if (+ html_style_status == "fallback"+ and isinstance(html_style_phase, str)+ and isinstance(html_style_reason_code, str)+ ):+ outcome["html_style_phase"] = html_style_phase+ outcome["html_style_reason_code"] = html_style_reason_code+ return outcome+++async def _deliver_race_completed_report(+ *,+ route: dict[str, object],+ chunk: dict[str, Any],+ file_name: str,+ conversation_id: str,+ secrets: tuple[str, ...],+) -> dict[str, Any] | None:+ """修复A:交付停止-完成竞速窗口内捕获的 completed 终局帧。++ 用户按停止时消费循环已被取消,但子进程可能在停止信号生效前按自然+ 完成路径输出 completed 终局帧——快照同时按 workflow_completed 清理,+ "继续"时无可恢复状态、brief 成品又无止损产物可捞,报告将彻底丢失。+ 本函数复用正常完成路径的产物管线(html 直写 / markdown 引文管线)+ 与进度收尾推送,把已生成的报告交付给用户。返回 completed outcome;+ 不可交付(帧无效/写盘失败/推送失败)返回 None,调用方保持停止语义。+ """+ try:+ safe_chunk = _redact_json_value(chunk, secrets)+ except _StreamProtocolInvalid:+ return None+ if not isinstance(safe_chunk, dict):+ return None+ final_result = safe_chunk.get("final_result")+ if not isinstance(final_result, dict):+ return None+ response_content = final_result.get("response_content")+ if not isinstance(response_content, str) or not response_content:+ return None+ response_content_type = _normalize_response_content_type(final_result)+ if response_content_type is None:+ return None+ if not route.get("session_id") or not route.get("channel_id"):+ return None+ resolved_cid = str(safe_chunk.get("conversation_id") or conversation_id)++ push = WebSocketGatewayPushTransport()+ todo_path: Path | None = None+ try:+ todo_path = deepresearch_todo_path(+ session_id=str(route["session_id"]),+ workspace_key=str(route.get("workspace_key") or "default"),+ )+ except Exception as exc: # pylint: disable=broad-exception-caught+ logger.warning(+ "[deepresearch_stream] resolve todo path failed type=%s",+ type(exc).__name__,+ )++ async def send(payload: dict[str, Any]) -> bool:+ try:+ safe_payload = _redact_json_value(payload, secrets)+ except _StreamProtocolInvalid:+ return False+ if not isinstance(safe_payload, dict):+ return False+ if todo_path is not None and safe_payload.get("event_type") == "task.update":+ try:+ persist_deepresearch_task_update(safe_payload, todo_path=todo_path)+ except Exception as exc: # pylint: disable=broad-exception-caught+ logger.warning(+ "[deepresearch_stream] persist todo failed type=%s",+ type(exc).__name__,+ )+ try:+ await push.send_push(+ {+ "request_id": route.get("request_id", ""),+ "channel_id": route["channel_id"],+ "session_id": route["session_id"],+ "payload": safe_payload,+ "is_complete": False,+ }+ )+ return True+ except Exception as exc: # pylint: disable=broad-exception-caught+ logger.warning(+ "[deepresearch_stream] race-completed push failed type=%s",+ type(exc).__name__,+ )+ return False++ # 进度收尾:消费循环已被取消,原 RouterState 不可达;合成路由状态+ # 关闭"最终报告处理"子任务并把全阶段标记完成,防止前端进度列表+ # 停留在"报告交付"转圈。+ state = RouterState(current_stage=4, final_report_started=True)+ for payload in complete_final_report_processing(state):+ await send(payload)+ for payload in advance_stage(state, 4, complete=True):+ await send(payload)++ html_style_status = None+ html_style_phase = None+ html_style_reason_code = None+ try:+ if response_content_type == "text/html":+ artifacts = {+ "html": await _write_report_html(response_content, file_name)+ }+ else:+ artifact_result = await _write_report_artifacts_stream(+ final_result,+ file_name,+ resolved_cid,+ _normalize_citation_artifacts(safe_chunk),+ )+ if isinstance(artifact_result, tuple) and len(artifact_result) == 4:+ (+ artifacts,+ html_style_status,+ html_style_phase,+ html_style_reason_code,+ ) = artifact_result+ elif isinstance(artifact_result, tuple):+ artifacts, html_style_status = artifact_result+ html_style_phase = None+ html_style_reason_code = None+ else:+ # Preserve compatibility with private test doubles and older callers.+ artifacts = artifact_result+ html_style_phase = None+ html_style_reason_code = None+ except Exception as exc: # pylint: disable=broad-exception-caught+ logger.warning(+ "[deepresearch_stream] race-completed artifact write failed type=%s",+ type(exc).__name__,+ )+ return None+ artifact_mime_types = {"md": "text/markdown", "html": "text/html"}+ files = [+ {+ "path": value,+ "name": Path(value).name,+ "mime_type": artifact_mime_types.get(key),+ }+ for key, value in artifacts.items()+ if key in artifact_mime_types+ ]+ if not files:+ return None+ file_payload: dict[str, Any] = {"event_type": "chat.file", "files": files}+ file_metadata: dict[str, Any] = {}+ if response_content_type == "text/markdown" and "md" in artifacts:+ markdown_index = list(artifacts).index("md")+ bundle = _build_related_artifact_bundle(safe_chunk, markdown_index)+ if bundle:+ file_metadata["artifactBundle"] = bundle+ if html_style_status in {"applied", "fallback"}:+ file_metadata["htmlStyleStatus"] = html_style_status+ if (+ html_style_status == "fallback"+ and isinstance(html_style_phase, str)+ and isinstance(html_style_reason_code, str)+ ):+ file_metadata["htmlStylePhase"] = html_style_phase+ file_metadata["htmlStyleReasonCode"] = html_style_reason_code+ if file_metadata:+ file_payload["metadata"] = file_metadata+ if not await send(file_payload):+ return None+ logger.warning(+ "[deepresearch_stream] race-completed report delivered "+ "conversation_id=%s",+ resolved_cid,+ )+ outcome: dict[str, Any] = {+ "status": "completed",+ "conversation_id": resolved_cid,+ "report_delivered": True,+ "race_completed": True,+ }+ if html_style_status in {"applied", "fallback"}:+ outcome["html_style_status"] = html_style_status+ return outcome+++async def salvage_deepresearch_report(+ *, conversation_id: str, file_name: str+) -> dict[str, Any] | None:+ """修复7(execute 认领侧入口):无快照可恢复但报告已落盘时止损交付。++ 供 deepresearch_execute 在认领失败(probe 无可恢复快照)时调用:+ 报告在收尾阶段被停或交付前崩溃的场景下,直接交付已生成的报告,+ 不重跑研究。返回 completed outcome 或 None(不可止损)。+ """+ route = _get_route()+ push = WebSocketGatewayPushTransport()++ # 与 stream 交付路径同口径脱敏(_deliver_race_completed_report 使用+ # _config_secret_values(config)):止损交付的报告全文同样经 WebSocket+ # 推送,若报告内容(如搜索结果引用)携带与 config secret 匹配的子串,+ # 不脱敏会直接外泄。secrets 计算失败回退空表——止损交付本身不因此+ # 中断(与改前行为一致),仅失去脱敏。+ try:+ salvage_config = _build_deepresearch_request_config(+ interactive_ask=True,+ service_id=str(route.get("service_id") or "default"),+ agent_id=str(route.get("agent_id") or "default"),+ )+ salvage_secrets = _config_secret_values(salvage_config)+ except Exception: # pylint: disable=broad-exception-caught+ salvage_secrets = ()++ async def send(payload: dict[str, Any]) -> bool:+ if not route.get("session_id") or not route.get("channel_id"):+ return False+ try:+ safe_payload = _redact_json_value(payload, salvage_secrets)+ except _StreamProtocolInvalid:+ return False+ if not isinstance(safe_payload, dict):+ return False+ try:+ await push.send_push(+ {+ "request_id": route.get("request_id", ""),+ "channel_id": route["channel_id"],+ "session_id": route["session_id"],+ "payload": safe_payload,+ "is_complete": False,+ }+ )+ return True+ except Exception as exc: # pylint: disable=broad-exception-caught+ logger.warning(+ "[deepresearch_stream] salvage push failed type=%s",+ type(exc).__name__,+ )+ return False++ return await _deliver_salvaged_report(+ route=route,+ conversation_id=conversation_id,+ file_name=file_name,+ send=send,+ reason="claim_without_checkpoint",+ )++async def _consume_stream(*,proc: Any,@@ -2409,10 +3396,22 @@ async def _consume_stream(else {})existing_state = _deepresearch_router_state_ctx.get()- state = (- existing_state- if isinstance(existing_state, RouterState)- else RouterState(+ # 停止续跑:阶段提示来自认领侧按被停止节点的推导,种子取 hint-1,+ # 使首个 resuming 帧恰好推进到 hint(之前的阶段已完成、hint 进行中)。+ stage_hint = (+ _deepresearch_stage_hint_ctx.get()+ if action == "resume" and node == "stopped"+ else None+ )+ if existing_state is not None and isinstance(existing_state, RouterState):+ state = existing_state+ elif stage_hint:+ state = RouterState(+ section_titles=dict(cached_titles),+ current_stage=stage_hint - 1,+ )+ else:+ state = RouterState(section_titles=dict(cached_titles),current_stage=(_RESUME_NODE_CURRENT_STAGE.get(node, 0)@@ -2423,7 +3422,6 @@ async def _consume_stream(action == "resume" and node == "user_feedback_processor"),)- )outcome_cid = conversation_idtodo_path: Path | None = Noneif route.get("session_id"):@@ -2545,6 +3543,7 @@ async def _consume_stream("interrupted","error","cancelled",+ "stopped",}if first_sdk_node_ns is None and not is_terminal:is_timed_node = str(chunk.get("agent") or "") in _TIMED_SDK_NODES@@ -2558,6 +3557,10 @@ async def _consume_stream(stage = 2elif action == "resume" and node == "user_feedback_processor":stage = 4+ elif action == "resume" and node == "stopped" and stage_hint:+ # 停止续跑:直接推进到被停止阶段,避免前端进度列表回退到+ # 第一步"研究主题澄清"转圈误导用户以为从头重跑。+ stage = stage_hintfor payload in advance_stage(state, stage):await send(payload)await send(@@ -2650,6 +3653,19 @@ async def _consume_stream(else "")if not response_content:+ # 修复7:completed 帧缺报告正文时先尝试止损交付已落盘的+ # raw_report.md(同一会话此前运行可能已产出报告)。+ salvage = await _deliver_salvaged_report(+ route=route,+ conversation_id=str(+ chunk.get("conversation_id") or outcome_cid+ ),+ file_name=file_name,+ send=send,+ reason="completed_missing_response_content",+ )+ if salvage is not None:+ return attach_terminal_timing(salvage, chunk)return attach_terminal_timing({"status": "error","conversation_id": chunk.get("conversation_id", outcome_cid),@@ -2806,7 +3822,34 @@ async def _consume_stream(if workflow_usage is not None:completed_outcome["workflow_llm_token_usage"] = workflow_usagereturn attach_terminal_timing(completed_outcome, chunk)+ if status_value == "stopped":+ # 优雅停止终态(正常路径由 CancelledError 分支处理;此处覆盖+ # 取消信号晚于子进程优雅退出的竞态)。checkpoint 已落盘,+ # 可用 resume --node stopped 从被停止节点继续,已完成节点不重跑。+ return attach_terminal_timing(+ {+ "status": "stopped",+ "conversation_id": str(+ chunk.get("conversation_id") or outcome_cid+ ),+ },+ chunk,+ )if status_value == "error":+ # 修复7:子进程异常终局但报告已落盘时止损交付——本类事故中+ # 20 分钟研究报告已写入 raw_report.md,resume 崩溃却向用户返+ # 回 empty_report,报告与用户双重损失。+ salvage = await _deliver_salvaged_report(+ route=route,+ conversation_id=str(+ chunk.get("conversation_id") or outcome_cid+ ),+ file_name=file_name,+ send=send,+ reason=str(chunk.get("error_code") or "workflow_error"),+ )+ if salvage is not None:+ return attach_terminal_timing(salvage, chunk)return attach_terminal_timing({"status": "error","conversation_id": chunk.get("conversation_id", outcome_cid),diff --git a/tests/unit_tests/agentserver/test_ask_user_validation.py b/tests/unit_tests/agentserver/test_ask_user_validation.pyindex 3f67b381c9..acab6b506a 100644--- a/tests/unit_tests/agentserver/test_ask_user_validation.py+++ b/tests/unit_tests/agentserver/test_ask_user_validation.py@@ -442,7 +442,6 @@ async def test_answered_structured_payload_can_opt_in_to_machine_state():],},},- "A",],)async def test_legacy_answer_representations_are_rejected(legacy_input):@@ -462,3 +461,29 @@ async def test_legacy_answer_representations_are_rejected(legacy_input):# Legacy / unparseable representations are treated as skipped (not# [INVALID_ARGUMENT]) to avoid misleading the LLM into fallback cascades.assert "未提供回答" in decision.tool_result++[email protected]("raw_input", ["继续", "A", " 稍等,我先补充一下背景 "])+async def test_parse_failed_raw_text_is_injected_into_history(raw_input):+ """修复点2:非结构化纯文本回复以原文注入 LLM 历史,不当"未答"丢弃。"""+ rail = StructuredAskUserRail()+ tc = _make_tool_call(+ {+ "query": "Choose",+ "questions": [+ {"question": "Which?", "header": "Choice", "options": []}+ ],+ }+ )++ decision = await rail.resolve_interrupt(MagicMock(), tc, raw_input)++ assert isinstance(decision, RejectResult)+ # 不是 [INVALID_ARGUMENT](工具没坏),也不是"未提供回答"(用户确实说话了)+ assert "[INVALID_ARGUMENT]" not in decision.tool_result+ assert "未提供回答" not in decision.tool_result+ # 用户原文进入历史,模型可据此推进+ assert "用户回复原文" in decision.tool_result+ assert raw_input.strip() in decision.tool_result+ assert "不要重复发起相同提问" in decision.tool_resultdiff --git a/tests/unit_tests/agentserver/test_deepresearch_execute_tool.py b/tests/unit_tests/agentserver/test_deepresearch_execute_tool.pyindex 8cf0efdb00..6ccc826048 100644--- a/tests/unit_tests/agentserver/test_deepresearch_execute_tool.py+++ b/tests/unit_tests/agentserver/test_deepresearch_execute_tool.py@@ -5,15 +5,21 @@ from __future__ import annotationsimport asyncioimport base64import json+import loggingimport pickleimport sqlite3+from contextlib import contextmanagerfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, Mock, patchimport pytest+from openjiuwen.core.foundation.llm import ToolMessagefrom openjiuwen.core.single_agent.interrupt.exception import ToolInterruptExceptionfrom openjiuwen.core.single_agent.rail.base import ToolCallInputs+from jiuwenswarm.agents.harness.common.rails import (+ deepresearch_execution_rail as dr,+)from jiuwenswarm.agents.harness.common.rails.deepresearch_execution_rail import (DEEPRESEARCH_EXECUTION_ALIAS_KEY,DEEPRESEARCH_EXECUTION_STATE_KEY,@@ -42,6 +48,25 @@ class _Model:self.invoke = AsyncMock(return_value=SimpleNamespace(content=content))[email protected](autouse=True)+def _disable_query_scan_by_default(monkeypatch):+ """修复9':默认把扫库认领打桩为未命中。++ 真实扫库会经 _resolve_skill_root 读开发机共享技能目录下的+ checkpointer.db,可能命中与本文件默认 query 相同的真实会话,+ 使既有认领失败用例变得机器相关。扫库专项用例在用例内显式+ 覆盖本桩(patch.object 后应用即覆盖)。stream action='start'+ 的认领兜底入口(_claim_start_snapshot)同理打桩——未打桩的+ 用例若放行到真实 stream 实现会真实读库。+ """+ monkeypatch.setattr(+ de, "_scan_resumable_checkpoint_by_query", Mock(return_value=None)+ )+ monkeypatch.setattr(+ dt, "_claim_start_snapshot", AsyncMock(return_value=None)+ )++def test_execution_rail_converts_before_stream_event_rail():assert DeepResearchExecutionRail.priority > JiuSwarmStreamEventRail.priority@@ -176,8 +201,13 @@ async def test_new_query_persists_request_report_type_before_sdk_start():@pytest.mark.asyncio-async def test_execute_claims_interrupted_conversation_with_cached_outline():- """传入 conversation_id 且缓存有大纲 → 跳过 start 重跑,直接呈现大纲审阅卡片。"""+async def test_execute_rejects_cached_outline_claim_without_checkpoint():+ """修复5:probe 未命中(无可恢复快照)时不得用残留缓存大纲假认领。++ 事故场景:图正常完结清快照后,内存大纲缓存残留,旧逻辑仍弹大纲卡,+ 用户确认后 resume 无快照可恢复而全新起跑并崩溃。新契约:probe=None+ 一律走认领失败 → 全新 id 从头执行。+ """outline = {"title": "智能家电竞争格局研究","sections": [@@ -185,10 +215,29 @@ async def test_execute_claims_interrupted_conversation_with_cached_outline():{"id": "2", "title": "主要玩家"},],}+ outcome = {+ "status": "error",+ "error_code": "runner_failed",+ "error": "boom",+ }route_token = dt.push_deepresearch_route("R1", "CH1", "S1")try:dt._cache_outline_json(dt._get_route(), "C-OLD", outline)- with patch.object(de, "_call_deepresearch_stream_impl", new=AsyncMock()) as stream:+ with (+ patch.object(+ de, "_probe_resumable_checkpoint", new=Mock(return_value=None)+ ),+ patch.object(+ de,+ "salvage_deepresearch_report",+ new=AsyncMock(return_value=None),+ ),+ patch.object(+ de,+ "_call_deepresearch_stream_impl",+ new=AsyncMock(return_value=json.dumps(outcome, ensure_ascii=False)),+ ) as stream,+ ):result, saved = await _invoke(conversation_id="C-OLD")finally:dt.reset_deepresearch_route(route_token)@@ -197,19 +246,115 @@ async def test_execute_claims_interrupted_conversation_with_cached_outline():with dt._OUTLINE_TITLE_CACHES_GUARD:dt._OUTLINE_TITLE_CACHES.clear()+ # 不得弹大纲卡:缓存大纲被拒绝,走全新起跑+ assert result["kind"] == "error"+ stream.assert_awaited_once()+ assert stream.await_args.kwargs["action"] == "start"+ new_cid = stream.await_args.kwargs["conversation_id"]+ assert new_cid and new_cid != "C-OLD"+ assert saved[-1]["phase"] == "error"+++async def test_execute_claims_outline_with_db_confirmed_cache_fallback():+ """修复5边界:db 确认 outline_interaction 可恢复中断但快照缺大纲 JSON+ → 允许缓存兜底补大纲(claim source=cache)。"""+ outline = {+ "title": "智能家电竞争格局研究",+ "sections": [+ {"id": "1", "title": "市场规模", "is_core_section": True, "description": "整体规模"},+ ],+ }+ probe = {"node": "outline_interaction"}+ route_token = dt.push_deepresearch_route("R1", "CH1", "S1")+ try:+ dt._cache_outline_json(dt._get_route(), "C-OLC", outline)+ with (+ patch.object(de, "_probe_resumable_checkpoint", new=Mock(return_value=probe)),+ patch.object(de, "_call_deepresearch_stream_impl", new=AsyncMock()) as stream,+ ):+ result, saved = await _invoke(conversation_id="C-OLC")+ finally:+ dt.reset_deepresearch_route(route_token)+ with dt._OUTLINE_JSON_CACHES_GUARD:+ dt._OUTLINE_JSON_CACHES.clear()+ with dt._OUTLINE_TITLE_CACHES_GUARD:+ dt._OUTLINE_TITLE_CACHES.clear()+assert result["kind"] == "interaction"stream.assert_not_awaited()final = saved[-1]assert final["phase"] == "wait_outline"- assert final["conversation_id"] == "C-OLD"- assert final["outline_presented"] is True+ assert final["conversation_id"] == "C-OLC"question = result["interaction"]["questions"][0]- assert [option["label"] for option in question["options"]] == [- "确认大纲,继续研究",- "需要修改",- ]assert "### P1: 市场规模(重点)" in question["preview"]["text"]- assert "### P2: 主要玩家" in question["preview"]["text"]+++async def test_execute_claim_failure_salvages_existing_report():+ """修复7:认领失败(无可恢复快照)但报告已落盘且主题一致 → 止损交付,+ 不重跑研究。"""+ salvage_outcome = {+ "status": "completed",+ "conversation_id": "C-SAL",+ "report_delivered": True,+ "salvaged_report": True,+ }+ with (+ patch.object(+ de, "_probe_resumable_checkpoint", new=Mock(return_value=None)+ ),+ patch.object(+ de,+ "salvage_deepresearch_report",+ new=AsyncMock(return_value=salvage_outcome),+ ) as salvage,+ patch.object(de, "_call_deepresearch_stream_impl", new=AsyncMock()) as stream,+ ):+ result, saved = await _invoke(conversation_id="C-SAL")++ salvage.assert_awaited_once()+ stream.assert_not_awaited()+ assert result["kind"] == "completed"+ assert "已成功生成并交付" in result["content"]+ assert saved[-1]["phase"] == "completed"+ assert saved[-1]["conversation_id"] == "C-SAL"+++async def test_execute_error_phase_salvages_existing_report():+ """修复7:error 相位死路(无可恢复快照)且主题一致 → 先止损交付报告。"""+ salvage_outcome = {+ "status": "completed",+ "conversation_id": "C-ERRS",+ "report_delivered": True,+ "salvaged_report": True,+ }+ state = {+ "schema_version": 1,+ "phase": "error",+ "revision": 1,+ "query": "研究智能家电竞争格局",+ "file_name": "智能家电报告",+ "conversation_id": "C-ERRS",+ }+ with (+ patch.object(+ de, "_probe_resumable_checkpoint", new=Mock(return_value=None)+ ),+ patch.object(+ de,+ "salvage_deepresearch_report",+ new=AsyncMock(return_value=salvage_outcome),+ ) as salvage,+ patch.object(de, "_call_deepresearch_stream_impl", new=AsyncMock()) as stream,+ ):+ result, saved = await _invoke(state=state, conversation_id="C-ERRS")++ salvage.assert_awaited_once()+ stream.assert_not_awaited()+ assert result["kind"] == "completed"+ assert saved[-1]["phase"] == "completed"@pytest.mark.asyncio@@ -243,6 +388,19 @@ def _encode_checkpoint_blob(value):return "__BYTES__:" + base64.b64encode(pickle.dumps(value)).decode("ascii")+_HOST_SESSION = "S-HOST"+++@contextmanager+def _host_route(session_id: str = _HOST_SESSION):+ """绑定与快照归属字段配套的宿主 route(probe/scan 认领校验依赖)。"""+ token = dt.push_deepresearch_route("R-OWN", "CH-OWN", session_id)+ try:+ yield+ finally:+ dt.reset_deepresearch_route(token)++def _write_checkpoint_db(root,conversation_id,@@ -251,23 +409,43 @@ def _write_checkpoint_db(node_status="__interrupt__",questions="",outline=None,+ exceptions=None,+ extra_pending=None,+ original_query="",+ host_session_id="",):data_dir = root / "data"data_dir.mkdir(exist_ok=True)connection = sqlite3.connect(str(data_dir / "checkpointer.db"))try:connection.execute(- "CREATE TABLE kv_store (key VARCHAR(255), value VARCHAR(4096))"- )- graph_state = SimpleNamespace(- pending_node={node: SimpleNamespace(status=node_status)}+ "CREATE TABLE IF NOT EXISTS kv_store"+ " (key VARCHAR(255), value VARCHAR(4096))")+ pending_node = {+ node: SimpleNamespace(+ status=node_status,+ exception=list(exceptions or []),+ )+ }+ for entry in extra_pending or ():+ pending_node[str(entry["node"])] = SimpleNamespace(+ status=str(entry.get("status") or "__interrupt__"),+ exception=list(entry.get("exceptions") or []),+ )+ graph_state = SimpleNamespace(pending_node=pending_node)search_context = {}+ if original_query:+ search_context["original_query"] = original_queryif questions:search_context["questions"] = questionsif outline is not None:search_context["current_outline"] = outline- workflow_state = {"global_state": {"search_context": search_context}}+ global_state: dict = {"search_context": search_context}+ if host_session_id:+ # SDK StartNode 白名单写入的会话 config(归属字段随快照落盘)+ global_state["config"] = {"host_session_id": host_session_id}+ workflow_state = {"global_state": global_state}connection.executemany("INSERT INTO kv_store (key, value) VALUES (?, ?)",[@@ -293,9 +471,13 @@ def test_probe_resumable_checkpoint_reads_feedback_stage(tmp_path):"C-FB",node="feedback_handler",questions="1. 重点研究哪些品类?\n第一问的补充限定\n\n2. 覆盖哪些市场?",+ host_session_id=_HOST_SESSION,)- with patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path)):+ with (+ patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path)),+ _host_route(),+ ):probe = dt._probe_resumable_checkpoint("C-FB")assert probe == {@@ -320,9 +502,13 @@ def test_probe_resumable_checkpoint_reads_outline_stage(tmp_path):node="outline_interaction",questions="1. 问题",outline=outline,+ host_session_id=_HOST_SESSION,)- with patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path)):+ with (+ patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path)),+ _host_route(),+ ):probe = dt._probe_resumable_checkpoint("C-OL")assert probe == {@@ -359,6 +545,43 @@ def test_probe_resumable_checkpoint_returns_none_without_resumable_interrupt(tmpassert dt._probe_resumable_checkpoint("C-ERR") is None+def test_probe_resumable_checkpoint_prefers_stop_snapshot_over_stale_interrupt(tmp_path):+ """停止快照优先于残留 interrupt:认领停止会话不再被拉回早期交互重弹卡。"""+ outline = SimpleNamespace(+ title="智能家电竞争格局研究",+ thought="先规模后玩家",+ sections=[+ SimpleNamespace(title="市场规模", is_core_section=True),+ ],+ )+ # 停止前的早期交互残留(stale interrupt)排在 pending_node 前部;+ # 若 interrupt 优先,会把已停止会话错认成大纲中断认领。+ _write_checkpoint_db(+ tmp_path,+ "C-STP",+ node="outline_interaction",+ node_status="__interrupt__",+ questions="1. 重点研究哪些品类?",+ outline=outline,+ host_session_id=_HOST_SESSION,+ extra_pending=[+ {+ "node": "report_writing",+ "status": "__error__",+ "exceptions": [RuntimeError("deepresearch task stopped by user")],+ }+ ],+ )++ with (+ patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path)),+ _host_route(),+ ):+ probe = dt._probe_resumable_checkpoint("C-STP")++ assert probe == {"node": "report_writing", "stopped": True}++@pytest.mark.asyncioasync def test_execute_claims_feedback_stage_from_checkpoint_probe():"""checkpointer.db 探测到停研究问题阶段 → 出反馈卡,state 进入 wait_feedback。"""@@ -458,91 +681,723 @@ async def test_execute_restarts_fresh_when_checkpoint_lacks_questions():@pytest.mark.asyncio-async def test_invalid_option_generation_retries_then_keeps_free_text_questions():- questions = ["重点研究哪些品类?", "覆盖哪些市场?"]- outcome = {- "status": "interrupted",- "conversation_id": "conversation-1",- "node_id": "feedback_handler",- "marker": {"questions": "\n".join(questions)},+async def test_execute_claims_stopped_snapshot_and_resumes_stopped_node():+ """probe 报告停止快照且主题一致 → 不弹交互卡直通 resume node='stopped'。"""+ probe = {"node": "report_writing", "stopped": True}+ completed = {+ "status": "completed",+ "conversation_id": "C-STP",+ "report_delivered": True,}- model = _Model("not-json")-- with patch.object(- de,- "_call_deepresearch_stream_impl",- new=AsyncMock(return_value=json.dumps(outcome, ensure_ascii=False)),+ state = {+ "schema_version": 1,+ "phase": "new",+ "revision": 0,+ "query": "研究智能家电竞争格局",+ "file_name": "智能家电报告",+ "conversation_id": "C-STP",+ "requested_report_type": "brief",+ }+ with (+ patch.object(+ de, "_probe_resumable_checkpoint", new=Mock(return_value=probe)+ ) as probe_mock,+ patch.object(+ de,+ "_call_deepresearch_stream_impl",+ new=AsyncMock(return_value=json.dumps(completed, ensure_ascii=False)),+ ) as stream,):- result, _ = await _invoke(model=model)+ result, saved = await _invoke(+ state=state, query="研究智能家电竞争格局"+ )- assert [item["question"] for item in result["interaction"]["questions"]] == questions- assert [item["options"] for item in result["interaction"]["questions"]] == [[], []]- assert model.invoke.await_count == 2+ probe_mock.assert_called_once_with("C-STP")+ stream.assert_awaited_once()+ assert stream.await_args.kwargs["action"] == "resume"+ assert stream.await_args.kwargs["node"] == "stopped"+ assert stream.await_args.kwargs["conversation_id"] == "C-STP"+ assert result["kind"] == "completed"+ assert saved[0]["phase"] == "resuming_stopped"+ assert saved[-1]["phase"] == "completed"@pytest.mark.asyncio-async def test_option_generation_timeout_keeps_free_text_questions():- questions = ["重点研究哪些品类?", "覆盖哪些市场?"]+async def test_execute_stopped_snapshot_with_new_topic_restarts_fresh():+ """停止快照 + 用户换主题 → 不认领旧会话、不复活旧大纲缓存,全新 id 研究新主题。"""+ probe = {"node": "report_writing", "stopped": True}+ outline = {+ "title": "智能家电竞争格局研究",+ "sections": [+ {"id": "1", "title": "市场规模", "is_core_section": True},+ ],+ }outcome = {- "status": "interrupted",- "conversation_id": "conversation-1",- "node_id": "feedback_handler",- "marker": {"questions": "\n".join(questions)},+ "status": "error",+ "error_code": "runner_failed",+ "error": "boom",+ }+ state = {+ "schema_version": 1,+ "phase": "new",+ "revision": 0,+ "query": "研究智能家电竞争格局",+ "file_name": "智能家电报告",+ "conversation_id": "C-STP",+ "requested_report_type": "brief",}+ route_token = dt.push_deepresearch_route("R1", "CH1", "S4")+ try:+ dt._cache_outline_json(dt._get_route(), "C-STP", outline)+ with (+ patch.object(+ de,+ "_probe_resumable_checkpoint",+ new=Mock(return_value=probe),+ ),+ patch.object(+ de,+ "_call_deepresearch_stream_impl",+ new=AsyncMock(return_value=json.dumps(outcome, ensure_ascii=False)),+ ) as stream,+ ):+ result, saved = await _invoke(+ state=state, query="研究新能源车市场竞争格局"+ )+ finally:+ dt.reset_deepresearch_route(route_token)+ with dt._OUTLINE_JSON_CACHES_GUARD:+ dt._OUTLINE_JSON_CACHES.clear()+ with dt._OUTLINE_TITLE_CACHES_GUARD:+ dt._OUTLINE_TITLE_CACHES.clear()- async def never_returns(*_args, **_kwargs):- await asyncio.Event().wait()+ # 不弹旧主题的任何交互卡;换全新 id 且以新主题 start。+ assert result["kind"] == "error"+ stream.assert_awaited_once()+ assert stream.await_args.kwargs["action"] == "start"+ assert stream.await_args.kwargs["query"] == "研究新能源车市场竞争格局"+ new_cid = stream.await_args.kwargs["conversation_id"]+ assert new_cid and new_cid != "C-STP"- model = SimpleNamespace(invoke=never_returns)- with (- patch.object(- de,- "_OPTIONS_GENERATION_TIMEOUT_SECONDS",- 0.01,- ),- patch.object(- de,- "_call_deepresearch_stream_impl",- new=AsyncMock(return_value=json.dumps(outcome, ensure_ascii=False)),- ),- ):- result, saved = await asyncio.wait_for(_invoke(model=model), timeout=0.2)- assert result["kind"] == "interaction"- assert [item["question"] for item in result["interaction"]["questions"]] == questions- assert [item["options"] for item in result["interaction"]["questions"]] == [[], []]- assert saved[-1]["phase"] == "wait_feedback"+def test_is_stop_requested_exception_recognizes_cancelled_error():+ """SDK 取消路径写入的 __error__+CancelledError 快照按可续跑停止快照识别。"""+ assert dt._is_stop_requested_exception(asyncio.CancelledError()) is True+ assert dt._is_stop_requested_exception(RuntimeError("普通失败")) is False+ assert dt._is_stop_requested_exception("not an exception") is False-async def test_option_generation_preserves_model_defaults_and_completion_budget():- questions = ["重点研究哪些品类?", "覆盖哪些市场?", "报告用于什么决策?"]- model = _Model(_option_payload(*questions))- model.model_config = SimpleNamespace(model_name="glm-5.2")- context = de.DeepResearchExecutionContext(- tool_call_id="call-1",- state=None,- user_input=None,- model=model,- agent_id="jiuwenswarm",- save_state=lambda _value: None,+def test_probe_resumable_checkpoint_recognizes_cancelled_snapshot(tmp_path):+ """取消落盘的 __error__+CancelledError 快照 → stopped=True,认领后可直通续跑。"""+ _write_checkpoint_db(+ tmp_path,+ "C-CXL",+ node="report_writing",+ node_status="__error__",+ exceptions=[asyncio.CancelledError()],+ host_session_id=_HOST_SESSION,)- options = await de._generate_options(context, "研究智能家电竞争格局", questions)+ with (+ patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path)),+ _host_route(),+ ):+ probe = dt._probe_resumable_checkpoint("C-CXL")- assert all(len(item) == 2 for item in options)- messages = model.invoke.await_args.args[0]- kwargs = model.invoke.await_args.kwargs- assert kwargs["max_tokens"] == 2048- assert "extra_body" not in kwargs- prompt = messages[0]["content"]- assert "description 不超过 50 字" in prompt- assert "不得输出分析或推理过程" in prompt+ assert probe == {"node": "report_writing", "stopped": True}-def test_option_description_is_truncated_without_rejecting_valid_options():- payload = json.dumps(- {+def test_scan_resumable_checkpoint_by_query_claims_stopped_snapshot(tmp_path):+ """修复9':LLM 幻觉 cid 时按 query 扫库 → 认领到同主题的停止快照。"""+ _write_checkpoint_db(+ tmp_path,+ "C-REAL",+ node="report_writing",+ node_status="__error__",+ exceptions=[RuntimeError("deepresearch task stopped by user")],+ original_query="研究智能家电竞争格局",+ host_session_id=_HOST_SESSION,+ )++ with (+ patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path)),+ _host_route(),+ ):+ scan = dt._scan_resumable_checkpoint_by_query("研究智能家电竞争格局")++ assert scan == {+ "conversation_id": "C-REAL",+ "node": "report_writing",+ "stopped": True,+ }+++def test_scan_resumable_checkpoint_by_query_claims_interrupt_with_cards(tmp_path):+ """修复9':扫库命中 interrupt → 附带回弹卡字段(questions/outline_json)。"""+ outline = SimpleNamespace(+ title="智能家电竞争格局研究",+ thought="先规模后玩家",+ sections=[SimpleNamespace(title="市场规模", is_core_section=True)],+ )+ _write_checkpoint_db(+ tmp_path,+ "C-INT",+ node="outline_interaction",+ questions="1. 重点研究哪些品类?",+ outline=outline,+ original_query="研究智能家电竞争格局",+ host_session_id=_HOST_SESSION,+ )++ with (+ patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path)),+ _host_route(),+ ):+ scan = dt._scan_resumable_checkpoint_by_query("研究智能家电竞争格局")++ assert scan is not None+ assert scan["conversation_id"] == "C-INT"+ assert scan["node"] == "outline_interaction"+ assert scan.get("stopped") is not True+ assert scan["questions"] == ["1. 重点研究哪些品类?"]+ assert scan["outline_json"]["sections"] == [+ {"title": "市场规模", "is_core_section": True}+ ]+++def test_scan_resumable_checkpoint_by_query_rejects_topic_change(tmp_path):+ """修复9':换主题不认领旧会话;original_query 缺失同样不认领。"""+ _write_checkpoint_db(+ tmp_path,+ "C-REAL",+ node="report_writing",+ node_status="__error__",+ exceptions=[asyncio.CancelledError()],+ original_query="研究智能家电竞争格局",+ )+ # 第二个会话快照缺失 original_query(更早版本落盘)+ _write_checkpoint_db(+ tmp_path,+ "C-NOQ",+ node="feedback_handler",+ questions="1. 问题",+ )++ with patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path)):+ assert (+ dt._scan_resumable_checkpoint_by_query("研究新能源车市场竞争格局")+ is None+ )+ assert dt._scan_resumable_checkpoint_by_query("") is None+++def test_scan_resumable_checkpoint_by_query_prefers_latest_match(tmp_path):+ """修复9':rowid 倒序,同主题多快照时认领最新落盘的会话。"""+ for cid in ("C-OLD", "C-NEW"):+ _write_checkpoint_db(+ tmp_path,+ cid,+ node="report_writing",+ node_status="__error__",+ exceptions=[asyncio.CancelledError()],+ original_query="研究智能家电竞争格局",+ host_session_id=_HOST_SESSION,+ )++ with (+ patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path)),+ _host_route(),+ ):+ scan = dt._scan_resumable_checkpoint_by_query("研究智能家电竞争格局")++ assert scan == {+ "conversation_id": "C-NEW",+ "node": "report_writing",+ "stopped": True,+ }+++def test_scan_resumable_checkpoint_by_query_ignores_unresumable(tmp_path):+ """修复9':无可续跑状态的快照(正常完结残留)不参与认领。"""+ _write_checkpoint_db(+ tmp_path,+ "C-DONE",+ node="report_writing",+ node_status="__success__",+ original_query="研究智能家电竞争格局",+ )++ with patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path)):+ assert (+ dt._scan_resumable_checkpoint_by_query("研究智能家电竞争格局") is None+ )+++def test_probe_rejects_cross_session_snapshot(tmp_path, caplog):+ """归属校验:快照归属别家宿主会话 → 拒绝认领并记观察哨日志。"""+ _write_checkpoint_db(+ tmp_path,+ "C-FOREIGN",+ node="feedback_handler",+ questions="1. 问题",+ host_session_id="S-OTHER",+ )++ with (+ patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path)),+ _host_route(),+ caplog.at_level(logging.WARNING),+ ):+ assert dt._probe_resumable_checkpoint("C-FOREIGN") is None++ assert any(+ "ownership rejected" in record.message+ and "reason=ownership_mismatch" in record.message+ and "C-FOREIGN" in record.message+ for record in caplog.records+ )+++def test_probe_rejects_legacy_snapshot_without_owner(tmp_path, caplog):+ """归属校验:升级前落盘的旧快照无归属字段 → 一律拒绝(拍板)。"""+ _write_checkpoint_db(+ tmp_path,+ "C-LEGACY",+ node="feedback_handler",+ questions="1. 问题",+ )++ with (+ patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path)),+ _host_route(),+ caplog.at_level(logging.WARNING),+ ):+ assert dt._probe_resumable_checkpoint("C-LEGACY") is None++ assert any(+ "reason=missing_owner" in record.message for record in caplog.records+ )+++def test_probe_rejects_when_requester_unverifiable(tmp_path):+ """归属校验:请求未绑定宿主会话(无 session_id)→ 严格拒绝认领。"""+ _write_checkpoint_db(+ tmp_path,+ "C-ANY",+ node="feedback_handler",+ questions="1. 问题",+ host_session_id=_HOST_SESSION,+ )++ with patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path)):+ assert dt._probe_resumable_checkpoint("C-ANY") is None+++def test_scan_skips_foreign_snapshot_and_claims_own(tmp_path, caplog):+ """归属校验:同 query 命中别家会话快照 → 跳过并继续认领本会话快照。++ 复现实机事故形态:新会话跑同主题,扫库先撞上别家(或陈旧)快照,+ 必须跳过它继续扫,而不是误认领。+ """+ # 先落本会话快照(rowid 较小),再落别家快照(rowid 较大 → 扫库先命中)+ _write_checkpoint_db(+ tmp_path,+ "C-OWN",+ node="report_writing",+ node_status="__error__",+ exceptions=[asyncio.CancelledError()],+ original_query="研究智能家电竞争格局",+ host_session_id=_HOST_SESSION,+ )+ _write_checkpoint_db(+ tmp_path,+ "C-FOREIGN",+ node="report_writing",+ node_status="__error__",+ exceptions=[asyncio.CancelledError()],+ original_query="研究智能家电竞争格局",+ host_session_id="S-OTHER",+ )++ with (+ patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path)),+ _host_route(),+ caplog.at_level(logging.WARNING),+ ):+ scan = dt._scan_resumable_checkpoint_by_query("研究智能家电竞争格局")++ assert scan is not None+ assert scan["conversation_id"] == "C-OWN"+ assert any(+ "reason=ownership_mismatch" in record.message+ and "C-FOREIGN" in record.message+ for record in caplog.records+ )+++def test_scan_returns_none_when_no_candidate_owned(tmp_path, caplog):+ """归属校验:候选全为别家/旧快照 → 不认领任何对象,退回全新起跑。"""+ _write_checkpoint_db(+ tmp_path,+ "C-FOREIGN",+ node="report_writing",+ node_status="__error__",+ exceptions=[asyncio.CancelledError()],+ original_query="研究智能家电竞争格局",+ host_session_id="S-OTHER",+ )+ _write_checkpoint_db(+ tmp_path,+ "C-LEGACY",+ node="report_writing",+ node_status="__error__",+ exceptions=[asyncio.CancelledError()],+ original_query="研究智能家电竞争格局",+ )++ with (+ patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path)),+ _host_route(),+ caplog.at_level(logging.WARNING),+ ):+ assert dt._scan_resumable_checkpoint_by_query("研究智能家电竞争格局") is None++ reasons = {+ "reason=ownership_mismatch",+ "reason=missing_owner",+ }+ logged = {record.message for record in caplog.records}+ assert any(reason in message for message in logged for reason in reasons)+++def test_build_request_config_injects_host_session_id_from_route():+ """供给侧:config frame 随 route 携带宿主会话归属标识。"""+ with (+ patch.object(dt, "get_task_env_overlay", return_value=None),+ patch.object(dt, "build_effective_env_overlay", return_value={}),+ patch.object(dt, "_build_deepresearch_config", return_value={}),+ _host_route("S-CFG"),+ ):+ config = dt._build_deepresearch_request_config(interactive_ask=True)++ assert config["DEEPSEARCH_HOST_SESSION_ID"] == "S-CFG"+ assert config["DEEPSEARCH_HITL"] == "true"+++def test_build_request_config_omits_host_session_id_without_route():+ """供给侧:未绑定 route 时不注入归属键(行为与旧版 config frame 兼容)。"""+ with (+ patch.object(dt, "get_task_env_overlay", return_value=None),+ patch.object(dt, "build_effective_env_overlay", return_value={}),+ patch.object(dt, "_build_deepresearch_config", return_value={}),+ ):+ config = dt._build_deepresearch_request_config(interactive_ask=False)++ assert "DEEPSEARCH_HOST_SESSION_ID" not in config+ assert config["DEEPSEARCH_HITL"] == "false"+++async def test_execute_hallucinated_cid_claims_stopped_conversation_by_scan(tmp_path):+ """修复9':LLM 幻觉 cid → probe 落空但扫库按主题命中停止快照,认领直通续跑。"""+ _write_checkpoint_db(+ tmp_path,+ "C-REAL",+ node="report_writing",+ node_status="__error__",+ exceptions=[RuntimeError("deepresearch task stopped by user")],+ original_query="研究智能家电竞争格局",+ host_session_id=_HOST_SESSION,+ )+ completed = {+ "status": "completed",+ "conversation_id": "C-REAL",+ "report_delivered": True,+ }+ state = {+ "schema_version": 1,+ "phase": "new",+ "revision": 0,+ "query": "研究智能家电竞争格局",+ "file_name": "智能家电报告",+ "conversation_id": "C-HALLUCINATED",+ "requested_report_type": "brief",+ }+ with (+ _host_route(),+ patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path)),+ patch.object(+ de,+ "_scan_resumable_checkpoint_by_query",+ new=dt._scan_resumable_checkpoint_by_query,+ ),+ patch.object(de, "_call_deepresearch_stream_impl",+ new=AsyncMock(return_value=json.dumps(completed, ensure_ascii=False))) as stream,+ ):+ result, saved = await _invoke(+ state=state, query="研究智能家电竞争格局"+ )++ stream.assert_awaited_once()+ assert stream.await_args.kwargs["action"] == "resume"+ assert stream.await_args.kwargs["node"] == "stopped"+ assert stream.await_args.kwargs["conversation_id"] == "C-REAL"+ assert result["kind"] == "completed"+ assert saved[0]["phase"] == "resuming_stopped"+ assert saved[0]["conversation_id"] == "C-REAL"+++async def test_execute_hallucinated_cid_scan_miss_starts_fresh(tmp_path):+ """修复9':扫库也无同主题快照 → 换全新 id 从头执行(不复用幻觉 cid)。"""+ _write_checkpoint_db(+ tmp_path,+ "C-OTHER",+ node="report_writing",+ node_status="__error__",+ exceptions=[asyncio.CancelledError()],+ original_query="研究智能家电竞争格局",+ )+ outcome = {+ "status": "error",+ "error_code": "runner_failed",+ "error": "boom",+ }+ route_token = dt.push_deepresearch_route("R1", "CH1", "S9")+ try:+ with (+ patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path)),+ patch.object(de, "_call_deepresearch_stream_impl",+ new=AsyncMock(return_value=json.dumps(outcome, ensure_ascii=False))) as stream,+ ):+ result, saved = await _invoke(+ query="研究新能源车市场竞争格局",+ conversation_id="C-HALLUCINATED",+ )+ finally:+ dt.reset_deepresearch_route(route_token)++ assert result["kind"] == "error"+ assert saved[-1]["phase"] == "error"+ stream.assert_awaited_once()+ assert stream.await_args.kwargs["action"] == "start"+ new_cid = stream.await_args.kwargs["conversation_id"]+ assert new_cid and new_cid != "C-HALLUCINATED"+++async def test_execute_hallucinated_cid_scan_claims_outline_interaction(tmp_path):+ """修复9':扫库命中 outline_interaction → 主题一致即回弹大纲审阅卡。"""+ outline = SimpleNamespace(+ title="智能家电竞争格局研究",+ thought="先规模后玩家",+ sections=[SimpleNamespace(title="市场规模", is_core_section=True)],+ )+ _write_checkpoint_db(+ tmp_path,+ "C-REAL",+ node="outline_interaction",+ questions="1. 重点研究哪些品类?",+ outline=outline,+ original_query="研究智能家电竞争格局",+ host_session_id=_HOST_SESSION,+ )+ state = {+ "schema_version": 1,+ "phase": "new",+ "revision": 0,+ "query": "研究智能家电竞争格局",+ "file_name": "智能家电报告",+ "conversation_id": "C-HALLUCINATED",+ "requested_report_type": "brief",+ }+ with (+ _host_route(),+ patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path)),+ patch.object(+ de,+ "_scan_resumable_checkpoint_by_query",+ new=dt._scan_resumable_checkpoint_by_query,+ ),+ patch.object(de, "_call_deepresearch_stream_impl", new=AsyncMock()) as stream,+ ):+ result, saved = await _invoke(+ state=state, query="研究智能家电竞争格局"+ )++ stream.assert_not_awaited()+ assert result["kind"] == "interaction"+ final = saved[-1]+ assert final["phase"] == "wait_outline"+ assert final["conversation_id"] == "C-REAL"+ assert final["outline_presented"] is True+++async def test_execute_hallucinated_cid_scan_salvages_report(tmp_path):+ """修复9':扫库未命中可续跑快照,但同主题报告已落盘 → 以扫出的 cid 止损交付。++ 扫库要求 original_query 严格一致才认领;报告止损场景中快照已被清理,+ 无从扫出 cid,salvage 仍以入参 cid 定位(修复7 语义不变)。+ """+ salvage_outcome = {+ "status": "completed",+ "conversation_id": "C-SAL",+ "report_delivered": True,+ "salvaged_report": True,+ }+ with (+ patch.object(dt, "_resolve_skill_root", return_value=""),+ patch.object(+ de,+ "salvage_deepresearch_report",+ new=AsyncMock(return_value=salvage_outcome),+ ) as salvage,+ patch.object(de, "_call_deepresearch_stream_impl", new=AsyncMock()) as stream,+ ):+ result, saved = await _invoke(conversation_id="C-SAL")++ salvage.assert_awaited_once()+ assert salvage.await_args.kwargs["conversation_id"] == "C-SAL"+ stream.assert_not_awaited()+ assert result["kind"] == "completed"+ assert saved[-1]["phase"] == "completed"+ assert saved[-1]["conversation_id"] == "C-SAL"+++async def test_execute_claim_failure_logs_warning_and_starts_fresh(caplog):+ """历史会话 checkpoint 探测失败 → 记 warning 且换全新 id 从头执行。"""+ outcome = {+ "status": "error",+ "error_code": "runner_failed",+ "error": "boom",+ }+ state = {+ "schema_version": 1,+ "phase": "new",+ "revision": 0,+ "query": "研究智能家电竞争格局",+ "file_name": "智能家电报告",+ "conversation_id": "C-GONE",+ "requested_report_type": "brief",+ }+ with (+ patch.object(+ de, "_probe_resumable_checkpoint", new=Mock(return_value=None)+ ) as probe_mock,+ patch.object(+ de,+ "_call_deepresearch_stream_impl",+ new=AsyncMock(return_value=json.dumps(outcome, ensure_ascii=False)),+ ) as stream,+ ):+ with caplog.at_level("WARNING", logger=de.logger.name):+ result, _saved = await _invoke(+ state=state, query="研究智能家电竞争格局"+ )++ probe_mock.assert_called_once_with("C-GONE")+ stream.assert_awaited_once()+ assert stream.await_args.kwargs["action"] == "start"+ new_cid = stream.await_args.kwargs["conversation_id"]+ assert new_cid and new_cid != "C-GONE"+ assert result["kind"] == "error"+ warnings = [+ record+ for record in caplog.records+ if record.levelno == 30 and "claim failed" in record.getMessage()+ ]+ assert warnings, "认领失败应记录可观测的 warning 日志"+ assert "C-GONE" in warnings[0].getMessage()+++async def test_invalid_option_generation_retries_then_keeps_free_text_questions():+ questions = ["重点研究哪些品类?", "覆盖哪些市场?"]+ outcome = {+ "status": "interrupted",+ "conversation_id": "conversation-1",+ "node_id": "feedback_handler",+ "marker": {"questions": "\n".join(questions)},+ }+ model = _Model("not-json")++ with patch.object(+ de,+ "_call_deepresearch_stream_impl",+ new=AsyncMock(return_value=json.dumps(outcome, ensure_ascii=False)),+ ):+ result, _ = await _invoke(model=model)++ assert [item["question"] for item in result["interaction"]["questions"]] == questions+ assert [item["options"] for item in result["interaction"]["questions"]] == [[], []]+ assert model.invoke.await_count == 2+++async def test_option_generation_timeout_keeps_free_text_questions():+ questions = ["重点研究哪些品类?", "覆盖哪些市场?"]+ outcome = {+ "status": "interrupted",+ "conversation_id": "conversation-1",+ "node_id": "feedback_handler",+ "marker": {"questions": "\n".join(questions)},+ }++ async def never_returns(*_args, **_kwargs):+ await asyncio.Event().wait()++ model = SimpleNamespace(invoke=never_returns)+ with (+ patch.object(+ de,+ "_OPTIONS_GENERATION_TIMEOUT_SECONDS",+ 0.01,+ ),+ patch.object(+ de,+ "_call_deepresearch_stream_impl",+ new=AsyncMock(return_value=json.dumps(outcome, ensure_ascii=False)),+ ),+ ):+ result, saved = await asyncio.wait_for(_invoke(model=model), timeout=0.2)++ assert result["kind"] == "interaction"+ assert [item["question"] for item in result["interaction"]["questions"]] == questions+ assert [item["options"] for item in result["interaction"]["questions"]] == [[], []]+ assert saved[-1]["phase"] == "wait_feedback"+++async def test_option_generation_preserves_model_defaults_and_completion_budget():+ questions = ["重点研究哪些品类?", "覆盖哪些市场?", "报告用于什么决策?"]+ model = _Model(_option_payload(*questions))+ model.model_config = SimpleNamespace(model_name="glm-5.2")+ context = de.DeepResearchExecutionContext(+ tool_call_id="call-1",+ state=None,+ user_input=None,+ model=model,+ agent_id="jiuwenswarm",+ save_state=lambda _value: None,+ )++ options = await de._generate_options(context, "研究智能家电竞争格局", questions)++ assert all(len(item) == 2 for item in options)+ messages = model.invoke.await_args.args[0]+ kwargs = model.invoke.await_args.kwargs+ assert kwargs["max_tokens"] == 2048+ assert "extra_body" not in kwargs+ prompt = messages[0]["content"]+ assert "description 不超过 50 字" in prompt+ assert "不得输出分析或推理过程" in prompt+++def test_option_description_is_truncated_without_rejecting_valid_options():+ payload = json.dumps(+ {"items": [{"question_index": 0,@@ -1012,42 +1867,238 @@ async def test_inflight_replay_fails_closed_without_duplicate_sdk_call():"conversation_id": "conversation-1","revision": 4,}- with patch.object(de, "_call_deepresearch_stream_impl", new=AsyncMock()) as stream:- result, _ = await _invoke(state=state, user_input={"status": "answered"})+ with patch.object(de, "_call_deepresearch_stream_impl", new=AsyncMock()) as stream:+ result, _ = await _invoke(state=state, user_input={"status": "answered"})++ assert result["kind"] == "error"+ assert result["error_code"] == "execution_uncertain"+ stream.assert_not_awaited()+++async def test_cancelled_feedback_stops_without_resuming_sdk():+ state = {+ "schema_version": 1,+ "phase": "wait_feedback",+ "query": "q",+ "file_name": "r",+ "conversation_id": "conversation-1",+ "questions": ["继续吗?"],+ "revision": 3,+ }+ with patch.object(de, "_call_deepresearch_stream_impl", new=AsyncMock()) as stream:+ result, saved = await _invoke(+ state=state,+ user_input={"status": "cancelled", "answers": []},+ )++ assert result["kind"] == "cancelled"+ assert saved[-1]["phase"] == "cancelled"+ stream.assert_not_awaited()+++async def test_cancelled_during_sdk_window_translates_to_stopped_without_error_overwrite():+ """修复点3.1回归:取消落在 SDK 窗口时只落 stopped 终态。++ 旧的双守卫串联结构中,守卫#1 的转译结果(无 status 字段)会被+ 守卫#2 内的 _handle_outcome 误判为无效 outcome,在同一 revision+ 上追加 error 覆盖写(生产日志 phase=new rev=4 与 phase=error rev=4+ 同毫秒双写的根因)。单守卫重构后 saved 序列为 resuming_feedback →+ new,绝无 error 帧。+ """+ state = {+ "schema_version": 1,+ "phase": "wait_feedback",+ "query": "研究智能家电竞争格局",+ "file_name": "智能家电报告",+ "conversation_id": "conversation-1",+ "questions": ["继续吗?"],+ "revision": 3,+ }+ answer = {"status": "answered", "answers": [{"selected_options": ["是"]}]}++ async def _raise_cancelled(**kwargs):+ raise asyncio.CancelledError()++ with patch.object(de, "_call_deepresearch_stream_impl", new=_raise_cancelled):+ result, saved = await _invoke(state=state, user_input=answer)++ assert result["kind"] == "stopped"+ assert [frame["phase"] for frame in saved] == ["resuming_feedback", "new"]+ assert saved[-1]["conversation_id"] == "conversation-1"+ # 修复11:stopped 文案为条件式恢复口径——禁止模型在用户停止后+ # 自主重启(旧邀请式"如需继续,请再次调用"是生产事故诱因)。+ # content 不含 conversation_id(与 rail 改写口径对齐,cid 不泄露+ # 给模型;认领靠 query + 归属守卫,cid 功能载体是 state)。+ assert "请勿" in result["content"]+ assert "明确要求继续" in result["content"]+ assert "如需继续,请再次调用" not in result["content"]+ assert "conversation-1" not in result["content"]+++async def test_cancelled_during_option_generation_translates_to_stopped():+ """修复点3.1:取消落在 _handle_outcome 内的选项生成段也被同一守卫覆盖。"""+ state = {+ "schema_version": 1,+ "phase": "wait_feedback",+ "query": "研究智能家电竞争格局",+ "file_name": "智能家电报告",+ "conversation_id": "conversation-1",+ "questions": ["继续吗?"],+ "revision": 3,+ }+ answer = {"status": "answered", "answers": [{"selected_options": ["是"]}]}+ interrupted = {+ "status": "interrupted",+ "conversation_id": "conversation-1",+ "node_id": "feedback_handler",+ "marker": {"questions": "1. 继续吗?"},+ }+ model = _Model(_option_payload("继续吗?"))+ model.invoke = AsyncMock(side_effect=asyncio.CancelledError())+ with patch.object(+ de,+ "_call_deepresearch_stream_impl",+ new=AsyncMock(return_value=json.dumps(interrupted, ensure_ascii=False)),+ ):+ result, saved = await _invoke(state=state, user_input=answer, model=model)++ assert result["kind"] == "stopped"+ assert [frame["phase"] for frame in saved] == ["resuming_feedback", "new"]+++async def test_sdk_cancelled_outcome_translates_to_stopped_terminal():+ """修复点3.2:SDK 竞态 cancelled outcome(取消晚于子进程优雅退出)统一 stopped 口径。"""+ state = {+ "schema_version": 1,+ "phase": "wait_feedback",+ "query": "研究智能家电竞争格局",+ "file_name": "智能家电报告",+ "conversation_id": "conversation-1",+ "questions": ["继续吗?"],+ "revision": 3,+ }+ answer = {"status": "answered", "answers": [{"selected_options": ["是"]}]}+ cancelled_outcome = {+ "status": "cancelled",+ "conversation_id": "conversation-1",+ }+ with patch.object(+ de,+ "_call_deepresearch_stream_impl",+ new=AsyncMock(return_value=json.dumps(cancelled_outcome, ensure_ascii=False)),+ ):+ result, saved = await _invoke(state=state, user_input=answer)++ assert result["kind"] == "stopped"+ # content 不含 conversation_id(修复11 口径对齐,cid 不泄露给模型)+ assert "conversation-1" not in result["content"]+ assert saved[-1]["phase"] == "new"+ assert saved[-1]["conversation_id"] == "conversation-1"+++async def test_error_phase_with_stopped_snapshot_claims_and_resumes():+ """修复点3.2:error 相位下存有停止快照时认领续跑而非判死。"""+ state = {+ "schema_version": 1,+ "phase": "error",+ "revision": 4,+ "query": "研究智能家电竞争格局",+ "file_name": "智能家电报告",+ "conversation_id": "conversation-1",+ "requested_report_type": "brief",+ }+ probe = {"node": "report_writing", "stopped": True}+ completed = {+ "status": "completed",+ "conversation_id": "conversation-1",+ "report_delivered": True,+ }+ with (+ patch.object(de, "_probe_resumable_checkpoint", new=Mock(return_value=probe)),+ patch.object(+ de,+ "_call_deepresearch_stream_impl",+ new=AsyncMock(return_value=json.dumps(completed, ensure_ascii=False)),+ ) as stream,+ ):+ result, saved = await _invoke(state=state)++ stream.assert_awaited_once()+ assert stream.await_args.kwargs["action"] == "resume"+ assert stream.await_args.kwargs["node"] == "stopped"+ assert stream.await_args.kwargs["conversation_id"] == "conversation-1"+ assert result["kind"] == "completed"+ assert saved[0]["phase"] == "resuming_stopped"+ assert saved[-1]["phase"] == "completed"+++async def test_error_phase_without_stopped_snapshot_reports_finished():+ """修复点3.2:error 相位无停止快照(真实失败)→ 判死并引导重新发起。"""+ state = {+ "schema_version": 1,+ "phase": "error",+ "revision": 4,+ "query": "研究智能家电竞争格局",+ "file_name": "智能家电报告",+ "conversation_id": "conversation-1",+ }+ with (+ patch.object(de, "_probe_resumable_checkpoint", new=Mock(return_value=None)),+ patch.object(de, "_call_deepresearch_stream_impl", new=AsyncMock()) as stream,+ ):+ result, _ = await _invoke(state=state)assert result["kind"] == "error"- assert result["error_code"] == "execution_uncertain"+ assert "请重新发起" in result["content"]stream.assert_not_awaited()@pytest.mark.asyncio-async def test_cancelled_feedback_stops_without_resuming_sdk():+async def test_cancelled_phase_stays_terminal_even_with_stopped_snapshot():+ """修复点3.2(选1):cancelled 是显式放弃的死终态,有停止快照也不认领。"""state = {"schema_version": 1,- "phase": "wait_feedback",- "query": "q",- "file_name": "r",+ "phase": "cancelled",+ "revision": 4,+ "query": "研究智能家电竞争格局",+ "file_name": "智能家电报告","conversation_id": "conversation-1",- "questions": ["继续吗?"],- "revision": 3,}- with patch.object(de, "_call_deepresearch_stream_impl", new=AsyncMock()) as stream:- result, saved = await _invoke(- state=state,- user_input={"status": "cancelled", "answers": []},- )+ probe = {"node": "report_writing", "stopped": True}+ with (+ patch.object(de, "_probe_resumable_checkpoint", new=Mock(return_value=probe)),+ patch.object(de, "_call_deepresearch_stream_impl", new=AsyncMock()) as stream,+ ):+ result, saved = await _invoke(state=state)assert result["kind"] == "cancelled"- assert saved[-1]["phase"] == "cancelled"+ assert "已经结束" in result["content"]stream.assert_not_awaited()+ assert saved == []-def _rail_ctx(*, result, session=None, resume_input=None, tool_call_id="call-1"):+def _rail_ctx(+ *,+ result,+ session=None,+ resume_input=None,+ resume_key=None,+ tool_call_id="call-1",+ arguments=None,+):session = session or _Session()tool_call = SimpleNamespace(id=tool_call_id,name="deepresearch_execute",- arguments={"query": "q", "file_name": "r"},+ arguments=arguments+ if arguments is not None+ else {"query": "q", "file_name": "r"},)forced: list[dict] = []extra = {}@@ -1056,7 +2107,7 @@ def _rail_ctx(*, result, session=None, resume_input=None, tool_call_id="call-1")from openjiuwen.core.session.interaction.interactive_input import InteractiveInputinteractive_input = InteractiveInput()- interactive_input.update(tool_call_id, resume_input)+ interactive_input.update(resume_key or tool_call_id, resume_input)extra[RESUME_USER_INPUT_KEY] = interactive_inputreturn SimpleNamespace(session=session,@@ -1103,7 +2154,14 @@ async def test_execution_rail_turns_interaction_result_into_native_interrupt():assert isinstance(ctx.inputs.tool_result, ToolInterruptException)assert ctx.inputs.tool_result.request.questions == result["interaction"]["questions"]assert session.state[DEEPRESEARCH_EXECUTION_STATE_KEY]["call-1"] == state- assert ctx.inputs.tool_msg is None+ # 修复点1a:占位 JSON 不再裸入 LLM 历史,改为面向模型的 ToolMessage;+ # tool_call_id 保持原始调用 id(与 assistant 消息中的 tool_calls 对齐,+ # 而非 interaction 别名 id),内部 phase/占位结构不泄露。+ assert isinstance(ctx.inputs.tool_msg, ToolMessage)+ assert ctx.inputs.tool_msg.tool_call_id == "call-1"+ assert "结构化问答" in ctx.inputs.tool_msg.content+ assert "wait_feedback" not in ctx.inputs.tool_msg.content+ assert "schema_version" not in ctx.inputs.tool_msg.content@pytest.mark.asyncio@@ -1127,6 +2185,57 @@ async def test_execution_rail_force_finishes_terminal_result_without_next_llm():assert session.state[DEEPRESEARCH_EXECUTION_STATE_KEY] == {}+async def test_execution_rail_rewrites_stopped_result_to_block_auto_restart():+ """修复11:stopped 结果 JSON 不再裸入 LLM 历史,改写为禁止自动重启口径。++ 旧实现 stopped 分支直接 return,完整 JSON(含内部 state/revision 与+ "请再次调用本工具"邀请文案)裸入 LLM 历史,模型自主重启了已被用户+ 停止的研究。改写后:tool_msg 为禁止口径且不含 conversation_id(切断+ 模型拿 cid 直通重启的最短路径);tool_result 保持原 dict(stopped 非+ interaction,不转 TIE);不 force finish;states 保留停止快照供下一+ 次调用凭 probe/扫库认领。+ """+ state = {+ "schema_version": 1,+ "phase": "new",+ "query": "研究智能家电竞争格局",+ "conversation_id": "conversation-1",+ "revision": 4,+ }+ result = {+ "schema_version": de.EXECUTION_SCHEMA,+ "kind": "stopped",+ "content": (+ "DeepResearch 任务已被用户停止(conversation_id=conversation-1)。"+ "如需继续,请再次调用 deepresearch_execute 并传入"+ " conversation_id=conversation-1,将从停止处恢复。"+ ),+ "state": state,+ }+ session = _Session()+ rail = DeepResearchExecutionRail(model_provider=lambda: None)+ ctx = _rail_ctx(result=result, session=session)++ await rail.before_tool_call(ctx)+ await rail.after_tool_call(ctx)++ assert isinstance(ctx.inputs.tool_msg, ToolMessage)+ assert ctx.inputs.tool_msg.tool_call_id == "call-1"+ assert "已被用户停止" in ctx.inputs.tool_msg.content+ assert "请勿" in ctx.inputs.tool_msg.content+ # conversation_id 与内部 state 字段不泄露进 LLM 历史+ assert "conversation-1" not in ctx.inputs.tool_msg.content+ assert "schema_version" not in ctx.inputs.tool_msg.content+ assert "revision" not in ctx.inputs.tool_msg.content+ # tool_result 保持原始 dict,不转 ToolInterruptException+ assert ctx.inputs.tool_result is result+ # 不 force finish——外层请求正被用户停止,无需再产出回答+ assert ctx.force_finish_requests == []+ # 停止快照 state 保留,供下一次调用认领直通续跑+ assert session.state[DEEPRESEARCH_EXECUTION_STATE_KEY]["call-1"] == state++@pytest.mark.asyncioasync def test_execution_rail_binds_request_id_for_nested_options_llm():result = {@@ -1228,3 +2337,349 @@ async def test_same_outer_tool_call_survives_multiple_native_interrupts():assert "✅ **深度研究已完成!**" in second.force_finish_requests[0]["output"]assert session.state[DEEPRESEARCH_EXECUTION_STATE_KEY] == {}assert session.state[DEEPRESEARCH_EXECUTION_ALIAS_KEY] == {}+++def _stale_session(**state_overrides):+ """硬中断现场:in-flight state 遗留在旧 tool_call_id 下。"""+ state = {+ "schema_version": 1,+ "phase": "starting",+ "query": "q",+ "file_name": "r",+ "conversation_id": "conversation-1",+ "requested_report_type": "brief",+ "revision": 0,+ }+ state.update(state_overrides)+ session = _Session()+ session.update_state({DEEPRESEARCH_EXECUTION_STATE_KEY: {"call-old": state}})+ return session+++_STOPPED_PROBE = {"node": "researcher", "stopped": True}+++async def test_bridge_recovers_stale_inflight_state_and_resumes():+ """场景①:state miss + 同 query + 探针停止快照 → 桥接并直通续跑。"""+ session = _stale_session()+ rail = DeepResearchExecutionRail(model_provider=lambda: None)+ ctx = _rail_ctx(+ result=None,+ session=session,+ tool_call_id="call-new",+ arguments={"query": "q", "file_name": "r"},+ )+ stopped_probe = {"node": "researcher", "stopped": True}+ completed = {+ "status": "completed",+ "conversation_id": "conversation-1",+ "report_delivered": True,+ }+ with (+ patch.object(dr, "_probe_resumable_checkpoint", return_value=stopped_probe),+ patch.object(de, "_probe_resumable_checkpoint", return_value=stopped_probe),+ ):+ await rail.before_tool_call(ctx)+ assert session.state[DEEPRESEARCH_EXECUTION_ALIAS_KEY] == {+ "call-new": "call-old"+ }+ with patch.object(+ de,+ "_call_deepresearch_stream_impl",+ new=AsyncMock(return_value=json.dumps(completed, ensure_ascii=False)),+ ) as stream:+ ctx.inputs.tool_result = await de.deepresearch_execute._func(+ query="q",+ file_name="r",+ )+ await rail.after_tool_call(ctx)++ assert stream.await_count == 1+ assert stream.await_args.kwargs["action"] == "resume"+ assert stream.await_args.kwargs["node"] == "stopped"+ assert stream.await_args.kwargs["conversation_id"] == "conversation-1"+++async def test_bridge_rejects_when_query_switches_topic():+ """场景②:用户换研究主题 → 不桥,全新会话重跑。"""+ session = _stale_session()+ rail = DeepResearchExecutionRail(model_provider=lambda: None)+ ctx = _rail_ctx(+ result=None,+ session=session,+ tool_call_id="call-new",+ arguments={"query": "完全不同的新主题", "file_name": "r"},+ )+ with (+ patch.object(dr, "_probe_resumable_checkpoint", return_value=_STOPPED_PROBE),+ patch.object(de, "_probe_resumable_checkpoint", return_value=None),+ ):+ await rail.before_tool_call(ctx)++ assert session.state.get(DEEPRESEARCH_EXECUTION_ALIAS_KEY, {}) == {}+ completed = {"status": "completed", "report_delivered": True}+ with patch.object(+ de,+ "_call_deepresearch_stream_impl",+ new=AsyncMock(return_value=json.dumps(completed, ensure_ascii=False)),+ ) as stream:+ await de.deepresearch_execute._func(query="完全不同的新主题", file_name="r")++ assert stream.await_args.kwargs["action"] == "start"+ assert stream.await_args.kwargs["conversation_id"] != "conversation-1"+++async def test_bridge_rejects_multiple_candidate_states():+ """场景③:两条同主题候选 → 唯一性守卫拒绝,不桥。"""+ state = {+ "schema_version": 1,+ "phase": "starting",+ "query": "q",+ "file_name": "r",+ "conversation_id": "conversation-1",+ "revision": 0,+ }+ other = dict(state, conversation_id="conversation-2")+ session = _Session()+ session.update_state(+ {+ DEEPRESEARCH_EXECUTION_STATE_KEY: {+ "call-old-a": state,+ "call-old-b": other,+ }+ }+ )+ rail = DeepResearchExecutionRail(model_provider=lambda: None)+ ctx = _rail_ctx(+ result=None,+ session=session,+ tool_call_id="call-new",+ arguments={"query": "q", "file_name": "r"},+ )+ with patch.object(dr, "_probe_resumable_checkpoint", return_value=_STOPPED_PROBE):+ await rail.before_tool_call(ctx)++ assert session.state.get(DEEPRESEARCH_EXECUTION_ALIAS_KEY, {}) == {}+++async def test_bridge_rejects_when_explicit_cid_points_elsewhere():+ """场景④:显式传入不同的 conversation_id → 不抢别人的会话。"""+ session = _stale_session()+ rail = DeepResearchExecutionRail(model_provider=lambda: None)+ ctx = _rail_ctx(+ result=None,+ session=session,+ tool_call_id="call-new",+ arguments={+ "query": "q",+ "file_name": "r",+ "conversation_id": "conversation-other",+ },+ )+ with patch.object(dr, "_probe_resumable_checkpoint", return_value=_STOPPED_PROBE):+ await rail.before_tool_call(ctx)++ assert session.state.get(DEEPRESEARCH_EXECUTION_ALIAS_KEY, {}) == {}+++async def test_bridge_rejects_live_inflight_state_without_stopped_snapshot():+ """场景⑤(探针门):in-flight state 无停止快照(子进程还活着)→ 不桥。"""+ session = _stale_session()+ rail = DeepResearchExecutionRail(model_provider=lambda: None)+ ctx = _rail_ctx(+ result=None,+ session=session,+ tool_call_id="call-new",+ arguments={"query": "q", "file_name": "r"},+ )+ live_probe = {"node": "feedback_handler", "questions": ["继续吗?"]}+ with patch.object(dr, "_probe_resumable_checkpoint", return_value=live_probe):+ await rail.before_tool_call(ctx)++ assert session.state.get(DEEPRESEARCH_EXECUTION_ALIAS_KEY, {}) == {}+++async def test_bridge_from_new_phase_state_cleans_alias_on_terminal():+ """场景⑥:new 相位(免探针门)桥接,终态后 state 与 alias 清理干净。"""+ session = _stale_session(phase="new")+ rail = DeepResearchExecutionRail(model_provider=lambda: None)+ ctx = _rail_ctx(+ result=None,+ session=session,+ tool_call_id="call-new",+ arguments={"query": "q", "file_name": "r"},+ )+ await rail.before_tool_call(ctx)+ assert session.state[DEEPRESEARCH_EXECUTION_ALIAS_KEY] == {"call-new": "call-old"}++ result = {+ "schema_version": de.EXECUTION_SCHEMA,+ "kind": "completed",+ "content": "研究报告已生成并交付。",+ "state": {"schema_version": 1, "phase": "completed", "revision": 5},+ }+ ctx.inputs.tool_result = result+ await rail.after_tool_call(ctx)++ assert session.state[DEEPRESEARCH_EXECUTION_STATE_KEY] == {}+ assert session.state[DEEPRESEARCH_EXECUTION_ALIAS_KEY] == {}+++async def test_bridge_from_error_phase_state_resumes_stopped():+ """场景⑦(修复点3.2):error 相位 + 停止快照 → 桥接并直通续跑。"""+ session = _stale_session(phase="error", revision=4)+ rail = DeepResearchExecutionRail(model_provider=lambda: None)+ ctx = _rail_ctx(+ result=None,+ session=session,+ tool_call_id="call-new",+ arguments={"query": "q", "file_name": "r"},+ )+ completed = {+ "status": "completed",+ "conversation_id": "conversation-1",+ "report_delivered": True,+ }+ with (+ patch.object(dr, "_probe_resumable_checkpoint", return_value=_STOPPED_PROBE),+ patch.object(de, "_probe_resumable_checkpoint", return_value=_STOPPED_PROBE),+ ):+ await rail.before_tool_call(ctx)+ assert session.state[DEEPRESEARCH_EXECUTION_ALIAS_KEY] == {+ "call-new": "call-old"+ }+ with patch.object(+ de,+ "_call_deepresearch_stream_impl",+ new=AsyncMock(return_value=json.dumps(completed, ensure_ascii=False)),+ ) as stream:+ ctx.inputs.tool_result = await de.deepresearch_execute._func(+ query="q",+ file_name="r",+ )+ await rail.after_tool_call(ctx)++ assert stream.await_count == 1+ assert stream.await_args.kwargs["action"] == "resume"+ assert stream.await_args.kwargs["node"] == "stopped"+ assert stream.await_args.kwargs["conversation_id"] == "conversation-1"+++async def test_bridge_rejects_error_phase_state_without_stopped_snapshot():+ """场景⑧(探针门):error 相位无停止快照(子进程失败退出)→ 不桥。"""+ session = _stale_session(phase="error", revision=4)+ rail = DeepResearchExecutionRail(model_provider=lambda: None)+ ctx = _rail_ctx(+ result=None,+ session=session,+ tool_call_id="call-new",+ arguments={"query": "q", "file_name": "r"},+ )+ with patch.object(dr, "_probe_resumable_checkpoint", return_value=None):+ await rail.before_tool_call(ctx)++ assert session.state.get(DEEPRESEARCH_EXECUTION_ALIAS_KEY, {}) == {}+++async def test_bridge_rejects_cancelled_phase_state():+ """场景⑨(选1):cancelled 是显式放弃的死终态,不入桥候选。"""+ session = _stale_session(phase="cancelled", revision=4)+ rail = DeepResearchExecutionRail(model_provider=lambda: None)+ ctx = _rail_ctx(+ result=None,+ session=session,+ tool_call_id="call-new",+ arguments={"query": "q", "file_name": "r"},+ )+ with patch.object(dr, "_probe_resumable_checkpoint", return_value=_STOPPED_PROBE):+ await rail.before_tool_call(ctx)++ assert session.state.get(DEEPRESEARCH_EXECUTION_ALIAS_KEY, {}) == {}+++def test_resume_input_falls_back_to_only_entry_on_key_mismatch():+ """作答键与恢复键不一致但作答唯一 → 兜底取之;多条目时仍按键取。"""+ from openjiuwen.core.single_agent.interrupt.state import RESUME_USER_INPUT_KEY+ from openjiuwen.core.session.interaction.interactive_input import InteractiveInput++ answer = {"status": "answered"}+ interactive_input = InteractiveInput()+ interactive_input.update("call_a02da078", answer)+ ctx = SimpleNamespace(extra={RESUME_USER_INPUT_KEY: interactive_input})++ # 键断裂(作答挂在历史卡片 id 下):唯一条目兜底取值。+ assert (+ dr._resume_input(ctx, "call_6f57dea2_interaction_1") == answer+ )+ # 键匹配:正常取值。+ assert dr._resume_input(ctx, "call_a02da078") == answer++ # 多条目时无法安全兜底:仍返回 None,不得张冠李戴。+ interactive_input.update("call_other_card", {"status": "answered"})+ assert dr._resume_input(ctx, "call_6f57dea2_interaction_1") is None+++async def test_rail_resumes_outline_with_answer_keyed_by_stale_card_id():+ """作答挂在历史卡片 id 下(键断裂)→ rail 兜底取唯一作答续跑大纲确认。"""+ outline_confirmed = {+ "status": "answered",+ "answers": [+ {+ "question": "研究大纲是否确认?",+ "selected_options": ["确认大纲,继续研究"],+ }+ ],+ }+ completed = {+ "status": "completed",+ "conversation_id": "conversation-1",+ "report_delivered": True,+ }+ session = _Session()+ session.state[DEEPRESEARCH_EXECUTION_STATE_KEY] = {+ "call-1": {+ "schema_version": 1,+ "phase": "wait_outline",+ "revision": 1,+ "query": "研究智能家电竞争格局",+ "file_name": "智能家电报告",+ "conversation_id": "conversation-1",+ "requested_report_type": "brief",+ "outline_presented": True,+ }+ }+ rail = DeepResearchExecutionRail(model_provider=lambda: None)+ ctx = _rail_ctx(+ result=None,+ session=session,+ resume_input=outline_confirmed,+ resume_key="call_a02da078",+ tool_call_id="call-1",+ )+ await rail.before_tool_call(ctx)+ with patch.object(+ de,+ "_call_deepresearch_stream_impl",+ new=AsyncMock(return_value=json.dumps(completed, ensure_ascii=False)),+ ) as stream:+ ctx.inputs.tool_result = await de.deepresearch_execute._func(+ query="研究智能家电竞争格局",+ file_name="智能家电报告",+ )+ await rail.after_tool_call(ctx)++ # 兜底取到作答 → 大纲确认通过,resume outline_interaction 并完成。+ stream.assert_awaited_once()+ assert stream.await_args.kwargs["action"] == "resume"+ assert stream.await_args.kwargs["node"] == "outline_interaction"+ assert ctx.force_finish_requests[0]["result_type"] == "answer"diff --git a/tests/unit_tests/agentserver/test_deepresearch_sdk_bridge.py b/tests/unit_tests/agentserver/test_deepresearch_sdk_bridge.pyindex 10965f55e6..3fc16db245 100644--- a/tests/unit_tests/agentserver/test_deepresearch_sdk_bridge.py+++ b/tests/unit_tests/agentserver/test_deepresearch_sdk_bridge.py@@ -422,6 +422,15 @@ async def test_sdk_is_lazy_logs_only_to_stderr_and_restores_tls(tmp_path: Path,monkeypatch.setenv("LLM_SSL_VERIFY", "parent-llm")monkeypatch.delenv("TOOL_SSL_VERIFY", raising=False)+ # 预热:把 redirect_stdout 块内会发生的真实 openjiuwen import 与 auth 补丁应用+ # 提前到块外完成。pytest log_cli=true 下 live-log 每条日志都会 suspend/resume+ # 全局捕获,resume 会把 sys.stdout 无条件重置回捕获对象、踢掉 redirect 防御;+ # 预热后块内 import 全部命中 sys.modules 缓存、补丁命中幂等短路,零日志 emit,+ # 本用例不再依赖套件中是否存在更早的模块预热者。+ from jiuwenswarm.llm_sse_patch import apply_openai_auth_header_patch++ apply_openai_auth_header_patch()+result = await bridge.stylize_request(_request(), output)captured = capsys.readouterr()assert result["status"] == "completed"diff --git a/tests/unit_tests/agentserver/test_deepresearch_stream_router.py b/tests/unit_tests/agentserver/test_deepresearch_stream_router.pyindex 889f4736d8..ef4ec6941c 100644--- a/tests/unit_tests/agentserver/test_deepresearch_stream_router.py+++ b/tests/unit_tests/agentserver/test_deepresearch_stream_router.py@@ -1926,7 +1926,11 @@ def test_brief_research_nodes_advance_stage_three_in_task_list(agent):assert all(frame["event_type"] != "chat.delta" for frame in frames)-def test_brief_sub_reporter_completion_starts_stage_four_before_final_node_chunk():+def test_brief_sub_reporter_legacy_no_total_starts_stage_four_on_first_done():+ """旧生产端未透传 section_total 时退回旧口径:首个完成即开启 stage 4。++ 保证 jiuwenswarm 先于 deepsearch 合入时不把进度卡死在 stage 3。+ """state = RouterState(current_stage=3)frames = route_chunk(@@ -1953,6 +1957,77 @@ def test_brief_sub_reporter_completion_starts_stage_four_before_final_node_chunkassert node_complete < stage_four+def test_brief_sub_reporter_first_section_done_keeps_stage_three():+ """section_total 透传后对齐专业版口径:首个章节完成仍停留 stage 3。"""+ state = RouterState(current_stage=3)++ frames = route_chunk(+ {+ "agent": "brief_sub_reporter",+ "event": "done",+ "section_idx": "1",+ "section_total": 3,+ "content": "章节写作完成",+ },+ state,+ )++ assert state.final_report_started is False+ assert state.expected_section_total == 3+ assert state.completed_section_indices == {"1"}+ assert _stage_update(frames) is None+ assert all(+ frame.get("task_id") != "deepresearch_stage_4" for frame in frames+ )+++def test_brief_sub_reporter_all_sections_done_starts_stage_four():+ """全部章节完成(最后一个 done)才开启 stage 4。"""+ state = RouterState(current_stage=3)++ def _route_section_done(section_idx: str) -> list[dict]:+ return route_chunk(+ {+ "agent": "brief_sub_reporter",+ "event": "done",+ "section_idx": section_idx,+ "section_total": 3,+ "content": "章节写作完成",+ },+ state,+ )++ # 前两个章节完成:停留 stage 3。+ for section_idx in ("1", "2"):+ frames = _route_section_done(section_idx)+ assert all(+ frame.get("task_id") != "deepresearch_stage_4" for frame in frames+ )+ assert state.completed_section_indices == {"1", "2"}+ assert state.final_report_started is False++ # 第三个(最后一个)章节完成:开启 stage 4。+ final_frames = _route_section_done("3")+ assert state.completed_section_indices == {"1", "2", "3"}+ assert state.final_report_started is True+ _assert_stage(_stage_update(final_frames), 4)+ node_complete = next(+ index+ for index, frame in enumerate(final_frames)+ if frame["event_type"] == "chat.reasoning"+ and frame.get("task_id") == "deepresearch_stage_3"+ and frame.get("stream_source_id") == "dr_brief_sub_reporter"+ and frame.get("content") == "精简章节撰写完成\n"+ )+ stage_four = next(+ index+ for index, frame in enumerate(final_frames)+ if frame["event_type"] == "task.update"+ and frame["tasks"][3]["status"] == "in_progress"+ )+ assert node_complete < stage_four++@pytest.mark.parametrize("agent",[diff --git a/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py b/tests/unit_tests/agentserver/test_deepresearch_stream_tool.pyindex 36825658c4..5d2f4430ab 100644--- a/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py+++ b/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py@@ -181,6 +181,10 @@ def _stream_patches(proc: _Proc, *, route: dict[str, str] | None = None):},),patch("asyncio.create_subprocess_exec", new=AsyncMock(return_value=proc)),+ # stream action='start' 的扫库认领兜底默认打桩为未命中:真实认领会+ # 读共享 checkpointer.db,认领专项用例不进入本桩、自行打桩+ # _scan_resumable_checkpoint_by_query。+ patch.object(dt, "_claim_start_snapshot", AsyncMock(return_value=None)),)@@ -400,6 +404,149 @@ async def test_stream_rejects_invalid_report_type_before_child_spawn():spawn.assert_not_awaited()+async def test_start_claims_stopped_snapshot_and_resumes_stopped_node():+ """停止恢复兜底:同主题停止快照 → start 改写为 resume node='stopped'。++ 回归实证(2026-10-15 19:52):停止后新请求中 deepresearch_execute 被+ ProgressiveToolRail 过滤(stopped 文案指引成死信),外层模型绕行+ stream action='start' 全新起跑丢快照;认领兜底后同一入口直通续跑。+ """+ proc = _Proc(+ [+ json.dumps(+ {"__deepsearch_status__": "started", "conversation_id": "C-STP"}+ ),+ json.dumps(+ {"__deepsearch_status__": "stopped", "conversation_id": "C-STP"}+ ),+ ]+ )+ patches = _stream_patches(proc)+ claim = {+ "conversation_id": "C-STP",+ "node": "report_writing",+ "stopped": True,+ }+ with (+ patches[0],+ patches[1],+ patches[2],+ patches[3],+ patches[4],+ patches[5] as spawn,+ patch.object(+ dt, "_scan_resumable_checkpoint_by_query", Mock(return_value=claim)+ ),+ ):+ outcome = json.loads(+ await dt.deepresearch_stream._func(+ action="start", query="研究智能家电竞争格局"+ )+ )++ argv = [str(arg) for arg in spawn.await_args.args]+ assert "resume" in argv+ assert "run" not in argv+ assert "--query" not in argv+ assert argv[argv.index("--conversation-id") + 1] == "C-STP"+ assert argv[argv.index("--node") + 1] == "stopped"+ assert outcome["status"] == "stopped"+ assert outcome["resume_hint"]["node"] == "stopped"+++async def test_start_claims_interrupt_snapshot_returns_synthesized_interaction():+ """停止恢复兜底:同主题交互中断快照 → 本地合成 interrupted 重弹卡。++ 停止落在交互卡待答复期间时快照是 __interrupt__ 态:交互内容已由+ 扫库带出,直接合成标准 interrupted outcome(含 resume_hint 契约),+ 不拉起子进程空转一圈。+ """+ proc = _Proc()+ patches = _stream_patches(proc)+ claim = {+ "conversation_id": "C-INT",+ "node": "outline_interaction",+ "questions": ["1. 重点研究哪些品类?"],+ "outline_json": {+ "title": "智能家电竞争格局研究",+ "thought": "先规模后玩家",+ "sections": [{"title": "市场规模", "is_core_section": True}],+ },+ }+ with (+ patches[0],+ patches[1],+ patches[2],+ patches[3],+ patches[4],+ patches[5] as spawn,+ patch.object(+ dt, "_scan_resumable_checkpoint_by_query", Mock(return_value=claim)+ ),+ ):+ outcome = json.loads(+ await dt.deepresearch_stream._func(+ action="start", query="研究智能家电竞争格局"+ )+ )++ spawn.assert_not_awaited()+ assert outcome["status"] == "interrupted"+ assert outcome["conversation_id"] == "C-INT"+ assert outcome["node_id"] == "outline_interaction"+ assert outcome["marker"]["questions"] == ["1. 重点研究哪些品类?"]+ assert outcome["marker"]["outline"]["sections"] == [+ {"title": "市场规模", "is_core_section": True}+ ]+ assert "市场规模" in outcome["prompt"]+ assert outcome["resume_hint"]["node"] == "outline_interaction"+ assert outcome["resume_hint"]["interaction_result_required"] is True+++async def test_start_skips_claim_when_scan_misses():+ """扫库未命中(无同主题快照/归属不符)→ 保持全新起跑 argv 不变。"""+ proc = _Proc(+ [+ json.dumps(+ {"__deepsearch_status__": "started", "conversation_id": "C1"}+ ),+ json.dumps(+ {+ "__deepsearch_status__": "interrupted",+ "agent": "feedback_handler",+ "conversation_id": "C1",+ }+ ),+ ]+ )+ patches = _stream_patches(proc)+ with (+ patches[0],+ patches[1],+ patches[2],+ patches[3],+ patches[4],+ patches[5] as spawn,+ patch.object(+ dt, "_scan_resumable_checkpoint_by_query", Mock(return_value=None)+ ),+ ):+ outcome = json.loads(+ await dt.deepresearch_stream._func(+ action="start", query="研究智能家电竞争格局"+ )+ )++ argv = [str(arg) for arg in spawn.await_args.args]+ assert "run" in argv+ assert argv[argv.index("--query") + 1] == "研究智能家电竞争格局"+ assert "resume" not in argv+ assert outcome["status"] == "interrupted"++def test_only_six_standard_proxy_names_are_forwarded(tmp_path: Path, monkeypatch):venv = tmp_path / "runtime"python = venv / "bin" / "python"@@ -1330,6 +1477,385 @@ async def test_completed_marker_requires_nonempty_report():assert outcome["error_code"] == "empty_report"+def _write_raw_report(tmp_path: Path, cid: str, content: str) -> None:+ data_dir = tmp_path / "data"+ data_dir.mkdir(parents=True, exist_ok=True)+ (data_dir / f"{cid}.raw_report.md").write_text(content, encoding="utf-8")+++_SALVAGE_REPORT_BODY = "# 研究报告\n" + "深度研究内容。" * 40+++def test_locate_salvage_report_reads_raw_report(tmp_path):+ """修复7:定位并读取子进程落盘的 raw_report.md。"""+ _write_raw_report(tmp_path, "C1", _SALVAGE_REPORT_BODY)+ with patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path)):+ located = dt._locate_salvage_report("C1")++ assert located is not None+ assert located["response_content"].startswith("# 研究报告")+ assert located["citation_artifacts"]["raw_report_path"].endswith(+ "C1.raw_report.md"+ )+++def test_locate_salvage_report_returns_none_when_missing_or_trivial(tmp_path):+ """修复7:raw_report 缺失或内容过短 → 不可止损。"""+ with patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path)):+ assert dt._locate_salvage_report("C-MISS") is None+ _write_raw_report(tmp_path, "C-TINY", "太短")+ with patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path)):+ assert dt._locate_salvage_report("C-TINY") is None+++async def test_salvage_deepresearch_report_redacts_config_secrets():+ """止损交付与 stream 交付同口径脱敏 config secrets(检视修复)。"""+ route = {+ "request_id": "R1",+ "channel_id": "CH1",+ "session_id": "S1",+ "service_id": "default",+ "agent_id": "default",+ }++ async def fake_deliver(*, route, conversation_id, file_name, send, reason):+ delivered = await send(+ {+ "event_type": "task.update",+ "content": "报告引用中出现 llm-secret 与 search-secret",+ }+ )+ assert delivered is True+ return {"status": "completed", "report_delivered": True}++ push = AsyncMock()+ with ExitStack() as stack:+ stack.enter_context(+ patch.object(dt, "_get_route", return_value=route)+ )+ stack.enter_context(+ patch.object(+ dt,+ "_build_deepresearch_request_config",+ return_value=_valid_config(),+ )+ )+ stack.enter_context(+ patch.object(+ dt, "WebSocketGatewayPushTransport", return_value=push+ )+ )+ stack.enter_context(+ patch.object(dt, "_deliver_salvaged_report", new=fake_deliver)+ )+ outcome = await dt.salvage_deepresearch_report(+ conversation_id="C1", file_name="报告"+ )++ assert outcome == {"status": "completed", "report_delivered": True}+ payload = push.send_push.await_args.args[0]["payload"]+ assert "llm-secret" not in payload["content"]+ assert "search-secret" not in payload["content"]+ assert "[REDACTED]" in payload["content"]+++async def test_error_frame_salvages_raw_report(tmp_path):+ """修复7:子进程异常终局但报告已落盘 → 止损交付,outcome=completed。"""+ _write_raw_report(tmp_path, "C1", _SALVAGE_REPORT_BODY)+ proc = _Proc(+ [+ json.dumps({"__deepsearch_status__": "resuming", "conversation_id": "C1"}),+ json.dumps(+ {+ "__deepsearch_status__": "error",+ "conversation_id": "C1",+ "error_code": "workflow_error",+ "error": "boom",+ }+ ),+ ]+ )+ route = {+ "request_id": "",+ "channel_id": "CH1",+ "session_id": "S1",+ "service_id": "default",+ "agent_id": "default",+ }+ patches = _stream_patches(proc, route=route)+ push = AsyncMock()+ with ExitStack() as stack:+ for item in patches:+ stack.enter_context(item)+ stack.enter_context(+ patch.object(dt, "WebSocketGatewayPushTransport", return_value=push)+ )+ stack.enter_context(+ patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path))+ )+ stack.enter_context(+ patch.object(+ dt,+ "_write_report_artifacts_stream",+ new=AsyncMock(+ return_value=({"md": "/out/report.md"}, "fallback", None, None)+ ),+ )+ )+ outcome = json.loads(+ await dt.deepresearch_stream._func(+ action="resume", conversation_id="C1", node="stopped"+ )+ )++ assert outcome["status"] == "completed"+ assert outcome["report_delivered"] is True+ assert outcome["salvaged_report"] is True+ assert outcome["html_style_status"] == "fallback"+++async def test_empty_report_salvages_raw_report(tmp_path):+ """修复7:completed 帧缺报告正文但 raw_report 已落盘 → 同样止损交付。"""+ _write_raw_report(tmp_path, "C1", _SALVAGE_REPORT_BODY)+ proc = _Proc(+ [+ json.dumps(+ {+ "__deepsearch_status__": "completed",+ "conversation_id": "C1",+ "final_result": {"response_content": ""},+ }+ )+ ]+ )+ route = {+ "request_id": "",+ "channel_id": "CH1",+ "session_id": "S1",+ "service_id": "default",+ "agent_id": "default",+ }+ patches = _stream_patches(proc, route=route)+ push = AsyncMock()+ with ExitStack() as stack:+ for item in patches:+ stack.enter_context(item)+ stack.enter_context(+ patch.object(dt, "WebSocketGatewayPushTransport", return_value=push)+ )+ stack.enter_context(+ patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path))+ )+ stack.enter_context(+ patch.object(+ dt,+ "_write_report_artifacts_stream",+ new=AsyncMock(+ return_value=({"md": "/out/report.md"}, None, None, None)+ ),+ )+ )+ outcome = json.loads(+ await dt.deepresearch_stream._func(action="start", query="q")+ )++ assert outcome["status"] == "completed"+ assert outcome["salvaged_report"] is True+++class _RaceStopReader:+ """stdout double:消费者首次 read 阻塞(模拟研究进行中),被取消后由+ 帧感知排空读出自然完成输出的终局数据(修复A 竞速场景)。"""++ def __init__(self, terminal: bytes):+ self.terminal = terminal+ self.reads = 0++ async def read(self, size: int = -1) -> bytes:+ self.reads += 1+ if self.reads == 1:+ # 永不触发的事件:消费者在此阻塞,直到任务被取消。+ await asyncio.Event().wait()+ n = size if size and size > 0 else len(self.terminal)+ chunk, self.terminal = self.terminal[:n], self.terminal[n:]+ return chunk or b""+++def test_capture_completed_frame_filters_terminal_frames():+ """修复A:仅捕获带 response_content 的 completed 帧。"""+ captured: dict[str, Any] = {}+ dt._capture_completed_frame(b"not json", captured)+ assert captured == {}+ dt._capture_completed_frame(+ json.dumps({"__deepsearch_status__": "stopped", "conversation_id": "C1"}).encode(),+ captured,+ )+ assert captured == {}+ dt._capture_completed_frame(+ json.dumps(+ {+ "__deepsearch_status__": "completed",+ "conversation_id": "C1",+ "final_result": {"response_content": ""},+ }+ ).encode(),+ captured,+ )+ assert captured == {}+ dt._capture_completed_frame(+ json.dumps(+ {+ "__deepsearch_status__": "completed",+ "conversation_id": "C1",+ "final_result": {"response_content": "report-1"},+ }+ ).encode(),+ captured,+ )+ assert captured["final_result"]["response_content"] == "report-1"+ dt._capture_completed_frame(+ json.dumps(+ {+ "__deepsearch_status__": "completed",+ "conversation_id": "C1",+ "final_result": {"response_content": "report-2"},+ }+ ).encode(),+ captured,+ )+ # 多个 completed 帧时保留最后一个+ assert captured["final_result"]["response_content"] == "report-2"+++async def test_drain_stream_while_stopping_captures_completed_frame():+ """修复A:帧感知排空捕获 completed 帧,非 completed 终态不捕获。"""+ payload = b"".join(+ line.encode("utf-8") + b"\n"+ for line in (+ json.dumps({"__deepsearch_status__": "resuming", "conversation_id": "C1"}),+ json.dumps(+ {+ "__deepsearch_status__": "completed",+ "conversation_id": "C1",+ "final_result": {"response_content": "report"},+ }+ ),+ json.dumps({"__deepsearch_status__": "stopped", "conversation_id": "C1"}),+ )+ )+ captured: dict[str, Any] = {}+ await dt._drain_stream_while_stopping(_Reader(payload), captured)++ assert captured["__deepsearch_status__"] == "completed"+ assert captured["final_result"]["response_content"] == "report"+++async def test_drain_stream_while_stopping_without_capture_keeps_blind_drain():+ """captured=None 时保持纯排空行为(兼容旧调用)。"""+ payload = json.dumps(+ {+ "__deepsearch_status__": "completed",+ "final_result": {"response_content": "report"},+ }+ ).encode("utf-8") + b"\n"+ await dt._drain_stream_while_stopping(_Reader(payload), None)+++def _race_route() -> dict[str, str]:+ return {+ "request_id": "R1",+ "channel_id": "CH1",+ "session_id": "S1",+ "service_id": "default",+ "agent_id": "default",+ }+++async def test_stop_race_delivers_completed_report():+ """修复A:停止-完成竞速——取消后子进程自然完成,帧感知排空捕获+ completed 帧 → 报告照常交付,进度收尾为全阶段完成。"""+ completed_frame = json.dumps(+ {+ "__deepsearch_status__": "completed",+ "conversation_id": "C1",+ "final_result": {+ "response_content": "<html><body>研究报告</body></html>",+ "response_content_type": "text/html",+ },+ }+ )+ proc = _Proc([], running=True)+ proc.stdout = _RaceStopReader((completed_frame + "\n").encode("utf-8"))+ push = AsyncMock()+ with ExitStack() as stack:+ for item in _stream_patches(proc, route=_race_route()):+ stack.enter_context(item)+ stack.enter_context(+ patch.object(dt, "WebSocketGatewayPushTransport", return_value=push)+ )+ stack.enter_context(+ patch.object(+ dt,+ "_write_report_html",+ new=AsyncMock(return_value="/out/report.html"),+ )+ )+ stack.enter_context(+ patch.object(+ dt, "deepresearch_todo_path", side_effect=RuntimeError("no todo")+ )+ )+ task = asyncio.create_task(+ dt.deepresearch_stream._func(action="start", query="race")+ )+ await asyncio.sleep(0.01) # 让消费者阻塞在首次 read+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task++ payloads = [call.args[0]["payload"] for call in push.send_push.await_args_list]+ file_payloads = [p for p in payloads if p.get("event_type") == "chat.file"]+ assert file_payloads+ assert file_payloads[0]["files"][0]["path"] == "/out/report.html"+ assert file_payloads[0]["files"][0]["mime_type"] == "text/html"+ task_updates = [p for p in payloads if p.get("event_type") == "task.update"]+ assert task_updates+ final_update = task_updates[-1]+ assert final_update["completed_tasks"] == 4+ assert final_update["in_progress_tasks"] == 0+++async def test_stop_without_race_keeps_stop_semantics():+ """修复A回归:无 completed 帧的纯停止路径行为不变——只优雅停止,+ 不推送任何报告产物。"""+ proc = _Proc([], running=True)+ proc.stdout = _RaceStopReader(b"")+ push = AsyncMock()+ with ExitStack() as stack:+ for item in _stream_patches(proc, route=_race_route()):+ stack.enter_context(item)+ stack.enter_context(+ patch.object(dt, "WebSocketGatewayPushTransport", return_value=push)+ )+ task = asyncio.create_task(+ dt.deepresearch_stream._func(action="start", query="stop")+ )+ await asyncio.sleep(0.01)+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task++ payloads = [call.args[0]["payload"] for call in push.send_push.await_args_list]+ assert not [p for p in payloads if p.get("event_type") == "chat.file"]++@pytest.mark.asyncioasync def test_completed_marker_requires_all_section_progress():proc = _Proc(@@ -3381,6 +3907,185 @@ async def test_user_feedback_resume_can_complete_final_report_without_section_re)+def test_stage_for_resume_node_maps_stop_node_to_stage():+ """停止续跑:被停止节点 → 前端进度起始阶段;未映射节点回退 3。"""+ from jiuwenswarm.agents.harness.common.tools.deepresearch.stream_router import (+ stage_for_resume_node,+ )++ assert stage_for_resume_node("feedback_handler") == 1+ assert stage_for_resume_node("outline_interaction") == 2+ assert stage_for_resume_node("editor_team") == 3+ assert stage_for_resume_node("brief_info_collector") == 3+ # 最终报告节点:直播流中章节完成后流出 chunk 即开启 stage 4,+ # 停止在这些节点 → 续跑从 stage 4 恢复(与用户停止前看到的一致)+ assert stage_for_resume_node("brief_source_tracer") == 4+ assert stage_for_resume_node("brief_html_reporter") == 4+ assert stage_for_resume_node("reporter") == 4+ assert stage_for_resume_node("source_tracer") == 4+ # 非业务节点(start/end/agent_team 等)与空串回退研究阶段+ assert stage_for_resume_node("start") == 3+ assert stage_for_resume_node("") == 3+++async def test_stopped_resume_with_stage_hint_skips_early_stages():+ """停止续跑:阶段提示(brief_source_tracer→3)使进度列表直接从第三阶段+ 进行中开始,不回退到第一步"研究主题澄清"转圈。"""+ proc = _Proc(+ [+ json.dumps({"__deepsearch_status__": "resuming", "conversation_id": "C1"}),+ json.dumps({"__deepsearch_status__": "error", "error": "stop"}),+ ]+ )+ route = {+ "request_id": "R",+ "channel_id": "CH",+ "session_id": "S",+ "service_id": "default",+ "agent_id": "default",+ }+ push = AsyncMock()+ patches = _stream_patches(proc, route=route)+ token = dt._deepresearch_stage_hint_ctx.set(3)+ try:+ with ExitStack() as stack:+ for item in patches:+ stack.enter_context(item)+ stack.enter_context(+ patch.object(dt, "WebSocketGatewayPushTransport", return_value=push)+ )+ await dt.deepresearch_stream._func(+ action="resume", conversation_id="C1", node="stopped"+ )+ finally:+ dt._deepresearch_stage_hint_ctx.reset(token)++ task_updates = [+ call.args[0]["payload"]+ for call in push.send_push.await_args_list+ if call.args[0]["payload"].get("event_type") == "task.update"+ ]+ # 不出现"第一阶段进行中"的回退帧+ assert not any(+ task.get("task_id") == "deepresearch_stage_1"+ and task.get("status") == "in_progress"+ for payload in task_updates+ for task in payload.get("tasks", [])+ )+ # 首个 task.update 快照:阶段1-2已完成、阶段3进行中+ assert task_updates, "expected at least one task.update snapshot"+ first = task_updates[0]["tasks"]+ assert first[0]["status"] == "completed"+ assert first[1]["status"] == "completed"+ assert first[2]["status"] == "in_progress"+++async def test_start_claim_stopped_resume_pushes_stage_hint_from_claim_node():+ """start 扫库认领续跑:阶段提示由认领分支按 claim node 推导,首个+ task.update 快照直接落在该节点所属阶段,不回退 stage1。++ 回归实证(2026-10-16 日志):brief_html_reporter 停止后续跑,认领改写+ 为 resume node='stopped' 但未设置阶段提示,resuming 分支取默认+ stage=1,前端显示"回到 stage1 从头重跑"转圈 2 分 45 秒后直跳全部+ 完成。+ """+ proc = _Proc(+ [+ json.dumps({"__deepsearch_status__": "resuming", "conversation_id": "C-CLM"}),+ json.dumps({"__deepsearch_status__": "error", "error": "stop"}),+ ]+ )+ route = {+ "request_id": "R",+ "channel_id": "CH",+ "session_id": "S",+ "service_id": "default",+ "agent_id": "default",+ }+ push = AsyncMock()+ patches = _stream_patches(proc, route=route)+ claim = {+ "conversation_id": "C-CLM",+ "node": "brief_html_reporter",+ "stopped": True,+ }+ with ExitStack() as stack:+ for item in patches:+ stack.enter_context(item)+ stack.enter_context(+ patch.object(dt, "WebSocketGatewayPushTransport", return_value=push)+ )+ stack.enter_context(+ patch.object(dt, "_claim_start_snapshot", AsyncMock(return_value=claim))+ )+ await dt.deepresearch_stream._func(+ action="start", query="研究智能家电竞争格局"+ )++ task_updates = [+ call.args[0]["payload"]+ for call in push.send_push.await_args_list+ if call.args[0]["payload"].get("event_type") == "task.update"+ ]+ # brief_html_reporter 属最终报告节点:阶段 1-3 已完成、阶段 4 进行中+ assert not any(+ task.get("task_id") == "deepresearch_stage_1"+ and task.get("status") == "in_progress"+ for payload in task_updates+ for task in payload.get("tasks", [])+ )+ assert task_updates, "expected at least one task.update snapshot"+ first = task_updates[0]["tasks"]+ assert first[0]["status"] == "completed"+ assert first[1]["status"] == "completed"+ assert first[2]["status"] == "completed"+ assert first[3]["status"] == "in_progress"+++async def test_stopped_resume_without_hint_keeps_legacy_stage_one():+ """停止续跑:认领侧未提供阶段提示(旧路径/直调) → 维持回退第一步的+ 原有行为,不因本次改动产生回归。"""+ proc = _Proc(+ [+ json.dumps({"__deepsearch_status__": "resuming", "conversation_id": "C1"}),+ json.dumps({"__deepsearch_status__": "error", "error": "stop"}),+ ]+ )+ route = {+ "request_id": "R",+ "channel_id": "CH",+ "session_id": "S",+ "service_id": "default",+ "agent_id": "default",+ }+ push = AsyncMock()+ patches = _stream_patches(proc, route=route)+ with ExitStack() as stack:+ for item in patches:+ stack.enter_context(item)+ stack.enter_context(+ patch.object(dt, "WebSocketGatewayPushTransport", return_value=push)+ )+ await dt.deepresearch_stream._func(+ action="resume", conversation_id="C1", node="stopped"+ )++ task_updates = [+ call.args[0]["payload"]+ for call in push.send_push.await_args_list+ if call.args[0]["payload"].get("event_type") == "task.update"+ ]+ assert any(+ task.get("task_id") == "deepresearch_stage_1"+ and task.get("status") == "in_progress"+ for payload in task_updates+ for task in payload.get("tasks", [])+ )++def test_artifact_bundle_ignores_blank_and_unapproved_companions():bundle = dt._build_related_artifact_bundle({@@ -3403,7 +4108,6 @@ def test_artifact_bundle_ignores_blank_and_unapproved_companions():],}-@pytest.mark.asyncioasync def test_offline_html_uses_verified_snapshot_and_preserves_occupied_output(tmp_path: Path,