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(skill_turbo): ask_user 卡片双弹修复:回退强制 emit(2e41c076)改为 harness __interaction__ 单路发卡;HITL suppress 清除不连 hitl_pending_stream;同外层调用连续中断卡片 {id}#{n} 序号区分;回退 tcid 混入 request_id(508137309)
d30029696b406438e0aaf
diff --git a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.pyindex b71b717ae4..31e7138e18 100644--- a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py@@ -1379,15 +1379,10 @@ class JiuSwarmStreamEventRail(DeepAgentRail):_skill_turbo_tic.tool_call.id if _skill_turbo_tic.tool_call else "?",ctx.inputs.tool_call.id if isinstance(ctx.inputs, ToolCallInputs) else "?",)- # 主路径必须主动 emit:外层 tool_name 是 skill_acceleration_exec,- # _emit_ask_user_question_if_interrupted 不会命中;也不能只依赖- # harness __interaction__(同 tool_call_id 二次 HITL 时常哑火)。- await self._emit_skill_turbo_ask_user_question(- session,- outer_tool_call=ctx.inputs.tool_call,- skill_turbo_tic=_skill_turbo_tic,- )- return # 跳过 _emit_tool_result;ask_user 已在上方强制发出+ # 卡片由 harness __interaction__ 转换统一发出(外层+ # tool_call_id,harness 恢复按同一 id 对齐);此处不再主动+ # emit,避免同一次中断发出两张 ask_user 卡片。+ return # 跳过 _emit_tool_result:中断态无结果可发except Exception:logger.debug("[StreamEventRail] skill_turbo HITL rewrite failed",@@ -1531,62 +1526,6 @@ class JiuSwarmStreamEventRail(DeepAgentRail):except Exception:logger.debug("tool_result emit failed", exc_info=True)- @staticmethod- async def _emit_skill_turbo_ask_user_question(- session: Session,- *,- outer_tool_call: Any,- skill_turbo_tic: Any,- ) -> None:- """Emit chat.ask_user_question for SkillTurbo nested ask_user HITL.-- request_id is the inner ask_user tool_call.id (unique per ask_user),- NOT the outer skill_acceleration_exec id. This ensures sequential- ask_user cards within the same skill_acceleration_exec have distinct- request_ids, so the frontend shows each as a separate card.-- SkillTurbo resume (_resume_user_input_from_raw) extracts the user's- answer via ``next(iter(user_inputs.values()))`` — it ignores the key,- so using the inner ask_user id does not break resume.- """- inner_tc = getattr(skill_turbo_tic, "tool_call", None)- payload = _ask_user_question_payload_from_interrupt(- inner_tc or outer_tool_call,- skill_turbo_tic,- )- if not payload:- logger.debug(- "[StreamEventRail] SkillTurbo HITL ask_user payload unavailable"- )- return- inner_request_id = str(payload.get("request_id") or "").strip()- if not inner_request_id:- logger.warning(- "[StreamEventRail] SkillTurbo HITL ask_user skipped: "- "inner ask_user request_id unavailable; harness_id=%s",- getattr(outer_tool_call, "id", ""),- )- return- try:- await session.write_stream(- OutputSchema(- type="chat.ask_user_question",- index=0,- payload=payload,- )- )- logger.info(- "[StreamEventRail] SkillTurbo HITL emitted chat.ask_user_question "- "request_id=%s harness_id=%s",- inner_request_id,- getattr(outer_tool_call, "id", ""),- )- except Exception:- logger.debug(- "[StreamEventRail] SkillTurbo HITL ask_user emit failed",- exc_info=True,- )-@staticmethodasync def _emit_ask_user_question_if_interrupted(session: Session,diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex a0a8373335..defc60b423 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -1545,6 +1545,12 @@ class JiuWenSwarm:)if answers or is_explicit_ask_user_response:request_id = params.get("request_id", "")+ # ask_user 卡片序号后缀({call_id}#{n},区分同一外层调用的第 n 次+ # 中断)在此剥掉,恢复 harness 原始 tool_call id 用于对齐+ if isinstance(request_id, str):+ _m = re.search(r"^(?P<base>.+)#\d+$", request_id.strip())+ if _m and _m.group("base").strip():+ request_id = _m.group("base").strip()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 ""interactive_input = self._build_interactive_input_from_answers(diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 4b22759dfc..3c0651e1b4 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -200,6 +200,15 @@ def _is_outer_react_tool_result(payload: Any) -> bool:return True+def _ask_user_questions_key(payload: dict) -> str:+ """ask_user 卡片的 questions 规范化键,用于判定同一中断的重复通道。"""+ try:+ questions = payload.get("questions") or []+ return json.dumps(questions, sort_keys=True, default=str)+ except (TypeError, ValueError):+ return repr(payload.get("questions"))++_DEEPRESEARCH_REWRITE_REPLAY_STATE_KEY = "deepresearch_rewrite_fast_path_replays"_DEEPRESEARCH_REWRITE_REPLAY_SCHEMA_VERSION = 1_DEEPRESEARCH_REWRITE_REPLAY_MAX_ENTRIES = 32@@ -2116,6 +2125,9 @@ class JiuWenSwarmDeepAdapter:# trust 判定使用;由白名单同步/热刷新/_refresh_skill_identity 维护。self._prebuilt_skills: set[str] = set()self._stream_event_rail: JiuSwarmStreamEventRail | None = None+ # ask_user 卡片序号:同一外层 tool_call_id 的第 N 次中断共用同一 id,+ # 卡片 request_id 以 {id}#{n} 区分(跨请求存续,见 should_skip_duplicate_ask_user)+ self._ask_user_card_seq: dict[str, int] = {}self._task_execution_rail: TaskExecutionRail | None = Noneself._skill_turbo_prompt_rail: Any = Noneself._skill_turbo_delivery_summary_rail: Any = None@@ -16911,6 +16923,7 @@ class JiuWenSwarmDeepAdapter:"total_cost": 0.0,}emitted_ask_user_request_ids: set[str] = set()+ emitted_ask_user_questions: dict[str, str] = {}accounted_deepresearch_usage_ids: set[str] = set()approved_plan_exit_tool_call_id = self._approved_plan_exit_resume_tool_call_id(request.params@@ -16918,17 +16931,11 @@ class JiuWenSwarmDeepAdapter:saw_approved_plan_exit_result = Falsedef should_skip_duplicate_ask_user(parsed: dict | None) -> bool:- if not isinstance(parsed, dict):- return False- if parsed.get("event_type") != "chat.ask_user_question":- return False- request_id = str(parsed.get("request_id") or "").strip()- if not request_id:- return False- if request_id in emitted_ask_user_request_ids:- return True- emitted_ask_user_request_ids.add(request_id)- return False+ return self._dedupe_ask_user_card(+ parsed,+ emitted_ask_user_request_ids,+ emitted_ask_user_questions,+ )first_byte_marked = Falsefirst_answer_marked = False@@ -17493,17 +17500,15 @@ class JiuWenSwarmDeepAdapter:# After ask_user, skip trailing metadata until a real resume# chunk arrives (in-place HITL). Unknown types default to clear# so new SDK frames cannot re-hang the stream.- if suppress_stream_after_hitl:- if self._is_hitl_suppress_noise_chunk(chunk):- continue- suppress_stream_after_hitl = False- hitl_pending_stream = False- logger.info(- "[JiuWenSwarmDeepAdapter] HITL suppress cleared on "- "runner resume: request_id=%s chunk_type=%s",- rid,- getattr(chunk, "type", None) or type(chunk).__name__,- )+ # Only suppress is cleared (resume forwarding); hitl_pending_stream+ # stays True to drive the chat.invocation_paused end-frame.+ suppress_stream_after_hitl, _skip = self._apply_hitl_suppress_clear(+ chunk,+ suppress_stream_after_hitl=suppress_stream_after_hitl,+ request_id=rid,+ )+ if _skip:+ continue# First chunk handed back by the runner: records the time to# first token for this round.if not first_chunk_seen:@@ -17866,7 +17871,11 @@ class JiuWenSwarmDeepAdapter:)emitted_chat_error = True- if accumulated_text and not hitl_pending_stream:+ # 守卫用 suppress_stream_after_hitl(当前是否处于 HITL 抑制中):+ # ask_user 暂停中为 True 跳过;in-place 续跑后为 False 放行(此时+ # 轮次已正常完成/取消,flush 与合成 final 必须发出,否则前端悬挂)。+ # hitl_pending_stream 只反映"本轮出过 ask_user 卡片",不随续跑复位。+ if accumulated_text and not suppress_stream_after_hitl:# Same rule as _adapt_goal_intermediate_final: demote host# flush only when the flushed text belonged to a goal round.if self._should_demote_goal_intermediate_final():@@ -17887,7 +17896,7 @@ class JiuWenSwarmDeepAdapter:payload=note_chat_payload(flush_payload),is_complete=False,)- if accumulated_reasoning and not hitl_pending_stream:+ if accumulated_reasoning and not suppress_stream_after_hitl:yield AgentResponseChunk(request_id=rid,channel_id=cid,@@ -17898,9 +17907,11 @@ class JiuWenSwarmDeepAdapter:# pause→clear (and similar): round cancelled, iterator ends without# a model chat.final. Synthesize a real final so the frontend can# stopStreaming; do not demote.- # HITL 暂停时跳过合成 final:由循环后的 chat.invocation_paused 终结帧- # 收尾,避免 relayclaw sidecar 提前关闭 FrameQueue 导致 recoverable_pause 丢失。- if not hitl_pending_stream and self._should_emit_stream_end_chat_final(+ # HITL 暂停中(suppress 未清除)跳过合成 final:由循环后的+ # chat.invocation_paused 终结帧收尾,避免 relayclaw sidecar 提前关闭+ # FrameQueue 导致 recoverable_pause 丢失;in-place 续跑后 suppress 已+ # 清除,轮次完成/取消时必须合成 final 让前端 stopStreaming。+ if not suppress_stream_after_hitl and self._should_emit_stream_end_chat_final(had_assistant_output=had_assistant_output,emitted_terminal_chat_final=emitted_terminal_chat_final,):@@ -18211,25 +18222,93 @@ class JiuWenSwarmDeepAdapter:"""HITL 暂停判定:payload 是否为 ask_user 卡片事件。"""return isinstance(payload, dict) and payload.get("event_type") == "chat.ask_user_question"+ def _dedupe_ask_user_card(+ self,+ parsed: dict | None,+ emitted_request_ids: set[str],+ emitted_questions: dict[str, str],+ ) -> bool:+ """ask_user 卡片去重与序号区分;返回 True 表示跳过本张卡。++ - 同一中断的多通道重复(独立 ``__interaction__`` 与 controller 嵌套):+ 同 call id + 同 questions → 跳过。+ - 同一外层 skill_acceleration_exec 内的第 N 次中断共用同一 call id:+ questions 不同 → 卡片 request_id 改为 ``{id}#{n}`` 放行(前端才显示为+ 独立卡片);作答回传时由 _build_interactive_input_from_answers 入口+ 剥掉后缀对齐 harness 原始 id。序号计数在 adapter 实例上跨请求存续。+ """+ if not isinstance(parsed, dict):+ return False+ if parsed.get("event_type") != "chat.ask_user_question":+ return False+ request_id = str(parsed.get("request_id") or "").strip()+ if not request_id:+ return False+ questions_key = _ask_user_questions_key(parsed)+ if any(+ (fid == request_id or fid.startswith(f"{request_id}#"))+ and qk == questions_key+ for fid, qk in emitted_questions.items()+ ):+ return True+ seq = self._ask_user_card_seq.get(request_id, 0)+ final_id = request_id if seq == 0 else f"{request_id}#{seq + 1}"+ self._ask_user_card_seq[request_id] = seq + 1+ emitted_request_ids.add(final_id)+ emitted_questions[final_id] = questions_key+ if final_id != request_id:+ parsed["request_id"] = final_id+ return False+@staticmethoddef _is_hitl_suppress_noise_chunk(chunk: Any) -> bool:"""Metadata that may follow ask_user before the stream truly pauses.These must not clear suppress / hitl_pending; any other chunk means the- runner resumed in-place and outbound must resume. Includes- ``__interaction__`` / non-fatal ``controller_output`` tails that arrive- with the ask_user card itself (not a user-answer resume).+ runner resumed in-place and outbound must resume. Includes non-fatal+ ``controller_output`` tails that arrive with the ask_user card itself+ (not a user-answer resume).++ ``__interaction__`` is NOT noise: after the forced-emit revert it is the+ only source of the ask_user card and must clear suppress to be+ forwarded to the frontend.``controller_output.task_failed`` is NOT noise: it must clear suppressand surface ``chat.error`` (otherwise HITL stays paused forever)."""ctype = getattr(chunk, "type", None)- if ctype in ("llm_usage", "context.usage", "__interaction__"):+ if ctype in ("llm_usage", "context.usage"):return Trueif ctype == "controller_output":return JiuWenSwarmDeepAdapter._run_failure(chunk) is Nonereturn False+ @staticmethod+ def _apply_hitl_suppress_clear(+ chunk: Any,+ *,+ suppress_stream_after_hitl: bool,+ request_id: str = "",+ ) -> tuple[bool, bool]:+ """HITL suppress 清除决策,返回 (suppress_after, skip_chunk)。++ ask_user 之后的 chunk:噪声(llm_usage / context.usage)继续抑制并跳过;+ 首个非噪声 chunk 清除 suppress(恢复转发,防 invocation 永久挂起)。+ ``hitl_pending_stream`` 不在此处触碰——由调用方持有,驱动+ ``chat.invocation_paused`` 收尾帧,气泡保持开启等待用户输入。+ """+ if not suppress_stream_after_hitl:+ return suppress_stream_after_hitl, False+ if JiuWenSwarmDeepAdapter._is_hitl_suppress_noise_chunk(chunk):+ return suppress_stream_after_hitl, True+ logger.info(+ "[JiuWenSwarmDeepAdapter] HITL suppress cleared on runner resume: "+ "request_id=%s chunk_type=%s",+ request_id,+ getattr(chunk, "type", None) or type(chunk).__name__,+ )+ return False, False+@staticmethoddef _run_failure(chunk) -> tuple[str, str] | None:"""Return ``(error_type, message)`` if *chunk* is a run-level terminal failure.diff --git a/jiuwenswarm/server/runtime/skill_turbo/executor.py b/jiuwenswarm/server/runtime/skill_turbo/executor.pyindex 1c1a195cf2..4665132b7e 100644--- a/jiuwenswarm/server/runtime/skill_turbo/executor.py+++ b/jiuwenswarm/server/runtime/skill_turbo/executor.py@@ -1499,34 +1499,19 @@ class SkillTurboExecutor:return None, current_tool_call_iddef _next_tool_call_id(self, tool_name: str, kwargs: dict[str, Any]) -> str:- """生成确定性 tool_call_id:基于 (tool_name, request_id, canonical_args, call_index) 哈希。-- - request_id:``self._execution_inputs["request_id"]``,外层 ReAct 调用的- UUID(skill_turbo_tools 注入 inputs),全局唯一。它随 ``save_resume_ctx``- 整体落盘、resume 时 ``apply_interactive_ask_to_inputs`` 原样复原- (不改动 request_id),因此同请求内重放稳定、跨请求不同。- 混入它可避免「相同 ask_user args」时 tool_call_id 在不同会话/请求间撞车- 导致 relay-claw 的 AskUserQuestionBridge 把后续卡片当同 HITL 重放吞掉- (前端不弹卡)。- - canonical_args:``json.dumps(sort_keys, default=str)`` 后取 sha1[:8]- - call_index:本次执行内同 (name, args, request_id) 的第几次调用(从 0 起算)+ """生成确定性 tool_call_id:基于 (tool_name, canonical_args, call_index) 哈希。- 重放时只要 plan_code+inputs 一致且同一请求,相同顺序的同名同参调用必然得到- 同样的 id;与 ``PermissionInterruptRail`` 的 ``user_inputs[tool_call_id]``- 对应即可命中。+ - canonical_args:``json.dumps(sort_keys, default=str)`` 后取 sha1[:8]+ - call_index:本次执行内同 (name, args) 的第几次调用(从 0 起算)- request_id 缺失(无外层请求上下文的单测/降级)时退化为原行为,仅保留同执行内- 确定性,不影响重放匹配(回退命中走 tool_name + idx 路径)。+ 重放时只要 plan_code+inputs 一致,相同顺序的同名同参调用必然得到同样的 id;+ 与 ``PermissionInterruptRail`` 的 ``user_inputs[tool_call_id]`` 对应即可命中。"""try:args_canonical = json.dumps(kwargs, sort_keys=True, default=str)except (TypeError, ValueError):args_canonical = repr(sorted(kwargs.items()))- # 混入 request_id:跨请求隔离,同请求内重放稳定(resume_ctx 整体穿越中断)。- # request_id 缺失时退化为原行为(args_canonical 单独哈希),不引入新失败模式。- rid = str(self._execution_inputs.get("request_id") or "")- args_source = f"{rid}\n{args_canonical}" if rid else args_canonical- args_hash = hashlib.sha1(args_source.encode("utf-8")).hexdigest()[:8]+ args_hash = hashlib.sha1(args_canonical.encode("utf-8")).hexdigest()[:8]key = f"{tool_name}|{args_hash}"idx = self._tool_call_counter.get(key, 0)self._tool_call_counter[key] = idx + 1diff --git a/tests/unit_tests/agentserver/test_interface_deep_stream_outbound.py b/tests/unit_tests/agentserver/test_interface_deep_stream_outbound.pyindex a82e820653..fe1a4dbde0 100644--- a/tests/unit_tests/agentserver/test_interface_deep_stream_outbound.py+++ b/tests/unit_tests/agentserver/test_interface_deep_stream_outbound.py@@ -174,16 +174,22 @@ def test_same_round_streamed_answer_still_empty_final() -> None:def test_hitl_suppress_noise_keeps_flags() -> None:- """Pause-tail metadata must not clear suppress."""+ """Pause-tail metadata must not clear suppress.++ ``__interaction__`` is not noise: it is the ask_user card source after the+ forced-emit revert and must be forwarded.+ """for chunk_type in ("llm_usage","context.usage",- "__interaction__","controller_output",):assert JiuWenSwarmDeepAdapter._is_hitl_suppress_noise_chunk(SimpleNamespace(type=chunk_type, payload={}))+ assert not JiuWenSwarmDeepAdapter._is_hitl_suppress_noise_chunk(+ SimpleNamespace(type="__interaction__", payload={})+ )def test_hitl_suppress_task_failed_not_noise() -> None:diff --git a/tests/unit_tests/agentserver/test_repro_hitl_double_resume.py b/tests/unit_tests/agentserver/test_repro_hitl_double_resume.pynew file mode 100644index 0000000000..10f33af8b5--- /dev/null+++ b/tests/unit_tests/agentserver/test_repro_hitl_double_resume.py@@ -0,0 +1,51 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""ask_user HITL 挂起期间的 suppress 清除行为:ask_user 之后首个非噪声 chunk+只清 suppress(恢复转发),hitl_pending_stream 保持 True,使收尾帧仍为+chat.invocation_paused(气泡保持开启)。直接测 adapter 静态方法,防护回退。+"""++from __future__ import annotations++from types import SimpleNamespace++from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (+ JiuWenSwarmDeepAdapter,+)+++def _apply(chunk, suppress=True):+ return JiuWenSwarmDeepAdapter._apply_hitl_suppress_clear(+ chunk,+ suppress_stream_after_hitl=suppress,+ request_id="req-1",+ )+++def test_noise_chunks_keep_suppression() -> None:+ """噪声 chunk(llm_usage / context.usage):维持抑制并跳过。"""+ for chunk_type in ("llm_usage", "context.usage"):+ suppress, skip = _apply(SimpleNamespace(type=chunk_type, payload={}))+ assert suppress is True+ assert skip is True+++def test_first_non_noise_chunk_clears_suppress_keeps_hitl_pending() -> None:+ """首个非噪声 chunk:清 suppress(恢复转发)。++ hitl_pending_stream 由调用方持有、本方法不触碰——它驱动+ chat.invocation_paused 收尾帧;曾在此分支被一并清成 False 导致气泡+ 提前关闭、前端二次 resume。+ """+ for chunk_type in ("llm_output", "chat.ask_user_question", "__interaction__"):+ suppress, skip = _apply(SimpleNamespace(type=chunk_type, payload={}))+ assert suppress is False, f"{chunk_type} 应清除 suppress"+ assert skip is False, f"{chunk_type} 清除后应继续处理(不跳过)"+++def test_suppress_off_passes_through_untouched() -> None:+ """suppress 已清除:chunk 原样放行(不跳过、状态不变)。"""+ chunk = SimpleNamespace(type="llm_usage", payload={})+ suppress, skip = _apply(chunk, suppress=False)+ assert suppress is False+ assert skip is Falsediff --git a/tests/unit_tests/agentserver/test_repro_seq_ask_user_cards.py b/tests/unit_tests/agentserver/test_repro_seq_ask_user_cards.pynew file mode 100644index 0000000000..73c4203bd8--- /dev/null+++ b/tests/unit_tests/agentserver/test_repro_seq_ask_user_cards.py@@ -0,0 +1,111 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""同一外层 skill_acceleration_exec 调用内连续 ask_user 中断的卡片区分。++回退强制 emit 后卡片唯一来源是 harness __interaction__,request_id = 外层+call id——同一外层调用内第二次中断与第一次共用同一 id,前端按 requestId+区分卡片会丢卡;且流内去重会把它当重复跳过。此处验证:+- 第二次中断(同 id 不同 questions)→ 卡片 id 加序号后缀 {id}#{n} 放行+- 同一中断的多通道重复(同 id 同 questions)→ 跳过+- 序号计数跨请求存续(新流内集合不误判、id 不回退)+"""++from __future__ import annotations++from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (+ JiuWenSwarmDeepAdapter,+)++_Q_P1 = [{"question": "演示主题是什么?", "header": "主题", "options": []}]+_Q_P2 = [{"question": "需要多少页?", "header": "页数", "options": []}]+++def _card(request_id: str, questions: list) -> dict:+ return {+ "event_type": "chat.ask_user_question",+ "request_id": request_id,+ "questions": questions,+ "source": "ask_user_interrupt",+ }+++def _adapter() -> JiuWenSwarmDeepAdapter:+ adapter = JiuWenSwarmDeepAdapter.__new__(JiuWenSwarmDeepAdapter)+ adapter._ask_user_card_seq = {}+ return adapter+++def test_first_interrupt_uses_raw_id() -> None:+ adapter = _adapter()+ ids: set[str] = set()+ questions: dict[str, str] = {}+ card = _card("call_outer_1", _Q_P1)+ assert adapter._dedupe_ask_user_card(card, ids, questions) is False+ assert card["request_id"] == "call_outer_1"+++def test_second_interrupt_same_outer_id_gets_suffix() -> None:+ """同一外层调用内第二次中断(不同 questions):id 加 #2 后缀放行。"""+ adapter = _adapter()+ ids: set[str] = set()+ questions: dict[str, str] = {}+ first = _card("call_outer_1", _Q_P1)+ second = _card("call_outer_1", _Q_P2)+ assert adapter._dedupe_ask_user_card(first, ids, questions) is False+ assert adapter._dedupe_ask_user_card(second, ids, questions) is False+ assert first["request_id"] == "call_outer_1"+ assert second["request_id"] == "call_outer_1#2"+++def test_same_interrupt_duplicate_channels_skipped() -> None:+ """同一中断的多通道重复(同 id 同 questions):跳过,不改 id。"""+ adapter = _adapter()+ ids: set[str] = set()+ questions: dict[str, str] = {}+ first = _card("call_outer_1", _Q_P1)+ replay = _card("call_outer_1", _Q_P1)+ assert adapter._dedupe_ask_user_card(first, ids, questions) is False+ assert adapter._dedupe_ask_user_card(replay, ids, questions) is True+ assert replay["request_id"] == "call_outer_1"+++def test_duplicate_channel_of_second_card_also_skipped() -> None:+ """第二张卡(#2)的迟到重复通道:不误判为新卡、不弹副本。"""+ adapter = _adapter()+ ids: set[str] = set()+ questions: dict[str, str] = {}+ for card in (+ _card("call_outer_1", _Q_P1),+ _card("call_outer_1", _Q_P2),+ ):+ assert adapter._dedupe_ask_user_card(card, ids, questions) is False+ dup_of_second = _card("call_outer_1", _Q_P2)+ assert adapter._dedupe_ask_user_card(dup_of_second, ids, questions) is True+++def test_seq_survives_across_requests() -> None:+ """序号跨请求存续:新流(空集合)内第二次中断仍得 #2,不回退原 id。"""+ adapter = _adapter()+ ids1: set[str] = set()+ questions1: dict[str, str] = {}+ assert adapter._dedupe_ask_user_card(+ _card("call_outer_1", _Q_P1), ids1, questions1+ ) is False+ # 新请求:流内集合为空,adapter 实例(seq)存续+ ids2: set[str] = set()+ questions2: dict[str, str] = {}+ second = _card("call_outer_1", _Q_P2)+ assert adapter._dedupe_ask_user_card(second, ids2, questions2) is False+ assert second["request_id"] == "call_outer_1#2"+++def test_third_interrupt_gets_next_suffix() -> None:+ adapter = _adapter()+ ids: set[str] = set()+ questions: dict[str, str] = {}+ q3 = [{"question": "风格?", "header": "风格", "options": []}]+ for card in (_card("call_outer_1", _Q_P1), _card("call_outer_1", _Q_P2)):+ adapter._dedupe_ask_user_card(card, ids, questions)+ third = _card("call_outer_1", q3)+ assert adapter._dedupe_ask_user_card(third, ids, questions) is False+ assert third["request_id"] == "call_outer_1#3"diff --git a/tests/unit_tests/agentserver/test_stream_event_rail_todo.py b/tests/unit_tests/agentserver/test_stream_event_rail_todo.pyindex aa864b6b63..10d5910e51 100644--- a/tests/unit_tests/agentserver/test_stream_event_rail_todo.py+++ b/tests/unit_tests/agentserver/test_stream_event_rail_todo.py@@ -220,90 +220,6 @@ async def test_ask_user_interrupt_emits_question_event_from_tool_args():assert output.payload["questions"][0]["question"] == "请选择方案"-async def test_skill_turbo_hitl_emits_ask_user_with_inner_request_id():- """Nested ask_user questions use the inner ask_user tool_call.id as- request_id, so sequential ask_user cards are not conflated by the- frontend (which keys cards on requestId)."""- class ToolInterruptException(Exception):- def __init__(self):- super().__init__()- self.request = SimpleNamespace(- tool_call_id="skill_turbo-tc-ask_user-54ee111d-0",- tool_name="ask_user",- tool_args={- "questions": [- {- "question": "需要多少页?",- "header": "页数",- "options": [{"label": "10页", "description": ""}],- }- ]- },- )- self.tool_call = SimpleNamespace(- id="skill_turbo-tc-ask_user-54ee111d-0",- name="ask_user",- arguments={- "questions": [- {- "question": "需要多少页?",- "header": "页数",- "options": [{"label": "10页", "description": ""}],- }- ]- },- )-- session = _FakeSession()- outer_tc = SimpleNamespace(id="call_c2967f3aec5c412583a203b9", name="skill_acceleration_exec")-- await JiuSwarmStreamEventRail._emit_skill_turbo_ask_user_question(- session,- outer_tool_call=outer_tc,- skill_turbo_tic=ToolInterruptException(),- )-- assert len(session.outputs) == 1- output = session.outputs[0]- assert output.type == "chat.ask_user_question"- assert output.payload["request_id"] == "skill_turbo-tc-ask_user-54ee111d-0"- assert output.payload["source"] == "ask_user_interrupt"- assert output.payload["questions"][0]["question"] == "需要多少页?"---async def test_skill_turbo_hitl_skips_emit_when_inner_request_id_missing(monkeypatch):- """Without inner ask_user request_id, do not emit a question card."""- class ToolInterruptException(Exception):- def __init__(self):- super().__init__()- self.request = SimpleNamespace(- tool_call_id="",- tool_name="ask_user",- tool_args={- "questions": [- {- "question": "需要多少页?",- "header": "页数",- "options": [{"label": "10页", "description": ""}],- }- ]- },- )- self.tool_call = None-- session = _FakeSession()-- await JiuSwarmStreamEventRail._emit_skill_turbo_ask_user_question(- session,- outer_tool_call=None,- skill_turbo_tic=ToolInterruptException(),- )-- assert session.outputs == []--@pytest.mark.asyncioasync def test_ask_user_interrupt_emits_question_event_from_exception_cause():class ToolInterruptException(Exception):