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

refactor(ask-user): unify answer response contract

openJiuwen-bot82cab38ca9c9
diff --git a/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py b/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py
index e26c5c9a1c..a11e6d0b7b 100644
--- a/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py
@@ -22,21 +22,21 @@ import logging
import uuid
from typing import Any, Iterable, Mapping, Optional
-from pydantic import BaseModel, Field
-
from openjiuwen.core.foundation.llm.schema.tool_call import ToolCall
from openjiuwen.core.foundation.tool import Tool
from openjiuwen.core.foundation.tool.base import ToolCard
from openjiuwen.core.single_agent.interrupt import InterruptRequest
from openjiuwen.core.single_agent.rail import AgentCallbackContext
from openjiuwen.harness.prompts import resolve_language
-from openjiuwen.harness.rails.interrupt.ask_user_rail import (
- AskUserPayload,
- AskUserRail,
-)
+from openjiuwen.harness.rails.interrupt.ask_user_rail import AskUserRail
from openjiuwen.harness.rails.interrupt.interrupt_base import (
InterruptDecision,
)
+from jiuwenswarm.common.schema.ask_user import (
+ AskUserResponseError,
+ ask_user_response_schema,
+ parse_ask_user_response,
+)
logger = logging.getLogger(__name__)
@@ -95,6 +95,22 @@ _QUESTIONS_ITEM_SCHEMA: dict[str, Any] = {
"default": False,
"description": "Allow multiple selections instead of just one.",
},
+ "preview": {
+ "type": "object",
+ "description": (
+ "Optional question-level artifact preview. Use this for a shared "
+ "outline or document that the choices confirm or edit."
+ ),
+ "properties": {
+ "title": {"type": "string"},
+ "text": {"type": "string", "minLength": 1},
+ "format": {"type": "string", "enum": ["markdown"]},
+ "editable": {"type": "boolean"},
+ "outline_ref": {"type": "string"},
+ "meta": {"type": "object"},
+ },
+ "required": ["text"],
+ },
},
"required": ["question"],
}
@@ -124,7 +140,7 @@ EXTENDED_INPUT_PARAMS_EN: dict[str, Any] = {
"description": (
"Return the answered structured-question envelope as compact JSON "
"instead of readable text. Use only when a downstream tool must "
- "preserve status and the original answers array."
+ "preserve status and the canonical answers array."
),
},
},
@@ -154,7 +170,7 @@ EXTENDED_INPUT_PARAMS_CN: dict[str, Any] = {
"default": False,
"description": (
"将结构化问题的回答 envelope 作为紧凑 JSON 返回,而不是可读文本。"
- "仅当下游工具必须保留 status 和原始 answers 数组时使用。"
+ "仅当下游工具必须保留 status 和标准 answers 数组时使用。"
),
},
},
@@ -186,42 +202,6 @@ _EXTENDED_DESCRIPTION_CN: str = (
"仅在视觉对比有助于用户决策时使用。"
)
-# ---------------------------------------------------------------------------
-# Structured answer payload
-# ---------------------------------------------------------------------------
-
-
-class StructuredAskUserPayload(BaseModel):
- """Payload for structured user answers."""
-
- answers: dict[str, str | list[str]] = Field(
- default_factory=dict,
- description=(
- "Mapping of question text to selected option label(s). "
- "Value is a str for single-select, or list[str] for multi-select."
- ),
- )
-
-
-def _skipped_answer_has_user_input(item: Any) -> bool:
- """Return whether a skipped answer shell contains an effective response."""
- if not isinstance(item, dict):
- return True
- selected = item.get("selected_options")
- if isinstance(selected, list):
- if any(
- not isinstance(option, str) or bool(option.strip())
- for option in selected
- ):
- return True
- elif selected is not None:
- return True
- custom_input = item.get("custom_input")
- if custom_input is None:
- return False
- return not isinstance(custom_input, str) or bool(custom_input.strip())
-
-
# ---------------------------------------------------------------------------
# Extended AskUserTool
# ---------------------------------------------------------------------------
@@ -323,11 +303,8 @@ class StructuredAskUserRail(AskUserRail):
) -> InterruptDecision:
"""Handle interrupt resolution with structured answer support.
- For structured questions: user_input contains a dict with an `answers`
- key mapping question text → selected option label. We convert this to
- a rejection with the answer text.
-
- For plain query: delegate to parent class behavior (AskUserPayload).
+ All answers use the canonical ``status + answers[]`` response. The
+ readable and machine outputs are derived from that single value.
"""
args = self._parse_tool_args(tool_call)
return_json = args.get("return_json", False)
@@ -381,6 +358,18 @@ class StructuredAskUserRail(AskUserRail):
"must be a string when provided."
)
)
+ if "preview" in question:
+ preview = question["preview"]
+ preview_text = (
+ preview.get("text") if isinstance(preview, Mapping) else None
+ )
+ if not isinstance(preview_text, str) or not preview_text.strip():
+ return self.reject(
+ tool_result=(
+ f"[INVALID_ARGUMENT] questions[{question_index}].preview "
+ "must be an object with non-empty text."
+ )
+ )
if "options" not in question:
continue
options = question["options"]
@@ -418,130 +407,39 @@ class StructuredAskUserRail(AskUserRail):
# Detect if this was a structured questions call by checking tool_args
is_structured = questions_data is not None and len(questions_data) > 0
+ try:
+ response = parse_ask_user_response(user_input)
+ except AskUserResponseError as exc:
+ return self.reject(tool_result=f"[INVALID_ARGUMENT] {exc}")
- if is_structured:
- if isinstance(user_input, dict) and user_input.get("status") == "skipped":
- skipped_answers = user_input.get("answers")
- if (
- set(user_input) == {"status", "answers"}
- and isinstance(skipped_answers, list)
- and not any(
- _skipped_answer_has_user_input(answer)
- for answer in skipped_answers
- )
- ):
- return self.reject(
- tool_result=json.dumps(
- {"status": "skipped", "answers": []},
- ensure_ascii=False,
- separators=(",", ":"),
- )
- )
- return self.reject(
- tool_result=(
- "[INVALID_ARGUMENT] skipped responses must contain only "
- "status='skipped' and answers without selected options "
- "or custom input."
- )
- )
- try:
- if return_json:
- envelope = (
- user_input.get("_structured_response")
- if isinstance(user_input, dict)
- else None
- )
- if not (
- isinstance(envelope, dict)
- and envelope.get("status") == "answered"
- and isinstance(envelope.get("answers"), list)
- ):
- return self.reject(
- tool_result=(
- "[INVALID_ARGUMENT] return_json requires an answered "
- "structured response envelope."
- )
- )
- return self.reject(
- tool_result=json.dumps(
- {
- "status": "answered",
- "answers": envelope["answers"],
- },
- ensure_ascii=False,
- separators=(",", ":"),
- )
- )
-
- if isinstance(user_input, StructuredAskUserPayload):
- payload = user_input
- elif isinstance(user_input, dict):
- if "answers" in user_input:
- payload = StructuredAskUserPayload(
- answers=user_input.get("answers", {}),
- )
- else:
- # Frontend sends answers as {question: selected_option}
- payload = StructuredAskUserPayload(answers=user_input)
- elif isinstance(user_input, AskUserPayload):
- # Upstream AskUserPayload changed: answer (str) → answers (dict)
- free_text = getattr(user_input, "answer", None)
- if free_text is not None:
- payload = StructuredAskUserPayload(
- answers={"__free_text__": free_text},
- )
- else:
- payload = StructuredAskUserPayload(
- answers=user_input.answers,
- )
- elif isinstance(user_input, str):
- payload = StructuredAskUserPayload(
- answers={"__free_text__": user_input},
- )
- else:
- return self.interrupt(self._build_ask_request(tool_call))
-
- # Format answer as readable text for the LLM
- answer_parts = []
- for q_text, selected in payload.answers.items():
- if q_text == "__free_text__":
- answer_parts.append(selected if isinstance(selected, str) else ", ".join(selected))
- else:
- value_text = selected if isinstance(selected, str) else ", ".join(selected)
- answer_parts.append(f"{q_text}: {value_text}")
- answer_text = "\n".join(answer_parts) if answer_parts else ""
- if not answer_text.strip():
- # Empty resume (e.g. bare Other) must not look like a valid answer (#2330).
- return self.reject(
- tool_result=(
- "[INVALID_ARGUMENT] answers must include at least "
- "one non-empty response."
- )
- )
- logger.info(
- "[StructuredAskUserRail] Resolved structured answer: %s",
- answer_text,
- )
- return self.reject(tool_result=answer_text)
-
- except Exception as exc:
- logger.warning(
- "[StructuredAskUserRail] Failed to parse structured answer: %s, "
- "falling back to interrupt",
- exc,
+ machine_payload = response.to_dict(include_original_request=False)
+ if is_structured and return_json:
+ return self.reject(
+ tool_result=json.dumps(
+ machine_payload,
+ ensure_ascii=False,
+ separators=(",", ":"),
)
- return self.interrupt(self._build_ask_request(tool_call))
+ )
- # Plain query — delegate to parent which handles AskUserPayload.answers
- if isinstance(user_input, AskUserPayload):
- return await super().resolve_interrupt(
- ctx, tool_call, user_input, auto_confirm_config
+ if response.status == "skipped":
+ answer_text = "用户已跳过本次问答,未提供回答。"
+ elif is_structured:
+ answer_text = response.to_readable_text()
+ else:
+ answer_text = str(
+ {
+ answer.question or "__free_text__": answer.readable_value()
+ for answer in response.answers
+ }
)
- elif isinstance(user_input, str):
- return self.reject(tool_result=user_input)
- return await super().resolve_interrupt(
- ctx, tool_call, user_input, auto_confirm_config
+ if not answer_text:
+ answer_text = "用户未提供回答。"
+ logger.info(
+ "[StructuredAskUserRail] Resolved answer: %s",
+ answer_text,
)
+ return self.reject(tool_result=answer_text)
def _build_ask_request(self, tool_call: Optional[ToolCall]) -> InterruptRequest:
"""Build interrupt request. For structured questions, the questions data
@@ -549,7 +447,9 @@ class StructuredAskUserRail(AskUserRail):
interrupt handler). No need to attach questions to InterruptRequest
itself since from_tool_call() doesn't copy extra fields."""
request = super()._build_ask_request(tool_call)
- return request
+ return request.model_copy(
+ update={"payload_schema": ask_user_response_schema()}
+ )
def extract_questions(
self, tool_call: Optional[ToolCall]
diff --git a/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py b/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py
index 6bb04daa24..a498425378 100644
--- a/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py
+++ b/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py
@@ -695,6 +695,9 @@ def _build_multi_questions(questions_data: list) -> list:
"options": options,
"multi_select": q.get("multi_select", False),
}
+ preview = _normalize_question_preview(q.get("preview"))
+ if preview is not None:
+ question_payload["preview"] = preview
questions.append(question_payload)
return questions
@@ -735,6 +738,29 @@ def _normalize_question_option(option: dict[str, Any]) -> dict[str, Any]:
return normalized
+def _normalize_question_preview(preview: Any) -> dict[str, Any] | None:
+ if not isinstance(preview, dict):
+ return None
+ text = preview.get("text")
+ if not isinstance(text, str) or not text.strip():
+ return None
+
+ normalized: dict[str, Any] = {"text": text}
+ for field in ("title", "outline_ref"):
+ value = preview.get(field)
+ if isinstance(value, str):
+ normalized[field] = value
+ if preview.get("format") == "markdown":
+ normalized["format"] = "markdown"
+ editable = preview.get("editable")
+ if isinstance(editable, bool):
+ normalized["editable"] = editable
+ meta = preview.get("meta")
+ if isinstance(meta, dict):
+ normalized["meta"] = dict(meta)
+ return normalized
+
+
def _default_interrupt_options() -> list[dict[str, str]]:
return [
{"label": "本次允许", "description": "仅本次授权执行"},
diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/runtime.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/runtime.py
index a1435e0e06..c67fb65938 100644
--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/runtime.py
+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/runtime.py
@@ -1,4 +1,4 @@
-"""Isolated interpreter selection and child environment for DeepResearch."""
+"""Jiuwen interpreter reuse and isolated child environment for DeepResearch."""
from __future__ import annotations
@@ -6,6 +6,7 @@ import asyncio
import json
import os
import stat
+import sys
import tempfile
import zipfile
from contextlib import asynccontextmanager, suppress
@@ -13,9 +14,8 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Any, AsyncIterator
-from jiuwenswarm.common.local_env_config import export_spawn_environ, read_env
+from jiuwenswarm.common.local_env_config import export_spawn_environ
-_PYTHON_EXECUTABLE_ENV = "DEEPRESEARCH_PYTHON_EXECUTABLE"
_ALLOWED_PROXY_KEYS = (
"HTTP_PROXY",
"http_proxy",
@@ -43,7 +43,7 @@ _BRIDGE_JSON_MAX_CONTAINER = 20_000
class DeepResearchRuntimeError(RuntimeError):
- """Raised when the configured isolated DeepResearch runtime is unusable."""
+ """Raised when the DeepResearch child runtime is unusable."""
@dataclass(frozen=True, slots=True)
@@ -54,23 +54,19 @@ class _BridgeArtifact:
descriptor: int
-def resolve_python_executable() -> Path:
- """Resolve and validate the explicitly configured virtualenv interpreter."""
- configured = read_env(_PYTHON_EXECUTABLE_ENV, "").strip()
- if not configured:
- raise DeepResearchRuntimeError("runtime_python_missing")
+def _virtualenv_root(executable: Path) -> Path | None:
+ root = executable.parent.parent
+ return root if (root / "pyvenv.cfg").is_file() else None
+
- candidate = Path(configured)
+def resolve_python_executable() -> Path:
+ """Return the interpreter that is running JiuwenSwarm."""
+ candidate = Path(sys.executable)
if not candidate.is_absolute():
raise DeepResearchRuntimeError("runtime_python_invalid")
lexical_path = Path(os.path.abspath(os.fspath(candidate)))
- venv_root = lexical_path.parent.parent
- if (
- not lexical_path.is_file()
- or not os.access(lexical_path, os.X_OK)
- or not (venv_root / "pyvenv.cfg").is_file()
- ):
+ if not lexical_path.is_file() or not os.access(lexical_path, os.X_OK):
raise DeepResearchRuntimeError("runtime_python_invalid")
return lexical_path
@@ -79,7 +75,7 @@ def build_child_env(executable: Path) -> dict[str, str]:
"""Build the minimal process environment for an isolated DeepResearch child."""
python = Path(executable)
bin_dir = python.parent
- venv_root = bin_dir.parent
+ venv_root = _virtualenv_root(python)
child_env = export_spawn_environ()
for key in _FORBIDDEN_INHERITED_KEYS:
@@ -97,7 +93,10 @@ def build_child_env(executable: Path) -> dict[str, str]:
if inherited_path
else str(bin_dir)
)
- child_env["VIRTUAL_ENV"] = str(venv_root)
+ if venv_root is None:
+ child_env.pop("VIRTUAL_ENV", None)
+ else:
+ child_env["VIRTUAL_ENV"] = str(venv_root)
return child_env
diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/stream_router.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/stream_router.py
index 03f4cb6a78..2e3b73f1fa 100644
--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/stream_router.py
+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/stream_router.py
@@ -486,6 +486,41 @@ def _format_outline_markdown(data: dict[str, Any]) -> str | None:
return "\n\n".join(blocks)
+def _format_outline_card_markdown(data: dict[str, Any]) -> str | None:
+ """Format outline JSON as a card-style markdown with ## 页面规划 and ### P{N}: entries.
+
+ The (重点) suffix becomes part of the display title after the colon.
+ """
+ title = _text_field(data.get("title"))
+ thought = _text_field(data.get("thought"))
+ raw_sections = data.get("sections")
+ if not title or not isinstance(raw_sections, list):
+ return None
+
+ sections: list[tuple[dict[str, Any], str]] = []
+ for section in raw_sections:
+ if not isinstance(section, dict):
+ continue
+ section_title = _text_field(section.get("title"))
+ if section_title:
+ sections.append((section, section_title))
+ if not sections:
+ return None
+
+ blocks: list[str] = []
+ blocks.append(f"# 大纲:{_escape_markdown_text(title)}")
+ if thought:
+ blocks.append(f"**研究思路**:{_escape_markdown_text(thought)}")
+
+ section_lines: list[str] = ["## 页面规划"]
+ for section_number, (section, section_title) in enumerate(sections, start=1):
+ core_suffix = "(重点)" if section.get("is_core_section") is True else ""
+ safe_section_title = _escape_markdown_text(section_title)
+ section_lines.append(f"### P{section_number}: {safe_section_title}{core_suffix}")
+ blocks.append("\n".join(section_lines))
+ return "\n\n".join(blocks)
+
+
def _format_plan_markdown(data: dict[str, Any]) -> str | None:
title = _text_field(data.get("title"))
thought = _text_field(data.get("thought"))
@@ -700,6 +735,23 @@ def _all_sections_completed(state: RouterState) -> bool:
return bool(expected) and expected.issubset(state.completed_section_indices)
+def _is_successful_workflow_end(chunk: dict, agent: str, event: str) -> bool:
+ """Recognize the SDK EndNode result emitted after the workflow has finished."""
+ if (
+ agent != "end"
+ or event != "summary_response"
+ or str(chunk.get("section_idx", "0")).strip() not in {"", "0"}
+ ):
+ return False
+ result = _as_json_object(chunk.get("content"))
+ return bool(
+ result
+ and isinstance(result.get("response_content"), str)
+ and result["response_content"].strip()
+ and not result.get("exception_info")
+ )
+
+
def _final_report_boundary(event_type: str) -> dict:
return {
"event_type": event_type,
@@ -870,6 +922,24 @@ def route_chunk(chunk: dict, state: RouterState) -> list[dict]:
state.interrupt_conversation_id = cid
return frames
+ # 用户输入结束:大纲已根据修改重新生成,自动确认继续研究
+ if str(chunk.get("event")) == "user_input_ended":
+ frames.append({
+ "event_type": "chat.reasoning",
+ "task_id": "deepresearch_stage_2",
+ "stream_source_id": "dr_outline",
+ "content": "大纲已根据您的修改重新生成,自动确认继续研究",
+ })
+ return frames
+
+ # DeepSearch emits a successful top-level EndNode result before the runner's
+ # terminal marker. It is the formal workflow boundary even when an SDK
+ # version omits one of the parallel sub_reporter ``done`` events. Section
+ # ``end``/``SECTION END`` frames are excluded by section_idx and content.
+ if _is_successful_workflow_end(chunk, agent, event):
+ frames.extend(start_final_report_processing(state))
+ return frames
+
if not agent or agent in _SKIP_NODES:
return frames
diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py
index e28ccb7663..1a8e85a645 100644
--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py
+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py
@@ -38,6 +38,7 @@ from jiuwenswarm.agents.harness.common.tools.deepresearch.path_safety import (
)
from jiuwenswarm.agents.harness.common.tools.deepresearch.stream_router import (
RouterState,
+ _format_outline_card_markdown,
advance_stage,
build_interrupt_prompt,
collected_questions,
@@ -186,6 +187,10 @@ _OUTLINE_TITLE_CACHES: dict[
tuple[str, str, str], dict[str, dict[str, str]]
] = {}
_OUTLINE_TITLE_CACHES_GUARD = threading.Lock()
+_OUTLINE_JSON_CACHES: dict[
+ tuple[str, str, str], dict[str, dict[str, Any]]
+] = {}
+_OUTLINE_JSON_CACHES_GUARD = threading.Lock()
class _ReportPublicationCollision(FileExistsError):
@@ -341,6 +346,60 @@ def _clear_outline_title_cache(
_OUTLINE_TITLE_CACHES.pop(key, None)
+def _get_cached_outline_json(
+ route: dict[str, object], conversation_id: object
+) -> dict[str, Any]:
+ conversation = str(conversation_id or "").strip()
+ if not conversation:
+ return {}
+ key = _outline_cache_key(route)
+ with _OUTLINE_JSON_CACHES_GUARD:
+ cache = _OUTLINE_JSON_CACHES.get(key)
+ return dict(cache.get(conversation, {})) if cache is not None else {}
+
+
+def _cache_outline_json(
+ route: dict[str, object],
+ conversation_id: object,
+ outline_json: dict[str, Any],
+) -> None:
+ conversation = str(conversation_id or "").strip()
+ if not conversation or not isinstance(outline_json, dict):
+ return
+ serialized = json.dumps(outline_json, ensure_ascii=False)
+ if len(serialized) > DEEPRESEARCH_OUTLINE_CACHE_TEXT_CHARS:
+ return
+ key = _outline_cache_key(route)
+ with _OUTLINE_JSON_CACHES_GUARD:
+ cache = _OUTLINE_JSON_CACHES.get(key)
+ if cache is None:
+ while len(_OUTLINE_JSON_CACHES) >= DEEPRESEARCH_OUTLINE_CACHE_TENANTS:
+ _OUTLINE_JSON_CACHES.pop(next(iter(_OUTLINE_JSON_CACHES)))
+ cache = {}
+ _OUTLINE_JSON_CACHES[key] = cache
+ if conversation in cache:
+ cache.pop(conversation)
+ while len(cache) >= DEEPRESEARCH_OUTLINE_CACHE_CONVERSATIONS:
+ cache.pop(next(iter(cache)))
+ cache[conversation] = dict(outline_json)
+
+
+def _clear_outline_json_cache(
+ route: dict[str, object], conversation_id: object
+) -> None:
+ conversation = str(conversation_id or "").strip()
+ if not conversation:
+ return
+ key = _outline_cache_key(route)
+ with _OUTLINE_JSON_CACHES_GUARD:
+ cache = _OUTLINE_JSON_CACHES.get(key)
+ if cache is None:
+ return
+ cache.pop(conversation, None)
+ if not cache:
+ _OUTLINE_JSON_CACHES.pop(key, None)
+
+
def _map_provider_to_type(provider: str) -> str:
value = provider.strip().lower()
return _PROVIDER_TO_TYPE.get(value, value)
@@ -817,6 +876,116 @@ def _normalize_feedback_handler_resume_feedback(
return feedback
+_OUTLINE_EDITED_HEADING_RE = re.compile(r"^###\s*P(\d+):\s*(.*)$")
+_OUTLINE_CORE_SUFFIX = "(重点)"
+_OUTLINE_CONFIRM_CHOICES = {
+ "outline_confirm",
+ "确认大纲,继续研究",
+ "确认",
+}
+_OUTLINE_EDIT_CHOICES = {
+ "outline_use_edited",
+ "需要修改",
+ "其他",
+ "Other",
+}
+
+
+def _resolve_outline_interaction_feedback(
+ interaction_result: str,
+ *,
+ conversation_id: str,
+ route: dict[str, object],
+) -> str:
+ """Resolve resume feedback for the ``outline_interaction`` node.
+
+ Returns a JSON string ready for the SDK ``--feedback`` argument:
+
+ * ``outline_confirm`` -> ``{"interrupt_feedback":"accepted","feedback":""}``
+ * ``outline_use_edited`` -> ``{"interrupt_feedback":"revise_outline","feedback":"<outline JSON string>"}``
+ * user cancel/error status -> ``{"interrupt_feedback":"cancel","feedback":""}``
+
+ Raises ``ValueError`` on any malformed ``interaction_result`` (fail closed);
+ the caller returns the ``outline_interaction_invalid_result`` error outcome
+ without spawning the subprocess.
+ """
+ if not interaction_result:
+ raise ValueError("interaction_result is empty")
+ try:
+ result = json.loads(interaction_result)
+ except (TypeError, json.JSONDecodeError) as exc:
+ raise ValueError("interaction_result 必须是合法 JSON") from exc
+ if not isinstance(result, dict):
+ raise ValueError("interaction_result 必须是 JSON 对象")
+
+ status_value = str(result.get("status") or "").strip().lower()
+ if status_value in {"cancelled", "error"}:
+ return '{"interrupt_feedback":"cancel","feedback":""}'
+
+ answers = result.get("answers")
+ if status_value == "skipped":
+ if isinstance(answers, list) and any(
+ _interaction_answer_has_user_input(answer) for answer in answers
+ ):
+ raise ValueError("skipped interaction_result 不能包含有效回答")
+ return '{"interrupt_feedback":"accepted","feedback":""}'
+
+ if not isinstance(answers, list) or not answers:
+ raise ValueError("interaction_result.answers 缺失或为空")
+ first_answer = answers[0]
+ if not isinstance(first_answer, dict):
+ raise ValueError("interaction_result.answers[0] 必须是 JSON 对象")
+ selected_options = first_answer.get("selected_options")
+ if not isinstance(selected_options, list) or not selected_options:
+ raise ValueError("selected_options 缺失或为空")
+ choice = selected_options[0]
+
+ if choice in _OUTLINE_CONFIRM_CHOICES:
+ return '{"interrupt_feedback":"accepted","feedback":""}'
+
+ if choice in _OUTLINE_EDIT_CHOICES:
+ cached_outline = _get_cached_outline_json(route, conversation_id)
+ sections = cached_outline.get("sections") if isinstance(cached_outline, dict) else None
+ if not cached_outline or not isinstance(sections, list) or not sections:
+ raise ValueError("cached Outline JSON missing or empty")
+
+ custom_input = str(first_answer.get("custom_input") or "")
+ edited_titles: dict[int, str] = {}
+ for line in custom_input.split("\n"):
+ match = _OUTLINE_EDITED_HEADING_RE.match(line)
+ if not match:
+ continue
+ page_num = int(match.group(1))
+ raw_title = match.group(2).rstrip()
+ if raw_title.endswith(_OUTLINE_CORE_SUFFIX):
+ raw_title = raw_title[: -len(_OUTLINE_CORE_SUFFIX)].rstrip()
+ edited_titles[page_num] = raw_title
+ if not edited_titles:
+ raise ValueError("no ### P{N}: title patterns in custom_input")
+
+ # Copy sections to avoid mutating the cache (the getter returns a
+ # shallow copy whose nested ``sections`` list is still shared).
+ new_sections = [dict(section) for section in sections]
+ new_outline = {**cached_outline, "sections": new_sections}
+ for page_num, edited_title in edited_titles.items():
+ idx = page_num - 1
+ if 0 <= idx < len(new_sections):
+ new_sections[idx]["title"] = edited_title
+ # Page count mismatch: skip out-of-range pages, do NOT add/remove
+ # sections. Caller's contract: only matching indices update.
+
+ outline_json_str = json.dumps(new_outline, ensure_ascii=False)
+ return json.dumps(
+ {
+ "interrupt_feedback": "revise_outline",
+ "feedback": outline_json_str,
+ },
+ ensure_ascii=False,
+ )
+
+ raise ValueError(f"unknown selected_options[0]={choice!r}")
+
+
def _resolve_skill_root() -> str:
"""Resolve only from configured shared skill roots."""
task_overlay = get_task_env_overlay()
@@ -1505,6 +1674,31 @@ async def deepresearch_stream( # pylint: disable=huawei-too-many-arguments
},
ensure_ascii=False,
)
+ elif node == "outline_interaction":
+ if not interaction_result:
+ return json.dumps(
+ {
+ "status": "error",
+ "error_code": "outline_interaction_invalid_result",
+ "error": "outline_interaction resume requires interaction_result",
+ },
+ ensure_ascii=False,
+ )
+ try:
+ feedback = _resolve_outline_interaction_feedback(
+ interaction_result,
+ conversation_id=conversation_id,
+ route=route,
+ )
+ except ValueError as exc:
+ return json.dumps(
+ {
+ "status": "error",
+ "error_code": "outline_interaction_invalid_result",
+ "error": f"outline_interaction interaction_result invalid: {exc}",
+ },
+ ensure_ascii=False,
+ )
argv = [
str(python_bin),
script,
@@ -1677,6 +1871,9 @@ async def deepresearch_stream( # pylint: disable=huawei-too-many-arguments
_clear_outline_title_cache(
route, outcome.get("conversation_id", conversation_id)
)
+ _clear_outline_json_cache(
+ route, outcome.get("conversation_id", conversation_id)
+ )
if (
outcome.get("status") == "interrupted"
and outcome.get("node_id") == "outline_interaction"
@@ -1693,14 +1890,6 @@ async def deepresearch_stream( # pylint: disable=huawei-too-many-arguments
},
ensure_ascii=False,
)
- return await _call_deepresearch_stream_impl(
- action="resume",
- conversation_id=str(outcome.get("conversation_id", conversation_id)),
- feedback='{"interrupt_feedback":"accepted","feedback":""}',
- node="outline_interaction",
- file_name=file_name,
- _router_state=outcome.pop("_router_state", None),
- )
outcome.pop("_router_state", None)
outcome = _sanitize_terminal_outcome(outcome, config)
return json.dumps(outcome, ensure_ascii=False)
@@ -1851,6 +2040,7 @@ async def _consume_stream(
questions = collected_questions(state)
if questions:
marker["questions"] = questions
+ outline_json_dict: dict[str, Any] | None = None
missing_outline = (
node_id == "outline_interaction"
and not marker.get("outline")
@@ -1861,7 +2051,18 @@ async def _consume_stream(
and state.outline_parts
)
if missing_outline:
- marker["outline"] = "".join(state.outline_parts)
+ card_markdown = ""
+ try:
+ outline_json_dict = json.loads("".join(state.outline_parts))
+ formatted = _format_outline_card_markdown(outline_json_dict)
+ if formatted:
+ card_markdown = formatted
+ else:
+ outline_json_dict = {}
+ except (json.JSONDecodeError, TypeError):
+ outline_json_dict = {}
+ marker["outline"] = card_markdown
+ marker["preview"] = {"text": card_markdown}
resolved_cid = str(
chunk.get("conversation_id")
or outcome_cid
@@ -1877,6 +2078,8 @@ 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 node_id == "user_feedback_processor" and state.report_parts:
report = "".join(state.report_parts)
marker["report"] = report[:6000] + (
@@ -1890,8 +2093,6 @@ async def _consume_stream(
"prompt": build_interrupt_prompt(node_id, state, marker, query),
"_router_state": state,
}
- if node_id == "outline_interaction":
- outcome["interaction_policy"] = "silent_auto_accept"
continue
if status_value == "completed":
final_result = chunk.get("final_result")
diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch_task_manager.py b/jiuwenswarm/agents/harness/common/tools/deepresearch_task_manager.py
index da353e9ca2..8f71d3386b 100644
--- a/jiuwenswarm/agents/harness/common/tools/deepresearch_task_manager.py
+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch_task_manager.py
@@ -398,6 +398,12 @@ class DeepResearchTaskManager:
section_titles[match.group(1)] = match.group(2).strip()
continue
match = re.match(r"(\d+)[.、)]\s*(.+)", heading)
+ if match:
+ section_titles[match.group(1)] = match.group(2).strip()
+ continue
+ match = re.match(
+ r"[Pp](\d+)(?:\s*[::、.)-]\s*|\s+)(.+)", heading
+ )
if match:
section_titles[match.group(1)] = match.group(2).strip()
continue
diff --git a/jiuwenswarm/channels/web/frontend/package.json b/jiuwenswarm/channels/web/frontend/package.json
index bae68a8df4..6ae1b6cd38 100644
--- a/jiuwenswarm/channels/web/frontend/package.json
+++ b/jiuwenswarm/channels/web/frontend/package.json
@@ -25,6 +25,7 @@
"test:history-pagination": "tsc src/features/historyPagination.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/history-pagination --skipLibCheck --noEmitOnError && node --test tests/historyPagination.test.mjs",
"test:artifact-collection": "esbuild src/components/ArtifactsPanel/artifactCollection.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/artifact-collection/artifactCollection.mjs && node --test tests/artifactCollection.test.mjs",
"test:desktop-save": "esbuild src/utils/desktopSave.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/desktop-save/desktopSave.mjs && node --test tests/desktopSave.test.mjs",
+ "test:ask-user-submission": "tsc src/components/InteractionSlot/interactionSubmission.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/ask-user-submission --skipLibCheck --noEmitOnError && node --test tests/askUserSubmission.test.mjs",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsx
index 2e5f25701f..dd6f56bf0f 100644
--- a/jiuwenswarm/channels/web/frontend/src/App.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx
@@ -42,7 +42,7 @@ import {
import { useWebSocket, mergePersistedGoalCompletionMessages, stampGoalObjectiveMessages } from './hooks';
import { webRequest } from './services/webClient';
import { useTeamPanelState } from './features/teamPanelState';
-import { AgentMode, MediaItem, UserAnswer, ModelEntry, type Session } from './types';
+import { AgentMode, MediaItem, UserAnswer, ModelEntry, type Session, type UserAnswerStatus } from './types';
import {
ensureSessionRuntimes,
useSessionStore,
@@ -1804,10 +1804,15 @@ function AppContent() {
[cancel, clearGoal, mode, pause]
);
- const handleUserAnswer = useCallback((requestId: string, answers: UserAnswer[], source?: string) => {
+ const handleUserAnswer = useCallback((
+ requestId: string,
+ answers: UserAnswer[],
+ source?: string,
+ status?: UserAnswerStatus,
+ ) => {
const currentSessionId = sessionIdRef.current;
if (!currentSessionId || currentSessionId === NEW_CONVERSATION_ID) return;
- void sendUserAnswer(currentSessionId, requestId, answers, source);
+ void sendUserAnswer(currentSessionId, requestId, answers, source, status);
}, [sendUserAnswer]);
const handleLoadMoreHistory = useCallback(async () => {
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx
index 66fa5bbc34..50baeb3cd4 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx
@@ -10,7 +10,7 @@ import { ArrowRight, CheckCircle2, ClipboardList, Copy, Info, LoaderCircle, Shar
import type { TFunction } from 'i18next';
import { useTranslation } from 'react-i18next';
import { useChatStore, useHarnessStore, useSessionStore, useTodoStore } from '../../stores';
-import { AgentMode, MediaItem, Message, UserAnswer, type ProjectInfo } from '../../types';
+import { AgentMode, MediaItem, Message, UserAnswer, type ProjectInfo, type UserAnswerStatus } from '../../types';
import type { HumanShareCommand } from '../../stores/sessionStore';
import { MessageList } from './MessageList';
import { ContextCompressionLines } from './MessageItem';
@@ -69,7 +69,12 @@ interface ChatPanelProps {
onCancel: () => void;
onSwitchMode: (mode: AgentMode) => void;
isProcessing: boolean;
- onUserAnswer: (requestId: string, answers: UserAnswer[], source?: string) => void;
+ onUserAnswer: (
+ requestId: string,
+ answers: UserAnswer[],
+ source?: string,
+ status?: UserAnswerStatus,
+ ) => void;
onExportShare?: () => void | Promise<void>;
isExportingShare?: boolean;
canExportShare?: boolean;
diff --git a/jiuwenswarm/channels/web/frontend/src/components/InteractionSlot/InteractionPrompt.tsx b/jiuwenswarm/channels/web/frontend/src/components/InteractionSlot/InteractionPrompt.tsx
index 12235e78ed..27b3e16a91 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/InteractionSlot/InteractionPrompt.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/InteractionSlot/InteractionPrompt.tsx
@@ -11,7 +11,8 @@ import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { FileText, ChevronLeft, ChevronRight } from 'lucide-react';
import { useChatStore } from '../../stores';
-import type { AskUserQuestionPayload, Message, Question, UserAnswer } from '../../types';
+import type { AskUserQuestionPayload, Message, Question, UserAnswer, UserAnswerStatus } from '../../types';
+import { buildEmptyAskUserAnswers, resolveAskUserStatus } from './interactionSubmission';
import { buildQaSummaryContent, type QaSummaryData, type QaSummaryItem } from './qaSummary';
/** 后端为「有选项的问题」追加的自定义输入占位项。 */
@@ -20,22 +21,14 @@ const CUSTOM_OPTION_LABEL = 'Other';
/** 多轮上限(产品约定:多轮确认最多不超过 4 轮)。 */
const MAX_PAGES = 4;
-/**
- * 「跳过」/「取消」时回传给后端的标记文本。
- *
- * 协议里没有独立于 options 之外的「跳过」/「取消」信号——ask_user 的结构化问答
- * 唯一的输出通道就是 selected_options / custom_input 拼成的文本,最终由 LLM
- * 读文本自行判断语义(见 jiuwenswarm/agents/harness/common/rails/ask_user_rail.py
- * StructuredAskUserRail.resolve_interrupt)。这里比照后端既有的同类标记文本
- * (如 interface.py 里硬编码的「用户拒绝」「用户希望继续规划」)不做 i18n,
- * 因为它是喂给 LLM 的内部信号而非界面文案。
- */
-const SKIPPED_ANSWER_TEXT = '用户已跳过此题,未选择任何选项。';
-const CANCELLED_ANSWER_TEXT = '用户已取消本次问答,未作答。';
-
interface InteractionPromptProps {
pending: AskUserQuestionPayload;
- onSubmit: (requestId: string, answers: UserAnswer[], source?: string) => void;
+ onSubmit: (
+ requestId: string,
+ answers: UserAnswer[],
+ source?: string,
+ status?: UserAnswerStatus,
+ ) => void;
}
interface PageState {
@@ -45,7 +38,7 @@ interface PageState {
customActive: boolean;
/**
* 该页是否因「点击跳过按钮且当前无任何选择/输入」而被显式标记为跳过。
- * 仅用于 answerFor 判断是否要用 SKIPPED_ANSWER_TEXT 替代「默认选第一项」的兜底;
+ * 仅用于 answerFor 判断是否要返回空答案而非套用「默认选第一项」的兜底;
* 一旦用户在该页重新做出任何选择/输入,会被清除。
*/
skippedNoSelection?: boolean;
@@ -130,10 +123,10 @@ export function InteractionPrompt({ pending, onSubmit }: InteractionPromptProps)
const q = questions[idx];
const s = overrides?.[idx] ?? states[idx] ?? emptyPage();
const customText = s.custom.trim();
- // 该页是被「跳过」按钮显式标记为「无选择」的:如实告知后端「已跳过」,
- // 不再套用下面「默认选第一项」的兜底(否则会把跳过误传成某个具体选项)。
+ // 该页被显式跳过时返回空答案;交互状态由顶层 status 表达,不能再把
+ // 内部提示文本伪装成 custom_input,也不能套用默认第一项的兜底。
if (s.skippedNoSelection && s.selected.length === 0 && !customText) {
- return { question: q?.question, selected_options: [], custom_input: SKIPPED_ANSWER_TEXT };
+ return { question: q?.question, selected_options: [], custom_input: '' };
}
// Other 已激活但未输入:不得回落成第一个普通选项(#2330)。
if (s.customActive && !customText) {
@@ -153,14 +146,8 @@ export function InteractionPrompt({ pending, onSubmit }: InteractionPromptProps)
);
const buildAnswers = useCallback(
- (overrides?: Record<number, PageState>, forcedTextByIdx?: Record<number, string>): UserAnswer[] =>
- questions.map((q, idx) => {
- const forced = forcedTextByIdx?.[idx];
- if (forced !== undefined) {
- return { question: q.question, selected_options: [], custom_input: forced };
- }
- return answerFor(idx, overrides);
- }),
+ (overrides?: Record<number, PageState>): UserAnswer[] =>
+ questions.map((_q, idx) => answerFor(idx, overrides)),
[questions, answerFor],
);
@@ -185,7 +172,12 @@ export function InteractionPrompt({ pending, onSubmit }: InteractionPromptProps)
}, [setPendingQuestion]);
const submit = useCallback(
- (withEcho: boolean, overrides?: Record<number, PageState>, forcedTextByIdx?: Record<number, string>) => {
+ (
+ withEcho: boolean,
+ requestedStatus: UserAnswerStatus,
+ overrides?: Record<number, PageState>,
+ discardAnswers = false,
+ ) => {
if (submitting) return;
setSubmitting(true);
if (withEcho) {
@@ -200,10 +192,15 @@ export function InteractionPrompt({ pending, onSubmit }: InteractionPromptProps)
addMessage(sid, message);
}
}
- onSubmit(pending.request_id, buildAnswers(overrides, forcedTextByIdx), pending.source);
+ const answers = discardAnswers
+ ? buildEmptyAskUserAnswers(questions)
+ : buildAnswers(overrides);
+ // “跳过当前页”后仍可能已有其他页的真实回答;此时整轮仍是 answered。
+ const status = resolveAskUserStatus(requestedStatus, answers);
+ onSubmit(pending.request_id, answers, pending.source, status);
clearPending();
},
- [submitting, pending, buildSummary, buildAnswers, addMessage, onSubmit, clearPending],
+ [submitting, pending, buildSummary, buildAnswers, questions, addMessage, onSubmit, clearPending],
);
const goPrev = useCallback(() => setPage((p) => Math.max(0, p - 1)), []);
@@ -218,15 +215,15 @@ export function InteractionPrompt({ pending, onSubmit }: InteractionPromptProps)
const handleNextOrConfirm = useCallback(() => {
// Other 空输入:留在当前页提示用户填写,勿提交以免进入黄色 thinking(#2330)。
if (incompleteCustom) return;
- if (isLast) submit(true);
+ if (isLast) submit(true, 'answered');
else goNextPage();
}, [incompleteCustom, isLast, submit, goNextPage]);
const handleSkip = useCallback(() => {
// 跳过:无论当前页此前是否已经选中过某个选项/填过自定义输入,点击"跳过"
// 都必须视为"这道题被跳过了",绝不能把之前的选择原样带出去(bug011)。
- // 显式标记为"已跳过",后续 answerFor/buildSummary 会用 SKIPPED_ANSWER_TEXT
- // 如实告知后端,而不是套用"默认选第一项"的兜底逻辑——这一点是本次修复的核心,
+ // 显式标记为"已跳过",后续 answerFor 会生成空答案并由顶层 status 表达语义,
+ // 而不是套用"默认选第一项"的兜底逻辑——这一点是本次修复的核心,
// 务必确保 skippedNoSelection 分支在 answerFor 里排在"默认选第一项"兜底之前
// (见 answerFor 实现),不会被兜底逻辑抢先命中。
// patch() 触发的 setStates 是异步的,若末页直接 submit 会读到旧值,
@@ -234,19 +231,14 @@ export function InteractionPrompt({ pending, onSubmit }: InteractionPromptProps)
const skippedState: PageState = { ...emptyPage(), skippedNoSelection: true };
const overridden = { ...states, [page]: skippedState };
patch(() => skippedState);
- if (isLast) submit(true, overridden);
+ if (isLast) submit(true, 'skipped', overridden);
else goNextPage();
}, [states, page, patch, isLast, submit, goNextPage]);
const handleCancel = useCallback(() => {
- // 取消整轮:不管当前页/其它页有没有选择、选了什么,统一对每道题回传明确的
- // "已取消"标记,避免后端/LLM 把取消误当成某个具体选项的选择;不回显到聊天记录。
- const forcedTextByIdx: Record<number, string> = {};
- questions.forEach((_, idx) => {
- forcedTextByIdx[idx] = CANCELLED_ANSWER_TEXT;
- });
- submit(false, undefined, forcedTextByIdx);
- }, [submit, questions]);
+ // 当前协议不区分 skip/cancel;取消整轮统一提交 skipped + 空 answers,且不回显。
+ submit(false, 'skipped', undefined, true);
+ }, [submit]);
if (!current) return null;
diff --git a/jiuwenswarm/channels/web/frontend/src/components/InteractionSlot/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/InteractionSlot/index.tsx
index 7262414fbe..aa4fdfc3f9 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/InteractionSlot/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/InteractionSlot/index.tsx
@@ -10,14 +10,19 @@
*/
import { useChatStore } from '../../stores';
-import type { UserAnswer } from '../../types';
+import type { UserAnswer, UserAnswerStatus } from '../../types';
import { AuthorizationPrompt } from './AuthorizationPrompt';
import { InteractionPrompt } from './InteractionPrompt';
import { classifyPrompt } from './promptRouting';
import './InteractionSlot.css';
interface InteractionSlotProps {
- onSubmit: (requestId: string, answers: UserAnswer[], source?: string) => void;
+ onSubmit: (
+ requestId: string,
+ answers: UserAnswer[],
+ source?: string,
+ status?: UserAnswerStatus,
+ ) => void;
}
export function InteractionSlot({ onSubmit }: InteractionSlotProps) {
diff --git a/jiuwenswarm/channels/web/frontend/src/components/InteractionSlot/interactionSubmission.ts b/jiuwenswarm/channels/web/frontend/src/components/InteractionSlot/interactionSubmission.ts
new file mode 100644
index 0000000000..68cea4c89f
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/components/InteractionSlot/interactionSubmission.ts
@@ -0,0 +1,32 @@
+import type { Question, UserAnswer, UserAnswerStatus } from '../../types';
+
+const CUSTOM_INPUT_OPTION_LABELS = new Set(['Other', '其他']);
+
+/** Return whether a normalized AskUser answer contains actual user input. */
+export function hasAskUserInput(answer: UserAnswer): boolean {
+ const hasSelectedOption = answer.selected_options.some(option => {
+ const normalized = option.trim();
+ return Boolean(normalized) && !CUSTOM_INPUT_OPTION_LABELS.has(normalized);
+ });
+ return hasSelectedOption || Boolean(answer.custom_input?.trim());
+}
+
+/**
+ * A page-level skip can finish a multi-page interaction that already has real
+ * answers. Only an interaction with no user input is globally skipped.
+ */
+export function resolveAskUserStatus(requestedStatus: UserAnswerStatus, answers: UserAnswer[]): UserAnswerStatus {
+ if (requestedStatus === 'skipped' && answers.some(hasAskUserInput)) {
+ return 'answered';
+ }
+ return requestedStatus;
+}
+
+/** Cancel/skip the whole interaction without leaking stale page selections. */
+export function buildEmptyAskUserAnswers(questions: Pick<Question, 'question'>[]): UserAnswer[] {
+ return questions.map(question => ({
+ question: question.question,
+ selected_options: [],
+ custom_input: '',
+ }));
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
index 56559f62e2..242032b6d3 100644
--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts
@@ -18,6 +18,7 @@ import {
AskUserQuestionPayload,
EvolutionStatusPayload,
UserAnswer,
+ UserAnswerStatus,
MediaItem,
AgentMode,
Session,
@@ -523,7 +524,8 @@ interface UseWebSocketReturn {
sessionId: string,
requestId: string,
answers: UserAnswer[],
- source?: string
+ source?: string,
+ status?: UserAnswerStatus
) => Promise<void>;
respondActivate: (
sessionId: string,
@@ -1689,7 +1691,13 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
// 发送用户回答
const sendUserAnswer = useCallback(
- async (sessionId: string, requestId: string, answers: UserAnswer[], source?: string) => {
+ async (
+ sessionId: string,
+ requestId: string,
+ answers: UserAnswer[],
+ source?: string,
+ status?: UserAnswerStatus,
+ ) => {
try {
const pendingQuestion = useChatStore.getState().getRuntime(sessionId)?.pendingQuestion;
const pendingMatches = pendingQuestion?.request_id === requestId;
@@ -1708,6 +1716,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
: {};
const approvalSchemaPayload = approvalSchema ? { approval_schema: approvalSchema } : {};
const sourcePayload = effectiveSource ? { source: effectiveSource } : {};
+ const statusPayload = status ? { status } : {};
const structuredPlanPayload =
pendingMatches && pendingQuestion?.planApprovalKind === 'plan_approval'
? {
@@ -1736,6 +1745,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
...getSessionWorkContext(sessionId),
request_id: requestId,
answers: answers,
+ ...statusPayload,
...sourcePayload,
...structuredPlanPayload,
...approvalSchemaPayload,
@@ -1766,6 +1776,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {
...getSessionWorkContext(sessionId),
request_id: requestId,
answers,
+ ...statusPayload,
...sourcePayload,
...approvalSchemaPayload,
...evolutionMetaPayload,
diff --git a/jiuwenswarm/channels/web/frontend/src/types/websocket.ts b/jiuwenswarm/channels/web/frontend/src/types/websocket.ts
index bd6d8068d4..bcf7a22b13 100644
--- a/jiuwenswarm/channels/web/frontend/src/types/websocket.ts
+++ b/jiuwenswarm/channels/web/frontend/src/types/websocket.ts
@@ -168,11 +168,15 @@ export interface UserAnswer {
custom_input?: string;
}
+/** AskUser 交互的显式完成状态。缺失时后端按 answered 处理。 */
+export type UserAnswerStatus = 'answered' | 'skipped';
+
/**
* 用户回答 Payload(客户端 -> 服务端)
*/
export interface UserAnswerPayload {
request_id: string;
+ status?: UserAnswerStatus;
answers: UserAnswer[];
evolution_meta?: Record<string, unknown>;
plan_approval_kind?: string;
diff --git a/jiuwenswarm/channels/web/frontend/tests/askUserSubmission.test.mjs b/jiuwenswarm/channels/web/frontend/tests/askUserSubmission.test.mjs
new file mode 100644
index 0000000000..98270dad69
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/tests/askUserSubmission.test.mjs
@@ -0,0 +1,38 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import {
+ buildEmptyAskUserAnswers,
+ hasAskUserInput,
+ resolveAskUserStatus,
+} from '../node_modules/.cache/ask-user-submission/components/InteractionSlot/interactionSubmission.js';
+
+test('preserves explicit answered even when answers are empty', () => {
+ assert.equal(resolveAskUserStatus('answered', []), 'answered');
+});
+
+test('preserves skipped only when the whole interaction has no user input', () => {
+ const emptyAnswers = [
+ { question: 'First?', selected_options: [], custom_input: '' },
+ { question: 'Second?', selected_options: ['Other'], custom_input: ' ' },
+ ];
+
+ assert.equal(resolveAskUserStatus('skipped', emptyAnswers), 'skipped');
+ assert.equal(hasAskUserInput(emptyAnswers[1]), false);
+});
+
+test('page-level skip keeps the interaction answered when another page has input', () => {
+ const partialAnswers = [
+ { question: 'First?', selected_options: ['A'], custom_input: '' },
+ { question: 'Second?', selected_options: [], custom_input: '' },
+ ];
+
+ assert.equal(resolveAskUserStatus('skipped', partialAnswers), 'answered');
+});
+
+test('whole-interaction cancellation creates only empty answer shells', () => {
+ assert.deepEqual(buildEmptyAskUserAnswers([{ question: 'First?' }, { question: 'Second?' }]), [
+ { question: 'First?', selected_options: [], custom_input: '' },
+ { question: 'Second?', selected_options: [], custom_input: '' },
+ ]);
+});
diff --git a/jiuwenswarm/common/local_env_config.py b/jiuwenswarm/common/local_env_config.py
index 318764e989..aefa9fdf2c 100644
--- a/jiuwenswarm/common/local_env_config.py
+++ b/jiuwenswarm/common/local_env_config.py
@@ -148,8 +148,6 @@ BUSINESS_MIRROR_KEYS: frozenset[str] = frozenset(
"WEB_SEARCH_URL",
"EXECUTION_METHOD",
"TAVILY_API_KEY",
- # Non-secret per-tenant DeepResearch runtime selection.
- "DEEPRESEARCH_PYTHON_EXECUTABLE",
# ACRCloud (audio_tools / read_env)
"ACR_ACCESS_KEY",
"ACR_ACCESS_SECRET",
@@ -1141,6 +1139,9 @@ def read_default_headers_raw() -> str:
raw = read_env(env_key, "")
if raw.strip():
return raw.strip()
+ api_key = read_env("API_KEY", "").strip()
+ if api_key and api_key != "huawei-maas-session":
+ return ""
for env_key in _DEFAULT_HEADERS_FALLBACK_ALIASES:
raw = read_env(env_key, "")
text = raw.strip()
diff --git a/jiuwenswarm/common/schema/ask_user.py b/jiuwenswarm/common/schema/ask_user.py
new file mode 100644
index 0000000000..13e59aac9f
--- /dev/null
+++ b/jiuwenswarm/common/schema/ask_user.py
@@ -0,0 +1,208 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Canonical AskUser response contract shared by adapters, rails, and tools."""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from dataclasses import dataclass
+from typing import Any, Literal
+
+
+_OTHER_OPTION_LABELS = frozenset({"Other", "其他"})
+
+
+class AskUserResponseError(ValueError):
+ """Raised when an AskUser response violates the canonical contract."""
+
+
+@dataclass(frozen=True)
+class AskUserAnswer:
+ """One normalized answer item."""
+
+ question: str
+ selected_options: tuple[str, ...]
+ custom_input: str | None
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "question": self.question,
+ "selected_options": list(self.selected_options),
+ "custom_input": self.custom_input,
+ }
+
+ def readable_value(self) -> str:
+ values = [*self.selected_options]
+ if self.custom_input:
+ values.append(self.custom_input)
+ return ", ".join(values)
+
+
+@dataclass(frozen=True)
+class AskUserResponse:
+ """The only internal representation of an AskUser response."""
+
+ status: Literal["answered", "skipped"]
+ answers: tuple[AskUserAnswer, ...]
+ original_request: str | None = None
+
+ def to_dict(self, *, include_original_request: bool = True) -> dict[str, Any]:
+ payload: dict[str, Any] = {
+ "status": self.status,
+ "answers": [answer.to_dict() for answer in self.answers],
+ }
+ if include_original_request and self.original_request:
+ payload["original_request"] = self.original_request
+ return payload
+
+ def to_readable_text(self) -> str:
+ parts = []
+ for answer in self.answers:
+ value = answer.readable_value()
+ if answer.question:
+ parts.append(f"{answer.question}: {value}")
+ else:
+ parts.append(value)
+ return "\n".join(parts)
+
+
+def ask_user_response_schema() -> dict[str, Any]:
+ """Return the public JSON schema for the canonical resume response."""
+
+ return {
+ "type": "object",
+ "additionalProperties": True,
+ "properties": {
+ "status": {
+ "type": "string",
+ "enum": ["answered", "skipped"],
+ },
+ "answers": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": True,
+ "properties": {
+ "question": {"type": "string"},
+ "selected_options": {
+ "type": "array",
+ "items": {"type": "string"},
+ },
+ "custom_input": {
+ "anyOf": [
+ {"type": "string"},
+ {"type": "null"},
+ ],
+ },
+ },
+ "required": ["selected_options"],
+ },
+ },
+ "original_request": {"type": "string"},
+ },
+ "required": ["status", "answers"],
+ }
+
+
+def _normalize_answer(item: Any, index: int) -> AskUserAnswer | None:
+ if not isinstance(item, Mapping):
+ raise AskUserResponseError(f"answers[{index}] must be an object")
+
+ raw_question = item.get("question", "")
+ if not isinstance(raw_question, str):
+ raise AskUserResponseError(f"answers[{index}].question must be a string")
+ question = raw_question.strip()
+
+ if "selected_options" not in item:
+ raise AskUserResponseError(
+ f"answers[{index}].selected_options is required"
+ )
+ raw_selected = item["selected_options"]
+ if not isinstance(raw_selected, list):
+ raise AskUserResponseError(
+ f"answers[{index}].selected_options must be an array"
+ )
+ selected_options: list[str] = []
+ for option_index, option in enumerate(raw_selected):
+ if not isinstance(option, str):
+ raise AskUserResponseError(
+ f"answers[{index}].selected_options[{option_index}] "
+ "must be a string"
+ )
+ normalized_option = option.strip()
+ if normalized_option and normalized_option not in _OTHER_OPTION_LABELS:
+ selected_options.append(normalized_option)
+
+ raw_custom = item.get("custom_input")
+ if raw_custom is not None and not isinstance(raw_custom, str):
+ raise AskUserResponseError(
+ f"answers[{index}].custom_input must be a string or null"
+ )
+ custom_input = raw_custom.strip() if isinstance(raw_custom, str) else None
+ if not custom_input:
+ custom_input = None
+
+ if not selected_options and custom_input is None:
+ return None
+ return AskUserAnswer(
+ question=question,
+ selected_options=tuple(selected_options),
+ custom_input=custom_input,
+ )
+
+
+def normalize_ask_user_response(
+ *,
+ status: Any,
+ answers: Any,
+ original_request: Any = None,
+) -> AskUserResponse:
+ """Normalize the current array protocol into one semantic response."""
+
+ if not isinstance(status, str):
+ raise AskUserResponseError("status must be a string")
+ normalized_status = status.strip().lower()
+ if normalized_status not in {"", "answered", "skipped"}:
+ raise AskUserResponseError(
+ "status must be 'answered' or 'skipped' when provided"
+ )
+ if not isinstance(answers, list):
+ raise AskUserResponseError("answers must be an array")
+ if original_request is not None and not isinstance(original_request, str):
+ raise AskUserResponseError("original_request must be a string when provided")
+
+ normalized_answer_items: list[AskUserAnswer] = []
+ for index, item in enumerate(answers):
+ answer = _normalize_answer(item, index)
+ if answer is not None:
+ normalized_answer_items.append(answer)
+ normalized_answers = tuple(normalized_answer_items)
+ if normalized_status == "skipped" and normalized_answers:
+ raise AskUserResponseError("skipped response must not contain user input")
+
+ effective_status: Literal["answered", "skipped"] = (
+ "skipped" if normalized_status == "skipped" else "answered"
+ )
+ normalized_original_request = (
+ original_request.strip() if isinstance(original_request, str) else ""
+ )
+ return AskUserResponse(
+ status=effective_status,
+ answers=normalized_answers,
+ original_request=normalized_original_request or None,
+ )
+
+
+def parse_ask_user_response(value: Any) -> AskUserResponse:
+ """Parse the canonical internal mapping without legacy fallbacks."""
+
+ if not isinstance(value, Mapping):
+ raise AskUserResponseError("AskUser response must be an object")
+ fields = set(value)
+ if not {"status", "answers"}.issubset(fields):
+ raise AskUserResponseError("AskUser response must contain status and answers")
+ return normalize_ask_user_response(
+ status=value["status"],
+ answers=value["answers"],
+ original_request=value.get("original_request"),
+ )
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.py
index 4ebd939bfa..4e2c8299ce 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py
@@ -45,6 +45,7 @@ from jiuwenswarm.server.utils.utils import is_team_params
from jiuwenswarm.common.config import get_config
from jiuwenswarm.extensions.registry import ExtensionRegistry
from jiuwenswarm.common.schema.agent import AgentRequest, AgentResponse, AgentResponseChunk
+from jiuwenswarm.common.schema.ask_user import normalize_ask_user_response
from jiuwenswarm.common.chat_final import ensure_final_mode_inplace
from jiuwenswarm.extensions.hook_event import AgentServerHookEvents
from jiuwenswarm.extensions.hooks_context import MemoryHookContext
@@ -72,9 +73,6 @@ class _TeamPlanApprovalPayloadError(ValueError):
"""Raised when a structured team.plan approval payload is malformed."""
-_ASK_USER_OTHER_OPTION_LABELS = {"Other", "其他"}
-
-
def _permission_response_key(request: AgentRequest) -> str | None:
"""Return the opaque request ID for a permission continuation."""
if request.req_method not in (ReqMethod.CHAT_SEND, ReqMethod.CHAT_RESUME):
@@ -1360,10 +1358,10 @@ class JiuWenSwarm:
answers = params.get("answers", [])
source = params.get("source", "")
status = params.get("status", "")
- is_explicit_ask_user_skip = (
- source == "ask_user_interrupt" and status == "skipped"
+ is_explicit_ask_user_response = (
+ source == "ask_user_interrupt" and "status" in params
)
- if answers or is_explicit_ask_user_skip:
+ if answers or is_explicit_ask_user_response:
request_id = params.get("request_id", "")
raw_original_request = params.get("original_request") if source == "ask_user_interrupt" else ""
original_request = raw_original_request.strip() if isinstance(raw_original_request, str) else ""
@@ -1629,7 +1627,7 @@ class JiuWenSwarm:
request_id: 工具调用 ID
answers: 用户答案列表,每个答案对应一个问题
source: 中断来源,用于区分 PermissionRail 和 AskUserRail
- status: 显式交互状态;仅 AskUserRail 的 skipped 状态参与构建
+ status: AskUserRail 显式交互状态;缺失时由回答内容推导
Returns:
InteractiveInput 实例
@@ -1639,96 +1637,20 @@ class JiuWenSwarm:
interactive_input = InteractiveInput()
if source == "ask_user_interrupt":
- if status == "skipped":
- interactive_input.update(
- request_id,
- {"status": "skipped", "answers": answers},
- )
- logger.info(
- "[JiuWenSwarm] AskUserRail skipped InteractiveInput.update: "
- "request_id=%s answer_shell_count=%s",
- request_id,
- len(answers) if isinstance(answers, list) else -1,
- )
- return interactive_input
-
- answers_dict = {}
- free_text_answer = ""
- for answer in answers:
- if isinstance(answer, dict):
- question_text = str(answer.get("question", "") or "").strip()
- selected_options = answer.get("selected_options", [])
- custom_input = str(answer.get("custom_input", "") or "").strip()
- if selected_options and isinstance(selected_options, list):
- # Normalize each option to a stripped string, drop empties.
- cleaned_options = [
- str(raw_option or "").strip()
- for raw_option in selected_options
- if str(raw_option or "").strip()
- ]
- if custom_input:
- # "Other" is only a UI placeholder. Preserve normal
- # multi-select choices and append the user's text.
- normal_options = [
- option
- for option in cleaned_options
- if option not in _ASK_USER_OTHER_OPTION_LABELS
- ]
- if normal_options:
- answer_value: Any = [*normal_options, custom_input]
- else:
- answer_value = custom_input
- elif len(cleaned_options) == 1:
- # Bare "Other" without custom text is incomplete (#2330).
- sole = cleaned_options[0]
- answer_value = (
- ""
- if sole in _ASK_USER_OTHER_OPTION_LABELS
- else sole
- )
- elif cleaned_options:
- # Multi-select: preserve real choices; drop placeholder-only Other.
- normal_options = [
- option
- for option in cleaned_options
- if option not in _ASK_USER_OTHER_OPTION_LABELS
- ]
- answer_value = normal_options if normal_options else ""
- else:
- answer_value = ""
- elif custom_input:
- answer_value = custom_input
- else:
- answer_value = ""
- if question_text and answer_value:
- answers_dict[question_text] = answer_value
- elif answer_value:
- free_text_answer = (
- answer_value
- if isinstance(answer_value, str)
- else ", ".join(answer_value)
- )
- if not answers_dict and free_text_answer:
- answers_dict["__free_text__"] = free_text_answer
- payload: dict[str, Any] = {"answers": answers_dict}
- normalized_status = (
- status.strip().lower() if isinstance(status, str) else ""
+ response = normalize_ask_user_response(
+ status=status,
+ answers=answers,
+ original_request=original_request,
)
- if normalized_status == "answered":
- payload["_structured_response"] = {
- "status": "answered",
- "answers": answers,
- }
- if isinstance(original_request, str) and original_request.strip():
- payload["original_request"] = original_request.strip()
+ payload = response.to_dict()
interactive_input.update(request_id, payload)
logger.info(
"[JiuWenSwarm] AskUserRail InteractiveInput.update: request_id=%s "
- "answer_count=%s has_original_request=%s has_structured_response=%s",
+ "status=%s answer_count=%s has_original_request=%s",
request_id,
- len(answers_dict),
+ response.status,
+ len(response.answers),
"original_request" in payload,
- "_structured_response" in payload,
)
return interactive_input
diff --git a/tests/system_tests/test_structured_ask_user.py b/tests/system_tests/test_structured_ask_user.py
index 0eb09adc06..b30daf9b4c 100644
--- a/tests/system_tests/test_structured_ask_user.py
+++ b/tests/system_tests/test_structured_ask_user.py
@@ -21,8 +21,6 @@ from openjiuwen.core.foundation.llm.schema.tool_call import ToolCall
from openjiuwen.core.single_agent.interrupt.response import (
ToolCallInterruptRequest,
)
-from openjiuwen.harness.rails.interrupt.ask_user_rail import AskUserPayload
-
from jiuwenswarm.agents.harness.common.rails.ask_user_rail import (
EXTENDED_INPUT_PARAMS_CN,
EXTENDED_INPUT_PARAMS_EN,
@@ -587,6 +585,25 @@ class TestStructuredAskUserRailResolveInterrupt:
from openjiuwen.harness.rails.interrupt.interrupt_base import InterruptResult
assert isinstance(decision, InterruptResult)
+ @staticmethod
+ @pytest.mark.asyncio
+ async def test_interrupt_advertises_canonical_response_schema():
+ """The public interrupt schema must match the canonical resume contract."""
+ rail = StructuredAskUserRail()
+ tc = _make_tool_call(arguments={"query": "What is your role?"})
+
+ decision = await rail.resolve_interrupt(MagicMock(), tc, None)
+
+ schema = decision.request.payload_schema
+ assert schema["type"] == "object"
+ assert schema["additionalProperties"] is True
+ assert schema["required"] == ["status", "answers"]
+ assert schema["properties"]["status"]["enum"] == ["answered", "skipped"]
+ assert schema["properties"]["answers"]["type"] == "array"
+ answer_schema = schema["properties"]["answers"]["items"]
+ assert answer_schema["additionalProperties"] is True
+ assert answer_schema["required"] == ["selected_options"]
+
@staticmethod
@pytest.mark.asyncio
async def test_four_questions_are_allowed():
@@ -844,8 +861,8 @@ class TestStructuredAskUserRailResolveInterrupt:
@staticmethod
@pytest.mark.asyncio
- async def test_structured_answer_dict_returns_reject():
- """Structured answer as dict should return RejectResult with formatted text."""
+ async def test_canonical_structured_answer_returns_readable_text():
+ """The canonical answer array produces the readable model response."""
rail = StructuredAskUserRail()
tc = _make_tool_call(arguments={
"query": "Update?",
@@ -855,7 +872,16 @@ class TestStructuredAskUserRailResolveInterrupt:
ctx = MagicMock()
# Simulate user selecting "Apply update"
- user_input = {"answers": {"Apply update?": "Apply update"}}
+ user_input = {
+ "status": "answered",
+ "answers": [
+ {
+ "question": "Apply update?",
+ "selected_options": ["Apply update"],
+ "custom_input": None,
+ }
+ ],
+ }
decision = await rail.resolve_interrupt(ctx, tc, user_input)
from openjiuwen.harness.rails.interrupt.interrupt_base import RejectResult
@@ -864,8 +890,8 @@ class TestStructuredAskUserRailResolveInterrupt:
@staticmethod
@pytest.mark.asyncio
- async def test_structured_answer_string_fallback():
- """String answer for a structured question should be handled as free-text."""
+ async def test_canonical_structured_free_text_answer():
+ """Free text uses custom_input in the same canonical answer array."""
rail = StructuredAskUserRail()
tc = _make_tool_call(arguments={
"query": "Update?",
@@ -873,7 +899,20 @@ class TestStructuredAskUserRailResolveInterrupt:
})
ctx = MagicMock()
- decision = await rail.resolve_interrupt(ctx, tc, "I want to customize")
+ decision = await rail.resolve_interrupt(
+ ctx,
+ tc,
+ {
+ "status": "answered",
+ "answers": [
+ {
+ "question": "Apply?",
+ "selected_options": [],
+ "custom_input": "I want to customize",
+ }
+ ],
+ },
+ )
from openjiuwen.harness.rails.interrupt.interrupt_base import RejectResult
assert isinstance(decision, RejectResult)
@@ -881,23 +920,27 @@ class TestStructuredAskUserRailResolveInterrupt:
@staticmethod
@pytest.mark.asyncio
- async def test_plain_query_delegates_to_parent():
- """Plain query (no questions) should delegate to parent AskUserRail."""
+ async def test_plain_query_uses_canonical_answer():
+ """Plain queries use custom_input instead of a second payload type."""
rail = StructuredAskUserRail()
tc = _make_tool_call(arguments={"query": "What is your role?"})
ctx = MagicMock()
- # AskUserPayload changed: answer (str) → answers (dict)
- # Construct payload compatible with both old and new upstream versions
- if "answer" in AskUserPayload.model_fields:
- user_input = AskUserPayload(answer="I am a developer")
- else:
- user_input = AskUserPayload(answers={"What is your role?": "I am a developer"})
+ user_input = {
+ "status": "answered",
+ "answers": [
+ {
+ "question": "",
+ "selected_options": [],
+ "custom_input": "I am a developer",
+ }
+ ],
+ }
decision = await rail.resolve_interrupt(ctx, tc, user_input)
from openjiuwen.harness.rails.interrupt.interrupt_base import RejectResult
assert isinstance(decision, RejectResult)
- assert "I am a developer" in decision.tool_result
+ assert decision.tool_result == "{'__free_text__': 'I am a developer'}"
@staticmethod
@pytest.mark.asyncio
@@ -914,10 +957,19 @@ class TestStructuredAskUserRailResolveInterrupt:
ctx = MagicMock()
user_input = {
- "answers": {
- "Branch naming?": "feature/*",
- "Test runner?": "pytest",
- },
+ "status": "answered",
+ "answers": [
+ {
+ "question": "Branch naming?",
+ "selected_options": ["feature/*"],
+ "custom_input": None,
+ },
+ {
+ "question": "Test runner?",
+ "selected_options": ["pytest"],
+ "custom_input": None,
+ },
+ ],
}
decision = await rail.resolve_interrupt(ctx, tc, user_input)
diff --git a/tests/unit_tests/agentserver/test_agentserver_modes.py b/tests/unit_tests/agentserver/test_agentserver_modes.py
index 0bc100f184..eb927a5cdf 100644
--- a/tests/unit_tests/agentserver/test_agentserver_modes.py
+++ b/tests/unit_tests/agentserver/test_agentserver_modes.py
@@ -578,7 +578,14 @@ def test_build_inputs_preserves_original_request_on_ask_user_answers(monkeypatch
assert isinstance(inputs["query"], InteractiveInput)
assert inputs["query"].user_inputs == {
"tool-ask-1": {
- "answers": {"你希望用什么技术实现?": "浏览器(HTML/CSS/JS)"},
+ "status": "answered",
+ "answers": [
+ {
+ "question": "你希望用什么技术实现?",
+ "selected_options": ["浏览器(HTML/CSS/JS)"],
+ "custom_input": None,
+ }
+ ],
"original_request": "做一个斗地主游戏",
}
}
@@ -617,7 +624,7 @@ def test_build_inputs_preserves_explicit_skipped_ask_user_envelope(monkeypatch):
assert inputs["query"].user_inputs == {
"tool-ask-skipped-1": {
"status": "skipped",
- "answers": answers,
+ "answers": [],
}
}
@@ -656,11 +663,8 @@ def test_build_inputs_preserves_answered_ask_user_envelope_for_opt_in_consumers(
assert isinstance(inputs["query"], InteractiveInput)
assert inputs["query"].user_inputs == {
"tool-ask-answered-1": {
- "answers": {"研究重点是什么?": "技术实现"},
- "_structured_response": {
- "status": "answered",
- "answers": answers,
- },
+ "status": "answered",
+ "answers": answers,
}
}
@@ -695,6 +699,37 @@ def test_build_inputs_maps_explicit_skipped_with_empty_answers_to_interactive_in
}
+def test_build_inputs_preserves_explicit_empty_answered(monkeypatch):
+ from openjiuwen.core.session.interaction.interactive_input import InteractiveInput
+ from jiuwenswarm.server.runtime.agent_adapter import interface as interface_module
+
+ monkeypatch.setattr(interface_module, "get_config", lambda: {"preferred_language": "zh"})
+ monkeypatch.setattr(interface_module, "get_memory_mode", lambda _config: "disabled")
+
+ request = AgentRequest(
+ request_id="req-empty-answered",
+ channel_id="web",
+ session_id="web-session",
+ params={
+ "query": "",
+ "request_id": "tool-ask-empty-answered-1",
+ "source": "ask_user_interrupt",
+ "status": "answered",
+ "answers": [],
+ },
+ )
+
+ inputs, _, _ = interface_module.JiuWenSwarm().build_inputs(request)
+
+ assert isinstance(inputs["query"], InteractiveInput)
+ assert inputs["query"].user_inputs == {
+ "tool-ask-empty-answered-1": {
+ "status": "answered",
+ "answers": [],
+ }
+ }
+
+
def test_build_inputs_merges_multi_select_custom_input(monkeypatch):
from openjiuwen.core.session.interaction.interactive_input import InteractiveInput
from jiuwenswarm.server.runtime.agent_adapter import interface as interface_module
@@ -731,10 +766,19 @@ def test_build_inputs_merges_multi_select_custom_input(monkeypatch):
assert isinstance(inputs["query"], InteractiveInput)
assert inputs["query"].user_inputs == {
"tool-ask-1": {
- "answers": {
- "启用哪些模块?": ["auth", "metrics"],
- "还有其他需求吗?": "tracing",
- }
+ "status": "answered",
+ "answers": [
+ {
+ "question": "启用哪些模块?",
+ "selected_options": ["auth"],
+ "custom_input": "metrics",
+ },
+ {
+ "question": "还有其他需求吗?",
+ "selected_options": [],
+ "custom_input": "tracing",
+ },
+ ],
}
}
@@ -776,7 +820,8 @@ def test_build_inputs_drops_bare_other_without_custom_input(monkeypatch):
assert isinstance(inputs["query"], InteractiveInput)
assert inputs["query"].user_inputs == {
"tool-ask-1": {
- "answers": {},
+ "status": "answered",
+ "answers": [],
}
}
diff --git a/tests/unit_tests/agentserver/test_ask_user_validation.py b/tests/unit_tests/agentserver/test_ask_user_validation.py
index c2001333c2..5661ecf6f4 100644
--- a/tests/unit_tests/agentserver/test_ask_user_validation.py
+++ b/tests/unit_tests/agentserver/test_ask_user_validation.py
@@ -11,7 +11,10 @@ import pytest
from openjiuwen.core.foundation.llm.schema.tool_call import ToolCall
from openjiuwen.harness.rails.interrupt.interrupt_base import InterruptResult, RejectResult
-from jiuwenswarm.agents.harness.common.rails.ask_user_rail import StructuredAskUserRail
+from jiuwenswarm.agents.harness.common.rails.ask_user_rail import (
+ StructuredAskUserRail,
+ StructuredAskUserTool,
+)
def _make_tool_call(arguments: dict) -> ToolCall:
@@ -23,6 +26,18 @@ def _make_tool_call(arguments: dict) -> ToolCall:
)
+def test_structured_ask_user_schema_declares_question_preview():
+ tool = StructuredAskUserTool(language="cn", agent_id="test")
+
+ preview_schema = tool.card.input_params["properties"]["questions"]["items"][
+ "properties"
+ ]["preview"]
+
+ assert preview_schema["type"] == "object"
+ assert preview_schema["required"] == ["text"]
+ assert preview_schema["properties"]["text"]["type"] == "string"
+
+
@pytest.mark.asyncio
async def test_options_string_a_b_is_rejected():
"""Issue #2331: options='a,b' must reject instead of silent no-UI."""
@@ -71,12 +86,13 @@ async def test_valid_options_still_interrupt():
@pytest.mark.asyncio
-async def test_empty_structured_answers_are_rejected():
- """Issue #2330: empty resume (bare Other) must not resolve as a blank answer."""
+async def test_empty_structured_answers_preserve_answered_machine_state():
+ """The shared AskUser contract preserves answered even when answers are empty."""
rail = StructuredAskUserRail()
tc = _make_tool_call(
{
"query": "Choose",
+ "return_json": True,
"questions": [
{
"question": "Which option?",
@@ -93,15 +109,15 @@ async def test_empty_structured_answers_are_rejected():
decision = await rail.resolve_interrupt(
MagicMock(),
tc,
- {"answers": {}},
+ {"status": "answered", "answers": []},
)
assert isinstance(decision, RejectResult)
- assert "answers must include at least one non-empty response" in decision.tool_result
+ assert decision.tool_result == '{"status":"answered","answers":[]}'
@pytest.mark.asyncio
-async def test_explicit_skipped_preserves_compact_machine_state():
+async def test_explicit_skipped_keeps_readable_default():
rail = StructuredAskUserRail()
tc = _make_tool_call(
{
@@ -118,6 +134,29 @@ async def test_explicit_skipped_preserves_compact_machine_state():
{"status": "skipped", "answers": []},
)
+ assert isinstance(decision, RejectResult)
+ assert decision.tool_result == "用户已跳过本次问答,未提供回答。"
+
+
+async def test_explicit_skipped_can_opt_in_to_compact_machine_state():
+ rail = StructuredAskUserRail()
+ tc = _make_tool_call(
+ {
+ "query": "Choose",
+ "return_json": True,
+ "questions": [
+ {"question": "Which?", "header": "Choice", "options": []}
+ ],
+ }
+ )
+
+ decision = await rail.resolve_interrupt(
+ MagicMock(),
+ tc,
+ {"status": "skipped", "answers": []},
+ )
+
assert isinstance(decision, RejectResult)
assert decision.tool_result == '{"status":"skipped","answers":[]}'
@@ -128,6 +167,7 @@ async def test_explicit_skipped_accepts_empty_frontend_answer_shells():
tc = _make_tool_call(
{
"query": "Choose",
+ "return_json": True,
"questions": [
{"question": "Which?", "header": "Choice", "options": []}
],
@@ -159,13 +199,34 @@ async def test_explicit_skipped_accepts_empty_frontend_answer_shells():
assert decision.tool_result == '{"status":"skipped","answers":[]}'
+async def test_empty_answered_uses_non_empty_readable_fallback():
+ rail = StructuredAskUserRail()
+ tc = _make_tool_call(
+ {
+ "query": "Choose",
+ "questions": [
+ {"question": "Which?", "header": "Choice", "options": []}
+ ],
+ }
+ )
+
+ decision = await rail.resolve_interrupt(
+ MagicMock(),
+ tc,
+ {"status": "answered", "answers": []},
+ )
+
+ assert isinstance(decision, RejectResult)
+ assert decision.tool_result == "用户未提供回答。"
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
"user_input",
[
{"status": "skipped", "answers": {"Which?": "A"}},
{"status": "skipped", "answers": []},
- {"status": "skipped", "answers": [], "extra": True},
{
"status": "skipped",
"answers": [
@@ -218,7 +279,16 @@ async def test_answered_structured_payload_keeps_readable_text_semantics():
decision = await rail.resolve_interrupt(
MagicMock(),
tc,
- {"status": "answered", "answers": {"Which?": "A"}},
+ {
+ "status": "answered",
+ "answers": [
+ {
+ "question": "Which?",
+ "selected_options": ["A"],
+ "custom_input": None,
+ }
+ ],
+ },
)
assert isinstance(decision, RejectResult)
@@ -249,10 +319,7 @@ async def test_answered_structured_payload_can_opt_in_to_machine_state():
decision = await rail.resolve_interrupt(
MagicMock(),
tc,
- {
- "answers": {"Which?": "A"},
- "_structured_response": answer_envelope,
- },
+ answer_envelope,
)
assert isinstance(decision, RejectResult)
@@ -269,3 +336,41 @@ async def test_answered_structured_payload_can_opt_in_to_machine_state():
)
== "问题: Which?\n回答: A"
)
+
+
+ "legacy_input",
+ [
+ {"answers": {"Which?": "A"}},
+ {
+ "answers": {"Which?": "A"},
+ "_structured_response": {
+ "status": "answered",
+ "answers": [
+ {
+ "question": "Which?",
+ "selected_options": ["A"],
+ "custom_input": None,
+ }
+ ],
+ },
+ },
+ "A",
+ ],
+)
+async def test_legacy_answer_representations_are_rejected(legacy_input):
+ rail = StructuredAskUserRail()
+ tc = _make_tool_call(
+ {
+ "query": "Choose",
+ "questions": [
+ {"question": "Which?", "header": "Choice", "options": []}
+ ],
+ }
+ )
+
+ decision = await rail.resolve_interrupt(MagicMock(), tc, legacy_input)
+
+ assert isinstance(decision, RejectResult)
+ assert "INVALID_ARGUMENT" in decision.tool_result
diff --git a/tests/unit_tests/agentserver/test_deepresearch_runtime.py b/tests/unit_tests/agentserver/test_deepresearch_runtime.py
index bde79447a6..09235e46f9 100644
--- a/tests/unit_tests/agentserver/test_deepresearch_runtime.py
+++ b/tests/unit_tests/agentserver/test_deepresearch_runtime.py
@@ -23,21 +23,19 @@ def _fake_venv_python(tmp_path: Path, *, executable: bool = True) -> Path:
return python
-def test_resolve_python_executable_reads_bound_overlay(tmp_path: Path, monkeypatch):
+def test_resolve_python_executable_ignores_configured_override(monkeypatch):
from jiuwenswarm.agents.harness.common.tools.deepresearch.runtime import (
resolve_python_executable,
)
- python = _fake_venv_python(tmp_path)
monkeypatch.setenv("DEEPRESEARCH_PYTHON_EXECUTABLE", "/ambient/must-not-win")
- token = bind_task_env_overlay({"DEEPRESEARCH_PYTHON_EXECUTABLE": str(python)})
- try:
- assert resolve_python_executable() == python
- finally:
- reset_task_env_overlay(token)
+ assert resolve_python_executable() == Path(os.path.abspath(sys.executable))
-def test_resolve_python_executable_preserves_symlinked_venv_identity(tmp_path: Path):
+def test_resolve_python_executable_preserves_symlinked_venv_identity(
+ tmp_path: Path,
+ monkeypatch,
+):
from jiuwenswarm.agents.harness.common.tools.deepresearch.runtime import (
build_child_env,
resolve_python_executable,
@@ -49,37 +47,43 @@ def test_resolve_python_executable_preserves_symlinked_venv_identity(tmp_path: P
(venv_root / "pyvenv.cfg").write_text("home = /usr/bin\n", encoding="utf-8")
python = bin_dir / "python"
python.symlink_to(sys.executable)
- token = bind_task_env_overlay({"DEEPRESEARCH_PYTHON_EXECUTABLE": str(python)})
- try:
- resolved = resolve_python_executable()
- child_env = build_child_env(resolved)
- finally:
- reset_task_env_overlay(token)
+ monkeypatch.setattr(sys, "executable", str(python))
+ resolved = resolve_python_executable()
+ child_env = build_child_env(resolved)
assert resolved == python
assert child_env["VIRTUAL_ENV"] == str(venv_root)
assert child_env["PATH"].split(os.pathsep)[0] == str(bin_dir)
-def test_resolve_python_executable_missing_never_falls_back(monkeypatch):
+def test_resolve_python_executable_accepts_current_process_runtime_without_virtualenv(
+ tmp_path: Path,
+ monkeypatch,
+):
from jiuwenswarm.agents.harness.common.tools.deepresearch.runtime import (
- DeepResearchRuntimeError,
+ build_child_env,
resolve_python_executable,
)
- monkeypatch.setenv("DEEPRESEARCH_PYTHON_EXECUTABLE", "/ambient/must-be-sealed")
- token = bind_task_env_overlay({})
- try:
- with pytest.raises(DeepResearchRuntimeError, match="^runtime_python_missing$"):
- resolve_python_executable()
- finally:
- reset_task_env_overlay(token)
+ python = tmp_path / "embedded-runtime" / "python"
+ python.parent.mkdir(parents=True)
+ python.write_text("#!/bin/sh\n", encoding="utf-8")
+ python.chmod(0o755)
+ monkeypatch.setattr(sys, "executable", str(python))
+ monkeypatch.delenv("DEEPRESEARCH_PYTHON_EXECUTABLE", raising=False)
+ resolved = resolve_python_executable()
+ child_env = build_child_env(resolved)
+
+ assert resolved == python
+ assert "VIRTUAL_ENV" not in child_env
+ assert child_env["PATH"].split(os.pathsep)[0] == str(python.parent)
[email protected]("invalid_kind", ["relative", "missing", "not_executable", "not_venv"])
-def test_resolve_python_executable_rejects_invalid_runtime(
[email protected]("invalid_kind", ["relative", "missing", "not_executable"])
+def test_resolve_python_executable_rejects_invalid_current_runtime(
tmp_path: Path,
invalid_kind: str,
+ monkeypatch,
):
from jiuwenswarm.agents.harness.common.tools.deepresearch.runtime import (
DeepResearchRuntimeError,
@@ -92,17 +96,10 @@ def test_resolve_python_executable_rejects_invalid_runtime(
configured = str(tmp_path / "missing" / "python")
elif invalid_kind == "not_executable":
configured = str(_fake_venv_python(tmp_path, executable=False))
- else:
- python = _fake_venv_python(tmp_path)
- (python.parent.parent / "pyvenv.cfg").unlink()
- configured = str(python)
- token = bind_task_env_overlay({"DEEPRESEARCH_PYTHON_EXECUTABLE": configured})
- try:
- with pytest.raises(DeepResearchRuntimeError, match="^runtime_python_invalid$"):
- resolve_python_executable()
- finally:
- reset_task_env_overlay(token)
+ monkeypatch.setattr(sys, "executable", configured)
+ with pytest.raises(DeepResearchRuntimeError, match="^runtime_python_invalid$"):
+ resolve_python_executable()
def test_build_child_env_isolates_python_and_allows_only_http_proxy_family(
diff --git a/tests/unit_tests/agentserver/test_deepresearch_stream_router.py b/tests/unit_tests/agentserver/test_deepresearch_stream_router.py
index dc0763522a..f796860598 100644
--- a/tests/unit_tests/agentserver/test_deepresearch_stream_router.py
+++ b/tests/unit_tests/agentserver/test_deepresearch_stream_router.py
@@ -13,6 +13,7 @@ from jiuwenswarm.agents.harness.common.tools.deepresearch.stream_router import (
complete_final_report_processing,
route_chunk,
start_final_report_processing,
+ _format_outline_card_markdown,
)
@@ -1616,3 +1617,66 @@ def test_retrieved_source_allows_only_constructed_http_link():
assert r"\[mail\]\(mailto" in content
assert r"\[internal\]\(\/models\)" in content
assert r"\<a href" in content
+
+
+def test_format_outline_card_markdown_happy_path():
+ data = {
+ "title": "行业分析",
+ "thought": "先分析市场,再比较竞争格局。",
+ "sections": [
+ {"title": "市场现状", "is_core_section": True},
+ {"title": "竞争格局", "is_core_section": False},
+ {"title": "发展趋势", "is_core_section": True},
+ ],
+ }
+ result = _format_outline_card_markdown(data)
+ assert result is not None
+ assert "## 页面规划" in result
+ assert "### P1: 市场现状(重点)" in result
+ assert "### P2: 竞争格局" in result
+ assert "### P3: 发展趋势(重点)" in result
+ assert "# 大纲:行业分析" in result
+ assert "**研究思路**:先分析市场,再比较竞争格局。" in result
+
+
+def test_format_outline_card_markdown_missing_title_returns_none():
+ assert _format_outline_card_markdown({}) is None
+ assert _format_outline_card_markdown({"title": "", "sections": []}) is None
+ assert _format_outline_card_markdown({"title": "t", "sections": []}) is None
+ assert _format_outline_card_markdown({"title": "t", "sections": None}) is None
+
+
+def test_format_outline_card_markdown_empty_sections_returns_none():
+ data = {"title": "测试", "sections": [{"title": ""}]}
+ assert _format_outline_card_markdown(data) is None
+
+
+def test_format_outline_card_markdown_no_thought():
+ data = {
+ "title": "测试",
+ "sections": [{"title": "第一章", "is_core_section": False}],
+ }
+ result = _format_outline_card_markdown(data)
+ assert result is not None
+ assert "**研究思路**" not in result
+ assert "### P1: 第一章" in result
+
+
+def test_user_input_ended_emits_chat_reasoning():
+ state = RouterState()
+ frames = route_chunk({"event": "user_input_ended"}, state)
+ assert frames == [
+ {
+ "event_type": "chat.reasoning",
+ "task_id": "deepresearch_stage_2",
+ "stream_source_id": "dr_outline",
+ "content": "大纲已根据您的修改重新生成,自动确认继续研究",
+ },
+ ]
+
+
+def test_user_input_ended_does_not_mutate_state():
+ state = RouterState()
+ route_chunk({"event": "user_input_ended"}, state)
+ assert state.active_nodes == {}
+ assert state.interrupt_node_id == ""
diff --git a/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py b/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py
index b8b6a63c1c..6f6056d60e 100644
--- a/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py
+++ b/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py
@@ -294,7 +294,6 @@ def test_only_six_standard_proxy_names_are_forwarded(tmp_path: Path, monkeypatch
python.write_text("#!/bin/sh\n", encoding="utf-8")
python.chmod(0o755)
(venv / "pyvenv.cfg").write_text("home = /usr/bin\n", encoding="utf-8")
- monkeypatch.setenv("DEEPRESEARCH_PYTHON_EXECUTABLE", str(python))
for key in (
"HTTP_PROXY",
"http_proxy",
@@ -700,12 +699,13 @@ async def test_feedback_interrupt_injects_accumulated_questions():
@pytest.mark.asyncio
-async def test_outline_interrupt_auto_resumes_once_and_completes(tmp_path: Path):
+async def test_outline_interrupt_returns_interrupted_without_auto_resume(tmp_path: Path):
+ """outline_interaction interrupt now surfaces to caller instead of auto-resuming with accepted feedback."""
outline = json.dumps(
{"title": "AI Agent", "sections": [{"id": "1", "title": "架构"}]},
ensure_ascii=False,
)
- start_proc = _Proc(
+ proc = _Proc(
[
json.dumps({"__deepsearch_status__": "started", "conversation_id": "C1"}),
json.dumps({"agent": "outline", "content": outline}, ensure_ascii=False),
@@ -720,28 +720,120 @@ async def test_outline_interrupt_auto_resumes_once_and_completes(tmp_path: Path)
),
]
)
- resume_proc = _Proc(
+ 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"
+ assert outcome["node_id"] == "outline_interaction"
+ assert "interaction_policy" not in outcome
+
+
+async def test_outline_interrupt_marker_uses_card_markdown_and_caches_json(tmp_path: Path):
+ """When interrupted marker lacks outline, card markdown is built from state.outline_parts and full JSON is cached."""
+ outline_json = {
+ "title": "AI Agent 架构",
+ "thought": "从框架到部署",
+ "sections": [
+ {"id": "1", "title": "架构设计", "is_core_section": True, "description": "核心架构"},
+ {"id": "2", "title": "部署方案", "format_requirements": "markdown"},
+ ],
+ }
+ outline_str = json.dumps(outline_json, ensure_ascii=False)
+ proc = _Proc(
[
- json.dumps({"__deepsearch_status__": "resuming", "conversation_id": "C1"}),
+ json.dumps({"__deepsearch_status__": "started", "conversation_id": "C1"}),
+ json.dumps({"agent": "outline", "content": outline_str}, ensure_ascii=False),
json.dumps(
{
- "agent": "sub_reporter",
- "section_idx": "1",
- "section_total": 1,
- "event": "done",
- }
+ "__deepsearch_status__": "interrupted",
+ "agent": "outline_interaction",
+ "conversation_id": "C1",
+ },
+ 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"
+ assert outcome["node_id"] == "outline_interaction"
+ assert "interaction_policy" not in outcome
+ marker = outcome["marker"]
+ assert "## 页面规划" in marker["outline"]
+ assert "### P1: 架构设计(重点)" in marker["outline"]
+ assert "### P2: 部署方案" in marker["outline"]
+ assert marker["preview"]["text"] == marker["outline"]
+ cached = dt._get_cached_outline_json(route, "C1")
+ assert cached["title"] == "AI Agent 架构"
+ assert len(cached["sections"]) == 2
+ assert cached["sections"][0]["is_core_section"] is True
+ assert cached["sections"][0]["description"] == "核心架构"
+ assert cached["sections"][1]["format_requirements"] == "markdown"
+ 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_outline_interrupt_handles_unparseable_outline_parts(tmp_path: Path):
+ """Unparseable state.outline_parts produces empty marker.outline and empty preview, still interrupted."""
+ proc = _Proc(
+ [
+ json.dumps({"__deepsearch_status__": "started", "conversation_id": "C1"}),
+ json.dumps({"agent": "outline", "content": "not valid json"}, ensure_ascii=False),
json.dumps(
{
- "__deepsearch_status__": "completed",
+ "__deepsearch_status__": "interrupted",
+ "agent": "outline_interaction",
"conversation_id": "C1",
- "final_result": {"response_content": "done"},
- }
+ },
+ ensure_ascii=False,
),
]
)
- spawn = AsyncMock(side_effect=[start_proc, resume_proc])
- push = AsyncMock()
route = {
"request_id": "R1",
"channel_id": "CH1",
@@ -749,27 +841,82 @@ async def test_outline_interrupt_auto_resumes_once_and_completes(tmp_path: Path)
"service_id": "default",
"agent_id": "default",
}
- report_path = tmp_path / "report.md"
- with patch.object(dt, "resolve_python_executable", return_value=Path("/runtime/bin/python")), patch.object(
- dt, "_resolve_run_script", return_value="/runner"
- ), patch.object(dt, "_build_deepresearch_request_config", return_value=_valid_config()), patch.object(
- dt, "_build_deepresearch_child_env", return_value={"PATH": "/runtime/bin"}
- ), patch.object(dt, "_get_route", return_value=route), patch.object(
- dt, "WebSocketGatewayPushTransport", return_value=push
- ), patch.object(
- dt,
- "_write_report_artifacts_stream",
- new=AsyncMock(return_value={"md": str(report_path)}),
- ), patch("asyncio.create_subprocess_exec", new=spawn):
+ 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"
+ assert outcome["node_id"] == "outline_interaction"
+ assert "interaction_policy" not in outcome
+ marker = outcome["marker"]
+ assert marker["outline"] == ""
+ assert marker["preview"] == {"text": ""}
+ cached = dt._get_cached_outline_json(route, "C1")
+ assert cached == {}
+ 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_behavior_unchanged(tmp_path: Path):
+ """feedback_handler interrupt still returns interrupted outcome with questions in marker — regression check."""
+ proc = _Proc(
+ [
+ json.dumps({"__deepsearch_status__": "started", "conversation_id": "C1"}),
+ json.dumps(
+ {
+ "__deepsearch_status__": "interrupted",
+ "agent": "feedback_handler",
+ "conversation_id": "C1",
+ "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"] == "completed"
- assert spawn.await_count == 2
- resume_args = spawn.await_args_list[1].args
- assert resume_args[2] == "resume"
- assert '{"interrupt_feedback":"accepted","feedback":""}' in resume_args
+ assert outcome["status"] == "interrupted"
+ assert outcome["node_id"] == "feedback_handler"
+ assert "interaction_policy" not in outcome
+ marker = outcome["marker"]
+ assert marker["questions"] == [{"id": "q1", "question": "什么?"}]
+ assert "preview" not in marker
@pytest.mark.asyncio
@@ -786,13 +933,26 @@ async def test_repeated_outline_interrupt_returns_loop_error():
),
]
)
+ artifact = dt._ProgressArtifact(Path("/private/progress"), (1, 2), (3, 4))
+ remove = Mock()
+ manager = Mock()
patches = _stream_patches(proc)
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="resume", conversation_id="C1", node="outline_interaction"
+ action="resume",
+ conversation_id="C1",
+ node="outline_interaction",
+ interaction_result=(
+ '{"status":"answered","answers":[{"question":"q",'
+ '"selected_options":["outline_confirm"],"custom_input":null}]}'
+ ),
)
)
@@ -843,6 +1003,75 @@ async def test_completed_marker_requires_all_section_progress():
assert outcome["error_code"] == "incomplete_section_progress"
+async def test_completed_marker_accepts_p_numbered_sections_beneath_wrapper_heading(
+ tmp_path: Path,
+):
+ outline = (
+ "# 大纲:用户需求洞察报告\n"
+ "## 页面规划\n"
+ "### P1: 用户画像构建(重点)\n"
+ "### P2: 行为习惯分析(重点)\n"
+ "### P3: 真实痛点挖掘(重点)\n"
+ "### P4: 消费决策逻辑剖析(重点)\n"
+ "### P5: 潜在需求识别与产品设计建议(重点)"
+ )
+ lines = [
+ json.dumps({"__deepsearch_status__": "started", "conversation_id": "C1"}),
+ json.dumps({"agent": "outline", "content": outline}),
+ *[
+ json.dumps(
+ {
+ "agent": "sub_reporter",
+ "section_idx": str(index),
+ "section_total": 5,
+ "event": "done",
+ }
+ )
+ for index in range(1, 6)
+ ],
+ json.dumps(
+ {
+ "__deepsearch_status__": "completed",
+ "conversation_id": "C1",
+ "final_result": {"response_content": "# Final"},
+ }
+ ),
+ ]
+ proc = _Proc(lines)
+ route = {
+ "request_id": "R1",
+ "channel_id": "CH1",
+ "session_id": "S1",
+ "service_id": "default",
+ "agent_id": "default",
+ }
+ 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,
+ "_write_report_artifacts_stream",
+ new=AsyncMock(return_value={"md": str(tmp_path / "r.md")}),
+ )
+ )
+ outcome = json.loads(
+ await dt.deepresearch_stream._func(action="start", query="q")
+ )
+
+ assert outcome == {
+ "status": "completed",
+ "conversation_id": "C1",
+ "report_delivered": True,
+ "report_chars": len("# Final"),
+ }
+
+
@pytest.mark.asyncio
async def test_completed_marker_accepts_sdk_final_report_after_degraded_section(
tmp_path: Path,
@@ -911,6 +1140,126 @@ async def test_completed_marker_accepts_sdk_final_report_after_degraded_section(
}
+async def test_completed_marker_accepts_formal_sdk_end_result_when_section_done_is_missing(
+ tmp_path: Path,
+):
+ """The SDK's successful EndNode result is the authoritative workflow boundary."""
+ final_result = {"response_content": "# Final"}
+ proc = _Proc(
+ [
+ json.dumps({"__deepsearch_status__": "started", "conversation_id": "C1"}),
+ json.dumps(
+ {
+ "agent": "sub_reporter",
+ "section_idx": "1",
+ "section_total": 2,
+ "event": "done",
+ }
+ ),
+ json.dumps(
+ {
+ "agent": "reporter",
+ "section_idx": "0",
+ "event": "start",
+ "content": "assembling report",
+ }
+ ),
+ json.dumps(
+ {
+ "agent": "end",
+ "section_idx": "0",
+ "event": "summary_response",
+ "content": json.dumps(final_result),
+ }
+ ),
+ json.dumps(
+ {
+ "__deepsearch_status__": "completed",
+ "conversation_id": "C1",
+ "final_result": final_result,
+ }
+ ),
+ ]
+ )
+ route = {
+ "request_id": "R1",
+ "channel_id": "CH1",
+ "session_id": "S1",
+ "service_id": "default",
+ "agent_id": "default",
+ }
+ 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,
+ "_write_report_artifacts_stream",
+ new=AsyncMock(return_value={"md": str(tmp_path / "r.md")}),
+ )
+ )
+ outcome = json.loads(
+ await dt.deepresearch_stream._func(action="start", query="q")
+ )
+
+ assert outcome == {
+ "status": "completed",
+ "conversation_id": "C1",
+ "report_delivered": True,
+ "report_chars": len("# Final"),
+ }
+
+
+async def test_completed_marker_rejects_sdk_end_result_with_exception() -> None:
+ final_result = {
+ "response_content": "# Partial",
+ "exception_info": "report workflow failed",
+ }
+ proc = _Proc(
+ [
+ json.dumps({"__deepsearch_status__": "started", "conversation_id": "C1"}),
+ json.dumps(
+ {
+ "agent": "reporter",
+ "section_idx": "0",
+ "event": "start",
+ "content": "assembling report",
+ }
+ ),
+ json.dumps(
+ {
+ "agent": "end",
+ "section_idx": "0",
+ "event": "summary_response",
+ "content": json.dumps(final_result),
+ }
+ ),
+ json.dumps(
+ {
+ "__deepsearch_status__": "completed",
+ "conversation_id": "C1",
+ "final_result": final_result,
+ }
+ ),
+ ]
+ )
+ patches = _stream_patches(proc)
+ with ExitStack() as stack:
+ for item in patches:
+ stack.enter_context(item)
+ outcome = json.loads(
+ await dt.deepresearch_stream._func(action="start", query="q")
+ )
+
+ assert outcome["error_code"] == "incomplete_section_progress"
+
+
@pytest.mark.asyncio
async def test_completed_marker_rejects_final_pipeline_that_only_started(tmp_path: Path):
proc = _Proc(
@@ -2873,3 +3222,326 @@ def test_posix_zip_extraction_stays_on_held_destination_when_name_is_swapped(
assert list(outside.iterdir()) == []
assert moved_owned.is_dir()
assert list(moved_owned.iterdir()) == []
+
+# --- Todo 3: outline_interaction resume resolver tests ---
+
+def _outline_route() -> dict[str, str]:
+ return {
+ "request_id": "R1",
+ "channel_id": "CH1",
+ "session_id": "S1",
+ "service_id": "default",
+ "agent_id": "default",
+ }
+
+
+def _three_section_outline() -> dict[str, Any]:
+ return {
+ "title": "AI Agent 架构",
+ "thought": "从框架到部署",
+ "sections": [
+ {"id": "1", "title": "架构设计", "is_core_section": True, "description": "核心架构"},
+ {"id": "2", "title": "部署方案", "format_requirements": "markdown"},
+ {"id": "3", "title": "性能评估", "is_core_section": False, "description": "基准测试"},
+ ],
+ }
+
+
+def _outline_interaction_result(selected: str, custom_input: str | None = None) -> str:
+ payload: dict[str, Any] = {
+ "request_id": "R1",
+ "source": "deepresearch_stream",
+ "answers": [
+ {
+ "question": "请审阅研究报告大纲",
+ "selected_options": [selected],
+ "custom_input": custom_input,
+ }
+ ],
+ }
+ return json.dumps(payload, ensure_ascii=False)
+
+
+def test_resolve_outline_confirm_branch_returns_accepted_feedback() -> None:
+ """outline_confirm -> interrupt_feedback=accepted, empty feedback string."""
+ feedback = dt._resolve_outline_interaction_feedback(
+ _outline_interaction_result("outline_confirm"),
+ conversation_id="C1",
+ route=_outline_route(),
+ )
+ parsed = json.loads(feedback)
+ assert parsed["interrupt_feedback"] == "accepted"
+ assert parsed["feedback"] == ""
+
+
+def test_resolve_outline_confirm_accepts_live_ask_user_label() -> None:
+ """The generic AskUser card returns its display label, not the UI-only id."""
+ interaction_result = json.dumps(
+ {
+ "status": "answered",
+ "answers": [
+ {
+ "question": "请审阅生成的研究报告大纲,确认后将继续执行深度研究。",
+ "selected_options": ["确认大纲,继续研究"],
+ "custom_input": None,
+ }
+ ],
+ },
+ ensure_ascii=False,
+ )
+
+ feedback = dt._resolve_outline_interaction_feedback(
+ interaction_result,
+ conversation_id="C1",
+ route=_outline_route(),
+ )
+
+ assert json.loads(feedback) == {
+ "interrupt_feedback": "accepted",
+ "feedback": "",
+ }
+
+
+def test_resolve_outline_skipped_result_defaults_to_accepted() -> None:
+ """Outline timeout/skip follows the skill contract and continues research."""
+ interaction_result = json.dumps(
+ {
+ "status": "skipped",
+ "answers": [
+ {
+ "question": "请审阅生成的研究报告大纲,确认后将继续执行深度研究。",
+ "selected_options": [],
+ "custom_input": None,
+ }
+ ],
+ },
+ ensure_ascii=False,
+ )
+
+ feedback = dt._resolve_outline_interaction_feedback(
+ interaction_result,
+ conversation_id="C1",
+ route=_outline_route(),
+ )
+
+ assert json.loads(feedback) == {
+ "interrupt_feedback": "accepted",
+ "feedback": "",
+ }
+
+
+def test_resolve_outline_use_edited_updates_all_titles_and_preserves_other_fields() -> None:
+ """outline_use_edited with matching page count -> revise_outline, all titles updated, other fields unchanged."""
+ route = _outline_route()
+ dt._cache_outline_json(route, "C1", _three_section_outline())
+ try:
+ edited_md = "### P1: NewA\n### P2: NewB\n### P3: NewC"
+ feedback = dt._resolve_outline_interaction_feedback(
+ _outline_interaction_result("outline_use_edited", custom_input=edited_md),
+ conversation_id="C1",
+ route=route,
+ )
+ parsed = json.loads(feedback)
+ assert parsed["interrupt_feedback"] == "revise_outline"
+ inner = json.loads(parsed["feedback"])
+ assert inner["title"] == "AI Agent 架构"
+ assert inner["sections"][0]["title"] == "NewA"
+ assert inner["sections"][1]["title"] == "NewB"
+ assert inner["sections"][2]["title"] == "NewC"
+ # Other fields preserved
+ assert inner["sections"][0]["is_core_section"] is True
+ assert inner["sections"][0]["description"] == "核心架构"
+ assert inner["sections"][1]["format_requirements"] == "markdown"
+ assert inner["sections"][2]["is_core_section"] is False
+ # Cache not mutated (shallow copy returned by getter is the working surface)
+ cached = dt._get_cached_outline_json(route, "C1")
+ assert cached["sections"][0]["title"] == "架构设计"
+ finally:
+ with dt._OUTLINE_JSON_CACHES_GUARD:
+ dt._OUTLINE_JSON_CACHES.clear()
+ with dt._OUTLINE_TITLE_CACHES_GUARD:
+ dt._OUTLINE_TITLE_CACHES.clear()
+
+
+def test_resolve_outline_use_edited_strips_core_section_suffix() -> None:
+ """(重点) suffix in edited title is stripped before mapping to Section.title."""
+ route = _outline_route()
+ dt._cache_outline_json(route, "C1", _three_section_outline())
+ try:
+ edited_md = "### P1: 全新架构(重点)\n### P2: 部署方案"
+ feedback = dt._resolve_outline_interaction_feedback(
+ _outline_interaction_result("outline_use_edited", custom_input=edited_md),
+ conversation_id="C1",
+ route=route,
+ )
+ parsed = json.loads(feedback)
+ inner = json.loads(parsed["feedback"])
+ assert inner["sections"][0]["title"] == "全新架构"
+ assert inner["sections"][1]["title"] == "部署方案"
+ finally:
+ with dt._OUTLINE_JSON_CACHES_GUARD:
+ dt._OUTLINE_JSON_CACHES.clear()
+ with dt._OUTLINE_TITLE_CACHES_GUARD:
+ dt._OUTLINE_TITLE_CACHES.clear()
+
+
+def test_resolve_outline_use_edited_cache_miss_raises_value_error() -> None:
+ """No cached Outline JSON -> ValueError (fail closed)."""
+ route = _outline_route()
+ try:
+ with pytest.raises(ValueError, match="cached"):
+ dt._resolve_outline_interaction_feedback(
+ _outline_interaction_result("outline_use_edited", custom_input="### P1: NewA"),
+ conversation_id="C1",
+ route=route,
+ )
+ finally:
+ with dt._OUTLINE_JSON_CACHES_GUARD:
+ dt._OUTLINE_JSON_CACHES.clear()
+ with dt._OUTLINE_TITLE_CACHES_GUARD:
+ dt._OUTLINE_TITLE_CACHES.clear()
+
+
+def test_resolve_outline_use_edited_empty_cache_raises_value_error() -> None:
+ """Empty dict cached (Todo 2 parse-failure path) -> ValueError (treat as cache miss)."""
+ route = _outline_route()
+ dt._cache_outline_json(route, "C1", {})
+ try:
+ with pytest.raises(ValueError, match="cached"):
+ dt._resolve_outline_interaction_feedback(
+ _outline_interaction_result("outline_use_edited", custom_input="### P1: NewA"),
+ conversation_id="C1",
+ route=route,
+ )
+ finally:
+ with dt._OUTLINE_JSON_CACHES_GUARD:
+ dt._OUTLINE_JSON_CACHES.clear()
+ with dt._OUTLINE_TITLE_CACHES_GUARD:
+ dt._OUTLINE_TITLE_CACHES.clear()
+
+
+def test_resolve_outline_page_count_mismatch_updates_only_matching_indices() -> None:
+ """Edited has fewer pages than cached -> only matching indices updated, unmatched sections untouched."""
+ route = _outline_route()
+ dt._cache_outline_json(route, "C1", _three_section_outline())
+ try:
+ edited_md = "### P1: NewA\n### P2: NewB"
+ feedback = dt._resolve_outline_interaction_feedback(
+ _outline_interaction_result("outline_use_edited", custom_input=edited_md),
+ conversation_id="C1",
+ route=route,
+ )
+ parsed = json.loads(feedback)
+ inner = json.loads(parsed["feedback"])
+ assert inner["sections"][0]["title"] == "NewA"
+ assert inner["sections"][1]["title"] == "NewB"
+ # Third section keeps original title (no add/remove)
+ assert inner["sections"][2]["title"] == "性能评估"
+ assert len(inner["sections"]) == 3
+ finally:
+ with dt._OUTLINE_JSON_CACHES_GUARD:
+ dt._OUTLINE_JSON_CACHES.clear()
+ with dt._OUTLINE_TITLE_CACHES_GUARD:
+ dt._OUTLINE_TITLE_CACHES.clear()
+
+
+def test_resolve_outline_page_count_more_than_cached_skips_out_of_range() -> None:
+ """Edited has more pages than cached -> out-of-range pages skipped, no new sections added."""
+ route = _outline_route()
+ dt._cache_outline_json(route, "C1", _three_section_outline())
+ try:
+ edited_md = "### P1: NewA\n### P2: NewB\n### P3: NewC\n### P4: ShouldBeSkipped"
+ feedback = dt._resolve_outline_interaction_feedback(
+ _outline_interaction_result("outline_use_edited", custom_input=edited_md),
+ conversation_id="C1",
+ route=route,
+ )
+ parsed = json.loads(feedback)
+ inner = json.loads(parsed["feedback"])
+ assert len(inner["sections"]) == 3
+ assert inner["sections"][0]["title"] == "NewA"
+ assert inner["sections"][1]["title"] == "NewB"
+ assert inner["sections"][2]["title"] == "NewC"
+ finally:
+ with dt._OUTLINE_JSON_CACHES_GUARD:
+ dt._OUTLINE_JSON_CACHES.clear()
+ with dt._OUTLINE_TITLE_CACHES_GUARD:
+ dt._OUTLINE_TITLE_CACHES.clear()
+
+
+ "interaction_result",
+ [
+ "",
+ "not-json",
+ "[]",
+ json.dumps({"status": "answered"}), # missing answers
+ json.dumps({"status": "answered", "answers": "not-a-list"}),
+ json.dumps({"status": "answered", "answers": []}),
+ json.dumps({"status": "answered", "answers": [{"selected_options": "not-a-list"}]}),
+ json.dumps({"status": "answered", "answers": [{"selected_options": []}]}),
+ json.dumps({"status": "answered", "answers": [{"selected_options": ["unknown_choice"]}]}),
+ json.dumps({"status": "answered", "answers": [{"selected_options": ["outline_use_edited"], "custom_input": "no heading lines here"}]}),
+ ],
+)
+def test_resolve_outline_malformed_result_raises_value_error(interaction_result: str) -> None:
+ """All malformed interaction_result variants -> ValueError (fail closed, no auto-accept)."""
+ route = _outline_route()
+ dt._cache_outline_json(route, "C1", _three_section_outline())
+ try:
+ with pytest.raises(ValueError):
+ dt._resolve_outline_interaction_feedback(
+ interaction_result,
+ conversation_id="C1",
+ route=route,
+ )
+ finally:
+ with dt._OUTLINE_JSON_CACHES_GUARD:
+ dt._OUTLINE_JSON_CACHES.clear()
+ with dt._OUTLINE_TITLE_CACHES_GUARD:
+ dt._OUTLINE_TITLE_CACHES.clear()
+
+
+def test_resolve_outline_cancel_status_returns_cancel_feedback() -> None:
+ """AskUserQuestion status=cancelled -> interrupt_feedback=cancel, empty feedback."""
+ feedback = dt._resolve_outline_interaction_feedback(
+ json.dumps({"status": "cancelled", "answers": []}, ensure_ascii=False),
+ conversation_id="C1",
+ route=_outline_route(),
+ )
+ parsed = json.loads(feedback)
+ assert parsed["interrupt_feedback"] == "cancel"
+ assert parsed["feedback"] == ""
+
+
+def test_resolve_outline_error_status_returns_cancel_feedback() -> None:
+ """AskUserQuestion status=error -> interrupt_feedback=cancel (treat errors as user-initiated cancellation)."""
+ feedback = dt._resolve_outline_interaction_feedback(
+ json.dumps({"status": "error", "error": "ask_user_question timeout"}, ensure_ascii=False),
+ conversation_id="C1",
+ route=_outline_route(),
+ )
+ parsed = json.loads(feedback)
+ assert parsed["interrupt_feedback"] == "cancel"
+ assert parsed["feedback"] == ""
+
+
+async def test_outline_interaction_resume_invalid_result_does_not_spawn():
+ """outline_interaction resume with malformed interaction_result returns outline_interaction_invalid_result and never spawns the subprocess."""
+ spawn = AsyncMock()
+ with patch.object(dt, "resolve_python_executable", return_value=Path("/runtime/bin/python")), patch.object(
+ dt, "_resolve_run_script", return_value="/runner"
+ ), patch("asyncio.create_subprocess_exec", new=spawn):
+ outcome = json.loads(
+ await dt.deepresearch_stream._func(
+ action="resume",
+ conversation_id="C1",
+ node="outline_interaction",
+ interaction_result="not-json",
+ )
+ )
+
+ assert outcome["error_code"] == "outline_interaction_invalid_result"
+ assert outcome["status"] == "error"
+ spawn.assert_not_awaited()
diff --git a/tests/unit_tests/agentserver/test_deepresearch_task_manager.py b/tests/unit_tests/agentserver/test_deepresearch_task_manager.py
index 9daa8bfa78..6f89a38857 100644
--- a/tests/unit_tests/agentserver/test_deepresearch_task_manager.py
+++ b/tests/unit_tests/agentserver/test_deepresearch_task_manager.py
@@ -430,6 +430,22 @@ def test_explicit_petal_snapshot_never_reads_bound_tenant_overlay():
"# 深度研究报告:主题\n## 第1章:背景\n### 2. 趋势\n## 结论",
{"1": "背景", "2": "趋势", "3": "结论"},
),
+ (
+ "# 大纲:用户需求洞察报告\n"
+ "## 页面规划\n"
+ "### P1: 用户画像构建(重点)\n"
+ "### P2: 行为习惯分析(重点)\n"
+ "### P3: 真实痛点挖掘(重点)\n"
+ "### P4: 消费决策逻辑剖析(重点)\n"
+ "### P5: 潜在需求识别与产品设计建议(重点)",
+ {
+ "1": "用户画像构建(重点)",
+ "2": "行为习惯分析(重点)",
+ "3": "真实痛点挖掘(重点)",
+ "4": "消费决策逻辑剖析(重点)",
+ "5": "潜在需求识别与产品设计建议(重点)",
+ },
+ ),
],
)
def test_extract_deepresearch_section_titles(text, expected):
diff --git a/tests/unit_tests/agentserver/test_interrupt_helpers.py b/tests/unit_tests/agentserver/test_interrupt_helpers.py
index 754970b6d3..578d92cff6 100644
--- a/tests/unit_tests/agentserver/test_interrupt_helpers.py
+++ b/tests/unit_tests/agentserver/test_interrupt_helpers.py
@@ -213,3 +213,39 @@ def test_build_multi_questions_appends_other_for_valid_options():
)
assert [opt["label"] for opt in questions[0]["options"]] == ["A", "B", "Other"]
+
+
+def test_build_multi_questions_preserves_question_preview():
+ from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers import (
+ _build_multi_questions,
+ )
+
+ questions = _build_multi_questions(
+ [
+ {
+ "question": "Review the outline?",
+ "header": "Outline",
+ "options": [
+ {"label": "Confirm", "description": "Continue"},
+ {"label": "Edit", "description": "Revise"},
+ ],
+ "preview": {
+ "title": "Research outline",
+ "text": "# Outline\n\n## P1: Scope",
+ "format": "markdown",
+ "editable": True,
+ "outline_ref": "outline-1",
+ "meta": {"currentRound": 1},
+ },
+ }
+ ]
+ )
+
+ assert questions[0]["preview"] == {
+ "title": "Research outline",
+ "text": "# Outline\n\n## P1: Scope",
+ "format": "markdown",
+ "editable": True,
+ "outline_ref": "outline-1",
+ "meta": {"currentRound": 1},
+ }
diff --git a/tests/unit_tests/common/test_ask_user_response.py b/tests/unit_tests/common/test_ask_user_response.py
new file mode 100644
index 0000000000..7efad4b94d
--- /dev/null
+++ b/tests/unit_tests/common/test_ask_user_response.py
@@ -0,0 +1,162 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Tests for the canonical AskUser response contract."""
+
+from __future__ import annotations
+
+import pytest
+
+from jiuwenswarm.common.schema.ask_user import (
+ AskUserResponseError,
+ normalize_ask_user_response,
+ parse_ask_user_response,
+)
+
+
+def test_normalize_answered_response_preserves_one_structured_representation():
+ response = normalize_ask_user_response(
+ status="answered",
+ answers=[
+ {
+ "question": " Enable which modules? ",
+ "selected_options": ["auth", "Other"],
+ "custom_input": " metrics ",
+ }
+ ],
+ original_request=" Build the service ",
+ )
+
+ assert response.to_dict() == {
+ "status": "answered",
+ "answers": [
+ {
+ "question": "Enable which modules?",
+ "selected_options": ["auth"],
+ "custom_input": "metrics",
+ }
+ ],
+ "original_request": "Build the service",
+ }
+ assert response.to_readable_text() == "Enable which modules?: auth, metrics"
+
+
[email protected]("label", ["Other", "其他"])
+def test_explicit_answered_bare_other_preserves_empty_answered_contract(label: str):
+ response = normalize_ask_user_response(
+ status="answered",
+ answers=[
+ {
+ "question": "Which?",
+ "selected_options": [label],
+ "custom_input": " ",
+ }
+ ],
+ )
+
+ assert response.to_dict() == {"status": "answered", "answers": []}
+
+
+def test_normalize_missing_status_derives_answered_from_current_array_protocol():
+ response = normalize_ask_user_response(
+ status="",
+ answers=[
+ {
+ "question": "",
+ "selected_options": [],
+ "custom_input": "plain answer",
+ }
+ ],
+ )
+
+ assert response.status == "answered"
+ assert response.to_readable_text() == "plain answer"
+
+
+def test_normalize_missing_status_defaults_to_answered_for_current_native_clients():
+ response = normalize_ask_user_response(
+ status="",
+ answers=[
+ {
+ "question": "Which?",
+ "selected_options": ["Other"],
+ "custom_input": " ",
+ }
+ ],
+ )
+
+ assert response.to_dict() == {"status": "answered", "answers": []}
+
+
+def test_explicit_answered_without_user_content_is_preserved():
+ response = normalize_ask_user_response(status="answered", answers=[])
+
+ assert response.to_dict() == {"status": "answered", "answers": []}
+
+
+def test_skipped_with_user_content_is_rejected():
+ with pytest.raises(AskUserResponseError, match="skipped response"):
+ normalize_ask_user_response(
+ status="skipped",
+ answers=[
+ {
+ "question": "Which?",
+ "selected_options": ["A"],
+ "custom_input": None,
+ }
+ ],
+ )
+
+
+ "answers",
+ [
+ {"Which?": "A"},
+ ["A"],
+ [{"question": "Which?", "selected_options": "A"}],
+ [{"question": "Which?", "selected_options": [1]}],
+ ],
+)
+def test_malformed_or_legacy_answers_are_rejected(answers):
+ with pytest.raises(AskUserResponseError):
+ normalize_ask_user_response(status="answered", answers=answers)
+
+
+def test_parse_rejects_legacy_sidecar_and_answer_map():
+ with pytest.raises(AskUserResponseError):
+ parse_ask_user_response(
+ {
+ "answers": {"Which?": "A"},
+ "_structured_response": {
+ "status": "answered",
+ "answers": [],
+ },
+ }
+ )
+
+
+def test_parse_accepts_and_drops_unknown_extension_fields():
+ response = parse_ask_user_response(
+ {
+ "status": "answered",
+ "answers": [
+ {
+ "question": "Which?",
+ "selected_options": ["A"],
+ "custom_input": None,
+ "answer_metadata": {"display_order": 1},
+ }
+ ],
+ "client_version": "1.2",
+ }
+ )
+
+ assert response.to_dict() == {
+ "status": "answered",
+ "answers": [
+ {
+ "question": "Which?",
+ "selected_options": ["A"],
+ "custom_input": None,
+ }
+ ],
+ }
diff --git a/tests/unit_tests/common/test_local_env_config.py b/tests/unit_tests/common/test_local_env_config.py
index 0d23efa95d..08b66bc447 100644
--- a/tests/unit_tests/common/test_local_env_config.py
+++ b/tests/unit_tests/common/test_local_env_config.py
@@ -113,18 +113,12 @@ class TestLocalEnvConfig:
assert result == "plain_text"
mock_crypto.encrypt.assert_not_called()
- def test_deepresearch_python_executable_is_overlay_aware_business_config(self):
+ def test_deepresearch_python_executable_is_not_a_runtime_config_source(self):
key = "DEEPRESEARCH_PYTHON_EXECUTABLE"
- assert key in BUSINESS_MIRROR_KEYS
+ assert key not in BUSINESS_MIRROR_KEYS
assert key not in SPAWN_ENV_KEYS
assert is_sensitive_env_name(key) is False
- token = bind_task_env_overlay({key: "/tenant/venv/bin/python"})
- try:
- assert read_env(key) == "/tenant/venv/bin/python"
- finally:
- reset_task_env_overlay(token)
-
def test_export_spawn_environ_keeps_process_path_without_tenant_credentials(self):
from jiuwenswarm.common.local_env_config import export_spawn_environ
diff --git a/tests/unit_tests/test_default_headers_maas_fallback.py b/tests/unit_tests/test_default_headers_maas_fallback.py
index b49133caa6..3e703caf53 100644
--- a/tests/unit_tests/test_default_headers_maas_fallback.py
+++ b/tests/unit_tests/test_default_headers_maas_fallback.py
@@ -44,6 +44,19 @@ def test_read_default_headers_falls_back_to_petal_json() -> None:
reset_task_env_overlay(token)
+def test_read_default_headers_does_not_reuse_petal_auth_for_custom_openai() -> None:
+ token = bind_task_env_overlay(
+ {
+ "API_KEY": "sk-custom-openai",
+ "PETAL_SEARCH_HEADERS": '{"Authorization":"Basic petal"}',
+ }
+ )
+ try:
+ assert read_default_headers() is None
+ finally:
+ reset_task_env_overlay(token)
+
+
def test_read_default_headers_ignores_non_json_petal_key() -> None:
token = bind_task_env_overlay({"PETAL_API_KEY": "sk-not-json"})
try: