Skip to content

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): enable prompts in team web mode

jack_ricky26fa6f656ed0
diff --git a/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py b/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py
index 4c63a9bb4c..adc274e55e 100644
--- a/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py
+++ b/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py
@@ -174,8 +174,9 @@ def build_member_rails(
try:
rail = ResponsePromptRail()
+ rail.set_channel(channel)
rails_list.append(rail)
- logger.info("[TeamRuntime] ResponsePromptRail created")
+ logger.info("[TeamRuntime] ResponsePromptRail created: channel=%s", channel)
except Exception as exc:
logger.warning("[TeamRuntime] ResponsePromptRail failed: %s", exc)
diff --git a/jiuwenswarm/agents/swarm/providers/builtin_rails.py b/jiuwenswarm/agents/swarm/providers/builtin_rails.py
index 327b156809..61fe54042f 100644
--- a/jiuwenswarm/agents/swarm/providers/builtin_rails.py
+++ b/jiuwenswarm/agents/swarm/providers/builtin_rails.py
@@ -16,8 +16,12 @@ present before ``register_from_catalog`` runs.
from __future__ import annotations
+from typing import Any
+
from openjiuwen.agent_teams.harness.manifest import (
+ ConstructionInput,
ElementKind,
+ context_field,
harness_element,
)
@@ -34,12 +38,32 @@ RESPONSE_PROMPT = "swarm.response_prompt"
STREAM_EVENT = "swarm.stream_event"
AVATAR_PROMPT = "swarm.avatar_prompt"
-harness_element(
+
+class ResponsePromptInput(ConstructionInput):
+ """Construction inputs for the response-format prompt rail."""
+
+ channel: str = context_field(
+ attr="channel",
+ default="default",
+ description="Resolved channel key.",
+ )
+
+
+@harness_element(
kind=ElementKind.RAIL,
name=RESPONSE_PROMPT,
description="Appends the response-format prompt segment before each model call.",
- builder=ResponsePromptRail,
)
+def _build_response_prompt_rail(
+ params: dict[str, Any],
+ context: Any,
+) -> ResponsePromptRail:
+ inp = ResponsePromptInput.resolve(params, context)
+ rail = ResponsePromptRail()
+ rail.set_channel(inp.channel)
+ return rail
+
+
harness_element(
kind=ElementKind.RAIL,
name=STREAM_EVENT,
diff --git a/jiuwenswarm/channels/web/frontend/scripts/test-team-a2ui-render-path.mjs b/jiuwenswarm/channels/web/frontend/scripts/test-team-a2ui-render-path.mjs
new file mode 100644
index 0000000000..89fb9d11b8
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/scripts/test-team-a2ui-render-path.mjs
@@ -0,0 +1,65 @@
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+
+const root = new URL('..', import.meta.url);
+const sourceUrl = new URL('src/components/ChatPanel/MessageItem.tsx', root);
+const source = await readFile(sourceUrl, 'utf8');
+
+function between(sourceText, startMarker, endMarker) {
+ const start = sourceText.indexOf(startMarker);
+ assert.notEqual(start, -1, `${startMarker} should exist`);
+ const end = sourceText.indexOf(endMarker, start);
+ assert.notEqual(end, -1, `${endMarker} should exist after ${startMarker}`);
+ return sourceText.slice(start, end);
+}
+
+const teamLeaderRenderer = between(
+ source,
+ 'function TeamLeaderPlainTextMessage',
+ 'export function ContextCompressionLines',
+);
+
+assert.match(
+ teamLeaderRenderer,
+ /<A2UIMessageContent\b/,
+ 'team leader messages shown to users must use the A2UI-aware renderer',
+);
+assert.doesNotMatch(
+ teamLeaderRenderer,
+ /<MarkdownMessageBody\b/,
+ 'team leader messages shown to users must not render A2UI JSON as plain markdown',
+);
+assert.match(
+ teamLeaderRenderer,
+ /messageId=\{messageId\}/,
+ 'team leader A2UI renderer should receive a stable message id',
+);
+
+const teamEventBranch = between(
+ source,
+ "content.startsWith('team.event:')",
+ '// 检查是否为 team_leader 消息',
+);
+
+assert.match(
+ teamEventBranch,
+ /messageId=\{id\}/,
+ 'team.event user-facing messages should pass their message id to the team leader renderer',
+);
+
+const teamLeaderIdBranch = between(
+ source,
+ "const isTeamLeaderMsg = id && id.startsWith('team-leader-');",
+ '// 用户/助手消息',
+);
+
+assert.match(
+ teamLeaderIdBranch,
+ /messageId=\{id\}/,
+ 'team-leader messages should pass their message id to the team leader renderer',
+);
+assert.match(
+ teamLeaderIdBranch,
+ /isStreaming=\{isStreaming\}/,
+ 'streaming team-leader messages should forward streaming state to the A2UI renderer',
+);
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx
index aec99cdfb8..ce80c1578e 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageItem.tsx
@@ -77,11 +77,15 @@ export function TeamMemberMessageFrame({
function TeamLeaderPlainTextMessage({
member = 'team_leader',
content,
+ messageId,
+ isStreaming = false,
showAvatar = true,
fileItems,
}: {
member?: string;
content: string;
+ messageId: string;
+ isStreaming?: boolean;
showAvatar?: boolean;
fileItems?: FileDownloadItem[];
}) {
@@ -93,10 +97,14 @@ function TeamLeaderPlainTextMessage({
{fileItems && fileItems.length > 0 && (
<FileDownloadList files={fileItems} className="w-full md:w-1/2" />
)}
- <MarkdownMessageBody
- content={content}
- className="team-member-message__plain"
- />
+ <div className="team-member-message__plain">
+ <A2UIMessageContent
+ content={content}
+ messageId={messageId}
+ isStreaming={isStreaming}
+ testId="team-leader-message-body"
+ />
+ </div>
</TeamMemberMessageFrame>
);
}
@@ -392,6 +400,7 @@ export function MessageItem({
<TeamLeaderPlainTextMessage
member={event.fromMember}
content={event.content}
+ messageId={id}
showAvatar={showAvatar}
/>
);
@@ -452,6 +461,8 @@ export function MessageItem({
<TeamLeaderPlainTextMessage
member="team_leader"
content={messageContent || (isStreaming ? '正在接收中...' : '')}
+ messageId={id}
+ isStreaming={isStreaming}
showAvatar={showAvatar}
fileItems={fileItems}
/>
diff --git a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py
index 0f7984ce84..e4a903ea6b 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py
@@ -172,6 +172,42 @@ def _resolve_channel_id(channel_id: str | None) -> str:
return str(channel_id or "default").strip() or "default"
+def _resolve_request_language(request: Any) -> str:
+ metadata = getattr(request, "metadata", None)
+ params = getattr(request, "params", None)
+ sources = []
+ if isinstance(metadata, dict):
+ sources.append(metadata)
+ if isinstance(params, dict):
+ sources.append(params)
+
+ for source in sources:
+ for key in ("language", "preferred_language", "preferred_response_language"):
+ value = source.get(key)
+ if value:
+ return str(value).strip().lower() or "zh"
+ return "zh"
+
+
+def _safe_query_preview(query: Any, limit: int = 200) -> str:
+ if isinstance(query, str):
+ return query[:limit]
+ return str(query)[:limit]
+
+
+def _normalize_team_query(query: Any, *, channel_id: str | None, language: str) -> Any:
+ from jiuwenswarm.server.runtime.a2ui.integration import build_user_prompt_if_a2ui_event
+
+ a2ui_prompt = build_user_prompt_if_a2ui_event(
+ query,
+ channel=_resolve_channel_id(channel_id),
+ language=language,
+ )
+ if a2ui_prompt is not None:
+ return a2ui_prompt
+ return query
+
+
async def ensure_monitor_handlers_for_active_runtime(
channel_id: str | None,
session_id: str,
@@ -730,7 +766,12 @@ async def process_team_message_stream(
channel_id = request.channel_id
team_manager = get_team_manager(channel_id)
- query = inputs.get("query", "")
+ language = _resolve_request_language(request)
+ query = _normalize_team_query(
+ inputs.get("query", ""),
+ channel_id=channel_id,
+ language=language,
+ )
query_text = query if isinstance(query, str) else ""
try:
from jiuwenswarm.agents.harness.team.remote_member_bootstrap import (
@@ -929,7 +970,7 @@ async def process_team_message_stream(
_resolve_channel_id(channel_id),
session_id,
reason,
- query[:200],
+ _safe_query_preview(query),
)
error_msg = _INTERACT_REASON_ERROR_MAP.get(reason or "",
"Failed to send message, please try again later")
diff --git a/tests/agents/swarm/test_manifest_catalog.py b/tests/agents/swarm/test_manifest_catalog.py
index b0d52a9112..65b72e0821 100644
--- a/tests/agents/swarm/test_manifest_catalog.py
+++ b/tests/agents/swarm/test_manifest_catalog.py
@@ -10,7 +10,6 @@ introspection, and the unification of class rails with factory rails.
from __future__ import annotations
-import inspect
import json
import logging
@@ -22,6 +21,8 @@ from openjiuwen.agent_teams.schema.deep_agent_spec import RailSpec
from jiuwenswarm.agents.swarm import register_swarm_providers, registry
from jiuwenswarm.agents.swarm.context import SwarmBuildContext
+from jiuwenswarm.agents.harness.common.prompt.prompt_builder import LocalSectionName
+from jiuwenswarm.server.runtime.a2ui.config import A2UIConfig
from openjiuwen.agent_teams.harness.manifest import (
ElementKind,
HarnessElementDescriptor,
@@ -63,6 +64,18 @@ def _swarm_catalog() -> dict[str, HarnessElementDescriptor]:
}
+class _FakePromptBuilder:
+ def __init__(self) -> None:
+ self.language = "cn"
+ self.sections = {}
+
+ def add_section(self, section) -> None:
+ self.sections[section.name] = section
+
+ def remove_section(self, name: str) -> None:
+ self.sections.pop(name, None)
+
+
def test_every_registry_name_has_descriptor() -> None:
"""The catalog covers exactly the registry's ``swarm.*`` name constants."""
register_swarm_providers()
@@ -296,8 +309,13 @@ def test_catalog_covers_all_kinds_without_swarm_rail_types() -> None:
assert swarm_rails <= _swarm_keys(das._RAIL_PROVIDER_REGISTRY)
-def test_class_rail_builds_via_railspec() -> None:
- """A unified class rail resolves and builds through openjiuwen RailSpec.build."""
+async def test_response_prompt_rail_builds_via_railspec_with_channel(monkeypatch) -> None:
+ """The response rail provider should carry context channel into A2UI gating."""
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.a2ui.config.get_current_a2ui_config",
+ lambda: A2UIConfig(enabled=True),
+ )
register_swarm_providers()
ctx = SwarmBuildContext(language="cn", channel="web")
@@ -305,6 +323,9 @@ def test_class_rail_builds_via_railspec() -> None:
assert rail is not None
assert type(rail).__name__ == "ResponsePromptRail"
- assert inspect.isclass(
- resolve_factory(get_catalog()[registry.RESPONSE_PROMPT].factory_ref)
- )
+ builder = _FakePromptBuilder()
+ rail.init(type("Agent", (), {"system_prompt_builder": builder})())
+
+ await rail.before_model_call(type("Ctx", (), {"inputs": type("Inputs", (), {})()})())
+
+ assert LocalSectionName.A2UI in builder.sections
diff --git a/tests/unit_tests/agentserver/test_team_helpers.py b/tests/unit_tests/agentserver/test_team_helpers.py
index a1476e6c3a..ea2d3eea6f 100644
--- a/tests/unit_tests/agentserver/test_team_helpers.py
+++ b/tests/unit_tests/agentserver/test_team_helpers.py
@@ -1085,6 +1085,75 @@ async def test_process_team_message_stream_emits_processing_done_for_followup(mo
assert chunks[1].is_complete is True
+async def test_process_team_message_stream_converts_a2ui_followup_event(monkeypatch):
+ monkeypatch.setenv("JIUWENSWARM_A2UI_ENABLED", "true")
+
+ class _FakeManager:
+ interact_calls: list[tuple[str, str]] = []
+
+ @staticmethod
+ def has_stream_task(session_id: str) -> bool:
+ assert session_id == "sess-team-a2ui"
+ return True
+
+ @staticmethod
+ async def get_swarm_enriched_team_spec(**kwargs):
+ return SimpleNamespace(team_name="unit-team")
+
+ @classmethod
+ async def interact(cls, session_id: str, query: str):
+ cls.interact_calls.append((session_id, query))
+ return True, None
+
+ monkeypatch.setattr(team_helpers, "get_team_manager", lambda channel_id: _FakeManager())
+
+ request = SimpleNamespace(
+ session_id="sess-team-a2ui",
+ request_id="req-team-a2ui",
+ channel_id="web",
+ metadata={"language": "zh"},
+ params={"mode": "team"},
+ )
+ inputs = {
+ "query": {
+ "type": "a2ui.client_event",
+ "protocolVersion": "0.8",
+ "event": {
+ "userAction": {
+ "name": "submitDietForm",
+ "surfaceId": "diet-preferences",
+ "sourceComponentId": "submit-btn",
+ "context": {"name": "Codex", "dietType": ["balanced"]},
+ },
+ },
+ },
+ }
+
+ chunks = []
+ async for chunk in team_helpers.process_team_message_stream(
+ request,
+ inputs,
+ object(),
+ ):
+ chunks.append(chunk)
+
+ assert len(_FakeManager.interact_calls) == 1
+ session_id, prompt = _FakeManager.interact_calls[0]
+ assert session_id == "sess-team-a2ui"
+ assert isinstance(prompt, str)
+ assert "A2UI" in prompt
+ assert "submitDietForm" in prompt
+ assert "dietType" in prompt
+ assert chunks[0].payload == {
+ "event_type": "chat.processing_status",
+ "session_id": "sess-team-a2ui",
+ "is_processing": False,
+ "is_complete": True,
+ }
+ assert chunks[1].is_complete is True
+
+
@pytest.mark.anyio
async def test_process_team_message_stream_emits_processing_done_for_evolve_approval(monkeypatch):
approval_event = SimpleNamespace(
diff --git a/tests/unit_tests/agentserver/test_team_runtime_inheritance.py b/tests/unit_tests/agentserver/test_team_runtime_inheritance.py
index 513df3e5c8..5c335de955 100644
--- a/tests/unit_tests/agentserver/test_team_runtime_inheritance.py
+++ b/tests/unit_tests/agentserver/test_team_runtime_inheritance.py
@@ -19,6 +19,8 @@ from jiuwenswarm.agents.harness.team.team_runtime_inheritance import (
filter_inheritable_ability_cards,
resolve_model_config,
)
+from jiuwenswarm.agents.harness.common.prompt.prompt_builder import LocalSectionName
+from jiuwenswarm.server.runtime.a2ui.config import A2UIConfig
class _FakeAbilityManager:
@@ -29,6 +31,18 @@ class _FakeAbilityManager:
return list(self._abilities)
+class _FakePromptBuilder:
+ def __init__(self) -> None:
+ self.language = "cn"
+ self.sections = {}
+
+ def add_section(self, section) -> None:
+ self.sections[section.name] = section
+
+ def remove_section(self, name: str) -> None:
+ self.sections.pop(name, None)
+
+
def _make_tool_card(name: str) -> ToolCard:
return ToolCard(
id=name,
@@ -65,6 +79,28 @@ def test_filter_inheritable_ability_cards_includes_extended_swarm_tools():
assert "send_file_to_user" not in inherited_names
+async def test_build_member_rails_syncs_response_prompt_channel_for_a2ui(monkeypatch):
+ """Team Web model calls should inherit the runtime channel for A2UI prompts."""
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.a2ui.config.get_current_a2ui_config",
+ lambda: A2UIConfig(enabled=True),
+ )
+
+ rails = build_member_rails(
+ member_info=MemberInfo(role="leader"),
+ runtime=RuntimeInfo(channel="web", language="cn"),
+ )
+ response_rails = [rail for rail in rails if type(rail).__name__ == "ResponsePromptRail"]
+ assert len(response_rails) == 1
+
+ prompt_builder = _FakePromptBuilder()
+ response_rails[0].init(SimpleNamespace(system_prompt_builder=prompt_builder))
+ await response_rails[0].before_model_call(SimpleNamespace(inputs=SimpleNamespace()))
+
+ assert LocalSectionName.A2UI in prompt_builder.sections
+
+
# -- resolve_model_config tests --
def test_resolve_model_config_from_default():