JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(a2ui): stabilize interactions and text rendering
jack_ricky052f287c381f
diff --git a/jiuwenswarm/channels/web/frontend/scripts/test-a2ui-interaction-guards.mjs b/jiuwenswarm/channels/web/frontend/scripts/test-a2ui-interaction-guards.mjsnew file mode 100644index 0000000000..2045a0d5f9--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/scripts/test-a2ui-interaction-guards.mjs@@ -0,0 +1,150 @@+import assert from 'node:assert/strict';+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import ts from 'typescript';++const root = new URL('..', import.meta.url);+const tempDir = await mkdtemp(join(tmpdir(), 'a2ui-interaction-guards-'));++const moduleMap = new Map([+ ['src/features/a2ui/a2uiContent.ts', 'a2uiContent.mjs'],+ ['src/features/a2ui/actionBridge.ts', 'actionBridge.mjs'],+ ['src/features/a2ui/actionDefaults.ts', 'actionDefaults.mjs'],+ ['src/features/a2ui/featureConfig.ts', 'featureConfig.mjs'],+ ['src/features/a2ui/formDefaults.ts', 'formDefaults.mjs'],+]);++function rewriteLocalImports(source) {+ return source+ .replaceAll("from './a2uiContent'", "from './a2uiContent.mjs'")+ .replaceAll("from './actionDefaults'", "from './actionDefaults.mjs'")+ .replaceAll("from './featureConfig'", "from './featureConfig.mjs'")+ .replaceAll("from './formDefaults'", "from './formDefaults.mjs'");+}++async function transpileTsModule(sourcePath, outputFileName) {+ const sourceUrl = new URL(sourcePath, root);+ const source = await readFile(sourceUrl, 'utf8');+ const transpiled = ts.transpileModule(source, {+ compilerOptions: {+ module: ts.ModuleKind.ES2020,+ target: ts.ScriptTarget.ES2020,+ importsNotUsedAsValues: ts.ImportsNotUsedAsValues.Remove,+ },+ });+ const outputPath = join(tempDir, outputFileName);+ await writeFile(outputPath, rewriteLocalImports(transpiled.outputText), 'utf8');+ return outputPath;+}++async function importTsModule(sourcePath) {+ for (const [path, output] of moduleMap.entries()) {+ await transpileTsModule(path, output);+ }+ const outputPath = join(tempDir, moduleMap.get(sourcePath));+ return import(`file://${outputPath.replace(/\\/g, '/')}`);+}++try {+ const { namespaceA2UIMessages } = await importTsModule('src/features/a2ui/a2uiContent.ts');+ const plainNamespaced = namespaceA2UIMessages(+ [{ beginRendering: { surfaceId: 'surface-1', root: 'root' } }],+ 'msg_new',+ );+ assert.equal(+ plainNamespaced[0].beginRendering.surfaceId,+ 'msg_new:surface-1',+ 'plain surface ids should be scoped to the current message namespace',+ );++ const alreadyNamespaced = namespaceA2UIMessages(+ [{ surfaceUpdate: { surfaceId: 'msg_old:surface-1', components: [] } }],+ 'msg_new',+ );+ assert.equal(+ alreadyNamespaced[0].surfaceUpdate.surfaceId,+ 'msg_old:surface-1',+ 'surface ids that already carry a message namespace must not be scoped twice',+ );++ const {+ dispatchA2UIAction,+ setA2UIActionHandler,+ } = await importTsModule('src/features/a2ui/actionBridge.ts');++ let finishFirst;+ const firstCompletion = new Promise((resolve) => {+ finishFirst = resolve;+ });+ const handled = [];+ const cleanup = setA2UIActionHandler(async (message) => {+ handled.push(message.userAction?.sourceComponentId);+ if (handled.length === 1) {+ await firstCompletion;+ }+ });++ const baseAction = {+ userAction: {+ name: 'showHello',+ surfaceId: 'msg_old:surface-1',+ sourceComponentId: 'helloButton',+ context: {},+ timestamp: '2026-06-22T00:00:00.000Z',+ },+ };++ const firstDispatch = dispatchA2UIAction(baseAction);+ await dispatchA2UIAction(baseAction);+ assert.deepEqual(+ handled,+ ['helloButton'],+ 'duplicate clicks for the same in-flight A2UI action should be ignored',+ );++ await dispatchA2UIAction({+ userAction: {+ ...baseAction.userAction,+ sourceComponentId: 'otherButton',+ },+ });+ assert.deepEqual(+ handled,+ ['helloButton', 'otherButton'],+ 'different A2UI action keys should still be allowed while one key is in flight',+ );++ finishFirst();+ await firstDispatch;+ await dispatchA2UIAction(baseAction);+ assert.deepEqual(+ handled,+ ['helloButton', 'otherButton', 'helloButton'],+ 'the same A2UI action key should be allowed again after its request settles',+ );++ cleanup();++ const {+ resolveA2UITextValue,+ } = await importTsModule('src/features/a2ui/formDefaults.ts');++ assert.equal(+ resolveA2UITextValue({ literalString: 'helloworld' }, () => null),+ 'helloworld',+ 'literal Text values should still render normally',+ );+ assert.equal(+ resolveA2UITextValue({ path: '/message' }, () => new Map([['text', 'helloworld']])),+ 'helloworld',+ 'Text paths that resolve to a single scalar inside a Map should unwrap that scalar',+ );+ assert.equal(+ resolveA2UITextValue({ path: '/message' }, () => new Map([['title', 'A'], ['body', 'B']])),+ null,+ 'Text paths that resolve to an object-like Map must not render as [object Map]',+ );+} finally {+ await rm(tempDir, { recursive: true, force: true });+}diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsxindex 4d383b2994..4157a3c3c0 100644--- a/jiuwenswarm/channels/web/frontend/src/App.tsx+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx@@ -1106,7 +1106,7 @@ for (let i = payload.team.length; i < 10; i++) {return setA2UIActionHandler((message) => {const currentSessionId = sessionIdRef.current;if (!currentSessionId || currentSessionId === 'new') return;- void sendStructuredChatContent(+ return sendStructuredChatContent(buildA2UIClientEventContent(message),currentSessionId,);diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ChatPanel.css b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ChatPanel.cssindex 3dd14119dd..37462277c4 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ChatPanel.css+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ChatPanel.css@@ -1198,27 +1198,38 @@display: flex;flex-direction: column;gap: 0.75rem;+ max-width: 100%;min-width: 0;+ overflow-wrap: anywhere;}.a2ui-message-content__surfaces {display: flex;flex-direction: column;gap: 0.75rem;+ max-width: 100%;min-width: 0;}.a2ui-message-content .a2ui-surface {+ box-sizing: border-box;max-width: 100%;+ min-width: 0;color: var(--text);+ overflow-x: auto;+ overflow-y: visible;}.a2ui-message-content .a2ui-card > section {+ max-width: 100%;+ min-width: 0;+ max-height: min(70vh, 720px);border: 1px solid rgba(148, 163, 184, 0.26);border-radius: 12px;background: linear-gradient(180deg, rgba(255, 255, 255, 0.08), rgba(255, 255, 255, 0.03));box-shadow: 0 12px 28px rgba(15, 23, 42, 0.16);- overflow: hidden;+ overflow: auto;+ overflow-wrap: anywhere;}:root.a2ui-material-symbols-unavailable .a2ui-message-content .a2ui-icon {diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/TextWithDefaults.tsx b/jiuwenswarm/channels/web/frontend/src/features/a2ui/TextWithDefaults.tsxnew file mode 100644index 0000000000..e7eaf3f68d--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/TextWithDefaults.tsx@@ -0,0 +1,68 @@+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++import { useMemo } from 'react';+import type { CSSProperties } from 'react';+import ReactMarkdown from 'react-markdown';+import remarkGfm from 'remark-gfm';+import {+ classMapToString,+ stylesToObject,+ useA2UIComponent,+ type A2UIComponentProps,+ type AnyComponentNode,+} from '@a2ui/react';+import { hostWeightStyle } from './fieldBinding';+import { isRecord, resolveA2UITextValue } from './formDefaults';++type TextNodeLike = Extract<AnyComponentNode, { type: 'Text' }>;+type TextUsageHint = 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'caption' | 'body';+type ClassMap = Record<string, boolean>;++function textClassMap(value: unknown): ClassMap {+ return isRecord(value) ? value as ClassMap : {};+}++export function TextWithDefaults({+ node,+ surfaceId,+}: A2UIComponentProps<TextNodeLike>) {+ const { theme, getValue } = useA2UIComponent(node, surfaceId);+ const props = node.properties;+ const usageHint = props.usageHint as TextUsageHint | undefined;+ const textValue = resolveA2UITextValue(props.text, getValue);++ const classes = useMemo(() => {+ const textTheme = theme.components.Text as Record<string, unknown>;+ return classMapToString({+ ...textClassMap(textTheme.all),+ ...textClassMap(usageHint ? textTheme[usageHint] : undefined),+ });+ }, [theme.components.Text, usageHint]);++ const additionalStyles = useMemo(() => {+ const textStyles = theme.additionalStyles?.Text;+ if (!textStyles) return undefined;+ if (isRecord(textStyles) && usageHint && isRecord(textStyles[usageHint])) {+ return stylesToObject(textStyles[usageHint] as Record<string, string>);+ }+ return stylesToObject(textStyles as Record<string, string>);+ }, [theme.additionalStyles?.Text, usageHint]);++ if (textValue === null || textValue === '') {+ return null;+ }++ const textStyle = usageHint === 'caption'+ ? { ...additionalStyles, fontStyle: 'italic' } as CSSProperties+ : additionalStyles;++ return (+ <div className="a2ui-text" style={hostWeightStyle(node.weight)}>+ <section className={classes} style={textStyle}>+ <ReactMarkdown remarkPlugins={[remarkGfm]}>+ {textValue}+ </ReactMarkdown>+ </section>+ </div>+ );+}diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/a2ui.css b/jiuwenswarm/channels/web/frontend/src/features/a2ui/a2ui.cssindex 67626aa6d5..004f6ce7b3 100644--- a/jiuwenswarm/channels/web/frontend/src/features/a2ui/a2ui.css+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/a2ui.css@@ -2,6 +2,32 @@/* A2UI Component Styles */+body .a2ui-surface,+body .a2ui-surface *,+body .a2ui-surface *::before,+body .a2ui-surface *::after {+ box-sizing: border-box;+}++body .a2ui-surface {+ max-width: 100%;+ min-width: 0;+ overflow-wrap: anywhere;+}++body .a2ui-surface section {+ max-width: 100%;+ min-width: 0;+}++body .a2ui-surface button,+body .a2ui-surface [role="button"] {+ max-width: 100%;+ min-width: 2.5rem;+ white-space: normal;+ overflow-wrap: anywhere;+}+/* ─── Horizontal scrollable containers (utility class) ─── */.a2ui-horizontal-scroll {overflow-x: auto;diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/a2uiContent.ts b/jiuwenswarm/channels/web/frontend/src/features/a2ui/a2uiContent.tsindex a4de50936e..ef3b56b1a5 100644--- a/jiuwenswarm/channels/web/frontend/src/features/a2ui/a2uiContent.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/a2uiContent.ts@@ -299,19 +299,23 @@ export function namespaceA2UIMessages(messages: ServerToClientMessage[],namespace: string): ServerToClientMessage[] {+ const namespaceSurfaceId = (surfaceId: string): string => (+ /^msg_[A-Za-z0-9_-]+:/.test(surfaceId) ? surfaceId : `${namespace}:${surfaceId}`+ );+return messages.map((message) => {const cloned = structuredClone(message) as ServerToClientMessage;if (cloned.beginRendering?.surfaceId) {- cloned.beginRendering.surfaceId = `${namespace}:${cloned.beginRendering.surfaceId}`;+ cloned.beginRendering.surfaceId = namespaceSurfaceId(cloned.beginRendering.surfaceId);}if (cloned.surfaceUpdate?.surfaceId) {- cloned.surfaceUpdate.surfaceId = `${namespace}:${cloned.surfaceUpdate.surfaceId}`;+ cloned.surfaceUpdate.surfaceId = namespaceSurfaceId(cloned.surfaceUpdate.surfaceId);}if (cloned.dataModelUpdate?.surfaceId) {- cloned.dataModelUpdate.surfaceId = `${namespace}:${cloned.dataModelUpdate.surfaceId}`;+ cloned.dataModelUpdate.surfaceId = namespaceSurfaceId(cloned.dataModelUpdate.surfaceId);}if (cloned.deleteSurface?.surfaceId) {- cloned.deleteSurface.surfaceId = `${namespace}:${cloned.deleteSurface.surfaceId}`;+ cloned.deleteSurface.surfaceId = namespaceSurfaceId(cloned.deleteSurface.surfaceId);}return cloned;});diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/actionBridge.ts b/jiuwenswarm/channels/web/frontend/src/features/a2ui/actionBridge.tsindex ae17e1d1f8..d6e92664d2 100644--- a/jiuwenswarm/channels/web/frontend/src/features/a2ui/actionBridge.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/actionBridge.ts@@ -17,6 +17,21 @@ type A2UIActionHandler = () => void | Promise<void>;let currentHandler: A2UIActionHandler | null = null;+const inFlightActionKeys = new Set<string>();++function inFlightActionKey(message: A2UIClientEventMessage): string | null {+ const userAction = message.userAction;+ if (!userAction) {+ return null;+ }+ const surfaceId = userAction.surfaceId || '';+ const sourceComponentId = userAction.sourceComponentId || '';+ const actionName = userAction.name || '';+ if (!surfaceId || !sourceComponentId || !actionName) {+ return null;+ }+ return `${surfaceId}\u0000${sourceComponentId}\u0000${actionName}`;+}/*** Clean up action context to fix model-generated key issues.@@ -98,9 +113,11 @@ export function setA2UIActionHandler(handler: A2UIActionHandler | null): () => void {currentHandler = handler;+ inFlightActionKeys.clear();return () => {if (currentHandler === handler) {currentHandler = null;+ inFlightActionKeys.clear();}};}@@ -148,5 +165,24 @@ export async function dispatchA2UIAction(});}- await currentHandler(message);+ const actionKey = inFlightActionKey(message);+ if (actionKey && inFlightActionKeys.has(actionKey)) {+ a2uiWarn('[A2UI] duplicate action ignored while request is in flight:', {+ name: userAction?.name,+ sourceComponentId: userAction?.sourceComponentId,+ surfaceId: userAction?.surfaceId,+ });+ return;+ }++ if (actionKey) {+ inFlightActionKeys.add(actionKey);+ }+ try {+ await currentHandler(message);+ } finally {+ if (actionKey) {+ inFlightActionKeys.delete(actionKey);+ }+ }}diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/formDefaults.ts b/jiuwenswarm/channels/web/frontend/src/features/a2ui/formDefaults.tsindex b1cc2742fe..6377b255d2 100644--- a/jiuwenswarm/channels/web/frontend/src/features/a2ui/formDefaults.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/formDefaults.ts@@ -121,3 +121,52 @@ export function visibleChoiceDefault(props: UnknownRecord): unknown {}return literalDefaults.length > 0 ? literalDefaults : null;}++export function a2uiScalarText(value: unknown): string | null {+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {+ return String(value);+ }++ if (value instanceof Map) {+ const scalarValues = Array.from(value.values())+ .map((item) => a2uiScalarText(item))+ .filter((item): item is string => item !== null);+ return scalarValues.length === 1 ? scalarValues[0] : null;+ }++ if (Array.isArray(value)) {+ return value.length === 1 ? a2uiScalarText(value[0]) : null;+ }++ if (isRecord(value)) {+ const scalarValues = Object.values(value)+ .map((item) => a2uiScalarText(item))+ .filter((item): item is string => item !== null);+ return scalarValues.length === 1 ? scalarValues[0] : null;+ }++ return null;+}++export function resolveA2UITextValue(+ value: unknown,+ getValue: (path: string) => unknown,+): string | null {+ if (!isRecord(value)) {+ return null;+ }++ if (value.literalString !== undefined) {+ return a2uiScalarText(value.literalString);+ }++ if (value.literal !== undefined) {+ return a2uiScalarText(value.literal);+ }++ if (typeof value.path === 'string') {+ return a2uiScalarText(getValue(value.path));+ }++ return null;+}diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/rendererRegistry.tsx b/jiuwenswarm/channels/web/frontend/src/features/a2ui/rendererRegistry.tsxindex 79cd4ff23f..c4609826a4 100644--- a/jiuwenswarm/channels/web/frontend/src/features/a2ui/rendererRegistry.tsx+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/rendererRegistry.tsx@@ -8,6 +8,7 @@ import { DateTimeInputWithDefaults } from './DateTimeInputWithDefaults';import { MultipleChoiceWithDefaults } from './MultipleChoiceWithDefaults';import { SliderWithDefaults } from './SliderWithDefaults';import { TextFieldWithDefaults } from './TextFieldWithDefaults';+import { TextWithDefaults } from './TextWithDefaults';export interface A2UIRendererProps {surfaceId: string;@@ -19,6 +20,9 @@ const a2uiV08Registry = ComponentRegistry.getInstance();// which runs lazily on first A2UI render. We apply them both here (for early// access) and again in the renderer component (after ensureInitialized runs).function applyOverrides() {+ a2uiV08Registry.register('Text', {+ component: TextWithDefaults,+ });a2uiV08Registry.register('CheckBox', {component: CheckBoxWithDefaults,});diff --git a/jiuwenswarm/server/runtime/a2ui/prompt_instructions.py b/jiuwenswarm/server/runtime/a2ui/prompt_instructions.pyindex 6094ca6311..6c108e53d0 100644--- a/jiuwenswarm/server/runtime/a2ui/prompt_instructions.py+++ b/jiuwenswarm/server/runtime/a2ui/prompt_instructions.py@@ -30,6 +30,14 @@ def build_a2ui_autonomy_instruction(language: str = "en") -> str:"use Text literalString emoji or text labels instead so ligature fallback ""text does not appear.")+ 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."+ )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, "@@ -58,6 +66,7 @@ def build_a2ui_autonomy_instruction(language: str = "en") -> str:+ template_binding_rule_en+ image_url_rule_en+ icon_font_rule_en+ + unsupported_component_rule_en)template_binding_rule_zh = (@@ -74,6 +83,12 @@ def build_a2ui_autonomy_instruction(language: str = "en") -> str:"随后必须收敛到最终 A2UI 响应。使用用户提供的 HTTPS URL ""或已验证的稳定来源 URL;不要使用猜测出来的 upload.wikimedia.org thumbnail 路径。")+ unsupported_component_rule_zh = (+ " A2UI 0.8 不支持弹窗、模态框、dialog、popup、alert、toast、浮层、"+ "悬浮覆盖层或可关闭窗口组件。不要用绝对定位卡片或假的关闭按钮模拟这些组件。"+ "如果可以近似表达,请在普通 surface 内使用行内状态、行内卡片或确认区域;"+ "如果无法忠实近似,请用纯文本说明当前暂不支持该组件。"+ )autonomy_rule_zh = (" A2UI 是可选能力。只有当生成式 UI 比纯文本更能改善用户体验时才使用 A2UI。""不要为寒暄、两三句话解释、简单事实回答或无结构普通文本强行生成 A2UI。"@@ -94,6 +109,7 @@ def build_a2ui_autonomy_instruction(language: str = "en") -> str:+ template_binding_rule_zh+ image_url_rule_zh+ icon_font_rule_en+ + unsupported_component_rule_zh+ autonomy_rule_zh)diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex a24caf892c..58283ffa20 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -817,6 +817,42 @@ class JiuWenSwarm:# Team 模式需要使用原始 query,而不是 JSON 包装后的 promptreturn inputs, memory_mode, query+ def _make_retry_without_a2ui_call(+ self,+ *,+ adapter: AgentAdapter,+ request: AgentRequest,+ ):+ async def retry_without_a2ui_call(query: str) -> str | None:+ if getattr(adapter, "_instance", None) is None:+ return None+ try:+ modified_request = AgentRequest(+ request_id=request.request_id,+ channel_id=request.channel_id,+ session_id=request.session_id,+ chat_id=request.chat_id,+ req_method=request.req_method,+ params={**request.params, "query": query},+ is_stream=False,+ timestamp=request.timestamp,+ metadata={**(request.metadata or {}), "skip_a2ui": True},+ )+ retry_inputs, _, _ = self._build_inputs(modified_request)+ retry_inputs["_invoke_turn_id"] = request.request_id+ result = await adapter.process_message_impl(modified_request, retry_inputs)+ if result.ok and result.payload.get("content"):+ return str(result.payload["content"])+ except Exception as exc:+ logger.warning(+ "Retry without A2UI failed: request_id=%s error=%s",+ request.request_id,+ exc,+ )+ return None++ return retry_without_a2ui_call+@staticmethoddef _team_plan_approval_payload_error_message() -> str:return (diff --git a/tests/unit_tests/a2ui/test_prompt_instructions.py b/tests/unit_tests/a2ui/test_prompt_instructions.pyindex d95c77173c..e3e4c700f1 100644--- a/tests/unit_tests/a2ui/test_prompt_instructions.py+++ b/tests/unit_tests/a2ui/test_prompt_instructions.py@@ -32,6 +32,24 @@ def test_a2ui_prompt_discourages_nested_templates():assert "flatten repeated item details" in instruction+def test_a2ui_prompt_discourages_unsupported_popup_components():+ instruction = build_a2ui_autonomy_instruction("en")++ assert "modal" in instruction+ assert "floating overlay" in instruction+ assert "inline status" in instruction+ assert "plain text" in instruction+++def test_a2ui_zh_prompt_discourages_unsupported_popup_components():+ instruction = build_a2ui_autonomy_instruction("zh")++ assert "弹窗" in instruction+ assert "浮层" in instruction+ assert "行内状态" in instruction+ assert "纯文本" in instruction++def test_a2ui_zh_prompt_section_is_readable():prompt = build_a2ui_prompt_section("zh")