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
生成式UI:bugfix
shenmuxi57d68e7c99d2
diff --git a/jiuwenswarm/agents/harness/common/rails/response_prompt_rail.py b/jiuwenswarm/agents/harness/common/rails/response_prompt_rail.pyindex e0cafbec3c..8e76694be6 100644--- a/jiuwenswarm/agents/harness/common/rails/response_prompt_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/response_prompt_rail.py@@ -28,7 +28,10 @@ SKIP_A2UI_PROMPT_CONTEXT_KEY = "skip_a2ui"A2UI_BROWSER_WORKFLOW_CONTEXT_KEY = "a2ui_browser_workflow"# browser-workflow 功能总开关(休眠中):False 时 a2ui prompt 不注入# preflight/发送确认门禁规则,browser 意图检测被旁路。-# 重开前需:① 修复 browser-workflow prompt 的已知问题(见 PR #8390 检视记录);+# 重开前需:① 修复 browser-workflow prompt 的 3 项 latent 问题:+# a) build_a2ui_browser_workflow_instruction 无 language 参数且文案纯英文(prompt_instructions.py:82);+# b) _BROWSER_WORKFLOW_INTENT_RE 过宽(prompt_instructions.py:34,易误判普通 browser 提及为 workflow 意图);+# c) protocol.py 14 个 _build_*_client_event_prompt 仅英文文案(无 i18n,与主 a2ui prompt 中英双轨不一致);# ② 与工具注册联动——同时设置 env PLAYWRIGHT_RUNTIME_MCP_ENABLED,否则只开# prompt 无工具;只开 env 不开本开关则模型可执行浏览器动作但缺确认门禁提示。# 两处 call-site(before_invoke / before_model_call)均引用本常量,恢复只改这一处。diff --git a/jiuwenswarm/server/docs/bugfix/B_01_a2ui-empty-finalized-silent-loss.md b/jiuwenswarm/server/docs/bugfix/B_01_a2ui-empty-finalized-silent-loss.mdnew file mode 100644index 0000000000..8a684552a9--- /dev/null+++ b/jiuwenswarm/server/docs/bugfix/B_01_a2ui-empty-finalized-silent-loss.md@@ -0,0 +1,84 @@+# B_01 — A2UI repair 空输出被误判合法,suppress 扣发的 chat.final 静默丢失++- 日期:2026-10-29+- 分支:dev-stable+- 症状(触发率测试 case #26,双表单同回复场景):relay-claw 落库内容只剩 `散文 + <a2ui<a2ui-json>` probe 残片(61 字符),模型实际产出的 9K~18K A2UI 整块静默丢失;UI 显示「组件不可用」,无任何报错,刷新后依旧。++## 1. 根因链++```+模型 A2UI 输出校验失败(validator: valid=False)+ → finalizer repair 循环调 repair_call+ → JiuWenSwarmDeepAdapter.repair_model_response:self._model is None(officeclaw tenant pool 适配器在+ finalize 时不持有模型实例——repair 在 producer finally cleanup 之后执行)→ 返回 None+ → _coerce_model_message_content(None) → ""+ → spec.validate_response(""):无 tagged block、无 a2ui part → vacuously valid=True+ → 误报 status="repaired"、finalized=""(changed=true)+ → interface.py 流式收尾 `if finalized_assistant_message and (...)`:"" falsy+ → suppress 扣住的原 chat.final 的重发整体跳过 → 整块内容永不送达 relay+ → relay 收到空 final,不触发 replace_final → 持久化 delta 累积的 probe 残片+```++sidecar 关键日志签名(修复前):++```+A2UI finalizer validation complete: valid=False+A2UI finalizer repair attempt started: attempt=1+[JiuWenSwarmDeepAdapter] repair skipped: no model instance available+A2UI finalizer repair attempt complete: attempt=1 valid=True ← 空内容伪装成修复成功+A2UI response finalization status: status=repaired ← 且不会走 repair_failed 的 retry 降级+```++## 2. 修复(三层守卫,本提交)++| 层 | 文件 | 改动 | 激活条件(全部为原异常态,健康路径零触达) |+|---|---|---|---|+| 校验洞 | `runtime/a2ui/runtime/finalizer.py` | repair 输出 strip 为空 → 记 `last_error="repair returned empty content"` 并 `continue`(跑满 attempt 后落 `repair_failed`,触发既有 retry_without_a2ui 降级,返回可读非空文本) | 仅 a2ui 校验失败后 repair 返回 None/空 |+| 流式兜底 | `agent_adapter/interface.py` L~4250 | `suppress_a2ui_stream` 且 finalized 为空且原始内容非空 → 回退重发被扣的原始内容(relay 前端 replace_final + jsonrepair 仍有渲染机会) | 仅 suppress 激活 + finalized 空 |+| unary 兜底 | `agent_adapter/interface.py` L~3128 | finalize 返回空 → 恢复 finalize 前快照,防正文被清空 | 仅 a2ui finalize 返回空 |++## 3. 影响范围++仅 a2ui 链(通道白名单 web/officeclaw、a2ui 开关开启、含 A2UI 标记的响应);非 a2ui 流量逐字节不变。`validate_a2ui_response("")==valid` 的公共语义(普通文本合法)不改,守卫放在 finalizer repair 循环内。++## 4. 验证++- 单测:`tests/unit_tests/a2ui/test_finalizer.py` 新增 2 例(空/None repair 输出 → repair_failed + 非空降级)、`test_response_finalization.py` 新增 1 例(入口恒非空且不含破损标签);全套 106 passed。+- live(2026-10-29 复验 case #26 提示词):+ - 修复前签名:`attempt=1 valid=True → status=repaired`,落库 61 字符残片、表单全丢+ - 修复后签名:`attempt=1/2 returned empty → status=repair_failed → A2UI repair failed, retrying without A2UI → finalized changed=true`,重发激活、内容不再丢+- §9.1 跨仓契约(发帧侧已实施,本提交):`_make_a2ui_final_chunk` payload 增加 `a2ui_resend: True`——声明"suppress 链重发的权威终稿"。relay 消费侧(见 relay-claw PR5508 后续提交)见标记即整段覆写正文、不再按 `<a2ui-json>` 标签门控,降级无标签终稿同样覆写,probe 残片不再落库。发帧先合入安全:旧 relay 忽略未知 payload 字段,行为不变。++## 5. 后续可选项++officeclaw pool 适配器在 finalize 时不持有模型(`_model is None`)导致 repair 在该通道结构性不可用;如需真正可用,需让 `repair_model_response` 懒解析 `_model_cache`/当前选择模型,或调整 cleanup 与 finalize 次序——独立评估,不在本缺陷修复范围。++## 6. 检视跟进(2026-10-30,PR #9194 未解决意见)++### 6.1 流级回归用例(检视 3.1)++helper 级用例(`_a2ui_probe_for_frame` / `_a2ui_suppress_should_engage`)无法覆盖真实帧顺序,本轮补流级用例 `tests/unit_tests/a2ui/test_foreign_stream_bookkeeping.py`:++- 复用 `tests/unit_tests/agentserver/` 既有 harness(`JiuWenSwarm` + fake adapter 逐帧驱动 `process_message_stream`),可 yield 任意 `event_type` / `stream_source_id` 帧;此前「仓库无流循环基建」的判断不成立。+- 用例 1:父 delta → 子流 delta(带 `stream_source_id` + `<a2ui-json>`)→ 父 delta → 父 `chat.tool_call` → 父 final → 晚到子流 final。断言 `assistant_message` = 父终稿、tool_call 落库正文仅含主链 delta、历史无子流文本、无 probe 占位帧(同时锚定 CR#1/#2/#3)。+- 用例 2:suppress 激活后父 final 先到、晚到子流 final 不得顶掉终稿;占位帧行为保持不变,历史无子流文本。++### 6.2 依赖描述修正(检视 3.5)++`relay-claw 前端已部署 replace_final` 的表述与事实不符:该能力在 relay-claw PR #5508 中实现,尚未合入 dev-stable/main、未部署。已修正 `runtime/a2ui/integration.py`(3 处)与 `runtime/agent_adapter/interface.py`(1 处)的注释,明确:++- 依赖 relay-claw PR #5508 合入并部署后 `suppress` 才可安全启用;+- 合入顺序须 relay-claw 先行,否则 officeclaw 累积 content 的 `<a2ui 前半 + probe 占位` 无法覆写清洗;+- 若无法保证顺序,应把 officeclaw 的白名单翻转收敛到配置开关。++行为未变(白名单仍为 web + officeclaw),本次仅修正注释事实与顺序声明。++### 6.3 finalize adapter 解析的渠道门控与 docstring 修正++`_resolve_turn_adapter_for_finalize` 原先的 docstring 写「finalize 时刻这里是幂等缓存命中」,与实现不符:解析走 `_get_or_create_session_adapter`,缓存条目在 finalize 前被清掉(`cleanup_session_adapter`、空闲 TTL 驱逐(默认 2h)、企业身份切换)或不在同一缓存域时会 miss,miss 分支会冷建新实例(`_new_session_scoped_adapter` → `create_instance` → `start_interaction` → `warmup_session_context`)。++本次修正:++- docstring 如实描述两条分支:常态命中;miss 时冷建是「让 repair 拿到可用 `_model`」付出的秒级代价,不再声称一定命中。+- 解析前增加渠道门控:`is_a2ui_channel(channel)` 与 `should_finalize_repair(channel)` 任一不成立时直接返回 root。这两类渠道的 `finalize_assistant_response_if_a2ui` 本就早退,此前每轮仍多做一次解析,且 miss 时会无谓冷建。a2ui 且启用 repair 的渠道行为不变。+- 单测:`tests/unit_tests/a2ui/test_finalize_adapter_wiring.py` 新增 2 例(非 a2ui 渠道、未启用 repair 渠道均不解析、不调用 getter);a2ui 域 119 passed / 1 skipped。diff --git a/jiuwenswarm/server/runtime/a2ui/integration.py b/jiuwenswarm/server/runtime/a2ui/integration.pyindex 37782a0518..e0de348fc7 100644--- a/jiuwenswarm/server/runtime/a2ui/integration.py+++ b/jiuwenswarm/server/runtime/a2ui/integration.py@@ -29,13 +29,16 @@ _A2UI_CHANNEL_ID = "web"# relay-claw 走 officeclaw channel,a2ui 对其原生生效(与 web 同等)。_A2UI_CHANNEL_IDS = frozenset({"web", "officeclaw"})-# a2ui 流式 probe(pending render chunk)机制的适用渠道:目前仅 web 前端。-# officeclaw (relay-claw) 用 parseA2UIContent(本仓库 channels/web/frontend-# a2uiContent.ts,relay-claw 经 vendor 同步使用)从累积文本提取 <a2ui-json> 块,-# probe 插入的 <a2ui-json>\n 会与 agent 原始块重复、污染 content 致前端提取失败。-# 与 _A2UI_CHANNEL_IDS(能原生渲染 a2ui 的渠道)有意双轨:新增渠道时-# 「能渲染」不自动等于「需要 probe」,两侧必须各自显式声明,防语义搭便车。-_A2UI_PROBE_CHANNEL_IDS = frozenset({"web"})+# a2ui 流式 probe(pending render chunk)机制的适用渠道。+# officeclaw (relay-claw) 启用 probe → suppress 自动激活(扣 a2ui delta + 原 chat.final+# + 改写 is_complete,relay-claw 不 break)。probe 的 <a2ui-json>\n 占位帧会与 delta 拆分+# 的 <a2ui 前半在累积 content 里拼接产生 -json> 污染,只能由前端 chat.final+# replace_final 覆写(patchMessage({content}=finalized))清掉。+# 依赖关系(勿按"已部署"理解):该前端能力在 relay-claw PR #5508 中实现,尚未合入+# dev-stable/main、未部署。合入顺序必须 relay-claw 先行;在此之前 officeclaw 的+# suppress 会把不可清洗的 <a2ui 前半 + probe 占位留在累积 content 里,属行为回退。+# 若无法保证顺序,应把 officeclaw 的翻转收敛到配置开关,前端部署后再开启。+_A2UI_PROBE_CHANNEL_IDS = frozenset({"web", "officeclaw"})def is_a2ui_channel(channel: str | None) -> bool:@@ -48,15 +51,13 @@ def is_a2ui_probe_channel(channel: str | None) -> bool:return str(channel or "").strip().lower() in _A2UI_PROBE_CHANNEL_IDS-# 仅这些渠道走服务端 A2UI repair/retry/重发(finalize_assistant_response_if_a2ui)。-# officeclaw (relay-claw) 故意排除,完全跳过服务端 finalize(含校验):-# 1. 服务端 repair 后整段 chat.final 重发会与已累积 delta 产生重复块;-# 2. 该重发帧落在 wire 终结块之后被 relay-claw 消费方 break 丢弃;-# 3. 破损 a2ui 内容原样透传,由前端做文本降级显示(本仓库 a2uiContent.ts-# extractTextFromMalformedA2UI :173-211 正则文本打捞 + invalidA2UIFallback-# :162 固定错误文案降级——是降级显示而非 JSON 修复)。-# 完全跳过 = 不 repair/不校验/不重发,从根上消除重发帧时序丢失与重复块。-_A2UI_FINALIZE_REPAIR_CHANNEL_IDS = frozenset({"web"})+# officeclaw (relay-claw) 启用服务端 A2UI repair/retry/finalize:+# suppress 扣住原 chat.final(不上 wire)+ 改写 is_complete(relay-claw 不 break),+# post-stream repair 后发送 finalized(前端首次收到,不是"重发")。+# 依赖 relay-claw PR #5508 的 chat.final a2ui replace_final / a2ui_resend 消费能力+# (尚未合入 dev-stable/main、未部署)。合入顺序 relay-claw #5508 先行;否则 content+# 仍按 delta 语义累积,probe 污染无法覆写清洗。+_A2UI_FINALIZE_REPAIR_CHANNEL_IDS = frozenset({"web", "officeclaw"})def should_finalize_repair(channel: str | None) -> bool:@@ -142,10 +143,11 @@ async def finalize_assistant_response_if_a2ui(if not is_a2ui_channel(channel):return content- # officeclaw (relay-claw) 完全跳过服务端 finalize(含校验):不 repair、不校验、- # 不重发。破损 a2ui 内容原样透传,由前端做文本降级显示(本仓库 a2uiContent.ts- # extractTextFromMalformedA2UI :173-211 正则文本打捞 + invalidA2UIFallback :162- # 固定错误文案降级——是降级显示而非 JSON 修复)。+ # officeclaw (relay-claw) 启用 suppress + repair(与 web 对齐):+ # suppress 扣住原 chat.final + 改写 is_complete,post-stream repair 后+ # 发送 finalized(前端首次收到)。覆写依赖 relay-claw PR #5508 的+ # replace_final / a2ui_resend 消费(尚未合入 dev-stable/main、未部署),+ # 合入顺序须 relay-claw 先行,否则累积的 <a2ui 前半 + probe 污染无法清洗。if not should_finalize_repair(channel):return contentdiff --git a/jiuwenswarm/server/runtime/a2ui/runtime/finalizer.py b/jiuwenswarm/server/runtime/a2ui/runtime/finalizer.pyindex 7b4b92cb62..f97b1bcc53 100644--- a/jiuwenswarm/server/runtime/a2ui/runtime/finalizer.py+++ b/jiuwenswarm/server/runtime/a2ui/runtime/finalizer.py@@ -142,7 +142,20 @@ class A2UIResponseFinalizer:response = repair_call(prompt)if inspect.isawaitable(response):response = await response- repaired_content = _coerce_model_message_content(response)+ model_output = _coerce_model_message_content(response)+ if not model_output.strip():+ # 空输出(如适配器无模型可修 → 返回 None → 强制成 "")不得按成功修复处理:+ # validate("") 因无 a2ui 块而恒真,会把"修复失败"伪装成 status=repaired、+ # finalized=空串;下游 interface 对空 finalized 跳过 suppress 扣发的+ # chat.final 重发,整块表单静默丢失、落库只剩 probe 残留。+ last_error = "repair returned empty content"+ logger.info(+ "A2UI finalizer repair attempt returned empty: request_id=%s attempt=%d",+ request_id,+ _attempt,+ )+ continue+ repaired_content = model_outputvalidation = spec.validate_response(repaired_content)logger.info("A2UI finalizer repair attempt complete: request_id=%s attempt=%d valid=%s",diff --git a/jiuwenswarm/server/runtime/a2ui/runtime/response_finalization.py b/jiuwenswarm/server/runtime/a2ui/runtime/response_finalization.pyindex de856191b7..3cb72f6ce9 100644--- a/jiuwenswarm/server/runtime/a2ui/runtime/response_finalization.py+++ b/jiuwenswarm/server/runtime/a2ui/runtime/response_finalization.py@@ -27,7 +27,11 @@ logger = logging.getLogger(__name__)# Type for a function that can retry a request without A2UIRetryWithoutA2UI = Callable[[str], Any]-_A2UI_FINALIZATION_TIMEOUT_SECONDS = 45.0+# Must cover max_repair_attempts full LLM rounds: a measured repair turn+# (schema repair prompt + regenerated JSON, glm-5.2) takes ~30-40s, so the+# old 45s budget killed the first attempt before it could return and degraded+# every invalid block to stripped text.+_A2UI_FINALIZATION_TIMEOUT_SECONDS = 120.0_A2UI_FAST_PATH_VALIDATION_TIMEOUT_SECONDS = 5.0diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex b476744062..44833803ed 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -81,6 +81,7 @@ from jiuwenswarm.server.runtime.a2ui.integration import (finalize_assistant_response_if_a2ui,is_a2ui_channel,is_a2ui_probe_channel,+ should_finalize_repair,)from jiuwenswarm.server.runtime.a2ui.protocol import is_a2ui_client_eventfrom jiuwenswarm.server.runtime.a2ui.runtime.finalizer import should_finalize_a2ui_content@@ -466,6 +467,10 @@ def _make_a2ui_final_chunk("event_type": "chat.final","session_id": session_id,"content": content,+ # §9.1 契约:suppress 链重发的权威终稿。relay 见标记即整段覆写正文+ # (不再要求含 <a2ui-json> 标签),清掉流式期已上 wire 的半截+ # `<a2ui` + probe 占位残片;降级无标签终稿同样被干净覆写。+ "a2ui_resend": True,},is_complete=False,)@@ -497,6 +502,54 @@ def _is_foreign_stream_source(payload: Any) -> bool:return isinstance(source_id, str) and bool(source_id) and source_id != "main"+def _a2ui_probe_for_frame(+ probe: str,+ content: str,+ *,+ event_type: str,+ enabled: bool,+ foreign: bool,+) -> tuple[tuple[str, str] | None, str]:+ """Advance the parent's a2ui probe state machine with one stream frame.++ Returns ``(split, next_probe)``. Mirror frames from nested streams must+ never touch the probe buffer or yield a split: a child marker left in the+ parent's 512-byte probe window makes the *next main-chain* frame split on+ it (``marker_start <= content_start``) and spuriously engages suppression+ — the parent's deltas get withheld and a bogus render probe is emitted+ (PR9194 review CR#2). Gate the whole probe step on ``foreign`` instead of+ only gating engage, so the state machine input stays clean.+ """+ # Split guards for G.CTL.03 (<=3 boolean operands per condition): frame+ # validity first, then event-type whitelist — same short-circuit semantics.+ if foreign or not enabled or not content:+ return None, probe+ if event_type not in {"chat.delta", "chat.final"}:+ return None, probe+ split = _split_a2ui_stream_content(probe, content)+ return split, _extend_a2ui_stream_probe(probe, content)+++def _a2ui_suppress_should_engage(+ suppress_active: bool,+ a2ui_split: tuple[str, str] | None,+ foreign: bool,+) -> bool:+ """Gate the a2ui withhold state machine for one stream frame.++ Mirror frames from a nested stream (subagent / skill node) must never+ engage suppression on the parent turn: their markers belong to the child+ timeline, and letting them trip the state machine withholds the parent's+ deltas, emits a spurious render probe and mixes child text into the+ finalized parent answer. Once suppression is already active, every frame+ stays withheld (unchanged) — the flag belongs to the parent turn, not to+ the frame that set it.+ """+ if suppress_active:+ return True+ return not foreign and a2ui_split is not None++def _is_duplicate_full_body_delta(pending_chunks: list[str], content: str) -> bool:"""True when ``content`` is an exact replay of the already-buffered answer body.@@ -2165,6 +2218,47 @@ class JiuWenSwarm:return retry_without_a2ui_call+ @staticmethod+ async def _resolve_turn_adapter_for_finalize(+ adapter: AgentAdapter,+ request: AgentRequest,+ session_id: str | None,+ ) -> AgentAdapter:+ """Return the session-scoped adapter that actually executed this turn.++ _ensure_adapter 返回的 root facade 按设计不自建实例(热更新仅级联+ session adapter),其 _model/_instance 恒为 None:repair_call 挂在 root 上+ 时 repair_model_response 每轮都 skip,retry_without_a2ui 也在 _instance+ 守卫处静默返回 None,repair_failed 后"降级非 a2ui 重答"的设计路径从不执行,+ 最终 a2ui 块被整块剥离。++ 解析走 _get_or_create_session_adapter,常态是缓存命中:流执行链在+ _process_message_stream_impl 内已创建过 session adapter(create_instance+ 完成 _model 绑定)。条目在 finalize 前被清理(cleanup_session_adapter /+ 空闲 TTL 驱逐 / 企业身份切换)或不在同一缓存域时会 miss,此时会冷建一个+ 新实例(create_instance + start_interaction + warmup_session_context,+ 秒级代价)——这是让 repair 拿到可用 _model 付出的代价,不是无成本命中。++ 仅对启用服务端 repair 的 a2ui 渠道解析;其他渠道的 finalize 会早退,直接+ 返回 root,避免每轮多走一次解析、也避免在没有 repair 的渠道上触发冷建。+ 解析失败保持旧的 root 接线行为,不引入新故障面。+ """+ channel = getattr(request, "channel_id", None)+ if not is_a2ui_channel(channel) or not should_finalize_repair(channel):+ return adapter+ getter = getattr(adapter, "_get_or_create_session_adapter", None)+ if not callable(getter) or not session_id:+ return adapter+ try:+ return await getter(session_id, request=request) # pylint: disable=protected-access+ except Exception as exc:+ logger.warning(+ "[JiuWenSwarm] resolve turn-scoped finalize adapter failed "+ "session_id=%s: %s (falling back to root adapter)",+ session_id, exc, exc_info=True,+ )+ return adapter+@staticmethoddef _build_interactive_input_from_answers(request_id: str,@@ -3133,11 +3227,15 @@ class JiuWenSwarm:if result.ok and result.payload.get("content"):content = result.payload["content"]content_str = content if isinstance(content, str) else str(content)- repair_call = getattr(adapter, "repair_model_response", None)+ turn_adapter = await self._resolve_turn_adapter_for_finalize(+ adapter, request, session_id,+ )+ repair_call = getattr(turn_adapter, "repair_model_response", None)retry_without_a2ui_call = self._make_retry_without_a2ui_call(- adapter=adapter,+ adapter=turn_adapter,request=request,)+ pre_finalize_content_str = content_strcontent_str = await finalize_assistant_response_if_a2ui(content_str,channel=request.channel_id,@@ -3146,6 +3244,10 @@ class JiuWenSwarm:repair_call=repair_call,retry_without_a2ui_call=retry_without_a2ui_call,)+ if not content_str:+ # 同流式路径兜底:finalize 空返回(如 repair 不可用被误判合法)+ # 不得把 unary 正文整体清空,回退 finalize 前的原始字符串。+ content_str = pre_finalize_content_strif isinstance(content, str):result.payload["content"] = content_strfrom jiuwenswarm.server.handlers._shared import _sessions_dir_for_request@@ -3751,10 +3853,11 @@ class JiuWenSwarm:suppress_a2ui_stream = Falsea2ui_pending_render_sent = Falsea2ui_stream_probe = ""- # probe 渠道白名单收口在 integration._A2UI_PROBE_CHANNEL_IDS(当前仅 web)。- # officeclaw (relay-claw) 不发 a2ui probe pending chunk:relay-claw 前端用- # parseA2UIContent 从文本提取 <a2ui-json> 块,probe 插入的 <a2ui-json>\n- # 会与 agent 原始块重复,污染累积 content 致前端提取失败。+ # probe 渠道白名单收口在 integration._A2UI_PROBE_CHANNEL_IDS(web + officeclaw)。+ # officeclaw (relay-claw) 启用 probe → suppress 自动激活(扣 a2ui delta + 原+ # chat.final + 改写 is_complete)。覆写依赖 relay-claw PR #5508 的+ # replace_final / a2ui_resend 消费(尚未合入 dev-stable/main、未部署),+ # 合入顺序须 relay-claw 先行,否则累积的 <a2ui 前半 + probe 污染无法清洗。a2ui_probe_enabled = is_a2ui_probe_channel(cid)_yielded_from_queue = 0logger.info(@@ -3839,10 +3942,15 @@ class JiuWenSwarm:)payload_content = str(data.payload.get("content", ""))- a2ui_split = None- if a2ui_probe_enabled and et in {"chat.delta", "chat.final"} and payload_content:- a2ui_split = _split_a2ui_stream_content(a2ui_stream_probe, payload_content)- a2ui_stream_probe = _extend_a2ui_stream_probe(a2ui_stream_probe, payload_content)+ # foreign 判定前置(CR#2):子流镜像帧不得进入父轮 probe 状态机+ frame_is_foreign = _is_foreign_stream_source(data.payload)+ a2ui_split, a2ui_stream_probe = _a2ui_probe_for_frame(+ a2ui_stream_probe,+ payload_content,+ event_type=et,+ enabled=a2ui_probe_enabled,+ foreign=frame_is_foreign,+ )if _should_defer_a2ui_processing_status(suppress_a2ui_stream=suppress_a2ui_stream,event_type=et,@@ -3855,8 +3963,10 @@ class JiuWenSwarm:)continueif et == "chat.delta":- final_answer_chunks.append(payload_content)- if suppress_a2ui_stream or a2ui_split is not None:+ delta_is_foreign = frame_is_foreign+ if not delta_is_foreign:+ final_answer_chunks.append(payload_content)+ if _a2ui_suppress_should_engage(suppress_a2ui_stream, a2ui_split, delta_is_foreign):first_a2ui_suppression = not suppress_a2ui_streamif first_a2ui_suppression:logger.info(@@ -3891,7 +4001,11 @@ class JiuWenSwarm:)should_record = Falsecontinue- durable_pending_final_chunks.append(payload_content)+ # CR#3:与 final_answer_chunks / reasoning 缓冲同款守卫——+ # 子流 delta 不进 durable 缓冲(否则父 tool_call 持久化时+ # 把子流文本写成父历史、空 final rescue 又把合并当父正文)。+ if not delta_is_foreign:+ durable_pending_final_chunks.append(payload_content)should_record = Falseelif et == "chat.reasoning":# Reasoning mirrored from a nested stream stays@@ -3912,7 +4026,9 @@ class JiuWenSwarm:elif et == "chat.final":if isinstance(data.payload, dict):ensure_final_mode_inplace(data.payload)- if suppress_a2ui_stream or a2ui_split is not None:+ if _a2ui_suppress_should_engage(+ suppress_a2ui_stream, a2ui_split, frame_is_foreign+ ):first_a2ui_suppression = not suppress_a2ui_streamif first_a2ui_suppression:logger.info(@@ -3924,8 +4040,12 @@ class JiuWenSwarm:if first_a2ui_suppression and not a2ui_pending_render_sent:yield _make_a2ui_pending_render_chunk(request_id=rid, channel_id=cid)a2ui_pending_render_sent = True- final_answer_content = payload_content- durable_pending_final_chunks = []+ # CR#1:suppress 激活后 foreign final 也进本分支+ # (维持 withhold 不变),但不得改写父轮被扣的终稿+ # 与 durable 缓冲——bookkeeping 只认主链帧。+ if not frame_is_foreign:+ final_answer_content = payload_content+ durable_pending_final_chunks = []continue# Facade-level rescue: reasoning-only models may emit an# empty chat.final after chat.reasoning. Fill a short@@ -3938,16 +4058,20 @@ class JiuWenSwarm:# RelayClaw computeFinalTextDelta appends another copy# (esp. after post-tool \n\n round-break).merged_from_deltas = False- if (- not str(payload_content or "").strip()- and durable_pending_final_chunks- and isinstance(data.payload, dict)- ):- merged = "".join(durable_pending_final_chunks)- if merged.strip():- data.payload["content"] = merged- payload_content = merged- merged_from_deltas = True+ # CR#1/#3:rescue/fill 只在主链 final 上做。子流空 final+ # 若也进这里,会把父轮 durable 合并进子帧、或触发+ # reasoning-only fill,污染子流内容并掏空父缓冲。+ if not frame_is_foreign:+ if (+ not str(payload_content or "").strip()+ and durable_pending_final_chunks+ and isinstance(data.payload, dict)+ ):+ merged = "".join(durable_pending_final_chunks)+ if merged.strip():+ data.payload["content"] = merged+ payload_content = merged+ merged_from_deltas = True# Segment-local visibility only: durable_final_content# is prior-tool text and must not suppress post-tool# reasoning-only rescue.@@ -3962,35 +4086,37 @@ class JiuWenSwarm:(data.payload or {}).get("reasoning_content") or "").strip())- if isinstance(data.payload, dict):- filled = fill_reasoning_only_empty_final_content(- content=payload_content,- has_visible_streamed_text=has_visible_streamed_text,- has_reasoning=has_reasoning,- lang=str(- get_config().get("preferred_language", "zh")- ),- )- if filled != payload_content:- data.payload["content"] = filled- payload_content = filled- logger.info(- "[JiuWenSwarm] filled reasoning-only empty "- "chat.final: request_id=%s "- "had_visible_streamed_text=%s",- rid,- has_visible_streamed_text,- )- elif not str(payload_content or "").strip():- logger.info(- "[JiuWenSwarm] skipped reasoning-only empty "- "chat.final fill: request_id=%s "- "has_reasoning=%s had_visible_streamed_text=%s",- rid,- has_reasoning,- has_visible_streamed_text,+ if not frame_is_foreign:+ if isinstance(data.payload, dict):+ filled = fill_reasoning_only_empty_final_content(+ content=payload_content,+ has_visible_streamed_text=has_visible_streamed_text,+ has_reasoning=has_reasoning,+ lang=str(+ get_config().get("preferred_language", "zh")+ ),)- durable_pending_final_chunks = []+ if filled != payload_content:+ data.payload["content"] = filled+ payload_content = filled+ logger.info(+ "[JiuWenSwarm] filled reasoning-only empty "+ "chat.final: request_id=%s "+ "had_visible_streamed_text=%s",+ rid,+ has_visible_streamed_text,+ )+ elif not str(payload_content or "").strip():+ logger.info(+ "[JiuWenSwarm] skipped reasoning-only empty "+ "chat.final fill: request_id=%s "+ "has_reasoning=%s had_visible_streamed_text=%s",+ rid,+ has_reasoning,+ has_visible_streamed_text,+ )+ # 主链 final 才结算父轮 durable;子流 final 不得掏空+ durable_pending_final_chunks = []if should_record and not _is_foreign_stream_source(data.payload):payload_dict = dict(data.payload)@@ -4023,7 +4149,9 @@ class JiuWenSwarm:)if et == "chat.final":durable_final_content = str(data.payload.get("content", ""))- if et == "chat.final":+ if et == "chat.final" and not frame_is_foreign:+ # CR#1:普通(未 suppress)路径同样不认子流 final——+ # 晚到的 foreign chat.final 否则会把父轮答案顶掉。final_answer_content = str(data.payload.get("content", ""))# History kept the merged body; strip wire so hosts# that already rendered chat.delta do not append again.@@ -4056,10 +4184,15 @@ class JiuWenSwarm:)payload_content = str(data.get("content", ""))- a2ui_split = None- if a2ui_probe_enabled and et in {"chat.delta", "chat.final"} and payload_content:- a2ui_split = _split_a2ui_stream_content(a2ui_stream_probe, payload_content)- a2ui_stream_probe = _extend_a2ui_stream_probe(a2ui_stream_probe, payload_content)+ # foreign 判定前置(CR#2,与 chunk 路同款)+ frame_is_foreign = _is_foreign_stream_source(data)+ a2ui_split, a2ui_stream_probe = _a2ui_probe_for_frame(+ a2ui_stream_probe,+ payload_content,+ event_type=et,+ enabled=a2ui_probe_enabled,+ foreign=frame_is_foreign,+ )if _should_defer_a2ui_processing_status(suppress_a2ui_stream=suppress_a2ui_stream,event_type=et,@@ -4074,8 +4207,10 @@ class JiuWenSwarm:if et == "chat.final":ensure_final_mode_inplace(data)if et == "chat.delta":- final_answer_chunks.append(payload_content)- if suppress_a2ui_stream or a2ui_split is not None:+ delta_is_foreign = frame_is_foreign+ if not delta_is_foreign:+ final_answer_chunks.append(payload_content)+ if _a2ui_suppress_should_engage(suppress_a2ui_stream, a2ui_split, delta_is_foreign):first_a2ui_suppression = not suppress_a2ui_streamif first_a2ui_suppression:logger.info(@@ -4108,7 +4243,9 @@ class JiuWenSwarm:)should_record = Falsecontinue- durable_pending_final_chunks.append(payload_content)+ # CR#3:子流 delta 不进父 durable 缓冲(与 chunk 路同款)+ if not delta_is_foreign:+ durable_pending_final_chunks.append(payload_content)should_record = Falseelif et == "chat.reasoning":if not _is_foreign_stream_source(data):@@ -4119,7 +4256,9 @@ class JiuWenSwarm:_persist_pending_final_text()final_answer_chunks = []elif et == "chat.final":- if suppress_a2ui_stream or a2ui_split is not None:+ if _a2ui_suppress_should_engage(+ suppress_a2ui_stream, a2ui_split, frame_is_foreign+ ):first_a2ui_suppression = not suppress_a2ui_streamif first_a2ui_suppression:logger.info(@@ -4131,8 +4270,11 @@ class JiuWenSwarm:if first_a2ui_suppression and not a2ui_pending_render_sent:yield _make_a2ui_pending_render_chunk(request_id=rid, channel_id=cid)a2ui_pending_render_sent = True- final_answer_content = payload_content- durable_pending_final_chunks = []+ # CR#1:foreign final 维持 withhold,但不得改写父轮+ # 被扣终稿与 durable 缓冲(与 chunk 路同款守卫)+ if not frame_is_foreign:+ final_answer_content = payload_content+ durable_pending_final_chunks = []continuehas_visible_streamed_text = bool("".join(final_answer_chunks).strip()@@ -4144,8 +4286,10 @@ class JiuWenSwarm:or str(data.get("reasoning_content") or "").strip())merged_from_deltas = False+ # CR#3:子流空 final 不得合并/掏空父轮 durableif (- not str(payload_content or "").strip()+ not frame_is_foreign+ and not str(payload_content or "").strip()and durable_pending_final_chunks):merged = "".join(durable_pending_final_chunks)@@ -4160,6 +4304,8 @@ class JiuWenSwarm:has_reasoning=has_reasoning,lang=str(get_config().get("preferred_language", "zh")),)+ if frame_is_foreign:+ filled = payload_content # 子流 final 不做 reasoning-only 补白if filled != payload_content:data["content"] = filledpayload_content = filled@@ -4179,7 +4325,9 @@ class JiuWenSwarm:has_reasoning,has_visible_streamed_text,)- durable_pending_final_chunks = []+ if not frame_is_foreign:+ # 主链 final 才结算父轮 durable+ durable_pending_final_chunks = []if should_record and not _is_foreign_stream_source(data):extra_fields = {@@ -4214,7 +4362,8 @@ class JiuWenSwarm:)if et == "chat.final":durable_final_content = str(data.get("content", ""))- if et == "chat.final":+ if et == "chat.final" and not frame_is_foreign:+ # CR#1:晚到的 foreign final 不得顶掉父轮答案final_answer_content = str(data.get("content", ""))if merged_from_deltas:data["content"] = ""@@ -4250,9 +4399,10 @@ class JiuWenSwarm:permission_reservation.release_if_unstarted()assistant_message = final_answer_content or "".join(final_answer_chunks)- repair_call = getattr(adapter, "repair_model_response", None)+ turn_adapter = await self._resolve_turn_adapter_for_finalize(adapter, request, session_id)+ repair_call = getattr(turn_adapter, "repair_model_response", None)retry_without_a2ui_call = self._make_retry_without_a2ui_call(- adapter=adapter,+ adapter=turn_adapter,request=request,)@@ -4264,6 +4414,17 @@ class JiuWenSwarm:repair_call=repair_call,retry_without_a2ui_call=retry_without_a2ui_call,)+ if suppress_a2ui_stream and not finalized_assistant_message and assistant_message:+ # suppress 已把原 chat.final 扣在手上(未上 wire),此处 finalized 若为空+ # (如适配器无模型可修、repair 返回 None 被强转空串——case #26 形态),+ # 下面的重发会被整体跳过,整块 a2ui 静默丢失、relay 落库只剩 probe 残留。+ # 兜底回退重发被扣的原始内容:即便 JSON 破损,relay 前端 replace_final+ # 覆写 + jsonrepair 仍有渲染机会,优于什么都不发。+ logger.warning(+ "A2UI finalized empty under suppression: request_id=%s falling back to raw stream content",+ rid or "",+ )+ finalized_assistant_message = assistant_messageif finalized_assistant_message and (finalized_assistant_message != assistant_message or suppress_a2ui_stream):diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 56bc3e5f8b..f51329083c 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -24081,7 +24081,11 @@ class JiuWenSwarmDeepAdapter:async def repair_model_response(self, prompt: str) -> str | None:"""Run a focused repair prompt using the currently selected chat model."""if self._model is None:- logger.warning("[JiuWenSwarmDeepAdapter] repair skipped: no model instance available")+ logger.warning(+ "[JiuWenSwarmDeepAdapter] repair skipped: no model instance available "+ "(cache_keys=%s default=%s)",+ list(self._model_cache)[:5], self._default_model_name or "<unset>",+ )return Nonefrom openjiuwen.core.foundation.llm.schema.message import UserMessagediff --git a/tests/unit_tests/a2ui/test_finalize_adapter_wiring.py b/tests/unit_tests/a2ui/test_finalize_adapter_wiring.pynew file mode 100644index 0000000000..7fc8cde0af--- /dev/null+++ b/tests/unit_tests/a2ui/test_finalize_adapter_wiring.py@@ -0,0 +1,405 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Wiring regression tests for the A2UI finalize repair/retry adapter.++repair_model_response 与 retry_without_a2ui 的方法体依赖 session-scoped adapter 上+由 create_instance 建立的 _model/_instance;_ensure_adapter 返回的 root facade 按+设计不构建实例(热更新仅级联 session adapter),两者挂在 root 上时 repair 全部被+skip、降级重答在 _instance 守卫处静默返回 None,a2ui 块最终被整块剥离、落库只剩+纯文本。finalize 接线必须先解析出真正执行本轮的 session adapter。++用例分两层:+- helper 级(解析分支/门控/链式契约)——覆盖 ``_resolve_turn_adapter_for_finalize``+ 自身语义;+- 生产接线点(``process_message_stream`` / ``process_message``)——驱动真实入口,+ 断言 repair/retry 两个回调确实绑定到 session adapter。缺了这层,接线回退成+ ``getattr(adapter, ...)`` 时全套件仍全绿,静默内容降级无法被检测。+"""++from types import SimpleNamespace++import pytest++from jiuwenswarm.server.runtime.agent_adapter.interface import JiuWenSwarm++VALID_A2UI_RESPONSE = """<a2ui-json>+[+ {+ "beginRendering": {+ "surfaceId": "wiring-test",+ "root": "root"+ }+ },+ {+ "surfaceUpdate": {+ "surfaceId": "wiring-test",+ "components": [+ {+ "id": "root",+ "component": {+ "Text": {+ "text": {+ "literalString": "Repaired form"+ }+ }+ }+ }+ ]+ }+ }+]+</a2ui-json>"""++INVALID_A2UI_RESPONSE = """Here is the form.+<a2ui-json>+[+ {+ "type": "beginRendering",+ "version": "0.8"+ }+]+</a2ui-json>"""+++class _FakeRootAdapter:+ def __init__(self, session_adapter=None, error: BaseException | None = None):+ self._session_adapter = session_adapter+ self._error = error+ self.calls: list[tuple] = []++ async def _get_or_create_session_adapter(self, session_id, request=None):+ self.calls.append((session_id, request))+ if self._error is not None:+ raise self._error+ return self._session_adapter+++async def _broken_repair(prompt: str):+ return None+++async def _working_repair(prompt: str):+ return SimpleNamespace(content=VALID_A2UI_RESPONSE)+++async def test_resolve_turn_adapter_returns_session_scoped_adapter():+ session = _FakeRootAdapter() # any object identity works as the session adapter+ root = _FakeRootAdapter(session_adapter=session)+ request = SimpleNamespace(request_id="req-1", channel_id="web")++ resolved = await JiuWenSwarm._resolve_turn_adapter_for_finalize(+ root, request, "sess-1"+ )++ assert resolved is session+ assert root.calls == [("sess-1", request)]+++async def test_resolve_turn_adapter_falls_back_to_root_when_lookup_raises():+ root = _FakeRootAdapter(+ session_adapter=SimpleNamespace(), error=RuntimeError("boom")+ )++ resolved = await JiuWenSwarm._resolve_turn_adapter_for_finalize(+ root,+ SimpleNamespace(request_id="req-2", channel_id="web"),+ "sess-2",+ )++ assert resolved is root+++async def test_resolve_turn_adapter_falls_back_without_session_id():+ root = _FakeRootAdapter(session_adapter=SimpleNamespace())++ resolved = await JiuWenSwarm._resolve_turn_adapter_for_finalize(+ root,+ SimpleNamespace(request_id="req-3", channel_id="web"),+ None,+ )++ assert resolved is root+ assert root.calls == []+++async def test_resolve_turn_adapter_returns_adapter_without_getter():+ adapter = SimpleNamespace()++ resolved = await JiuWenSwarm._resolve_turn_adapter_for_finalize(+ adapter,+ SimpleNamespace(request_id="req-4", channel_id="web"),+ "sess-4",+ )++ assert resolved is adapter+++async def test_finalize_repairs_invalid_block_via_resolved_session_adapter(monkeypatch):+ """链式契约:root 修不动(repair 恒 None),解析出的 session adapter 能修 → 终稿保留有效块。"""+ from jiuwenswarm.server.runtime.a2ui.runtime.response_finalization import (+ finalize_a2ui_assistant_content,+ )++ monkeypatch.setenv("JIUWENSWARM_A2UI_ENABLED", "true")++ session = SimpleNamespace(repair_model_response=_working_repair)+ root = SimpleNamespace(+ repair_model_response=_broken_repair,+ _get_or_create_session_adapter=_FakeRootAdapter(+ session_adapter=session+ )._get_or_create_session_adapter,+ )+ turn = await JiuWenSwarm._resolve_turn_adapter_for_finalize(+ root,+ SimpleNamespace(request_id="req-5", channel_id="web"),+ "sess-5",+ )++ result = await finalize_a2ui_assistant_content(+ INVALID_A2UI_RESPONSE,+ user_query="设备报修登记表单",+ request_id="req-5",+ repair_call=turn.repair_model_response,+ a2ui_enabled=True,+ )++ assert result == VALID_A2UI_RESPONSE+++async def test_resolve_turn_adapter_skips_non_a2ui_channel():+ """非 a2ui 渠道 finalize 会早退:不得解析 adapter,避免无意义的缓存查询与冷建。"""+ root = _FakeRootAdapter(session_adapter=SimpleNamespace())++ resolved = await JiuWenSwarm._resolve_turn_adapter_for_finalize(+ root,+ SimpleNamespace(request_id="req-6", channel_id="feishu"),+ "sess-6",+ )++ assert resolved is root+ assert root.calls == []+++async def test_resolve_turn_adapter_skips_channel_without_repair(monkeypatch):+ """a2ui 渠道但未启用服务端 repair 时同样早退,避免为一个不会使用的 repair 冷建。"""+ from jiuwenswarm.server.runtime.agent_adapter import interface as interface_module++ monkeypatch.setattr(interface_module, "should_finalize_repair", lambda _channel: False)+ root = _FakeRootAdapter(session_adapter=SimpleNamespace())++ resolved = await JiuWenSwarm._resolve_turn_adapter_for_finalize(+ root,+ SimpleNamespace(request_id="req-7", channel_id="web"),+ "sess-7",+ )++ assert resolved is root+ assert root.calls == []+++# ── 生产接线点锚定(检视意见:helper 级用例无法发现接线回退)────────────────────+# 上面 7 个用例只验证 ``_resolve_turn_adapter_for_finalize`` 本身或手工接线后的+# finalize 契约;把 interface.py 里两处生产接线回退成 ``getattr(adapter, ...)``+# 后全套件仍全绿——真实 bug(root facade 无实例,repair 恒 skip、retry 静默返回+# None,a2ui 块被整块剥皮)无法被检测。以下用例驱动真实入口+# (``process_message_stream`` / ``process_message``),断言 repair/retry 两个回调+# 都绑定到解析出的 session adapter:+# - repair:``__self__`` 必须是 session adapter(root 的 repair 恒不可修)+# - retry:真实调用一次,root 因 ``_instance is None`` 会静默返回 None,+# 能返回内容即证明闭包捕获的是带实例的 session adapter++_RETRY_CONTENT = "RETRY_WITHOUT_A2UI_OK"+++class _SessionAdapterProbe:+ """执行本轮的 session adapter:有实例,repair 与 retry 都可用。"""++ def __init__(self) -> None:+ self._instance = object()+ self.retried_queries: list[str] = []++ async def repair_model_response(self, _prompt: str):+ return SimpleNamespace(content=VALID_A2UI_RESPONSE)++ async def process_message_impl(self, _request, _inputs):+ self.retried_queries.append(_request.params.get("query"))+ return SimpleNamespace(ok=True, payload={"content": _RETRY_CONTENT})+++class _RootFacadeProbe:+ """``_ensure_adapter`` 返回的 root facade:按设计不自建实例。"""++ def __init__(self, session_adapter, frames: list[dict] | None = None) -> None:+ self._instance = None+ self._session_adapter = session_adapter+ self._frames = frames or []+ self.resolved_session_ids: list[str] = []++ async def _get_or_create_session_adapter(self, session_id, request=None, **kwargs):+ self.resolved_session_ids.append(session_id)+ return self._session_adapter++ async def repair_model_response(self, _prompt: str):+ return None++ async def handle_heartbeat(self, _request):+ return None++ async def process_message_stream_impl(self, request, _inputs):+ from jiuwenswarm.common.schema.agent import AgentResponseChunk++ for payload in self._frames:+ yield AgentResponseChunk(+ request_id=request.request_id,+ channel_id=request.channel_id,+ payload=dict(payload),+ is_complete=False,+ )++ async def process_message_impl(self, _request, _inputs):+ return SimpleNamespace(ok=True, payload={"content": "ROOT_RETRY_MUST_NOT_RUN"})+++def _web_request(*, is_stream: bool):+ from jiuwenswarm.common.schema.agent import AgentRequest+ from jiuwenswarm.common.schema.message import ReqMethod++ return AgentRequest(+ request_id="req-wiring",+ req_method=ReqMethod.CHAT_SEND,+ channel_id="web",+ session_id="session-wiring",+ params={"query": "生成表单", "mode": "agent"},+ is_stream=is_stream,+ )+++def _build_swarm(monkeypatch, root):+ from jiuwenswarm.server.runtime.agent_adapter import interface as interface_module++ swarm = interface_module.JiuWenSwarm()+ swarm._adapter = root+ swarm._sdk_name = "harness"+ monkeypatch.setattr(swarm, "_build_inputs", lambda request: ({}, "local", "生成表单"))+ monkeypatch.setattr(interface_module, "get_config", lambda: {"preferred_language": "zh"})+ monkeypatch.setattr(interface_module, "is_auto_memory_enabled", lambda *_a, **_k: False)+ monkeypatch.setattr(interface_module, "is_memory_enabled", lambda *_a, **_k: False)+ monkeypatch.setattr(interface_module, "_schedule_symphony_session_feedback", lambda *_a: None)+ monkeypatch.setattr(interface_module, "append_history_record", lambda **_k: None)+ monkeypatch.setattr(swarm, "_append_history_record", lambda **_k: None)+ return swarm+++def _capture_finalize(monkeypatch):+ """截获真实 finalize 调用,保留 repair/retry 回调供断言。"""+ from jiuwenswarm.server.runtime.agent_adapter import interface as interface_module++ captured: dict[str, object] = {}++ async def fake_finalize(content, **kwargs):+ captured.setdefault("repair_call", kwargs.get("repair_call"))+ captured.setdefault(+ "retry_without_a2ui_call", kwargs.get("retry_without_a2ui_call")+ )+ return content++ monkeypatch.setattr(+ interface_module, "finalize_assistant_response_if_a2ui", fake_finalize+ )+ return captured+++async def _assert_both_calls_bound_to_session(+ captured: dict[str, object], session, root+) -> None:+ repair_call = captured["repair_call"]+ retry_call = captured["retry_without_a2ui_call"]++ assert getattr(repair_call, "__self__", None) is session, (+ "repair 回调必须绑定到执行本轮的 session adapter(root facade 无实例,"+ f"repair 会恒 skip):实际 {getattr(repair_call, '__self__', None)!r}"+ )++ # root 的 _instance 为 None → retry 闭包会静默返回 None(静默内容降级)+ assert await retry_call("重答一次") == _RETRY_CONTENT, (+ "retry 回调必须走 session adapter;拿 root 时 _instance 守卫会静默返回 None"+ )+ assert session.retried_queries == ["重答一次"], (+ "retry 必须真正落到 session adapter 的 process_message_impl"+ )+++async def test_stream_entrypoint_wires_turn_adapter_for_repair_and_retry(monkeypatch):+ """生产接线点 1:``process_message_stream`` 收尾必须用 session adapter 组装回调。"""+ session = _SessionAdapterProbe()+ root = _RootFacadeProbe(+ session,+ frames=[+ {"event_type": "chat.delta", "content": "表单正文"},+ {"event_type": "chat.final", "content": "终稿"},+ ],+ )+ swarm = _build_swarm(monkeypatch, root)+ captured = _capture_finalize(monkeypatch)++ try:+ async for _ in swarm.process_message_stream(_web_request(is_stream=True)):+ pass+ finally:+ await swarm._session_manager.close_all_sessions()++ assert "session-wiring" in root.resolved_session_ids, (+ "finalize 时必须解析出本轮 session adapter"+ )+ await _assert_both_calls_bound_to_session(captured, session, root)+++async def test_unary_entrypoint_wires_turn_adapter_for_repair_and_retry(monkeypatch):+ """生产接线点 2:``process_message`` 非流式收尾同样必须用 session adapter。"""+ from jiuwenswarm.server.runtime.a2ui import integration as integration_module++ session = _SessionAdapterProbe()+ root = _RootFacadeProbe(session)+ swarm = _build_swarm(monkeypatch, root)+ captured = _capture_finalize(monkeypatch)++ # 绕过非流式路径上与本接线无关的前置(技能/插件/租户/配额/人脉附件)+ async def _noop(*_args, **_kwargs):+ return None++ monkeypatch.setattr(swarm, "_handle_skills_request", _noop)+ monkeypatch.setattr(swarm, "_handle_plugins_request", _noop)+ monkeypatch.setattr(swarm, "_materialize_enterprise_attachments", _noop)+ monkeypatch.setattr(swarm, "_append_ask_user_answered_history", lambda **_k: None)+ monkeypatch.setattr(swarm, "_bind_tenant_request_context", lambda *_a, **_k: (None, None))+ monkeypatch.setattr(+ swarm, "_reset_tenant_request_context", staticmethod(lambda *_a: None)+ )+ monkeypatch.setattr(+ integration_module, "reload_quota_policies_from_gateway_db", _noop, raising=False+ )++ async def fake_submit_and_wait(_session_id, _task):+ return SimpleNamespace(ok=True, payload={"content": "终稿"})++ monkeypatch.setattr(swarm._session_manager, "submit_and_wait", fake_submit_and_wait)++ try:+ await swarm.process_message(_web_request(is_stream=False))+ finally:+ await swarm._session_manager.close_all_sessions()++ assert "session-wiring" in root.resolved_session_ids, (+ "非流式 finalize 同样必须解析出本轮 session adapter"+ )+ await _assert_both_calls_bound_to_session(captured, session, root)+diff --git a/tests/unit_tests/a2ui/test_finalizer.py b/tests/unit_tests/a2ui/test_finalizer.pyindex 1591405862..f30304ea3c 100644--- a/tests/unit_tests/a2ui/test_finalizer.py+++ b/tests/unit_tests/a2ui/test_finalizer.py@@ -118,6 +118,58 @@ async def test_a2ui_finalizer_falls_back_after_failed_repairs():assert result == "Here is the UI."+async def test_a2ui_finalizer_treats_empty_repair_output_as_failure():+ """Empty repair output must never count as a valid repair.++ Regression for case #26 (2026-10-29): the adapter's repair_model_response+ returns None when no model instance is available; coercing that to "" used+ to pass ``validate_response("")`` vacuously (no blocks -> valid), so the+ finalizer reported status="repaired" with empty content. Downstream,+ interface.py skips the suppressed-final resend for falsy finalized content+ and the whole A2UI block is silently lost (persisted probe residue only).+ """+ from jiuwenswarm.server.runtime.a2ui.runtime.finalizer import A2UIResponseFinalizer++ calls: list[str] = []++ async def repair_call(prompt: str):+ calls.append(prompt)+ return SimpleNamespace(content="")++ result = await A2UIResponseFinalizer().finalize_result(+ INVALID_A2UI_RESPONSE,+ user_query="生成库存展示界面",+ request_id="req-finalizer-empty-repair",+ repair_call=repair_call,+ )++ # 空输出不得标成 repaired;应跑满 max_repair_attempts 后落 repair_failed+ assert result.status == "repair_failed"+ assert len(calls) == 2+ # 返回内容必须非空(基于原始内容可读降级),否则 suppress 下重发被跳过+ assert result.content.strip() != ""+++async def test_a2ui_finalizer_treats_none_repair_return_as_failure():+ """repair_call returning bare None (no model available) is a failed repair."""+ from jiuwenswarm.server.runtime.a2ui.runtime.finalizer import A2UIResponseFinalizer++ async def repair_call(prompt: str):+ return None++ result = await A2UIResponseFinalizer().finalize_result(+ INVALID_A2UI_RESPONSE,+ user_query="生成库存展示界面",+ request_id="req-finalizer-none-repair",+ repair_call=repair_call,+ )++ assert result.status == "repair_failed"+ assert result.content.strip() != ""++@pytest.mark.asyncioasync def test_a2ui_finalizer_leaves_plain_text_untouched():from jiuwenswarm.server.runtime.a2ui.runtime.finalizer import A2UIResponseFinalizerdiff --git a/tests/unit_tests/a2ui/test_foreign_stream_bookkeeping.py b/tests/unit_tests/a2ui/test_foreign_stream_bookkeeping.pynew file mode 100644index 0000000000..f7f42613ba--- /dev/null+++ b/tests/unit_tests/a2ui/test_foreign_stream_bookkeeping.py@@ -0,0 +1,176 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++# pylint: disable=protected-access++"""流级回归:嵌套流镜像帧不得改写父轮 bookkeeping(PR #9194 检视 CR-008/CR-010)。++helper 级用例(``_a2ui_probe_for_frame`` / ``_a2ui_suppress_should_engage``)无法+覆盖真实帧顺序;本文件用 fake adapter 把「父轮 delta → 子流 delta(含+``<a2ui-json>``)→ 父轮 tool_call → 父轮 final → 晚到子流 final」灌进+``JiuWenSwarm.process_message_stream``,断言收尾 ``assistant_message`` 与落库历史+都不含子流文本。用例覆盖三条守卫:++- CR#2:子流 marker 不得进入父轮 probe(否则下一条主链 delta 被误 suppress)。+- CR#3:子流 delta 不得进入 ``durable_pending_final_chunks``(否则 tool_call+ 会把子流文本写成父历史)。+- CR#1:晚到的子流 final 不得顶掉父轮 ``final_answer_content``。+"""++from __future__ import annotations++import pytest++from jiuwenswarm.common.schema.agent import AgentRequest, AgentResponseChunk+from jiuwenswarm.common.schema.message import ReqMethod+from jiuwenswarm.server.runtime.agent_adapter import interface as interface_module++# 与被测模块 _A2UI_PENDING_RENDER_DELTA 保持一致:suppress 触发时发出的占位帧内容+_PENDING_RENDER_DELTA = "<a2ui-json>\n"++_CHILD_SOURCE_ID = "member_1"+++class _ScriptedStreamAdapter:+ """按脚本逐帧 yield 的 fake adapter(payload 可带 stream_source_id 模拟子流镜像)。"""++ def __init__(self, frames: list[dict[str, str]]) -> None:+ self._frames = frames++ async def process_message_stream_impl(self, request: AgentRequest, _inputs: dict) -> object:+ for payload in self._frames:+ yield AgentResponseChunk(+ request_id=request.request_id,+ channel_id=request.channel_id,+ payload=dict(payload),+ is_complete=False,+ )+++def _build_swarm(monkeypatch: pytest.MonkeyPatch, frames: list[dict[str, str]]):+ swarm = interface_module.JiuWenSwarm()+ swarm._adapter = _ScriptedStreamAdapter(frames)+ swarm._sdk_name = "harness"+ monkeypatch.setattr(swarm, "_build_inputs", lambda request: ({}, "local", "生成表单"))+ monkeypatch.setattr(interface_module, "get_config", lambda: {"preferred_language": "zh"})+ monkeypatch.setattr(interface_module, "is_auto_memory_enabled", lambda *_args, **_kwargs: False)+ monkeypatch.setattr(interface_module, "is_memory_enabled", lambda *_args, **_kwargs: False)+ monkeypatch.setattr(interface_module, "_schedule_symphony_session_feedback", lambda *_args: None)+ monkeypatch.setattr(interface_module, "append_history_record", lambda **_kwargs: None)+ return swarm+++def _request() -> AgentRequest:+ return AgentRequest(+ request_id="req-foreign-stream",+ req_method=ReqMethod.CHAT_SEND,+ channel_id="web",+ session_id="session-foreign-stream",+ params={"query": "生成表单", "mode": "agent"},+ is_stream=True,+ )+++async def _collect(swarm, request: AgentRequest) -> list[AgentResponseChunk]:+ return [chunk async for chunk in swarm.process_message_stream(request)]+++async def test_foreign_mirror_frames_do_not_pollute_parent_round(monkeypatch):+ """CR#1/#2/#3 流级复现:子流帧全程不触碰父轮 probe、durable 与终稿。"""+ frames = [+ # 父轮第一段正文+ {"event_type": "chat.delta", "content": "父轮开头。"},+ # 子流镜像 delta:带 stream_source_id + a2ui marker(旧实现会污染父轮 probe)+ {+ "event_type": "chat.delta",+ "content": "子流 <a2ui-json>{\"beginRendering\": {}}</a2ui-json>",+ "stream_source_id": _CHILD_SOURCE_ID,+ },+ # 父轮第二段正文:若 probe 被污染,这里会被 split 误判 suppress+ {"event_type": "chat.delta", "content": "父轮继续。"},+ # 父轮工具调用:触发 _persist_pending_final_text(落库父轮已流出的正文)+ {"event_type": "chat.tool_call", "content": ""},+ # 父轮终稿+ {"event_type": "chat.final", "content": "父轮终稿。"},+ # 晚到的子流终稿:不得顶掉父轮答案+ {"event_type": "chat.final", "content": "子流终稿。", "stream_source_id": _CHILD_SOURCE_ID},+ ]+ swarm = _build_swarm(monkeypatch, frames)++ history: list[dict] = []+ monkeypatch.setattr(swarm, "_append_history_record", lambda **kwargs: history.append(kwargs))++ finalized_inputs: list[str] = []++ async def fake_finalize(content, **_kwargs):+ finalized_inputs.append(content)+ return content++ monkeypatch.setattr(+ interface_module, "finalize_assistant_response_if_a2ui", fake_finalize+ )++ try:+ chunks = await _collect(swarm, _request())+ finally:+ await swarm._session_manager.close_all_sessions()++ # 1. 收尾 assistant_message 是父轮终稿(子流文本不参与组装)+ assert finalized_inputs == ["父轮终稿。"]++ # 2. 父轮 tool_call 落库的是主链 delta;父轮 final 单独落库+ persisted_finals = [+ record["content"]+ for record in history+ if record.get("role") == "assistant" and record.get("event_type") == "chat.final"+ ]+ assert persisted_finals == ["父轮开头。父轮继续。", "父轮终稿。"]++ # 3. 任何历史记录都不含子流文本+ assert all("子流" not in str(record.get("content") or "") for record in history)++ # 4. 子流 marker 未触发 suppress:没有 probe 占位帧+ assert all(+ (chunk.payload or {}).get("content") != _PENDING_RENDER_DELTA for chunk in chunks+ )+++async def test_late_foreign_final_keeps_parent_answer_under_suppression(monkeypatch):+ """CR#1 补充:suppress 已激活时,晚到的子流 final 仍维持 withhold,但不改写父轮终稿。"""+ frames = [+ # 主链 marker 触发 suppress+ {"event_type": "chat.delta", "content": "表单如下:<a2ui-json>{\"beginRendering\": {}}</a2ui-json>"},+ # 父轮终稿先到(被扣住,不上 wire)+ {"event_type": "chat.final", "content": "父轮终稿。"},+ # 子流终稿晚到:旧实现会覆盖 final_answer_content+ {"event_type": "chat.final", "content": "子流终稿。", "stream_source_id": _CHILD_SOURCE_ID},+ ]+ swarm = _build_swarm(monkeypatch, frames)++ history: list[dict] = []+ monkeypatch.setattr(swarm, "_append_history_record", lambda **kwargs: history.append(kwargs))++ finalized_inputs: list[str] = []++ async def fake_finalize(content, **_kwargs):+ finalized_inputs.append(content)+ return content++ monkeypatch.setattr(+ interface_module, "finalize_assistant_response_if_a2ui", fake_finalize+ )++ try:+ chunks = await _collect(swarm, _request())+ finally:+ await swarm._session_manager.close_all_sessions()++ # 父轮终稿被扣住后由 finalize 收尾;晚到子流 final 不得顶上+ assert finalized_inputs == ["父轮终稿。"]++ # suppress 激活时仍会发占位帧(行为不变),但历史里不得出现子流文本+ assert any(+ (chunk.payload or {}).get("content") == _PENDING_RENDER_DELTA for chunk in chunks+ )+ assert all("子流" not in str(record.get("content") or "") for record in history)diff --git a/tests/unit_tests/a2ui/test_integration_bridge.py b/tests/unit_tests/a2ui/test_integration_bridge.pyindex 872b260ce6..eddfd16c6e 100644--- a/tests/unit_tests/a2ui/test_integration_bridge.py+++ b/tests/unit_tests/a2ui/test_integration_bridge.py@@ -240,7 +240,13 @@ def test_a2ui_pending_render_delta_stays_open():def test_a2ui_repaired_final_chunk_keeps_session_binding():- """The repaired final must replace the pending A2UI bubble in its session."""+ """The repaired final must replace the pending A2UI bubble in its session.++ §9.1 契约:重发帧带 a2ui_resend=True。suppress 期间 wire 上已流出+ 半截 `<a2ui` + probe 占位(relay 侧 delta 累积);降级终稿可能不含+ <a2ui-json> 标签,relay 的 replace_final 原本按标签门控不覆写,残片+ 会留在正文。带 a2ui_resend 标记即声明"这是权威终稿,无条件整段覆写"。+ """from jiuwenswarm.server.runtime.agent_adapter.interface import _make_a2ui_final_chunkchunk = _make_a2ui_final_chunk(@@ -254,6 +260,7 @@ def test_a2ui_repaired_final_chunk_keeps_session_binding():"event_type": "chat.final","session_id": "sess-a2ui","content": "<a2ui-json>[]</a2ui-json>",+ "a2ui_resend": True,}@@ -393,15 +400,13 @@ async def test_finalize_assistant_response_if_a2ui_bypasses_non_web_channel(monk@pytest.mark.asyncio-async def test_finalize_officeclaw_skips_server_side_repair_and_resend(monkeypatch):- """officeclaw (relay-claw) must NOT run server-side A2UI repair/retry/resend.-- officeclaw completely skips server-side finalize (including validation) — no- repair, no retry, no resend. Broken a2ui content is passed through as-is;- the frontend does text degradation display (extractTextFromMalformedA2UI- regex salvage + invalidA2UIFallback fixed error text — degradation, not- JSON repair). Skipping entirely eliminates the timing issue (resend- frame after terminal) and the duplicate-block concern.+async def test_finalize_officeclaw_runs_server_side_repair_and_resend(monkeypatch):+ """officeclaw (relay-claw) now runs server-side A2UI repair/retry/resend.++ officeclaw 启用 probe + suppress + repair(与 web 对齐)。suppress 扣住原 chat.final+ + 改写 is_complete,relay-claw 不 break;relay-claw 前端已部署 chat.final a2ui+ replace_final 覆写(patchMessage({content}=finalized)),覆写掉 delta 累积的+ <a2ui 前半 + probe 污染。repair 修复破损 JSON,发送 finalized(前端首次收到)。"""import types@@ -446,13 +451,39 @@ async def test_finalize_officeclaw_skips_server_side_repair_and_resend(monkeypatretry_without_a2ui_call=retry_without_a2ui_call,)+ # officeclaw 现在走 repair(不再跳过)+ # fake_finalize 原样返回入参,result 应等于 broken_a2uiassert result == broken_a2ui- assert config_calls == []- assert finalize_calls == []+ assert config_calls == [1]+ assert len(finalize_calls) == 1+ # repair_call / retry_without_a2ui_call 传给 finalize 守卫,未被直接调用(fake_finalize 短路)+ # 但列表不应有遗漏的意外调用assert repair_calls == []assert retry_calls == [][email protected]("channel,expected", [+ ("web", True),+ ("officeclaw", True),+ ("feishu", False),+ (None, False),+])+def test_a2ui_probe_channel_whitelist(channel, expected):+ """白名单回归保护:officeclaw 启用 probe 后不可被误改回去。"""+ assert integration.is_a2ui_probe_channel(channel) is expected++[email protected]("channel,expected", [+ ("web", True),+ ("officeclaw", True),+ ("feishu", False),+ (None, False),+])+def test_finalize_repair_whitelist(channel, expected):+ """白名单回归保护:officeclaw 启用 repair 后不可被误改回去。"""+ assert integration.should_finalize_repair(channel) is expected++@pytest.mark.asyncioasync def test_finalize_web_still_runs_server_side_repair(monkeypatch):"""web must keep running server-side A2UI repair/retry/resend (regression guard)."""@@ -548,3 +579,83 @@ def test_partial_marker_triggers_on_long_dataModel_prefix():)assert _looks_like_partial_a2ui_marker("content\ndataModel") is True+++def test_suppress_engage_ignores_foreign_frames():+ """Nested-stream mirror frames must never engage the parent's suppression.++ Regression: a member/skill-node delta whose mirrored text carries a2ui+ markers used to trip the parent state machine — withholding the parent's+ stream, emitting a spurious render probe and mixing child text into the+ finalized answer.+ """+ from jiuwenswarm.server.runtime.agent_adapter.interface import (+ _a2ui_suppress_should_engage,+ )++ # Main-chain marker frame engages first-time suppression; foreign does not.+ assert _a2ui_suppress_should_engage(False, ("prefix", "rest"), False) is True+ assert _a2ui_suppress_should_engage(False, ("prefix", "rest"), True) is False+ # No marker: nobody engages.+ assert _a2ui_suppress_should_engage(False, None, False) is False+ # Once the parent is suppressing, every frame stays withheld (flag belongs+ # to the parent turn, not the frame that set it).+ assert _a2ui_suppress_should_engage(True, None, True) is True+++def test_foreign_source_predicate_semantics():+ """chat.delta guards must use the same foreign predicate as reasoning/tool_call."""+ from jiuwenswarm.server.runtime.agent_adapter.interface import (+ _is_foreign_stream_source,+ )++ assert _is_foreign_stream_source({"stream_source_id": "node-7"}) is True+ assert _is_foreign_stream_source({"stream_source_id": "main"}) is False+ assert _is_foreign_stream_source({}) is False+ assert _is_foreign_stream_source(None) is False+++# ── CR 三连击回归(renquanjia 2026-10-29 #1/#2/#3):foreign 判定必须前置到+# probe/split 之前,子流 marker 不得进入父轮 probe 窗口;engage/durable/normal+# 各路径的父轮 bookkeeping(final_answer_content/durable 缓冲)不得被子流帧改写。++def test_probe_frame_gate_skips_foreign_frames():+ """CR#2 回归:foreign 帧不得扩展父轮 probe、不得产出 split。++ 旧序:split+extend 先算、foreign 后判——子流 chat.delta 含 <a2ui-json> 时+ marker 滞留父轮 probe(512B 窗口),下一条主链帧 combined=probe+content+ 命中 marker_start<=content_start → split=("",content) → 主链被误 suppress、+ 扣发文本、发 spurious 占位帧。+ """+ from jiuwenswarm.server.runtime.agent_adapter.interface import _a2ui_probe_for_frame++ split, probe = _a2ui_probe_for_frame(+ probe="ok ", content="前文", event_type="chat.delta", enabled=True, foreign=True,+ )+ assert split is None+ assert probe == "ok " # 子流帧完全不接触父轮 probe++ # foreign 的 marker 帧同样不进 probe+ split, probe = _a2ui_probe_for_frame(+ probe="", content="hello <a2ui-json>", event_type="chat.delta", enabled=True, foreign=True,+ )+ assert split is None+ assert probe == ""++ # 主链帧行为不变:marker 产出 split 且 probe 累积+ split, probe = _a2ui_probe_for_frame(+ probe="", content="hello <a2ui-json>", event_type="chat.delta", enabled=True, foreign=False,+ )+ assert split is not None+ assert "<a2ui-json>" in probe+++def test_suppress_engage_gate_semantics_unchanged():+ """gate 分工锚定:suppress 激活后 foreign 帧仍 withhold(True),+ 未激活时仅非 foreign 且有 split 才 engage。父轮 bookkeeping 守卫在调用点,+ 若未来把 withhold 与 bookkeeping 合并回 gate,本用例会以语义变化提醒。"""+ from jiuwenswarm.server.runtime.agent_adapter.interface import _a2ui_suppress_should_engage++ assert _a2ui_suppress_should_engage(True, None, True) is True # suppress 后 foreign 维持扣发+ assert _a2ui_suppress_should_engage(False, ("", "x"), True) is False # 未激活时 foreign 不 engage+ assert _a2ui_suppress_should_engage(False, ("", "x"), False) is Truediff --git a/tests/unit_tests/a2ui/test_response_finalization.py b/tests/unit_tests/a2ui/test_response_finalization.pyindex ddcb34808b..c7a0790f29 100644--- a/tests/unit_tests/a2ui/test_response_finalization.py+++ b/tests/unit_tests/a2ui/test_response_finalization.py@@ -107,6 +107,39 @@ async def test_finalize_a2ui_assistant_content_repairs_parseable_invalid_responsassert len(repair_prompts) == 1+async def test_finalize_a2ui_assistant_content_never_returns_empty_when_repair_unavailable(monkeypatch):+ """Regression for case #26 (2026-10-29): officeclaw stream finalize.++ When the adapter has no model instance, repair_call returns None. That used+ to coerce to "" and validate vacuously as "repaired", making the entry+ return empty content. interface.py then skips the suppressed-final resend+ and the persisted assistant message keeps only the probe residue+ (prose + "<a2ui<a2ui-json>"), silently dropping the whole form.++ The entry must always return non-empty content so the resend path fires.+ """+ from jiuwenswarm.server.runtime.a2ui.runtime.response_finalization import finalize_a2ui_assistant_content++ monkeypatch.setenv("JIUWENSWARM_A2UI_ENABLED", "true")++ async def repair_call(prompt: str):+ return None++ result = await finalize_a2ui_assistant_content(+ INVALID_A2UI_RESPONSE,+ user_query="帮我做订机票和订酒店两个表单",+ request_id="req-repair-unavailable",+ repair_call=repair_call,+ a2ui_enabled=True,+ )++ assert isinstance(result, str)+ assert result.strip() != ""+ # 降级不得保留破损协议块(前端会把它当正文/污染)+ assert "<a2ui-json>" not in result++@pytest.mark.asyncioasync def test_finalize_a2ui_assistant_content_leaves_valid_response_unchanged(monkeypatch):from jiuwenswarm.server.runtime.a2ui.runtime import response_finalization