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): resolve A2UI rendering and interaction issues
z2tng60a88dc5e8da
diff --git a/jiuwenswarm/agents/harness/common/rails/response_prompt_rail.py b/jiuwenswarm/agents/harness/common/rails/response_prompt_rail.pyindex b8495a8e23..80086cd31e 100644--- a/jiuwenswarm/agents/harness/common/rails/response_prompt_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/response_prompt_rail.py@@ -19,6 +19,8 @@ from jiuwenswarm.agents.harness.common.prompt.prompt_builder import (logger = logging.getLogger(__name__)+SKIP_A2UI_PROMPT_CONTEXT_KEY = "skip_a2ui"+class ResponsePromptRail(DeepAgentRail):"""Inject the response section as an independent prompt section."""@@ -49,6 +51,8 @@ class ResponsePromptRail(DeepAgentRail):extra = getattr(ctx, "extra", None)if isinstance(extra, dict) and channel:extra[JIUWENSWARM_CHANNEL_CONTEXT_KEY] = channel+ if isinstance(extra, dict) and self._should_skip_a2ui(ctx):+ extra[SKIP_A2UI_PROMPT_CONTEXT_KEY] = Trueasync def before_model_call(self, ctx: AgentCallbackContext) -> None:if self.system_prompt_builder is None:@@ -56,7 +60,20 @@ class ResponsePromptRail(DeepAgentRail):language = self.system_prompt_builder.language or "cn"self.system_prompt_builder.add_section(_response_prompt(language))- self._sync_a2ui_prompt_section(self._resolve_channel(ctx))+ self._sync_a2ui_prompt_section(+ self._resolve_channel(ctx),+ skip_a2ui=self._should_skip_a2ui(ctx),+ )++ def _should_skip_a2ui(self, ctx: AgentCallbackContext) -> bool:+ inputs = getattr(ctx, "inputs", None)+ if isinstance(inputs, dict) and inputs.get(SKIP_A2UI_PROMPT_CONTEXT_KEY) is True:+ return True+ if getattr(inputs, SKIP_A2UI_PROMPT_CONTEXT_KEY, False) is True:+ return True++ extra = getattr(ctx, "extra", None)+ return isinstance(extra, dict) and extra.get(SKIP_A2UI_PROMPT_CONTEXT_KEY) is Truedef _resolve_channel(self, ctx: AgentCallbackContext) -> str | None:"""Read the request channel from callback inputs when available."""@@ -93,7 +110,7 @@ class ResponsePromptRail(DeepAgentRail):return None- def _sync_a2ui_prompt_section(self, channel: str | None) -> None:+ def _sync_a2ui_prompt_section(self, channel: str | None, *, skip_a2ui: bool = False) -> None:"""Inject or remove the A2UI prompt section from runtime config."""if self.system_prompt_builder is None:return@@ -101,6 +118,10 @@ class ResponsePromptRail(DeepAgentRail):try:from jiuwenswarm.server.runtime.a2ui.integration import is_a2ui_channel+ if skip_a2ui:+ self.system_prompt_builder.remove_section(LocalSectionName.A2UI)+ return+if not is_a2ui_channel(channel):self.system_prompt_builder.remove_section(LocalSectionName.A2UI)returndiff --git a/jiuwenswarm/channels/web/frontend/scripts/test-a2ui-action-defaults.mjs b/jiuwenswarm/channels/web/frontend/scripts/test-a2ui-action-defaults.mjsindex 1bd50ef4b8..105128c73a 100644--- a/jiuwenswarm/channels/web/frontend/scripts/test-a2ui-action-defaults.mjs+++ b/jiuwenswarm/channels/web/frontend/scripts/test-a2ui-action-defaults.mjs@@ -6,9 +6,10 @@ import ts from 'typescript';const root = new URL('..', import.meta.url);const sourceUrl = new URL('src/features/a2ui/actionDefaults.ts', root);+const helperUrl = new URL('src/features/a2ui/formDefaults.ts', root);const tempDir = await mkdtemp(join(tmpdir(), 'a2ui-action-defaults-'));-async function importTsModule(url) {+async function transpileTsModule(url, outputFileName) {const source = await readFile(url, 'utf8');const transpiled = ts.transpileModule(source, {compilerOptions: {@@ -17,8 +18,17 @@ async function importTsModule(url) {importsNotUsedAsValues: ts.ImportsNotUsedAsValues.Remove,},});- const outputPath = join(tempDir, 'actionDefaults.mjs');- await writeFile(outputPath, transpiled.outputText, 'utf8');+ const outputPath = join(tempDir, outputFileName);+ const outputText = outputFileName === 'actionDefaults.mjs'+ ? transpiled.outputText.replaceAll("from './formDefaults'", "from './formDefaults.mjs'")+ : transpiled.outputText;+ await writeFile(outputPath, outputText, 'utf8');+ return outputPath;+}++async function importTsModule(url) {+ await transpileTsModule(helperUrl, 'formDefaults.mjs');+ const outputPath = await transpileTsModule(url, 'actionDefaults.mjs');return import(`file://${outputPath.replace(/\\/g, '/')}`);}@@ -328,4 +338,128 @@ assert.deepEqual('defaults recorded in an earlier surface update should be available to later buttons',);+clearA2UIActionDefaults();+recordA2UIActionDefaults([+ {+ surfaceUpdate: {+ surfaceId: 'surface-1',+ components: [+ {+ id: 'multi-choice',+ component: {+ MultipleChoice: {+ variant: 'checkbox',+ selections: { path: '/foods' },+ options: [+ { label: { literalString: 'Chinese' }, value: 'chinese' },+ { label: { literalString: 'Western' }, value: 'western' },+ ],+ },+ },+ },+ {+ id: 'submit',+ component: {+ Button: {+ child: 'submit-label',+ action: {+ name: 'submit_form',+ context: [{ key: 'foods', value: { path: '/foods' } }],+ },+ },+ },+ },+ ],+ },+ },+]);++assert.deepEqual(+ enrichA2UIClientEventWithDefaults({+ userAction: {+ name: 'submit_form',+ sourceComponentId: 'submit',+ surfaceId: 'surface-1',+ timestamp: '2026-05-30T00:00:00.000Z',+ context: { foods: null },+ },+ }).userAction.context,+ { foods: null },+ 'checkbox-style MultipleChoice should not submit the first option as an invisible default',+);++clearA2UIActionDefaults();+recordA2UIActionDefaults([+ {+ surfaceUpdate: {+ surfaceId: 'surface-1',+ components: [+ {+ id: 'form-field',+ component: {+ TextField: {+ text: { path: '/name', literalString: 'Alice' },+ },+ },+ },+ {+ id: 'slider-field',+ component: {+ Slider: {+ value: { path: '/age', literalNumber: 30 },+ },+ },+ },+ {+ id: 'checkbox-field',+ component: {+ CheckBox: {+ value: { path: '/accepted', literalBoolean: true },+ },+ },+ },+ {+ id: 'date-field',+ component: {+ DateTimeInput: {+ value: { path: '/date', literalString: '2026-06-14' },+ },+ },+ },+ {+ id: 'submit',+ component: {+ Button: {+ child: 'submit-label',+ action: {+ name: 'submit_form',+ context: [+ { key: 'name', value: { path: '/name' } },+ { key: 'age', value: { path: '/age' } },+ { key: 'accepted', value: { path: '/accepted' } },+ { key: 'date', value: { path: '/date' } },+ ],+ },+ },+ },+ },+ ],+ },+ },+]);++assert.deepEqual(+ enrichA2UIClientEventWithDefaults({+ userAction: {+ name: 'submit_form',+ sourceComponentId: 'submit',+ surfaceId: 'surface-1',+ timestamp: '2026-05-30T00:00:00.000Z',+ context: { name: null, age: null, accepted: null, date: null },+ },+ }).userAction.context,+ { name: 'Alice', age: 30, accepted: true, date: '2026-06-14' },+ 'literal defaults for TextField, Slider, CheckBox, and DateTimeInput should be submitted',+);+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 a61f2e760b..b33be864ab 100644--- a/jiuwenswarm/channels/web/frontend/src/App.tsx+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx@@ -204,6 +204,7 @@ function AppContent() {const [shareExportSnapshot, setShareExportSnapshot] = useState<ShareImageSnapshot | null>(null);const [restartSeenDisconnect, setRestartSeenDisconnect] = useState(false);const [appliedWithoutRestart, setAppliedWithoutRestart] = useState(false);+ const [a2uiRefreshPending, setA2uiRefreshPending] = useState(false);const [newSessionToastVisible, setNewSessionToastVisible] = useState(false);const [heartbeatToastVisible, setHeartbeatToastVisible] = useState(false);const [heartbeatToastMessage, setHeartbeatToastMessage] = useState('');@@ -467,6 +468,7 @@ function AppContent() {setRestartSuccess(false);setRestartSeenDisconnect(false);setAppliedWithoutRestart(false);+ setA2uiRefreshPending(false);}, [clearRestartAutoCloseTimer]);const clearNewSessionToastTimer = useCallback(() => {@@ -537,14 +539,11 @@ function AppContent() {'config.set',updates);- if ('a2ui_enabled' in updates) {- setA2UIFeatureEnabled(normalizeA2UIEnabled(updates.a2ui_enabled));- }setServerConfig((prev) => {if (!prev) return updates;const next: Record<string, unknown> = { ...prev, ...updates };// Keep the bilingual memory_forbidden_description dictionary structure.- if (typeof prev.memory_forbidden_description === 'object' && prev.memory_forbidden_description !== null+ if (typeof prev?.memory_forbidden_description === 'object' && prev.memory_forbidden_description !== null&& !Array.isArray(prev.memory_forbidden_description) && updates.memory_forbidden_description !== undefined) {const prevDict = prev.memory_forbidden_description as Record<string, string>;const lang = i18n.language || 'zh';@@ -556,13 +555,24 @@ function AppContent() {setRestartModalOpen(true);setRestartSuccess(false);setRestartSeenDisconnect(false);- setAppliedWithoutRestart(payload?.applied_without_restart === true);- clearRestartAutoCloseTimer();- if (payload?.applied_without_restart === true) {+ if ('a2ui_enabled' in updates) {+ setAppliedWithoutRestart(false);+ setA2uiRefreshPending(true);setRestartSuccess(true);+ clearRestartAutoCloseTimer();restartAutoCloseTimerRef.current = window.setTimeout(() => {closeRestartModal();+ window.location.reload();}, 5000);+ } else {+ setAppliedWithoutRestart(payload?.applied_without_restart === true);+ clearRestartAutoCloseTimer();+ if (payload?.applied_without_restart === true) {+ setRestartSuccess(true);+ restartAutoCloseTimerRef.current = window.setTimeout(() => {+ closeRestartModal();+ }, 5000);+ }}}, [clearRestartAutoCloseTimer, closeRestartModal, request]);@@ -635,6 +645,7 @@ for (let i = payload.team.length; i < 10; i++) {}, [applyConfigSaveUiState, buildAgentsTeamsFlatConfig, request]);const saveAllConfigAndRestart = useCallback(async (payload: ConfigSaveAllPayload) => {+ const isA2UIChange = payload.config && 'a2ui_enabled' in payload.config;const result = await request<{ updated?: string[]; applied_without_restart?: boolean }>('config.save_all',payload as unknown as Record<string, unknown>@@ -664,7 +675,22 @@ for (let i = payload.team.length; i < 10; i++) {}return next;});- applyConfigSaveUiState(result?.applied_without_restart === true);+ if (isA2UIChange) {+ // Show modal then refresh page after 5 seconds+ setConfigError(null);+ setRestartModalOpen(true);+ setRestartSuccess(true);+ setRestartSeenDisconnect(false);+ setAppliedWithoutRestart(false);+ setA2uiRefreshPending(true);+ clearRestartAutoCloseTimer();+ restartAutoCloseTimerRef.current = window.setTimeout(() => {+ closeRestartModal();+ window.location.reload();+ }, 5000);+ } else {+ applyConfigSaveUiState(result?.applied_without_restart === true);+ }}, [applyConfigSaveUiState, buildAgentsTeamsFlatConfig, i18n.language, request]);useEffect(() => {@@ -1675,19 +1701,33 @@ for (let i = payload.team.length; i < 10; i++) {</div>)}<h3 className="text-base font-semibold text-text mb-1">- {!restartSuccess ? t('app.restarting') : appliedWithoutRestart ? t('app.configApplied') : t('app.restartSuccess')}+ {!restartSuccess+ ? t('app.restarting')+ : a2uiRefreshPending+ ? t('app.a2uiRefresh')+ : appliedWithoutRestart+ ? t('app.configApplied')+ : t('app.restartSuccess')}</h3><p className="text-sm text-text-muted mb-5">{!restartSuccess? t('app.restartWaiting')- : appliedWithoutRestart- ? t('app.configAppliedDesc')- : t('app.restartSuccessDesc')}+ : a2uiRefreshPending+ ? t('app.a2uiRefreshDesc')+ : appliedWithoutRestart+ ? t('app.configAppliedDesc')+ : t('app.restartSuccessDesc')}</p>{restartSuccess && (<buttontype="button"- onClick={closeRestartModal}+ onClick={() => {+ if (a2uiRefreshPending) {+ window.location.reload();+ } else {+ closeRestartModal();+ }+ }}className="btn primary !px-4 !py-2">{t('common.ok')}diff --git a/jiuwenswarm/channels/web/frontend/src/components/AgentPanel/FileViewer.tsx b/jiuwenswarm/channels/web/frontend/src/components/AgentPanel/FileViewer.tsxindex b4bdb41afe..297b09f106 100644--- a/jiuwenswarm/channels/web/frontend/src/components/AgentPanel/FileViewer.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/AgentPanel/FileViewer.tsx@@ -416,6 +416,7 @@ export function FileViewer({ filePath, fileName, reloadNonce = 0 }: FileViewerPr<ChatTimelineListmessages={historyMessages}mode={historyPreviewMode ?? undefined}+ disableA2UIInteraction={true}/></div>)diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsxindex 69edf98fda..b3589a4cfe 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx@@ -81,6 +81,7 @@ function TeamLeaderPlainTextMessage({isStreaming = false,showAvatar = true,fileItems,+ disableA2UIInteraction = false,}: {member?: string;content: string;@@ -88,6 +89,7 @@ function TeamLeaderPlainTextMessage({isStreaming?: boolean;showAvatar?: boolean;fileItems?: FileDownloadItem[];+ disableA2UIInteraction?: boolean;}) {return (<TeamMemberMessageFrame@@ -102,6 +104,7 @@ function TeamLeaderPlainTextMessage({content={content}messageId={messageId}isStreaming={isStreaming}+ disableInteraction={disableA2UIInteraction}testId="team-leader-message-body"/></div>@@ -178,12 +181,14 @@ interface MessageItemProps {message: Message;autoSpeak?: boolean;showAvatar?: boolean;+ disableA2UIInteraction?: boolean;}export function MessageItem({message,autoSpeak = false,showAvatar = true,+ disableA2UIInteraction = false,}: MessageItemProps) {const { t } = useTranslation();const {@@ -465,6 +470,7 @@ export function MessageItem({isStreaming={isStreaming}showAvatar={showAvatar}fileItems={fileItems}+ disableA2UIInteraction={disableA2UIInteraction}/>);}@@ -518,6 +524,7 @@ export function MessageItem({content={content}messageId={id}isStreaming={true}+ disableInteraction={disableA2UIInteraction}testId="thinking-body"/>)@@ -531,6 +538,7 @@ export function MessageItem({<A2UIMessageContentcontent={content}messageId={id}+ disableInteraction={disableA2UIInteraction}testId="thinking-body"/>)}diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageList.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageList.tsxindex 48a105bb72..1b9d2f8dfd 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageList.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageList.tsx@@ -10,6 +10,7 @@ import { MessageItem, getMessageActor } from './MessageItem';import { ToolGroupDisplay } from './ToolGroupDisplay';import { useChatStore, useSessionStore } from '../../stores';import { isTeamMemberCollaborationMessage } from './teamEventUtils';+import { isA2UIClientEventContent } from '../../features/a2ui/a2uiContent';interface MessageListProps {messages: Message[];@@ -19,6 +20,7 @@ interface ChatTimelineListProps {messages: Message[];executions?: ToolExecution[];mode?: string;+ disableA2UIInteraction?: boolean;}type TimelineItem =@@ -83,7 +85,11 @@ function buildTimelineItems(executions: ToolExecution[]): TimelineItem[] {const messageItems: TimelineItem[] = messages- .filter((msg) => msg.role !== 'tool')+ .filter((msg) => {+ if (msg.role === 'tool') return false;+ if (msg.role === 'user' && isA2UIClientEventContent(msg.content)) return false;+ return true;+ }).map((message, index) => ({type: 'message',key: `message-${message.id}-${index}`,@@ -221,6 +227,7 @@ export function ChatTimelineList({messages,executions = [],mode = 'default',+ disableA2UIInteraction = false,}: ChatTimelineListProps) {const isTeamMode = mode === 'team';const renderItems = useMemo(@@ -241,6 +248,7 @@ export function ChatTimelineList({key={item.key}message={item.message}showAvatar={item.showAvatar}+ disableA2UIInteraction={disableA2UIInteraction}/>);}diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIErrorBoundary.tsx b/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIErrorBoundary.tsxnew file mode 100644index 0000000000..b0a6d40b36--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIErrorBoundary.tsx@@ -0,0 +1,59 @@+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++import { Component, type ErrorInfo, type ReactNode } from 'react';+import { a2uiError } from './formDefaults';++interface A2UIErrorBoundaryProps {+ children: ReactNode;+ fallback?: ReactNode;+ onError?: (error: Error, errorInfo: ErrorInfo) => void;+}++interface A2UIErrorBoundaryState {+ hasError: boolean;+ error: Error | null;+}++/**+ * Error boundary for A2UI components to prevent page crashes+ * when rendering invalid or missing component references.+ */+export class A2UIErrorBoundary extends Component<+ A2UIErrorBoundaryProps,+ A2UIErrorBoundaryState+> {+ constructor(props: A2UIErrorBoundaryProps) {+ super(props);+ this.state = { hasError: false, error: null };+ }++ static getDerivedStateFromError(error: Error): A2UIErrorBoundaryState {+ return { hasError: true, error };+ }++ componentDidCatch(error: Error, errorInfo: ErrorInfo) {+ a2uiError('[A2UI Error Boundary]', { error, errorInfo });+ this.props.onError?.(error, errorInfo);+ }++ render() {+ if (this.state.hasError) {+ if (this.props.fallback) {+ return this.props.fallback;+ }++ return (+ <div className="a2ui-error-boundary p-4 border border-danger/30 rounded-lg bg-danger/5">+ <p className="text-danger text-sm font-medium mb-1">+ 界面内容暂时无法显示+ </p>+ <p className="text-text-muted text-xs">+ 请稍后重试或重新生成结果+ </p>+ </div>+ );+ }++ return this.props.children;+ }+}diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIMessageContent.tsx b/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIMessageContent.tsxindex e42154049b..efbcaad2d9 100644--- a/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIMessageContent.tsx+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIMessageContent.tsx@@ -12,11 +12,14 @@ import {import { recordA2UIActionDefaults } from './actionDefaults';import { isA2UIFeatureEnabled } from './featureConfig';import { getA2UIRenderer } from './rendererRegistry';+import { A2UIErrorBoundary } from './A2UIErrorBoundary';+import { a2uiError } from './formDefaults';interface A2UIMessageContentProps {content: string;messageId: string;isStreaming?: boolean;+ disableInteraction?: boolean;testId?: string;}@@ -38,6 +41,7 @@ export function A2UIMessageContent({content,messageId,isStreaming = false,+ disableInteraction = false,testId,}: A2UIMessageContentProps) {const { processMessages } = useA2UIActions();@@ -45,10 +49,11 @@ export function A2UIMessageContent({const a2uiEnabled = isA2UIFeatureEnabled();const renderParts = useMemo<RenderPart[]>(() => {- return parseA2UIContent(content, {+ const parsed = parseA2UIContent(content, {enabled: a2uiEnabled,isStreaming,- }).map((part, index) => {+ });+ return parsed.map((part, index) => {if (part.kind === 'text') {return {kind: 'text',@@ -66,17 +71,76 @@ export function A2UIMessageContent({surfaceIds: extractA2UISurfaceIds(messages),};});- }, [a2uiEnabled, content, isStreaming, namespace]);+ }, [a2uiEnabled, content, isStreaming, namespace, messageId]);useEffect(() => {for (const part of renderParts) {if (a2uiEnabled && part.kind === 'a2ui') {recordA2UIActionDefaults(part.messages);- processMessages(part.messages);++ try {+ processMessages(part.messages);+ } catch (err) {+ // Enhanced error logging with context+ const surfaceIds = part.surfaceIds.join(', ');+ const msgCount = part.messages.length;+ a2uiError('[A2UI] processMessages failed:', {+ error: err instanceof Error ? err.message : String(err),+ protocolVersion: part.protocolVersion,+ surfaceIds,+ messageCount: msgCount,+ stack: err instanceof Error ? err.stack : undefined,+ });++ // Also log the raw A2UI messages for debugging (truncated)+ try {+ const raw = JSON.stringify(part.messages);+ if (raw.length > 2000) {+ a2uiError('[A2UI] Raw A2UI payload (truncated):', raw.substring(0, 2000) + '...');+ } else {+ a2uiError('[A2UI] Raw A2UI payload:', part.messages);+ }+ } catch {+ a2uiError('[A2UI] Could not serialize A2UI messages');+ }+ }}}}, [a2uiEnabled, processMessages, renderParts]);+ // Dev-only diagnostic: log horizontal overflow containers after DOM layout+ useEffect(() => {+ if (!import.meta.env.DEV) return;++ const rafId = window.requestAnimationFrame(() => {+ const selectors = [+ '.a2ui-surface .a2ui-row > section',+ '.a2ui-surface .a2ui-list[data-direction="horizontal"] > section',+ ];++ document.querySelectorAll(selectors.join(',')).forEach((el, index) => {+ const element = el as HTMLElement;+ const style = getComputedStyle(element);+ const hasOverflow = element.scrollWidth > element.clientWidth + 2;++ if (hasOverflow) {+ console.log('[A2UI-SCROLL] horizontal overflow:', {+ index,+ tag: element.tagName,+ clientWidth: element.clientWidth,+ scrollWidth: element.scrollWidth,+ hasOverflow,+ overflowX: style.overflowX,+ scrollbarWidth: style.scrollbarWidth,+ className: element.className,+ });+ }+ });+ });++ return () => window.cancelAnimationFrame(rafId);+ }, [renderParts]);+return (<div className="chat-text a2ui-message-content" data-testid={testId}>{renderParts.map((part) => {@@ -102,7 +166,15 @@ export function A2UIMessageContent({return (<div key={part.key} className="a2ui-message-content__surfaces">{part.surfaceIds.map((surfaceId) => (- <Renderer key={surfaceId} surfaceId={surfaceId} />+ <A2UIErrorBoundary key={surfaceId}>+ {disableInteraction ? (+ <div className="pointer-events-none opacity-75">+ <Renderer surfaceId={surfaceId} />+ </div>+ ) : (+ <Renderer surfaceId={surfaceId} />+ )}+ </A2UIErrorBoundary>))}</div>);diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/CheckBoxWithDefaults.tsx b/jiuwenswarm/channels/web/frontend/src/features/a2ui/CheckBoxWithDefaults.tsxnew file mode 100644index 0000000000..b8c92daedb--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/CheckBoxWithDefaults.tsx@@ -0,0 +1,68 @@+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++import { useCallback, useId } from 'react';+import type { ChangeEvent } from 'react';+import {+ classMapToString,+ stylesToObject,+ useA2UIComponent,+ type A2UIComponentProps,+ type AnyComponentNode,+} from '@a2ui/react';+import { hostWeightStyle, useA2UIBoundValue } from './fieldBinding';++type CheckBoxNodeLike = Extract<AnyComponentNode, { type: 'CheckBox' }>;++export function CheckBoxWithDefaults({+ node,+ surfaceId,+}: A2UIComponentProps<CheckBoxNodeLike>) {+ const { theme, resolveString, resolveBoolean, setValue, getValue } = useA2UIComponent(+ node,+ surfaceId,+ );+ const props = node.properties;+ const id = useId();+ const label = resolveString(props.label);+ const readBoolean = useCallback((value: unknown) => Boolean(value), []);+ const [checked, commitChecked] = useA2UIBoundValue({+ path: props.value?.path,+ initialValue: resolveBoolean(props.value) ?? false,+ literalValue: props.value?.literalBoolean,+ getValue,+ setValue,+ fromModelValue: readBoolean,+ });++ const updateFromInput = useCallback(+ (event: ChangeEvent<HTMLInputElement>) => {+ commitChecked(event.target.checked);+ },+ [commitChecked],+ );++ return (+ <div className="a2ui-checkbox" style={hostWeightStyle(node.weight)}>+ <section+ className={classMapToString(theme.components.CheckBox.container)}+ style={stylesToObject(theme.additionalStyles?.CheckBox)}+ >+ <input+ type="checkbox"+ id={id}+ checked={checked}+ onChange={updateFromInput}+ className={classMapToString(theme.components.CheckBox.element)}+ />+ {label && (+ <label+ htmlFor={id}+ className={classMapToString(theme.components.CheckBox.label)}+ >+ {label}+ </label>+ )}+ </section>+ </div>+ );+}diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/DateTimeInputWithDefaults.tsx b/jiuwenswarm/channels/web/frontend/src/features/a2ui/DateTimeInputWithDefaults.tsxnew file mode 100644index 0000000000..529b8f8caf--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/DateTimeInputWithDefaults.tsx@@ -0,0 +1,75 @@+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++import { useCallback, useId } from 'react';+import type { ChangeEvent } from 'react';+import {+ classMapToString,+ stylesToObject,+ useA2UIComponent,+ type A2UIComponentProps,+ type AnyComponentNode,+} from '@a2ui/react';+import { hostWeightStyle, useA2UIBoundValue } from './fieldBinding';++type DateTimeInputNodeLike = Extract<AnyComponentNode, { type: 'DateTimeInput' }>;++type DateInputKind = 'date' | 'time' | 'datetime-local';++function dateInputKind(enableDate: boolean, enableTime: boolean): DateInputKind {+ if (enableDate && enableTime) return 'datetime-local';+ return enableTime ? 'time' : 'date';+}++function dateInputLabel(enableDate: boolean, enableTime: boolean): string {+ if (enableDate && enableTime) return 'Date & Time';+ return enableTime ? 'Time' : 'Date';+}++export function DateTimeInputWithDefaults({+ node,+ surfaceId,+}: A2UIComponentProps<DateTimeInputNodeLike>) {+ const { theme, resolveString, setValue, getValue } = useA2UIComponent(node, surfaceId);+ const props = node.properties;+ const id = useId();+ const enableDate = props.enableDate ?? true;+ const enableTime = props.enableTime ?? false;+ const stringifyValue = useCallback((value: unknown) => String(value), []);+ const hasVisibleDefault = useCallback((value: string) => value !== '', []);+ const [value, commitValue] = useA2UIBoundValue({+ path: props.value?.path,+ initialValue: resolveString(props.value) ?? '',+ getValue,+ setValue,+ fromModelValue: stringifyValue,+ shouldSeedInitial: hasVisibleDefault,+ });++ const updateFromInput = useCallback(+ (event: ChangeEvent<HTMLInputElement>) => {+ commitValue(event.target.value);+ },+ [commitValue],+ );++ return (+ <div className="a2ui-datetime-input" style={hostWeightStyle(node.weight)}>+ <section className={classMapToString(theme.components.DateTimeInput.container)}>+ <label+ htmlFor={id}+ className={classMapToString(theme.components.DateTimeInput.label)}+ >+ {dateInputLabel(enableDate, enableTime)}+ </label>+ <input+ type={dateInputKind(enableDate, enableTime)}+ id={id}+ value={value}+ onChange={updateFromInput}+ className={classMapToString(theme.components.DateTimeInput.element)}+ style={stylesToObject(theme.additionalStyles?.DateTimeInput)}+ />+ </section>+ </div>+ );+}diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/MultipleChoiceWithDefaults.tsx b/jiuwenswarm/channels/web/frontend/src/features/a2ui/MultipleChoiceWithDefaults.tsxindex 6d14544242..d6285d8e93 100644--- a/jiuwenswarm/channels/web/frontend/src/features/a2ui/MultipleChoiceWithDefaults.tsx+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/MultipleChoiceWithDefaults.tsx@@ -1,6 +1,6 @@// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.-import { useCallback, useEffect, useId } from 'react';+import { useCallback, useId, useMemo, useState } from 'react';import type { CSSProperties, ChangeEvent } from 'react';import {classMapToString,@@ -10,38 +10,36 @@ import {type AnyComponentNode,type DataValue,} from '@a2ui/react';+import {+ a2uiError,+ a2uiWarn,+ dualWriteA2UIValue,+ isMultiSelectChoice,+ literalArrayValues,+ visibleChoiceDefault as visibleChoiceDefaultValue,+} from './formDefaults';type MultipleChoiceNodeLike = Extract<AnyComponentNode, { type: 'MultipleChoice' }>;-function selectedValueFromData(value: DataValue | null): string | null {+function selectedValuesFromData(value: DataValue | null): string[] {if (Array.isArray(value)) {- for (const item of value) {- if (typeof item === 'string') {- return item;- }- }- return null;+ return value.filter((item): item is string => typeof item === 'string' && item !== '');}- return typeof value === 'string' ? value : null;-}--function isMissingSelection(value: DataValue | null): boolean {- return value === null || value === undefined || (Array.isArray(value) && value.length === 0);+ if (typeof value === 'string' && value !== '') {+ return [value];+ }+ return [];}export function visibleMultipleChoiceDefault(props: MultipleChoiceNodeLike['properties']): string | null {- const firstOption = props.options?.find((option) => typeof option.value === 'string');- if (firstOption) {- return firstOption.value;- }- for (const item of props.selections?.literalArray ?? []) {- if (typeof item === 'string') {- return item;- }+ const defaultValue = visibleChoiceDefaultValue(props as unknown as Record<string, unknown>);+ if (Array.isArray(defaultValue)) {+ const firstDefault = defaultValue.find((item): item is string => typeof item === 'string');+ return firstDefault ?? null;}- return null;+ return typeof defaultValue === 'string' ? defaultValue : null;}export function MultipleChoiceWithDefaults({@@ -52,33 +50,201 @@ export function MultipleChoiceWithDefaults({const props = node.properties;const id = useId();const selectionsPath = props.selections?.path;- const descriptionValue = (props as MultipleChoiceNodeLike['properties'] & {- description?: Parameters<typeof resolveString>[0];- }).description;- const description = resolveString(descriptionValue) ?? 'Select an item';++ // Read label from schema: try 'label' first, then 'description', then fallback+ const rawLabel = (props as unknown as Record<string, unknown>).label;+ const rawDescription = (props as unknown as Record<string, unknown>).description;+ const descriptionValue = rawLabel ?? rawDescription;+ const description = resolveString(descriptionValue as Parameters<typeof resolveString>[0]) ?? 'Select an item';++ const rawProps = props as unknown as Record<string, unknown>;+ const isMultiSelect = isMultiSelectChoice(rawProps);+ const literalDefaults = literalArrayValues(props.selections).filter(+ (item): item is string => typeof item === 'string' && item !== '',+ );const defaultValue = visibleMultipleChoiceDefault(props);const dataValue = selectionsPath ? getValue(selectionsPath) : null;- const selectedValue = selectedValueFromData(dataValue) ?? defaultValue ?? '';+ const selectedValues = selectedValuesFromData(dataValue);+ const effectiveSelectedValues = selectedValues.length > 0 ? selectedValues : literalDefaults;+ const maxAllowedSelections = rawProps.maxAllowedSelections as number | undefined;+ // @a2ui/web_core schema defines 'variant' but TS types may not include it+ const variant = rawProps.variant as string | undefined;+ const type = variant ?? rawProps.type as string | undefined;++ const isSingleSelect = !isMultiSelect;++ // Filterable search support+ const filterable = rawProps.filterable as boolean | undefined;+ const options = props.options ?? [];+ const shouldShowFilter = filterable === true || options.length >= 10;+ const [searchQuery, setSearchQuery] = useState('');- useEffect(() => {- if (selectionsPath && defaultValue !== null && isMissingSelection(getValue(selectionsPath))) {- setValue(selectionsPath, [defaultValue]);- }- }, [defaultValue, getValue, selectionsPath, setValue]);+ const filteredOptions = useMemo(() => {+ if (!shouldShowFilter || !searchQuery.trim()) return options;+ const q = searchQuery.trim().toLowerCase();+ return options.filter((option) => {+ const label = resolveString(option.label);+ const value = option.value;+ return (+ (label && label.toLowerCase().includes(q)) ||+ (value && value.toLowerCase().includes(q))+ );+ });+ }, [options, searchQuery, shouldShowFilter, resolveString]);- const handleChange = useCallback(+ const handleSingleChange = useCallback((event: ChangeEvent<HTMLSelectElement>) => {if (selectionsPath) {- setValue(selectionsPath, [event.target.value]);+ dualWriteA2UIValue(setValue, selectionsPath, [event.target.value]);}},- [selectionsPath, setValue]+ [selectionsPath, setValue],+ );++ const handleMultiChange = useCallback(+ (optionValue: string, checked: boolean) => {+ if (!selectionsPath) {+ a2uiWarn('[A2UI-MC] selectionsPath is undefined, cannot write');+ return;+ }++ // Single-select mode (maxAllowedSelections === 1): always replace+ if (isSingleSelect) {+ const nextValue = [optionValue];+ dualWriteA2UIValue(setValue, selectionsPath, nextValue);+ return;+ }++ // Multi-select mode: add/remove from array+ const currentValues = [...effectiveSelectedValues];+ if (checked) {+ if (!currentValues.includes(optionValue)) {+ currentValues.push(optionValue);+ }+ } else {+ const index = currentValues.indexOf(optionValue);+ if (index !== -1) {+ currentValues.splice(index, 1);+ }+ }++ // Respect maxAllowedSelections for multi-select+ if (maxAllowedSelections !== undefined && currentValues.length > maxAllowedSelections) {+ return;+ }++ dualWriteA2UIValue(setValue, selectionsPath, currentValues);+ },+ [selectionsPath, effectiveSelectedValues, maxAllowedSelections, isSingleSelect, setValue],);const hostStyle = (node.weight !== undefined ? { '--weight': node.weight } : {}) as CSSProperties;+ // Build label text with multi-select hint+ const labelText = useMemo(() => {+ if (isSingleSelect || maxAllowedSelections === undefined) return description;+ return `${description}(最多选 ${maxAllowedSelections} 项)`;+ }, [description, isSingleSelect, maxAllowedSelections]);++ // Render chips UI+ if (type === 'chips') {+ return (+ <div className="a2ui-multiplechoice" style={hostStyle}>+ <section className={classMapToString(theme.components.MultipleChoice.container)}>+ <label+ className={classMapToString(theme.components.MultipleChoice.label)}+ >+ {labelText}+ </label>+ {shouldShowFilter && (+ <input+ type="search"+ placeholder="搜索选项"+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}+ className="mb-2 px-3 py-1 border border-gray-300 rounded text-sm w-full"+ />+ )}+ <div className="flex flex-wrap gap-2">+ {filteredOptions.map((option) => {+ const optionValue = option.value;+ const isSelected = effectiveSelectedValues.includes(optionValue);+ return (+ <button+ key={optionValue}+ type="button"+ className={`px-3 py-1 rounded-full border ${+ isSelected+ ? 'bg-blue-500 text-white border-blue-500'+ : 'bg-white text-gray-700 border-gray-300 hover:border-blue-300'+ }`}+ aria-pressed={isSelected}+ onClick={() => {+ try {+ handleMultiChange(option.value, !isSelected);+ } catch (err) {+ a2uiError('[A2UI-MC] handleMultiChange threw:', err);+ }+ }}+ >+ {resolveString(option.label)}+ </button>+ );+ })}+ </div>+ </section>+ </div>+ );+ }++ // Render checkboxes UI+ if (isMultiSelect) {+ return (+ <div className="a2ui-multiplechoice" style={hostStyle}>+ <section className={classMapToString(theme.components.MultipleChoice.container)}>+ <label+ className={classMapToString(theme.components.MultipleChoice.label)}+ >+ {labelText}+ </label>+ {shouldShowFilter && (+ <input+ type="search"+ placeholder="搜索选项"+ value={searchQuery}+ onChange={(e) => setSearchQuery(e.target.value)}+ className="mb-2 px-3 py-1 border border-gray-300 rounded text-sm w-full"+ />+ )}+ <div className="flex flex-col gap-1">+ {filteredOptions.map((option) => {+ const optionValue = option.value;+ const isSelected = effectiveSelectedValues.includes(optionValue);+ return (+ <label+ key={optionValue}+ className="flex items-center gap-2 cursor-pointer"+ >+ <input+ type="checkbox"+ checked={isSelected}+ onChange={(e) => handleMultiChange(optionValue, e.target.checked)}+ className="w-4 h-4"+ />+ <span>{resolveString(option.label)}</span>+ </label>+ );+ })}+ </div>+ </section>+ </div>+ );+ }++ // Render single-select dropdown+ const selectedValue = selectedValues[0] ?? defaultValue ?? '';return (<div className="a2ui-multiplechoice" style={hostStyle}><section className={classMapToString(theme.components.MultipleChoice.container)}>@@ -86,7 +252,7 @@ export function MultipleChoiceWithDefaults({htmlFor={id}className={classMapToString(theme.components.MultipleChoice.label)}>- {description}+ {labelText}</label><selectname="data"@@ -94,7 +260,7 @@ export function MultipleChoiceWithDefaults({value={selectedValue}className={classMapToString(theme.components.MultipleChoice.element)}style={stylesToObject(theme.additionalStyles?.MultipleChoice)}- onChange={handleChange}+ onChange={handleSingleChange}>{(props.options ?? []).map((option) => (<option key={option.value} value={option.value}>diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/SliderWithDefaults.tsx b/jiuwenswarm/channels/web/frontend/src/features/a2ui/SliderWithDefaults.tsxnew file mode 100644index 0000000000..7307d0fc95--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/SliderWithDefaults.tsx@@ -0,0 +1,77 @@+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++import { useCallback, useId } from 'react';+import type { ChangeEvent } from 'react';+import {+ classMapToString,+ stylesToObject,+ useA2UIComponent,+ type A2UIComponentProps,+ type AnyComponentNode,+} from '@a2ui/react';+import { hostWeightStyle, useA2UIBoundValue } from './fieldBinding';++type SliderNodeLike = Extract<AnyComponentNode, { type: 'Slider' }>;++function numberFromModel(value: unknown): number {+ return Number(value);+}++export function SliderWithDefaults({+ node,+ surfaceId,+}: A2UIComponentProps<SliderNodeLike>) {+ const { theme, resolveNumber, resolveString, setValue, getValue } = useA2UIComponent(+ node,+ surfaceId,+ );+ const props = node.properties;+ const id = useId();+ const minValue = props.minValue ?? 0;+ const maxValue = props.maxValue ?? 0;+ const [value, commitValue] = useA2UIBoundValue({+ path: props.value?.path,+ initialValue: resolveNumber(props.value) ?? 0,+ literalValue: props.value?.literalNumber,+ getValue,+ setValue,+ fromModelValue: numberFromModel,+ });++ const updateFromInput = useCallback(+ (event: ChangeEvent<HTMLInputElement>) => {+ commitValue(Number(event.target.value));+ },+ [commitValue],+ );++ const labelValue = (props as unknown as Record<string, unknown>).label;+ const label = labelValue ? resolveString(labelValue as Parameters<typeof resolveString>[0]) : '';++ return (+ <div className="a2ui-slider" style={hostWeightStyle(node.weight)}>+ <section className={classMapToString(theme.components.Slider.container)}>+ <label+ htmlFor={id}+ className={classMapToString(theme.components.Slider.label)}+ >+ {label}+ </label>+ <input+ type="range"+ id={id}+ name="data"+ value={value}+ min={minValue}+ max={maxValue}+ onChange={updateFromInput}+ className={classMapToString(theme.components.Slider.element)}+ style={stylesToObject(theme.additionalStyles?.Slider)}+ />+ <span className={classMapToString(theme.components.Slider.label)}>+ {value}+ </span>+ </section>+ </div>+ );+}diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/TextFieldWithDefaults.tsx b/jiuwenswarm/channels/web/frontend/src/features/a2ui/TextFieldWithDefaults.tsxnew file mode 100644index 0000000000..a76e4af955--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/TextFieldWithDefaults.tsx@@ -0,0 +1,95 @@+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++import { useCallback, useId, useState } from 'react';+import type { ChangeEvent, HTMLInputTypeAttribute } from 'react';+import {+ classMapToString,+ stylesToObject,+ useA2UIComponent,+ type A2UIComponentProps,+ type AnyComponentNode,+} from '@a2ui/react';+import { hostWeightStyle, useA2UIBoundValue } from './fieldBinding';++type TextFieldNodeLike = Extract<AnyComponentNode, { type: 'TextField' }>;+type TextControlKind = 'shortText' | 'longText' | 'number' | 'date' | 'obscured';++function textControlKind(props: TextFieldNodeLike['properties']): TextControlKind {+ const extraProps = props as unknown as Record<string, unknown>;+ return String(extraProps.textFieldType ?? extraProps.type ?? 'shortText') as TextControlKind;+}++function htmlInputType(kind: TextControlKind): HTMLInputTypeAttribute {+ if (kind === 'obscured') return 'password';+ if (kind === 'number' || kind === 'date') return kind;+ return 'text';+}++export function TextFieldWithDefaults({+ node,+ surfaceId,+}: A2UIComponentProps<TextFieldNodeLike>) {+ const { theme, resolveString, setValue, getValue } = useA2UIComponent(node, surfaceId);+ const props = node.properties;+ const id = useId();+ const label = resolveString(props.label);+ const fieldKind = textControlKind(props);+ const validationRegexp = props.validationRegexp;+ const stringifyValue = useCallback((value: unknown) => String(value), []);+ const hasVisibleDefault = useCallback((value: string) => value !== '', []);+ const [value, commitValue] = useA2UIBoundValue({+ path: props.text?.path,+ initialValue: resolveString(props.text) ?? '',+ getValue,+ setValue,+ fromModelValue: stringifyValue,+ shouldSeedInitial: hasVisibleDefault,+ });+ const [_isValid, setIsValid] = useState(true);++ const updateFromInput = useCallback(+ (event: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {+ const newValue = event.target.value;+ commitValue(newValue);+ if (validationRegexp) {+ setIsValid(new RegExp(validationRegexp).test(newValue));+ }+ },+ [commitValue, validationRegexp],+ );++ return (+ <div className="a2ui-textfield" style={hostWeightStyle(node.weight)}>+ <section className={classMapToString(theme.components.TextField.container)}>+ {label && (+ <label+ htmlFor={id}+ className={classMapToString(theme.components.TextField.label)}+ >+ {label}+ </label>+ )}+ {fieldKind === 'longText' ? (+ <textarea+ id={id}+ value={value}+ onChange={updateFromInput}+ placeholder="Please enter a value"+ className={classMapToString(theme.components.TextField.element)}+ style={stylesToObject(theme.additionalStyles?.TextField)}+ />+ ) : (+ <input+ type={htmlInputType(fieldKind)}+ id={id}+ value={value}+ onChange={updateFromInput}+ placeholder="Please enter a value"+ className={classMapToString(theme.components.TextField.element)}+ style={stylesToObject(theme.additionalStyles?.TextField)}+ />+ )}+ </section>+ </div>+ );+}diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/a2ui.css b/jiuwenswarm/channels/web/frontend/src/features/a2ui/a2ui.cssnew file mode 100644index 0000000000..67626aa6d5--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/a2ui.css@@ -0,0 +1,136 @@+/* Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. */++/* A2UI Component Styles */++/* ─── Horizontal scrollable containers (utility class) ─── */+.a2ui-horizontal-scroll {+ overflow-x: auto;+ scrollbar-width: thin;+ scrollbar-color: #888 #f1f1f1;+}++.a2ui-horizontal-scroll::-webkit-scrollbar {+ height: 8px;+}++.a2ui-horizontal-scroll::-webkit-scrollbar-track {+ background: #f1f1f1;+ border-radius: 4px;+}++.a2ui-horizontal-scroll::-webkit-scrollbar-thumb {+ background: #888;+ border-radius: 4px;+}++.a2ui-horizontal-scroll::-webkit-scrollbar-thumb:hover {+ background: #555;+}++/* ─── Row component ─── */+/* Use body prefix to exceed library specificity (.a2ui-surface .a2ui-row) */++body .a2ui-surface .a2ui-row {+ max-width: 100%;+ min-width: 0;+}++body .a2ui-surface .a2ui-row > section {+ max-width: 100%;+ min-width: 0;+ flex-wrap: nowrap;+ overflow-x: auto;+ overflow-y: hidden;+ padding-bottom: 8px;+ scrollbar-width: thin;+ scrollbar-color: #888 #f1f1f1;+ -webkit-overflow-scrolling: touch;+}++/* Distribution alignment (keep data-attribute selectors) */+body .a2ui-surface .a2ui-row[data-distribution="spaceBetween"] > section {+ justify-content: space-between;+}++body .a2ui-surface .a2ui-row[data-distribution="spaceAround"] > section {+ justify-content: space-around;+}++body .a2ui-surface .a2ui-row[data-distribution="spaceEvenly"] > section {+ justify-content: space-evenly;+}++body .a2ui-surface .a2ui-row[data-distribution="center"] > section {+ justify-content: center;+}++body .a2ui-surface .a2ui-row[data-distribution="end"] > section {+ justify-content: flex-end;+}++/* Item alignment */+body .a2ui-surface .a2ui-row[data-alignment="center"] > section {+ align-items: center;+}++body .a2ui-surface .a2ui-row[data-alignment="end"] > section {+ align-items: flex-end;+}++body .a2ui-surface .a2ui-row[data-alignment="stretch"] > section {+ align-items: stretch;+}++/* ─── Horizontal List component ─── */+/* Override library's scrollbar-width: none on the inner <section> */++body .a2ui-surface .a2ui-list[data-direction="horizontal"] {+ max-width: 100%;+ min-width: 0;+}++body .a2ui-surface .a2ui-list[data-direction="horizontal"] > section {+ max-width: 100%;+ min-width: 0;+ overflow-x: auto !important;+ overflow-y: hidden;+ padding-bottom: 8px;+ scrollbar-width: thin !important;+ scrollbar-color: #888 #f1f1f1;+ -webkit-overflow-scrolling: touch;+}++/* Override library's flex: 1 0 fit-content and max-width on List children */+body .a2ui-surface .a2ui-list[data-direction="horizontal"] > section > * {+ flex: 0 0 auto;+ max-width: none;+}++/* ─── WebKit scrollbar styles (Edge / Chrome) ─── */+body .a2ui-surface .a2ui-row > section::-webkit-scrollbar,+body .a2ui-surface .a2ui-list[data-direction="horizontal"] > section::-webkit-scrollbar {+ height: 8px;+}++body .a2ui-surface .a2ui-row > section::-webkit-scrollbar-track,+body .a2ui-surface .a2ui-list[data-direction="horizontal"] > section::-webkit-scrollbar-track {+ background: rgba(0, 0, 0, 0.08);+ border-radius: 999px;+}++body .a2ui-surface .a2ui-row > section::-webkit-scrollbar-thumb,+body .a2ui-surface .a2ui-list[data-direction="horizontal"] > section::-webkit-scrollbar-thumb {+ background: rgba(0, 0, 0, 0.28);+ border-radius: 999px;+}++body .a2ui-surface .a2ui-row > section::-webkit-scrollbar-thumb:hover,+body .a2ui-surface .a2ui-list[data-direction="horizontal"] > section::-webkit-scrollbar-thumb:hover {+ background: rgba(0, 0, 0, 0.38);+}++/* ─── TextField obscured type (password) ─── */+.a2ui-textfield input[type="password"] {+ font-family: 'password';+ letter-spacing: 0.125em;+}diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/a2uiContent.ts b/jiuwenswarm/channels/web/frontend/src/features/a2ui/a2uiContent.tsindex 58dbc14bb8..a4de50936e 100644--- a/jiuwenswarm/channels/web/frontend/src/features/a2ui/a2uiContent.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/a2uiContent.ts@@ -157,10 +157,54 @@ function makeA2UIPart(messages: ServerToClientMessage[]): A2UIContentPart {function invalidA2UIFallback(): A2UIContentPart {return {kind: 'text',- text: '[A2UI content could not be rendered]',+ text: '界面内容暂时无法显示,请稍后重试或重新生成结果。',};}+/**+ * Try to extract readable text from malformed A2UI content.+ * This helps when the model generates A2UI-like content but with syntax errors.+ */+function extractTextFromMalformedA2UI(content: string): string | null {+ // Try to extract content between tags even if JSON is invalid+ const openTagIndex = content.indexOf(A2UI_OPEN_TAG);+ const closeTagIndex = content.indexOf(A2UI_CLOSE_TAG);++ if (openTagIndex >= 0 && closeTagIndex > openTagIndex) {+ const body = content.slice(+ openTagIndex + A2UI_OPEN_TAG.length,+ closeTagIndex,+ );+ // Try to find any readable text in the body+ // Look for text content in JSON-like structures+ const textMatches = body.match(/"text"\s*:\s*"([^"]+)"/g);+ if (textMatches && textMatches.length > 0) {+ const extractedTexts = textMatches+ .map((match) => {+ const textContent = match.match(/"text"\s*:\s*"([^"]+)"/);+ return textContent?.[1] ?? '';+ })+ .filter(Boolean);+ if (extractedTexts.length > 0) {+ return extractedTexts.join('\n');+ }+ }++ // Try to find any string values that look like text content+ const anyStringMatches = body.match(/"([^"]{10,})"/g);+ if (anyStringMatches && anyStringMatches.length > 0) {+ const potentialTexts = anyStringMatches+ .map((match) => match.slice(1, -1)) // Remove quotes+ .filter((text) => text.length > 10 && !text.startsWith('{') && !text.startsWith('['));+ if (potentialTexts.length > 0) {+ return potentialTexts[0]; // Return the first substantial text found+ }+ }+ }++ return null;+}+function pendingA2UIFallback(): A2UIContentPart {return {kind: 'text',@@ -234,7 +278,17 @@ export function parseA2UIContent(const body = content.slice(bodyStart, closeIndex);const messages = parseJsonMessageList(body);- parts.push(messages ? makeA2UIPart(messages) : invalidA2UIFallback());+ if (messages) {+ parts.push(makeA2UIPart(messages));+ } else {+ // Try to extract readable text from malformed A2UI content+ const extractedText = extractTextFromMalformedA2UI(content.slice(openIndex, closeIndex + A2UI_CLOSE_TAG.length));+ if (extractedText) {+ parts.push({ kind: 'text', text: extractedText });+ } else {+ parts.push(invalidA2UIFallback());+ }+ }cursor = closeIndex + A2UI_CLOSE_TAG.length;}@@ -274,3 +328,44 @@ export function a2uiContentToText(content: string): string {.filter(Boolean).join('\n\n');}++/**+ * 检查内容是否为 A2UI client event(内部交互事件,不应显示)。+ * 只判断 content,不判断 role —— 调用处应明确只过滤 user role。+ * 支持: object / string JSON / array / JSON-ish fallback+ */+export function isA2UIClientEventContent(content: unknown): boolean {+ if (content == null) return false;++ if (Array.isArray(content)) {+ return content.some(isA2UIClientEventContent);+ }++ if (typeof content === 'object') {+ const record = content as Record<string, unknown>;+ if (record.type === 'a2ui.client_event') return true;+ if (isA2UIClientEventContent(record.content)) return true;+ if (isA2UIClientEventContent(record.event)) return true;+ if (isA2UIClientEventContent(record.data)) return true;+ return false;+ }++ if (typeof content !== 'string') return false;++ const trimmed = content.trim();+ if (!trimmed) return false;++ try {+ const parsed = JSON.parse(trimmed);+ return isA2UIClientEventContent(parsed);+ } catch {+ const looksStructured = trimmed.startsWith('{') || trimmed.startsWith('[');+ if (!looksStructured) return false;++ return (+ trimmed.includes('"type"') && trimmed.includes('a2ui.client_event')+ ) || (+ trimmed.includes("'type'") && trimmed.includes('a2ui.client_event')+ );+ }+}diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/actionBridge.ts b/jiuwenswarm/channels/web/frontend/src/features/a2ui/actionBridge.tsindex 7bd52d628c..ae17e1d1f8 100644--- a/jiuwenswarm/channels/web/frontend/src/features/a2ui/actionBridge.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/actionBridge.ts@@ -4,6 +4,7 @@ import type { A2UIClientEventMessage } from '@a2ui/react';import { isA2UIFeatureEnabled } from './featureConfig';import { A2UI_PROTOCOL_VERSION } from './a2uiContent';import { enrichA2UIClientEventWithDefaults } from './actionDefaults';+import { a2uiDebug, a2uiWarn } from './formDefaults';export interface A2UIClientEventContent {type: 'a2ui.client_event';@@ -17,6 +18,71 @@ type A2UIActionHandler = (let currentHandler: A2UIActionHandler | null = null;+/**+ * Clean up action context to fix model-generated key issues.+ * The model sometimes generates object keys instead of strings,+ * which JS coerces to "[object Object]". This function:+ * 1. Filters out [object Object] keys+ * 2. Attempts to recover the correct key from path-like objects+ */+function cleanActionContext(+ context: Record<string, unknown> | undefined+): Record<string, unknown> | undefined {+ if (!context) return context;++ const cleaned: Record<string, unknown> = {};+ for (const [rawKey, rawValue] of Object.entries(context)) {+ if (rawKey === '[object Object]') {+ // Try to recover: if value has a path property, extract the last segment+ if (rawValue && typeof rawValue === 'object' && 'path' in rawValue) {+ const path = (rawValue as { path: string }).path;+ if (typeof path === 'string') {+ const segments = path.split('/').filter(Boolean);+ if (segments.length > 0 && segments[segments.length - 1] !== '') {+ const recoveredKey = segments[segments.length - 1];+ // Validate: recovered key must look like a field name (alphanumeric + underscore)+ if (/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(recoveredKey)) {+ a2uiDebug('[A2UI] recovered context key from [object Object]:', {+ recoveredKey,+ originalPath: path,+ });+ cleaned[recoveredKey] = rawValue;+ continue;+ }+ a2uiWarn('[A2UI] dropped invalid context entry:', {+ rawKey,+ rawValue: typeof rawValue === 'object' ? JSON.stringify(rawValue)?.substring(0, 100) : rawValue,+ normalizedKey: recoveredKey,+ dropReason: 'recovered key failed field name validation',+ });+ continue;+ }+ }+ }+ // Cannot recover — drop the entry entirely+ a2uiWarn('[A2UI] dropped invalid context entry:', {+ rawKey,+ rawValue: typeof rawValue === 'string' ? rawValue.substring(0, 50) : typeof rawValue,+ normalizedKey: null,+ dropReason: 'unrecoverable [object Object] key',+ });+ continue;+ }+ // Also skip empty string keys+ if (rawKey === '') {+ a2uiWarn('[A2UI] dropped invalid context entry:', {+ rawKey: '(empty)',+ rawValue: typeof rawValue === 'string' ? rawValue.substring(0, 50) : typeof rawValue,+ normalizedKey: null,+ dropReason: 'empty string key',+ });+ continue;+ }+ cleaned[rawKey] = rawValue;+ }+ return Object.keys(cleaned).length > 0 ? cleaned : undefined;+}+export function buildA2UIClientEventContent(message: A2UIClientEventMessage): A2UIClientEventContent {@@ -46,8 +112,41 @@ export async function dispatchA2UIAction(return;}if (!currentHandler) {- console.warn('[A2UI] action ignored because no chat sender is registered');+ a2uiWarn('[A2UI] action ignored because no chat sender is registered');return;}++ // Clean up context to fix [object Object] key issues+ if (message.userAction?.context) {+ const cleaned = cleanActionContext(message.userAction.context);+ if (cleaned !== message.userAction.context) {+ message = {+ ...message,+ userAction: {+ ...message.userAction,+ context: cleaned,+ },+ };+ }+ }++ // Log the action for debugging+ const userAction = message.userAction;+ if (userAction) {+ a2uiDebug('[A2UI] dispatching action:', {+ name: userAction.name,+ sourceComponentId: userAction.sourceComponentId,+ surfaceId: userAction.surfaceId,+ contextKeys: userAction.context ? Object.keys(userAction.context) : [],+ contextValues: userAction.context,+ contextEntries: userAction.context ? Object.entries(userAction.context).map(([k, v]) => ({+ key: k,+ keyType: typeof k,+ valueType: typeof v,+ value: v === null ? 'null' : v === undefined ? 'undefined' : JSON.stringify(v)?.substring(0, 100),+ })) : [],+ });+ }+await currentHandler(message);}diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/actionDefaults.ts b/jiuwenswarm/channels/web/frontend/src/features/a2ui/actionDefaults.tsindex 778226b3af..dcd45bd53c 100644--- a/jiuwenswarm/channels/web/frontend/src/features/a2ui/actionDefaults.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/actionDefaults.ts@@ -1,6 +1,14 @@// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.import type { A2UIClientEventMessage, ServerToClientMessage } from '@a2ui/react';+import {+ a2uiDebug,+ a2uiPathCandidates,+ isRecord,+ normalizeA2UIPath,+ shouldFillEmptyActionValue,+ visibleChoiceDefault,+} from './formDefaults';type UnknownRecord = Record<string, unknown>;@@ -14,10 +22,6 @@ interface ActionDefaultEntry {const actionDefaults = new Map<string, ActionDefaultEntry>();const surfaceDefaultsByPath = new Map<string, Map<string, unknown>>();-function isRecord(value: unknown): value is UnknownRecord {- return typeof value === 'object' && value !== null && !Array.isArray(value);-}-function componentType(component: unknown): string | null {if (!isRecord(component)) {return null;@@ -36,34 +40,6 @@ function componentProps(component: unknown): UnknownRecord | null {return component[type];}-function normalizePath(path: unknown): string | null {- if (typeof path !== 'string' || !path.trim()) {- return null;- }- const trimmed = path.trim();- return trimmed.startsWith('/') ? trimmed : `/${trimmed}`;-}--function visibleChoiceDefault(props: UnknownRecord): unknown {- const options = Array.isArray(props.options) ? props.options : [];- const firstOption = options.find(isRecord);- if (- firstOption &&- Object.prototype.hasOwnProperty.call(firstOption, 'value') &&- firstOption.value !== null &&- firstOption.value !== undefined- ) {- return firstOption.value;- }-- const selections = isRecord(props.selections) ? props.selections : null;- const literalArray = Array.isArray(selections?.literalArray)- ? selections.literalArray- : [];- const firstLiteral = literalArray.find((value) => value !== null && value !== undefined);- return firstLiteral ?? null;-}-function actionName(action: UnknownRecord): string | null {return typeof action.name === 'string'? action.name@@ -76,13 +52,58 @@ function actionKey(surfaceId: string, sourceComponentId: string, name: string):return `${surfaceId}\u0000${sourceComponentId}\u0000${name}`;}-function isEmptyActionValue(value: unknown): boolean {- return (- value === null ||- value === undefined ||- (Array.isArray(value) && value.length === 0) ||- (isRecord(value) && Object.keys(value).length === 0)- );+function rememberDefault(+ defaultsByPath: Map<string, unknown>,+ path: string | null,+ value: unknown,+): void {+ if (!path || value === null || value === undefined) {+ return;+ }+ for (const candidate of a2uiPathCandidates(path)) {+ defaultsByPath.set(candidate, value);+ }+}++function recordComponentDefault(+ defaultsByPath: Map<string, unknown>,+ component: UnknownRecord,+): void {+ const type = componentType(component);+ const props = componentProps(component);+ if (!type || !props) {+ return;+ }++ if (type === 'MultipleChoice' || type === 'SingleChoice') {+ const selections = isRecord(props.selections) ? props.selections : null;+ const selectionsPath = normalizeA2UIPath(selections?.path);+ rememberDefault(defaultsByPath, selectionsPath, visibleChoiceDefault(props));+ return;+ }++ if (type === 'TextField') {+ const text = isRecord(props.text) ? props.text : null;+ rememberDefault(defaultsByPath, normalizeA2UIPath(text?.path), text?.literalString);+ return;+ }++ if (type === 'Slider') {+ const value = isRecord(props.value) ? props.value : null;+ rememberDefault(defaultsByPath, normalizeA2UIPath(value?.path), value?.literalNumber);+ return;+ }++ if (type === 'CheckBox') {+ const value = isRecord(props.value) ? props.value : null;+ rememberDefault(defaultsByPath, normalizeA2UIPath(value?.path), value?.literalBoolean);+ return;+ }++ if (type === 'DateTimeInput') {+ const value = isRecord(props.value) ? props.value : null;+ rememberDefault(defaultsByPath, normalizeA2UIPath(value?.path), value?.literalString);+ }}export function clearA2UIActionDefaults(): void {@@ -110,16 +131,10 @@ export function recordA2UIActionDefaults(messages: ServerToClientMessage[]): voiconst defaultsByPath = surfaceDefaultsByPath.get(update.surfaceId) ?? new Map<string, unknown>();for (const instance of update.components) {- const props = componentProps(instance.component);- if (!props) {+ if (!isRecord(instance.component)) {continue;}- const selections = isRecord(props.selections) ? props.selections : null;- const selectionsPath = normalizePath(selections?.path);- const defaultValue = visibleChoiceDefault(props);- if (selectionsPath && defaultValue !== null) {- defaultsByPath.set(selectionsPath, [defaultValue]);- }+ recordComponentDefault(defaultsByPath, instance.component);}if (defaultsByPath.size > 0) {surfaceDefaultsByPath.set(update.surfaceId, defaultsByPath);@@ -141,13 +156,19 @@ export function recordA2UIActionDefaults(messages: ServerToClientMessage[]): voiif (!isRecord(contextItem) || typeof contextItem.key !== 'string' || !isRecord(contextItem.value)) {continue;}- const path = normalizePath(contextItem.value.path);+ const path = normalizeA2UIPath(contextItem.value.path);if (path && defaultsByPath.has(path)) {defaults[contextItem.key] = defaultsByPath.get(path);}}if (Object.keys(defaults).length > 0) {+ a2uiDebug('[A2UI-AD] recording action defaults:', {+ surfaceId: update.surfaceId,+ componentId: instance.id,+ actionName: name,+ defaults,+ });actionDefaults.set(actionKey(update.surfaceId, instance.id, name), {surfaceId: update.surfaceId,sourceComponentId: instance.id,@@ -183,7 +204,9 @@ export function enrichA2UIClientEventWithDefaults(const nextContext: Record<string, unknown> = { ...currentContext };let changed = false;for (const [key, value] of Object.entries(entry.defaults)) {- if (isEmptyActionValue(nextContext[key])) {+ const oldValue = nextContext[key];+ if (shouldFillEmptyActionValue(oldValue)) {+ a2uiDebug('[A2UI-AD] enriching visible default:', { key, defaultValue: value });nextContext[key] = value;changed = true;}diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/fieldBinding.ts b/jiuwenswarm/channels/web/frontend/src/features/a2ui/fieldBinding.tsnew file mode 100644index 0000000000..c133c247b2--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/fieldBinding.ts@@ -0,0 +1,72 @@+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++import { useCallback, useEffect, useState } from 'react';+import type { CSSProperties } from 'react';+import type { DataValue } from '@a2ui/react';+import { dualWriteA2UIValue } from './formDefaults';++type ReadModelValue = (path: string) => unknown;+type WriteModelValue = (path: string, value: DataValue) => void;++interface BoundValueOptions<T extends DataValue> {+ path?: string;+ initialValue: T;+ getValue: ReadModelValue;+ setValue: WriteModelValue;+ fromModelValue: (value: unknown) => T;+ shouldSeedInitial?: (value: T) => boolean;+ literalValue?: T;+}++function alwaysSeedInitial(): boolean {+ return true;+}++export function hostWeightStyle(weight: unknown): CSSProperties {+ return weight !== undefined ? ({ '--weight': weight } as CSSProperties) : {};+}++export function useA2UIBoundValue<T extends DataValue>({+ path,+ initialValue,+ getValue,+ setValue,+ fromModelValue,+ shouldSeedInitial,+ literalValue,+}: BoundValueOptions<T>): [T, (nextValue: T) => void] {+ const [currentValue, setCurrentValue] = useState(initialValue);+ const shouldSeed = shouldSeedInitial ?? alwaysSeedInitial;++ useEffect(() => {+ if (!path) return;++ const storedValue = getValue(path);+ if (storedValue === null) {+ if (shouldSeed(initialValue)) {+ dualWriteA2UIValue(setValue, path, initialValue);+ }+ return;+ }++ const nextValue = fromModelValue(storedValue);+ if (!Object.is(nextValue, currentValue)) {+ setCurrentValue(nextValue);+ }+ }, [currentValue, fromModelValue, getValue, initialValue, path, setValue, shouldSeed]);++ useEffect(() => {+ if (literalValue !== undefined) {+ setCurrentValue(literalValue);+ }+ }, [literalValue]);++ const commitValue = useCallback((nextValue: T) => {+ setCurrentValue(nextValue);+ if (path) {+ dualWriteA2UIValue(setValue, path, nextValue);+ }+ }, [path, setValue]);++ return [currentValue, commitValue];+}diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/formDefaults.ts b/jiuwenswarm/channels/web/frontend/src/features/a2ui/formDefaults.tsnew file mode 100644index 0000000000..b1cc2742fe--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/formDefaults.ts@@ -0,0 +1,123 @@+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++import type { DataValue } from '@a2ui/react';++type UnknownRecord = Record<string, unknown>;++export function isDevA2UIDiagnosticEnabled(): boolean {+ return Boolean(import.meta.env?.DEV);+}++export function a2uiDebug(message: string, data?: unknown): void {+ if (isDevA2UIDiagnosticEnabled()) {+ console.debug(message, data);+ }+}++export function a2uiWarn(message: string, data?: unknown): void {+ if (isDevA2UIDiagnosticEnabled()) {+ console.warn(message, data);+ }+}++export function a2uiError(message: string, data?: unknown): void {+ if (isDevA2UIDiagnosticEnabled()) {+ console.error(message, data);+ }+}++export function isRecord(value: unknown): value is UnknownRecord {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++export function normalizeA2UIPath(path: unknown): string | null {+ if (typeof path !== 'string' || !path.trim()) {+ return null;+ }+ const trimmed = path.trim();+ return trimmed.startsWith('/') ? trimmed : `/${trimmed}`;+}++export function leafA2UIPath(path: string): string | null {+ const segments = path.split('/').filter(Boolean);+ if (segments.length <= 1 || !path.startsWith('/')) {+ return null;+ }+ return `/${segments[segments.length - 1]}`;+}++export function a2uiPathCandidates(path: string): string[] {+ const normalized = normalizeA2UIPath(path);+ if (!normalized) {+ return [];+ }+ const leafPath = leafA2UIPath(normalized);+ return leafPath && leafPath !== normalized ? [normalized, leafPath] : [normalized];+}++export function dualWriteA2UIValue(+ setValue: (path: string, value: DataValue) => void,+ path: string,+ value: DataValue,+): void {+ const candidates = a2uiPathCandidates(path);+ for (const candidate of candidates) {+ setValue(candidate, value);+ }+}++export function shouldFillEmptyActionValue(value: unknown): boolean {+ if (value === undefined || value === null) {+ return true;+ }+ if (Array.isArray(value)) {+ return value.length === 0;+ }+ if (isRecord(value)) {+ return Object.keys(value).length === 0;+ }+ return false;+}++export function literalArrayValues(value: unknown): unknown[] {+ if (!isRecord(value)) {+ return [];+ }+ return Array.isArray(value.literalArray)+ ? value.literalArray.filter((item) => item !== null && item !== undefined)+ : [];+}++export function optionDefaultValue(options: unknown): unknown {+ if (!Array.isArray(options)) {+ return null;+ }+ for (const option of options) {+ if (isRecord(option) && option.value !== undefined && option.value !== null) {+ return option.value;+ }+ }+ return null;+}++export function isMultiSelectChoice(props: UnknownRecord): boolean {+ const variant = typeof props.variant === 'string' ? props.variant : undefined;+ const type = typeof props.type === 'string' ? props.type : undefined;+ const maxAllowedSelections =+ typeof props.maxAllowedSelections === 'number' ? props.maxAllowedSelections : undefined;+ return variant === 'chips' || variant === 'checkbox' || type === 'chips' ||+ type === 'checkbox' || (maxAllowedSelections !== undefined && maxAllowedSelections > 1);+}++export function visibleChoiceDefault(props: UnknownRecord): unknown {+ const selections = isRecord(props.selections) ? props.selections : null;+ const literalDefaults = literalArrayValues(selections);+ if (isMultiSelectChoice(props)) {+ return literalDefaults.length > 0 ? literalDefaults : null;+ }+ const optionDefault = optionDefaultValue(props.options);+ if (optionDefault !== null) {+ return [optionDefault];+ }+ return literalDefaults.length > 0 ? literalDefaults : null;+}diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/rendererRegistry.tsx b/jiuwenswarm/channels/web/frontend/src/features/a2ui/rendererRegistry.tsxindex cdad864795..79cd4ff23f 100644--- a/jiuwenswarm/channels/web/frontend/src/features/a2ui/rendererRegistry.tsx+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/rendererRegistry.tsx@@ -1,23 +1,58 @@// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.import type { ComponentType } from 'react';-import { A2UIRenderer, ComponentRegistry, registerDefaultCatalog } from '@a2ui/react';+import { A2UIRenderer, ComponentRegistry } from '@a2ui/react';import { A2UI_PROTOCOL_VERSION, type A2UIProtocolVersion } from './a2uiContent';+import { CheckBoxWithDefaults } from './CheckBoxWithDefaults';+import { DateTimeInputWithDefaults } from './DateTimeInputWithDefaults';import { MultipleChoiceWithDefaults } from './MultipleChoiceWithDefaults';+import { SliderWithDefaults } from './SliderWithDefaults';+import { TextFieldWithDefaults } from './TextFieldWithDefaults';export interface A2UIRendererProps {surfaceId: string;}-const a2uiV08Registry = new ComponentRegistry();-registerDefaultCatalog(a2uiV08Registry);-a2uiV08Registry.register('MultipleChoice', {- component: MultipleChoiceWithDefaults,-});+const a2uiV08Registry = ComponentRegistry.getInstance();-const A2UIV08Renderer = ({ surfaceId }: A2UIRendererProps) => (- <A2UIRenderer surfaceId={surfaceId} registry={a2uiV08Registry} />-);+// Register our overrides. These must be applied AFTER initializeDefaultCatalog()+// 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('CheckBox', {+ component: CheckBoxWithDefaults,+ });+ a2uiV08Registry.register('DateTimeInput', {+ component: DateTimeInputWithDefaults,+ });+ a2uiV08Registry.register('MultipleChoice', {+ component: MultipleChoiceWithDefaults,+ });+ a2uiV08Registry.register('Slider', {+ component: SliderWithDefaults,+ });+ a2uiV08Registry.register('TextField', {+ component: TextFieldWithDefaults,+ });+}++// Try early registration (may be overwritten by ensureInitialized)+applyOverrides();++// Re-apply overrides after the library's lazy initialization runs.+let _overridesApplied = false;++const A2UIV08Renderer = ({ surfaceId }: A2UIRendererProps) => {+ if (!_overridesApplied) {+ const current = a2uiV08Registry.get('TextField');+ if (current !== TextFieldWithDefaults) {+ applyOverrides();+ }+ _overridesApplied = true;+ }++ return <A2UIRenderer surfaceId={surfaceId} registry={a2uiV08Registry} />;+};export const rendererByVersion: Record<A2UIProtocolVersion,diff --git a/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts b/jiuwenswarm/channels/web/frontend/src/features/historyRestore.tsindex a8ebb7ce57..f5254b6f96 100644--- a/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/historyRestore.ts@@ -1,6 +1,7 @@import { Message, MessageRole, UsageSummary, FileDownloadItem, WsEvent } from '../types';import { webClient } from '../services/webClient';import { normalizeFinalContent } from '../utils/finalContent';+import { isA2UIClientEventContent } from './a2ui/a2uiContent';export const HISTORY_GET_METHOD = 'history.get';export const HISTORY_MESSAGE_EVENT = 'history.message';@@ -253,7 +254,11 @@ function parseHistoryTimelineEntry(const at = recordTimestampIso(record);if (role === 'user') {- const content = pickFirstString(record, ['content', 'text', 'body']) ?? '';+ const rawContent = record.content ?? record.text ?? record.body;+ if (isA2UIClientEventContent(rawContent)) {+ return null;+ }+ const content = typeof rawContent === 'string' ? rawContent : String(rawContent ?? '');if (!content.trim()) {return null;}diff --git a/jiuwenswarm/channels/web/frontend/src/features/shareImageExport.tsx b/jiuwenswarm/channels/web/frontend/src/features/shareImageExport.tsxindex 50423d44e0..9904b04471 100644--- a/jiuwenswarm/channels/web/frontend/src/features/shareImageExport.tsx+++ b/jiuwenswarm/channels/web/frontend/src/features/shareImageExport.tsx@@ -13,6 +13,7 @@ import {import { isUserMember } from '../utils/teamMemberAvatar';import { parseHistoryJsonFileToPreviewMessages } from './historyRestore';import { parseTeamHistoryPanelRecords } from './teamHistoryPanelRestore';+import { isA2UIClientEventContent } from './a2ui/a2uiContent';import { getSvgNaturalHeight, getSvgNaturalWidth } from '../utils/svgDimensions';import './shareImageExport.css';@@ -41,11 +42,24 @@ const SHARE_IMAGE_WIDTH = 750;const SHARE_IMAGE_PIXEL_RATIO = 3;const OPENJIUWEN_WEBSITE_URL = 'https://openjiuwen.com';const JIUWENSWARM_REPO_URL = 'https://gitcode.com/openJiuwen/jiuwenswarm';+const TRANSPARENT_IMAGE_DATA_URL = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';function isRecord(value: unknown): value is Record<string, unknown> {return Boolean(value) && typeof value === 'object' && !Array.isArray(value);}+/**+ * Filter out A2UI client event messages from the message list.+ * These messages are internal interaction events and should not be included in exports.+ */+function filterA2UIClientEvents(messages: unknown[]): unknown[] {+ return messages.filter((msg) => {+ if (!isRecord(msg)) return true;+ if (msg.role === 'user' && isA2UIClientEventContent(msg.content)) return false;+ return true;+ });+}+function normalizeMode(records: unknown[]): string {const modes = records.filter(isRecord)@@ -140,9 +154,11 @@ export const ShareImageDocument = forwardRef<HTMLDivElement, ShareImageDocumentPreturn null;}const messages = parseHistoryJsonFileToPreviewMessages(snapshot.records, snapshot.session_id);+ // Filter out A2UI client event messages from exports+ const filteredMessages = filterA2UIClientEvents(messages) as typeof messages;return {mode: normalizeMode(snapshot.records),- messages,+ messages: filteredMessages,groupMessages: collectGroupMessages(snapshot),};}, [snapshot]);@@ -184,6 +200,7 @@ export const ShareImageDocument = forwardRef<HTMLDivElement, ShareImageDocumentPmessages={data.messages}executions={[]}mode={data.mode}+ disableA2UIInteraction={true}/>) : (<div className="share-image-empty">{t('share.noMainConversation')}</div>@@ -229,21 +246,72 @@ function nextFrame(): Promise<void> {});}-async function waitForImages(node: HTMLElement): Promise<void> {+interface ImageSnapshot {+ image: HTMLImageElement;+ src: string | null;+ srcset: string | null;+ sizes: string | null;+}++function replaceBrokenImageForExport(image: HTMLImageElement, snapshots: ImageSnapshot[]): void {+ snapshots.push({+ image,+ src: image.getAttribute('src'),+ srcset: image.getAttribute('srcset'),+ sizes: image.getAttribute('sizes'),+ });+ image.removeAttribute('srcset');+ image.removeAttribute('sizes');+ image.src = TRANSPARENT_IMAGE_DATA_URL;+}++async function waitForImage(image: HTMLImageElement): Promise<boolean> {+ if (image.complete) {+ return image.naturalWidth > 0;+ }+ if (typeof image.decode === 'function') {+ await image.decode();+ return image.naturalWidth > 0;+ }+ return new Promise<boolean>((resolve) => {+ image.addEventListener('load', () => resolve(image.naturalWidth > 0), { once: true });+ image.addEventListener('error', () => resolve(false), { once: true });+ });+}++async function prepareImagesForExport(node: HTMLElement): Promise<() => void> {const images = Array.from(node.querySelectorAll('img'));+ const snapshots: ImageSnapshot[] = [];+await Promise.all(images.map(async (image) => {- if (image.complete && image.naturalWidth > 0) {- return;+ try {+ if (await waitForImage(image)) {+ return;+ }+ } catch {+ // Ignore broken or undecodable images in share export. A2UI Image can+ // intentionally contain an invalid URL to demonstrate fallback UI.}- if (typeof image.decode === 'function') {- await image.decode();- return;++ replaceBrokenImageForExport(image, snapshots);+ try {+ await waitForImage(image);+ } catch {+ // The transparent data URL should decode, but keep export tolerant.}- await new Promise<void>((resolve, reject) => {- image.addEventListener('load', () => resolve(), { once: true });- image.addEventListener('error', () => reject(new Error('share_image_asset_failed')), { once: true });- });}));++ return () => {+ for (const snapshot of snapshots) {+ const { image, src, srcset, sizes } = snapshot;+ if (src === null) image.removeAttribute('src');+ else image.setAttribute('src', src);+ if (srcset === null) image.removeAttribute('srcset');+ else image.setAttribute('srcset', srcset);+ if (sizes === null) image.removeAttribute('sizes');+ else image.setAttribute('sizes', sizes);+ }+ };}interface SvgSnapshot {@@ -357,18 +425,19 @@ async function waitForMermaidDiagrams(node: HTMLElement): Promise<void> {export async function exportShareImageNode(node: HTMLElement): Promise<string> {await document.fonts?.ready;- await waitForImages(node);- await waitForMermaidDiagrams(node);- await nextFrame();+ const restoreImages = await prepareImagesForExport(node);+ let restoreMermaidDiagrams = (): void => {};+ try {+ await waitForMermaidDiagrams(node);+ await nextFrame();- // Scale down wide Mermaid diagrams so they are not clipped in the exported- // image. toPng reads the DOM synchronously, so the restore callback must be- // called after the render completes.- const restoreMermaidDiagrams = fitMermaidDiagramsForExport(node);- await nextFrame();+ // Scale down wide Mermaid diagrams so they are not clipped in the exported+ // image. toPng reads the DOM synchronously, so the restore callback must be+ // called after the render completes.+ restoreMermaidDiagrams = fitMermaidDiagramsForExport(node);+ await nextFrame();- const backgroundColor = window.getComputedStyle(node).backgroundColor;- try {+ const backgroundColor = window.getComputedStyle(node).backgroundColor;return await toPng(node, {cacheBust: true,pixelRatio: SHARE_IMAGE_PIXEL_RATIO,@@ -378,5 +447,6 @@ export async function exportShareImageNode(node: HTMLElement): Promise<string> {});} finally {restoreMermaidDiagrams();+ restoreImages();}}diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex 1b5718900b..85d68e6f38 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -1463,8 +1463,10 @@"restarting": "Restarting service","restartSuccess": "Restart successful","configApplied": "Config applied",+ "a2uiRefresh": "Config applied","restartWaiting": "Waiting for backend to restart and reconnect...","configAppliedDesc": "Config hot-reloaded, this dialog will close in 5 seconds.",+ "a2uiRefreshDesc": "The page will refresh in 5 seconds.","restartSuccessDesc": "Backend started successfully, this dialog will close in 5 seconds."},"extensions": {diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex acb6f20348..5f42a4e301 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -1462,8 +1462,10 @@"restarting": "正在重启服务","restartSuccess": "重启成功","configApplied": "配置已生效",+ "a2uiRefresh": "配置已生效","restartWaiting": "正在等待后端重新启动并恢复连接,请稍候...","configAppliedDesc": "配置已热更新,窗口将在 5 秒后自动关闭。",+ "a2uiRefreshDesc": "页面将在 5 秒后自动刷新。","restartSuccessDesc": "后端已启动成功,窗口将在 5 秒后自动关闭。"},"extensions": {diff --git a/jiuwenswarm/channels/web/frontend/src/main.tsx b/jiuwenswarm/channels/web/frontend/src/main.tsxindex b8b3f8857f..d59ec347ba 100644--- a/jiuwenswarm/channels/web/frontend/src/main.tsx+++ b/jiuwenswarm/channels/web/frontend/src/main.tsx@@ -6,6 +6,7 @@ import { injectStyles } from '@a2ui/react/styles';import App from './App.tsx'import { dispatchA2UIAction } from './features/a2ui/actionBridge';import './index.css'+import './features/a2ui/a2ui.css'function flagA2UIIconFontAvailability() {if (typeof document === 'undefined' || !('fonts' in document)) {diff --git a/jiuwenswarm/server/runtime/a2ui/integration.py b/jiuwenswarm/server/runtime/a2ui/integration.pyindex f18ba1c49f..370205ba57 100644--- a/jiuwenswarm/server/runtime/a2ui/integration.py+++ b/jiuwenswarm/server/runtime/a2ui/integration.py@@ -92,6 +92,7 @@ async def finalize_assistant_response_if_a2ui(user_query: Any,request_id: str,repair_call: Any,+ retry_without_a2ui_call: Any = None,) -> str:"""Validate/repair assistant A2UI content while keeping host modules generic."""if not is_a2ui_channel(channel):@@ -111,6 +112,7 @@ async def finalize_assistant_response_if_a2ui(request_id=request_id,repair_call=repair_call if callable(repair_call) else None,a2ui_enabled=a2ui_config.enabled,+ retry_without_a2ui_call=retry_without_a2ui_call if callable(retry_without_a2ui_call) else None,)diff --git a/jiuwenswarm/server/runtime/a2ui/protocol.py b/jiuwenswarm/server/runtime/a2ui/protocol.pyindex cc4c825903..4e23886f8f 100644--- a/jiuwenswarm/server/runtime/a2ui/protocol.py+++ b/jiuwenswarm/server/runtime/a2ui/protocol.py@@ -91,8 +91,8 @@ class A2UIProtocolSpec:def build_prompt(self, language: str = "en") -> str:if language in {"zh", "cn"}:role = (- "你是 jiuwenswarm 的 A2UI 生成器。遇到适合富交互界面的回答时,"- "必须生成严格符合 A2UI 0.8 schema 的消息。"+ "JiuwenSwarm 支持可选的 A2UI 输出格式。当富交互界面适合当前回答时,"+ "可以生成严格符合 A2UI 0.8 schema 的消息。")ui = ("当用户需要列表、卡片、表单、确认结果、可点击操作或结构化信息比较时使用 A2UI。"@@ -107,9 +107,9 @@ class A2UIProtocolSpec:)else:role = (- "You are jiuwenswarm's A2UI generator. When a rich interactive "- "answer is appropriate, generate messages that strictly validate "- "against the A2UI 0.8 schema."+ "JiuwenSwarm supports an optional 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 "diff --git a/jiuwenswarm/server/runtime/a2ui/runtime/finalizer.py b/jiuwenswarm/server/runtime/a2ui/runtime/finalizer.pyindex cfe3eb84fd..b5e0bf5322 100644--- a/jiuwenswarm/server/runtime/a2ui/runtime/finalizer.py+++ b/jiuwenswarm/server/runtime/a2ui/runtime/finalizer.py@@ -6,6 +6,7 @@ from __future__ import annotationsimport inspectfrom collections.abc import Callable+from dataclasses import dataclassfrom typing import Anyfrom jiuwenswarm.server.runtime.a2ui.protocol import A2UI_OPEN_TAG, get_protocol_spec@@ -14,6 +15,15 @@ from jiuwenswarm.server.runtime.a2ui.protocol import A2UI_OPEN_TAG, get_protocolRepairCall = Callable[[str], Any]+@dataclass(frozen=True)+class A2UIFinalizationResult:+ """Structured finalization result for retry decisions."""++ content: str+ status: str+ validation_error: str | None = None++def _coerce_model_message_content(message: Any) -> str:if isinstance(message, str):return message@@ -33,14 +43,9 @@ def _a2ui_failure_text(content: str, validation_error: str) -> str:spec = get_protocol_spec()readable = spec.format_for_text_channel(content)if readable:- return (- "A2UI 界面生成失败,已退回纯文本结果。\n\n"- f"{readable}"- )- return (- "A2UI 界面生成失败,模型连续返回了不符合 A2UI 0.8 schema "- f"的内容。最后一次校验错误:{validation_error}"- )+ return readable+ _ = validation_error+ return "界面内容生成失败,请重试或换一种方式描述你的需求。"class A2UIResponseFinalizer:@@ -55,14 +60,32 @@ class A2UIResponseFinalizer:repair_call: RepairCall | None,max_repair_attempts: int = 2,) -> str:+ result = await self.finalize_result(+ content,+ user_query=user_query,+ request_id=request_id,+ repair_call=repair_call,+ max_repair_attempts=max_repair_attempts,+ )+ return result.content++ async def finalize_result(+ self,+ content: str,+ *,+ user_query: Any,+ request_id: str,+ repair_call: RepairCall | None,+ max_repair_attempts: int = 2,+ ) -> A2UIFinalizationResult:_ = request_idif A2UI_OPEN_TAG not in (content or ""):- return content+ return A2UIFinalizationResult(content=content, status="skipped")spec = get_protocol_spec()validation = spec.validate_response(content)if validation.valid:- return content+ return A2UIFinalizationResult(content=content, status="valid")repaired_content = contentlast_error = validation.error@@ -80,10 +103,14 @@ class A2UIResponseFinalizer:repaired_content = _coerce_model_message_content(response)validation = spec.validate_response(repaired_content)if validation.valid:- return repaired_content+ return A2UIFinalizationResult(content=repaired_content, status="repaired")last_error = validation.error- return _a2ui_failure_text(repaired_content, last_error)+ return A2UIFinalizationResult(+ content=_a2ui_failure_text(repaired_content, last_error),+ status="repair_failed",+ validation_error=last_error,+ )-__all__ = ["A2UIResponseFinalizer"]+__all__ = ["A2UIFinalizationResult", "A2UIResponseFinalizer"]diff --git a/jiuwenswarm/server/runtime/a2ui/runtime/response_finalization.py b/jiuwenswarm/server/runtime/a2ui/runtime/response_finalization.pyindex 00f66f8a90..eb00f26183 100644--- a/jiuwenswarm/server/runtime/a2ui/runtime/response_finalization.py+++ b/jiuwenswarm/server/runtime/a2ui/runtime/response_finalization.py@@ -5,13 +5,16 @@from __future__ import annotationsimport logging-from typing import Any+from typing import Any, Callablefrom jiuwenswarm.server.runtime.a2ui.runtime.finalizer import A2UIResponseFinalizer, RepairCalllogger = logging.getLogger(__name__)+# Type for a function that can retry a request without A2UI+RetryWithoutA2UI = Callable[[str], Any]+async def finalize_a2ui_assistant_content(content: str,@@ -20,13 +23,21 @@ async def finalize_a2ui_assistant_content(request_id: str,repair_call: RepairCall | None,a2ui_enabled: bool,+ retry_without_a2ui_call: RetryWithoutA2UI | None = None,) -> str:- """Validate and repair a complete assistant response when A2UI is enabled."""+ """Validate and repair a complete assistant response when A2UI is enabled.++ Flow:+ 1. Validate A2UI content+ 2. If invalid, try to repair (up to 2 times)+ 3. If repair fails, retry user request WITHOUT A2UI prompt+ 4. Return repaired A2UI, plain retry result, or safe plain text+ """if not a2ui_enabled or not isinstance(content, str) or "<a2ui-json>" not in content:return contenttry:- finalized = await A2UIResponseFinalizer().finalize(+ finalization = await A2UIResponseFinalizer().finalize_result(content,user_query=user_query,request_id=request_id,@@ -36,9 +47,51 @@ async def finalize_a2ui_assistant_content(logger.exception("A2UI response finalization failed: request_id=%s error=%s", request_id, exc)return content+ finalized = finalization.content+ if finalization.status == "repair_failed":+ logger.info(+ "A2UI repair failed, retrying without A2UI: request_id=%s",+ request_id,+ )+ # Retry without A2UI prompt+ if retry_without_a2ui_call is not None:+ try:+ retry_response = retry_without_a2ui_call(str(user_query or ""))+ import inspect+ if inspect.isawaitable(retry_response):+ retry_response = await retry_response+ retry_content = _coerce_model_message_content(retry_response)+ if retry_content:+ logger.info(+ "Retry without A2UI succeeded: request_id=%s",+ request_id,+ )+ return retry_content+ except Exception as retry_exc:+ logger.exception(+ "Retry without A2UI failed: request_id=%s error=%s",+ request_id,+ retry_exc,+ )+if finalized != content:logger.info("A2UI response finalized: request_id=%s changed=true", request_id)return finalized+def _coerce_model_message_content(message: Any) -> str:+ if isinstance(message, str):+ return message+ if isinstance(message, dict):+ value = message.get("content") or message.get("output") or ""+ return value if isinstance(value, str) else str(value)+ value = getattr(message, "content", None)+ if isinstance(value, str):+ return value+ value = getattr(message, "output", None)+ if isinstance(value, str):+ return value+ return str(message) if message is not None else ""++__all__ = ["finalize_a2ui_assistant_content"]diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex 1d20745acc..23b6d6e678 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -101,6 +101,10 @@ def _append_compact_history_from_payload()+def _contains_a2ui_marker(value: Any) -> bool:+ return isinstance(value, str) and "<a2ui-json>" in value++load_dotenv(dotenv_path=get_env_file(), override=True)reset_free_search_runtime_flags()@@ -681,6 +685,8 @@ class JiuWenSwarm:"channel": channel,"language": language,}+ if request.metadata and request.metadata.get("skip_a2ui") is True:+ inputs["skip_a2ui"] = True# 传递 enable_memory 参数enable_memory = request.metadata.get("enable_memory", True) if request.metadata else True@@ -735,6 +741,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 _build_interactive_input_from_answers(request_id: str, answers: list[dict], source: str = ""@@ -1196,12 +1238,17 @@ class JiuWenSwarm:content = result.payload["content"]content_str = content if isinstance(content, str) else str(content)repair_call = getattr(adapter, "repair_model_response", None)+ retry_without_a2ui_call = self._make_retry_without_a2ui_call(+ adapter=adapter,+ request=request,+ )content_str = await finalize_assistant_response_if_a2ui(content_str,channel=request.channel_id,user_query=raw_query,request_id=request.request_id or "",repair_call=repair_call,+ retry_without_a2ui_call=retry_without_a2ui_call,)if isinstance(content, str):result.payload["content"] = content_str@@ -1366,6 +1413,7 @@ class JiuWenSwarm:else:await self._session_manager.submit_task(session_id, run_stream_task)+ suppress_a2ui_stream = Falsetry:while not stream_done.is_set() or not stream_queue.empty():try:@@ -1423,6 +1471,16 @@ class JiuWenSwarm:mode=request.params.get("mode", "unknown"),)+ payload_content = str(data.payload.get("content", ""))+ if et == "chat.delta" and (suppress_a2ui_stream or _contains_a2ui_marker(payload_content)):+ suppress_a2ui_stream = True+ final_answer_chunks.append(payload_content)+ continue+ if et == "chat.final" and (suppress_a2ui_stream or _contains_a2ui_marker(payload_content)):+ suppress_a2ui_stream = True+ final_answer_content = payload_content+ continue+if should_record:payload_dict = dict(data.payload)extra_fields = {k: v for k, v in payload_dict.items() if@@ -1463,6 +1521,16 @@ class JiuWenSwarm:mode=request.params.get("mode", "unknown"),)+ payload_content = str(data.get("content", ""))+ if et == "chat.delta" and (suppress_a2ui_stream or _contains_a2ui_marker(payload_content)):+ suppress_a2ui_stream = True+ final_answer_chunks.append(payload_content)+ continue+ if et == "chat.final" and (suppress_a2ui_stream or _contains_a2ui_marker(payload_content)):+ suppress_a2ui_stream = True+ final_answer_content = payload_content+ continue+if should_record:extra_fields = {k: v for k, v in data.items() if k not in ("event_type", "content")}if et == EventType.TEAM_MESSAGE.value and "event" in data:@@ -1498,14 +1566,22 @@ class JiuWenSwarm:assistant_message = final_answer_content or "".join(final_answer_chunks)repair_call = getattr(adapter, "repair_model_response", None)+ retry_without_a2ui_call = self._make_retry_without_a2ui_call(+ adapter=adapter,+ request=request,+ )+finalized_assistant_message = await finalize_assistant_response_if_a2ui(assistant_message,channel=cid,user_query=raw_query,request_id=rid or "",repair_call=repair_call,+ retry_without_a2ui_call=retry_without_a2ui_call,)- if finalized_assistant_message and finalized_assistant_message != assistant_message:+ if finalized_assistant_message and (+ finalized_assistant_message != assistant_message or suppress_a2ui_stream+ ):append_history_record(session_id=session_id,request_id=rid,diff --git a/tests/unit_tests/a2ui/test_finalizer.py b/tests/unit_tests/a2ui/test_finalizer.pyindex add0f1e058..152350022a 100644--- a/tests/unit_tests/a2ui/test_finalizer.py+++ b/tests/unit_tests/a2ui/test_finalizer.py@@ -83,7 +83,8 @@ async def test_a2ui_finalizer_falls_back_after_failed_repairs():)assert "<a2ui-json>" not in result- assert "A2UI 界面生成失败" in result+ assert "A2UI 界面生成失败" not in result+ assert result == "Here is the UI."@pytest.mark.asynciodiff --git a/tests/unit_tests/a2ui/test_prompt_instructions.py b/tests/unit_tests/a2ui/test_prompt_instructions.pyindex 3884785dc9..d95c77173c 100644--- a/tests/unit_tests/a2ui/test_prompt_instructions.py+++ b/tests/unit_tests/a2ui/test_prompt_instructions.py@@ -35,12 +35,20 @@ def test_a2ui_prompt_discourages_nested_templates():def test_a2ui_zh_prompt_section_is_readable():prompt = build_a2ui_prompt_section("zh")- assert "你是 jiuwenswarm 的 A2UI 生成器" in prompt+ assert "你是 jiuwenswarm 的 A2UI 生成器" not in prompt+ assert "JiuwenSwarm 支持可选的 A2UI 输出格式" in promptassert "当用户需要列表、卡片、表单" in promptassert "浣犳槸" not in promptassert "鐢熸垚" not in prompt+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++def test_a2ui_zh_client_event_prompt_is_readable():prompt = build_a2ui_client_event_prompt({diff --git a/tests/unit_tests/a2ui/test_response_finalization.py b/tests/unit_tests/a2ui/test_response_finalization.pyindex 4067656258..4ece508beb 100644--- a/tests/unit_tests/a2ui/test_response_finalization.py+++ b/tests/unit_tests/a2ui/test_response_finalization.py@@ -104,3 +104,61 @@ async def test_finalize_a2ui_assistant_content_skips_when_disabled(monkeypatch):)assert result == INVALID_A2UI_RESPONSE+++async def test_finalize_a2ui_assistant_content_retries_without_a2ui_after_failed_repairs(monkeypatch):+ from jiuwenswarm.server.runtime.a2ui.runtime.response_finalization import finalize_a2ui_assistant_content++ monkeypatch.setenv("JIUWENSWARM_A2UI_ENABLED", "true")+ repair_prompts = []+ retry_queries = []++ async def repair_call(prompt: str):+ repair_prompts.append(prompt)+ return SimpleNamespace(content=INVALID_A2UI_RESPONSE)++ async def retry_without_a2ui_call(query: str):+ retry_queries.append(query)+ return "plain text result"++ result = await finalize_a2ui_assistant_content(+ INVALID_A2UI_RESPONSE,+ user_query="generate a form",+ request_id="req-retry-without-a2ui",+ repair_call=repair_call,+ a2ui_enabled=True,+ retry_without_a2ui_call=retry_without_a2ui_call,+ )++ assert result == "plain text result"+ assert len(repair_prompts) == 2+ assert retry_queries == ["generate a form"]+++async def test_finalize_a2ui_assistant_content_returns_safe_text_when_retry_fails(monkeypatch):+ 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 SimpleNamespace(content=INVALID_A2UI_RESPONSE)++ async def retry_without_a2ui_call(query: str):+ _ = query+ return None++ result = await finalize_a2ui_assistant_content(+ INVALID_A2UI_RESPONSE,+ user_query="generate a form",+ request_id="req-retry-fails",+ repair_call=repair_call,+ a2ui_enabled=True,+ retry_without_a2ui_call=retry_without_a2ui_call,+ )++ assert "<a2ui-json>" not in result+ assert "[A2UI content could not be rendered]" not in result+ assert "A2UI 界面生成失败" not in result+ assert result == "Here is a form."diff --git a/tests/unit_tests/a2ui/test_web_only_prompt_rail.py b/tests/unit_tests/a2ui/test_web_only_prompt_rail.pyindex 5a3321a200..1968d09592 100644--- a/tests/unit_tests/a2ui/test_web_only_prompt_rail.py+++ b/tests/unit_tests/a2ui/test_web_only_prompt_rail.py@@ -56,6 +56,25 @@ async def test_response_prompt_rail_keeps_a2ui_for_web_channel(monkeypatch):assert LocalSectionName.A2UI in rail.system_prompt_builder.sections+async def test_response_prompt_rail_removes_a2ui_when_request_skips_it(monkeypatch):+ """Repair fallback retries need a request-scoped way to remove A2UI instructions."""+ 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++ await rail.before_model_call(SimpleNamespace(inputs={"channel": "web", "skip_a2ui": True}))++ assert "response" in rail.system_prompt_builder.sections+ assert LocalSectionName.A2UI not in rail.system_prompt_builder.sections++@pytest.mark.asyncioasync def test_response_prompt_rail_keeps_web_channel_from_invoke_context(monkeypatch):"""Model-call inputs drop channel, so Web channel must survive via invoke context."""