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
[mirror] openJiuwen-ai/jiuwenswarm#512: fix (A2UI): support EN for A2UI hints
m056838700dff4afe9edd4
diff --git a/jiuwenswarm/agents/harness/common/tools/browser_start_client.py b/jiuwenswarm/agents/harness/common/tools/browser_start_client.pyindex 4ccb68b52c..0448e97f23 100644--- a/jiuwenswarm/agents/harness/common/tools/browser_start_client.py+++ b/jiuwenswarm/agents/harness/common/tools/browser_start_client.py@@ -27,11 +27,14 @@ import loggingimport osimport platformimport shutil+import socketimport subprocessimport sys+import timefrom pathlib import Pathfrom typing import Any+import psutilimport yamlfrom openjiuwen.harness.tools.browser_move.playwright_runtime.profiles import (BrowserProfile,@@ -218,6 +221,121 @@ def _creation_flags_for_windows() -> int:return flags+def _normalized_path(value: str) -> str:+ expanded = os.path.expandvars(os.path.expanduser((value or "").strip().strip('"')))+ return os.path.normcase(os.path.normpath(os.path.abspath(expanded)))+++def _cmdline_option(args: list[str], option: str) -> str:+ prefix = f"{option}="+ for index, arg in enumerate(args):+ if arg.startswith(prefix):+ return arg[len(prefix):]+ if arg == option and index + 1 < len(args):+ return args[index + 1]+ return ""+++def _find_existing_browser_processes(+ *, chrome_exec: str, port: int, user_data_dir: str+) -> list[Any]:+ """Find only Chrome processes belonging to this browser service."""+ expected_executable = _normalized_path(chrome_exec)+ expected_user_data_dir = _normalized_path(user_data_dir)+ matches: list[Any] = []+ for process in psutil.process_iter(["pid", "ppid", "exe", "cmdline"]):+ try:+ executable = str(process.info.get("exe") or "")+ args = [str(arg) for arg in (process.info.get("cmdline") or [])]+ if not executable:+ continue+ if _normalized_path(executable) != expected_executable:+ continue+ if _cmdline_option(args, "--remote-debugging-port") != str(port):+ continue++ actual_user_data_dir = _cmdline_option(args, "--user-data-dir")+ if not actual_user_data_dir:+ continue+ if _normalized_path(actual_user_data_dir) != expected_user_data_dir:+ continue++ matches.append(process)+ except (psutil.AccessDenied, psutil.NoSuchProcess, OSError):+ continue+ return matches+++def _port_is_open(host: str, port: int, *, timeout_s: float = 0.2) -> bool:+ connect_host = "127.0.0.1" if host in {"", "0.0.0.0", "::"} else host+ try:+ with socket.create_connection((connect_host, port), timeout=timeout_s):+ return True+ except OSError:+ return False+++def _stop_existing_browser_service(+ *,+ chrome_exec: str,+ host: str,+ port: int,+ user_data_dir: str,+ timeout_s: float = 5.0,+) -> list[int]:+ matches = _find_existing_browser_processes(+ chrome_exec=chrome_exec,+ port=port,+ user_data_dir=user_data_dir,+ )+ if not matches:+ return []++ matched_pids = {process.pid for process in matches}+ roots = [+ process+ for process in matches+ if int(process.info.get("ppid") or 0) not in matched_pids+ ] or matches+ targets: dict[int, Any] = {process.pid: process for process in matches}+ for root in roots:+ try:+ targets.update({child.pid: child for child in root.children(recursive=True)})+ except (psutil.AccessDenied, psutil.NoSuchProcess):+ pass++ processes = list(targets.values())+ for process in processes:+ try:+ process.terminate()+ except psutil.NoSuchProcess:+ pass+ _, alive = psutil.wait_procs(processes, timeout=timeout_s)+ for process in alive:+ try:+ process.kill()+ except psutil.NoSuchProcess:+ pass+ if alive:+ _, alive = psutil.wait_procs(alive, timeout=2.0)+ if alive:+ remaining = ", ".join(str(process.pid) for process in alive)+ raise RuntimeError(f"Could not stop existing browser service processes: {remaining}")++ deadline = time.monotonic() + timeout_s+ while _port_is_open(host, port) and time.monotonic() < deadline:+ time.sleep(0.1)+ if _port_is_open(host, port):+ raise RuntimeError(f"Browser service port {host}:{port} did not close after restart")++ stopped_pids = sorted(targets)+ logger.info(+ "Stopped existing browser service before restart: "+ f"pids={stopped_pids}, host={host}, port={port}"+ )+ return stopped_pids++def start_browser(*, dry_run: bool = False, config_file: str = "") -> int:browser_cfg = _load_browser_config(config_file)os_name = _os_key()@@ -286,6 +404,18 @@ def start_browser(*, dry_run: bool = False, config_file: str = "") -> int:logger.info(" ".join(args))return 0+ _stop_existing_browser_service(+ chrome_exec=chrome_exec,+ host=host,+ port=port,+ user_data_dir=user_data_dir,+ )+ if _port_is_open(host, port):+ raise RuntimeError(+ f"Browser service port {host}:{port} is occupied by an unrecognized process. "+ "Stop that process or choose another remote_debugging_port."+ )+logger.info("Launching browser process with remote debugging enabled: "f"command={args}"diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIErrorBoundary.tsx b/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIErrorBoundary.tsxindex ac1ea5f84e..9fdc3ee3bc 100644--- a/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIErrorBoundary.tsx+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIErrorBoundary.tsx@@ -5,7 +5,7 @@ import { a2uiError } from './formDefaults';interface A2UIErrorBoundaryProps {children: ReactNode;- fallback?: ReactNode;+ fallback: ReactNode;onError?: (error: Error, errorInfo: ErrorInfo) => void;resetKey?: string;}@@ -45,20 +45,7 @@ export class A2UIErrorBoundary extends Component<render() {if (this.state.hasError) {- if (this.props.fallback) {- return this.props.fallback;- }-- return (- <div className="a2ui-error-boundary p-4 border border-danger/30 rounded-lg bg-danger/5">- <p className="text-danger text-sm font-medium mb-1">- 界面内容暂时无法显示- </p>- <p className="text-text-muted text-xs">- 请稍后重试或重新生成结果- </p>- </div>- );+ return this.props.fallback;}return this.props.children;diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIMessageContent.tsx b/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIMessageContent.tsxindex bc365642a6..812cb4bcef 100644--- a/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIMessageContent.tsx+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/A2UIMessageContent.tsx@@ -2,6 +2,7 @@import { useEffect, useMemo, memo } from 'react';import { useA2UIActions } from '@a2ui/react';+import { useTranslation } from 'react-i18next';import { MarkdownRenderer } from '../../components/MarkdownRenderer';import {extractA2UISurfaceIds,@@ -54,6 +55,7 @@ export const A2UIMessageContent = memo(function A2UIMessageContent({testId,}: A2UIMessageContentProps) {const { processMessages } = useA2UIActions();+ const { t } = useTranslation();const namespace = useMemo(() => `msg_${safeNamespace(messageId)}`, [messageId]);const a2uiEnabled = isA2UIFeatureEnabled();@@ -61,6 +63,8 @@ export const A2UIMessageContent = memo(function A2UIMessageContent({const parsed = parseA2UIContent(content, {enabled: a2uiEnabled,isStreaming,+ pendingText: t('a2ui.generating'),+ invalidText: t('a2ui.unavailable'),});return parsed.map((part, index) => {if (part.kind === 'text') {@@ -82,7 +86,7 @@ export const A2UIMessageContent = memo(function A2UIMessageContent({resetKey,};});- }, [a2uiEnabled, content, isStreaming, namespace, messageId]);+ }, [a2uiEnabled, content, isStreaming, namespace, messageId, t]);useEffect(() => {for (const part of renderParts) {@@ -169,7 +173,7 @@ export const A2UIMessageContent = memo(function A2UIMessageContent({if (!Renderer) {return (<div key={part.key} className="text-sm text-danger">- Unsupported A2UI protocol version: {part.protocolVersion}+ {t('a2ui.unsupportedProtocol', { version: part.protocolVersion })}</div>);}@@ -180,6 +184,16 @@ export const A2UIMessageContent = memo(function A2UIMessageContent({<A2UIErrorBoundarykey={`${surfaceId}:${part.resetKey}`}resetKey={part.resetKey}+ fallback={(+ <div className="a2ui-error-boundary p-4 border border-danger/30 rounded-lg bg-danger/5">+ <p className="text-danger text-sm font-medium mb-1">+ {t('a2ui.unavailableTitle')}+ </p>+ <p className="text-text-muted text-xs">+ {t('a2ui.retry')}+ </p>+ </div>+ )}>{disableInteraction ? (<div className="pointer-events-none opacity-75">diff --git a/jiuwenswarm/channels/web/frontend/src/features/a2ui/a2uiContent.ts b/jiuwenswarm/channels/web/frontend/src/features/a2ui/a2uiContent.tsindex ef3b56b1a5..beaa146b9c 100644--- a/jiuwenswarm/channels/web/frontend/src/features/a2ui/a2uiContent.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/a2ui/a2uiContent.ts@@ -27,8 +27,13 @@ export type A2UIContentPart =interface ParseA2UIContentOptions {enabled?: boolean;isStreaming?: boolean;+ pendingText?: string;+ invalidText?: string;}+const DEFAULT_PENDING_TEXT = 'A2UI interface is being generated...';+const DEFAULT_INVALID_TEXT = 'The interface cannot be displayed right now. Please try again later.';+function isRecord(value: unknown): value is Record<string, unknown> {return typeof value === 'object' && value !== null && !Array.isArray(value);}@@ -154,10 +159,10 @@ function makeA2UIPart(messages: ServerToClientMessage[]): A2UIContentPart {};}-function invalidA2UIFallback(): A2UIContentPart {+function invalidA2UIFallback(text = DEFAULT_INVALID_TEXT): A2UIContentPart {return {kind: 'text',- text: '界面内容暂时无法显示,请稍后重试或重新生成结果。',+ text,};}@@ -205,10 +210,10 @@ function extractTextFromMalformedA2UI(content: string): string | null {return null;}-function pendingA2UIFallback(): A2UIContentPart {+function pendingA2UIFallback(text = DEFAULT_PENDING_TEXT): A2UIContentPart {return {kind: 'text',- text: 'A2UI 界面生成中...',+ text,};}@@ -272,7 +277,11 @@ export function parseA2UIContent(const bodyStart = openIndex + A2UI_OPEN_TAG.length;const closeIndex = content.indexOf(A2UI_CLOSE_TAG, bodyStart);if (closeIndex < 0) {- parts.push(options.isStreaming ? pendingA2UIFallback() : invalidA2UIFallback());+ parts.push(+ options.isStreaming+ ? pendingA2UIFallback(options.pendingText)+ : invalidA2UIFallback(options.invalidText)+ );break;}@@ -286,7 +295,7 @@ export function parseA2UIContent(if (extractedText) {parts.push({ kind: 'text', text: extractedText });} else {- parts.push(invalidA2UIFallback());+ parts.push(invalidA2UIFallback(options.invalidText));}}cursor = closeIndex + A2UI_CLOSE_TAG.length;diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex a890565395..5d9b062d16 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -15,6 +15,13 @@"modify": "Modify","delete": "Delete"},+ "a2ui": {+ "generating": "Generating A2UI interface...",+ "unavailable": "The interface cannot be displayed right now. Please try again or regenerate the result.",+ "unavailableTitle": "The interface cannot be displayed right now",+ "retry": "Please try again later or regenerate the result",+ "unsupportedProtocol": "Unsupported A2UI protocol version: {{version}}"+ },"nav": {"chat": "Chat","work": "Work",diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex eb30a58462..a6f3109438 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -15,6 +15,13 @@"modify": "修改","delete": "删除"},+ "a2ui": {+ "generating": "A2UI 界面生成中...",+ "unavailable": "界面内容暂时无法显示,请稍后重试或重新生成结果。",+ "unavailableTitle": "界面内容暂时无法显示",+ "retry": "请稍后重试或重新生成结果",+ "unsupportedProtocol": "不支持的 A2UI 协议版本:{{version}}"+ },"nav": {"chat": "对话","work": "工作",diff --git a/tests/unit_tests/test_browser_start_client.py b/tests/unit_tests/test_browser_start_client.pynew file mode 100644index 0000000000..27ddc143b4--- /dev/null+++ b/tests/unit_tests/test_browser_start_client.py@@ -0,0 +1,132 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++from types import SimpleNamespace++import pytest++from jiuwenswarm.agents.harness.common.tools import browser_start_client+++class _FakeProcess:+ def __init__(self, pid: int, ppid: int, executable: str, args: list[str]) -> None:+ self.pid = pid+ self.info = {"pid": pid, "ppid": ppid, "exe": executable, "cmdline": args}+++def test_process_discovery_requires_matching_executable_port_and_profile(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+) -> None:+ chrome = str(tmp_path / "chrome.exe")+ profile = str(tmp_path / "profile")+ processes = [+ _FakeProcess(+ 10,+ 1,+ chrome,+ [chrome, "--remote-debugging-port=9222", f"--user-data-dir={profile}"],+ ),+ _FakeProcess(+ 11,+ 1,+ chrome,+ [+ chrome,+ "--remote-debugging-port=9222",+ f"--user-data-dir={tmp_path / 'other'}",+ ],+ ),+ _FakeProcess(+ 12,+ 1,+ chrome,+ [chrome, "--remote-debugging-port=9333", f"--user-data-dir={profile}"],+ ),+ _FakeProcess(+ 13,+ 1,+ str(tmp_path / "python.exe"),+ ["python.exe", "--remote-debugging-port=9222", f"--user-data-dir={profile}"],+ ),+ ]+ monkeypatch.setattr(browser_start_client.psutil, "process_iter", lambda _attrs: processes)++ result = browser_start_client._find_existing_browser_processes(+ chrome_exec=chrome,+ port=9222,+ user_data_dir=profile,+ )++ assert [process.pid for process in result] == [10]+++ ("headless", "expected_headless_arg"),+ [(False, False), (True, True)],+)+def test_start_browser_restarts_with_current_headless_setting(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+ headless: bool,+ expected_headless_arg: bool,+) -> None:+ chrome = str(tmp_path / "chrome.exe")+ profile = str(tmp_path / "profile")+ events: list[object] = []+ monkeypatch.setattr(+ browser_start_client,+ "_load_browser_config",+ lambda _path: {+ "chrome_path": chrome,+ "remote_debugging_address": "127.0.0.1",+ "remote_debugging_port": 9222,+ "user_data_dir": profile,+ "profile_directory": "Default",+ "headless": headless,+ },+ )+ monkeypatch.setattr(browser_start_client, "_os_key", lambda: "windows")+ monkeypatch.setattr(browser_start_client, "_normalize_chrome_executable", lambda *_: chrome)+ monkeypatch.setattr(browser_start_client, "_parse_cdp_from_env", lambda host, port: (host, port))+ monkeypatch.setattr(+ browser_start_client,+ "_stop_existing_browser_service",+ lambda **kwargs: events.append(("stop", kwargs)) or [123],+ )+ monkeypatch.setattr(browser_start_client, "_port_is_open", lambda *_, **__: False)+ monkeypatch.setattr(browser_start_client, "_persist_browser_profile", lambda **_: None)++ def fake_popen(args, **kwargs):+ events.append(("popen", args, kwargs))+ return SimpleNamespace(pid=456)++ monkeypatch.setattr(browser_start_client.subprocess, "Popen", fake_popen)++ assert browser_start_client.start_browser(config_file="config.yaml") == 0+ assert events[0][0] == "stop"+ assert ("--headless=new" in events[1][1]) is expected_headless_arg+++def test_start_browser_refuses_unrecognized_port_owner(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+) -> None:+ chrome = str(tmp_path / "chrome.exe")+ monkeypatch.setattr(+ browser_start_client,+ "_load_browser_config",+ lambda _path: {"chrome_path": chrome, "headless": False},+ )+ monkeypatch.setattr(browser_start_client, "_os_key", lambda: "windows")+ monkeypatch.setattr(browser_start_client, "_normalize_chrome_executable", lambda *_: chrome)+ monkeypatch.setattr(browser_start_client, "_parse_cdp_from_env", lambda host, port: (host, port))+ monkeypatch.setattr(browser_start_client, "_stop_existing_browser_service", lambda **_: [])+ monkeypatch.setattr(browser_start_client, "_port_is_open", lambda *_, **__: True)+ monkeypatch.setattr(+ browser_start_client.subprocess,+ "Popen",+ lambda *_, **__: pytest.fail("Popen must not run for an unknown port owner"),+ )++ with pytest.raises(RuntimeError, match="occupied by an unrecognized process"):+ browser_start_client.start_browser(config_file="config.yaml")