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): 修复提示词作用域、流式渲染与表单交互问题
jack_rickybaf2070fcdb9
diff --git a/jiuwenswarm/agents/harness/common/rails/response_prompt_rail.py b/jiuwenswarm/agents/harness/common/rails/response_prompt_rail.pyindex 80086cd31e..df3f746a21 100644--- a/jiuwenswarm/agents/harness/common/rails/response_prompt_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/response_prompt_rail.py@@ -16,10 +16,14 @@ from jiuwenswarm.agents.harness.common.prompt.prompt_builder import (PromptPriority,_response_prompt,)+from jiuwenswarm.server.runtime.a2ui.prompt_instructions import (+ is_a2ui_browser_workflow_request,+)logger = logging.getLogger(__name__)SKIP_A2UI_PROMPT_CONTEXT_KEY = "skip_a2ui"+A2UI_BROWSER_WORKFLOW_CONTEXT_KEY = "a2ui_browser_workflow"class ResponsePromptRail(DeepAgentRail):@@ -53,6 +57,16 @@ class ResponsePromptRail(DeepAgentRail):extra[JIUWENSWARM_CHANNEL_CONTEXT_KEY] = channelif isinstance(extra, dict) and self._should_skip_a2ui(ctx):extra[SKIP_A2UI_PROMPT_CONTEXT_KEY] = True+ if isinstance(extra, dict):+ inputs = getattr(ctx, "inputs", None)+ query = (+ inputs.get("query")+ if isinstance(inputs, dict)+ else getattr(inputs, "query", None)+ )+ extra[A2UI_BROWSER_WORKFLOW_CONTEXT_KEY] = (+ is_a2ui_browser_workflow_request(query)+ )async def before_model_call(self, ctx: AgentCallbackContext) -> None:if self.system_prompt_builder is None:@@ -63,6 +77,14 @@ class ResponsePromptRail(DeepAgentRail):self._sync_a2ui_prompt_section(self._resolve_channel(ctx),skip_a2ui=self._should_skip_a2ui(ctx),+ include_browser_workflows=self._is_browser_workflow(ctx),+ identity=(+ self._resolve_context_value(ctx, "request_id"),+ (+ self._resolve_context_value(ctx, "conversation_id")+ or self._resolve_context_value(ctx, "session_id")+ ),+ ),)def _should_skip_a2ui(self, ctx: AgentCallbackContext) -> bool:@@ -110,39 +132,82 @@ class ResponsePromptRail(DeepAgentRail):return None- def _sync_a2ui_prompt_section(self, channel: str | None, *, skip_a2ui: bool = False) -> None:+ @staticmethod+ def _resolve_context_value(ctx: AgentCallbackContext, key: str) -> str | None:+ for source in (getattr(ctx, "inputs", None), getattr(ctx, "extra", None)):+ value = source.get(key) if isinstance(source, dict) else getattr(source, key, None)+ if value is not None and str(value).strip():+ return str(value)+ return None++ def _is_browser_workflow(self, ctx: AgentCallbackContext) -> bool:+ extra = getattr(ctx, "extra", None)+ if isinstance(extra, dict) and A2UI_BROWSER_WORKFLOW_CONTEXT_KEY in extra:+ return extra[A2UI_BROWSER_WORKFLOW_CONTEXT_KEY] is True++ inputs = getattr(ctx, "inputs", None)+ query = inputs.get("query") if isinstance(inputs, dict) else getattr(inputs, "query", None)+ return is_a2ui_browser_workflow_request(query)++ def _sync_a2ui_prompt_section(+ self,+ channel: str | None,+ *,+ skip_a2ui: bool = False,+ include_browser_workflows: bool = False,+ identity: tuple[str | None, str | None] = (None, None),+ ) -> None:"""Inject or remove the A2UI prompt section from runtime config."""if self.system_prompt_builder is None:return+ request_id, conversation_id = identitytry: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)- return-from jiuwenswarm.server.runtime.a2ui.config import get_current_a2ui_configfrom jiuwenswarm.server.runtime.a2ui.runtime.prompt import build_a2ui_prompt_section- if not get_current_a2ui_config().enabled:+ is_web_channel = is_a2ui_channel(channel)+ enabled = get_current_a2ui_config().enabled if is_web_channel else False+ injected = is_web_channel and enabled and not skip_a2ui++ if not injected:self.system_prompt_builder.remove_section(LocalSectionName.A2UI)- return-- self.system_prompt_builder.add_section(- PromptSection(- name=LocalSectionName.A2UI,- content={- "cn": build_a2ui_prompt_section("cn"),- "en": build_a2ui_prompt_section("en"),- },- priority=PromptPriority.A2UI,+ else:+ self.system_prompt_builder.add_section(+ PromptSection(+ name=LocalSectionName.A2UI,+ content={+ "cn": build_a2ui_prompt_section(+ "cn",+ include_browser_workflows=include_browser_workflows,+ ),+ "en": build_a2ui_prompt_section(+ "en",+ include_browser_workflows=include_browser_workflows,+ ),+ },+ priority=PromptPriority.A2UI,+ ))++ logger.info(+ "A2UI prompt decision: request_id=%s conversation_id=%s "+ "channel=%s enabled=%s injected=%s browser_workflows=%s skip_a2ui=%s",+ request_id or "-",+ conversation_id or "-",+ channel or "-",+ enabled,+ injected,+ include_browser_workflows if injected else False,+ skip_a2ui,)except Exception:- logger.exception("Failed to sync A2UI prompt section")+ logger.exception(+ "Failed to sync A2UI prompt section: request_id=%s "+ "conversation_id=%s channel=%s",+ request_id or "-",+ conversation_id or "-",+ channel or "-",+ )self.system_prompt_builder.remove_section(LocalSectionName.A2UI)diff --git a/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py b/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.pyindex 37e9f24f55..d9ee8c6c8c 100644--- a/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/runtime_prompt_rail.py@@ -421,46 +421,6 @@ class RuntimePromptRail(DeepAgentRail):"page inspection, or extracting data from a live website, use `task_tool` 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 `task_tool` or `browser_agent` is unavailable, say that the browser "diff --git a/jiuwenswarm/channels/web/frontend/scripts/test-a2ui-action-defaults.mjs b/jiuwenswarm/channels/web/frontend/scripts/test-a2ui-action-defaults.mjsindex 105128c73a..121bec40db 100644--- a/jiuwenswarm/channels/web/frontend/scripts/test-a2ui-action-defaults.mjs+++ b/jiuwenswarm/channels/web/frontend/scripts/test-a2ui-action-defaults.mjs@@ -37,6 +37,82 @@ const {enrichA2UIClientEventWithDefaults,recordA2UIActionDefaults,} = await importTsModule(sourceUrl);+const helperOutputPath = await transpileTsModule(helperUrl, 'formDefaults.mjs');+const {+ isMultiSelectChoice,+ isSingleSelectChoice,+ nextChoiceSelections,+ selectionCollectionValues,+} = await import(`file://${helperOutputPath.replace(/\\/g, '/')}?choice-helpers`);++assert.equal(+ isMultiSelectChoice({ variant: 'chips', maxAllowedSelections: 1 }),+ true,+ 'chips controls should retain their multi-choice visual renderer',+);+assert.equal(+ isSingleSelectChoice({ variant: 'chips', maxAllowedSelections: 1 }),+ true,+ 'chips appearance must not override maxAllowedSelections=1 semantics',+);+assert.equal(+ isSingleSelectChoice({ variant: 'checkbox', maxAllowedSelections: 1 }),+ true,+ 'checkbox appearance must not override maxAllowedSelections=1 semantics',+);+assert.deepEqual(+ nextChoiceSelections(['very_spicy'], 'mild', true, 1),+ ['mild'],+ 'single-select chips should replace the previous selection',+);+assert.deepEqual(+ nextChoiceSelections(['very_spicy'], 'mild', true, 2),+ ['very_spicy', 'mild'],+ 'multi-select chips should add a second selection within the limit',+);+assert.deepEqual(+ nextChoiceSelections(['very_spicy', 'mild'], 'no_spicy', true, 2),+ ['very_spicy', 'mild'],+ 'multi-select chips should keep their previous value when the limit is exceeded',+);+assert.deepEqual(+ nextChoiceSelections(['very_spicy', 'mild'], 'mild', false),+ ['very_spicy'],+ 'multi-select chips should remove an unchecked selection',+);+assert.deepEqual(+ selectionCollectionValues(new Map()),+ [],+ 'an empty A2UI valueMap must not consume a hidden selection slot',+);+assert.deepEqual(+ selectionCollectionValues(new Map([+ ['0', 'chinese'],+ ['1', 'japanese'],+ ])),+ ['chinese', 'japanese'],+ 'A2UI valueMap selections should be read from their values',+);+const fiveCuisineSelections = ['chinese', 'japanese', 'western', 'mexican']+ .reduce(+ (selected, cuisine) => nextChoiceSelections(selected, cuisine, true, 5),+ selectionCollectionValues(new Map()),+ );+assert.deepEqual(+ nextChoiceSelections(fiveCuisineSelections, 'italian', true, 5),+ ['chinese', 'japanese', 'western', 'mexican', 'italian'],+ 'an empty valueMap should allow all five visible selections',+);+assert.deepEqual(+ nextChoiceSelections(+ ['chinese', 'japanese', 'western', 'mexican', 'italian'],+ 'korean',+ true,+ 5,+ ),+ ['chinese', 'japanese', 'western', 'mexican', 'italian'],+ 'the sixth visible selection should still be rejected',+);function selectionMessages(defaultValue = 'chinese') {return [diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/MultipleChoiceWithDefaults.tsx b/jiuwenswarm/channels/web/frontend/src/features/a2ui/MultipleChoiceWithDefaults.tsxindex fb6feb2fab..83f61e8f60 100644--- a/jiuwenswarm/channels/web/frontend/src/features/a2ui/MultipleChoiceWithDefaults.tsx+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/MultipleChoiceWithDefaults.tsx@@ -15,7 +15,10 @@ import {a2uiWarn,dualWriteA2UIValue,isMultiSelectChoice,+ isSingleSelectChoice,literalArrayValues,+ nextChoiceSelections,+ selectionCollectionValues,visibleChoiceDefault as visibleChoiceDefaultValue,} from './formDefaults';@@ -38,13 +41,9 @@ function nonEmptyChoiceValue(value: unknown): string | null {}function selectedValuesFromData(value: DataValue | null): string[] {- if (Array.isArray(value)) {- return value- .map(nonEmptyChoiceValue)- .filter((item): item is string => item !== null);- }- const singleValue = nonEmptyChoiceValue(value);- return singleValue ? [singleValue] : [];+ return selectionCollectionValues(value)+ .map(nonEmptyChoiceValue)+ .filter((item): item is string => item !== null);}export function visibleMultipleChoiceDefault(@@ -89,7 +88,7 @@ export function MultipleChoiceWithDefaults({const variant = rawProps.variant as string | undefined;const type = variant ?? rawProps.type as string | undefined;- const isSingleSelect = !isMultiSelect;+ const isSingleSelect = isSingleSelectChoice(rawProps);// Filterable search supportconst filterable = rawProps.filterable as boolean | undefined;@@ -126,34 +125,15 @@ export function MultipleChoiceWithDefaults({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);+ const nextValues = nextChoiceSelections(+ effectiveSelectedValues,+ optionValue,+ checked,+ maxAllowedSelections,+ );+ dualWriteA2UIValue(setValue, selectionsPath, nextValues);},- [selectionsPath, effectiveSelectedValues, maxAllowedSelections, isSingleSelect, setValue],+ [selectionsPath, effectiveSelectedValues, maxAllowedSelections, setValue],);const hostStyle = (diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/formDefaults.ts b/jiuwenswarm/channels/web/frontend/src/features/a2ui/formDefaults.tsindex 6377b255d2..b7e559b1e7 100644--- a/jiuwenswarm/channels/web/frontend/src/features/a2ui/formDefaults.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/formDefaults.ts@@ -88,6 +88,22 @@ export function literalArrayValues(value: unknown): unknown[] {: [];}+export function selectionCollectionValues(value: unknown): unknown[] {+ if (value === null || value === undefined) {+ return [];+ }+ if (Array.isArray(value)) {+ return value.flatMap(selectionCollectionValues);+ }+ if (value instanceof Map) {+ return Array.from(value.values()).flatMap(selectionCollectionValues);+ }+ if (isRecord(value) && Object.keys(value).length === 0) {+ return [];+ }+ return [value];+}+export function optionDefaultValue(options: unknown): unknown {if (!Array.isArray(options)) {return null;@@ -109,6 +125,37 @@ export function isMultiSelectChoice(props: UnknownRecord): boolean {type === 'checkbox' || (maxAllowedSelections !== undefined && maxAllowedSelections > 1);}+export function isSingleSelectChoice(props: UnknownRecord): boolean {+ return props.maxAllowedSelections === 1;+}++export function nextChoiceSelections(+ currentValues: string[],+ optionValue: string,+ checked: boolean,+ maxAllowedSelections?: number,+): string[] {+ if (maxAllowedSelections === 1) {+ return [optionValue];+ }++ const nextValues = [...currentValues];+ const existingIndex = nextValues.indexOf(optionValue);+ if (checked && existingIndex === -1) {+ nextValues.push(optionValue);+ } else if (!checked && existingIndex !== -1) {+ nextValues.splice(existingIndex, 1);+ }++ if (+ maxAllowedSelections !== undefined &&+ nextValues.length > maxAllowedSelections+ ) {+ return currentValues;+ }+ return nextValues;+}+export function visibleChoiceDefault(props: UnknownRecord): unknown {const selections = isRecord(props.selections) ? props.selections : null;const literalDefaults = literalArrayValues(selections);diff --git a/jiuwenswarm/channels/web/frontend/vite.config.ts b/jiuwenswarm/channels/web/frontend/vite.config.tsindex 36e2f56266..2db97275d5 100644--- a/jiuwenswarm/channels/web/frontend/vite.config.ts+++ b/jiuwenswarm/channels/web/frontend/vite.config.ts@@ -832,6 +832,15 @@ function devFileContentApi(): Plugin {}// https://vitejs.dev/config/+function portFromEnv(name: string, fallback: number): number {+ const value = Number.parseInt(process.env[name] ?? '', 10)+ return Number.isInteger(value) && value > 0 && value <= 65535 ? value : fallback+}++const frontendPort = portFromEnv('FRONTEND_PORT', 5173)+const webPort = portFromEnv('WEB_PORT', 19000)+const webTarget = `http://127.0.0.1:${webPort}`+export default defineConfig({plugins: [suppressWsProxySocketErrors(), devWsTrafficLogger(), devFileContentApi(), react(), svgr()],resolve: {@@ -840,15 +849,15 @@ export default defineConfig({},},server: {- port: 5173, // 默认端口- strictPort: true, // 强制使用 5173 端口+ port: frontendPort,+ strictPort: true,proxy: {'/api': {- target: 'http://127.0.0.1:19000',+ target: webTarget,changeOrigin: true,},'/ws': {- target: 'http://127.0.0.1:19000',+ target: webTarget,ws: true,changeOrigin: true,configure: (proxy) => {diff --git a/jiuwenswarm/server/runtime/a2ui/prompt_instructions.py b/jiuwenswarm/server/runtime/a2ui/prompt_instructions.pyindex 04cb64c18f..099ef16de3 100644--- a/jiuwenswarm/server/runtime/a2ui/prompt_instructions.py+++ b/jiuwenswarm/server/runtime/a2ui/prompt_instructions.py@@ -4,8 +4,83 @@from __future__ import annotations+import json+import re+from typing import Any-def build_a2ui_autonomy_instruction(language: str = "en") -> str:++_BROWSER_WORKFLOW_ACTION_MARKERS = (+ "browser_preflight_submit",+ "run_browser_agent",+ "hotel_option_select",+ "continue_hotel_booking",+ "hotel_payment_confirm",+ "hotel_payment_cancel",+ "gmail_email_select",+ "continue_gmail_email_review",+ "gmail_reply_draft_select",+ "continue_gmail_reply_draft",+ "gmail_send_confirm",+ "gmail_send_cancel",+ "gmail_cleanup_select",+ "review_gmail_cleanup",+ "gmail_cleanup_confirm",+ "gmail_cleanup_cancel",+ "social_post_draft_select",+ "continue_social_post_draft",+ "social_post_confirm",+ "social_post_cancel",+)+_BROWSER_WORKFLOW_INTENT_RE = re.compile(+ r"(?:"+ r"(?:book|reserve|buy|purchase|checkout|fill|submit|search|summari[sz]e|"+ r"reply|clean|archive|delete|post|publish|comment|like|follow|open|click)"+ r".{0,80}"+ r"(?:browser|web(?:site)?|gmail|e-?mail|mailbox|hotel|ticket|form|"+ r"social(?:\s+media)?|facebook|instagram|linkedin|x\.com|twitter)"+ r"|"+ r"(?:browser|web(?:site)?|gmail|e-?mail|mailbox|hotel|ticket|form|"+ r"social(?:\s+media)?|facebook|instagram|linkedin|x\.com|twitter)"+ r".{0,80}"+ r"(?:book|reserve|buy|purchase|checkout|fill|submit|search|summari[sz]e|"+ r"reply|clean|archive|delete|post|publish|comment|like|follow|open|click)"+ r"|"+ r"(?:预订|预约|购买|下单|填写|提交|搜索|查找|总结|回复|清理|归档|删除|"+ r"发布|发帖|评论|点赞|关注|打开|点击)"+ r".{0,40}"+ r"(?:浏览器|网页|网站|邮箱|邮件|收件箱|酒店|宾馆|机票|车票|表单|"+ r"社交媒体|微博|小红书)"+ r"|"+ r"(?:浏览器|网页|网站|邮箱|邮件|收件箱|酒店|宾馆|机票|车票|表单|"+ r"社交媒体|微博|小红书)"+ r".{0,40}"+ r"(?:预订|预约|购买|下单|填写|提交|搜索|查找|总结|回复|清理|归档|删除|"+ r"发布|发帖|评论|点赞|关注|打开|点击)"+ r")",+ re.IGNORECASE | re.DOTALL,+)+++def is_a2ui_browser_workflow_request(value: Any) -> bool:+ """Return whether the current request needs browser-specific A2UI rules."""+ if isinstance(value, str):+ text = value+ elif isinstance(value, (dict, list, tuple)):+ try:+ text = json.dumps(value, ensure_ascii=False)+ except (TypeError, ValueError):+ text = str(value)+ else:+ text = str(value or "")++ normalized = text.lower()+ if any(marker in normalized for marker in _BROWSER_WORKFLOW_ACTION_MARKERS):+ return True+ return bool(_BROWSER_WORKFLOW_INTENT_RE.search(text))+++def build_a2ui_browser_workflow_instruction() -> str:+ """Return browser-workflow rules for requests that actually need them."""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 "@@ -100,6 +175,16 @@ def build_a2ui_autonomy_instruction(language: str = "en") -> str:"comment, like, follow, delete, or perform externally visible social ""actions without final explicit confirmation.")+ return (+ mandatory_account_action_rule_en+ + browser_preflight_rule_en+ + hotel_booking_flow_rule_en+ + gmail_flow_rule_en+ + social_post_flow_rule_en+ )+++def build_a2ui_autonomy_instruction(language: str = "en") -> str:template_binding_rule_en = (" For repeated list/card data, use A2UI template binding correctly: ""Duplicate dataModelUpdate keys are invalid. Encode arrays as one "@@ -205,11 +290,6 @@ 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"}:@@ -235,15 +315,12 @@ 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)__all__ = ["build_a2ui_autonomy_instruction",+ "build_a2ui_browser_workflow_instruction",+ "is_a2ui_browser_workflow_request",]diff --git a/jiuwenswarm/server/runtime/a2ui/protocol.py b/jiuwenswarm/server/runtime/a2ui/protocol.pyindex f53afe248c..e8fab57405 100644--- a/jiuwenswarm/server/runtime/a2ui/protocol.py+++ b/jiuwenswarm/server/runtime/a2ui/protocol.py@@ -20,7 +20,10 @@ from jiuwenswarm.server.runtime.a2ui.parser import (may_contain_a2ui_content,parse_a2ui_response,)-from jiuwenswarm.server.runtime.a2ui.prompt_instructions import build_a2ui_autonomy_instruction+from jiuwenswarm.server.runtime.a2ui.prompt_instructions import (+ build_a2ui_autonomy_instruction,+ build_a2ui_browser_workflow_instruction,+)from jiuwenswarm.server.runtime.a2ui.stream_guard import A2UIStreamGuardfrom jiuwenswarm.server.runtime.a2ui.text_formatter import format_for_text_channelfrom jiuwenswarm.server.runtime.a2ui.types import A2UIExample, A2UIResponsePart, A2UIValidationResult@@ -88,7 +91,12 @@ class A2UIProtocolSpec:def catalog(self):return self.schema_manager.get_selected_catalog()- def build_prompt(self, language: str = "en") -> str:+ def build_prompt(+ self,+ language: str = "en",+ *,+ include_browser_workflows: bool = False,+ ) -> str:if language in {"zh", "cn"}:role = ("JiuwenSwarm 支持可选的 A2UI 输出格式。当富交互界面适合当前回答时,"@@ -129,6 +137,8 @@ class A2UIProtocolSpec:)workflow = f"{workflow}\n\n{build_a2ui_autonomy_instruction(language)}"+ if include_browser_workflows:+ workflow = f"{workflow}\n\n{build_a2ui_browser_workflow_instruction()}"prompt = self.schema_manager.generate_system_prompt(role_description=role,workflow_description=workflow,@@ -229,8 +239,15 @@ def get_protocol_spec(version: str = A2UI_ACTIVE_PROTOCOL_VERSION) -> A2UIProtocreturn A2UIProtocolSpec(version)-def build_a2ui_prompt_section(language: str = "en") -> str:- return get_protocol_spec().build_prompt(language)+def build_a2ui_prompt_section(+ language: str = "en",+ *,+ include_browser_workflows: bool = False,+) -> str:+ return get_protocol_spec().build_prompt(+ language,+ include_browser_workflows=include_browser_workflows,+ )def format_a2ui_for_text_channel(content: str, version: str = VERSION_0_8) -> str:diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex 15168a13f5..bb9c590442 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -247,6 +247,55 @@ def _make_a2ui_pending_render_chunk(*, request_id: str, channel_id: str) -> Agen)+def _make_a2ui_final_chunk(+ *,+ request_id: str,+ channel_id: str,+ session_id: str,+ content: str,+) -> AgentResponseChunk:+ return AgentResponseChunk(+ request_id=request_id,+ channel_id=channel_id,+ payload={+ "event_type": "chat.final",+ "session_id": session_id,+ "content": content,+ },+ is_complete=False,+ )+++def _should_defer_a2ui_processing_status(+ *,+ suppress_a2ui_stream: bool,+ event_type: str,+ payload: dict[str, Any],+) -> bool:+ return (+ suppress_a2ui_stream+ and event_type == "chat.processing_status"+ and payload.get("is_processing") is False+ )+++def _normalize_nested_stream_chunk(+ chunk: AgentResponseChunk,+) -> AgentResponseChunk | None:+ """Keep the facade stream open until its post-processing has finished."""+ if not chunk.is_complete:+ return chunk+ payload = chunk.payload+ if payload is None:+ return None+ if isinstance(payload, dict):+ is_complete = payload.get("is_complete") is True+ has_event_type = bool(payload.get("event_type"))+ if is_complete and not has_event_type:+ return None+ return replace(chunk, is_complete=False)++def _extend_a2ui_stream_probe(previous: str, content: str) -> str:probe = f"{previous}{content}"if len(probe) <= _A2UI_STREAM_PROBE_WINDOW:@@ -265,7 +314,7 @@ def _looks_like_partial_a2ui_marker(value: Any) -> bool:if match is None:continuetoken = match.group(0)- if len(token) < 3:+ if len(token) < 2:continuerest = candidate[len(token):].strip()if rest and not any(marker.startswith(token + rest) for marker in _A2UI_STREAM_PARTIAL_MARKERS):@@ -320,7 +369,7 @@ def _a2ui_marker_start(value: Any) -> int | None:if match is None:continuetoken = match.group(0)- if len(token) < 3:+ if len(token) < 2:continuerest = candidate[len(token):].strip()if rest and not any(marker.startswith(token + rest) for marker in _A2UI_STREAM_PARTIAL_MARKERS):@@ -2359,6 +2408,10 @@ class JiuWenSwarm:)else:if isinstance(data, AgentResponseChunk):+ if suppress_a2ui_stream:+ data = _normalize_nested_stream_chunk(data)+ if data is None:+ continueif isinstance(data.payload, dict) and isinstance(data.payload.get("event_type"), str):et = str(data.payload.get("event_type"))should_record = et.startswith("chat.")@@ -2378,6 +2431,17 @@ class JiuWenSwarm: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 _should_defer_a2ui_processing_status(+ suppress_a2ui_stream=suppress_a2ui_stream,+ event_type=et,+ payload=data.payload,+ ):+ logger.info(+ "A2UI processing_status=false deferred until finalization: "+ "request_id=%s",+ rid,+ )+ continueif et == "chat.delta":final_answer_chunks.append(payload_content)if suppress_a2ui_stream or a2ui_split is not None:@@ -2478,6 +2542,17 @@ class JiuWenSwarm: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 _should_defer_a2ui_processing_status(+ suppress_a2ui_stream=suppress_a2ui_stream,+ event_type=et,+ payload=data,+ ):+ logger.info(+ "A2UI processing_status=false deferred until finalization: "+ "request_id=%s",+ rid,+ )+ continueif et == "chat.delta":final_answer_chunks.append(payload_content)if suppress_a2ui_stream or a2ui_split is not None:@@ -2618,11 +2693,11 @@ class JiuWenSwarm:)final_answer_content = finalized_assistant_messagefinal_answer_chunks = []- yield AgentResponseChunk(+ yield _make_a2ui_final_chunk(request_id=rid,channel_id=cid,- payload={"event_type": "chat.final", "content": finalized_assistant_message},- is_complete=False,+ session_id=session_id,+ content=finalized_assistant_message,)# cloud memory: after chat hookdiff --git a/jiuwenswarm/start_services.py b/jiuwenswarm/start_services.pyindex 35810d9a81..6e0d1e1eb5 100644--- a/jiuwenswarm/start_services.py+++ b/jiuwenswarm/start_services.py@@ -419,7 +419,12 @@ def _run_instance_with_pid(commands: list[tuple[str, list[str], Path]],processes: dict[str, subprocess.Popen[bytes]] = {}try:for cmd_name, cmd_args, cwd in commands:- processes[cmd_name] = _start_process(cmd_name, cmd_args, cwd)+ processes[cmd_name] = _start_process(+ cmd_name,+ cmd_args,+ cwd,+ ports=config.ports,+ )write_pid_file(config, os.getpid(), time.time())logging.info(f"[start_services] Instance '{config.name}' started")@@ -481,12 +486,27 @@ def _build_commands(mode: str, dotenv_path: Path | None = None) -> list[tuple[streturn commands-def _start_process(name: str, cmd: list[str], cwd: Path) -> subprocess.Popen[bytes]:+def _start_process(+ name: str,+ cmd: list[str],+ cwd: Path,+ *,+ ports: dict[str, int] | None = None,+) -> subprocess.Popen[bytes]:"""Start a single subprocess."""import jsonlogging.info(f"[start_services] starting {name}: {' '.join(cmd)} (cwd={cwd})")env = os.environ.copy()env["JIUWENSWARM_START_CMD"] = json.dumps(sys.argv[:])+ if ports:+ env.update(+ {+ "AGENT_SERVER_PORT": str(ports["agent_server"]),+ "WEB_PORT": str(ports["web"]),+ "GATEWAY_PORT": str(ports["gateway"]),+ "FRONTEND_PORT": str(ports["frontend"]),+ }+ )return subprocess.Popen(cmd, cwd=str(cwd), env=env)@@ -666,7 +686,10 @@ def _wait_for_services_ready(_print_port_banner(targets, ready)-def _run_processes(commands: list[tuple[str, list[str], Path]]) -> int:+def _run_processes(+ commands: list[tuple[str, list[str], Path]],+ ports: dict[str, int],+) -> int:"""Run processes and wait for them.Args:@@ -678,9 +701,9 @@ def _run_processes(commands: list[tuple[str, list[str], Path]]) -> int:processes: dict[str, subprocess.Popen[bytes]] = {}try:for name, cmd, cwd in commands:- processes[name] = _start_process(name, cmd, cwd)+ processes[name] = _start_process(name, cmd, cwd, ports=ports)- _wait_for_services_ready(_resolve_runtime_ports(), processes)+ _wait_for_services_ready(ports, processes)while True:for name, proc in processes.items():@@ -728,7 +751,7 @@ def _run(mode: str) -> int:if not commands:logging.info(f"[start_services] no commands to run for mode: {mode}")return 2- return _run_processes(commands)+ return _run_processes(commands, cmd.config.ports)def _action_list() -> int:@@ -1006,4 +1029,4 @@ def main() -> None:if __name__ == "__main__":- main()\ No newline at end of file+ main()diff --git a/tests/system_tests/test_a2ui_system_flow.py b/tests/system_tests/test_a2ui_system_flow.pyindex e59befba40..b9e9d4ac75 100644--- a/tests/system_tests/test_a2ui_system_flow.py+++ b/tests/system_tests/test_a2ui_system_flow.py@@ -50,7 +50,10 @@ async def test_a2ui_system_flow_accepts_event_and_valid_response(monkeypatch):monkeypatch.setenv("JIUWENSWARM_A2UI_ENABLED", "true")config = get_a2ui_config({"a2ui": {"enabled": True}})- prompt_section = build_a2ui_prompt_section("en")+ prompt_section = build_a2ui_prompt_section(+ "en",+ include_browser_workflows=True,+ )client_event = {"type": "a2ui.client_event","event": {diff --git a/tests/unit_tests/a2ui/test_integration_bridge.py b/tests/unit_tests/a2ui/test_integration_bridge.pyindex 599714af8c..33726a52ab 100644--- a/tests/unit_tests/a2ui/test_integration_bridge.py+++ b/tests/unit_tests/a2ui/test_integration_bridge.py@@ -210,6 +210,15 @@ def test_split_a2ui_stream_content_handles_partial_marker():assert split == ("现在为你展示结果。\n\n", "beg")+def test_split_a2ui_stream_content_suppresses_two_character_tag_prefix():+ """A tokenizer chunk containing only '<a' must not leak into visible text."""+ from jiuwenswarm.server.runtime.agent_adapter.interface import _split_a2ui_stream_content++ split = _split_a2ui_stream_content("", "现在为你展示结果。\n\n<a")++ assert split == ("现在为你展示结果。\n\n", "<a")++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@@ -218,6 +227,85 @@ def test_a2ui_pending_render_delta_stays_open():assert "</a2ui-json>" not in _A2UI_PENDING_RENDER_DELTA+def test_a2ui_repaired_final_chunk_keeps_session_binding():+ """The repaired final must replace the pending A2UI bubble in its session."""+ from jiuwenswarm.server.runtime.agent_adapter.interface import _make_a2ui_final_chunk++ chunk = _make_a2ui_final_chunk(+ request_id="req-a2ui",+ channel_id="web",+ session_id="sess-a2ui",+ content="<a2ui-json>[]</a2ui-json>",+ )++ assert chunk.payload == {+ "event_type": "chat.final",+ "session_id": "sess-a2ui",+ "content": "<a2ui-json>[]</a2ui-json>",+ }+++def test_a2ui_processing_false_waits_for_repaired_final():+ """A2UI finalization must finish before the frontend closes its stream."""+ from jiuwenswarm.server.runtime.agent_adapter.interface import (+ _should_defer_a2ui_processing_status,+ )++ payload = {+ "event_type": "chat.processing_status",+ "is_processing": False,+ }++ assert _should_defer_a2ui_processing_status(+ suppress_a2ui_stream=True,+ event_type="chat.processing_status",+ payload=payload,+ ) is True+ assert _should_defer_a2ui_processing_status(+ suppress_a2ui_stream=False,+ event_type="chat.processing_status",+ payload=payload,+ ) is False+++def test_nested_stream_completion_waits_for_facade_post_processing():+ """The adapter terminal must not close the wire before A2UI finalization."""+ from jiuwenswarm.common.schema.agent import AgentResponseChunk+ from jiuwenswarm.server.runtime.agent_adapter.interface import (+ _normalize_nested_stream_chunk,+ )++ terminal = AgentResponseChunk(+ request_id="req-a2ui",+ channel_id="web",+ payload=None,+ is_complete=True,+ )++ assert _normalize_nested_stream_chunk(terminal) is None+++def test_nested_terminal_event_remains_visible_without_closing_stream():+ """A meaningful terminal event is retained while the facade owns completion."""+ from jiuwenswarm.common.schema.agent import AgentResponseChunk+ from jiuwenswarm.server.runtime.agent_adapter.interface import (+ _normalize_nested_stream_chunk,+ )++ terminal_error = AgentResponseChunk(+ request_id="req-error",+ channel_id="web",+ payload={"event_type": "chat.error", "error": "failed"},+ is_complete=True,+ )++ normalized = _normalize_nested_stream_chunk(terminal_error)++ assert normalized is not None+ assert normalized.payload == terminal_error.payload+ assert normalized.is_complete is False++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 3b642bf1c1..d38e436a4a 100644--- a/tests/unit_tests/a2ui/test_prompt_instructions.py+++ b/tests/unit_tests/a2ui/test_prompt_instructions.py@@ -2,6 +2,8 @@from jiuwenswarm.server.runtime.a2ui.prompt_instructions import (build_a2ui_autonomy_instruction,+ build_a2ui_browser_workflow_instruction,+ is_a2ui_browser_workflow_request,)from jiuwenswarm.server.runtime.a2ui.runtime.prompt import (build_a2ui_client_event_prompt,@@ -23,8 +25,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 instruction+ assert "Mandatory A2UI account-action gate" not in instruction+ assert "browser_preflight_submit" not in instructiondef test_a2ui_prompt_discourages_nested_templates():@@ -35,7 +37,7 @@ def test_a2ui_prompt_discourages_nested_templates():def test_a2ui_prompt_defines_hotel_booking_actions():- instruction = build_a2ui_autonomy_instruction("en")+ instruction = build_a2ui_browser_workflow_instruction()assert "hotel_option_select" in instructionassert "continue_hotel_booking" in instruction@@ -62,7 +64,7 @@ def test_a2ui_zh_prompt_discourages_unsupported_popup_components():def test_a2ui_prompt_defines_gmail_and_social_actions():- instruction = build_a2ui_autonomy_instruction("en")+ instruction = build_a2ui_browser_workflow_instruction()assert "Mandatory A2UI account-action gate" in instructionassert "task_tool as a substitute" in instruction@@ -78,6 +80,36 @@ def test_a2ui_prompt_defines_gmail_and_social_actions():assert "social_post_cancel" in instruction+def test_a2ui_browser_workflow_detection_is_request_scoped():+ """Only real browser workflows and their A2UI events should match."""+ assert is_a2ui_browser_workflow_request("帮我预订北京的酒店")+ assert is_a2ui_browser_workflow_request("Search Gmail and draft replies")+ assert is_a2ui_browser_workflow_request(+ {+ "type": "a2ui.client_event",+ "event": {"userAction": {"name": "gmail_send_confirm"}},+ }+ )+ assert not is_a2ui_browser_workflow_request(+ "生成一个带有故宫图片的介绍故宫的A2UI卡片"+ )+ assert not is_a2ui_browser_workflow_request("生成一个酒店介绍 A2UI 卡片")+++def test_a2ui_prompt_adds_browser_rules_only_when_requested():+ """Generic cards stay concise while browser tasks retain workflow rules."""+ generic_prompt = build_a2ui_prompt_section("zh")+ browser_prompt = build_a2ui_prompt_section(+ "zh",+ include_browser_workflows=True,+ )++ assert "browser_preflight_submit" not in generic_prompt+ assert "Mandatory A2UI account-action gate" not in generic_prompt+ assert "browser_preflight_submit" in browser_prompt+ assert "Mandatory A2UI account-action gate" in browser_prompt++def test_a2ui_zh_prompt_section_is_readable():prompt = build_a2ui_prompt_section("zh")diff --git a/tests/unit_tests/a2ui/test_web_only_prompt_rail.py b/tests/unit_tests/a2ui/test_web_only_prompt_rail.pyindex 1968d09592..68738a73ee 100644--- a/tests/unit_tests/a2ui/test_web_only_prompt_rail.py+++ b/tests/unit_tests/a2ui/test_web_only_prompt_rail.py@@ -54,6 +54,102 @@ async def test_response_prompt_rail_keeps_a2ui_for_web_channel(monkeypatch):assert "response" in rail.system_prompt_builder.sectionsassert LocalSectionName.A2UI in rail.system_prompt_builder.sections+ content = rail.system_prompt_builder.sections[LocalSectionName.A2UI].content+ assert "browser_preflight_submit" not in content["en"]+++async def test_response_prompt_rail_scopes_browser_rules_to_browser_request(monkeypatch):+ """Browser A2UI flows remain available without polluting ordinary A2UI requests."""+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.a2ui.config.get_current_a2ui_config",+ lambda: A2UIConfig(enabled=True),+ )+ rail = ResponsePromptRail()+ rail.system_prompt_builder = _FakePromptBuilder()+ extra = {}++ await rail.before_invoke(+ SimpleNamespace(+ inputs=InvokeInputs(+ query="帮我搜索 Gmail 并起草需要回复的邮件",+ conversation_id="sess_browser",+ ),+ extra=extra,+ )+ )+ await rail.before_model_call(SimpleNamespace(inputs=SimpleNamespace(), extra=extra))++ content = rail.system_prompt_builder.sections[LocalSectionName.A2UI].content+ assert "browser_preflight_submit" in content["en"]+ assert "gmail_email_select" in content["en"]+ assert "social_post_confirm" in content["en"]+++async def test_response_prompt_rail_keeps_museum_card_prompt_generic(monkeypatch):+ """The reported museum-card request must not receive browser workflow rules."""+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.a2ui.config.get_current_a2ui_config",+ lambda: A2UIConfig(enabled=True),+ )+ rail = ResponsePromptRail()+ rail.system_prompt_builder = _FakePromptBuilder()+ extra = {}++ await rail.before_invoke(+ SimpleNamespace(+ inputs=InvokeInputs(+ query="生成一个带有故宫图片的介绍故宫的A2UI卡片",+ conversation_id="sess_museum",+ ),+ extra=extra,+ )+ )+ await rail.before_model_call(SimpleNamespace(inputs=SimpleNamespace(), extra=extra))++ content = rail.system_prompt_builder.sections[LocalSectionName.A2UI].content+ assert "browser_preflight_submit" not in content["cn"]+ assert "gmail_email_select" not in content["cn"]+++async def test_response_prompt_rail_logs_switch_and_injection_decision(+ monkeypatch,+):+ """Logs must expose the effective switch and injection state."""+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.a2ui.config.get_current_a2ui_config",+ lambda: A2UIConfig(enabled=False),+ )+ rail = ResponsePromptRail()+ rail.system_prompt_builder = _FakePromptBuilder()+ log_calls = []+ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.common.rails.response_prompt_rail.logger.info",+ lambda message, *args: log_calls.append((message, args)),+ )++ await rail.before_model_call(+ SimpleNamespace(+ inputs={+ "channel": "web",+ "request_id": "req-a2ui-log",+ "conversation_id": "sess-a2ui-log",+ }+ )+ )++ assert len(log_calls) == 1+ _, args = log_calls[0]+ assert args[:6] == (+ "req-a2ui-log",+ "sess-a2ui-log",+ "web",+ False,+ False,+ False,+ )@pytest.mark.asynciodiff --git a/tests/unit_tests/agentserver/test_system_prompt_restructure.py b/tests/unit_tests/agentserver/test_system_prompt_restructure.pyindex 41b72c0e02..82598775f4 100644--- a/tests/unit_tests/agentserver/test_system_prompt_restructure.py+++ b/tests/unit_tests/agentserver/test_system_prompt_restructure.py@@ -487,18 +487,12 @@ 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 prompt+ assert "browser_preflight_submit" not in prompt+ assert "hotel_option_select" not in prompt+ assert "gmail_email_select" not in prompt+ assert "social_post_draft_select" not in prompt+ assert "Mandatory Web A2UI account-action gate" not in prompt+ assert 'subagent_type` set to `"browser_agent"`' in promptassert "# Environment" in promptitems = await agent.prompt_attachment_manager.collect_for_session("sess1")diff --git a/tests/unit_tests/test_instance_manager.py b/tests/unit_tests/test_instance_manager.pyindex 9a2f1d0f75..0a5f9f06ec 100644--- a/tests/unit_tests/test_instance_manager.py+++ b/tests/unit_tests/test_instance_manager.py@@ -1336,7 +1336,7 @@ class TestStartServicesFallback:)monkeypatch.setattr("jiuwenswarm.start_services._run_processes",- lambda commands: 0,+ lambda commands, ports: 0,)rc = start_services._run("app")diff --git a/tests/unit_tests/test_start_services_ready_hint.py b/tests/unit_tests/test_start_services_ready_hint.pyindex 43d8691eb0..c7fbbb43e1 100644--- a/tests/unit_tests/test_start_services_ready_hint.py+++ b/tests/unit_tests/test_start_services_ready_hint.py@@ -10,7 +10,11 @@ from unittest.mock import MagicMock, patchimport pytest-from jiuwenswarm.start_services import _resolve_runtime_ports, _wait_for_services_ready+from jiuwenswarm.start_services import (+ _resolve_runtime_ports,+ _start_process,+ _wait_for_services_ready,+)def _open_ports(*open_ports: int):@@ -78,6 +82,34 @@ def test_resolve_runtime_ports_out_of_range_env_keeps_default(assert ports["web"] == 19000+def test_start_process_passes_resolved_ports_to_child(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+):+ captured: dict[str, object] = {}++ def fake_popen(cmd, *, cwd, env):+ captured.update({"cmd": cmd, "cwd": cwd, "env": env})+ return MagicMock()++ monkeypatch.setattr("jiuwenswarm.start_services.subprocess.Popen", fake_popen)+ ports = {+ "agent_server": 19092,+ "web": 20000,+ "gateway": 20001,+ "frontend": 6173,+ }++ _start_process("web-dev", ["npm", "run", "dev"], tmp_path, ports=ports)++ child_env = captured["env"]+ assert isinstance(child_env, dict)+ assert child_env["AGENT_SERVER_PORT"] == "19092"+ assert child_env["WEB_PORT"] == "20000"+ assert child_env["GATEWAY_PORT"] == "20001"+ assert child_env["FRONTEND_PORT"] == "6173"++def test_wait_for_services_ready_prints_access_url_for_web_dev(caplog: pytest.LogCaptureFixture):frontend = MagicMock()frontend.poll.return_value = None