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
兼容relay-claw集成a2ui,优化a2ui提示词提高触发率
shenmuxia6ae20226309
diff --git a/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py b/jiuwenswarm/agents/harness/common/prompt/prompt_builder.pyindex 4e10de1237..8ce4dd7ab0 100644--- a/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py+++ b/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py@@ -28,6 +28,7 @@ class PromptPriority(IntEnum):TODO = 85# thinking_discipline 紧挨最终可见回复之前:思考与 tool_calls 职责分工,高于 RESPONSE。THINKING_DISCIPLINE = 115+ A2UI_BOOST = 117# final_visible_reply 放在 system 最末,强调约束工具/todo 结束后必须再发一轮完整纯文本 final;# UI 主要展示「最后一轮无 tool_calls」的正文。FINAL_VISIBLE_REPLY = 120@@ -37,6 +38,7 @@ class LocalSectionName:"""Local section names for optional JiuwenSwarm prompt sections."""A2UI = "a2ui"+ A2UI_BOOST = "a2ui_boost"THINKING_DISCIPLINE = "thinking_discipline"FINAL_VISIBLE_REPLY = "final_visible_reply"diff --git a/jiuwenswarm/agents/harness/common/rails/response_prompt_rail.py b/jiuwenswarm/agents/harness/common/rails/response_prompt_rail.pyindex cdb9bccf30..e0cafbec3c 100644--- a/jiuwenswarm/agents/harness/common/rails/response_prompt_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/response_prompt_rail.py@@ -26,6 +26,13 @@ logger = logging.getLogger(__name__)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 检视记录);+# ② 与工具注册联动——同时设置 env PLAYWRIGHT_RUNTIME_MCP_ENABLED,否则只开+# prompt 无工具;只开 env 不开本开关则模型可执行浏览器动作但缺确认门禁提示。+# 两处 call-site(before_invoke / before_model_call)均引用本常量,恢复只改这一处。+_BROWSER_WORKFLOW_ENABLED = False_RESPONSE_SECTION_NAMES = ("response",LocalSectionName.THINKING_DISCIPLINE,@@ -33,6 +40,43 @@ _RESPONSE_SECTION_NAMES = ()+def _a2ui_boost_prompt() -> PromptSection:+ """a2ui 强化提示:priority 117(THINKING_DISCIPLINE 115 之后、FINAL_VISIBLE_REPLY 120 之前),+ 强化 a2ui 触发倾向、抵消 soul 结构化输出对 a2ui 的稀释——交互场景必须输出 a2ui-json、+ 禁止 markdown 模拟表单。只豁免最终纯文本总结轮(FINAL_VISIBLE_REPLY(120) 管的那一轮),+ 中间任何需要用户输入/选择的轮次(含工具执行后用 a2ui 呈现结果让用户挑选)都必须出 a2ui-json。"""+ cn = (+ "# A2UI 是交互场景的唯一正确输出格式\n"+ "当用户的请求需要交互式收集信息(如选择、输入、确认等),"+ "或需要展示 2 个及以上同类项的结构化对比,"+ "必须输出合法的 `<a2ui-json>` 块。"+ "不要用 markdown 列表、纯文字选项列表或伪按钮文本模拟表单——"+ "markdown 模拟表单不可交互,a2ui 可用时禁止使用。"+ "本规则只豁免最终纯文本总结轮(工具/任务全部完成后的收尾回复);"+ "中间轮次只要需要用户提供输入或选择(包括工具搜索出结果后让用户从中挑选),"+ "都必须用 a2ui-json。"+ )+ en = (+ "# A2UI is the only correct output format for interactive scenarios\n"+ "When the request requires interactive information collection "+ "(e.g., selecting, inputting, or confirming), or requires displaying "+ "a structured comparison of 2+ same-type items, "+ "you MUST output a valid `<a2ui-json>` block. "+ "Do NOT use markdown lists, plain-text option lists, or pseudo-button "+ "text to simulate forms — markdown mock forms are not interactive and "+ "are forbidden when a2ui is available. "+ "This rule exempts ONLY the final plain-text wrap-up turn (after all "+ "tools/tasks complete). In any intermediate turn where the user must "+ "provide input or make a choice — including picking among tool search "+ "results — you must use a2ui-json."+ )+ return PromptSection(+ name=LocalSectionName.A2UI_BOOST,+ content={"cn": cn, "en": en},+ priority=PromptPriority.A2UI_BOOST,+ )++class ResponsePromptRail(DeepAgentRail):"""Inject response format, thinking discipline, and final-reply rules."""@@ -51,6 +95,7 @@ class ResponsePromptRail(DeepAgentRail):for name in _RESPONSE_SECTION_NAMES:self.system_prompt_builder.remove_section(name)self.system_prompt_builder.remove_section(LocalSectionName.A2UI)+ self.system_prompt_builder.remove_section(LocalSectionName.A2UI_BOOST)self.system_prompt_builder = Noneself._runtime_channel = None@@ -73,7 +118,7 @@ class ResponsePromptRail(DeepAgentRail):else getattr(inputs, "query", None))extra[A2UI_BROWSER_WORKFLOW_CONTEXT_KEY] = (- is_a2ui_browser_workflow_request(query)+ _BROWSER_WORKFLOW_ENABLED and is_a2ui_browser_workflow_request(query))async def before_model_call(self, ctx: AgentCallbackContext) -> None:@@ -87,7 +132,7 @@ class ResponsePromptRail(DeepAgentRail):self._sync_a2ui_prompt_section(self._resolve_channel(ctx),skip_a2ui=self._should_skip_a2ui(ctx),- include_browser_workflows=self._is_browser_workflow(ctx),+ include_browser_workflows=_BROWSER_WORKFLOW_ENABLED and self._is_browser_workflow(ctx),identity=(self._resolve_context_value(ctx, "request_id"),(@@ -183,6 +228,7 @@ class ResponsePromptRail(DeepAgentRail):if not injected:self.system_prompt_builder.remove_section(LocalSectionName.A2UI)+ self.system_prompt_builder.remove_section(LocalSectionName.A2UI_BOOST)else:self.system_prompt_builder.add_section(PromptSection(@@ -200,6 +246,19 @@ class ResponsePromptRail(DeepAgentRail):priority=PromptPriority.A2UI,))+ # a2ui 强化(boost):仅 officeclaw 注入(officeclaw 的 system prompt 含+ # 性格描述,会引导模型走结构化输出而非 a2ui,需对冲)。priority 117+ # (THINKING_DISCIPLINE 115 之后、FINAL_VISIBLE_REPLY 120 之前),+ # 引导交互场景走 a2ui-json 而非 ask_user/markdown 模拟。+ is_officeclaw = str(channel or "").strip().lower() == "officeclaw"+ if is_officeclaw:+ self.system_prompt_builder.add_section(+ _a2ui_boost_prompt()+ )+ else:+ self.system_prompt_builder.remove_section(+ LocalSectionName.A2UI_BOOST+ )logger.info("A2UI prompt decision: request_id=%s conversation_id=%s "diff --git a/jiuwenswarm/channels/web/frontend/package-lock.json b/jiuwenswarm/channels/web/frontend/package-lock.jsonindex a3824b23da..bec3742928 100644--- a/jiuwenswarm/channels/web/frontend/package-lock.json+++ b/jiuwenswarm/channels/web/frontend/package-lock.json@@ -26,6 +26,7 @@"@codemirror/legacy-modes": "6.5.3","@codemirror/state": "6.7.1","@codemirror/view": "6.43.7",+ "@fontsource/material-symbols-outlined": "^5.3.9","@shikijs/langs": "^4.3.1","@tailwindcss/typography": "^0.5.19","@tanstack/react-virtual": "^3.14.9",@@ -1354,6 +1355,15 @@"integrity": "sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ==","license": "MIT"},+ "node_modules/@fontsource/material-symbols-outlined": {+ "version": "5.3.9",+ "resolved": "https://registry.npmjs.org/@fontsource/material-symbols-outlined/-/material-symbols-outlined-5.3.9.tgz",+ "integrity": "sha512-rPyajEu+UBQvAN78nnlvIReUtHAdaTMlNsrY5uFqf0eu+B9CYScof7AGy1hjF5jq3xARBGbdG9WVpuOi+nJhuQ==",+ "license": "OFL-1.1",+ "funding": {+ "url": "https://github.com/sponsors/ayuhito"+ }+ },"node_modules/@humanwhocodes/config-array": {"version": "0.13.0","resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz",diff --git a/jiuwenswarm/channels/web/frontend/package.json b/jiuwenswarm/channels/web/frontend/package.jsonindex 46d0df72c0..342ef6d071 100644--- a/jiuwenswarm/channels/web/frontend/package.json+++ b/jiuwenswarm/channels/web/frontend/package.json@@ -89,6 +89,7 @@"@codemirror/legacy-modes": "6.5.3","@codemirror/state": "6.7.1","@codemirror/view": "6.43.7",+ "@fontsource/material-symbols-outlined": "^5.3.9","@shikijs/langs": "^4.3.1","@tailwindcss/typography": "^0.5.19","@tanstack/react-virtual": "^3.14.9",diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/rendererRegistry.tsx b/jiuwenswarm/channels/web/frontend/src/features/a2ui/rendererRegistry.tsxindex c4609826a4..369d0bcb00 100644--- a/jiuwenswarm/channels/web/frontend/src/features/a2ui/rendererRegistry.tsx+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/rendererRegistry.tsx@@ -2,6 +2,10 @@import type { ComponentType } from 'react';import { A2UIRenderer, ComponentRegistry } from '@a2ui/react';+// Material Symbols Outlined 字体(@fontsource 静态切片 latin-400):@a2ui/react 的 Icon+// 组件靠字体连字(ligature)把 "favorite" 等名称渲染为图标;宿主缺字体时连字不生效,+// 界面显示裸文字。静态切片随包自带,离线可用。放在注册表模块与消费方同处归置。+import '@fontsource/material-symbols-outlined/latin-400.css';import { A2UI_PROTOCOL_VERSION, type A2UIProtocolVersion } from './a2uiContent';import { CheckBoxWithDefaults } from './CheckBoxWithDefaults';import { DateTimeInputWithDefaults } from './DateTimeInputWithDefaults';diff --git a/jiuwenswarm/channels/web/frontend/src/main.tsx b/jiuwenswarm/channels/web/frontend/src/main.tsxindex ef0b135e33..dc97a67db1 100644--- a/jiuwenswarm/channels/web/frontend/src/main.tsx+++ b/jiuwenswarm/channels/web/frontend/src/main.tsx@@ -11,6 +11,9 @@ import './styles/foundation.css'import './styles/themes/default/light.css'import './index.css'import './features/a2ui/a2ui.css'+// Material Symbols Outlined 字体 import 已移至 features/a2ui/rendererRegistry.tsx+// (与 Icon 渲染的消费方同处归置,对齐 relay-claw 侧结构;当前前端 a2ui 为静态引入链,+// 字体仍在主 bundle,未来若做 a2ui 懒加载可随 chunk 一起拆出)import { getApiPrefix, resolveApiUrl } from './utils/env';/*** 安装全局 fetch 拦截器:配置了 VITE_API_PREFIX 时,自动为指向同源的相对路径请求diff --git a/jiuwenswarm/server/runtime/a2ui/integration.py b/jiuwenswarm/server/runtime/a2ui/integration.pyindex 370205ba57..37782a0518 100644--- a/jiuwenswarm/server/runtime/a2ui/integration.py+++ b/jiuwenswarm/server/runtime/a2ui/integration.py@@ -26,10 +26,42 @@ _A2UI_CONFIG_DEFAULT_PAYLOAD: dict[str, str] = {_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"})+def is_a2ui_channel(channel: str | None) -> bool:"""Return whether the channel can natively run A2UI."""- return str(channel or "").strip().lower() == _A2UI_CHANNEL_ID+ return str(channel or "").strip().lower() in _A2UI_CHANNEL_IDS+++def is_a2ui_probe_channel(channel: str | None) -> bool:+ """Return whether the channel consumes A2UI streaming probe (pending render) chunks."""+ 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"})+++def should_finalize_repair(channel: str | None) -> bool:+ """Return whether the channel runs server-side A2UI repair/retry/resend."""+ return str(channel or "").strip().lower() in _A2UI_FINALIZE_REPAIR_CHANNEL_IDSdef _to_bool(value: Any) -> bool:@@ -71,15 +103,27 @@ def build_user_prompt_if_a2ui_event(Returns ``None`` when the payload is not an A2UI client event or when A2UI isdisabled, allowing the normal user prompt builder to continue unchanged.+ client_event 形态但被渠道/开关门控挡下时留 warning:此时 dict 会走普通+ prompt 路径被 json.dumps 进提示词(模型可解读但非成品 prompt),日志便于定位+ 前后端开关不一致(如 env 单侧强开、YAML truthy 变体、关开关瞬间的竞态)。"""+ if not isinstance(content, dict) or content.get("type") != "a2ui.client_event":+ return None+if not is_a2ui_channel(channel):+ logger.warning(+ "A2UI client event received on non-a2ui channel %r; "+ "falling back to raw-dict prompt (channel gate)",+ channel,+ )return Nonea2ui_config = _get_runtime_a2ui_config()if not a2ui_config.enabled:- return None-- if not isinstance(content, dict) or content.get("type") != "a2ui.client_event":+ logger.warning(+ "A2UI client event received while a2ui disabled; "+ "falling back to raw-dict prompt (feature gate)",+ )return Nonereturn _build_a2ui_client_event_prompt(content, channel, language)@@ -98,6 +142,13 @@ 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 修复)。+ if not should_finalize_repair(channel):+ return content+try:a2ui_config = _get_runtime_a2ui_config()except Exception:diff --git a/jiuwenswarm/server/runtime/a2ui/prompt_instructions.py b/jiuwenswarm/server/runtime/a2ui/prompt_instructions.pyindex 099ef16de3..c598f7eb89 100644--- a/jiuwenswarm/server/runtime/a2ui/prompt_instructions.py+++ b/jiuwenswarm/server/runtime/a2ui/prompt_instructions.py@@ -185,135 +185,160 @@ def build_a2ui_browser_workflow_instruction() -> str:def build_a2ui_autonomy_instruction(language: str = "en") -> str:- template_binding_rule_en = (- " For repeated list/card data, use A2UI template binding correctly: "- "Duplicate dataModelUpdate keys are invalid. Encode arrays as one "- 'collection key with indexed valueMap entries such as "0", "1", where '- "each item contains its own nested valueMap fields. Inside template "- "components, use item-relative paths like 'name', 'price', or "- "'/item/name' for Text, Image, and Button.action.context values; do not "- "use collection-absolute paths such as '/phones/name' inside templates. "- "Do not nest templates inside template-rendered components in A2UI 0.8; "- "flatten repeated item details into fields on the outer item, or use "- "explicit child components that bind to those fields."- )+ # --- en rules ---image_url_rule_en = (- " Do not invent image URLs. If external facts or images are needed, use "- "the available tools briefly, then converge to the final A2UI response. "- "Use a user-provided HTTPS URL or a verified stable source URL; do not "- "use guessed upload.wikimedia.org thumbnail paths."- )- icon_font_rule_en = (- " The host app may not have the Material Symbols icon font available. "- "Avoid A2UI Icon for semantic content such as product or status icons; "- "use Text literalString emoji or text labels instead so ligature fallback "- "text does not appear."+ " Do not invent image URLs. Use user-provided HTTPS URLs or verified "+ "stable sources; do not use guessed upload.wikimedia.org thumbnail paths.")unsupported_component_rule_en = (- " A2UI 0.8 does not support modal, dialog, popup, alert, toast, "- "floating overlay, or closeable window components. Do not simulate these "- "with absolute-positioned cards or fake close buttons. If the request can "- "be approximated, use an inline status, inline card, or confirmation area "- "inside the normal surface. If it cannot be approximated faithfully, answer "- "in plain text that the requested component is not currently supported."+ " A2UI does not support modal, dialog, popup, alert, toast, "+ "or floating overlay. Do not simulate these with absolute-positioned "+ "cards or fake close buttons. Use inline status, inline card, or "+ "confirmation area inside the normal surface instead. If the request "+ "cannot be approximated faithfully, answer in plain text that the "+ "requested component is not currently supported.")autonomy_rule_en = (- " A2UI is optional. Use A2UI only when a generated interface improves "- "the user's experience over plain text. Do not force A2UI for greetings, "- "short explanations, simple factual answers, or unstructured prose. Good "- "A2UI candidates include information collection forms, actionable "- "confirmations, multi-result comparison, object detail views, media-rich "- "cards, dashboards/status/inventory/task summaries, and tool-result "- "presentations. For real-world recommendation, comparison, shopping, "- "ranking, price, travel, restaurant, or product requests, use tools first "- "when available, then decide whether A2UI is the best final presentation. "- "If the user already provided complete structured data or asks for a demo, "- "you may render directly without tools. Never write tool_call, invoke, or "- "function-call tags as plain text."+ " When the user's request requires interactive information collection "+ "(e.g., selections, input, or confirmations), or requires displaying "+ "structured comparison of 2+ same-type items (e.g., multiple "+ "hotels/options/products/routes), prefer A2UI. "+ "Output format decision (execute before every reply) — judge in this "+ "order, first match wins, stop: "+ "1. Reply needs to collect user input (select/fill/confirm) → MUST A2UI; "+ "2. Reply contains 2+ same-type items in parallel comparison → MUST A2UI; "+ "3. Reply is a single narrative explanation, brief fact, or greeting → plain text. "+ "Fallback: when a reply matches multiple rules, prefer the more structured format "+ "(A2UI > plain text). "+ "A2UI typical scenarios: information collection forms, actionable "+ "confirmations, multi-result comparison, and tool-result presentations. "+ "For real-world recommendation, comparison, "+ "shopping, ranking, price, travel, restaurant, or product requests, "+ "use tools first when available, then decide whether A2UI is the best "+ "final presentation. If the user already provided complete structured "+ "data or asks for a demo, you may render directly without tools. "+ "Capability boundary FIRST: even when you cannot execute the final "+ "action (no browser agent, no Gmail/social/tax login, no payment), if "+ "the user needs you to collect structured intent (options/fields/"+ "preferences/quantities), you MUST render an A2UI form to "+ "gather it — never fall back to Markdown text questions or ask_user "+ "rounds just because you cannot execute. The collected data can "+ "produce a checklist/draft/plan for the user to act on externally. "+ "When collecting multiple structured fields, use one A2UI form "+ "(parallel collection) instead of ask_user rounds. "+ "CRITICAL — must emit a2ui-json, not markdown mock forms: "+ "when the above decision tree conditions are met, you MUST output a "+ "valid <a2ui-json> block. Do NOT simulate a form with markdown "+ "lists, plain-text option lists, or pseudo-button text. Markdown mock "+ "forms are NOT interactive and are FORBIDDEN when A2UI is available. "+ "If you catch yourself writing option lists or button text as plain "+ "text, STOP and emit a2ui-json instead. "+ "Never write tool_call, invoke, or function-call tags as plain text.")requested_component_rule_en = (- " You must match the requested component type: for an input box or "- "text field request, generate TextField/Form UI; generate a card list "- "only when the user asks for cards or a card list. Card/list UI is "- "not a universal fallback. For a single object detail request, build a "- "single object detail layout, not a multi-card demo. Do not substitute a "- "fixed demo for the requested component. For any user-editable "- "TextField, bind TextField.text to a data model path, initialize that "- "path with dataModelUpdate, and include the submitted value in "- "Button.action.context using a path reference. Do not emit an empty "- "Button.action.context for form submissions."- + template_binding_rule_en+ " You must match the requested component type: generate a card list "+ "only when the user asks for cards or a card list; Card/list is not "+ "a universal fallback. For a single object detail request, build a "+ "single object detail layout, not a multi-card demo. Do not substitute "+ "a fixed demo for the requested component. For every user-editable "+ "interactive component — TextField, MultipleChoice, CheckBox, "+ "DateTimeInput, and Slider — bind its value/selections to a data "+ "model path, initialize that path with dataModelUpdate, and include "+ "the submitted value in Button.action.context using a path reference. "+ "Use DateTimeInput (not TextField) for any date or time selection "+ "field. Do not emit an empty Button.action.context for form submissions. "+ "Button MUST use \"child\" to reference a component id (e.g. a Text "+ "component) for its label content; do NOT use a \"label\" field. "+ "For MultipleChoice, selections MUST be an object with a "+ "\"path\" key (e.g. selections={\"path\":\"/form/cabinClass\"}) and "+ "the default selection MUST be provided via dataModelUpdate on that "+ "path. "+ "MultipleChoice option values MUST NOT share a name with ANY component id "+ "(e.g. if a component id is \"anonymous\", use option value \"anon\" not \"anonymous\" — "+ "matching a component id causes circular dependency). "+ "No Button.action.context \"key\" may equal ANY component id in the same surface. "+ "For repeated list/card data, encode arrays as one collection key "+ "with indexed valueMap entries (\"0\", \"1\"); each item contains "+ "nested valueMap fields. Use item-relative paths inside templates "+ "(name, price, or /item/name). Do not nest templates inside "+ "template-rendered components in A2UI; flatten repeated item "+ "details into fields on the outer item, or use explicit child "+ "components bound to those fields."+ image_url_rule_en- + icon_font_rule_en+ unsupported_component_rule_en)-- template_binding_rule_zh = (- " 使用 List 或卡片列表展示重复数据时,dataModelUpdate 的 key 不能重复。"- "请把数组编码为一个集合 key,并在 valueMap 中使用 \"0\"、\"1\" 这类索引项;"- "每个 item 包含自己的嵌套 valueMap 字段。模板组件和 Button.action.context "- "内使用 item-relative path,例如 name、price 或 /item/name;"- "不要在模板内使用 /phones/name 这类集合绝对路径。A2UI 0.8 不要在模板渲染出的"- "组件内部再嵌套 template;请把重复 item 的明细拍平成外层 item 字段,或使用显式"- "子组件绑定这些字段。"- )+ # --- zh rules ---image_url_rule_zh = (- " 不要编造图片 URL。如果需要外部事实或图片,可以短暂使用可用工具,"- "随后必须收敛到最终 A2UI 响应。使用用户提供的 HTTPS URL "- "或已验证的稳定来源 URL;不要使用猜测出来的 upload.wikimedia.org thumbnail 路径。"+ " 不要编造图片 URL。使用用户提供的 HTTPS URL 或已验证的稳定来源;"+ "不要使用猜测的 upload.wikimedia.org thumbnail 路径。")unsupported_component_rule_zh = (- " A2UI 0.8 不支持弹窗、模态框、dialog、popup、alert、toast、浮层、"- "悬浮覆盖层或可关闭窗口组件。不要用绝对定位卡片或假的关闭按钮模拟这些组件。"- "如果可以近似表达,请在普通 surface 内使用行内状态、行内卡片或确认区域;"+ " A2UI 不支持弹窗、模态框、dialog、popup、alert、toast、浮层。"+ "不要用绝对定位卡片或假的关闭按钮模拟这些组件。"+ "请在普通 surface 内使用行内状态、行内卡片或确认区域替代。""如果无法忠实近似,请用纯文本说明当前暂不支持该组件。")autonomy_rule_zh = (- " A2UI 是可选能力。只有当生成式 UI 比纯文本更能改善用户体验时才使用 A2UI。"- "不要为寒暄、两三句话解释、简单事实回答或无结构普通文本强行生成 A2UI。"- "适合 A2UI 的通用场景包括:信息收集表单、可操作确认、多结果比较、"- "单对象详情、带媒体的卡片、仪表盘/状态/库存/任务摘要,以及工具结果的交互式展示。"+ " 当用户的请求需要交互式收集信息(如选择、输入、确认等),"+ "或需要展示 2 个及以上同类项的结构化对比(如多个酒店/方案/产品/路线),优先采用 A2UI。"+ "输出格式决策(每次回复前必须执行)——按以下顺序判断,命中即定格式,不再继续:"+ "1. 回复需要收集用户输入(选择/填写/确认等交互操作)→ 必须 A2UI;"+ "2. 回复包含 2 个及以上同类项的并列对比 → 必须 A2UI;"+ "3. 回复仅为单条叙述性解释、简短事实、寒暄 → 纯文本。"+ "兜底:当某回复同时满足多条格式规则时,优先选择更结构化的格式(A2UI > 纯文本)。"+ "A2UI 典型场景:信息收集表单、可操作确认、多结果比较、"+ "以及工具结果的交互式展示。""对于真实世界推荐、对比、选购、排行、价格、旅行、餐厅或产品请求,""如果有可用工具,应先使用工具获取依据,再判断 A2UI 是否是最佳最终展示方式。""如果用户已经提供完整结构化数据,或明确要求演示 UI,可以直接渲染而不调用工具。"+ "能力边界优先:即使你无法执行最终动作(无浏览器代理、无 Gmail/社媒/个税登录、"+ "无支付),只要用户需要你收集结构化意图(选项/字段/偏好/数量),"+ "你必须用 A2UI 表单收集——绝不能因做不了执行就退回 Markdown 文字问或 "+ "ask_user 逐个问。收集到的数据可生成对照清单/草稿/方案供用户在外部操作。"+ "当需收集多个结构化字段时,用一个 A2UI 表单并行收集,不要用 ask_user 逐个问。"+ "关键——必须输出 a2ui-json,禁止 markdown 模拟表单:"+ "满足上述决策树条件时,你必须输出合法的 <a2ui-json> 块。"+ "不要用 markdown 列表、纯文字选项列表、"+ "或伪按钮文本模拟表单。markdown 模拟表单不可交互,a2ui 可用时禁止使用。"+ "如果你发现自己在用纯文字写选项或按钮,立即停止,改输出 a2ui-json。""绝不能把 tool_call、invoke 或函数调用标签当作普通文本输出。")requested_component_rule_zh = (- " 必须匹配用户请求的组件类型:如果用户要求输入框或文本框,生成 TextField/Form UI;"- "只有用户要求卡片或卡片列表时才生成 card list。Card/list 不是万能 fallback。"- "单个对象详情请求应生成单对象详情布局,不要生成多卡片 demo。"- "不要用固定 demo 替代用户请求的组件。对可编辑 TextField,必须把 TextField.text "- "绑定到 data model 路径,用 dataModelUpdate 初始化该路径,并在 Button.action.context "- "中用 path reference 包含提交值。表单提交不能输出空的 Button.action.context。"- + template_binding_rule_zh+ " 必须匹配用户请求的组件类型:只有用户要求卡片或卡片列表时才生成 "+ "card list;Card/list 不是万能 fallback。单个对象详情请求应生成单对象"+ "详情布局,不要生成多卡片 demo。不要用固定 demo 替代用户请求的组件。"+ "对每个可交互组件——TextField、"+ "MultipleChoice、CheckBox、DateTimeInput、Slider——必须把其 value/selections "+ "绑定到 data model 路径,用 dataModelUpdate 初始化该路径,并在 "+ "Button.action.context 中用 path reference 包含提交值。"+ "日期或时间选择字段必须用 DateTimeInput(不用 TextField)。"+ "表单提交不能输出空的 Button.action.context。"+ "Button 必须用 \"child\" 引用一个组件 id(如 Text 组件)作为按钮文字,不要用 \"label\" 字段。"+ "MultipleChoice 尤其要注意:selections 必须是带 \"path\" 键的对象"+ "(如 selections={\"path\":\"/form/cabinClass\"}),默认选中值必须通过 "+ "dataModelUpdate 在该路径上设置。"+ "MultipleChoice 的 option value 不要跟任何组件 id 同名"+ "(如组件 id=\"anonymous\" 时 option value 用 \"anon\" 而非 \"anonymous\",否则会致循环依赖)。"+ "Button.action.context 的每个 \"key\" 不得与同一 surface 内任何组件 id 同名。"+ "List 或卡片列表展示重复数据时,dataModelUpdate 的 key 不能重复,"+ "请把数组编码为集合 key 并用索引项(\"0\"、\"1\"),每个 item 含嵌套 "+ "valueMap 字段,模板内用 item-relative path。"+ "不要在模板内使用集合绝对路径(如 /phones/name)。"+ "不要在模板渲染出的组件内部嵌套 template;"+ "请把重复 item 的明细拍平成外层 item 字段,或使用显式子组件绑定这些字段。"+ image_url_rule_zh- + icon_font_rule_en+ unsupported_component_rule_zh- + autonomy_rule_zh)if language in {"zh", "cn"}:return (- "A2UI 是可选能力;不要强行使用 A2UI。"- "如果富交互界面比纯文本更适合当前回答,可以输出一段很短的说明,"- "然后输出一个合法的 <a2ui-json>...</a2ui-json> block。"- "如果不适合 A2UI,请直接纯文本回答。不要承诺使用 A2UI 却只输出 Markdown。"- "如果确实需要外部事实或图片,可以短暂使用可用工具,"- "随后自行判断是否用 A2UI 呈现。"- "block 内必须是 A2UI 0.8 server-to-client message list,"- "并且必须先 beginRendering,再 surfaceUpdate,再按需 dataModelUpdate。"+ "如果决策树判定使用 A2UI,输出一段很短的说明后跟合法的 a2ui-json block。"+ + autonomy_rule_zh+ requested_component_rule_zh)return (- "A2UI is optional. Keep tools available. If a rich interactive interface "- "is better than plain text for this answer, output a very short intro "- "followed by one valid <a2ui-json>...</a2ui-json> block. If A2UI is not "- "appropriate, answer in plain text. Do not promise to show the result with "- "A2UI and then output only Markdown. If external facts or images are needed, "- "use the available tools briefly, then decide whether A2UI is the best "- "presentation. The block must contain an A2UI 0.8 "- "server-to-client message list, with beginRendering before "- "surfaceUpdate and dataModelUpdate only when needed."+ "If the decision tree determines A2UI is appropriate, output a very "+ "short intro followed by a valid a2ui-json block. "+ autonomy_rule_en+ requested_component_rule_en)diff --git a/jiuwenswarm/server/runtime/a2ui/protocol.py b/jiuwenswarm/server/runtime/a2ui/protocol.pyindex e8fab57405..df1b559ee7 100644--- a/jiuwenswarm/server/runtime/a2ui/protocol.py+++ b/jiuwenswarm/server/runtime/a2ui/protocol.py@@ -99,41 +99,32 @@ class A2UIProtocolSpec:) -> str:if language in {"zh", "cn"}:role = (- "JiuwenSwarm 支持可选的 A2UI 输出格式。当富交互界面适合当前回答时,"- "可以生成严格符合 A2UI 0.8 schema 的消息。"+ "JiuwenSwarm 支持 A2UI 输出格式。当富交互界面适合当前回答时,"+ "应生成严格符合 A2UI 0.8 schema 的消息。")ui = (- "当用户需要列表、卡片、表单、确认结果、可点击操作或结构化信息比较时使用 A2UI。"- "普通解释、简短回答、敏感内容或不需要交互的回答保持纯文本。"+ "交互场景用 A2UI,非交互(纯叙述、简短事实、寒暄)保持纯文本。")workflow = (- "如果使用 A2UI,回答可以包含说明文本和一个或多个 A2UI JSON block。"- f"每个 block 必须用 {A2UI_OPEN_TAG} 和 {A2UI_CLOSE_TAG} 包装。"- "block 内必须是 JSON list,list 中每个元素都是 A2UI server-to-client message。"- "必须先输出 beginRendering,再输出 surfaceUpdate;如果使用数据绑定,再按需输出 dataModelUpdate。"- "父组件必须先于子组件出现。不要输出其他协议版本的 schema、字段或组件。"+ "如果使用 A2UI,必须先输出 beginRendering,再输出 surfaceUpdate;"+ "如果使用数据绑定,再按需输出 dataModelUpdate。"+ "不要输出其他协议版本的 schema、字段或组件。")else:role = (- "JiuwenSwarm supports an optional A2UI output format. When a rich "+ "JiuwenSwarm supports A2UI output format. When a rich ""interactive answer is appropriate, generate messages that ""strictly validate against the A2UI 0.8 schema.")ui = (- "Use A2UI for lists, cards, forms, confirmations, clickable "- "actions, and structured comparisons. Keep ordinary explanations, "- "short answers, sensitive answers, and non-interactive replies as "- "plain text."+ "Use A2UI for interactive scenarios; keep non-interactive "+ "replies (narrative, brief facts, greetings) as plain text.")workflow = (- "When using A2UI, the response may contain conversational text and "- f"one or more A2UI JSON blocks wrapped in {A2UI_OPEN_TAG} and "- f"{A2UI_CLOSE_TAG}. The JSON inside each block MUST be a JSON list "- "of A2UI server-to-client messages. Emit beginRendering before "- "surfaceUpdate; include dataModelUpdate only when data binding is "- "needed. List parent components before child components. Do not "- "emit schema, fields, or components from any protocol version "- "other than 0.8."+ "When using A2UI, emit beginRendering before surfaceUpdate; "+ "include dataModelUpdate only when data binding is needed. "+ "Do not emit schema, fields, or components from any protocol "+ "version other than 0.8.")workflow = f"{workflow}\n\n{build_a2ui_autonomy_instruction(language)}"@@ -255,7 +246,13 @@ def format_a2ui_for_text_channel(content: str, version: str = VERSION_0_8) -> stdef format_content_for_channel(content: str, channel_id: str | None) -> str:- if str(channel_id or "").lower() == "web":+ # web/officeclaw 是原生 a2ui 渲染渠道:直接透传原始 <a2ui-json> 块(前端自行提取渲染)。+ # 注意 1:本函数当前全仓无生产调用方(历史遗留导出,网关侧+ # apply_non_web_text_fallback_to_payload 已是 no-op);未来若接线,调用方必须先过+ # a2ui.enabled 配置门控,否则关闭态下 officeclaw 会把协议原文直接透传给用户。+ # 注意 2:渠道集合与 integration._A2UI_CHANNEL_IDS 保持同步(protocol 不能反向+ # import integration——循环依赖,故此处内联字面量并加本注释锚定)。+ if str(channel_id or "").lower() in {"web", "officeclaw"}:return contentspec = get_protocol_spec()if not spec.may_contain_a2ui_content(content):diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex aadf7fc8b9..0eada1d2a1 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -80,7 +80,9 @@ from jiuwenswarm.common.utils import (from jiuwenswarm.server.runtime.a2ui.integration import (finalize_assistant_response_if_a2ui,is_a2ui_channel,+ is_a2ui_probe_channel,)+from jiuwenswarm.server.runtime.a2ui.protocol import is_a2ui_client_eventfrom jiuwenswarm.server.runtime.a2ui.runtime.finalizer import should_finalize_a2ui_contentfrom jiuwenswarm.agents.harness.common.auto_memory import (_execute_auto_memory_extraction,@@ -132,6 +134,33 @@ def _permission_response_key(request: AgentRequest) -> str | None:return request_id or None+def _is_a2ui_client_event_request(request: AgentRequest) -> bool:+ """True when this request carries an A2UI client event in params.content.++ 此类请求的 inputs["query"] 已由 build_user_prompt 转成可读 a2ui prompt;+ team 分支若再用 raw_query 覆写,raw_query = query if isinstance(query, str)+ else "" 为空字符串——用空串覆写转换后成品 prompt。+ """+ params = request.params if isinstance(request.params, dict) else {}+ return is_a2ui_client_event(params.get("content"))+++def _should_skip_team_raw_override(inputs: dict[str, Any], request: AgentRequest) -> bool:+ """team raw_query 覆写的豁免判定(可单测纯函数)。++ 豁免两类结构化请求:+ - InteractiveInput:ask_user/HITL 续答(既有先例)+ - A2UI client_event:query 已是转换后 a2ui prompt(str),但 raw_query 取自+ params.content(dict),raw_query = query if isinstance(query, str) else ""+ 为空字符串——不豁免时用空串覆写转换后成品 prompt。+ """+ from openjiuwen.core.session.interaction.interactive_input import InteractiveInput++ if isinstance(inputs.get("query"), InteractiveInput):+ return True+ return _is_a2ui_client_event_request(request)++def _is_team_permission_interactive_resume(request: AgentRequest,inputs: dict[str, Any],@@ -3441,12 +3470,20 @@ class JiuWenSwarm:from openjiuwen.core.session.interaction.interactive_input import InteractiveInputteam_query_is_interactive_input = isinstance(inputs.get("query"), InteractiveInput)- if not team_query_is_interactive_input:+ # a2ui client_event / InteractiveInput 请求豁免 raw_query 覆写(判定见纯函数)+ skip_raw_override = _should_skip_team_raw_override(inputs, request)+ if not skip_raw_override:inputs["query"] = raw_query- logger.info(- "[JiuWenSwarm] Team模式使用原始query: %s",- raw_query[:100] if isinstance(raw_query, str) and raw_query else type(inputs.get("query")).__name__,- )+ logger.info(+ "[JiuWenSwarm] Team模式使用原始query: %s",+ raw_query[:100] if isinstance(raw_query, str) and raw_query else type(inputs.get("query")).__name__,+ )+ else:+ # 豁免分支:query 是成品 prompt,单独文案避免与原始 query 混淆+ logger.info(+ "[JiuWenSwarm] Team模式豁免raw_query覆写(a2ui client_event/InteractiveInput),保留转换后query: type=%s",+ type(inputs.get("query")).__name__,+ )# cloud memory: before chat hookif memory_mode == "cloud":@@ -3694,7 +3731,11 @@ class JiuWenSwarm:suppress_a2ui_stream = Falsea2ui_pending_render_sent = Falsea2ui_stream_probe = ""- a2ui_probe_enabled = is_a2ui_channel(cid)+ # 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 致前端提取失败。+ a2ui_probe_enabled = is_a2ui_probe_channel(cid)_yielded_from_queue = 0logger.info("[JiuWenSwarm] consumer loop starting: request_id=%s is_team=%s is_first=%s",diff --git a/tests/unit_tests/a2ui/test_integration_bridge.py b/tests/unit_tests/a2ui/test_integration_bridge.pyindex 2e131381a6..872b260ce6 100644--- a/tests/unit_tests/a2ui/test_integration_bridge.py+++ b/tests/unit_tests/a2ui/test_integration_bridge.py@@ -22,10 +22,13 @@ from jiuwenswarm.server.runtime.a2ui.integration import ()-def test_a2ui_channel_policy_is_web_only():- """A2UI should only be active for the controlled Web channel."""+def test_a2ui_channel_policy_covers_web_and_officeclaw():+ """A2UI native channels are the controlled Web channel + officeclaw (relay-claw);+ all other channels stay off."""assert is_a2ui_channel("web") is Trueassert is_a2ui_channel("WEB") is True+ assert is_a2ui_channel("officeclaw") is True+ assert is_a2ui_channel("OfficeClaw") is Trueassert is_a2ui_channel("feishu") is Falseassert is_a2ui_channel("wechat") is Falseassert is_a2ui_channel(None) is False@@ -389,6 +392,101 @@ async def test_finalize_assistant_response_if_a2ui_bypasses_non_web_channel(monkassert result == content+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.+ """+ import types++ config_calls: list[int] = []++ def fake_config():+ config_calls.append(1)+ return types.SimpleNamespace(enabled=True)++ monkeypatch.setattr(integration, "_get_runtime_a2ui_config", fake_config)++ finalize_calls: list[str] = []++ async def fake_finalize(content, **kwargs):+ finalize_calls.append(content)+ return content++ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.a2ui.runtime.response_finalization.finalize_a2ui_assistant_content",+ fake_finalize,+ )++ repair_calls: list[str] = []++ async def repair_call(prompt: str):+ repair_calls.append(prompt)+ return prompt++ retry_calls: list[str] = []++ def retry_without_a2ui_call(query: str):+ retry_calls.append(query)+ return "retry content"++ broken_a2ui = "<a2ui-json>{broken json</a2ui-json>"+ result = await integration.finalize_assistant_response_if_a2ui(+ broken_a2ui,+ channel="officeclaw",+ user_query="generate a form",+ request_id="req-officeclaw",+ repair_call=repair_call,+ retry_without_a2ui_call=retry_without_a2ui_call,+ )++ assert result == broken_a2ui+ assert config_calls == []+ assert finalize_calls == []+ assert repair_calls == []+ assert retry_calls == []+++async def test_finalize_web_still_runs_server_side_repair(monkeypatch):+ """web must keep running server-side A2UI repair/retry/resend (regression guard)."""+ import types++ def fake_config():+ return types.SimpleNamespace(enabled=True)++ monkeypatch.setattr(integration, "_get_runtime_a2ui_config", fake_config)++ finalize_calls: list[str] = []++ async def fake_finalize(content, **kwargs):+ finalize_calls.append(content)+ return content++ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.a2ui.runtime.response_finalization.finalize_a2ui_assistant_content",+ fake_finalize,+ )++ content = "<a2ui-json>[]</a2ui-json>"+ result = await integration.finalize_assistant_response_if_a2ui(+ content,+ channel="web",+ user_query="generate a form",+ request_id="req-web",+ repair_call=None,+ )++ assert result == content+ assert finalize_calls == [content]++def test_partial_marker_ignores_short_data_token():"""'data' alone must not trigger A2UI suppression (ECharts false-positive)."""from jiuwenswarm.server.runtime.agent_adapter.interface import (diff --git a/tests/unit_tests/a2ui/test_prompt_instructions.py b/tests/unit_tests/a2ui/test_prompt_instructions.pyindex d38e436a4a..aa54bcb0d8 100644--- a/tests/unit_tests/a2ui/test_prompt_instructions.py+++ b/tests/unit_tests/a2ui/test_prompt_instructions.py@@ -11,20 +11,12 @@ from jiuwenswarm.server.runtime.a2ui.runtime.prompt import ()-def test_a2ui_prompt_discourages_icon_ligature_dependency():- instruction = build_a2ui_autonomy_instruction("en")-- assert "Avoid A2UI Icon for semantic content" in instruction- assert "Material Symbols" in instruction- assert "emoji or text labels" in instruction--def test_a2ui_prompt_is_autonomous_not_forced():instruction = build_a2ui_autonomy_instruction("en")- assert "A2UI is optional" in instruction- assert "If A2UI is not appropriate, answer in plain text" in instruction- assert "Do not promise to show the result with A2UI and then output only Markdown" in instruction+ assert "plain text" in instruction+ assert "narrative explanation" in instruction+ assert "markdown mock" in instructionassert "Mandatory A2UI account-action gate" not in instructionassert "browser_preflight_submit" not in instruction@@ -33,7 +25,7 @@ def test_a2ui_prompt_discourages_nested_templates():instruction = build_a2ui_autonomy_instruction("en")assert "Do not nest templates" in instruction- assert "flatten repeated item details" in instruction+ assert "indexed valueMap" in instructiondef test_a2ui_prompt_defines_hotel_booking_actions():@@ -114,8 +106,8 @@ def test_a2ui_zh_prompt_section_is_readable():prompt = build_a2ui_prompt_section("zh")assert "你是 jiuwenswarm 的 A2UI 生成器" not in prompt- assert "JiuwenSwarm 支持可选的 A2UI 输出格式" in prompt- assert "当用户需要列表、卡片、表单" in prompt+ assert "JiuwenSwarm 支持 A2UI 输出格式" in prompt+ assert "交互场景用 A2UI" in promptassert "浣犳槸" not in promptassert "鐢熸垚" not in prompt@@ -124,7 +116,7 @@ def test_a2ui_en_prompt_does_not_use_generator_identity():prompt = build_a2ui_prompt_section("en")assert "You are jiuwenswarm's A2UI generator" not in prompt- assert "JiuwenSwarm supports an optional A2UI output format" in prompt+ assert "JiuwenSwarm supports A2UI output format" in promptdef test_a2ui_zh_client_event_prompt_is_readable():diff --git a/tests/unit_tests/a2ui/test_team_raw_override_skip.py b/tests/unit_tests/a2ui/test_team_raw_override_skip.pynew file mode 100644index 0000000000..401a9bcb06--- /dev/null+++ b/tests/unit_tests/a2ui/test_team_raw_override_skip.py@@ -0,0 +1,41 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""team raw_query 覆写豁免回归测试。++client_event 请求的 inputs["query"] 已由 build_user_prompt 转为可读 a2ui prompt,+但 raw_query 取自 params.content(dict),raw_query = query if isinstance(query, str)+else "" 为空字符串——不豁免时用空串覆写转换后成品 prompt。+"""++from __future__ import annotations++from jiuwenswarm.common.schema.agent import AgentRequest+from jiuwenswarm.server.runtime.agent_adapter.interface import (+ _should_skip_team_raw_override,+)++_EVENT = {+ "type": "a2ui.client_event",+ "protocolVersion": "0.8",+ "event": {"userAction": {"name": "submit_form", "surfaceId": "s", "context": {"name": "张三"}}},+}+++def _req(params: dict) -> AgentRequest:+ return AgentRequest(request_id="r", channel_id="officeclaw", session_id="s", params=params)+++def test_skips_override_for_a2ui_client_event_request():+ inputs = {"query": "已转换的 a2ui prompt 文本"}+ assert _should_skip_team_raw_override(inputs, _req({"content": _EVENT, "mode": "team.plan"})) is True+++def test_does_not_skip_for_plain_team_text():+ inputs = {"query": "包装后的 prompt"}+ assert _should_skip_team_raw_override(inputs, _req({"query": "开会", "mode": "team.plan"})) is False+++def test_skips_for_interactive_input_instance():+ from openjiuwen.core.session.interaction.interactive_input import InteractiveInput++ assert _should_skip_team_raw_override({"query": InteractiveInput()}, _req({"query": "x"})) is Truediff --git a/tests/unit_tests/a2ui/test_web_only_prompt_rail.py b/tests/unit_tests/a2ui/test_web_only_prompt_rail.pyindex 68738a73ee..c9a1d590b3 100644--- a/tests/unit_tests/a2ui/test_web_only_prompt_rail.py+++ b/tests/unit_tests/a2ui/test_web_only_prompt_rail.py@@ -8,7 +8,10 @@ import pytestfrom openjiuwen.core.single_agent.rail.base import InvokeInputs, ModelCallInputsfrom jiuwenswarm.agents.harness.common.prompt.prompt_builder import LocalSectionName-from jiuwenswarm.agents.harness.common.rails.response_prompt_rail import ResponsePromptRail+from jiuwenswarm.agents.harness.common.rails.response_prompt_rail import (+ ResponsePromptRail,+ _BROWSER_WORKFLOW_ENABLED,+)from jiuwenswarm.server.runtime.a2ui.config import A2UIConfig@@ -58,6 +61,13 @@ async def test_response_prompt_rail_keeps_a2ui_for_web_channel(monkeypatch):assert "browser_preflight_submit" not in content["en"]+ not _BROWSER_WORKFLOW_ENABLED,+ reason="browser-workflow feature gate off (_BROWSER_WORKFLOW_ENABLED=False "+ "in response_prompt_rail; requires fixing 3 latent prompt issues + env "+ "PLAYWRIGHT_RUNTIME_MCP_ENABLED before re-enabling). Test auto-reactivates "+ "when the gate flips True.",+)@pytest.mark.asyncioasync def test_response_prompt_rail_scopes_browser_rules_to_browser_request(monkeypatch):"""Browser A2UI flows remain available without polluting ordinary A2UI requests."""@@ -301,3 +311,55 @@ async def test_response_prompt_rail_does_not_inject_a2ui_for_tui_session_prefix(assert "response" in rail.system_prompt_builder.sectionsassert LocalSectionName.A2UI not in rail.system_prompt_builder.sections+++async def test_a2ui_boost_injected_only_for_officeclaw_channel(monkeypatch):+ """A2UI_BOOST(117) targets officeclaw (relay-claw) to counteract soul's+ structured-output bias; other channels must not receive it."""+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.a2ui.config.get_current_a2ui_config",+ lambda: A2UIConfig(enabled=True),+ )+ rail = ResponsePromptRail()+ rail.system_prompt_builder = _FakePromptBuilder()++ await rail.before_model_call(SimpleNamespace(inputs={"channel": "officeclaw"}))++ assert LocalSectionName.A2UI in rail.system_prompt_builder.sections+ assert LocalSectionName.A2UI_BOOST in rail.system_prompt_builder.sections+++async def test_a2ui_boost_not_injected_for_web_channel(monkeypatch):+ """Web already renders A2UI natively without the boost counterweight."""+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.a2ui.config.get_current_a2ui_config",+ lambda: A2UIConfig(enabled=True),+ )+ rail = ResponsePromptRail()+ rail.system_prompt_builder = _FakePromptBuilder()++ await rail.before_model_call(SimpleNamespace(inputs={"channel": "web"}))++ assert LocalSectionName.A2UI in rail.system_prompt_builder.sections+ assert LocalSectionName.A2UI_BOOST not in rail.system_prompt_builder.sections+++async def test_a2ui_boost_removed_when_a2ui_disabled(monkeypatch):+ """With A2UI off, both the main section and a stale boost section must be+ removed from the prompt builder."""+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.a2ui.config.get_current_a2ui_config",+ lambda: A2UIConfig(enabled=False),+ )+ rail = ResponsePromptRail()+ rail.system_prompt_builder = _FakePromptBuilder()+ rail.system_prompt_builder.sections[LocalSectionName.A2UI] = object()+ rail.system_prompt_builder.sections[LocalSectionName.A2UI_BOOST] = object()++ await rail.before_model_call(SimpleNamespace(inputs={"channel": "officeclaw"}))++ assert LocalSectionName.A2UI not in rail.system_prompt_builder.sections+ assert LocalSectionName.A2UI_BOOST not in rail.system_prompt_builder.sections