Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix(deepresearch): 修复中断后 resume 从头跑且 LLM 代答交互确认的问题

KevinLLLove84d8e9502d96
diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py
index a4aba5c78c..19e7fe5b99 100644
--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py
+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py
@@ -25,7 +25,12 @@ from jiuwenswarm.common.schema.ask_user import (
from jiuwenswarm.perf.context import DeepResearchReportType
from .stream_router import _format_outline_card_markdown
-from .tools import _call_deepresearch_stream_impl
+from .tools import (
+ _call_deepresearch_stream_impl,
+ _get_cached_outline_json,
+ _get_route,
+ _probe_resumable_checkpoint,
+)
from .usage import normalize_workflow_llm_token_usage
logger = logging.getLogger(__name__)
@@ -650,6 +655,30 @@ def _outline_sections(outline_text: str) -> list[str]:
]
+def _outline_review_interaction(outline_text: str) -> dict[str, Any]:
+ """The outline review ask-user card shared by all entry paths."""
+ return {
+ "query": "请审阅生成的研究报告大纲",
+ "return_json": True,
+ "questions": [
+ {
+ "header": "研究报告大纲审阅",
+ "question": "请审阅生成的研究报告大纲,确认后将继续执行深度研究。",
+ "options": [
+ {"label": "确认大纲,继续研究"},
+ {"label": "需要修改"},
+ ],
+ "preview": {
+ "title": "研究报告大纲",
+ "text": outline_text,
+ "format": "markdown",
+ "editable": True,
+ },
+ }
+ ],
+ }
+
+
def _completion_content(
state: Mapping[str, Any], html_style_status: Any = None
) -> str:
@@ -814,26 +843,7 @@ async def _handle_outcome(
return _result(
"interaction",
state,
- interaction={
- "query": "请审阅生成的研究报告大纲",
- "return_json": True,
- "questions": [
- {
- "header": "研究报告大纲审阅",
- "question": "请审阅生成的研究报告大纲,确认后将继续执行深度研究。",
- "options": [
- {"label": "确认大纲,继续研究"},
- {"label": "需要修改"},
- ],
- "preview": {
- "title": "研究报告大纲",
- "text": outline_text,
- "format": "markdown",
- "editable": True,
- },
- }
- ],
- },
+ interaction=_outline_review_interaction(outline_text),
)
return _terminal_error(
context,
@@ -902,13 +912,19 @@ async def _handle_outcome(
"the standard detail, research-question, and outline review cards, "
"resumes the same SDK conversation, and directly delivers the terminal result. "
"report_type: 'professional' for in-depth multi-section reports, 'brief' for "
- "single-page concise reports; infer from the user's original wording."
+ "single-page concise reports; infer from the user's original wording. "
+ "Optional conversation_id claims a previous DeepResearch conversation "
+ "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."
),
)
async def deepresearch_execute(
query: str,
file_name: str = "",
report_type: DeepResearchReportType | None = None,
+ conversation_id: str = "",
) -> dict[str, Any]:
"""Run the interactive workflow without Main Agent resume choreography."""
context = _execution_context.get()
@@ -927,7 +943,10 @@ async def deepresearch_execute(
"phase": "new",
"query": query.strip(),
"file_name": file_name.strip(),
- "conversation_id": str(uuid.uuid4()),
+ # 传入 conversation_id 表示认领一个此前中断的旧会话(研究问题
+ # 确认或大纲确认阶段);认领失败(checkpointer.db 与缓存均无可
+ # 恢复状态)时下面 start 分支会换成全新 id 重跑。
+ "conversation_id": conversation_id.strip() or str(uuid.uuid4()),
# report_type 优先取 Main Agent 工具入参(从用户原话识别);未传入时
# 回退执行上下文(params 通道),最终兜底 brief。归一后写入 state,
# resume 路径读此值不重新识别。deepresearch_stream:1918 据此写
@@ -959,7 +978,99 @@ async def deepresearch_execute(
return _result(kind, state, content="DeepResearch 任务已经结束。")
if phase == "new":
- state = _persist(context, state, "starting")
+ claimed_cid = str(state.get("conversation_id") or "").strip()
+ probe = (
+ _probe_resumable_checkpoint(claimed_cid) if claimed_cid else None
+ )
+ probe_node = str(probe.get("node") or "") if probe else ""
+ if claimed_cid and probe_node == "feedback_handler":
+ # 认领成功:旧会话停在研究问题确认阶段(含跨进程重启),从
+ # checkpointer.db 恢复问题清单出反馈卡;用户答复后从原会话 resume。
+ questions = _split_questions(probe.get("questions"))
+ if questions:
+ options = await _generate_options(
+ context,
+ str(state.get("query") or ""),
+ questions,
+ )
+ cards = [
+ {
+ "header": "研究方向反馈",
+ "question": question,
+ "options": options[index],
+ }
+ for index, question in enumerate(questions)
+ ]
+ state = _persist(
+ context,
+ state,
+ "wait_feedback",
+ conversation_id=claimed_cid,
+ questions=questions,
+ )
+ logger.info(
+ "[deepresearch_execute] claimed interrupted conversation "
+ "tool_call_id=%s conversation_id=%s node=feedback_handler",
+ context.tool_call_id,
+ claimed_cid,
+ )
+ return _result(
+ "interaction",
+ state,
+ interaction={
+ "query": "请回答以下研究主题澄清问题",
+ "return_json": True,
+ "questions": cards,
+ },
+ )
+ claimed_outline = (
+ probe.get("outline_json")
+ if probe_node == "outline_interaction"
+ else None
+ )
+ if not isinstance(claimed_outline, dict):
+ claimed_outline = (
+ _get_cached_outline_json(_get_route(), claimed_cid)
+ if claimed_cid
+ else {}
+ )
+ claimed_sections = claimed_outline.get("sections")
+ if claimed_cid and isinstance(claimed_sections, list) and claimed_sections:
+ # 认领成功:旧会话已生成大纲且停在大纲确认,直接复用 checkpointer.db
+ # (或内存缓存兜底)中的大纲出审阅卡片,跳过 start 重跑;用户答复后
+ # 从原会话 resume。
+ outline_text = (
+ _format_outline_card_markdown(claimed_outline)
+ or "大纲已生成,请确认是否继续研究。"
+ )
+ state = _persist(
+ context,
+ state,
+ "wait_outline",
+ conversation_id=claimed_cid,
+ outline_presented=True,
+ outline_sections=_outline_sections(outline_text),
+ )
+ logger.info(
+ "[deepresearch_execute] claimed interrupted conversation "
+ "tool_call_id=%s conversation_id=%s node=outline_interaction",
+ context.tool_call_id,
+ claimed_cid,
+ )
+ return _result(
+ "interaction",
+ state,
+ interaction=_outline_review_interaction(outline_text),
+ )
+ if claimed_cid:
+ # 认领失败:checkpointer.db 与内存缓存均无该会话可恢复的中断状态
+ # (已完结/已清理/不存在),绝不复用中断会话的 id 发起新跑,换成
+ # 全新 id 从头执行。
+ state = _persist(
+ context, state, "starting", conversation_id=str(uuid.uuid4())
+ )
+ else:
+ state = _persist(context, state, "starting")
outcome = await _call_sdk(
context,
action="start",
diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py
index 5a38b08cbc..d20141dc5d 100644
--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py
+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py
@@ -11,7 +11,9 @@ import io
import json
import logging
import os
+import pickle
import re
+import sqlite3
import stat
import tempfile
import threading
@@ -281,6 +283,9 @@ _RESUME_NODE_CURRENT_STAGE = {
"outline_interaction": 2,
"user_feedback_processor": 3,
}
+_CHECKPOINT_WORKFLOW_ID = "research_workflow"
+_CHECKPOINT_INTERRUPT_STATUS = "__interrupt__"
+_QUESTION_PARAGRAPH_SPLIT = re.compile(r"\n\s*\n(?=\s*\d+[.、)]\s)")
def push_deepresearch_route(
@@ -1147,7 +1152,87 @@ def _resolve_outline_interaction_feedback(
ensure_ascii=False,
)
- raise ValueError(f"unknown selected_options[0]={choice!r}")
+ expected_choices = ", ".join(
+ sorted(_OUTLINE_CONFIRM_CHOICES | _OUTLINE_EDIT_CHOICES)
+ )
+ raise ValueError(
+ f"unknown selected_options[0]={choice!r}; "
+ f"expected one of: {expected_choices}"
+ )
+
+
+def _build_interrupted_resume_hint(
+ node_id: str, conversation_id: str
+) -> dict[str, Any]:
+ """Build the self-describing resume hint for one interrupted outcome.
+
+ The stream tool hands the interrupted outcome back to the caller LLM
+ verbatim. Without an explicit contract the model has historically
+ improvised resume arguments (e.g. selected_options=["approve"]) and
+ looped on validation errors instead of asking the user, so the hint
+ pins the exact resume parameters for the two interactive nodes.
+ """
+ if node_id == "outline_interaction":
+ return {
+ "action": "resume",
+ "node": "outline_interaction",
+ "conversation_id": conversation_id,
+ "interaction_result_required": True,
+ "valid_selected_options": sorted(
+ _OUTLINE_CONFIRM_CHOICES | _OUTLINE_EDIT_CHOICES
+ ),
+ "interaction_result_example": json.dumps(
+ {
+ "status": "answered",
+ "answers": [
+ {
+ "question": "请审阅生成的研究报告大纲",
+ "selected_options": ["outline_confirm"],
+ "custom_input": "",
+ }
+ ],
+ },
+ ensure_ascii=False,
+ ),
+ "guidance": (
+ "The workflow paused for outline review. Present the outline "
+ "to the user, collect the user's decision, then resume with "
+ "action='resume', this conversation_id, "
+ "node='outline_interaction', and the user's answer encoded as "
+ "interaction_result (see interaction_result_example; "
+ "selected_options[0] must be one of valid_selected_options). "
+ "Never answer on the user's behalf or resume without the "
+ "user's input."
+ ),
+ }
+ return {
+ "action": "resume",
+ "node": "feedback_handler",
+ "conversation_id": conversation_id,
+ "feedback_required": True,
+ "interaction_result_example": json.dumps(
+ {
+ "status": "answered",
+ "answers": [
+ {
+ "question": "研究主题澄清",
+ "selected_options": [],
+ "custom_input": "用户输入的反馈内容",
+ }
+ ],
+ },
+ ensure_ascii=False,
+ ),
+ "guidance": (
+ "The workflow paused for research-direction feedback. Ask the "
+ "user the questions from marker.questions, collect the user's "
+ "answers, then resume with action='resume', this "
+ "conversation_id, node='feedback_handler', and the user's answer "
+ "text as feedback. interaction_result is optional and only "
+ "records whether the user actually answered. Never answer on "
+ "the user's behalf or resume without the user's input."
+ ),
+ }
def _resolve_skill_root() -> str:
@@ -1198,6 +1283,112 @@ def _resolve_run_script() -> str:
return str(runner)
+def _read_checkpoint_kv_value(cursor: Any, key: str) -> Any:
+ cursor.execute("SELECT value FROM kv_store WHERE key = ?", (key,))
+ row = cursor.fetchone()
+ return row[0] if row else None
+
+
+def _decode_checkpoint_blob(raw: Any) -> Any:
+ if isinstance(raw, bytes):
+ raw = raw.decode("utf-8", errors="replace")
+ if not isinstance(raw, str) or not raw:
+ return None
+ payload = raw.split(":", 1)[1] if raw.startswith("__BYTES__:") else raw
+ try:
+ return pickle.loads(base64.b64decode(payload))
+ except Exception: # pylint: disable=broad-exception-caught
+ 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.
+ Returns None whenever the conversation has no resumable interrupt, so a
+ failed probe simply falls back to a fresh start.
+ """
+ cid = str(conversation_id or "").strip()
+ if not cid:
+ return None
+ root = _resolve_skill_root()
+ if not root:
+ return None
+ db_path = os.path.join(root, "data", "checkpointer.db")
+ if not os.path.isfile(db_path):
+ return None
+ try:
+ connection = sqlite3.connect(
+ f"file:{db_path}?mode=ro", uri=True, timeout=1.0
+ )
+ except sqlite3.Error:
+ return None
+ try:
+ cursor = connection.cursor()
+ graph_state = _decode_checkpoint_blob(
+ _read_checkpoint_kv_value(
+ cursor,
+ 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:
+ 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",
+ )
+ )
+ 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)
+ ),
+ }
+ )
+ 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
+ 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")
@@ -1788,7 +1979,18 @@ async def _call_deepresearch_stream_impl(
description=(
"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."
+ "interrupted, completed, or structured error outcome is returned. "
+ "action='start' launches a new research run and requires query; "
+ "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 "
+ "the USER's answer at an interaction node: present the marker content "
+ "to the user, collect the user's reply, then resume with it (the "
+ "user's answer text as feedback for feedback_handler; the user's "
+ "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."
),
)
async def deepresearch_stream( # pylint: disable=huawei-too-many-arguments
@@ -2093,6 +2295,14 @@ async def deepresearch_stream( # pylint: disable=huawei-too-many-arguments
_clear_outline_json_cache(
route, outcome.get("conversation_id", conversation_id)
)
+ if (
+ outcome.get("status") == "interrupted"
+ and outcome.get("node_id") in {"feedback_handler", "outline_interaction"}
+ ):
+ outcome["resume_hint"] = _build_interrupted_resume_hint(
+ str(outcome.get("node_id") or ""),
+ str(outcome.get("conversation_id") or conversation_id),
+ )
if (
outcome.get("status") == "interrupted"
and outcome.get("node_id") == "outline_interaction"
@@ -2355,8 +2565,14 @@ async def _consume_stream(
)
if titles and resolved_cid:
_cache_outline_titles(route, resolved_cid, titles)
- if outline_json_dict is not None and resolved_cid:
- _cache_outline_json(route, resolved_cid, outline_json_dict)
+ if resolved_cid:
+ if outline_json_dict is not None:
+ _cache_outline_json(route, resolved_cid, outline_json_dict)
+ elif isinstance(marker.get("outline"), dict):
+ # marker 自带完整 outline JSON 时同样写缓存:execute 认领
+ # 旧会话与 outline_use_edited 编辑回传都依赖该缓存
+ #(缺 sections 时下游 fail-closed)。
+ _cache_outline_json(route, resolved_cid, marker["outline"])
if node_id == "user_feedback_processor" and state.report_parts:
report = "".join(state.report_parts)
marker["report"] = report[:6000] + (
diff --git a/tests/unit_tests/agentserver/test_deepresearch_execute_tool.py b/tests/unit_tests/agentserver/test_deepresearch_execute_tool.py
index 87eebe04e8..8cf0efdb00 100644
--- a/tests/unit_tests/agentserver/test_deepresearch_execute_tool.py
+++ b/tests/unit_tests/agentserver/test_deepresearch_execute_tool.py
@@ -3,7 +3,10 @@
from __future__ import annotations
import asyncio
+import base64
import json
+import pickle
+import sqlite3
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock, patch
@@ -20,6 +23,7 @@ from jiuwenswarm.agents.harness.common.rails.stream_event_rail import (
JiuSwarmStreamEventRail,
)
from jiuwenswarm.agents.harness.common.tools.deepresearch import execution as de
+from jiuwenswarm.agents.harness.common.tools.deepresearch import tools as dt
class _Session:
@@ -68,6 +72,7 @@ async def _invoke(
query="研究智能家电竞争格局",
file_name="智能家电报告",
requested_report_type=None,
+ conversation_id="",
):
saved: list[dict] = []
token = de.bind_deepresearch_execution_context(
@@ -79,7 +84,11 @@ async def _invoke(
requested_report_type=requested_report_type,
)
try:
- result = await de.deepresearch_execute._func(query=query, file_name=file_name)
+ result = await de.deepresearch_execute._func(
+ query=query,
+ file_name=file_name,
+ conversation_id=conversation_id,
+ )
finally:
de.reset_deepresearch_execution_context(token)
return result, saved
@@ -166,6 +175,288 @@ async def test_new_query_persists_request_report_type_before_sdk_start():
assert stream.await_args.kwargs["report_type"] == "brief"
+async def test_execute_claims_interrupted_conversation_with_cached_outline():
+ """传入 conversation_id 且缓存有大纲 → 跳过 start 重跑,直接呈现大纲审阅卡片。"""
+ outline = {
+ "title": "智能家电竞争格局研究",
+ "sections": [
+ {"id": "1", "title": "市场规模", "is_core_section": True, "description": "整体规模"},
+ {"id": "2", "title": "主要玩家"},
+ ],
+ }
+ 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:
+ result, saved = await _invoke(conversation_id="C-OLD")
+ 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
+ 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_without_cached_outline_restarts_with_fresh_id():
+ """认领失败(缓存无大纲)→ 换全新 conversation_id 从头执行,绝不复用旧 id 发起新跑。"""
+ outcome = {
+ "status": "error",
+ "error_code": "runner_failed",
+ "error": "boom",
+ }
+ route_token = dt.push_deepresearch_route("R1", "CH1", "S2")
+ try:
+ with 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-GONE")
+ 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-GONE"
+
+
+def _encode_checkpoint_blob(value):
+ return "__BYTES__:" + base64.b64encode(pickle.dumps(value)).decode("ascii")
+
+
+def _write_checkpoint_db(
+ root,
+ conversation_id,
+ *,
+ node,
+ node_status="__interrupt__",
+ questions="",
+ outline=None,
+):
+ 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)}
+ )
+ search_context = {}
+ if questions:
+ search_context["questions"] = questions
+ if outline is not None:
+ search_context["current_outline"] = outline
+ workflow_state = {"global_state": {"search_context": search_context}}
+ connection.executemany(
+ "INSERT INTO kv_store (key, value) VALUES (?, ?)",
+ [
+ (
+ f"{conversation_id}:workflow-graph:research_workflow:checkpoint_data_value",
+ _encode_checkpoint_blob(graph_state),
+ ),
+ (
+ f"{conversation_id}:workflow:research_workflow:workflow_state_blobs",
+ _encode_checkpoint_blob(workflow_state),
+ ),
+ ],
+ )
+ connection.commit()
+ finally:
+ connection.close()
+
+
+def test_probe_resumable_checkpoint_reads_feedback_stage(tmp_path):
+ """停研究问题阶段的会话 → 探测出节点与按段落切分的问题清单。"""
+ _write_checkpoint_db(
+ tmp_path,
+ "C-FB",
+ node="feedback_handler",
+ questions="1. 重点研究哪些品类?\n第一问的补充限定\n\n2. 覆盖哪些市场?",
+ )
+
+ with patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path)):
+ probe = dt._probe_resumable_checkpoint("C-FB")
+
+ assert probe == {
+ "node": "feedback_handler",
+ "questions": ["1. 重点研究哪些品类?\n第一问的补充限定", "2. 覆盖哪些市场?"],
+ }
+
+
+def test_probe_resumable_checkpoint_reads_outline_stage(tmp_path):
+ """停大纲确认阶段的会话 → 探测出节点与工具层大纲 JSON。"""
+ outline = SimpleNamespace(
+ title="智能家电竞争格局研究",
+ thought="先规模后玩家",
+ sections=[
+ SimpleNamespace(title="市场规模", is_core_section=True),
+ SimpleNamespace(title="主要玩家", is_core_section=False),
+ ],
+ )
+ _write_checkpoint_db(
+ tmp_path,
+ "C-OL",
+ node="outline_interaction",
+ questions="1. 问题",
+ outline=outline,
+ )
+
+ with patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path)):
+ probe = dt._probe_resumable_checkpoint("C-OL")
+
+ assert probe == {
+ "node": "outline_interaction",
+ "questions": ["1. 问题"],
+ "outline_json": {
+ "title": "智能家电竞争格局研究",
+ "thought": "先规模后玩家",
+ "sections": [
+ {"title": "市场规模", "is_core_section": True},
+ {"title": "主要玩家", "is_core_section": False},
+ ],
+ },
+ }
+
+
+def test_probe_resumable_checkpoint_returns_none_without_resumable_interrupt(tmp_path):
+ """非中断状态 / 会话不存在 / db 不存在 → 均探测不到,认领退回新跑。"""
+ _write_checkpoint_db(
+ tmp_path,
+ "C-ERR",
+ node="feedback_handler",
+ node_status="__error__",
+ questions="1. 问题",
+ )
+
+ with patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path)):
+ assert dt._probe_resumable_checkpoint("C-ERR") is None
+ assert dt._probe_resumable_checkpoint("C-UNKNOWN") is None
+ (tmp_path / "data" / "checkpointer.db").unlink()
+ with patch.object(dt, "_resolve_skill_root", return_value=str(tmp_path)):
+ assert dt._probe_resumable_checkpoint("C-ERR") is None
+ with patch.object(dt, "_resolve_skill_root", return_value=""):
+ assert dt._probe_resumable_checkpoint("C-ERR") is None
+
+
+async def test_execute_claims_feedback_stage_from_checkpoint_probe():
+ """checkpointer.db 探测到停研究问题阶段 → 出反馈卡,state 进入 wait_feedback。"""
+ probe = {
+ "node": "feedback_handler",
+ "questions": ["1. 重点研究哪些品类?", "2. 覆盖哪些市场?"],
+ }
+ model = _Model(_option_payload("重点研究哪些品类?", "覆盖哪些市场?"))
+ with (
+ patch.object(
+ de, "_probe_resumable_checkpoint", new=Mock(return_value=probe)
+ ) as probe_mock,
+ patch.object(de, "_call_deepresearch_stream_impl", new=AsyncMock()) as stream,
+ ):
+ result, saved = await _invoke(model=model, conversation_id="C-FB")
+
+ probe_mock.assert_called_once_with("C-FB")
+ stream.assert_not_awaited()
+ assert result["kind"] == "interaction"
+ assert result["interaction"]["query"] == "请回答以下研究主题澄清问题"
+ cards = result["interaction"]["questions"]
+ assert [card["question"] for card in cards] == [
+ "重点研究哪些品类?",
+ "覆盖哪些市场?",
+ ]
+ assert all(len(card["options"]) == 2 for card in cards)
+ final = saved[-1]
+ assert final["phase"] == "wait_feedback"
+ assert final["conversation_id"] == "C-FB"
+ assert final["questions"] == ["重点研究哪些品类?", "覆盖哪些市场?"]
+
+
+async def test_execute_claims_outline_stage_from_checkpoint_probe():
+ """checkpointer.db 探测到停大纲确认 → 无需内存缓存直接出审阅卡(跨重启认领)。"""
+ probe = {
+ "node": "outline_interaction",
+ "outline_json": {
+ "title": "智能家电竞争格局研究",
+ "thought": "先规模后玩家",
+ "sections": [
+ {"title": "市场规模", "is_core_section": True},
+ {"title": "主要玩家", "is_core_section": False},
+ ],
+ },
+ }
+ 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-OL")
+
+ stream.assert_not_awaited()
+ assert result["kind"] == "interaction"
+ final = saved[-1]
+ assert final["phase"] == "wait_outline"
+ assert final["conversation_id"] == "C-OL"
+ assert final["outline_presented"] is True
+ question = result["interaction"]["questions"][0]
+ assert "**研究思路**:先规模后玩家" in question["preview"]["text"]
+ assert "### P1: 市场规模(重点)" in question["preview"]["text"]
+ assert "### P2: 主要玩家" in question["preview"]["text"]
+
+
+async def test_execute_restarts_fresh_when_checkpoint_lacks_questions():
+ """db 指向研究问题阶段但取不到问题清单 → 认领失败,换全新 id 重跑。"""
+ outcome = {
+ "status": "error",
+ "error_code": "runner_failed",
+ "error": "boom",
+ }
+ route_token = dt.push_deepresearch_route("R1", "CH1", "S3")
+ try:
+ with (
+ patch.object(
+ de,
+ "_probe_resumable_checkpoint",
+ new=Mock(return_value={"node": "feedback_handler"}),
+ ),
+ 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-FB2")
+ 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-FB2"
+
+
@pytest.mark.asyncio
async def test_invalid_option_generation_retries_then_keeps_free_text_questions():
questions = ["重点研究哪些品类?", "覆盖哪些市场?"]
diff --git a/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py b/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py
index b0a7d61e51..36825658c4 100644
--- a/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py
+++ b/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py
@@ -1157,6 +1157,117 @@ async def test_feedback_handler_interrupt_behavior_unchanged(tmp_path: Path):
assert "preview" not in marker
+async def test_outline_interrupt_resume_hint_pins_resume_contract(tmp_path: Path):
+ """interrupted outline_interaction outcome embeds a self-describing resume_hint."""
+ outline = json.dumps(
+ {"title": "AI Agent", "sections": [{"id": "1", "title": "架构"}]},
+ ensure_ascii=False,
+ )
+ proc = _Proc(
+ [
+ json.dumps({"__deepsearch_status__": "started", "conversation_id": "C1"}),
+ json.dumps({"agent": "outline", "content": outline}, ensure_ascii=False),
+ json.dumps(
+ {
+ "__deepsearch_status__": "interrupted",
+ "agent": "outline_interaction",
+ "conversation_id": "C1",
+ "outline": outline,
+ },
+ ensure_ascii=False,
+ ),
+ ]
+ )
+ route = {
+ "request_id": "R1",
+ "channel_id": "CH1",
+ "session_id": "S1",
+ "service_id": "default",
+ "agent_id": "default",
+ }
+ artifact = dt._ProgressArtifact(Path("/private/progress"), (1, 2), (3, 4))
+ remove = Mock()
+ manager = Mock()
+ patches = _stream_patches(proc, route=route)
+ try:
+ with ExitStack() as stack:
+ for item in patches:
+ stack.enter_context(item)
+ stack.enter_context(patch.object(dt, "WebSocketGatewayPushTransport", return_value=AsyncMock()))
+ stack.enter_context(patch.object(dt, "get_deepresearch_manager", return_value=manager))
+ stack.enter_context(patch.object(dt, "_create_progress_artifact", return_value=artifact))
+ stack.enter_context(patch.object(dt, "_remove_progress_artifact", remove))
+ outcome = json.loads(
+ await dt.deepresearch_stream._func(action="start", query="q", file_name="report")
+ )
+
+ assert outcome["status"] == "interrupted"
+ hint = outcome["resume_hint"]
+ assert hint["action"] == "resume"
+ assert hint["node"] == "outline_interaction"
+ assert hint["conversation_id"] == "C1"
+ assert "outline_confirm" in hint["valid_selected_options"]
+ assert "outline_use_edited" in hint["valid_selected_options"]
+ example = json.loads(hint["interaction_result_example"])
+ assert example["answers"][0]["selected_options"] == ["outline_confirm"]
+ assert "Never answer on the user's behalf" in hint["guidance"]
+ finally:
+ with dt._OUTLINE_JSON_CACHES_GUARD:
+ dt._OUTLINE_JSON_CACHES.clear()
+ with dt._OUTLINE_TITLE_CACHES_GUARD:
+ dt._OUTLINE_TITLE_CACHES.clear()
+
+
+async def test_feedback_handler_interrupt_resume_hint_pins_feedback_contract(tmp_path: Path):
+ """interrupted feedback_handler outcome embeds a feedback-oriented resume_hint."""
+ proc = _Proc(
+ [
+ json.dumps({"__deepsearch_status__": "started", "conversation_id": "C2"}),
+ json.dumps(
+ {
+ "__deepsearch_status__": "interrupted",
+ "agent": "feedback_handler",
+ "conversation_id": "C2",
+ "questions": [{"id": "q1", "question": "什么?"}],
+ },
+ ensure_ascii=False,
+ ),
+ ]
+ )
+ route = {
+ "request_id": "R1",
+ "channel_id": "CH1",
+ "session_id": "S1",
+ "service_id": "default",
+ "agent_id": "default",
+ }
+ artifact = dt._ProgressArtifact(Path("/private/progress"), (1, 2), (3, 4))
+ remove = Mock()
+ manager = Mock()
+ 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=AsyncMock()))
+ stack.enter_context(patch.object(dt, "get_deepresearch_manager", return_value=manager))
+ stack.enter_context(patch.object(dt, "_create_progress_artifact", return_value=artifact))
+ stack.enter_context(patch.object(dt, "_remove_progress_artifact", remove))
+ outcome = json.loads(
+ await dt.deepresearch_stream._func(action="start", query="q", file_name="report")
+ )
+
+ assert outcome["status"] == "interrupted"
+ hint = outcome["resume_hint"]
+ assert hint["action"] == "resume"
+ assert hint["node"] == "feedback_handler"
+ assert hint["conversation_id"] == "C2"
+ assert hint["feedback_required"] is True
+ assert "valid_selected_options" not in hint
+ assert "Never answer on the user's behalf" in hint["guidance"]
+
+
@pytest.mark.asyncio
async def test_repeated_outline_interrupt_returns_loop_error():
proc = _Proc(
@@ -4725,6 +4836,20 @@ def test_resolve_outline_malformed_result_raises_value_error(interaction_result:
dt._OUTLINE_TITLE_CACHES.clear()
+def test_resolve_outline_unknown_choice_error_lists_valid_choices() -> None:
+ """未知 selected_options 的报错必须列出全部合法值,避免调用方瞎猜参数。"""
+ with pytest.raises(ValueError) as excinfo:
+ dt._resolve_outline_interaction_feedback(
+ _outline_interaction_result("definitely_not_a_choice"),
+ conversation_id="C1",
+ route=_outline_route(),
+ )
+ message = str(excinfo.value)
+ assert "expected one of" in message
+ assert "outline_confirm" in message
+ assert "outline_use_edited" in message
+
+
def test_resolve_outline_cancel_status_returns_cancel_feedback() -> None:
"""AskUserQuestion status=cancelled -> interrupt_feedback=cancel, empty feedback."""
feedback = dt._resolve_outline_interaction_feedback(