JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(team): 修复 ask_user 交互事件未达前端与作答回注死锁
ZhouRZ12fc5635b3a0
diff --git a/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py b/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.pyindex 10966853a1..20adfe1e60 100644--- a/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py+++ b/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py@@ -1113,8 +1113,11 @@ def _extract_questions_from_value(value_obj: Any) -> list | None:# 2. questions embedded in tool_args (StructuredAskUserRail path)# ToolCallInterruptRequest.tool_args preserves the original tool call- # arguments, including the `questions` parameter.+ # arguments, including the `questions` parameter. task_interaction 载荷+ # 到达时值已是 model_dump 的 dict,tool_args 是键而非属性。tool_args = getattr(value_obj, 'tool_args', None)+ if tool_args is None and isinstance(value_obj, dict):+ tool_args = value_obj.get('tool_args')if tool_args is not None:if isinstance(tool_args, str):try:diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 66bfbe3aeb..d954efdc8c 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -17129,16 +17129,24 @@ class JiuWenSwarmDeepAdapter:session_adapter = await self._get_or_create_session_adapter(request.session_id, request=request)- try:- request_mcp = await session_adapter.register_request_scoped_office_claw_mcp(request)- except McpRegistryChatError as mcp_err:- return AgentResponse(- request_id=request.request_id,- channel_id=request.channel_id,- ok=False,- payload={"error": str(mcp_err)},- metadata=request.metadata,- )+ # 同流式路径:team 模式控制续接跳过 request-scoped MCP 注册,+ # 避免与持有生命周期锁的被中断原始请求死锁。+ from jiuwenswarm.server.runtime.agent_adapter.team_helpers import (+ is_team_control_continuation,+ )++ request_mcp = None+ if not is_team_control_continuation(request, inputs.get("query")):+ try:+ request_mcp = await session_adapter.register_request_scoped_office_claw_mcp(request)+ except McpRegistryChatError as mcp_err:+ return AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=False,+ payload={"error": str(mcp_err)},+ metadata=request.metadata,+ )try:with bind_active_office_claw_mcp_tools(request_mcp.tool_ids if request_mcp is not None else ()@@ -17821,17 +17829,27 @@ class JiuWenSwarmDeepAdapter:session_adapter = await self._get_or_create_session_adapter(request.session_id, request=request)- try:- request_mcp = await session_adapter.register_request_scoped_office_claw_mcp(request)- except McpRegistryChatError as mcp_err:- yield AgentResponseChunk(- request_id=request.request_id,- channel_id=request.channel_id,- payload={"event_type": "chat.error", "error": str(mcp_err)},- is_complete=True,- metadata=request.metadata or {},- )- return+ # team 模式控制续接(ask_user/permission 作答)只负责把答案经+ # interact() 投递给存活的 runtime,自身不执行工具;被中断的原始+ # 请求仍持有 request-scoped MCP 生命周期锁,此处再注册会与其+ # 互相等待形成死锁,故跳过注册、沿用原始请求的注册。+ from jiuwenswarm.server.runtime.agent_adapter.team_helpers import (+ is_team_control_continuation,+ )++ request_mcp = None+ if not is_team_control_continuation(request, inputs.get("query")):+ try:+ request_mcp = await session_adapter.register_request_scoped_office_claw_mcp(request)+ except McpRegistryChatError as mcp_err:+ yield AgentResponseChunk(+ request_id=request.request_id,+ channel_id=request.channel_id,+ payload={"event_type": "chat.error", "error": str(mcp_err)},+ is_complete=True,+ metadata=request.metadata or {},+ )+ returntry:with bind_active_office_claw_mcp_tools(request_mcp.tool_ids if request_mcp is not None else ()@@ -19810,6 +19828,27 @@ class JiuWenSwarmDeepAdapter:"任务执行失败",)return {"event_type": "chat.error", "error": error or "任务执行失败"}+ if inner_val == "task_interaction":+ # native-harness ask_user interrupts+ # surface here without __interaction__ payloads reaching+ # the stream. Parse the embedded interrupt result so the+ # question card still reaches the frontend.+ from jiuwenswarm.server.utils.stream_utils import (+ parse_task_interaction_payload,+ )+ try:+ interaction_event = parse_task_interaction_payload(payload)+ except Exception:+ logger.exception(+ "[interface_deep] failed to parse task_interaction payload"+ )+ interaction_event = None+ if interaction_event is not None:+ return interaction_event+ logger.warning(+ "[interface_deep] task_interaction without parsable ask_user payload;"+ " no question card could be built"+ )# Close the controller_output enum: HITL cards are emitted via# ``__interaction__``; remaining types are control-plane metadata.# Never fall through to ``str(payload)`` → chat.delta (ISSUE #3892).diff --git a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.pyindex a23de74ed8..1c08cce900 100644--- a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py+++ b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py@@ -569,6 +569,25 @@ def _normalize_team_query(query: Any, *, channel_id: str | None, language: str)return query+def is_team_control_continuation(request: Any, query: Any) -> bool:+ """判断请求是否为 team 模式控制续接(仅向存活 runtime 投递中断答案)。++ ask_user / permission 卡片的作答以新的 chat.send 到达:query 已被+ _build_inputs 归一为 InteractiveInput,真实投递动作是 team_manager.interact()。+ 此类请求自身不执行任何工具,必须沿用被中断原始请求持有的 request-scoped+ OfficeClaw MCP 注册;若在此再注册,会阻塞在原始请求释放的 MCP 生命周期+ 锁上(原始请求正等待这份答案,形成死锁)。+ """+ params = request.params if isinstance(getattr(request, "params", None), dict) else {}+ if params.get("mode", "agent") not in ("team", "team.plan", "code.team"):+ return False+ if params.get("source") not in {"permission_interrupt", "ask_user_interrupt"}:+ return False+ from openjiuwen.core.session.interaction.interactive_input import InteractiveInput++ return isinstance(query, InteractiveInput)++async def _team_session_has_runtime(team_manager: TeamManager, session_id: str) -> bool:# Keep ordinary team first-request detection scoped to claw-local# live markers only. Resumable Runner-pool entries are reserved for@@ -1399,6 +1418,83 @@ def _is_duplicate_ask_user_question(return False+# Chunk types that mean "the round made progress" — any of them cancels the+# ask_user card resend watchdog. llm_usage is excluded:+# usage frames accompany the interaction chunk itself, not a continuation.+_TEAM_PROGRESS_CHUNK_TYPES = frozenset({+ "llm_output", "llm_reasoning", "content_chunk", "tool_call",+ "tool_update", "controller_output", "answer", "__interaction__",+ "message", "team.runtime_ready", "team.completed",+})++_ASK_USER_RESEND_INTERVAL_S = max(+ 5.0,+ float(os.environ.get("JIUWENSWARM_TEAM_ASK_USER_RESEND_INTERVAL_S", "60") or 60),+)+_ASK_USER_RESEND_MAX = max(+ 1, int(os.environ.get("JIUWENSWARM_TEAM_ASK_USER_RESEND_MAX", "5") or 5)+)+++async def _resend_ask_user_loop(+ channel_id: str | None,+ session_id: str,+ event: dict[str, Any],+) -> None:+ """Re-broadcast a chat.ask_user_question card while the round stays quiet.++ Defense-in-depth for interaction-frame delivery loss:+ if the frontend misses the card it can never answer and the server waits+ forever. Resend the same request_id periodically; any real progress chunk+ cancels the loop.+ """+ request_id = str(event.get("request_id") or "")+ for attempt in range(1, _ASK_USER_RESEND_MAX + 1):+ await asyncio.sleep(_ASK_USER_RESEND_INTERVAL_S)+ logger.warning(+ "[TeamHelpers] ask_user card not answered; resending:"+ " channel_id=%s session_id=%s request_id=%s attempt=%s/%s",+ _resolve_channel_id(channel_id),+ session_id,+ request_id,+ attempt,+ _ASK_USER_RESEND_MAX,+ )+ _broadcast_event(channel_id, session_id, dict(event))+ logger.error(+ "[TeamHelpers] ask_user card still unanswered after %s resends:"+ " channel_id=%s session_id=%s request_id=%s",+ _ASK_USER_RESEND_MAX,+ _resolve_channel_id(channel_id),+ session_id,+ request_id,+ )+++def _arm_ask_user_resend(+ pending: dict[str, asyncio.Task],+ channel_id: str | None,+ session_id: str,+ event: dict[str, Any],+) -> None:+ request_id = str(event.get("request_id") or "")+ if not request_id:+ return+ existing = pending.pop(request_id, None)+ if existing is not None and not existing.done():+ existing.cancel()+ pending[request_id] = asyncio.create_task(+ _resend_ask_user_loop(channel_id, session_id, event)+ )+++def _cancel_ask_user_resends(pending: dict[str, asyncio.Task]) -> None:+ for task in pending.values():+ if not task.done():+ task.cancel()+ pending.clear()++def _team_processing_done_chunk(request_id: str,channel_id: str | None,@@ -1799,12 +1895,8 @@ async def process_team_message_stream(# 3. session 已初始化过 team runtime → False# 4. 否则 → True(首次请求,需要创建 team spec + stream)params = request.params if isinstance(getattr(request, "params", None), dict) else {}- from openjiuwen.core.session.interaction.interactive_input import InteractiveInput- is_control_continuation = (- isinstance(query, InteractiveInput)- and params.get("source") in {"permission_interrupt", "ask_user_interrupt"}- )+ is_control_continuation = is_team_control_continuation(request, query)has_active_waiters = team_manager.has_waiters(session_id)reuse_active_waiter = is_control_continuation and has_active_waitersis_first_request = (@@ -2411,6 +2503,9 @@ async def _consume_stream_with_query(received_chunks = 0first_model_output_at: float | None = Noneemitted_ask_user_request_ids: set[str] = set()+ # request_id -> resend task; armed when a chat.ask_user_question card is+ # broadcast, cancelled on any progress chunk or stream exit+ pending_ask_user_resends: dict[str, asyncio.Task] = {}team_stream: Any = None# Reset the team-events flag at the start of a new round so chat.final# can correctly determine whether the team is active.@@ -2466,6 +2561,10 @@ async def _consume_stream_with_query()async for chunk in team_stream:received_chunks += 1+ # Any progress chunk means the interaction was answered (or the+ # round moved on) — stop resending outstanding question cards.+ if pending_ask_user_resends and getattr(chunk, "type", None) in _TEAM_PROGRESS_CHUNK_TYPES:+ _cancel_ask_user_resends(pending_ask_user_resends)# First event of any kind from the runner — usually a framework# control event (team.runtime_ready and friends), not model output.# It marks how long team startup took before the stream came alive.@@ -2557,6 +2656,14 @@ async def _consume_stream_with_query(# 不存在的会话(见 relay-claw docs/architecture/# team-ask-user-question-lost-answer-analysis.md)。parsed.setdefault("session_id", session_id)+ # arm the resend watchdog so a lost or+ # unrendered card cannot deadlock the round silently.+ _arm_ask_user_resend(+ pending_ask_user_resends,+ channel_id,+ session_id,+ parsed,+ )if parsed.get("event_type") == "team.runtime_ready":ready_team_name = str(parsed.get("team_name") or team_spec.team_name)activation_kind = str(parsed.get("activation_kind") or "").strip()@@ -2706,6 +2813,8 @@ async def _consume_stream_with_query():break+ # Round over — no resends should outlive the stream loop.+ _cancel_ask_user_resends(pending_ask_user_resends)# If stream ended without any chunks, broadcast an error eventif received_chunks == 0:logger.warning(@@ -2730,6 +2839,7 @@ async def _consume_stream_with_query(received_chunks,)except asyncio.CancelledError:+ _cancel_ask_user_resends(pending_ask_user_resends)logger.info("[TeamHelpers] stream cancelled: channel_id=%s session_id=%s",_resolve_channel_id(channel_id),@@ -2737,6 +2847,7 @@ async def _consume_stream_with_query()raiseexcept Exception as exc:+ _cancel_ask_user_resends(pending_ask_user_resends)logger.error("[TeamHelpers] stream failed: channel_id=%s session_id=%s error=%s",_resolve_channel_id(channel_id),diff --git a/jiuwenswarm/server/utils/stream_utils.py b/jiuwenswarm/server/utils/stream_utils.pyindex 76350622c2..c991838035 100644--- a/jiuwenswarm/server/utils/stream_utils.py+++ b/jiuwenswarm/server/utils/stream_utils.py@@ -6,6 +6,7 @@ from __future__ import annotationsimport jsonimport logging+import uuidfrom typing import Anylogger = logging.getLogger(__name__)@@ -265,7 +266,16 @@ def _parse_typed_chunk(chunk: Any, _has_streamed_content: bool) -> dict[str, Anyif chunk_type == "controller_output" and payload is not None:interactions = _find_interaction_payloads(payload)if interactions:- return _parse_interaction_payload(interactions)+ parsed_event = _parse_interaction_payload(interactions)+ if parsed_event is not None:+ return parsed_event+ # interaction payloads were present but none+ # converted — previously this returned None silently and the+ # frontend never received the question.+ logger.warning(+ "[stream_utils] controller_output carried %d interaction payload(s) but none converted to a card",+ len(interactions),+ )inner_t = getattr(payload, "type", None)if inner_t is None and isinstance(payload, dict):inner_t = payload.get("type")@@ -294,6 +304,23 @@ def _parse_typed_chunk(chunk: Any, _has_streamed_content: bool) -> dict[str, Any"任务执行失败",)return {"event_type": "chat.error", "error": error}+ if inner_val == "task_interaction":+ # native-harness ask_user interrupts (deep-agent+ # task loop) surface as a bare task_interaction controller payload+ # without __interaction__ chunks reaching this stream. Parse the+ # embedded interrupt result; fall back to an awaiting-input card so+ # the frontend is never left waiting without an input affordance.+ parsed_event = parse_task_interaction_payload(payload)+ if parsed_event is not None:+ return parsed_event+ request_id_candidates = _collect_request_id_candidates(payload)+ fallback_rid = request_id_candidates[0] if request_id_candidates else ""+ logger.warning(+ "[stream_utils] task_interaction without parsable ask_user payload;"+ " emitting awaiting-input fallback request_id=%s",+ fallback_rid or "<generated>",+ )+ return _fallback_awaiting_input_card(fallback_rid)# Close the enum: do not stringify ControllerOutputPayload as visible text.if inner_val not in ("task_completion",@@ -622,6 +649,220 @@ def _find_interaction_payload(return matches[0] if matches else None+def _dump_model(obj: Any) -> Any:+ """Best-effort ``model_dump`` for pydantic objects, else the object."""+ if hasattr(obj, "model_dump"):+ try:+ return obj.model_dump(mode="python")+ except Exception:+ try:+ return obj.model_dump()+ except Exception:+ return obj+ return obj+++def _iter_ask_user_interrupt_values(+ obj: Any,+ *,+ _depth: int = 0,+ _seen: set[int] | None = None,+):+ """Yield dicts that look like ask_user interrupt values inside ``obj``.++ Native-harness ask_user interrupts (deep-agent task loop) embed the+ interrupt value somewhere inside the task-loop result carried by the+ ``task_interaction`` controller payload, e.g. a dict with+ ``tool_name == "ask_user"`` or a ToolCallInterruptRequest dump with+ ``payload_schema`` + ``questions``.+ """+ if obj is None or _depth > 10:+ return+ if _seen is None:+ _seen = set()+ obj_id = id(obj)+ if obj_id in _seen:+ return+ _seen.add(obj_id)++ if isinstance(obj, dict):+ tool_name = str(obj.get("tool_name") or "").strip()+ if tool_name == "ask_user" or (+ "payload_schema" in obj and "questions" in obj+ ):+ yield obj+ for value in obj.values():+ yield from _iter_ask_user_interrupt_values(+ value, _depth=_depth + 1, _seen=_seen+ )+ return++ if isinstance(obj, (list, tuple)):+ for value in obj:+ yield from _iter_ask_user_interrupt_values(+ value, _depth=_depth + 1, _seen=_seen+ )+ return++ dumped = _dump_model(obj)+ if dumped is not obj:+ yield from _iter_ask_user_interrupt_values(+ dumped, _depth=_depth + 1, _seen=_seen+ )+ return++ for attr_name in ("payload", "data", "value", "result", "state", "output"):+ if hasattr(obj, attr_name):+ yield from _iter_ask_user_interrupt_values(+ getattr(obj, attr_name), _depth=_depth + 1, _seen=_seen+ )+++def _collect_request_id_candidates(+ obj: Any,+ *,+ _depth: int = 0,+ _seen: set[int] | None = None,+) -> list[str]:+ """Collect plausible interaction request ids (tool_call_id et al)."""+ ids: list[str] = []+ if obj is None or _depth > 10:+ return ids+ if _seen is None:+ _seen = set()+ obj_id = id(obj)+ if obj_id in _seen:+ return ids+ _seen.add(obj_id)++ if isinstance(obj, dict):+ for key in ("tool_call_id", "request_id", "interrupt_id"):+ value = obj.get(key)+ if isinstance(value, str) and value.strip():+ ids.append(value.strip())+ interrupt_ids = obj.get("interrupt_ids")+ if isinstance(interrupt_ids, (list, tuple)):+ for value in interrupt_ids:+ if isinstance(value, str) and value.strip():+ ids.append(value.strip())+ for value in obj.values():+ ids.extend(+ _collect_request_id_candidates(value, _depth=_depth + 1, _seen=_seen)+ )+ return ids++ if isinstance(obj, (list, tuple)):+ for value in obj:+ ids.extend(+ _collect_request_id_candidates(value, _depth=_depth + 1, _seen=_seen)+ )+ return ids++ dumped = _dump_model(obj)+ if dumped is not obj:+ return _collect_request_id_candidates(dumped, _depth=_depth + 1, _seen=_seen)+ return ids+++def _ask_user_value_has_structured_questions(value_obj: dict[str, Any]) -> bool:+ """Whether the interrupt value carries a structured ``questions`` payload."""+ questions = value_obj.get("questions")+ if isinstance(questions, list) and questions:+ return True+ tool_args = value_obj.get("tool_args")+ if isinstance(tool_args, str):+ try:+ tool_args = json.loads(tool_args)+ except (ValueError, TypeError):+ tool_args = None+ return (+ isinstance(tool_args, dict)+ and isinstance(tool_args.get("questions"), list)+ and bool(tool_args["questions"])+ )+++def _resolve_task_interaction_request_id(+ value_obj: dict[str, Any],+ request_id_candidates: list[str],+) -> str:+ """Pick the request id that resumes the pending interrupt (tool_call_id)."""+ for source in (value_obj, value_obj.get("tool_args")):+ if not isinstance(source, dict):+ continue+ for key in ("tool_call_id", "request_id", "interrupt_id"):+ value = str(source.get(key) or "").strip()+ if value:+ return value+ return request_id_candidates[0] if request_id_candidates else ""+++def parse_task_interaction_payload(payload: Any) -> dict[str, Any] | None:+ """Build a frontend ask-user card from a TASK_INTERACTION controller payload.++ Rail-based interrupts already expose ``__interaction__`` payloads which+ ``_find_interaction_payloads`` picks up; this handles the remaining+ native-harness shapes so the ask_user question still reaches the frontend.+ Returns ``None`` when no ask_user value is embedded.+ """+ candidates = [+ value+ for value in _iter_ask_user_interrupt_values(payload)+ if isinstance(value, dict)+ ]+ if not candidates:+ return None++ request_id_candidates = _collect_request_id_candidates(payload)+ if not request_id_candidates:+ request_id_candidates = [f"task_interaction_{uuid.uuid4().hex[:12]}"]++ from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers import (+ convert_interactions_to_ask_user_question,+ )++ # Prefer structured question payloads, then plain query interrupts.+ candidates.sort(+ key=lambda v: 0 if _ask_user_value_has_structured_questions(v) else 1+ )+ for value_obj in candidates:+ request_id = _resolve_task_interaction_request_id(+ value_obj, request_id_candidates+ )+ try:+ card = convert_interactions_to_ask_user_question(+ [{"id": request_id, "value": value_obj}]+ )+ except Exception:+ logger.exception(+ "[stream_utils] failed to convert task_interaction value to ask_user card"+ )+ card = None+ if card is not None:+ return card+ return None+++def _fallback_awaiting_input_card(request_id: str) -> dict[str, Any]:+ """Build a generic awaiting-input card for unparsable task_interaction."""+ return {+ "event_type": "chat.ask_user_question",+ "request_id": request_id or f"task_interaction_{uuid.uuid4().hex[:12]}",+ "questions": [+ {+ "question": (+ "任务正在等待你的输入后才能继续,请直接回复;"+ "若此前的问题未显示,请重新描述你的需求。"+ ),+ "header": "Input required",+ "options": [],+ "multi_select": False,+ }+ ],+ "source": "task_interaction_fallback",+ }++def _parse_event_typed_chunk(chunk: Any) -> dict[str, Any]:"""Parse chunk with event_type attribute."""if isinstance(chunk, dict):diff --git a/tests/unit_tests/agentserver/test_request_scoped_office_claw_mcp.py b/tests/unit_tests/agentserver/test_request_scoped_office_claw_mcp.pyindex 210d13a3de..0f3888455a 100644--- a/tests/unit_tests/agentserver/test_request_scoped_office_claw_mcp.py+++ b/tests/unit_tests/agentserver/test_request_scoped_office_claw_mcp.py@@ -618,6 +618,150 @@ async def test_stream_request_binds_active_tool_allowlist() -> None:assert seen == {"allowed": True, "rejected_foreign": True}+def _team_answer_request(+ *,+ mode: str = "team",+ source: str = "ask_user_interrupt",+ request_id: str = "req-answer-1",+) -> AgentRequest:+ return AgentRequest(+ request_id=request_id,+ channel_id="officeclaw",+ session_id="session-456",+ params={+ "query": "",+ "mode": mode,+ "source": source,+ "status": "answered",+ "request_id": "call_ask_user_1",+ "answers": [+ {+ "question": "文件存放到哪个目录?",+ "selected_options": ["当前项目目录"],+ }+ ],+ "office_claw_mcp": _valid_config(),+ },+ )+++def _interactive_input_query() -> "InteractiveInput":+ from openjiuwen.core.session.interaction.interactive_input import InteractiveInput++ interactive_input = InteractiveInput()+ interactive_input.update(+ "call_ask_user_1",+ {"status": "answered", "answers": [{"selected_options": ["当前项目目录"]}]},+ )+ return interactive_input+++async def test_stream_team_control_continuation_skips_request_mcp() -> None:+ """team 模式 ask_user 作答不得注册 request-scoped MCP(会与暂停中的原始请求死锁)。"""+ parent = object.__new__(JiuWenSwarmDeepAdapter)+ parent._is_session_scoped_adapter = False+ chunk = AgentResponseChunk(request_id="req-answer-1", channel_id="officeclaw")++ class _Child:+ def __init__(self) -> None:+ self.register_request_scoped_office_claw_mcp = AsyncMock(+ side_effect=AssertionError("must not register for team answer delivery")+ )+ self.cleanup_request_scoped_office_claw_mcp = AsyncMock()++ async def process_message_stream_impl(self, request, inputs):+ yield chunk++ child = _Child()+ parent._get_or_create_session_adapter = AsyncMock(return_value=child)+ parent._evict_idle_session_adapters = AsyncMock()++ chunks = [+ item+ async for item in parent.process_message_stream_impl(+ _team_answer_request(),+ {"query": _interactive_input_query()},+ )+ ]++ assert chunks == [chunk]+ child.cleanup_request_scoped_office_claw_mcp.assert_awaited_once_with(None)+++async def test_unary_team_control_continuation_skips_request_mcp() -> None:+ parent = object.__new__(JiuWenSwarmDeepAdapter)+ parent._is_session_scoped_adapter = False+ response = AgentResponse(request_id="req-answer-1", channel_id="officeclaw")+ child = SimpleNamespace(+ register_request_scoped_office_claw_mcp=AsyncMock(+ side_effect=AssertionError("must not register for team answer delivery")+ ),+ process_message_impl=AsyncMock(return_value=response),+ cleanup_request_scoped_office_claw_mcp=AsyncMock(),+ )+ parent._get_or_create_session_adapter = AsyncMock(return_value=child)+ parent._evict_idle_session_adapters = AsyncMock()++ result = await parent.process_message_impl(+ _team_answer_request(),+ {"query": _interactive_input_query()},+ )++ assert result is response+ child.cleanup_request_scoped_office_claw_mcp.assert_awaited_once_with(None)+++async def test_agent_mode_answer_still_registers_request_mcp() -> None:+ """agent 模式的作答续跑仍需自行注册(原始请求已结束并释放注册)。"""+ parent = object.__new__(JiuWenSwarmDeepAdapter)+ parent._is_session_scoped_adapter = False+ registration = OfficeClawMcpRegistration("req-answer-1", ("tool-id",), ("tool",))+ response = AgentResponse(request_id="req-answer-1", channel_id="officeclaw")+ child = SimpleNamespace(+ register_request_scoped_office_claw_mcp=AsyncMock(return_value=registration),+ process_message_impl=AsyncMock(return_value=response),+ cleanup_request_scoped_office_claw_mcp=AsyncMock(),+ )+ parent._get_or_create_session_adapter = AsyncMock(return_value=child)+ parent._evict_idle_session_adapters = AsyncMock()++ result = await parent.process_message_impl(+ _team_answer_request(mode="agent"),+ {"query": _interactive_input_query()},+ )++ assert result is response+ child.register_request_scoped_office_claw_mcp.assert_awaited_once()+ child.cleanup_request_scoped_office_claw_mcp.assert_awaited_once_with(registration)+++async def test_team_normal_followup_still_registers_request_mcp() -> None:+ """team 模式普通文本消息(非作答投递)仍需注册。"""+ parent = object.__new__(JiuWenSwarmDeepAdapter)+ parent._is_session_scoped_adapter = False+ registration = OfficeClawMcpRegistration("req-follow-1", ("tool-id",), ("tool",))+ response = AgentResponse(request_id="req-follow-1", channel_id="officeclaw")+ child = SimpleNamespace(+ register_request_scoped_office_claw_mcp=AsyncMock(return_value=registration),+ process_message_impl=AsyncMock(return_value=response),+ cleanup_request_scoped_office_claw_mcp=AsyncMock(),+ )+ parent._get_or_create_session_adapter = AsyncMock(return_value=child)+ parent._evict_idle_session_adapters = AsyncMock()++ request = _request(_valid_config(), request_id="req-follow-1")+ request.params["mode"] = "team"+ result = await parent.process_message_impl(request, {"query": "继续上一步"})++ assert result is response+ child.register_request_scoped_office_claw_mcp.assert_awaited_once()+ child.cleanup_request_scoped_office_claw_mcp.assert_awaited_once_with(registration)++def test_carrier_stores_on_ability_manager_and_rebinds() -> None:"""The allowlist lives on the shared ability_manager, visible to either agent."""tool_id = "office-claw-request-aaa.office-claw.office_claw_multi_mention"diff --git a/tests/unit_tests/agentserver/test_task_interaction_ask_user_stream.py b/tests/unit_tests/agentserver/test_task_interaction_ask_user_stream.pynew file mode 100644index 0000000000..5d842248f7--- /dev/null+++ b/tests/unit_tests/agentserver/test_task_interaction_ask_user_stream.py@@ -0,0 +1,261 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""裸 ``task_interaction`` controller_output → 前端提问卡 的解析测试。++背景:原生 harness 的 ask_user 中断以裸 task_interaction controller_output+到达解析层,stream_utils 此前仅识别 ``__interaction__`` 载荷,该 chunk 被静默+丢弃——前端既收不到提问卡也收不到 chat.final。现需识别嵌入的 ask_user+中断值并转换为 ``chat.ask_user_question``,无法解析时下发兜底输入卡。+"""++from __future__ import annotations++from types import SimpleNamespace++from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (+ JiuWenSwarmDeepAdapter,+)+from jiuwenswarm.server.utils import stream_utils+from jiuwenswarm.server.utils.stream_utils import parse_stream_chunk+++def _ask_user_value(**overrides) -> dict:+ value = {+ "tool_name": "ask_user",+ "tool_call_id": "call_ask_user_1",+ "questions": [+ {+ "question": "文件存放到哪个目录?",+ "header": "Location",+ "options": [],+ "multi_select": False,+ }+ ],+ }+ value.update(overrides)+ return value+++def _task_interaction_chunk(payload: dict) -> SimpleNamespace:+ return SimpleNamespace(type="controller_output", payload=payload)+++def test_parse_task_interaction_ask_user_card_from_bare_controller_output() -> None:+ """裸 task_interaction(无 __interaction__ 标记)必须转出提问卡,不再被丢弃。"""+ chunk = _task_interaction_chunk(+ {"type": "task_interaction", "data": [_ask_user_value()]}+ )++ parsed = parse_stream_chunk(chunk)++ assert parsed is not None+ assert parsed["event_type"] == "chat.ask_user_question"+ assert parsed["request_id"] == "call_ask_user_1"+ assert parsed["source"] == "ask_user_interrupt"+ assert parsed["questions"][0]["question"] == "文件存放到哪个目录?"+++def test_parse_task_interaction_ask_user_card_appends_other_option() -> None:+ """带选项的问题转换为卡片时追加 __other__ 自定义输入项。"""+ value = _ask_user_value(+ questions=[+ {+ "question": "选择目录",+ "options": [+ {"label": "当前项目目录", "description": ""},+ {"label": "桌面", "description": ""},+ ],+ }+ ]+ )+ chunk = _task_interaction_chunk({"type": "task_interaction", "data": [value]})++ parsed = parse_stream_chunk(chunk)++ assert parsed is not None+ options = parsed["questions"][0]["options"]+ assert len(options) == 3+ assert options[-1]["label"] == "Other"+++def test_parse_task_interaction_from_pydantic_model_dump() -> None:+ """ToolCallInterruptRequest 等模型对象经 model_dump 展开后仍可识别。"""++ class _FakeInterruptRequest:+ def __init__(self, dump: dict) -> None:+ self._dump = dump++ def model_dump(self, mode: str = "python") -> dict:+ return dict(self._dump)++ chunk = _task_interaction_chunk(+ {+ "type": "task_interaction",+ "result": _FakeInterruptRequest(+ _ask_user_value(tool_call_id="call_dump_1")+ ),+ }+ )++ parsed = parse_stream_chunk(chunk)++ assert parsed is not None+ assert parsed["event_type"] == "chat.ask_user_question"+ assert parsed["request_id"] == "call_dump_1"+++def test_parse_task_interaction_questions_in_tool_args_json_string() -> None:+ """questions 藏在 tool_args JSON 字符串(StructuredAskUserRail 形态)也可解析。"""+ value = {+ "tool_name": "ask_user",+ "tool_call_id": "call_json",+ "tool_args": '{"questions": [{"question": "目录?"}]}',+ }+ chunk = _task_interaction_chunk({"type": "task_interaction", "data": [value]})++ parsed = parse_stream_chunk(chunk)++ assert parsed is not None+ assert parsed["request_id"] == "call_json"+ assert parsed["questions"][0]["question"] == "目录?"+++def test_parse_task_interaction_prefers_structured_questions_over_plain() -> None:+ """结构化 questions 候选优先于 plain query,即使 plain 排在前面。"""+ plain = {+ "tool_name": "ask_user",+ "tool_call_id": "call_plain",+ "message": "直接回答问题",+ }+ structured = _ask_user_value(tool_call_id="call_struct")+ chunk = _task_interaction_chunk(+ {"type": "task_interaction", "data": [plain, structured]}+ )++ parsed = parse_stream_chunk(chunk)++ assert parsed is not None+ assert parsed["request_id"] == "call_struct"+ assert parsed["questions"][0]["question"] == "文件存放到哪个目录?"+++def test_parse_task_interaction_request_id_prefers_value_over_candidates() -> None:+ """request_id 取中断值自身的 tool_call_id,而非外层收集到的候选。"""+ payload = {+ "type": "task_interaction",+ "tool_call_id": "outer_candidate",+ "data": [_ask_user_value(tool_call_id="inner_call")],+ }++ parsed = stream_utils.parse_task_interaction_payload(payload)++ assert parsed is not None+ assert parsed["request_id"] == "inner_call"+++def test_parse_task_interaction_request_id_falls_back_to_collected_candidates() -> None:+ """中断值无 id 时回退到外层收集的候选(如 data 兄弟节点的 tool_call_id)。"""+ value = {+ k: v for k, v in _ask_user_value().items() if k != "tool_call_id"+ }+ payload = {+ "type": "task_interaction",+ "data": [value, {"tool_call_id": "sibling_call"}],+ }++ parsed = stream_utils.parse_task_interaction_payload(payload)++ assert parsed is not None+ assert parsed["request_id"] == "sibling_call"+++def test_parse_task_interaction_without_ask_user_emits_fallback_card() -> None:+ """无法解析出 ask_user 值时必须下发兜底输入卡,前端不能没有输入入口。"""+ chunk = _task_interaction_chunk(+ {"type": "task_interaction", "data": [{"tool_call_id": "call_x", "status": "pending"}]}+ )++ parsed = parse_stream_chunk(chunk)++ assert parsed is not None+ assert parsed["event_type"] == "chat.ask_user_question"+ assert parsed["request_id"] == "call_x"+ assert parsed["source"] == "task_interaction_fallback"+ assert parsed["questions"][0]["question"]+ assert parsed["questions"][0]["options"] == []+ assert parsed["questions"][0]["multi_select"] is False+++def test_fallback_card_generates_request_id_when_missing() -> None:+ card = stream_utils._fallback_awaiting_input_card("")+ assert card["request_id"].startswith("task_interaction_")++ card = stream_utils._fallback_awaiting_input_card("keep_me")+ assert card["request_id"] == "keep_me"+++def test_parse_task_interaction_falls_through_unconverted_interaction_payloads() -> None:+ """__interaction__ 载荷存在但不可转换时,不得静默丢弃——落到+ task_interaction 分支继续解析嵌入的 ask_user 值。"""+ chunk = _task_interaction_chunk(+ {+ "type": "task_interaction",+ "data": [+ {"type": "__interaction__", "payload": _ask_user_value()}+ ],+ }+ )++ parsed = parse_stream_chunk(chunk)++ assert parsed is not None+ assert parsed["event_type"] == "chat.ask_user_question"+ assert parsed["request_id"] == "call_ask_user_1"+++def test_collect_request_id_candidates_gathers_ids_from_shapes() -> None:+ payload = {+ "tool_call_id": "outer_call",+ "interrupt_ids": ["int_1", "int_2"],+ "data": [+ {"request_id": "inner_req"},+ {"interrupt_id": "inner_int"},+ ],+ }++ ids = stream_utils._collect_request_id_candidates(payload)++ assert ids == ["outer_call", "int_1", "int_2", "inner_req", "inner_int"]+++def test_iter_ask_user_interrupt_values_terminates_on_cycles() -> None:+ cyclic: list = []+ cyclic.append(cyclic)+ container = {"tool_name": "ask_user", "questions": [], "nested": cyclic}++ values = list(stream_utils._iter_ask_user_interrupt_values(container))++ assert values == [container]+++def test_interface_deep_parse_stream_chunk_builds_task_interaction_card() -> None:+ """interface_deep 镜像解析:task_interaction 同样转出提问卡。"""+ chunk = _task_interaction_chunk(+ {"type": "task_interaction", "data": [_ask_user_value()]}+ )++ parsed = JiuWenSwarmDeepAdapter._parse_stream_chunk(chunk)++ assert parsed is not None+ assert parsed["event_type"] == "chat.ask_user_question"+ assert parsed["request_id"] == "call_ask_user_1"+++def test_interface_deep_parse_stream_chunk_unparsable_task_interaction_drops() -> None:+ """interface_deep 镜像解析:不可解析的 task_interaction 归为控制面元数据+ (返回 None),兜底卡由外层 stream_utils 负责。"""+ chunk = _task_interaction_chunk(+ {"type": "task_interaction", "data": [{"status": "pending"}]}+ )++ assert JiuWenSwarmDeepAdapter._parse_stream_chunk(chunk) is Nonediff --git a/tests/unit_tests/agentserver/test_team_ask_user_resend.py b/tests/unit_tests/agentserver/test_team_ask_user_resend.pynew file mode 100644index 0000000000..1bbe81ac52--- /dev/null+++ b/tests/unit_tests/agentserver/test_team_ask_user_resend.py@@ -0,0 +1,300 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""team 模式 ask_user 链路的看门狗与控制续接判定测试。++覆盖两块防御逻辑:+1. 提问卡重发看门狗——卡片投递丢失时周期重发,任何进度 chunk 或流结束+ 都必须停掉重发,不能让任务泄漏到轮次之外。+2. ``is_team_control_continuation`` 谓词——识别 ask_user/permission 作答的+ 控制续接请求(此类请求跳过 request-scoped MCP 注册,避免与被中断的+ 原始请求死锁)。+"""++from __future__ import annotations++import asyncio+import contextlib+from types import SimpleNamespace++import pytest++from jiuwenswarm.server.runtime.agent_adapter import team_helpers+++def _interactive_input():+ from openjiuwen.core.session.interaction.interactive_input import InteractiveInput++ interactive_input = InteractiveInput()+ interactive_input.update(+ "call_ask_user_1",+ {"status": "answered", "answers": [{"selected_options": ["当前项目目录"]}]},+ )+ return interactive_input+++def _ask_user_card(request_id: str = "call_ask_user_1") -> dict:+ return {+ "event_type": "chat.ask_user_question",+ "request_id": request_id,+ "questions": [+ {+ "question": "文件存放到哪个目录?",+ "header": "Question",+ "options": [],+ "multi_select": False,+ }+ ],+ "source": "ask_user_interrupt",+ }+++# --- is_team_control_continuation 谓词 ---++[email protected]("mode", ["team", "team.plan", "code.team"])+def test_is_team_control_continuation_accepts_team_modes(mode: str) -> None:+ request = SimpleNamespace(params={"mode": mode, "source": "ask_user_interrupt"})+ assert team_helpers.is_team_control_continuation(request, _interactive_input()) is True+++def test_is_team_control_continuation_accepts_permission_source() -> None:+ request = SimpleNamespace(params={"mode": "team", "source": "permission_interrupt"})+ assert team_helpers.is_team_control_continuation(request, _interactive_input()) is True+++def test_is_team_control_continuation_rejects_agent_mode() -> None:+ request = SimpleNamespace(params={"mode": "agent", "source": "ask_user_interrupt"})+ assert team_helpers.is_team_control_continuation(request, _interactive_input()) is False+++def test_is_team_control_continuation_defaults_missing_mode_to_agent() -> None:+ request = SimpleNamespace(params={"source": "ask_user_interrupt"})+ assert team_helpers.is_team_control_continuation(request, _interactive_input()) is False+++def test_is_team_control_continuation_rejects_other_sources() -> None:+ request = SimpleNamespace(params={"mode": "team", "source": "chat"})+ assert team_helpers.is_team_control_continuation(request, _interactive_input()) is False+++def test_is_team_control_continuation_requires_interactive_input_query() -> None:+ request = SimpleNamespace(params={"mode": "team", "source": "ask_user_interrupt"})+ assert team_helpers.is_team_control_continuation(request, "普通文本消息") is False+++def test_is_team_control_continuation_tolerates_non_dict_params() -> None:+ request = SimpleNamespace(params=None)+ assert team_helpers.is_team_control_continuation(request, _interactive_input()) is False+++# --- 重发看门狗单元 ---+++def test_progress_chunk_types_cover_progress_but_not_usage() -> None:+ # llm_usage 伴随 interaction chunk 本身到达,不算轮次推进,+ # 不得取消看门狗。+ assert "llm_usage" not in team_helpers._TEAM_PROGRESS_CHUNK_TYPES+ for chunk_type in (+ "llm_output",+ "llm_reasoning",+ "content_chunk",+ "tool_call",+ "tool_update",+ "controller_output",+ "answer",+ "__interaction__",+ "message",+ "team.runtime_ready",+ "team.completed",+ ):+ assert chunk_type in team_helpers._TEAM_PROGRESS_CHUNK_TYPES+++async def test_resend_ask_user_loop_broadcasts_copies_up_to_max(monkeypatch) -> None:+ broadcasts: list[dict] = []+ monkeypatch.setattr(+ team_helpers, "_broadcast_event", lambda c, s, e: broadcasts.append(e)+ )+ monkeypatch.setattr(team_helpers, "_ASK_USER_RESEND_INTERVAL_S", 0.01)+ monkeypatch.setattr(team_helpers, "_ASK_USER_RESEND_MAX", 3)+ event = _ask_user_card("rid-1")++ await team_helpers._resend_ask_user_loop("web", "sess", event)++ assert len(broadcasts) == 3+ assert all(item is not event for item in broadcasts)+ assert all(item["request_id"] == "rid-1" for item in broadcasts)+++async def test_resend_ask_user_loop_cancelled_stops_broadcasting(monkeypatch) -> None:+ broadcasts: list[dict] = []+ monkeypatch.setattr(+ team_helpers, "_broadcast_event", lambda c, s, e: broadcasts.append(e)+ )+ monkeypatch.setattr(team_helpers, "_ASK_USER_RESEND_INTERVAL_S", 0.02)+ monkeypatch.setattr(team_helpers, "_ASK_USER_RESEND_MAX", 10)++ task = asyncio.create_task(+ team_helpers._resend_ask_user_loop("web", "sess", _ask_user_card("rid-1"))+ )+ await asyncio.sleep(0.05)+ task.cancel()+ with contextlib.suppress(asyncio.CancelledError):+ await task++ count = len(broadcasts)+ assert 1 <= count <= 3+ await asyncio.sleep(0.1)+ assert len(broadcasts) == count+++async def test_arm_ask_user_resend_replaces_existing_and_cancel_clears(monkeypatch) -> None:+ started: list[str] = []++ async def _fake_loop(channel_id, session_id, event) -> None:+ started.append(str(event.get("request_id")))+ await asyncio.Event().wait()++ monkeypatch.setattr(team_helpers, "_resend_ask_user_loop", _fake_loop)+ pending: dict = {}++ team_helpers._arm_ask_user_resend(pending, "web", "sess", _ask_user_card("rid-1"))+ first = pending["rid-1"]+ await asyncio.sleep(0.01)+ assert started == ["rid-1"]++ team_helpers._arm_ask_user_resend(pending, "web", "sess", _ask_user_card("rid-1"))+ second = pending["rid-1"]+ await asyncio.sleep(0.01)+ assert first.cancelled()+ assert second is not first+ assert started == ["rid-1", "rid-1"]++ team_helpers._cancel_ask_user_resends(pending)+ await asyncio.sleep(0.01)+ assert pending == {}+ assert second.cancelled()+++async def test_arm_ask_user_resend_skips_without_request_id(monkeypatch) -> None:+ async def _fake_loop(channel_id, session_id, event) -> None:+ raise AssertionError("must not start without request_id")++ monkeypatch.setattr(team_helpers, "_resend_ask_user_loop", _fake_loop)+ pending: dict = {}++ team_helpers._arm_ask_user_resend(+ pending, "web", "sess", _ask_user_card("")+ )++ assert pending == {}+++# --- _consume_stream_with_query 集成 ---+++class _ResendTestManager:+ def __init__(self) -> None:+ self._seen: dict[str, bool] = {}++ def reset_seen_team_events(self, session_id: str) -> None:+ self._seen.pop(session_id, None)++ def reset_round_complete(self, session_id: str) -> None:+ pass++ def reset_workflow_completed(self, session_id: str) -> None:+ pass++ def get_monitor_handler(self, session_id: str):+ return None++ def clear_pending_runtime(self, session_id: str) -> None:+ pass++ def clear_active_runtime(self, session_id: str) -> None:+ pass++ def pop_stream_task(self, session_id: str):+ pass+++async def _run_consume(monkeypatch, stream_factory, parse_fn, *, session_id: str = "sess-resend") -> list[dict]:+ broadcasts: list[dict] = []+ monkeypatch.setattr(+ team_helpers, "_broadcast_event", lambda c, s, e: broadcasts.append(e)+ )+ monkeypatch.setattr(team_helpers, "_ASK_USER_RESEND_INTERVAL_S", 0.05)+ monkeypatch.setattr(team_helpers, "_ASK_USER_RESEND_MAX", 5)+ monkeypatch.setattr(team_helpers, "_run_agent_team_streaming", stream_factory)+ monkeypatch.setattr(team_helpers, "get_team_manager", lambda channel_id: _ResendTestManager())+ monkeypatch.setattr(team_helpers, "parse_stream_chunk", parse_fn)++ await team_helpers._consume_stream_with_query(+ "web",+ session_id,+ SimpleNamespace(team_name="spec-team"),+ "生成一份包含杭州天气的文件",+ round_id=1,+ )+ return broadcasts+++async def test_consume_stream_arms_resend_and_cancels_on_progress(monkeypatch) -> None:+ """提问卡广播后进入静默期→看门狗重发;进度 chunk 到达→停止重发。"""+ ask_chunk = SimpleNamespace(type="controller_output", payload={}, role=None)+ progress_chunk = SimpleNamespace(+ type="llm_output", payload={"content": "继续"}, role=None+ )++ def _fake_parse(chunk):+ if chunk is ask_chunk:+ return _ask_user_card()+ return {"event_type": "chat.delta", "content": "继续"}++ async def _fake_stream(**kwargs):+ yield ask_chunk+ await asyncio.sleep(0.12) # 静默期:两次重发(0.05/0.10)已发,第三次未到+ yield progress_chunk++ broadcasts = await _run_consume(monkeypatch, _fake_stream, _fake_parse)++ ask_events = [e for e in broadcasts if e.get("event_type") == "chat.ask_user_question"]+ # 原始卡片 1 张 + 静默期内重发 2 次;进度 chunk 到达后取消,重发 3-5 不再发出+ assert len(ask_events) == 3+ assert all(e["request_id"] == "call_ask_user_1" for e in ask_events)+ assert all(e.get("session_id") == "sess-resend" for e in ask_events)++ deltas = [e for e in broadcasts if e.get("event_type") == "chat.delta"]+ assert len(deltas) == 1+ assert broadcasts.index(deltas[0]) > broadcasts.index(ask_events[-1])++ # 轮次结束后不得再有重发漏出+ await asyncio.sleep(0.25)+ assert len(ask_events) == 3+++async def test_consume_stream_cancels_resends_on_stream_end(monkeypatch) -> None:+ """流结束(用户取消/团队收尾)时,未作答卡片的重发任务必须一并取消。"""+ ask_chunk = SimpleNamespace(type="controller_output", payload={}, role=None)++ def _fake_parse(chunk):+ return _ask_user_card()++ async def _fake_stream(**kwargs):+ yield ask_chunk++ broadcasts = await _run_consume(monkeypatch, _fake_stream, _fake_parse)++ ask_events = [e for e in broadcasts if e.get("event_type") == "chat.ask_user_question"]+ assert len(ask_events) == 1++ await asyncio.sleep(0.2)+ ask_events = [e for e in broadcasts if e.get("event_type") == "chat.ask_user_question"]+ assert len(ask_events) == 1