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(session): team模式3种mode统一处理

hwxiajing405f158c2244
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/mode.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/mode.ts
index e746e3ba02..fe834ac0f0 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/mode.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/mode.ts
@@ -83,10 +83,9 @@ export function createModeCommand(): SlashCommand {
return;
}
- // Check if leaving team mode with running tasks
+ // Check if switching mode with running team tasks
const currentMode = ctx.mode;
- const isLeavingTeamMode = isTeamMode(currentMode) && !isTeamMode(nextMode);
- if (isLeavingTeamMode && ctx.hasRunningTeamTasks?.()) {
+ if (currentMode !== nextMode && isTeamMode(currentMode) && ctx.hasRunningTeamTasks?.()) {
const answers = await ctx.askQuestions(
[
{
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/switch.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/switch.ts
index 2580e7b491..41163f3adb 100644
--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/switch.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/switch.ts
@@ -48,10 +48,9 @@ export function createSwitchCommand(): SlashCommand {
return;
}
- // Check if leaving team mode with running tasks
+ // Check if switching mode with running team tasks
const currentMode = ctx.mode;
- const isLeavingTeamMode = isTeamMode(currentMode) && !isTeamMode(requestedMode);
- if (isLeavingTeamMode && ctx.hasRunningTeamTasks?.()) {
+ if (currentMode !== requestedMode && isTeamMode(currentMode) && ctx.hasRunningTeamTasks?.()) {
const answers = await ctx.askQuestions(
[
{
diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
index 2e474c53e4..83ca90c54c 100644
--- a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
+++ b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts
@@ -2937,13 +2937,10 @@ export class AppScreen implements Component, Focusable {
// Check for mode switch when there's ongoing work
if (/^\/(?:mode|switch)\s/.test(text) && snapshot.cancellableWork) {
const currentMode = snapshot.mode;
- const isTeamMode = currentMode === "code.team" || currentMode === "team";
// Parse the target mode from the command
const modeMatch = text.match(/^\/(?:mode|switch)\s+(\S+)/);
const targetMode = modeMatch?.[1] ?? "";
- const targetIsTeamMode = targetMode === "code.team" || targetMode === "team";
- // Only warn when leaving team mode
- if (isTeamMode && !targetIsTeamMode) {
+ if (currentMode !== targetMode) {
const answers = await this.state.askQuestions(
[
{
diff --git a/jiuwenswarm/gateway/message_handler/command_parser/slash_command.py b/jiuwenswarm/gateway/message_handler/command_parser/slash_command.py
index ff3f298080..956825e2b3 100644
--- a/jiuwenswarm/gateway/message_handler/command_parser/slash_command.py
+++ b/jiuwenswarm/gateway/message_handler/command_parser/slash_command.py
@@ -352,7 +352,7 @@ FIRST_BATCH_REGISTRY: tuple[SlashCommandEntry, ...] = (
SlashCommandEntry(
id="mode",
canonical_text=f"{GatewaySlashCommand.MODE.value} agent|code|team|agent.plan|agent.fast|code.plan|"
- f"code.normal|code.team",
+ f"code.normal|code.team|team.plan",
scope="gateway",
req_method=None,
notes="受控通道切换模式:一级模式 agent/code/team(映射到默认子模式)或直达 agent.plan/agent.fast/code.plan/code.normal;"
diff --git a/jiuwenswarm/gateway/message_handler/message_handler.py b/jiuwenswarm/gateway/message_handler/message_handler.py
index 67920e39ca..1ea8496a8f 100644
--- a/jiuwenswarm/gateway/message_handler/message_handler.py
+++ b/jiuwenswarm/gateway/message_handler/message_handler.py
@@ -107,6 +107,12 @@ class ChannelMode(str, Enum):
CODE_NORMAL = "code.normal"
CODE_TEAM = "code.team"
TEAM = "team"
+ TEAM_PLAN = "team.plan"
+
+ @classmethod
+ def is_team_mode(cls, mode: str) -> bool:
+ """Return True if *mode* resolves to any team variant (case-insensitive)."""
+ return mode.strip().lower() in {cls.TEAM.value, cls.CODE_TEAM.value, cls.TEAM_PLAN.value}
@dataclass
@@ -337,7 +343,7 @@ class MessageHandler(ABC):
godview intent can resolve.
Trigger when:
- - params.mode == "team", or
+ - params.mode is a team variant (team / code.team / team.plan), or
- session already has subscribers (already a team session; web mode may be "agent")
"""
if not msg.session_id:
@@ -349,9 +355,9 @@ class MessageHandler(ABC):
if isinstance(msg.metadata, dict) and msg.metadata.get("member_name"):
return
_params = msg.params if isinstance(msg.params, dict) else {}
- _mode = str(_params.get("mode") or "").strip()
+ _mode = str(_params.get("mode") or "")
_session_has_subs = bool(self._session_sharing.lookup_all(msg.session_id))
- if not (_mode == "team" or _session_has_subs):
+ if not (ChannelMode.is_team_mode(_mode) or _session_has_subs):
return
godview_subs = self._session_sharing.lookup_member(msg.session_id, SubRole.GODVIEW)
_ch = msg.channel_id or "web"
@@ -451,7 +457,7 @@ class MessageHandler(ABC):
def _is_team_chat_send(msg: "Message") -> bool:
if not isinstance(msg.params, dict):
return False
- return str(msg.params.get("mode") or "").strip().lower() == "team"
+ return ChannelMode.is_team_mode(str(msg.params.get("mode") or ""))
@classmethod
def _is_interrupt_resume_chat_send(cls, msg: "Message") -> bool:
@@ -496,6 +502,7 @@ class MessageHandler(ABC):
"code.normal": ChannelMode.CODE_NORMAL,
"code.team": ChannelMode.CODE_TEAM,
"team": ChannelMode.TEAM,
+ "team.plan": ChannelMode.TEAM_PLAN,
}
mode = mode_map.get(mode_raw, ChannelMode.AGENT_PLAN)
return ChannelControlState(session_id=sid, mode=mode)
@@ -1294,6 +1301,7 @@ class MessageHandler(ABC):
"code.plan",
"code.normal",
"code.team",
+ "team.plan",
):
asyncio.create_task(
self.send_channel_notice(
@@ -1322,6 +1330,8 @@ class MessageHandler(ABC):
state.mode = ChannelMode.CODE_NORMAL
elif mode_str == "code.team":
state.mode = ChannelMode.CODE_TEAM
+ elif mode_str == "team.plan":
+ state.mode = ChannelMode.TEAM_PLAN
new_label = state.mode.value
if old_mode != state.mode:
asyncio.create_task(
diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.py
index e687e68b75..13722bc4e4 100644
--- a/jiuwenswarm/server/agent_ws_server.py
+++ b/jiuwenswarm/server/agent_ws_server.py
@@ -1957,6 +1957,40 @@ class AgentWebSocketServer:
session_id,
)
+ @staticmethod
+ def _is_stateless_method_request(request: AgentRequest) -> bool:
+ """skills / skilldev / plugins / symphony 为无状态 RPC,无需 mode 解析与 adapter.
+
+ 恢复 5084467df 引入、8f54b26a7 合入 team 时误删的短路判定。
+ """
+ return (
+ request.req_method is not None
+ and request.req_method.value.startswith(
+ ("skills.", "skilldev.", "plugins.", "symphony.")
+ )
+ )
+
+ async def _get_stateless_agent(self, channel_id: str) -> Any:
+ """为无状态请求取 agent,**不触发任何 mode 的 adapter 重建**.
+
+ 优先用 AgentManager 已缓存的 agent 模式 agent(get_agent_nowait 命中即返回,
+ 不命中返回 None,绝不创建);都没缓存时现场构造一个轻量 JiuWenSwarm()
+ (**不调 create_instance**,_adapter 保持 None)——其 process_message 内部对
+ skills/skilldev/plugins/symphony 的无状态短路会在 _ensure_adapter 之前 return,
+ 碰不到 adapter。真正的 adapter 重建留给 chat.send。
+
+ 相比 5084467df 原版用 get_agent(mode="agent") 作 fallback(会触发 agent 模式
+ adapter 重建,治标不治本),此处彻底解耦。JiuWenSwarm.__init__ 仅 4 个赋值 +
+ 一个只读目录的 SkillManager,现场 new 开销可忽略,无需额外缓存态。
+ """
+ cached = self._agent_manager.get_agent_nowait(
+ channel_id=channel_id, mode="agent"
+ )
+ if cached is not None:
+ return cached
+ from jiuwenswarm.server.runtime.agent_adapter.interface import JiuWenSwarm
+ return JiuWenSwarm() # 不调 create_instance,_adapter 保持 None
+
async def _prepare_code_mode_chat_turn(
self,
request: AgentRequest,
@@ -2109,6 +2143,23 @@ class AgentWebSocketServer:
await self._handle_acp_tool_response(ws, request, send_lock)
return
+ # 无状态请求(skills / skilldev / plugins / symphony)不需要 mode 解析和
+ # code mode 状态管理,直接走 process_message 即可。用轻量 agent 获取,不触发
+ # adapter 重建(恢复 8f54b26a7 误删的短路,并修正 5084467df 触发重建的缺陷)。
+ if self._is_stateless_method_request(request):
+ agent = await self._get_stateless_agent(channel_id)
+ resp = await agent.process_message(request)
+ if getattr(resp, "agent_ref", None) is None:
+ resp.agent_ref = request.agent_ref
+ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
+ async with send_lock:
+ await ws.send(json.dumps(wire, ensure_ascii=False))
+ logger.info(
+ "[AgentWebSocketServer] 非流式响应已发送: request_id=%s",
+ request.request_id,
+ )
+ return
+
mode, sub_mode, agent = await self._prepare_code_mode_chat_turn(
request, channel_id
)
@@ -2145,13 +2196,19 @@ class AgentWebSocketServer:
if current_task is not None:
self._session_stream_tasks[session_id] = current_task
- mode, sub_mode, agent = await self._prepare_code_mode_chat_turn(
- request, channel_id
- )
+ # 无状态流式请求(skills / skilldev / plugins / symphony)不需要 mode 解析和
+ # code mode 状态管理,直接走 process_message_stream 即可。用轻量 agent 获取,
+ # 不触发 adapter 重建(恢复 8f54b26a7 误删的短路,并修正 5084467df 触发重建的缺陷)。
+ if self._is_stateless_method_request(request):
+ agent = await self._get_stateless_agent(channel_id)
+ else:
+ mode, sub_mode, agent = await self._prepare_code_mode_chat_turn(
+ request, channel_id
+ )
- restored_plan = await self._ensure_code_mode_state(request, mode, sub_mode, agent)
- if restored_plan:
- await self._push_plan_mode_exited(request)
+ restored_plan = await self._ensure_code_mode_state(request, mode, sub_mode, agent)
+ if restored_plan:
+ await self._push_plan_mode_exited(request)
chunk_count = 0
# 心跳控制:当有真实 chunk 发送时重置,空闲时发送心跳
diff --git a/tests/unit_tests/gateway/test_message_handler_stream_cancel.py b/tests/unit_tests/gateway/test_message_handler_stream_cancel.py
index 8a5de20a31..cff879d4e5 100644
--- a/tests/unit_tests/gateway/test_message_handler_stream_cancel.py
+++ b/tests/unit_tests/gateway/test_message_handler_stream_cancel.py
@@ -12,7 +12,7 @@ import pytest
from jiuwenswarm.common.schema import Message
from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fields
from jiuwenswarm.common.schema.message import ReqMethod
-from jiuwenswarm.gateway.message_handler.message_handler import MessageHandler
+from jiuwenswarm.gateway.message_handler.message_handler import ChannelMode, MessageHandler
class _FakeAgentClient:
@@ -310,6 +310,12 @@ def test_team_chat_send_keeps_existing_team_stream() -> None:
assert not _should_cancel_existing_stream_before_chat_send(
_chat_send_message(channel_id="web", session_id="sess_team", mode="team"),
)
+ assert not _should_cancel_existing_stream_before_chat_send(
+ _chat_send_message(channel_id="web", session_id="sess_team", mode="code.team"),
+ )
+ assert not _should_cancel_existing_stream_before_chat_send(
+ _chat_send_message(channel_id="web", session_id="sess_team", mode="team.plan"),
+ )
assert _should_cancel_existing_stream_before_chat_send(
_chat_send_message(channel_id="web", session_id="sess_agent", mode="agent.plan"),
)
@@ -605,3 +611,40 @@ async def test_disconnect_backward_compatible_without_request_keys_kwarg() -> No
await asyncio.sleep(0)
assert len(_FakeAgentClient.sent_requests) == 1
+
+
+# ---------- ChannelMode.is_team_mode ----------
+
+
+ "mode,expected",
+ [
+ ("team", True),
+ ("code.team", True),
+ ("team.plan", True),
+ ("agent.plan", False),
+ ("agent.fast", False),
+ ("code.plan", False),
+ ("code.normal", False),
+ ("", False),
+ (" team ", True), # strip
+ ("Team", True), # case-insensitive
+ ],
+)
+def test_is_team_mode(mode: str, expected: bool) -> None:
+ assert ChannelMode.is_team_mode(mode) is expected
+
+
+ "mode,expected",
+ [
+ ("team", True),
+ ("code.team", True),
+ ("team.plan", True),
+ ("agent.plan", False),
+ ],
+)
+def test_is_team_chat_send_recognizes_all_team_modes(mode: str, expected: bool) -> None:
+ _is_team_chat_send = getattr(MessageHandler, "_is_team_chat_send")
+ msg = _chat_send_message(channel_id="web", session_id="sess", mode=mode)
+ assert _is_team_chat_send(msg) is expected