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, browser subagent): add A2UI to browser subagent, improve performance for A2UI and browser use
m05683870072d034fc8d39
diff --git a/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py b/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.pyindex fd698ca596..896ca7a468 100644--- a/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py@@ -374,6 +374,46 @@ class RuntimePromptRail(DeepAgentRail):"page inspection, or extracting data from a live website, use `spawn_sub_agent` with "'`subagent_type` set to `"browser_agent"` and put the full browser objective in '"`task_description`.\n"+ "- Before spawning `browser_agent` for booking, ticketing, purchasing, reservation, or "+ "form-filling tasks, check whether the user has supplied enough confirmed details. "+ "If required details are missing and A2UI is available, render a preflight A2UI form "+ "with action name `browser_preflight_submit` instead of starting browser automation. "+ "Do not use plain natural-language questions or `ask_user` for those missing "+ "browser-task details when A2UI is available on the Web channel.\n"+ "- Mandatory Web A2UI account-action gate: Gmail, email, mailbox cleanup, social "+ "media posting, comments, and other externally visible account actions MUST use A2UI "+ "when A2UI is available. Do not use `todo_create`, `todo_modify`, `memory_search`, "+ "`task_tool`, plain text, Markdown, or `ask_user` as a substitute for A2UI preflight, "+ "candidate selection, draft review, or final confirmation. For requests such as "+ "finding emails and replying to the ones that need a reply, first use A2UI preflight "+ "if filters or reply preferences are incomplete; after Gmail search, show the "+ "emails/threads as A2UI candidates before opening, summarizing multiple messages, "+ "drafting replies, or modifying mail; and show final A2UI confirmation before any "+ "send, archive, delete, unsubscribe, label, mark-read, post, publish, comment, like, "+ "follow, or delete action.\n"+ "- For hotel booking flows, after `browser_agent` returns candidate hotels, render the "+ "candidate list with A2UI selection actions named `hotel_option_select`. Include "+ "`next_action=\"continue_hotel_booking\"`, the selected hotel identity, and the "+ "confirmed city/date/guest context in each action context. When the user selects a "+ "hotel, call `browser_agent` to continue from the current browser state and selected "+ "candidate; do not restart the broad hotel search unless browser-state recovery is "+ "needed. At the payment/order summary page, render a final A2UI confirmation using "+ "`hotel_payment_confirm` and `hotel_payment_cancel` actions.\n"+ "- For Gmail search, summarization, reply drafting, and cleanup flows, render search "+ "results with `gmail_email_select` actions and cleanup candidates with "+ "`gmail_cleanup_select` actions. When the user selects an email, continue from the "+ "current Gmail browser state; do not repeat the broad Gmail search unless recovery is "+ "needed. Filling a reply draft must use `gmail_reply_draft_select` and must stop "+ "before sending. After `gmail_send_confirm`, send the email only if the visible "+ "Gmail compose state matches the confirmed context. Final cleanup requires "+ "`gmail_cleanup_confirm`. Respect `gmail_send_cancel` and `gmail_cleanup_cancel` "+ "by stopping without side effects.\n"+ "- For social media posting flows, render draft variants with "+ "`social_post_draft_select`. After draft selection, use `browser_agent` to fill the "+ "current platform compose UI but stop before any externally visible action. Final "+ "publishing requires `social_post_confirm`; after confirmation, publish only if "+ "the visible compose state matches the confirmed context. `social_post_cancel` "+ "stops without publishing.\n""- Do not use bash, execute_code, subprocess, shell commands, or direct Chrome/Edge launches ""for browser automation.\n""- If `spawn_sub_agent` or `browser_agent` is unavailable, say that the browser "diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIErrorBoundary.tsx b/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIErrorBoundary.tsxindex b0a6d40b36..ac1ea5f84e 100644--- a/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIErrorBoundary.tsx+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIErrorBoundary.tsx@@ -7,6 +7,7 @@ interface A2UIErrorBoundaryProps {children: ReactNode;fallback?: ReactNode;onError?: (error: Error, errorInfo: ErrorInfo) => void;+ resetKey?: string;}interface A2UIErrorBoundaryState {@@ -36,6 +37,12 @@ export class A2UIErrorBoundary extends Component<this.props.onError?.(error, errorInfo);}+ componentDidUpdate(prevProps: A2UIErrorBoundaryProps) {+ if (prevProps.resetKey !== this.props.resetKey && this.state.hasError) {+ this.setState({ hasError: false, error: null });+ }+ }+render() {if (this.state.hasError) {if (this.props.fallback) {diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIMessageContent.tsx b/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIMessageContent.tsxindex efbcaad2d9..c4028861d4 100644--- a/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIMessageContent.tsx+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIMessageContent.tsx@@ -31,12 +31,21 @@ type RenderPart =protocolVersion: string;messages: Extract<A2UIContentPart, { kind: 'a2ui' }>['messages'];surfaceIds: string[];+ resetKey: string;};function safeNamespace(input: string): string {return input.replace(/[^A-Za-z0-9_-]/g, '_');}+function stableHash(input: string): string {+ let hash = 0;+ for (let index = 0; index < input.length; index += 1) {+ hash = (hash * 31 + input.charCodeAt(index)) | 0;+ }+ return Math.abs(hash).toString(36);+}+export function A2UIMessageContent({content,messageId,@@ -63,12 +72,14 @@ export function A2UIMessageContent({}const messages = namespaceA2UIMessages(part.messages, namespace);+ const resetKey = `${namespace}:${index}:${stableHash(JSON.stringify(messages))}`;return {kind: 'a2ui',key: `a2ui-${index}`,protocolVersion: part.protocolVersion,messages,surfaceIds: extractA2UISurfaceIds(messages),+ resetKey,};});}, [a2uiEnabled, content, isStreaming, namespace, messageId]);@@ -166,7 +177,10 @@ export function A2UIMessageContent({return (<div key={part.key} className="a2ui-message-content__surfaces">{part.surfaceIds.map((surfaceId) => (- <A2UIErrorBoundary key={surfaceId}>+ <A2UIErrorBoundary+ key={`${surfaceId}:${part.resetKey}`}+ resetKey={part.resetKey}+ >{disableInteraction ? (<div className="pointer-events-none opacity-75"><Renderer surfaceId={surfaceId} />diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/MultipleChoiceWithDefaults.tsx b/jiuwenswarm/channels/web/frontend/src/features/a2ui/MultipleChoiceWithDefaults.tsxindex d6285d8e93..fb6feb2fab 100644--- a/jiuwenswarm/channels/web/frontend/src/features/a2ui/MultipleChoiceWithDefaults.tsx+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/MultipleChoiceWithDefaults.tsx@@ -21,14 +21,30 @@ import {type MultipleChoiceNodeLike = Extract<AnyComponentNode, { type: 'MultipleChoice' }>;+function choiceValueToString(value: unknown): string {+ if (typeof value === 'string') return value;+ if (typeof value === 'number' || typeof value === 'boolean') return String(value);+ if (value === null || value === undefined) return '';+ try {+ return JSON.stringify(value);+ } catch {+ return String(value);+ }+}++function nonEmptyChoiceValue(value: unknown): string | null {+ const text = choiceValueToString(value);+ return text !== '' ? text : null;+}+function selectedValuesFromData(value: DataValue | null): string[] {if (Array.isArray(value)) {- return value.filter((item): item is string => typeof item === 'string' && item !== '');- }- if (typeof value === 'string' && value !== '') {- return [value];+ return value+ .map(nonEmptyChoiceValue)+ .filter((item): item is string => item !== null);}- return [];+ const singleValue = nonEmptyChoiceValue(value);+ return singleValue ? [singleValue] : [];}export function visibleMultipleChoiceDefault(@@ -36,10 +52,12 @@ export function visibleMultipleChoiceDefault(): string | null {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');+ const firstDefault = defaultValue+ .map(nonEmptyChoiceValue)+ .find((item): item is string => item !== null);return firstDefault ?? null;}- return typeof defaultValue === 'string' ? defaultValue : null;+ return nonEmptyChoiceValue(defaultValue);}export function MultipleChoiceWithDefaults({@@ -59,9 +77,9 @@ export function MultipleChoiceWithDefaults({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 literalDefaults = literalArrayValues(props.selections)+ .map(nonEmptyChoiceValue)+ .filter((item): item is string => item !== null);const defaultValue = visibleMultipleChoiceDefault(props);const dataValue = selectionsPath ? getValue(selectionsPath) : null;const selectedValues = selectedValuesFromData(dataValue);@@ -83,11 +101,11 @@ export function MultipleChoiceWithDefaults({if (!shouldShowFilter || !searchQuery.trim()) return options;const q = searchQuery.trim().toLowerCase();return options.filter((option) => {- const label = resolveString(option.label);- const value = option.value;+ const label = resolveString(option.label) ?? '';+ const value = choiceValueToString(option.value);return (- (label && label.toLowerCase().includes(q)) ||- (value && value.toLowerCase().includes(q))+ label.toLowerCase().includes(q) ||+ value.toLowerCase().includes(q));});}, [options, searchQuery, shouldShowFilter, resolveString]);@@ -168,12 +186,13 @@ export function MultipleChoiceWithDefaults({/>)}<div className="flex flex-wrap gap-2">- {filteredOptions.map((option) => {- const optionValue = option.value;+ {filteredOptions.map((option, index) => {+ const optionValue = choiceValueToString(option.value);+ const optionLabel = resolveString(option.label) ?? optionValue;const isSelected = effectiveSelectedValues.includes(optionValue);return (<button- key={optionValue}+ key={optionValue || `option-${index}`}type="button"className={`px-3 py-1 rounded-full border ${isSelected@@ -183,13 +202,13 @@ export function MultipleChoiceWithDefaults({aria-pressed={isSelected}onClick={() => {try {- handleMultiChange(option.value, !isSelected);+ handleMultiChange(optionValue, !isSelected);} catch (err) {a2uiError('[A2UI-MC] handleMultiChange threw:', err);}}}>- {resolveString(option.label)}+ {optionLabel}</button>);})}@@ -219,12 +238,13 @@ export function MultipleChoiceWithDefaults({/>)}<div className="flex flex-col gap-1">- {filteredOptions.map((option) => {- const optionValue = option.value;+ {filteredOptions.map((option, index) => {+ const optionValue = choiceValueToString(option.value);+ const optionLabel = resolveString(option.label) ?? optionValue;const isSelected = effectiveSelectedValues.includes(optionValue);return (<label- key={optionValue}+ key={optionValue || `option-${index}`}className="flex items-center gap-2 cursor-pointer"><input@@ -233,7 +253,7 @@ export function MultipleChoiceWithDefaults({onChange={(e) => handleMultiChange(optionValue, e.target.checked)}className="w-4 h-4"/>- <span>{resolveString(option.label)}</span>+ <span>{optionLabel}</span></label>);})}@@ -262,11 +282,15 @@ export function MultipleChoiceWithDefaults({style={stylesToObject(theme.additionalStyles?.MultipleChoice)}onChange={handleSingleChange}>- {(props.options ?? []).map((option) => (- <option key={option.value} value={option.value}>- {resolveString(option.label)}- </option>- ))}+ {(props.options ?? []).map((option, index) => {+ const optionValue = choiceValueToString(option.value);+ const optionLabel = resolveString(option.label) ?? optionValue;+ return (+ <option key={optionValue || `option-${index}`} value={optionValue}>+ {optionLabel}+ </option>+ );+ })}</select></section></div>diff --git a/jiuwenswarm/server/runtime/a2ui/prompt_instructions.py b/jiuwenswarm/server/runtime/a2ui/prompt_instructions.pyindex 6c108e53d0..04cb64c18f 100644--- a/jiuwenswarm/server/runtime/a2ui/prompt_instructions.py+++ b/jiuwenswarm/server/runtime/a2ui/prompt_instructions.py@@ -6,6 +6,100 @@ from __future__ import annotationsdef build_a2ui_autonomy_instruction(language: str = "en") -> str:+ browser_preflight_rule_en = (+ " Browser task preflight: when the user asks you to perform a browser "+ "automation task such as booking tickets, reserving hotels, buying "+ "products, filling forms, handling webmail, posting to social media, or "+ "comparing purchasable options, first check "+ "whether the task has enough user-confirmed details before calling any "+ "browser tool or browser subagent. If required details are missing and "+ "the Web A2UI channel is available, do not start browser automation yet. "+ "Instead, render an A2UI information-collection or confirmation form. "+ "Do not ask for those missing browser-task details through plain natural "+ "language, Markdown, or the ask_user tool when A2UI is available. "+ "The submit Button action name MUST be 'browser_preflight_submit'. Its "+ "action.context MUST include original_query, task_type, next_action with "+ "the value 'run_browser_agent', must_confirm_before_payment with true, "+ "and all form values using path references. After this action is "+ "submitted, combine the original request and submitted values, then use "+ "spawn_sub_agent with subagent_type 'browser_agent'. Never buy, book, "+ "pay, or place an order without a final explicit user confirmation."+ )+ mandatory_account_action_rule_en = (+ " Mandatory A2UI account-action gate: on the Web channel, Gmail, email, "+ "mailbox cleanup, social-media posting, comments, or any externally "+ "visible account action MUST use A2UI when A2UI is available. This is "+ "not optional. Do not use plain text, Markdown, ask_user, todo tools, "+ "memory tools, task planning, or task_tool as a substitute for the A2UI "+ "preflight, candidate selection, draft review, or final confirmation. "+ "For a request like finding emails and replying to those that need a "+ "reply, first render an A2UI preflight if filters or reply preferences "+ "are incomplete; after Gmail search, render an A2UI email/thread "+ "candidate list before opening or replying to selected messages; after "+ "drafting, render a final A2UI send confirmation before sending. Never "+ "search multiple emails and send replies in the same uninterrupted run "+ "without an A2UI user selection and final send confirmation."+ )+ hotel_booking_flow_rule_en = (+ " Hotel booking A2UI flow: after browser_agent returns candidate hotels, "+ "present the candidates as A2UI cards or a comparable list. Each hotel's "+ "selection Button action name MUST be 'hotel_option_select'. Its "+ "action.context MUST include task_type='hotel', next_action with the "+ "value 'continue_hotel_booking', original_query, selected hotel name, "+ "candidate index or id, and the confirmed city/check-in/check-out/guest "+ "and room criteria. Include a candidate/detail URL, provider, room type, "+ "price, currency, and cancellation policy when available. After the user "+ "selects a hotel, continue the existing browser state for that candidate; "+ "do not restart the broad city/date search. At the payment or order "+ "summary page, render a final A2UI confirmation whose confirm Button "+ "action name is 'hotel_payment_confirm' and whose cancel Button action "+ "name is 'hotel_payment_cancel'."+ )+ gmail_flow_rule_en = (+ " Gmail A2UI flow: for Gmail search, summarization, reply drafting, or "+ "mailbox cleanup requests, collect missing filters with preflight A2UI "+ "before browser automation. If the user already provided enough filters, "+ "browser_agent may search Gmail, but the returned emails/threads MUST "+ "still be shown as A2UI candidates before summarizing multiple messages, "+ "drafting replies, modifying labels, archiving, deleting, unsubscribing, "+ "or sending anything. After browser_agent returns Gmail search "+ "results, render emails or threads as A2UI cards/lists. Each email "+ "selection Button action name MUST be 'gmail_email_select'. Its "+ "action.context MUST include task_type='gmail', next_action with the "+ "value 'continue_gmail_email_review', original_query, search query or "+ "filters, sender, subject, date/time, message/thread id or index, and "+ "thread URL when available. For reply drafts, render draft options whose "+ "selection Button action name is 'gmail_reply_draft_select' with "+ "next_action='continue_gmail_reply_draft', recipient, subject, selected "+ "draft body, tone, and selected thread context. At the final send step, "+ "render a confirmation with confirm action 'gmail_send_confirm' and "+ "cancel action 'gmail_send_cancel'; after the user clicks confirm, send "+ "the email only if the visible Gmail compose state still matches the "+ "A2UI confirmation context. For mailbox cleanup, candidate "+ "selection actions MUST use 'gmail_cleanup_select' with "+ "next_action='review_gmail_cleanup'. The final cleanup confirmation MUST "+ "use confirm action 'gmail_cleanup_confirm' and cancel action "+ "'gmail_cleanup_cancel'. Never send, delete, archive, unsubscribe, mark "+ "read, label, or otherwise modify Gmail without the relevant final "+ "confirmation action."+ )+ social_post_flow_rule_en = (+ " Social media A2UI flow: for posting to social media websites, first "+ "collect missing platform, account, audience, visibility, tone, media, "+ "link, and post intent details with A2UI. Render draft variants as A2UI "+ "cards. Each draft selection Button action name MUST be "+ "'social_post_draft_select'. Its action.context MUST include "+ "task_type='social_post', next_action with the value "+ "'continue_social_post_draft', original_query, platform, account or "+ "account_hint, selected draft body, visibility, media/link state, and "+ "target audience. After a draft is selected, fill the compose UI but do "+ "not publish. The final publish confirmation MUST use confirm action "+ "'social_post_confirm' and cancel action 'social_post_cancel'; after "+ "the user clicks confirm, publish the post only if the visible compose "+ "state still matches the A2UI confirmation context. Never publish, post, "+ "comment, like, follow, delete, or perform externally visible social "+ "actions without final explicit confirmation."+ )template_binding_rule_en = (" For repeated list/card data, use A2UI template binding correctly: ""Duplicate dataModelUpdate keys are invalid. Encode arrays as one "@@ -111,6 +205,11 @@ def build_a2ui_autonomy_instruction(language: str = "en") -> str:+ icon_font_rule_en+ unsupported_component_rule_zh+ autonomy_rule_zh+ + mandatory_account_action_rule_en+ + browser_preflight_rule_en+ + hotel_booking_flow_rule_en+ + gmail_flow_rule_en+ + social_post_flow_rule_en)if language in {"zh", "cn"}:@@ -136,6 +235,11 @@ def build_a2ui_autonomy_instruction(language: str = "en") -> str:"server-to-client message list, with beginRendering before ""surfaceUpdate and dataModelUpdate only when needed."+ autonomy_rule_en+ + mandatory_account_action_rule_en+ + browser_preflight_rule_en+ + hotel_booking_flow_rule_en+ + gmail_flow_rule_en+ + social_post_flow_rule_en+ requested_component_rule_en)diff --git a/jiuwenswarm/server/runtime/a2ui/protocol.py b/jiuwenswarm/server/runtime/a2ui/protocol.pyindex 4e23886f8f..f53afe248c 100644--- a/jiuwenswarm/server/runtime/a2ui/protocol.py+++ b/jiuwenswarm/server/runtime/a2ui/protocol.py@@ -270,8 +270,444 @@ def _log_a2ui_client_event(event: dict[str, Any]) -> None:)+def _get_a2ui_user_action(event: dict[str, Any]) -> dict[str, Any]:+ payload = event.get("event")+ user_action = payload.get("userAction") if isinstance(payload, dict) else None+ return user_action if isinstance(user_action, dict) else {}+++def _get_a2ui_action_context(event: dict[str, Any]) -> dict[str, Any]:+ user_action = _get_a2ui_user_action(event)+ context = user_action.get("context")+ return context if isinstance(context, dict) else {}+++def _get_a2ui_action_name(event: dict[str, Any]) -> str:+ user_action = _get_a2ui_user_action(event)+ return str(user_action.get("name") or "").strip()+++def _get_a2ui_next_action(event: dict[str, Any]) -> str:+ context = _get_a2ui_action_context(event)+ return str(context.get("next_action") or "").strip()+++def _is_browser_preflight_submit(event: dict[str, Any]) -> bool:+ action_name = _get_a2ui_action_name(event)+ next_action = _get_a2ui_next_action(event)+ return action_name == "browser_preflight_submit" or next_action == "run_browser_agent"+++def _is_hotel_option_select(event: dict[str, Any]) -> bool:+ action_name = _get_a2ui_action_name(event)+ next_action = _get_a2ui_next_action(event)+ return action_name in {"hotel_option_select", "hotel_candidate_select"} or next_action in {+ "continue_hotel_booking",+ "select_hotel_candidate",+ }+++def _is_hotel_payment_confirm(event: dict[str, Any]) -> bool:+ action_name = _get_a2ui_action_name(event)+ next_action = _get_a2ui_next_action(event)+ return action_name == "hotel_payment_confirm" or next_action == "confirm_hotel_payment"+++def _is_hotel_payment_cancel(event: dict[str, Any]) -> bool:+ action_name = _get_a2ui_action_name(event)+ next_action = _get_a2ui_next_action(event)+ return action_name == "hotel_payment_cancel" or next_action == "cancel_hotel_payment"+++def _is_gmail_email_select(event: dict[str, Any]) -> bool:+ action_name = _get_a2ui_action_name(event)+ next_action = _get_a2ui_next_action(event)+ return action_name in {"gmail_email_select", "gmail_thread_select"} or next_action in {+ "continue_gmail_email_review",+ "open_gmail_email",+ }+++def _is_gmail_reply_draft_select(event: dict[str, Any]) -> bool:+ action_name = _get_a2ui_action_name(event)+ next_action = _get_a2ui_next_action(event)+ return action_name in {"gmail_reply_draft_select", "gmail_draft_reply"} or next_action in {+ "continue_gmail_reply_draft",+ "fill_gmail_reply_draft",+ }+++def _is_gmail_send_confirm(event: dict[str, Any]) -> bool:+ action_name = _get_a2ui_action_name(event)+ next_action = _get_a2ui_next_action(event)+ return action_name == "gmail_send_confirm" or next_action == "confirm_gmail_send"+++def _is_gmail_send_cancel(event: dict[str, Any]) -> bool:+ action_name = _get_a2ui_action_name(event)+ next_action = _get_a2ui_next_action(event)+ return action_name == "gmail_send_cancel" or next_action == "cancel_gmail_send"+++def _is_gmail_cleanup_select(event: dict[str, Any]) -> bool:+ action_name = _get_a2ui_action_name(event)+ next_action = _get_a2ui_next_action(event)+ return action_name == "gmail_cleanup_select" or next_action == "review_gmail_cleanup"+++def _is_gmail_cleanup_confirm(event: dict[str, Any]) -> bool:+ action_name = _get_a2ui_action_name(event)+ next_action = _get_a2ui_next_action(event)+ return action_name == "gmail_cleanup_confirm" or next_action == "confirm_gmail_cleanup"+++def _is_gmail_cleanup_cancel(event: dict[str, Any]) -> bool:+ action_name = _get_a2ui_action_name(event)+ next_action = _get_a2ui_next_action(event)+ return action_name == "gmail_cleanup_cancel" or next_action == "cancel_gmail_cleanup"+++def _is_social_post_draft_select(event: dict[str, Any]) -> bool:+ action_name = _get_a2ui_action_name(event)+ next_action = _get_a2ui_next_action(event)+ return action_name in {"social_post_draft_select", "social_draft_select"} or next_action in {+ "continue_social_post_draft",+ "fill_social_post_draft",+ }+++def _is_social_post_confirm(event: dict[str, Any]) -> bool:+ action_name = _get_a2ui_action_name(event)+ next_action = _get_a2ui_next_action(event)+ return action_name == "social_post_confirm" or next_action == "confirm_social_post"+++def _is_social_post_cancel(event: dict[str, Any]) -> bool:+ action_name = _get_a2ui_action_name(event)+ next_action = _get_a2ui_next_action(event)+ return action_name == "social_post_cancel" or next_action == "cancel_social_post"+++def _build_a2ui_event_payload(+ event: dict[str, Any],+ channel: str,+ language: str,+) -> dict[str, Any]:+ return {+ "source": channel,+ "preferred_response_language": language,+ "type": A2UI_CLIENT_EVENT_TYPE,+ "protocolVersion": event.get("protocolVersion", VERSION_0_8),+ "event": event.get("event", {}),+ }+++def _build_browser_preflight_client_event_prompt(+ event: dict[str, Any],+ channel: str,+ language: str,+) -> str:+ payload = _build_a2ui_event_payload(event, channel, language)+ prefix = (+ "You receive an A2UI browser task preflight submission. The user has "+ "confirmed the values in event.userAction.context. Combine those values "+ "with original_query and start the browser task now by calling "+ "spawn_sub_agent with subagent_type='browser_agent' and a complete "+ "task_description. Do not ask again for values already present in the "+ "context. If any required browser-task detail is still missing, render "+ "one more A2UI form instead of starting the browser. Never buy, book, "+ "pay, submit an order, or perform an irreversible action without a final "+ "explicit user confirmation after the browser has shown the exact option "+ "or order summary.\n"+ )+ return prefix + json.dumps(payload, ensure_ascii=False)+++def _build_hotel_option_select_client_event_prompt(+ event: dict[str, Any],+ channel: str,+ language: str,+) -> str:+ payload = _build_a2ui_event_payload(event, channel, language)+ prefix = (+ "You receive an A2UI hotel candidate selection. The user selected one "+ "candidate from a hotel list previously returned by browser automation. "+ "Treat event.userAction.context as the authoritative selected candidate "+ "and booking context. Continue the existing hotel booking flow by calling "+ "spawn_sub_agent with subagent_type='browser_agent'. The task_description "+ "must instruct the browser_agent to continue from the current browser "+ "state/session and select or open the already chosen hotel candidate. Do "+ "not repeat the broad hotel search, do not change city/date/guest filters, "+ "and do not search again by city/date/hotel name unless recovery is needed "+ "because the current browser state no longer contains the selected "+ "candidate. If recovery is needed, prefer opening a candidate/detail URL "+ "from context; otherwise search narrowly for the selected hotel name using "+ "the already confirmed city, dates, guests, and room criteria. Continue "+ "only until the exact order summary or payment page is visible. Then stop "+ "and render a final A2UI confirmation with action name "+ "'hotel_payment_confirm' and a cancel action named 'hotel_payment_cancel'. "+ "Never buy, book, pay, submit an order, or perform an irreversible action "+ "until the user clicks that final confirmation.\n"+ )+ return prefix + json.dumps(payload, ensure_ascii=False)+++def _build_hotel_payment_confirm_client_event_prompt(+ event: dict[str, Any],+ channel: str,+ language: str,+) -> str:+ payload = _build_a2ui_event_payload(event, channel, language)+ prefix = (+ "You receive an A2UI final hotel payment confirmation. The user is "+ "confirming the exact order summary shown in event.userAction.context. "+ "Before taking any irreversible action, verify that the selected hotel, "+ "dates, guest/room details, total price, cancellation policy, and payment "+ "step in the current browser state match the context. If they do not "+ "match, stop and render a corrected A2UI confirmation instead of paying. "+ "If they match, continue with browser_agent only as far as allowed by the "+ "current product safety policy and available credentials; otherwise tell "+ "the user what must be completed manually.\n"+ )+ return prefix + json.dumps(payload, ensure_ascii=False)+++def _build_hotel_payment_cancel_client_event_prompt(+ event: dict[str, Any],+ channel: str,+ language: str,+) -> str:+ payload = _build_a2ui_event_payload(event, channel, language)+ prefix = (+ "You receive an A2UI hotel payment cancellation. Do not continue browser "+ "automation and do not submit payment or booking. Acknowledge the "+ "cancellation briefly in the preferred response language.\n"+ )+ return prefix + json.dumps(payload, ensure_ascii=False)+++def _build_gmail_email_select_client_event_prompt(+ event: dict[str, Any],+ channel: str,+ language: str,+) -> str:+ payload = _build_a2ui_event_payload(event, channel, language)+ prefix = (+ "You receive an A2UI Gmail email/thread selection. The user selected "+ "one item from Gmail search results previously returned by browser "+ "automation. Treat event.userAction.context as the authoritative "+ "selected email/thread and search context. Continue by calling "+ "spawn_sub_agent with subagent_type='browser_agent'. The task_description "+ "must instruct browser_agent to continue from the current Gmail browser "+ "state/session and open the selected email/thread. Do not repeat the "+ "broad Gmail search or change the query/date/sender filters unless "+ "browser-state recovery is needed. If recovery is needed, prefer a Gmail "+ "thread URL or stable message identifier from context; otherwise search "+ "narrowly for the selected subject/sender using the already confirmed "+ "filters. Read only the selected email/thread, summarize it, extract "+ "action items, and render an A2UI summary with reply-draft options. If "+ "the user asked to draft a reply, include action 'gmail_reply_draft_select'. "+ "Never send email without a final 'gmail_send_confirm' action.\n"+ )+ return prefix + json.dumps(payload, ensure_ascii=False)+++def _build_gmail_reply_draft_select_client_event_prompt(+ event: dict[str, Any],+ channel: str,+ language: str,+) -> str:+ payload = _build_a2ui_event_payload(event, channel, language)+ prefix = (+ "You receive an A2UI Gmail reply draft selection. The user selected a "+ "reply draft or drafting style from an email summary. Treat "+ "event.userAction.context as the authoritative selected email/thread, "+ "recipient, subject, and draft body. Continue by calling spawn_sub_agent "+ "with subagent_type='browser_agent' to open the existing selected Gmail "+ "thread and fill the reply compose box. Do not send the email. Do not "+ "repeat the broad Gmail search unless state recovery is needed; prefer "+ "thread URL or message identifiers from context for recovery. After the "+ "draft is filled or ready, render a final A2UI confirmation with action "+ "'gmail_send_confirm' and cancel action 'gmail_send_cancel'.\n"+ )+ return prefix + json.dumps(payload, ensure_ascii=False)+++def _build_gmail_send_confirm_client_event_prompt(+ event: dict[str, Any],+ channel: str,+ language: str,+) -> str:+ payload = _build_a2ui_event_payload(event, channel, language)+ prefix = (+ "You receive an A2UI final Gmail send confirmation. Before sending, "+ "verify that the visible Gmail compose/reply state matches "+ "event.userAction.context for recipient, subject, body, attachment "+ "state, and selected thread. If anything differs, stop and render a "+ "corrected A2UI confirmation. If it matches, call browser_agent to send "+ "the email now using the visible Gmail send action. Never send to a "+ "different recipient or with different content. If Gmail blocks sending "+ "or requires account/security steps outside the current browser session, "+ "stop and report the required manual step.\n"+ )+ return prefix + json.dumps(payload, ensure_ascii=False)+++def _build_gmail_send_cancel_client_event_prompt(+ event: dict[str, Any],+ channel: str,+ language: str,+) -> str:+ payload = _build_a2ui_event_payload(event, channel, language)+ prefix = (+ "You receive an A2UI Gmail send cancellation. Do not send email and do "+ "not continue browser automation. Acknowledge the cancellation briefly "+ "in the preferred response language.\n"+ )+ return prefix + json.dumps(payload, ensure_ascii=False)+++def _build_gmail_cleanup_select_client_event_prompt(+ event: dict[str, Any],+ channel: str,+ language: str,+) -> str:+ payload = _build_a2ui_event_payload(event, channel, language)+ prefix = (+ "You receive an A2UI Gmail cleanup selection. The user selected messages, "+ "categories, or cleanup rules from a Gmail cleanup candidate list. Treat "+ "event.userAction.context as the authoritative cleanup selection. Do not "+ "modify Gmail yet. Render a final A2UI cleanup confirmation that lists "+ "the exact operation, selected message count, representative subjects or "+ "senders, excluded messages, and risk level. The confirm action must be "+ "'gmail_cleanup_confirm' and the cancel action must be "+ "'gmail_cleanup_cancel'.\n"+ )+ return prefix + json.dumps(payload, ensure_ascii=False)+++def _build_gmail_cleanup_confirm_client_event_prompt(+ event: dict[str, Any],+ channel: str,+ language: str,+) -> str:+ payload = _build_a2ui_event_payload(event, channel, language)+ prefix = (+ "You receive an A2UI final Gmail cleanup confirmation. Continue by "+ "calling spawn_sub_agent with subagent_type='browser_agent'. The "+ "task_description must instruct browser_agent to continue from the "+ "current Gmail browser state/session and apply only the confirmed cleanup "+ "operation to the selected messages/categories in event.userAction.context. "+ "Do not repeat or broaden the Gmail search unless state recovery is "+ "needed. Before modifying Gmail, verify the selected messages/count and "+ "operation match the context. If they do not match, stop and render a "+ "corrected A2UI confirmation. Never delete, archive, unsubscribe, mark "+ "read, or label any unconfirmed message.\n"+ )+ return prefix + json.dumps(payload, ensure_ascii=False)+++def _build_gmail_cleanup_cancel_client_event_prompt(+ event: dict[str, Any],+ channel: str,+ language: str,+) -> str:+ payload = _build_a2ui_event_payload(event, channel, language)+ prefix = (+ "You receive an A2UI Gmail cleanup cancellation. Do not modify Gmail and "+ "do not continue browser automation. Acknowledge the cancellation briefly "+ "in the preferred response language.\n"+ )+ return prefix + json.dumps(payload, ensure_ascii=False)+++def _build_social_post_draft_select_client_event_prompt(+ event: dict[str, Any],+ channel: str,+ language: str,+) -> str:+ payload = _build_a2ui_event_payload(event, channel, language)+ prefix = (+ "You receive an A2UI social media post draft selection. The user selected "+ "one draft variant for a public social-media post. Treat "+ "event.userAction.context as the authoritative platform, account, draft "+ "body, media/link state, visibility, and posting context. Continue by "+ "calling spawn_sub_agent with subagent_type='browser_agent' to continue "+ "from the current browser state/session, open or use the selected social "+ "platform compose surface, and fill the selected draft. Do not publish, "+ "post, comment, like, follow, delete, or perform any externally visible "+ "action. After the draft is filled or ready, render a final A2UI "+ "confirmation with action 'social_post_confirm' and cancel action "+ "'social_post_cancel'.\n"+ )+ return prefix + json.dumps(payload, ensure_ascii=False)+++def _build_social_post_confirm_client_event_prompt(+ event: dict[str, Any],+ channel: str,+ language: str,+) -> str:+ payload = _build_a2ui_event_payload(event, channel, language)+ prefix = (+ "You receive an A2UI final social media post confirmation. Before "+ "publishing, verify that the visible compose state matches "+ "event.userAction.context for platform, account, body, media/link state, "+ "visibility, and target audience. If anything differs, stop and render a "+ "corrected A2UI confirmation. If it matches, call browser_agent to "+ "publish the post now using the visible platform publish/post action. "+ "Never publish different content or to a different account. If the "+ "platform blocks publishing or requires account/security steps outside "+ "the current browser session, stop and report the required manual step.\n"+ )+ return prefix + json.dumps(payload, ensure_ascii=False)+++def _build_social_post_cancel_client_event_prompt(+ event: dict[str, Any],+ channel: str,+ language: str,+) -> str:+ payload = _build_a2ui_event_payload(event, channel, language)+ prefix = (+ "You receive an A2UI social media post cancellation. Do not publish the "+ "post and do not continue browser automation. Acknowledge the cancellation "+ "briefly in the preferred response language.\n"+ )+ return prefix + json.dumps(payload, ensure_ascii=False)++def build_a2ui_client_event_prompt(event: dict[str, Any], channel: str, language: str) -> str:_log_a2ui_client_event(event)+ if _is_hotel_option_select(event):+ return _build_hotel_option_select_client_event_prompt(event, channel, language)+ if _is_hotel_payment_confirm(event):+ return _build_hotel_payment_confirm_client_event_prompt(event, channel, language)+ if _is_hotel_payment_cancel(event):+ return _build_hotel_payment_cancel_client_event_prompt(event, channel, language)+ if _is_gmail_email_select(event):+ return _build_gmail_email_select_client_event_prompt(event, channel, language)+ if _is_gmail_reply_draft_select(event):+ return _build_gmail_reply_draft_select_client_event_prompt(event, channel, language)+ if _is_gmail_send_confirm(event):+ return _build_gmail_send_confirm_client_event_prompt(event, channel, language)+ if _is_gmail_send_cancel(event):+ return _build_gmail_send_cancel_client_event_prompt(event, channel, language)+ if _is_gmail_cleanup_select(event):+ return _build_gmail_cleanup_select_client_event_prompt(event, channel, language)+ if _is_gmail_cleanup_confirm(event):+ return _build_gmail_cleanup_confirm_client_event_prompt(event, channel, language)+ if _is_gmail_cleanup_cancel(event):+ return _build_gmail_cleanup_cancel_client_event_prompt(event, channel, language)+ if _is_social_post_draft_select(event):+ return _build_social_post_draft_select_client_event_prompt(event, channel, language)+ if _is_social_post_confirm(event):+ return _build_social_post_confirm_client_event_prompt(event, channel, language)+ if _is_social_post_cancel(event):+ return _build_social_post_cancel_client_event_prompt(event, channel, language)+ if _is_browser_preflight_submit(event):+ return _build_browser_preflight_client_event_prompt(event, channel, language)+prefix = ("你收到了一次 A2UI 组件交互。请把 event.userAction.context ""视为用户提交的值。对于普通表单或按钮提交,请直接、简洁地使用首选回复语言回答。"@@ -285,13 +721,7 @@ def build_a2ui_client_event_prompt(event: dict[str, Any], channel: str, language"requests external work.\n"))- payload = {- "source": channel,- "preferred_response_language": language,- "type": A2UI_CLIENT_EVENT_TYPE,- "protocolVersion": event.get("protocolVersion", VERSION_0_8),- "event": event.get("event", {}),- }+ payload = _build_a2ui_event_payload(event, channel, language)return prefix + json.dumps(payload, ensure_ascii=False)diff --git a/jiuwenswarm/server/runtime/a2ui/runtime/finalizer.py b/jiuwenswarm/server/runtime/a2ui/runtime/finalizer.pyindex b5e0bf5322..7b4b92cb62 100644--- a/jiuwenswarm/server/runtime/a2ui/runtime/finalizer.py+++ b/jiuwenswarm/server/runtime/a2ui/runtime/finalizer.py@@ -5,6 +5,9 @@from __future__ import annotationsimport inspect+import logging+import re+import timefrom collections.abc import Callablefrom dataclasses import dataclassfrom typing import Any@@ -13,6 +16,11 @@ from jiuwenswarm.server.runtime.a2ui.protocol import A2UI_OPEN_TAG, get_protocolRepairCall = Callable[[str], Any]+logger = logging.getLogger(__name__)++_A2UI_PROTOCOL_LINE_RE = re.compile(+ r'(?im)^\s*(?:[\[{,]\s*)*"?(?:beginRendering|surfaceUpdate|dataModelUpdate|deleteSurface)"?\s*(?::|$)'+)@dataclass(frozen=True)@@ -48,6 +56,17 @@ def _a2ui_failure_text(content: str, validation_error: str) -> str:return "界面内容生成失败,请重试或换一种方式描述你的需求。"+def has_a2ui_protocol_marker(content: str) -> bool:+ """Return True when content looks like an A2UI payload or fragment."""+ text = content or ""+ return A2UI_OPEN_TAG in text or bool(_A2UI_PROTOCOL_LINE_RE.search(text))+++def should_finalize_a2ui_content(content: str) -> bool:+ """Return True when the response should enter A2UI validation/repair."""+ return isinstance(content, str) and has_a2ui_protocol_marker(content)++class A2UIResponseFinalizer:"""Validate, repair, or safely degrade a complete assistant response."""@@ -79,19 +98,42 @@ class A2UIResponseFinalizer:max_repair_attempts: int = 2,) -> A2UIFinalizationResult:_ = request_id- if A2UI_OPEN_TAG not in (content or ""):+ if not should_finalize_a2ui_content(content):return A2UIFinalizationResult(content=content, status="skipped")spec = get_protocol_spec()+ started_at = time.perf_counter()+ logger.info(+ "A2UI finalizer validating: request_id=%s content_chars=%d",+ request_id,+ len(content or ""),+ )validation = spec.validate_response(content)+ logger.info(+ "A2UI finalizer validation complete: request_id=%s valid=%s duration_ms=%.1f",+ request_id,+ validation.valid,+ (time.perf_counter() - started_at) * 1000,+ )if validation.valid:- return A2UIFinalizationResult(content=content, status="valid")+ if A2UI_OPEN_TAG in content or spec.may_contain_a2ui_content(content):+ return A2UIFinalizationResult(content=content, status="valid")+ last_error = (+ "A2UI-like content was emitted without a valid <a2ui-json> block "+ "or raw A2UI JSON message list."+ )+ else:+ last_error = validation.errorrepaired_content = content- last_error = validation.errorfor _attempt in range(1, max_repair_attempts + 1):if repair_call is None:break+ logger.info(+ "A2UI finalizer repair attempt started: request_id=%s attempt=%d",+ request_id,+ _attempt,+ )prompt = spec.build_repair_prompt(invalid_content=repaired_content,validation_error=last_error,@@ -102,6 +144,12 @@ class A2UIResponseFinalizer:response = await responserepaired_content = _coerce_model_message_content(response)validation = spec.validate_response(repaired_content)+ logger.info(+ "A2UI finalizer repair attempt complete: request_id=%s attempt=%d valid=%s",+ request_id,+ _attempt,+ validation.valid,+ )if validation.valid:return A2UIFinalizationResult(content=repaired_content, status="repaired")last_error = validation.error@@ -113,4 +161,9 @@ class A2UIResponseFinalizer:)-__all__ = ["A2UIFinalizationResult", "A2UIResponseFinalizer"]+__all__ = [+ "A2UIFinalizationResult",+ "A2UIResponseFinalizer",+ "has_a2ui_protocol_marker",+ "should_finalize_a2ui_content",+]diff --git a/jiuwenswarm/server/runtime/a2ui/runtime/response_finalization.py b/jiuwenswarm/server/runtime/a2ui/runtime/response_finalization.pyindex eb00f26183..de856191b7 100644--- a/jiuwenswarm/server/runtime/a2ui/runtime/response_finalization.py+++ b/jiuwenswarm/server/runtime/a2ui/runtime/response_finalization.py@@ -4,16 +4,31 @@from __future__ import annotations+import asyncio+import jsonimport logging+import timefrom typing import Any, Callable-from jiuwenswarm.server.runtime.a2ui.runtime.finalizer import A2UIResponseFinalizer, RepairCall+from jiuwenswarm.server.runtime.a2ui.parser import (+ coerce_message_list,+ iter_tagged_block_bodies,+ strip_tagged_a2ui_blocks,+)+from jiuwenswarm.server.runtime.a2ui.protocol import get_protocol_spec+from jiuwenswarm.server.runtime.a2ui.runtime.finalizer import (+ A2UIResponseFinalizer,+ RepairCall,+ should_finalize_a2ui_content,+)logger = logging.getLogger(__name__)# Type for a function that can retry a request without A2UIRetryWithoutA2UI = Callable[[str], Any]+_A2UI_FINALIZATION_TIMEOUT_SECONDS = 45.0+_A2UI_FAST_PATH_VALIDATION_TIMEOUT_SECONDS = 5.0async def finalize_a2ui_assistant_content(@@ -33,21 +48,68 @@ async def finalize_a2ui_assistant_content(3. If repair fails, retry user request WITHOUT A2UI prompt4. 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:+ if not a2ui_enabled or not isinstance(content, str) or not should_finalize_a2ui_content(content):return content+ started_at = time.perf_counter()+ logger.info(+ "A2UI response finalization started: request_id=%s has_tag=%s",+ request_id,+ "<a2ui-json>" in content,+ )++ fast_path_valid, fast_path_error = await _validate_parseable_tagged_a2ui_fast_path(content)+ if fast_path_valid:+ logger.info(+ "A2UI response finalization fast-path schema-valid: request_id=%s duration_ms=%.1f",+ request_id,+ (time.perf_counter() - started_at) * 1000,+ )+ return content+ if fast_path_error == "timeout":+ logger.warning(+ "A2UI response finalization fast-path validation timed out: request_id=%s timeout_s=%.1f duration_ms=%.1f",+ request_id,+ _A2UI_FAST_PATH_VALIDATION_TIMEOUT_SECONDS,+ (time.perf_counter() - started_at) * 1000,+ )+ return _a2ui_timeout_fallback(content)+ if fast_path_error:+ logger.info(+ "A2UI response finalization fast-path rejected: request_id=%s error=%s",+ request_id,+ fast_path_error,+ )+try:- finalization = await A2UIResponseFinalizer().finalize_result(- content,- user_query=user_query,- request_id=request_id,- repair_call=repair_call,+ finalization = await asyncio.wait_for(+ A2UIResponseFinalizer().finalize_result(+ content,+ user_query=user_query,+ request_id=request_id,+ repair_call=repair_call,+ ),+ timeout=_A2UI_FINALIZATION_TIMEOUT_SECONDS,+ )+ except asyncio.TimeoutError:+ logger.warning(+ "A2UI response finalization timed out: request_id=%s timeout_s=%.1f duration_ms=%.1f",+ request_id,+ _A2UI_FINALIZATION_TIMEOUT_SECONDS,+ (time.perf_counter() - started_at) * 1000,)+ return _a2ui_timeout_fallback(content)except Exception as exc: # noqa: BLE001logger.exception("A2UI response finalization failed: request_id=%s error=%s", request_id, exc)return contentfinalized = finalization.content+ logger.info(+ "A2UI response finalization status: request_id=%s status=%s duration_ms=%.1f",+ request_id,+ finalization.status,+ (time.perf_counter() - started_at) * 1000,+ )if finalization.status == "repair_failed":logger.info("A2UI repair failed, retrying without A2UI: request_id=%s",@@ -79,6 +141,52 @@ async def finalize_a2ui_assistant_content(return finalized+def _has_parseable_tagged_a2ui_blocks(content: str) -> bool:+ blocks = iter_tagged_block_bodies(content or "")+ if not blocks:+ return False+ for _, body in blocks:+ try:+ parsed = json.loads(body.strip())+ except json.JSONDecodeError:+ return False+ if coerce_message_list(parsed) is None:+ return False+ return True+++async def _validate_parseable_tagged_a2ui_fast_path(content: str) -> tuple[bool, str | None]:+ if not _has_parseable_tagged_a2ui_blocks(content):+ return False, None++ spec = get_protocol_spec()+ try:+ validation = await asyncio.wait_for(+ asyncio.to_thread(spec.validate_response, content),+ timeout=_A2UI_FAST_PATH_VALIDATION_TIMEOUT_SECONDS,+ )+ except asyncio.TimeoutError:+ return False, "timeout"+ except Exception as exc: # noqa: BLE001+ logger.exception("A2UI fast-path schema validation failed unexpectedly: error=%s", exc)+ return False, str(exc)++ return validation.valid, validation.error or None+++def _a2ui_timeout_fallback(content: str) -> str:+ try:+ readable = get_protocol_spec().format_for_text_channel(content)+ if readable:+ return readable+ except Exception as exc: # noqa: BLE001+ logger.exception("A2UI timeout fallback formatting failed: error=%s", exc)+ stripped = strip_tagged_a2ui_blocks(content or "")+ if stripped:+ return stripped+ return "A2UI 界面生成超时,请重试或改用普通文本结果。"++def _coerce_model_message_content(message: Any) -> str:if isinstance(message, str):return messagediff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex e048ba91eb..3c44f96f72 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -49,6 +49,7 @@ from jiuwenswarm.common.utils import (reset_free_search_runtime_flags,)from jiuwenswarm.server.runtime.a2ui.integration import finalize_assistant_response_if_a2ui+from jiuwenswarm.server.runtime.a2ui.runtime.finalizer import should_finalize_a2ui_contentfrom jiuwenswarm.agents.harness.common.auto_memory import (_execute_auto_memory_extraction,)@@ -110,7 +111,122 @@ def _append_compact_history_from_payload(def _contains_a2ui_marker(value: Any) -> bool:- return isinstance(value, str) and "<a2ui-json>" in value+ return isinstance(value, str) and should_finalize_a2ui_content(value)+++_A2UI_STREAM_PROBE_WINDOW = 512+_A2UI_STREAM_PARTIAL_MARKERS = (+ "<a2ui-json>",+ "beginRendering",+ "surfaceUpdate",+ "dataModelUpdate",+ "deleteSurface",+)+_A2UI_PENDING_RENDER_DELTA = "<a2ui-json>\n"+++def _make_a2ui_pending_render_chunk(*, request_id: str, channel_id: str) -> AgentResponseChunk:+ return AgentResponseChunk(+ request_id=request_id,+ channel_id=channel_id,+ payload={"event_type": "chat.delta", "content": _A2UI_PENDING_RENDER_DELTA},+ is_complete=False,+ )+++def _extend_a2ui_stream_probe(previous: str, content: str) -> str:+ probe = f"{previous}{content}"+ if len(probe) <= _A2UI_STREAM_PROBE_WINDOW:+ return probe+ return probe[-_A2UI_STREAM_PROBE_WINDOW:]+++def _looks_like_partial_a2ui_marker(value: Any) -> bool:+ if not isinstance(value, str) or not value:+ return False+ tail = value[-_A2UI_STREAM_PROBE_WINDOW:]+ recent_lines = tail.splitlines()[-3:] or [tail]+ for line in recent_lines:+ candidate = line.strip().lstrip("[{,").strip().lstrip('"')+ match = re.match(r"<?[A-Za-z][A-Za-z0-9_-]*>?", candidate)+ if match is None:+ continue+ token = match.group(0)+ if len(token) < 3:+ continue+ rest = candidate[len(token):].strip()+ if rest and not any(marker.startswith(token + rest) for marker in _A2UI_STREAM_PARTIAL_MARKERS):+ continue+ if any(marker.startswith(token) and token != marker for marker in _A2UI_STREAM_PARTIAL_MARKERS):+ return True+ return False+++def _stream_probe_has_a2ui_marker(value: Any) -> bool:+ return _contains_a2ui_marker(value) or _looks_like_partial_a2ui_marker(value)+++_A2UI_STREAM_PROTOCOL_START_RE = re.compile(+ r"(?im)^(?P<marker>[ \t]*(?:[\[{,][ \t]*)*\"?"+ r"(?:beginRendering|surfaceUpdate|dataModelUpdate|deleteSurface)\"?[ \t]*(?::|$))"+)+++def _recent_line_offsets(value: str) -> list[tuple[int, str]]:+ if not value:+ return []+ lines = value.splitlines(keepends=True)+ start = 0+ offsets: list[tuple[int, str]] = []+ for line in lines:+ offsets.append((start, line))+ start += len(line)+ if value.endswith("\n"):+ offsets.append((len(value), ""))+ return offsets[-3:] or [(0, value)]+++def _a2ui_marker_start(value: Any) -> int | None:+ if not isinstance(value, str) or not value:+ return None++ tag_index = value.find("<a2ui-json")+ protocol_match = _A2UI_STREAM_PROTOCOL_START_RE.search(value)+ protocol_index = protocol_match.start("marker") if protocol_match is not None else -1+ indexes = [index for index in (tag_index, protocol_index) if index >= 0]+ if indexes:+ return min(indexes)++ for line_start, line in _recent_line_offsets(value):+ stripped_line = line.strip()+ if not stripped_line:+ continue+ leading = len(line) - len(line.lstrip())+ candidate = stripped_line.lstrip("[{,").strip().lstrip('"')+ match = re.match(r"<?[A-Za-z][A-Za-z0-9_-]*>?", candidate)+ if match is None:+ continue+ token = match.group(0)+ if len(token) < 3:+ continue+ rest = candidate[len(token):].strip()+ if rest and not any(marker.startswith(token + rest) for marker in _A2UI_STREAM_PARTIAL_MARKERS):+ continue+ if any(marker.startswith(token) and token != marker for marker in _A2UI_STREAM_PARTIAL_MARKERS):+ return line_start + leading+ return None+++def _split_a2ui_stream_content(previous_probe: str, content: str) -> tuple[str, str] | None:+ combined = f"{previous_probe}{content}"+ marker_start = _a2ui_marker_start(combined)+ if marker_start is None:+ return None+ content_start = len(combined) - len(content)+ if marker_start <= content_start:+ return "", content+ split_index = marker_start - content_start+ return content[:split_index], content[split_index:]load_dotenv(dotenv_path=get_env_file(), override=True)@@ -1698,6 +1814,8 @@ class JiuWenSwarm:await self._session_manager.submit_task(session_id, run_stream_task)suppress_a2ui_stream = False+ a2ui_pending_render_sent = False+ a2ui_stream_probe = ""try:while not stream_done.is_set() or not stream_queue.empty():try:@@ -1756,10 +1874,33 @@ class JiuWenSwarm:)payload_content = str(data.payload.get("content", ""))+ a2ui_split = None+ if et in {"chat.delta", "chat.final"} and payload_content:+ a2ui_split = _split_a2ui_stream_content(a2ui_stream_probe, payload_content)+ a2ui_stream_probe = _extend_a2ui_stream_probe(a2ui_stream_probe, payload_content)if et == "chat.delta":final_answer_chunks.append(payload_content)- if suppress_a2ui_stream or _contains_a2ui_marker(payload_content):+ if suppress_a2ui_stream or a2ui_split is not None:+ first_a2ui_suppression = not suppress_a2ui_stream+ if first_a2ui_suppression:+ logger.info(+ "A2UI stream suppression activated: request_id=%s event_type=%s",+ rid,+ et,+ )suppress_a2ui_stream = True+ if a2ui_split is not None and a2ui_split[0]:+ prefix_payload = dict(data.payload)+ prefix_payload["content"] = a2ui_split[0]+ yield AgentResponseChunk(+ request_id=data.request_id,+ channel_id=data.channel_id,+ payload=prefix_payload,+ is_complete=False,+ )+ if first_a2ui_suppression and not a2ui_pending_render_sent:+ yield _make_a2ui_pending_render_chunk(request_id=rid, channel_id=cid)+ a2ui_pending_render_sent = Truecontinuedurable_pending_final_chunks.append(payload_content)should_record = False@@ -1769,8 +1910,18 @@ class JiuWenSwarm:elif et == "chat.tool_call":_persist_pending_final_text()elif et == "chat.final":- if suppress_a2ui_stream or _contains_a2ui_marker(payload_content):+ if suppress_a2ui_stream or a2ui_split is not None:+ first_a2ui_suppression = not suppress_a2ui_stream+ if first_a2ui_suppression:+ logger.info(+ "A2UI stream suppression activated: request_id=%s event_type=%s",+ rid,+ et,+ )suppress_a2ui_stream = True+ if first_a2ui_suppression and not a2ui_pending_render_sent:+ yield _make_a2ui_pending_render_chunk(request_id=rid, channel_id=cid)+ a2ui_pending_render_sent = Truefinal_answer_content = payload_contentdurable_pending_final_chunks = []continue@@ -1819,10 +1970,33 @@ class JiuWenSwarm:)payload_content = str(data.get("content", ""))+ a2ui_split = None+ if et in {"chat.delta", "chat.final"} and payload_content:+ a2ui_split = _split_a2ui_stream_content(a2ui_stream_probe, payload_content)+ a2ui_stream_probe = _extend_a2ui_stream_probe(a2ui_stream_probe, payload_content)if et == "chat.delta":final_answer_chunks.append(payload_content)- if suppress_a2ui_stream or _contains_a2ui_marker(payload_content):+ if suppress_a2ui_stream or a2ui_split is not None:+ first_a2ui_suppression = not suppress_a2ui_stream+ if first_a2ui_suppression:+ logger.info(+ "A2UI stream suppression activated: request_id=%s event_type=%s",+ rid,+ et,+ )suppress_a2ui_stream = True+ if a2ui_split is not None and a2ui_split[0]:+ prefix_payload = dict(data)+ prefix_payload["content"] = a2ui_split[0]+ yield AgentResponseChunk(+ request_id=rid,+ channel_id=cid,+ payload=prefix_payload,+ is_complete=False,+ )+ if first_a2ui_suppression and not a2ui_pending_render_sent:+ yield _make_a2ui_pending_render_chunk(request_id=rid, channel_id=cid)+ a2ui_pending_render_sent = Truecontinuedurable_pending_final_chunks.append(payload_content)should_record = False@@ -1832,8 +2006,18 @@ class JiuWenSwarm:elif et == "chat.tool_call":_persist_pending_final_text()elif et == "chat.final":- if suppress_a2ui_stream or _contains_a2ui_marker(payload_content):+ if suppress_a2ui_stream or a2ui_split is not None:+ first_a2ui_suppression = not suppress_a2ui_stream+ if first_a2ui_suppression:+ logger.info(+ "A2UI stream suppression activated: request_id=%s event_type=%s",+ rid,+ et,+ )suppress_a2ui_stream = True+ if first_a2ui_suppression and not a2ui_pending_render_sent:+ yield _make_a2ui_pending_render_chunk(request_id=rid, channel_id=cid)+ a2ui_pending_render_sent = Truefinal_answer_content = payload_contentdurable_pending_final_chunks = []continuediff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 01cd3f34ac..4199235aaf 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -3144,7 +3144,7 @@ class JiuWenSwarmDeepAdapter:rails=rails,vision_model_config=self._vision_model_config,audio_model_config=self._audio_model_config,- enable_read_image_multimodal=False,+ enable_read_image_multimodal=self._vision_model_config is None,completion_timeout=config.get("completion_timeout", 3600.0),)@@ -3527,7 +3527,7 @@ class JiuWenSwarmDeepAdapter:context_engine_config=_deep_agent_context_engine_config(config),vision_model_config=self._vision_model_config,audio_model_config=self._audio_model_config,- enable_read_image_multimodal=False,+ enable_read_image_multimodal=self._vision_model_config is None,completion_timeout=config.get("completion_timeout", 3600.0),)diff --git a/tests/system_tests/test_a2ui_system_flow.py b/tests/system_tests/test_a2ui_system_flow.pyindex c42dcab627..e59befba40 100644--- a/tests/system_tests/test_a2ui_system_flow.py+++ b/tests/system_tests/test_a2ui_system_flow.py@@ -78,8 +78,342 @@ async def test_a2ui_system_flow_accepts_event_and_valid_response(monkeypatch):assert config.enabled is Trueassert "<a2ui-json>" in prompt_section+ assert "browser_preflight_submit" in prompt_section+ assert "hotel_option_select" in prompt_section+ assert "hotel_payment_confirm" in prompt_section+ assert "gmail_email_select" in prompt_section+ assert "gmail_cleanup_confirm" in prompt_section+ assert "social_post_draft_select" in prompt_section+ assert "social_post_confirm" in prompt_section+ assert "Do not ask for those missing browser-task details" in prompt_section+ assert "ask_user tool" in prompt_section+ assert "Mandatory A2UI account-action gate" in prompt_section+ assert "task_tool as a substitute" in prompt_section+ assert "returned emails/threads MUST still be shown as A2UI candidates" in prompt_sectionassert client_prompt is not Noneassert "submit_selection" in client_promptassert "alpha" in client_promptassert finalized == VALID_A2UI_RESPONSEassert validation.valid is True+++def test_a2ui_browser_preflight_event_prompts_browser_subagent(monkeypatch):+ """Browser preflight submissions should continue into the browser subagent path."""+ from jiuwenswarm.server.runtime.a2ui.integration import build_user_prompt_if_a2ui_event++ monkeypatch.setenv("JIUWENSWARM_A2UI_ENABLED", "true")++ client_event = {+ "type": "a2ui.client_event",+ "event": {+ "userAction": {+ "name": "browser_preflight_submit",+ "surfaceId": "browser-preflight",+ "sourceComponentId": "submit",+ "context": {+ "original_query": "Book a hotel in Shanghai",+ "task_type": "hotel",+ "next_action": "run_browser_agent",+ "city": "Shanghai",+ "check_in": "2026-07-01",+ "check_out": "2026-07-03",+ "must_confirm_before_payment": True,+ },+ }+ },+ }++ client_prompt = build_user_prompt_if_a2ui_event(+ client_event,+ channel="web",+ language="en",+ )++ assert client_prompt is not None+ assert "browser task preflight submission" in client_prompt+ assert "spawn_sub_agent" in client_prompt+ assert "browser_agent" in client_prompt+ assert "Book a hotel in Shanghai" in client_prompt+ assert "must_confirm_before_payment" in client_prompt+++def test_a2ui_hotel_option_select_continues_current_browser_state(monkeypatch):+ """Hotel candidate selection should not be interpreted as a fresh hotel search."""+ from jiuwenswarm.server.runtime.a2ui.integration import build_user_prompt_if_a2ui_event++ monkeypatch.setenv("JIUWENSWARM_A2UI_ENABLED", "true")++ client_event = {+ "type": "a2ui.client_event",+ "event": {+ "userAction": {+ "name": "hotel_option_select",+ "surfaceId": "hotel-candidates",+ "sourceComponentId": "hotel-2-select",+ "context": {+ "original_query": "Book a hotel in Shanghai",+ "task_type": "hotel",+ "next_action": "continue_hotel_booking",+ "city": "Shanghai",+ "check_in": "2026-07-01",+ "check_out": "2026-07-03",+ "guest_count": 2,+ "hotel_name": "Example Riverside Hotel",+ "candidate_index": 2,+ "detail_url": "https://example.test/hotel/2",+ },+ }+ },+ }++ client_prompt = build_user_prompt_if_a2ui_event(+ client_event,+ channel="web",+ language="en",+ )++ assert client_prompt is not None+ assert "hotel candidate selection" in client_prompt+ assert "spawn_sub_agent" in client_prompt+ assert "browser_agent" in client_prompt+ assert "current browser state/session" in client_prompt+ assert "Do not repeat the broad hotel search" in client_prompt+ assert "hotel_payment_confirm" in client_prompt+ assert "Example Riverside Hotel" in client_prompt+++def test_a2ui_hotel_payment_confirmation_is_guarded(monkeypatch):+ """Final payment confirmation should verify the visible order before proceeding."""+ from jiuwenswarm.server.runtime.a2ui.integration import build_user_prompt_if_a2ui_event++ monkeypatch.setenv("JIUWENSWARM_A2UI_ENABLED", "true")++ client_event = {+ "type": "a2ui.client_event",+ "event": {+ "userAction": {+ "name": "hotel_payment_confirm",+ "surfaceId": "hotel-payment",+ "sourceComponentId": "confirm",+ "context": {+ "task_type": "hotel",+ "next_action": "confirm_hotel_payment",+ "hotel_name": "Example Riverside Hotel",+ "total_price": "CNY 1288",+ },+ }+ },+ }++ client_prompt = build_user_prompt_if_a2ui_event(+ client_event,+ channel="web",+ language="en",+ )++ assert client_prompt is not None+ assert "final hotel payment confirmation" in client_prompt+ assert "verify that the selected hotel" in client_prompt+ assert "current browser state match the context" in client_prompt+ assert "Example Riverside Hotel" in client_prompt+++def test_a2ui_gmail_email_select_continues_current_search_results(monkeypatch):+ """Gmail email selection should open the selected result, not rerun the broad search."""+ from jiuwenswarm.server.runtime.a2ui.integration import build_user_prompt_if_a2ui_event++ monkeypatch.setenv("JIUWENSWARM_A2UI_ENABLED", "true")++ client_event = {+ "type": "a2ui.client_event",+ "event": {+ "userAction": {+ "name": "gmail_email_select",+ "surfaceId": "gmail-results",+ "sourceComponentId": "thread-1-open",+ "context": {+ "original_query": "Summarize recent project delay emails",+ "task_type": "gmail",+ "next_action": "continue_gmail_email_review",+ "search_query": "from:[email protected] project delay newer:7d",+ "sender": "[email protected]",+ "subject": "Project delay update",+ "thread_index": 1,+ "thread_url": "https://mail.google.com/mail/u/0/#inbox/thread-a:r1",+ },+ }+ },+ }++ client_prompt = build_user_prompt_if_a2ui_event(+ client_event,+ channel="web",+ language="en",+ )++ assert client_prompt is not None+ assert "Gmail email/thread selection" in client_prompt+ assert "spawn_sub_agent" in client_prompt+ assert "browser_agent" in client_prompt+ assert "current Gmail browser state/session" in client_prompt+ assert "Do not repeat the broad Gmail search" in client_prompt+ assert "gmail_reply_draft_select" in client_prompt+ assert "Project delay update" in client_prompt+++def test_a2ui_gmail_cleanup_confirmation_is_guarded(monkeypatch):+ """Gmail cleanup confirmation should verify selected messages before mutation."""+ from jiuwenswarm.server.runtime.a2ui.integration import build_user_prompt_if_a2ui_event++ monkeypatch.setenv("JIUWENSWARM_A2UI_ENABLED", "true")++ client_event = {+ "type": "a2ui.client_event",+ "event": {+ "userAction": {+ "name": "gmail_cleanup_confirm",+ "surfaceId": "gmail-cleanup-confirm",+ "sourceComponentId": "confirm",+ "context": {+ "task_type": "gmail_cleanup",+ "next_action": "confirm_gmail_cleanup",+ "operation": "archive",+ "selected_count": 12,+ "search_query": "category:promotions older:30d",+ },+ }+ },+ }++ client_prompt = build_user_prompt_if_a2ui_event(+ client_event,+ channel="web",+ language="en",+ )++ assert client_prompt is not None+ assert "final Gmail cleanup confirmation" in client_prompt+ assert "spawn_sub_agent" in client_prompt+ assert "current Gmail browser state/session" in client_prompt+ assert "verify the selected messages/count" in client_prompt+ assert "Never delete, archive, unsubscribe" in client_prompt+ assert "category:promotions older:30d" in client_prompt+++def test_a2ui_gmail_send_confirmation_allows_confirmed_send(monkeypatch):+ """Final Gmail send confirmation should send only matching visible content."""+ from jiuwenswarm.server.runtime.a2ui.integration import build_user_prompt_if_a2ui_event++ monkeypatch.setenv("JIUWENSWARM_A2UI_ENABLED", "true")++ client_event = {+ "type": "a2ui.client_event",+ "event": {+ "userAction": {+ "name": "gmail_send_confirm",+ "surfaceId": "gmail-send-confirm",+ "sourceComponentId": "send",+ "context": {+ "task_type": "gmail",+ "next_action": "confirm_gmail_send",+ "recipient": "[email protected]",+ "subject": "Re: Project delay update",+ "body": "Thanks for the update. I will adjust the plan.",+ },+ }+ },+ }++ client_prompt = build_user_prompt_if_a2ui_event(+ client_event,+ channel="web",+ language="en",+ )++ assert client_prompt is not None+ assert "final Gmail send confirmation" in client_prompt+ assert "visible Gmail compose/reply state matches" in client_prompt+ assert "send the email now" in client_prompt+ assert "Never send to a different recipient" in client_prompt+ assert "[email protected]" in client_prompt+++def test_a2ui_social_post_draft_select_stops_before_publish(monkeypatch):+ """Social draft selection should fill compose UI but not publish."""+ from jiuwenswarm.server.runtime.a2ui.integration import build_user_prompt_if_a2ui_event++ monkeypatch.setenv("JIUWENSWARM_A2UI_ENABLED", "true")++ client_event = {+ "type": "a2ui.client_event",+ "event": {+ "userAction": {+ "name": "social_post_draft_select",+ "surfaceId": "social-drafts",+ "sourceComponentId": "draft-1",+ "context": {+ "original_query": "Draft a LinkedIn product update",+ "task_type": "social_post",+ "next_action": "continue_social_post_draft",+ "platform": "LinkedIn",+ "account_hint": "Company Page",+ "draft_body": "We shipped a faster A2UI booking flow.",+ "visibility": "public",+ },+ }+ },+ }++ client_prompt = build_user_prompt_if_a2ui_event(+ client_event,+ channel="web",+ language="en",+ )++ assert client_prompt is not None+ assert "social media post draft selection" in client_prompt+ assert "spawn_sub_agent" in client_prompt+ assert "browser_agent" in client_prompt+ assert "fill the selected draft" in client_prompt+ assert "Do not publish" in client_prompt+ assert "social_post_confirm" in client_prompt+ assert "LinkedIn" in client_prompt+++def test_a2ui_social_post_confirmation_is_guarded(monkeypatch):+ """Final social publish should verify visible compose state before posting."""+ from jiuwenswarm.server.runtime.a2ui.integration import build_user_prompt_if_a2ui_event++ monkeypatch.setenv("JIUWENSWARM_A2UI_ENABLED", "true")++ client_event = {+ "type": "a2ui.client_event",+ "event": {+ "userAction": {+ "name": "social_post_confirm",+ "surfaceId": "social-post-confirm",+ "sourceComponentId": "publish",+ "context": {+ "task_type": "social_post",+ "next_action": "confirm_social_post",+ "platform": "LinkedIn",+ "account_hint": "Company Page",+ "draft_body": "We shipped a faster A2UI booking flow.",+ "visibility": "public",+ },+ }+ },+ }++ client_prompt = build_user_prompt_if_a2ui_event(+ client_event,+ channel="web",+ language="en",+ )++ assert client_prompt is not None+ assert "final social media post confirmation" in client_prompt+ assert "verify that the visible compose state matches" in client_prompt+ assert "publish the post now" in client_prompt+ assert "Never publish different content" in client_prompt+ assert "LinkedIn" in client_promptdiff --git a/tests/unit_tests/a2ui/test_finalizer.py b/tests/unit_tests/a2ui/test_finalizer.pyindex 152350022a..1591405862 100644--- a/tests/unit_tests/a2ui/test_finalizer.py+++ b/tests/unit_tests/a2ui/test_finalizer.py@@ -33,6 +33,14 @@ VALID_A2UI_RESPONSE = """<a2ui-json>]</a2ui-json>"""+UNTAGGED_A2UI_LIKE_RESPONSE = """beginRendering++Email summary:++- Found 5 messages from openjiuwen+- 1 message needs a reply+"""+INVALID_A2UI_RESPONSE = """Here is the UI.<a2ui-json>@@ -68,6 +76,29 @@ async def test_a2ui_finalizer_repairs_invalid_tagged_response():assert "A2UI 0.8" in prompts[0]+async def test_a2ui_finalizer_repairs_untagged_a2ui_like_response():+ from jiuwenswarm.server.runtime.a2ui.runtime.finalizer import A2UIResponseFinalizer++ prompts = []++ async def repair_call(prompt: str):+ prompts.append(prompt)+ return SimpleNamespace(content=VALID_A2UI_RESPONSE)++ result = await A2UIResponseFinalizer().finalize(+ UNTAGGED_A2UI_LIKE_RESPONSE,+ user_query="summarize openjiuwen email and confirm reply",+ request_id="req-finalizer-untagged-repair",+ repair_call=repair_call,+ )++ assert result == VALID_A2UI_RESPONSE+ assert len(prompts) == 1+ assert "A2UI tags" in prompts[0]+ assert "beginRendering" in prompts[0]++@pytest.mark.asyncioasync def test_a2ui_finalizer_falls_back_after_failed_repairs():from jiuwenswarm.server.runtime.a2ui.runtime.finalizer import A2UIResponseFinalizerdiff --git a/tests/unit_tests/a2ui/test_integration_bridge.py b/tests/unit_tests/a2ui/test_integration_bridge.pyindex ba320a8cf3..599714af8c 100644--- a/tests/unit_tests/a2ui/test_integration_bridge.py+++ b/tests/unit_tests/a2ui/test_integration_bridge.py@@ -145,6 +145,79 @@ def test_normal_text_prompt_builder_keeps_string_flow(monkeypatch):assert '"type": "user input"' in prompt+def test_a2ui_stream_probe_detects_split_protocol_marker():+ """Stream suppression should survive protocol markers split across chunks."""+ from jiuwenswarm.server.runtime.agent_adapter.interface import (+ _extend_a2ui_stream_probe,+ _stream_probe_has_a2ui_marker,+ )++ probe = ""+ probe = _extend_a2ui_stream_probe(probe, "好的,开始整理。\n\nbeg")++ assert _stream_probe_has_a2ui_marker(probe) is True++ probe = _extend_a2ui_stream_probe(probe, "inRend")++ assert _stream_probe_has_a2ui_marker(probe) is True+++def test_a2ui_stream_probe_ignores_regular_begin_text():+ """Plain text containing begin-like words should keep normal streaming."""+ from jiuwenswarm.server.runtime.agent_adapter.interface import (+ _extend_a2ui_stream_probe,+ _stream_probe_has_a2ui_marker,+ )++ probe = _extend_a2ui_stream_probe("", "I will begin by summarizing the mailbox.")++ assert _stream_probe_has_a2ui_marker(probe) is False+++def test_a2ui_stream_probe_ignores_begin_sentence_at_line_start():+ """A normal sentence starting with begin should not look like A2UI."""+ from jiuwenswarm.server.runtime.agent_adapter.interface import (+ _extend_a2ui_stream_probe,+ _stream_probe_has_a2ui_marker,+ )++ probe = _extend_a2ui_stream_probe("", "begin by summarizing the mailbox.")++ assert _stream_probe_has_a2ui_marker(probe) is False+++def test_split_a2ui_stream_content_keeps_prefix_streamable():+ """Only A2UI protocol text should be suppressed from a mixed chunk."""+ from jiuwenswarm.server.runtime.agent_adapter.interface import _split_a2ui_stream_content++ split = _split_a2ui_stream_content(+ "",+ "浏览器代理已完成搜索和整理,现在为你展示结果。\n\nbeginRendering\n邮件整理完成",+ )++ assert split == (+ "浏览器代理已完成搜索和整理,现在为你展示结果。\n\n",+ "beginRendering\n邮件整理完成",+ )+++def test_split_a2ui_stream_content_handles_partial_marker():+ """A partial marker should suppress only the marker line."""+ from jiuwenswarm.server.runtime.agent_adapter.interface import _split_a2ui_stream_content++ split = _split_a2ui_stream_content("", "现在为你展示结果。\n\nbeg")++ assert split == ("现在为你展示结果。\n\n", "beg")+++def test_a2ui_pending_render_delta_stays_open():+ """The Web renderer shows its pending state only for an open A2UI block."""+ from jiuwenswarm.server.runtime.agent_adapter.interface import _A2UI_PENDING_RENDER_DELTA++ assert _A2UI_PENDING_RENDER_DELTA.startswith("<a2ui-json>")+ assert "</a2ui-json>" not in _A2UI_PENDING_RENDER_DELTA++def test_agent_prompt_builder_accepts_a2ui_client_event_dict(monkeypatch):"""Structured Web A2UI events should bypass normal text prompt wrapping."""from jiuwenswarm.server.runtime.agent_adapter.interface import build_user_promptdiff --git a/tests/unit_tests/a2ui/test_prompt_instructions.py b/tests/unit_tests/a2ui/test_prompt_instructions.pyindex e3e4c700f1..3b642bf1c1 100644--- a/tests/unit_tests/a2ui/test_prompt_instructions.py+++ b/tests/unit_tests/a2ui/test_prompt_instructions.py@@ -23,6 +23,8 @@ def test_a2ui_prompt_is_autonomous_not_forced():assert "A2UI is optional" in instructionassert "If A2UI is not appropriate, answer in plain text" in instructionassert "Do not promise to show the result with A2UI and then output only Markdown" in instruction+ assert "Mandatory A2UI account-action gate" in instruction+ assert "This is not optional" in instructiondef test_a2ui_prompt_discourages_nested_templates():@@ -32,6 +34,15 @@ def test_a2ui_prompt_discourages_nested_templates():assert "flatten repeated item details" in instruction+def test_a2ui_prompt_defines_hotel_booking_actions():+ instruction = build_a2ui_autonomy_instruction("en")++ assert "hotel_option_select" in instruction+ assert "continue_hotel_booking" in instruction+ assert "hotel_payment_confirm" in instruction+ assert "hotel_payment_cancel" in instruction++def test_a2ui_prompt_discourages_unsupported_popup_components():instruction = build_a2ui_autonomy_instruction("en")@@ -50,6 +61,23 @@ def test_a2ui_zh_prompt_discourages_unsupported_popup_components():assert "纯文本" in instruction+def test_a2ui_prompt_defines_gmail_and_social_actions():+ instruction = build_a2ui_autonomy_instruction("en")++ assert "Mandatory A2UI account-action gate" in instruction+ assert "task_tool as a substitute" in instruction+ assert "Never search multiple emails and send replies in the same uninterrupted run" in instruction+ assert "returned emails/threads MUST still be shown as A2UI candidates" in instruction+ assert "gmail_email_select" in instruction+ assert "gmail_reply_draft_select" in instruction+ assert "gmail_send_confirm" in instruction+ assert "gmail_cleanup_select" in instruction+ assert "gmail_cleanup_confirm" in instruction+ assert "social_post_draft_select" in instruction+ assert "social_post_confirm" in instruction+ assert "social_post_cancel" in instruction++def test_a2ui_zh_prompt_section_is_readable():prompt = build_a2ui_prompt_section("zh")diff --git a/tests/unit_tests/a2ui/test_response_finalization.py b/tests/unit_tests/a2ui/test_response_finalization.pyindex 4ece508beb..ddcb34808b 100644--- a/tests/unit_tests/a2ui/test_response_finalization.py+++ b/tests/unit_tests/a2ui/test_response_finalization.py@@ -44,6 +44,24 @@ INVALID_A2UI_RESPONSE = """Here is a form.]</a2ui-json>"""+PARSEABLE_INVALID_A2UI_RESPONSE = """<a2ui-json>+[+ {+ "beginRendering": {+ "surfaceId": "bad"+ }+ }+]+</a2ui-json>"""++UNTAGGED_A2UI_LIKE_RESPONSE = """beginRendering++Email summary:++- Found 5 messages from openjiuwen+- 1 message needs a reply+"""+@pytest.mark.asyncioasync def test_finalize_a2ui_assistant_content_repairs_invalid_response(monkeypatch):@@ -66,8 +84,32 @@ async def test_finalize_a2ui_assistant_content_repairs_invalid_response(monkeypaassert result == VALID_A2UI_RESPONSE+async def test_finalize_a2ui_assistant_content_repairs_parseable_invalid_response(monkeypatch):+ from jiuwenswarm.server.runtime.a2ui.runtime.response_finalization import finalize_a2ui_assistant_content++ monkeypatch.setenv("JIUWENSWARM_A2UI_ENABLED", "true")+ repair_prompts = []++ async def repair_call(prompt: str):+ repair_prompts.append(prompt)+ return SimpleNamespace(content=VALID_A2UI_RESPONSE)++ result = await finalize_a2ui_assistant_content(+ PARSEABLE_INVALID_A2UI_RESPONSE,+ user_query="generate a form",+ request_id="req-parseable-invalid",+ repair_call=repair_call,+ a2ui_enabled=True,+ )++ assert result == VALID_A2UI_RESPONSE+ assert len(repair_prompts) == 1++@pytest.mark.asyncioasync def test_finalize_a2ui_assistant_content_leaves_valid_response_unchanged(monkeypatch):+ from jiuwenswarm.server.runtime.a2ui.runtime import response_finalizationfrom jiuwenswarm.server.runtime.a2ui.runtime.response_finalization import finalize_a2ui_assistant_contentmonkeypatch.setenv("JIUWENSWARM_A2UI_ENABLED", "true")@@ -75,6 +117,11 @@ async def test_finalize_a2ui_assistant_content_leaves_valid_response_unchanged(masync def repair_call(prompt: str):raise AssertionError("valid A2UI response must not trigger repair")+ async def fail_finalizer(*args, **kwargs):+ raise AssertionError("schema-valid tagged A2UI response should use the fast path")++ monkeypatch.setattr(response_finalization.A2UIResponseFinalizer, "finalize_result", fail_finalizer)+result = await finalize_a2ui_assistant_content(VALID_A2UI_RESPONSE,user_query="generate a form",@@ -86,6 +133,56 @@ async def test_finalize_a2ui_assistant_content_leaves_valid_response_unchanged(massert result == VALID_A2UI_RESPONSE+async def test_finalize_a2ui_assistant_content_times_out_to_text_fallback(monkeypatch):+ from jiuwenswarm.server.runtime.a2ui.runtime import response_finalization+ from jiuwenswarm.server.runtime.a2ui.runtime.response_finalization import finalize_a2ui_assistant_content++ monkeypatch.setenv("JIUWENSWARM_A2UI_ENABLED", "true")+ monkeypatch.setattr(response_finalization, "_A2UI_FINALIZATION_TIMEOUT_SECONDS", 0.01)++ async def slow_finalizer(*args, **kwargs):+ import asyncio++ await asyncio.sleep(1)++ monkeypatch.setattr(response_finalization.A2UIResponseFinalizer, "finalize_result", slow_finalizer)++ result = await finalize_a2ui_assistant_content(+ UNTAGGED_A2UI_LIKE_RESPONSE,+ user_query="summarize openjiuwen email and confirm reply",+ request_id="req-timeout",+ repair_call=None,+ a2ui_enabled=True,+ )++ assert "Email summary" in result+++async def test_finalize_a2ui_assistant_content_repairs_untagged_a2ui_like_response(monkeypatch):+ from jiuwenswarm.server.runtime.a2ui.runtime.response_finalization import finalize_a2ui_assistant_content++ monkeypatch.setenv("JIUWENSWARM_A2UI_ENABLED", "true")+ repair_prompts = []++ async def repair_call(prompt: str):+ repair_prompts.append(prompt)+ return SimpleNamespace(content=VALID_A2UI_RESPONSE)++ result = await finalize_a2ui_assistant_content(+ UNTAGGED_A2UI_LIKE_RESPONSE,+ user_query="summarize openjiuwen email and confirm reply",+ request_id="req-untagged-repair",+ repair_call=repair_call,+ a2ui_enabled=True,+ )++ assert result == VALID_A2UI_RESPONSE+ assert len(repair_prompts) == 1+ assert "A2UI tags" in repair_prompts[0]++@pytest.mark.asyncioasync def test_finalize_a2ui_assistant_content_skips_when_disabled(monkeypatch):from jiuwenswarm.server.runtime.a2ui.runtime.response_finalization import finalize_a2ui_assistant_contentdiff --git a/tests/unit_tests/agentserver/test_a2x_client_init.py b/tests/unit_tests/agentserver/test_a2x_client_init.pyindex 809679657a..b4a125dd46 100644--- a/tests/unit_tests/agentserver/test_a2x_client_init.py+++ b/tests/unit_tests/agentserver/test_a2x_client_init.py@@ -200,7 +200,14 @@ async def test_create_instance_registers_blank_agent_for_teammate(monkeypatch: preturn_value=(None, False)),patch.object(interface_module.JiuWenSwarmDeepAdapter, "load_user_rails", AsyncMock()),patch.object(interface_module, "init_permission_engine", return_value=None),- patch.object(interface_module, "create_deep_agent", return_value=MagicMock(name="deep_agent", ensure_initialized=AsyncMock())),+ patch.object(+ interface_module,+ "create_deep_agent",+ return_value=MagicMock(+ name="deep_agent",+ ensure_initialized=AsyncMock(),+ ),+ ),):await adapter.create_instance()@@ -383,16 +390,44 @@ async def test_create_instance_continues_when_a2x_client_init_fails(monkeypatch:kwargs = create_agent_mock.call_args.kwargsassert "runtime_cwd" not in kwargsassert "project_root" not in kwargs- assert kwargs["enable_read_image_multimodal"] is False+ assert kwargs["enable_read_image_multimodal"] is True-def test_make_deep_agent_config_disables_read_image_multimodal(+def test_make_deep_agent_config_keeps_read_image_multimodal_without_vision_model(monkeypatch: pytest.MonkeyPatch,) -> None:adapter = JiuWenSwarmDeepAdapter()config_base = _make_config("teamleader")monkeypatch.setattr(interface_module, "get_config", lambda: config_base)+ with patch.object(+ interface_module.JiuWenSwarmDeepAdapter,+ "_build_configured_subagents",+ return_value=(None, False),+ ):+ deep_cfg = adapter._make_deep_agent_config(+ model=object(),+ config=config_base["react"],+ agent_card=MagicMock(),+ tool_cards=[],+ rails=[],+ )++ assert deep_cfg.enable_read_image_multimodal is True+++def test_make_deep_agent_config_disables_read_image_multimodal_with_vision_model(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ adapter = JiuWenSwarmDeepAdapter()+ adapter._vision_model_config = interface_module.VisionModelConfig(+ api_key="vision-key",+ base_url="https://vision.example/v1",+ model="vision-model",+ )+ config_base = _make_config("teamleader")+ monkeypatch.setattr(interface_module, "get_config", lambda: config_base)+with patch.object(interface_module.JiuWenSwarmDeepAdapter,"_build_configured_subagents",diff --git a/tests/unit_tests/agentserver/test_system_prompt_restructure.py b/tests/unit_tests/agentserver/test_system_prompt_restructure.pyindex 432571d143..0b7678d47c 100644--- a/tests/unit_tests/agentserver/test_system_prompt_restructure.py+++ b/tests/unit_tests/agentserver/test_system_prompt_restructure.py@@ -257,6 +257,18 @@ async def test_runtime_dynamic_sections_go_to_prompt_attachment_when_manager_avaassert "# Runtime State" not in promptassert "# Language" in promptassert "# Browser Tool Policy" in prompt+ assert "browser_preflight_submit" in prompt+ assert "hotel_option_select" in prompt+ assert "hotel_payment_confirm" in prompt+ assert "gmail_email_select" in prompt+ assert "gmail_cleanup_confirm" in prompt+ assert "social_post_draft_select" in prompt+ assert "social_post_confirm" in prompt+ assert "Do not use plain natural-language questions or `ask_user`" in prompt+ assert "Mandatory Web A2UI account-action gate" in prompt+ assert "`todo_create`, `todo_modify`, `memory_search`" in prompt+ assert "`task_tool`, plain text, Markdown, or `ask_user`" in prompt+ assert "show final A2UI confirmation before any" in promptassert "# Environment" in promptitems = await agent.prompt_attachment_manager.collect_for_session("sess1")