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: keep A2UI web-only while preserving web prompts
jack_ricky40ee1563aede
diff --git a/jiuwenswarm/agents/harness/common/rails/response_prompt_rail.py b/jiuwenswarm/agents/harness/common/rails/response_prompt_rail.pyindex 66d97759d2..b8495a8e23 100644--- a/jiuwenswarm/agents/harness/common/rails/response_prompt_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/response_prompt_rail.py@@ -28,6 +28,7 @@ class ResponsePromptRail(DeepAgentRail):def __init__(self) -> None:super().__init__()self.system_prompt_builder = None+ self._runtime_channel: str | None = Nonedef init(self, agent) -> None:self.system_prompt_builder = getattr(agent, "system_prompt_builder", None)@@ -37,6 +38,11 @@ class ResponsePromptRail(DeepAgentRail):self.system_prompt_builder.remove_section("response")self.system_prompt_builder.remove_section(LocalSectionName.A2UI)self.system_prompt_builder = None+ self._runtime_channel = None++ def set_channel(self, channel: str | None) -> None:+ value = str(channel or "").strip()+ self._runtime_channel = value or Noneasync def before_invoke(self, ctx: AgentCallbackContext) -> None:channel = self._resolve_channel(ctx)@@ -52,8 +58,7 @@ class ResponsePromptRail(DeepAgentRail):self.system_prompt_builder.add_section(_response_prompt(language))self._sync_a2ui_prompt_section(self._resolve_channel(ctx))- @staticmethod- def _resolve_channel(ctx: AgentCallbackContext) -> str | None:+ def _resolve_channel(self, ctx: AgentCallbackContext) -> str | None:"""Read the request channel from callback inputs when available."""inputs = getattr(ctx, "inputs", None)if isinstance(inputs, dict):@@ -71,15 +76,22 @@ class ResponsePromptRail(DeepAgentRail):if value is not None:return str(value)+ if self._runtime_channel is not None:+ return self._runtime_channel+conversation_id = (inputs.get("conversation_id")if isinstance(inputs, dict)else getattr(inputs, "conversation_id", None))if isinstance(conversation_id, str) and "_" in conversation_id:- return conversation_id.split("_", 1)[0]+ channel = conversation_id.split("_", 1)[0]+ if channel == "sess":+ return "web"+ if channel:+ return channel- return "web"+ return Nonedef _sync_a2ui_prompt_section(self, channel: str | None) -> None:"""Inject or remove the A2UI prompt section from runtime config."""diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.pyindex 151d49c8ad..096c139ae5 100644--- a/jiuwenswarm/server/agent_ws_server.py+++ b/jiuwenswarm/server/agent_ws_server.py@@ -130,6 +130,16 @@ _HISTORY_RESTORABLE_ASSISTANT_EVENT_TYPES = frozenset(})++def _request_query_text(request: AgentRequest) -> str:+ """Return text chat query only; structured events are handled downstream."""+ if not isinstance(request.params, dict):+ return ""+ query = request.params.get("query")+ if not isinstance(query, str):+ return ""+ return query.strip()+# System prompt for LLM-based agent generation_AGENT_CREATION_SYSTEM_PROMPT = """\You are an elite AI agent architect. When given an agent name and description, your job is to design a high-performance agent that EXECUTES tasks to completion — not just analyzes and reports.@@ -488,9 +498,7 @@ def _check_and_handle_pending_approval(return False# Read the user's response- user_msg = ""- if isinstance(request.params, dict):- user_msg = (request.params.get("query") or "").strip()+ user_msg = _request_query_text(request)if not user_msg:# Empty user message — keep pending state_pending_plan_approvals[session_id] = pending@@ -553,7 +561,7 @@ async def _try_handle_direct_plan_implement(return Falseif request.params.get(PLAN_USER_APPROVED_FLAG):return False- user_msg = (request.params.get("query") or "").strip()+ user_msg = _request_query_text(request)if not is_direct_plan_implement_request(user_msg):return Falsediff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex fb1417340b..b2a3876461 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -932,7 +932,7 @@ class JiuWenClawDeepAdapter:channel = session_id.split("_", 1)[0]if channel == "sess":return "web"- if channel in {"acp", "cron", "heartbeat", "feishu", "web", "dingtalk", "wecom"}:+ if channel in {"acp", "cron", "heartbeat", "feishu", "web", "dingtalk", "wecom", "tui"}:return channelreturn "web"@@ -3533,6 +3533,8 @@ class JiuWenClawDeepAdapter:)self._runtime_prompt_rail.set_model_name(self._resolve_model_name())self._runtime_prompt_rail.set_mode(runtime_config.mode)+ if self._response_prompt_rail:+ self._response_prompt_rail.set_channel(resolved_channel)circuit_breaker_rail = getattr(self, "_circuit_breaker_rail", None)if circuit_breaker_rail is not None:circuit_breaker_rail.set_language(resolved_language)@@ -5126,6 +5128,19 @@ class JiuWenClawDeepAdapter:agent=self._instance,)+ await self._update_runtime_config(+ self._RuntimeConfig(+ session_id=request.session_id,+ mode=mode,+ request_id=request.request_id,+ channel_id=request.channel_id,+ request_metadata=request.metadata,+ trusted_dirs=inputs.get("trusted_dirs"),+ cwd=inputs.get("cwd"),+ project_dir=inputs.get("project_dir"),+ )+ )+activate_response = request.params.get("activate_response")if isinstance(activate_response, dict):async for chunk in self._auto_harness_service.resume_activate(diff --git a/tests/unit_tests/a2ui/test_auto_harness_channel_context.py b/tests/unit_tests/a2ui/test_auto_harness_channel_context.pynew file mode 100644index 0000000000..280eabfc10--- /dev/null+++ b/tests/unit_tests/a2ui/test_auto_harness_channel_context.py@@ -0,0 +1,141 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++# pylint: disable=protected-access++from __future__ import annotations++import pytest++from jiuwenswarm.common.schema.agent import AgentRequest, AgentResponseChunk+from jiuwenswarm.server.runtime.agent_adapter.interface_deep import JiuWenClawDeepAdapter+++class _FakeAutoHarnessService:+ @staticmethod+ def is_activate_only_request(request, query) -> bool:+ return False++ @staticmethod+ def is_implement_only_request(request, query) -> bool:+ return False++ @staticmethod+ async def run(+ request,+ session_id,+ request_id,+ *,+ query="",+ model=None,+ auto_accept=False,+ ):+ yield AgentResponseChunk(+ request_id=request_id,+ channel_id=request.channel_id,+ payload={"event_type": "chat.final", "content": "done"},+ is_complete=False,+ )+++async def test_auto_harness_syncs_tui_channel_before_service(monkeypatch):+ """AutoHarness must preserve the TUI channel before downstream model rails run."""+ adapter = object.__new__(JiuWenClawDeepAdapter)+ adapter._instance = object()+ adapter._auto_harness_service = _FakeAutoHarnessService()+ adapter._stream_event_rail = None++ captured = {}++ async def capture_runtime_config(self, runtime_config):+ captured["channel_id"] = runtime_config.channel_id+ captured["mode"] = runtime_config.mode+ captured["session_id"] = runtime_config.session_id++ monkeypatch.setattr(+ JiuWenClawDeepAdapter,+ "_has_valid_model_config",+ lambda self, model: True,+ )+ monkeypatch.setattr(+ JiuWenClawDeepAdapter,+ "_resolve_model_for_request",+ lambda self, request: None,+ )+ monkeypatch.setattr(JiuWenClawDeepAdapter, "_update_runtime_config", capture_runtime_config)++ request = AgentRequest(+ request_id="req-auto-harness-tui",+ channel_id="tui",+ session_id="tui_session_1",+ params={"mode": "auto_harness", "query": "run swarmflow"},+ )++ chunks = []+ async for chunk in adapter.process_message_stream_impl(+ request,+ {"query": "run swarmflow", "conversation_id": "tui_session_1", "channel": "tui"},+ ):+ chunks.append(chunk)++ assert captured == {+ "channel_id": "tui",+ "mode": "auto_harness",+ "session_id": "tui_session_1",+ }+ assert chunks[0].payload == {"event_type": "chat.final", "content": "done"}+++def test_prompt_channel_resolver_keeps_tui_prefix_non_web():+ """Session-prefix fallback should recognize TUI as a non-Web channel."""+ assert JiuWenClawDeepAdapter._resolve_prompt_channel("tui_session_1") == "tui"+++async def test_runtime_config_syncs_channel_to_response_prompt_rail(monkeypatch):+ """Inner ReAct model-call rails need the adapter-resolved channel."""+ adapter = object.__new__(JiuWenClawDeepAdapter)+ adapter._instance = object()+ adapter._project_dir = None+ adapter._workspace_dir = "/tmp"+ adapter._runtime_prompt_rail = None+ adapter._circuit_breaker_rail = None++ captured = {}++ class _ResponseRail:+ @staticmethod+ def set_channel(channel):+ captured["channel"] = channel++ async def async_noop(*args, **kwargs):+ return None++ adapter._response_prompt_rail = _ResponseRail()++ monkeypatch.setattr(JiuWenClawDeepAdapter, "_seed_runtime_cwd", lambda self, cwd=None: None)+ monkeypatch.setattr(JiuWenClawDeepAdapter, "_resolve_runtime_language", lambda self: "cn")+ monkeypatch.setattr(JiuWenClawDeepAdapter, "_write_runtime_state", lambda self, **kwargs: None)+ monkeypatch.setattr(JiuWenClawDeepAdapter, "_update_rails_for_mode", async_noop)+ monkeypatch.setattr(JiuWenClawDeepAdapter, "_update_tools_for_mode", async_noop)+ monkeypatch.setattr(JiuWenClawDeepAdapter, "_update_session_tools", async_noop)+ monkeypatch.setattr(+ JiuWenClawDeepAdapter,+ "_refresh_acp_runtime_tools",+ lambda self, *args: None,+ )+ monkeypatch.setattr(+ JiuWenClawDeepAdapter,+ "_update_prompt_for_mode",+ lambda self, *args: None,+ )++ await adapter._update_runtime_config(+ JiuWenClawDeepAdapter._RuntimeConfig(+ session_id="sess_123",+ mode="agent.fast",+ channel_id="web",+ )+ )++ assert captured == {"channel": "web"}diff --git a/tests/unit_tests/a2ui/test_web_only_prompt_rail.py b/tests/unit_tests/a2ui/test_web_only_prompt_rail.pyindex 89052a5546..5a3321a200 100644--- a/tests/unit_tests/a2ui/test_web_only_prompt_rail.py+++ b/tests/unit_tests/a2ui/test_web_only_prompt_rail.py@@ -5,7 +5,7 @@ from __future__ import annotationsfrom types import SimpleNamespaceimport pytest-from openjiuwen.core.single_agent.rail.base import InvokeInputs+from openjiuwen.core.single_agent.rail.base import InvokeInputs, ModelCallInputsfrom jiuwenswarm.agents.harness.common.prompt.prompt_builder import LocalSectionNamefrom jiuwenswarm.agents.harness.common.rails.response_prompt_rail import ResponsePromptRail@@ -78,6 +78,58 @@ async def test_response_prompt_rail_keeps_web_channel_from_invoke_context(monkeyassert LocalSectionName.A2UI in rail.system_prompt_builder.sections+async def test_response_prompt_rail_maps_sess_prefix_to_web(monkeypatch):+ """Web sessions use sess_* ids and should still receive Web-only A2UI."""+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.a2ui.config.get_current_a2ui_config",+ lambda: A2UIConfig(enabled=True),+ )+ rail = ResponsePromptRail()+ rail.system_prompt_builder = _FakePromptBuilder()++ await rail.before_model_call(+ SimpleNamespace(inputs=InvokeInputs(query="generate an A2UI form", conversation_id="sess_123"))+ )++ assert "response" in rail.system_prompt_builder.sections+ assert LocalSectionName.A2UI in rail.system_prompt_builder.sections+++async def test_response_prompt_rail_uses_runtime_channel_for_model_call_inputs(monkeypatch):+ """Real ReAct model-call inputs need the adapter-synced runtime channel."""+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.a2ui.config.get_current_a2ui_config",+ lambda: A2UIConfig(enabled=True),+ )+ rail = ResponsePromptRail()+ rail.system_prompt_builder = _FakePromptBuilder()+ rail.set_channel("web")++ await rail.before_model_call(SimpleNamespace(inputs=ModelCallInputs()))++ assert "response" in rail.system_prompt_builder.sections+ assert LocalSectionName.A2UI in rail.system_prompt_builder.sections+++async def test_response_prompt_rail_keeps_tui_runtime_channel_disabled(monkeypatch):+ """Runtime channel sync must not make non-Web ReAct model calls A2UI-aware."""+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.a2ui.config.get_current_a2ui_config",+ lambda: A2UIConfig(enabled=True),+ )+ rail = ResponsePromptRail()+ rail.system_prompt_builder = _FakePromptBuilder()+ rail.set_channel("tui")++ await rail.before_model_call(SimpleNamespace(inputs=ModelCallInputs()))++ assert "response" in rail.system_prompt_builder.sections+ assert LocalSectionName.A2UI not in rail.system_prompt_builder.sections++@pytest.mark.asyncioasync def test_response_prompt_rail_keeps_non_web_bypass_from_invoke_context(monkeypatch):"""Non-Web channel inferred from conversation id should still bypass A2UI."""@@ -98,3 +150,39 @@ async def test_response_prompt_rail_keeps_non_web_bypass_from_invoke_context(monawait rail.before_model_call(SimpleNamespace(inputs=SimpleNamespace(), extra=extra))assert LocalSectionName.A2UI not in rail.system_prompt_builder.sections+++async def test_response_prompt_rail_does_not_default_missing_channel_to_web(monkeypatch):+ """Missing channel context should not silently enable Web-only A2UI."""+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.a2ui.config.get_current_a2ui_config",+ lambda: A2UIConfig(enabled=True),+ )+ rail = ResponsePromptRail()+ rail.system_prompt_builder = _FakePromptBuilder()++ await rail.before_model_call(+ SimpleNamespace(inputs=InvokeInputs(query="generate a report", conversation_id="session1"))+ )++ assert "response" in rail.system_prompt_builder.sections+ assert LocalSectionName.A2UI not in rail.system_prompt_builder.sections+++async def test_response_prompt_rail_does_not_inject_a2ui_for_tui_session_prefix(monkeypatch):+ """TUI sessions inferred from conversation id should bypass A2UI."""+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.a2ui.config.get_current_a2ui_config",+ lambda: A2UIConfig(enabled=True),+ )+ rail = ResponsePromptRail()+ rail.system_prompt_builder = _FakePromptBuilder()++ await rail.before_model_call(+ SimpleNamespace(inputs=InvokeInputs(query="generate a report", conversation_id="tui_session_1"))+ )++ assert "response" in rail.system_prompt_builder.sections+ assert LocalSectionName.A2UI not in rail.system_prompt_builder.sectionsdiff --git a/tests/unit_tests/agentserver/test_plan_approval.py b/tests/unit_tests/agentserver/test_plan_approval.pyindex 42a2de60fe..d2673ab17e 100644--- a/tests/unit_tests/agentserver/test_plan_approval.py+++ b/tests/unit_tests/agentserver/test_plan_approval.py@@ -130,3 +130,32 @@ def test_pending_approval_accepts_feedback_text() -> None:assert PLAN_USER_APPROVED_FLAG not in request.paramsassert "用户要求修订计划" in request.params["query"]assert "多添加几个边界测试用例" in request.params["query"]+++def test_pending_approval_ignores_structured_a2ui_event() -> None:+ session_id = "sess_a2ui_event"+ _pending_plan_approvals[session_id] = {+ "pending": True,+ "plan_content": "# Plan",+ "plan_slug": "test-plan",+ "plan_path": "/tmp/plan.md",+ }+ event = {+ "type": "a2ui.client_event",+ "event": {+ "userAction": {+ "name": "submitForm",+ "context": {"dietary": ["vegetarian"]},+ }+ },+ }+ request = AgentRequest(+ request_id="req_a2ui_event",+ channel_id="web",+ session_id=session_id,+ params={"query": event, "content": event, "mode": "agent.fast"},+ )++ assert _check_and_handle_pending_approval(request, language="cn") is False+ assert _pending_plan_approvals[session_id]["pending"] is True+ assert request.params["query"] is eventdiff --git a/tests/unit_tests/agentserver/test_plan_mode_orchestration.py b/tests/unit_tests/agentserver/test_plan_mode_orchestration.pyindex a5c2f46029..cd0f03ba4d 100644--- a/tests/unit_tests/agentserver/test_plan_mode_orchestration.py+++ b/tests/unit_tests/agentserver/test_plan_mode_orchestration.py@@ -264,6 +264,34 @@ async def test_direct_implement_reads_plan_file(tmp_path: Path) -> None:assert "Direct plan body" in request.params["query"]+async def test_direct_implement_ignores_structured_a2ui_event() -> None:+ event = {+ "type": "a2ui.client_event",+ "event": {+ "userAction": {+ "name": "submitForm",+ "context": {"dietary": ["vegetarian"]},+ }+ },+ }+ request = AgentRequest(+ request_id="req_a2ui_event",+ channel_id="web",+ session_id="sess_a2ui_event",+ params={"query": event, "content": event, "mode": "agent.fast"},+ )++ handled = await _try_handle_direct_plan_implement(+ request,+ MagicMock(),+ language="cn",+ )++ assert handled is False+ assert request.params["query"] is event++@pytest.mark.asyncioasync def test_reject_switch_mode_then_direct_implement_exits_plan(tmp_path: Path,