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
feat(team): implement same-session online play
chensheng123458f54b26a7ac8
diff --git a/docs/zh/SUMMARY.md b/docs/zh/SUMMARY.mdindex 25d4c99c6d..68d87a03ef 100644--- a/docs/zh/SUMMARY.md+++ b/docs/zh/SUMMARY.md@@ -33,12 +33,9 @@- [上下文压缩卸载](上下文压缩卸载.md)- [编码记忆](编码记忆.md)- [技能系统](技能.md)-<<<<<<< HEAD- [技能交响乐:技能检索、编排与分发](symphony-技能编排与分发.md)-=======- [Agentic 技能检索](Agentic技能检索.md)- [Team Skills 团队技能](TeamSkills.md)->>>>>>> c84a5249 (doc: team skills 文档)- [Skill 自演进](Skill自演进.md)- [智能体与工作区](智能体.md)- [会话管理](会话.md)diff --git a/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py b/jiuwenswarm/agents/harness/common/prompt/prompt_builder.pyindex e0907b0c35..63a7d63f5e 100644--- a/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py+++ b/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py@@ -254,6 +254,11 @@ def _identity_prompt(- 用户询问生成的文件如何获取**调用方式**:使用文件的绝对路径作为参数调用 `send_file_to_user` 工具。++**跨 channel 投递**:`send_file_to_user` 接受可选参数 `target_channels`(字符串数组),用于指定文件投递的目标 channel(如 `["feishu", "xiaoyi", "web"]`)。+- 用户在某个 channel(如飞书)请求发送文件、或要求把文件发给指定 channel 时,传入 `target_channels`。+- 省略 `target_channels` 时,文件会自动投递给当前会话已接入的所有用户 channel(team 模式下含飞书等 IM 端)。+- 文件路径必须是服务端可访问的绝对路径。"""else:content = f"""@@ -327,6 +332,11 @@ When the `send_file_to_user` tool is available in your tool list, you **must** p- User asks how to obtain generated files**How to call**: Use the absolute file path(s) as the parameter to invoke the `send_file_to_user` tool.++**Cross-channel delivery**: `send_file_to_user` accepts an optional `target_channels` parameter (array of strings) to specify delivery targets by channel id (e.g. `["feishu", "xiaoyi", "web"]`).+- When a user on a given channel (e.g. Feishu) requests a file, or asks to send a file to a specific channel, pass `target_channels`.+- When `target_channels` is omitted, the file is auto-delivered to every user channel joined to the current session (including IM endpoints like Feishu in team mode).+- File paths must be absolute and server-accessible."""return PromptSection(name="identity",diff --git a/jiuwenswarm/agents/harness/common/tools/send_file_to_user.py b/jiuwenswarm/agents/harness/common/tools/send_file_to_user.pyindex 3f9c3aebe0..ed147b59d4 100644--- a/jiuwenswarm/agents/harness/common/tools/send_file_to_user.py+++ b/jiuwenswarm/agents/harness/common/tools/send_file_to_user.py@@ -76,15 +76,57 @@ class SendFileToolkit:bool(self._request_metadata),)- async def send_file(self, abs_file_path_list: Union[List[str], str]) -> str:+ @staticmethod+ def _normalize_target_channels(target_channels: Any) -> list[str]:+ """Normalize target_channels into a list of non-empty strings.++ Accepts a single string, a JSON array string, or a native list.+ Returns [] when absent/empty.+ """+ if target_channels is None:+ return []+ if isinstance(target_channels, str):+ stripped = target_channels.strip()+ if not stripped:+ return []+ try:+ parsed = json.loads(stripped)+ if isinstance(parsed, list):+ return [str(x).strip() for x in parsed if str(x).strip()]+ if isinstance(parsed, str):+ return [parsed.strip()] if parsed.strip() else []+ return [stripped]+ except (TypeError, ValueError):+ return [stripped]+ if isinstance(target_channels, (list, tuple)):+ return [str(x).strip() for x in target_channels if str(x).strip()]+ return [str(target_channels).strip()]++ async def send_file(+ self,+ abs_file_path_list: Union[List[str], str],+ target_channels: Union[List[str], str, None] = None,+ ) -> str:"""Send files to user.Args:abs_file_path_list: List of absolute file paths to send.+ target_channels: Optional explicit delivery targets. Each item is+ a channel id (e.g. "feishu", "web") or a team human-agent+ seat name (the member_name used in /join). When omitted the+ Gateway auto-routes the file to all channels joined to the+ session (team mode). When provided, the file is delivered+ only to the specified targets.Returns:Success message or error description."""+ target_channel_list = SendFileToolkit._normalize_target_channels(target_channels)+ if target_channel_list:+ logger.info(+ "[SendFileToolkit] send_file target_channels=%s session_id=%s",+ target_channel_list, self.session_id,+ )if isinstance(abs_file_path_list, str):try:parsed = json.loads(abs_file_path_list)@@ -187,8 +229,16 @@ class SendFileToolkit:},"is_complete": False,}+ # 合并 metadata:原始 request metadata + 文件投递目标提示。+ # send_file_targets 由 Gateway 的 dispatch 层解析为 fan_out_targets,+ # 使文件可跨 channel 投递到 team 会话已接入的 channel(如飞书)。+ merged_meta: dict[str, Any] = {}if self._request_metadata:- msg["metadata"] = dict(self._request_metadata)+ merged_meta.update(self._request_metadata)+ if target_channel_list:+ merged_meta["send_file_targets"] = list(target_channel_list)+ if merged_meta:+ msg["metadata"] = merged_metaawait server.send_push(msg)result_parts = [f"成功发送 {len(valid_files)} 个文件"]if missing_files:@@ -230,8 +280,11 @@ class SendFileToolkit:description=("【文件发送工具】当需要将生成的文件、导出的数据、创建的文档等发送给用户时使用此工具。""使用场景包括:用户请求导出/下载文件、任务完成后需要交付文件、生成报告/文档后发送给用户。"- "参数格式:接受单个路径字符串或路径数组,路径必须是绝对路径。"- "示例:'/tmp/report.pdf' 或 ['/tmp/file1.csv', '/tmp/file2.xlsx']"+ "参数格式:abs_file_path_list 接受单个路径字符串或路径数组,路径必须是绝对路径。"+ "示例:'/tmp/report.pdf' 或 ['/tmp/file1.csv', '/tmp/file2.xlsx']。"+ "target_channels 可选:指定文件投递的目标 channel(如 ['feishu', 'xiaoyi', 'web'])。"+ "省略时自动投递给当前会话已接入的所有用户 channel(team 模式下含飞书等 IM 端)。"+ "当用户在某个 channel(如飞书)请求文件、或要求把文件发给指定 channel 时,应显式传入 target_channels。"),input_params={"type": "object",@@ -244,7 +297,17 @@ class SendFileToolkit:"或 JSON 数组字符串如 '[\"/path/file1.csv\", \"/path/file2.xlsx\"]'。""支持任意文件类型(pdf、xlsx、docx、png、zip等)。"),- }+ },+ "target_channels": {+ "type": "array",+ "items": {"type": "string"},+ "description": (+ "可选:文件投递目标 channel 或 team 成员席位名列表,"+ "如 [\"feishu\"] 或 [\"xiaoyi\"]。"+ "省略时自动投递给当前会话已接入的所有用户 channel。"+ "当需跨 channel 投递(如 web 会话中把文件发给飞书用户)时传入此项。"+ ),+ },},"required": ["abs_file_path_list"],},diff --git a/jiuwenswarm/agents/harness/team/handlers/team_monitor_handler.py b/jiuwenswarm/agents/harness/team/handlers/team_monitor_handler.pyindex 4031519f06..aa0fa08e13 100644--- a/jiuwenswarm/agents/harness/team/handlers/team_monitor_handler.py+++ b/jiuwenswarm/agents/harness/team/handlers/team_monitor_handler.py@@ -57,9 +57,19 @@ class TeamMonitorHandler(BaseMonitorHandler):# Event conversion# ------------------------------------------------------------------- @staticmethod- def _handle_member_spawned(base: dict[str, Any], event: MonitorEvent) -> dict[str, Any]:+ async def _handle_member_spawned(self, base: dict[str, Any], event: MonitorEvent) -> dict[str, Any]:base["member_id"] = event.member_name+ # 获取成员 role:human_agent → mode="human",其他保留原 mode+ try:+ member_info = await self._monitor.get_member(event.member_name or "")+ if member_info is not None:+ base["mode"] = "human" if member_info.role == "human_agent" else member_info.role+ except Exception as e:+ logger.warning(+ "[TeamMonitorHandler] 获取成员 role 失败: member=%s, error=%s",+ event.member_name,+ e,+ )return base@staticmethod@@ -255,7 +265,10 @@ class TeamMonitorHandler(BaseMonitorHandler):"name": m.display_name,"status": m.status,"execution_status": m.execution_status,+ # MemberMode: build_mode/plan_mode(控制是否需要 leader 审批)"mode": m.mode,+ # role 字段:区分人类/AI(human_agent/teammate/leader)+ "role": m.role,}for m in members],@@ -281,3 +294,39 @@ class TeamMonitorHandler(BaseMonitorHandler):)return None+ async def get_member_list(self) -> list[dict[str, Any]] | None:+ """仅查询成员列表(不含 tasks)。++ ``get_team_snapshot`` 把 members 与 tasks 绑在同一个 try 里,一旦+ ``get_tasks()`` 抛错(如 team 任务表尚未建表/迁移,``no such table``),+ 整个 snapshot 返回 None,连 members 一起丢失。/join 成员校验只需要+ members,不依赖 tasks,故提供此窄方法做降级:tasks 取不到不影响+ 成员名校验。字段形状与 ``get_team_snapshot`` 的 members 项保持一致。+ """+ if self._monitor is None:+ return None+ try:+ members = await self._monitor.get_members()+ team_info = await self._monitor.get_team_info()+ leader_name = team_info.leader_member_name if team_info else None+ if leader_name:+ members = [m for m in members if m.member_name != leader_name]+ return [+ {+ "member_id": m.member_name,+ "name": m.display_name,+ "status": m.status,+ "execution_status": m.execution_status,+ "mode": m.mode,+ "role": m.role,+ }+ for m in members+ ]+ except Exception as e:+ logger.warning(+ "[TeamMonitorHandler] get_member_list failed: session_id=%s, error=%s",+ self._session_id,+ e,+ )+ return None+diff --git a/jiuwenswarm/agents/harness/team/team_manager.py b/jiuwenswarm/agents/harness/team/team_manager.pyindex ba5117aaf9..191797088a 100644--- a/jiuwenswarm/agents/harness/team/team_manager.py+++ b/jiuwenswarm/agents/harness/team/team_manager.py@@ -217,6 +217,16 @@ class TeamManager:self._active_pause_tasks: dict[str, asyncio.Task] = {}self._active_team_names: dict[str, str] = {}self._pending_team_names: dict[str, str] = {}+ # session_id → list of (request_id, asyncio.Queue) waiters+ self._pending_waiters: dict[str, list[tuple[str, asyncio.Queue]]] = {}+ # session_id → cron team round completion state. Lifetime-coupled to+ # _pending_waiters: set by _try_finish_cron_team_stream, popped by the+ # finisher coroutines once the cron stream ends.+ self._cron_team_completion: dict[str, dict[str, Any]] = {}+ # Sessions that have successfully initialized a team runtime at least once.+ # Persists across stream lifecycles so follow-up requests are not+ # misidentified as first requests.+ self._initialized_sessions: set[str] = set()# session_id → TeamSkillEvolutionRail instance (set by customizer, used for drain/approval)self._team_skill_rails: dict[str, Any] = {}# session_id → member SkillEvolutionRail instances@@ -242,6 +252,65 @@ class TeamManager:def pop_stream_task(self, session_id: str) -> asyncio.Task | None:return self._stream_tasks.pop(session_id, None)+ def is_session_initialized(self, session_id: str) -> bool:+ """Return whether the session has ever initialized a team runtime."""+ return session_id in self._initialized_sessions++ def clear_session_initialized(self, session_id: str) -> None:+ """Clear the initialized marker for a session (e.g. on stream end)."""+ self._initialized_sessions.discard(session_id)++ def has_waiters(self, session_id: str) -> bool:+ """Return whether there are pending waiters for the given session."""+ return bool(self._pending_waiters.get(session_id))++ def add_waiter(self, session_id: str, request_id: str, queue: asyncio.Queue) -> None:+ """Register a waiter queue for a session's event stream."""+ self._pending_waiters.setdefault(session_id, []).append((request_id, queue))++ def remove_waiter(self, session_id: str, request_id: str) -> None:+ """Remove a waiter by request_id; clean up empty lists."""+ waiters = self._pending_waiters.get(session_id)+ if waiters is None:+ return+ remaining = [(rid, q) for rid, q in waiters if rid != request_id]+ if remaining:+ self._pending_waiters[session_id] = remaining+ else:+ self._pending_waiters.pop(session_id, None)++ def broadcast_event(self, session_id: str, event: dict[str, Any]) -> None:+ """Broadcast an event to all request queues waiting on the same session."""+ waiters = self._pending_waiters.get(session_id)+ if waiters:+ for request_id, queue in waiters:+ try:+ queue.put_nowait(dict(event))+ except Exception:+ logger.debug(+ "[TeamManager] broadcast failed: session_id=%s request_id=%s",+ session_id,+ request_id,+ )++ def get_waiters(self, session_id: str) -> list[tuple[str, asyncio.Queue]]:+ """Return the (request_id, queue) pairs waiting on the given session."""+ return self._pending_waiters.get(session_id, [])++ def get_cron_completion(self, session_id: str) -> dict[str, Any] | None:+ """Return the cron team round completion state for the session, if any."""+ return self._cron_team_completion.get(session_id)++ def setdefault_cron_completion(+ self, session_id: str, default: dict[str, Any]+ ) -> dict[str, Any]:+ """Get or create the cron team round completion state for the session."""+ return self._cron_team_completion.setdefault(session_id, default)++ def pop_cron_completion(self, session_id: str) -> dict[str, Any] | None:+ """Drop the cron team round completion state for the session."""+ return self._cron_team_completion.pop(session_id, None)+def is_runtime_active(self, session_id: str) -> bool:"""Return whether a Runner-owned runtime is active for the session."""return session_id in self._active_team_names@@ -629,6 +698,7 @@ class TeamManager:def commit_runtime_ready(self, session_id: str, team_name: str) -> None:self._active_team_names[session_id] = team_nameself._pending_team_names.pop(session_id, None)+ self._initialized_sessions.add(session_id)logger.info("[TeamManager] commit_runtime_ready session_id=%s team_name=%s active=%s pending=%s",session_id,@@ -903,6 +973,7 @@ class TeamManager:try:logger.info("[TeamManager] creating TeamAgent from spec")team_agent = spec.build()+ team_agent.channel_id = channel_id # 记录 channel,供 _destroy_other_sessions 按 channel 隔离self._team_agents[session_id] = team_agent# After build, initialize team shared skill links.self.ensure_team_shared_skills_ready_for_session(session_id, spec)@@ -975,7 +1046,7 @@ class TeamManager:if team_agent is not None:return team_agent- await self._destroy_other_sessions(session_id)+ await self._destroy_other_sessions(session_id, channel_id)return await self.create_team(session_id,deep_agent,@@ -1208,9 +1279,18 @@ class TeamManager:async with self._bootstrap_lock:return await self._destroy_team(session_id)- async def _destroy_other_sessions(self, current_session_id: str) -> None:- """Destroy stale distributed bootstrap TeamAgents on session switch."""- stale_session_ids = [sid for sid in list(self._team_agents.keys()) if sid != current_session_id]+ async def _destroy_other_sessions(self, current_session_id: str, channel_id: str | None = None) -> None:+ """Destroy stale distributed bootstrap TeamAgents on session switch.++ 按 channel_id 过滤:singleton 模式下多个 channel 共享同一个 TeamManager,+ 只销毁同 channel 的旧 session,不影响其他 channel 正在运行的 team 实例。+ """+ stale_session_ids = []+ for sid, agent in self._team_agents.items():+ if sid != current_session_id and (+ channel_id is None or getattr(agent, 'channel_id', None) == channel_id+ ):+ stale_session_ids.append(sid)for stale_session_id in stale_session_ids:await self._destroy_team(stale_session_id)@@ -1999,62 +2079,55 @@ class TeamManager:)-_team_managers: dict[str, TeamManager] = {}+# Singleton TeamManager: all channels share one instance. Team runtime state+# (_stream_tasks / _initialized_sessions / _active_team_names /+# _pending_waiters / _cron_team_completion / rails / watchers) is indexed by+# session_id and is per-session, never per-channel. Sharing the instance lets a+# bridged follow-up request (e.g. a /join member replying from feishu while the+# originating web stream is still+# alive) see the originating channel's runtime markers so it is correctly+# routed through interact() instead of being misidentified as a first request+# and colliding with the Runner team pool.+_team_manager: TeamManager | None = Nonedef get_team_manager(channel_id: str | None = None) -> TeamManager:- resolved_channel_id = str(channel_id or "default").strip() or "default"- manager = _team_managers.get(resolved_channel_id)- if manager is None:- manager = TeamManager()- _team_managers[resolved_channel_id] = manager- return manager+ """Return the singleton TeamManager instance (channel_id is ignored)."""+ global _team_manager+ if _team_manager is None:+ _team_manager = TeamManager()+ return _team_managerdef find_team_skill_rail_across_managers(request_id: str) -> Any | None:- """Find the TeamSkillEvolutionRail that owns a pending request across all channel managers."""- for manager in _team_managers.values():- rail = manager.find_team_skill_rail_for_request(request_id)- if rail is not None:- return rail- return None+ """Find the TeamSkillEvolutionRail that owns a pending request."""+ return get_team_manager().find_team_skill_rail_for_request(request_id)def refresh_team_shared_skill_links_across_managers(session_id: str | None = None) -> bool:- """Refresh team shared skill links across channel managers."""- refreshed = 0- for manager in _team_managers.values():- if session_id is None:- refreshed += manager.refresh_all_team_shared_skill_links()- elif manager.refresh_team_shared_skill_links(session_id):- refreshed += 1- return refreshed > 0+ """Refresh team shared skill links on the singleton manager."""+ tm = get_team_manager()+ if session_id is None:+ return tm.refresh_all_team_shared_skill_links() > 0+ return tm.refresh_team_shared_skill_links(session_id)async def cancel_all_team_stream_tasks_across_managers(reason: str = "") -> None:- """Cancel team stream tasks for all channel managers."""- for manager in list(_team_managers.values()):- await manager.cancel_all_stream_tasks(reason=reason)+ """Cancel all team stream tasks on the singleton manager."""+ await get_team_manager().cancel_all_stream_tasks(reason=reason)async def stop_team_session_runtime_across_managers(session_id: str, reason: str = "") -> bool:- """Stop a team session runtime across all channel managers."""- stopped = False- for manager in list(_team_managers.values()):- manager_stopped = await manager.stop_session_runtime(session_id, reason=reason)- stopped = manager_stopped or stopped- return stopped+ """Stop a team session runtime on the singleton manager."""+ return await get_team_manager().stop_session_runtime(session_id, reason=reason)def get_all_team_managers() -> list[TeamManager]:- """Return a snapshot of all channel-scoped team managers."""- return list(_team_managers.values())+ """Return the singleton manager wrapped in a list (callers iterate this)."""+ return [get_team_manager()]def reset_team_manager(channel_id: str | None = None) -> None:- if channel_id is None:- _team_managers.clear()- return-- resolved_channel_id = str(channel_id).strip() or "default"- _team_managers.pop(resolved_channel_id, None)+ """Reset the singleton TeamManager (channel_id is ignored)."""+ global _team_manager+ _team_manager = Nonediff --git a/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py b/jiuwenswarm/agents/harness/team/team_runtime_inheritance.pyindex 4e03f2eed0..ce6811661d 100644--- a/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py+++ b/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py@@ -343,8 +343,16 @@ def build_member_rails(rails_list.append(evo_rail)# Context compression rail for all members (leader + teammates).+ # ``config`` here is the full config.yaml mapping (hot-reload path passes+ # ``get_config()``); strip the ``react`` outer key so the rail builder sees+ # the same ``{"context_engine_config": ...}`` shape the swarm provider path+ # passes (see member_rails._build_context_processor).if get_context_engine_enabled(config):- rail = _build_context_processor_rail(config)+ react = config.get("react", {}) if isinstance(config, dict) else {}+ react = react if isinstance(react, dict) else {}+ rail = _build_context_processor_rail(+ {"context_engine_config": react.get("context_engine_config", {})}+ )if rail is not None:rails_list.append(rail)@@ -567,9 +575,17 @@ def get_context_engine_enabled(config: dict[str, Any] | None) -> bool:def _build_context_processor_rail(config: dict[str, Any] | None) -> ContextProcessorRail | None:"""Build a preset ContextProcessorRail for team members with user config thresholds.- Mirrors the logic in interface_deep._build_context_processor_rail:- reads processor configs from react.context_engine_config and passes- them as (name, dict) pairs to ContextProcessorRail.+ Expects a pre-extracted mapping of shape ``{"context_engine_config": {...}}`` —+ the ``react`` outer key must already be stripped by the caller. Both call sites+ pass this shape:++ * ``build_member_rails`` (hot-reload path, full config source) extracts+ ``react.context_engine_config`` before calling;+ * ``member_rails._build_context_processor`` (swarm provider) bakes the+ section into ``ContextProcessorInput`` at spec-build time.++ Mirrors :func:`interface_deep._build_context_processor_rail`, which takes the+ same shape (the ``react`` section itself)."""try:from typing import List, Tuple@@ -577,11 +593,8 @@ def _build_context_processor_rail(config: dict[str, Any] | None) -> ContextProceuser_processors: List[Tuple[str, dict]] = []ctx_cfg: dict[str, Any] = {}if isinstance(config, dict):- react = config.get("react", {})- if isinstance(react, dict):- ctx_cfg = react.get("context_engine_config", {})- if not isinstance(ctx_cfg, dict):- ctx_cfg = {}+ raw = config.get("context_engine_config", {})+ ctx_cfg = raw if isinstance(raw, dict) else {}offloader_cfg = ctx_cfg.get("message_summary_offloader_config", {})if isinstance(offloader_cfg, dict) and offloader_cfg:diff --git a/jiuwenswarm/agents/swarm/config_specs.py b/jiuwenswarm/agents/swarm/config_specs.pyindex 35287612df..ac3d565e45 100644--- a/jiuwenswarm/agents/swarm/config_specs.py+++ b/jiuwenswarm/agents/swarm/config_specs.py@@ -275,10 +275,16 @@ def _acp_enabled(config: dict[str, Any]) -> bool:def _context_processor_params(config: dict[str, Any]) -> dict[str, Any]:- """Attribute params for the context-compression rail."""+ """Attribute params for the context-compression rail.++ ``context_engine_config`` lives under ``react`` in config.yaml; reading it+ at the top level returned ``{}``, leaving the rail with an empty config and+ no compressors mounted.+ """+ react = _config_section(config, "react")return {"context_engine_enabled": get_context_engine_enabled(config),- "context_engine_config": _config_section(config, "context_engine_config"),+ "context_engine_config": _config_section(react, "context_engine_config"),}diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsxindex 3e233b1073..ddacdb3748 100644--- a/jiuwenswarm/channels/web/frontend/src/App.tsx+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx@@ -105,6 +105,7 @@ function clearTeamRuntimeState(): void {sessionStore.setTeamMemberExecutionEvents([]);sessionStore.clearAllTeamMemberContextCompressionStatus();sessionStore.setTeamHistoryMessages([]);+ sessionStore.setTeamHumanShareCommands([]);}// 错误边界组件diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChannelsPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChannelsPanel/index.tsxindex f863a2ccac..fe8f13c2e3 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChannelsPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChannelsPanel/index.tsx@@ -1,5 +1,6 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';+import { ChevronRight, Plus, Trash2 } from 'lucide-react';import { webRequest } from '../../services/webClient';import { AvatarPermEditor } from './AvatarPermEditor';import { WechatQrModal } from './WechatQrModal';@@ -55,6 +56,8 @@ type FeishuConfig = {};type FeishuDraft = {+ name: string;+ is_default: boolean;enabled: boolean;enable_streaming: boolean;app_id: string;@@ -69,6 +72,13 @@ type FeishuDraft = {enable_memory: boolean;};+type FeishuAppConfig = FeishuConfig & {+ name: string;+ is_default: boolean;+};++type FeishuAppDraft = FeishuDraft;+type XiaoyiConfig = {enabled: boolean;ak: string;@@ -79,6 +89,8 @@ type XiaoyiConfig = {};type XiaoyiDraft = {+ name: string;+ is_default: boolean;enabled: boolean;ak: string;sk: string;@@ -87,6 +99,13 @@ type XiaoyiDraft = {enable_streaming: boolean;};+type XiaoyiAppConfig = XiaoyiConfig & {+ name: string;+ is_default: boolean;+};++type XiaoyiAppDraft = XiaoyiDraft;+type DingTalkConfig = {enabled: boolean;client_id: string;@@ -355,6 +374,8 @@ function normalizeFeishuConfig(input: unknown): FeishuConfig {function draftFromFeishuConfig(conf: FeishuConfig): FeishuDraft {return {+ name: '',+ is_default: true,enabled: conf.enabled,enable_streaming: conf.enable_streaming,app_id: conf.app_id,@@ -394,6 +415,49 @@ function buildFeishuPayload(draft: FeishuDraft): Record<string, unknown> {};}+function sortFeishuApps(apps: FeishuAppConfig[]): FeishuAppConfig[] {+ return [...apps].sort((a, b) => a.name.localeCompare(b.name, 'zh-Hans-CN'));+}++function normalizeFeishuAppConfig(input: unknown, fallbackName = '未命名飞书应用', isDefault = false): FeishuAppConfig {+ const base = normalizeFeishuConfig(input);+ const data = input && typeof input === 'object' ? (input as Record<string, unknown>) : {};+ return {+ ...base,+ name: String(data.name ?? fallbackName).trim() || fallbackName,+ is_default: data.is_default === undefined ? isDefault : Boolean(data.is_default),+ };+}++function normalizeFeishuAppsConfig(input: unknown): FeishuAppConfig[] {+ if (input && typeof input === 'object') {+ const data = input as Record<string, unknown>;+ if (Array.isArray(data.apps)) {+ const apps = data.apps.map((item, idx) => normalizeFeishuAppConfig(item, `飞书应用 ${idx + 1}`, idx === 0));+ return sortFeishuApps(apps.length > 0 ? apps : [normalizeFeishuAppConfig(DEFAULT_FEISHU_CONF, '默认飞书应用', true)]);+ }+ }+ return sortFeishuApps([normalizeFeishuAppConfig(input, '默认飞书应用', true)]);+}++function draftFromFeishuAppConfig(conf: FeishuAppConfig): FeishuAppDraft {+ return {+ ...draftFromFeishuConfig(conf),+ name: conf.name,+ is_default: conf.is_default,+ };+}++function buildFeishuAppConfig(draft: FeishuAppDraft): FeishuAppConfig {+ const payload = buildFeishuPayload(draft);+ return {+ ...DEFAULT_FEISHU_CONF,+ ...(payload as FeishuConfig),+ name: draft.name.trim() || '未命名飞书应用',+ is_default: draft.is_default,+ };+}+function normalizeXiaoyiConfig(input: unknown): XiaoyiConfig {if (!input || typeof input !== 'object') {return DEFAULT_XIAOYI_CONF;@@ -411,6 +475,8 @@ function normalizeXiaoyiConfig(input: unknown): XiaoyiConfig {function draftFromXiaoyiConfig(conf: XiaoyiConfig): XiaoyiDraft {return {+ name: '',+ is_default: true,enabled: conf.enabled,ak: conf.ak,sk: conf.sk,@@ -431,6 +497,49 @@ function buildXiaoyiPayload(draft: XiaoyiDraft): Record<string, unknown> {};}+function sortXiaoyiApps(apps: XiaoyiAppConfig[]): XiaoyiAppConfig[] {+ return [...apps].sort((a, b) => a.name.localeCompare(b.name, 'zh-Hans-CN'));+}++function normalizeXiaoyiAppConfig(input: unknown, fallbackName = '未命名小艺应用', isDefault = false): XiaoyiAppConfig {+ const base = normalizeXiaoyiConfig(input);+ const data = input && typeof input === 'object' ? (input as Record<string, unknown>) : {};+ return {+ ...base,+ name: String(data.name ?? fallbackName).trim() || fallbackName,+ is_default: data.is_default === undefined ? isDefault : Boolean(data.is_default),+ };+}++function normalizeXiaoyiAppsConfig(input: unknown): XiaoyiAppConfig[] {+ if (input && typeof input === 'object') {+ const data = input as Record<string, unknown>;+ if (Array.isArray(data.apps)) {+ const apps = data.apps.map((item, idx) => normalizeXiaoyiAppConfig(item, `小艺应用 ${idx + 1}`, idx === 0));+ return sortXiaoyiApps(apps.length > 0 ? apps : [normalizeXiaoyiAppConfig(DEFAULT_XIAOYI_CONF, '默认小艺应用', true)]);+ }+ }+ return sortXiaoyiApps([normalizeXiaoyiAppConfig(input, '默认小艺应用', true)]);+}++function draftFromXiaoyiAppConfig(conf: XiaoyiAppConfig): XiaoyiAppDraft {+ return {+ ...draftFromXiaoyiConfig(conf),+ name: conf.name,+ is_default: conf.is_default,+ };+}++function buildXiaoyiAppConfig(draft: XiaoyiAppDraft): XiaoyiAppConfig {+ const payload = buildXiaoyiPayload(draft);+ return {+ ...DEFAULT_XIAOYI_CONF,+ ...(payload as XiaoyiConfig),+ name: draft.name.trim() || '未命名小艺应用',+ is_default: draft.is_default,+ };+}+function normalizeDingtalkConfig(input: unknown): DingTalkConfig {if (!input || typeof input !== 'object') {return DEFAULT_DINGTALK_CONF;@@ -732,15 +841,25 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {const [error, setError] = useState<string | null>(null);const [lastUpdatedAt, setLastUpdatedAt] = useState<string | null>(null);- const [feishuConfig, setFeishuConfig] = useState<FeishuConfig>(DEFAULT_FEISHU_CONF);- const [draft, setDraft] = useState<FeishuDraft>(draftFromFeishuConfig(DEFAULT_FEISHU_CONF));+ const [feishuApps, setFeishuApps] = useState<FeishuAppConfig[]>(() =>+ normalizeFeishuAppsConfig(DEFAULT_FEISHU_CONF),+ );+ const [feishuDraftApps, setFeishuDraftApps] = useState<FeishuAppDraft[]>(() =>+ normalizeFeishuAppsConfig(DEFAULT_FEISHU_CONF).map(draftFromFeishuAppConfig),+ );+ const [expandedFeishuAppIndex, setExpandedFeishuAppIndex] = useState(0);const [visibleFields, setVisibleFields] = useState<Record<string, boolean>>({});const [feishuLoading, setFeishuLoading] = useState(false);const [saving, setSaving] = useState(false);const [saveError, setSaveError] = useState<string | null>(null);const [success, setSuccess] = useState<string | null>(null);- const [xiaoyiConfig, setXiaoyiConfig] = useState<XiaoyiConfig>(DEFAULT_XIAOYI_CONF);- const [xiaoyiDraft, setXiaoyiDraft] = useState<XiaoyiDraft>(draftFromXiaoyiConfig(DEFAULT_XIAOYI_CONF));+ const [xiaoyiApps, setXiaoyiApps] = useState<XiaoyiAppConfig[]>(() =>+ normalizeXiaoyiAppsConfig(DEFAULT_XIAOYI_CONF),+ );+ const [xiaoyiDraftApps, setXiaoyiDraftApps] = useState<XiaoyiAppDraft[]>(() =>+ normalizeXiaoyiAppsConfig(DEFAULT_XIAOYI_CONF).map(draftFromXiaoyiAppConfig),+ );+ const [expandedXiaoyiAppIndex, setExpandedXiaoyiAppIndex] = useState(0);const [xiaoyiVisibleFields, setXiaoyiVisibleFields] = useState<Record<string, boolean>>({});const [xiaoyiLoading, setXiaoyiLoading] = useState(false);const [xiaoyiSaving, setXiaoyiSaving] = useState(false);@@ -818,9 +937,10 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {setSuccess(null);try {const payload = await webRequest<{ config?: unknown }>('channel.feishu.get_conf');- const normalized = normalizeFeishuConfig(payload?.config);- setFeishuConfig(normalized);- setDraft(draftFromFeishuConfig(normalized));+ const normalized = normalizeFeishuAppsConfig(payload?.config);+ setFeishuApps(normalized);+ setFeishuDraftApps(normalized.map(draftFromFeishuAppConfig));+ setExpandedFeishuAppIndex(0);setVisibleFields({});} catch (err) {setSaveError(err instanceof Error ? err.message : t('channels.errors.loadFeishu'));@@ -835,9 +955,10 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {setXiaoyiSuccess(null);try {const payload = await webRequest<{ config?: unknown }>('channel.xiaoyi.get_conf');- const normalized = normalizeXiaoyiConfig(payload?.config);- setXiaoyiConfig(normalized);- setXiaoyiDraft(draftFromXiaoyiConfig(normalized));+ const normalized = normalizeXiaoyiAppsConfig(payload?.config);+ setXiaoyiApps(normalized);+ setXiaoyiDraftApps(normalized.map(draftFromXiaoyiAppConfig));+ setExpandedXiaoyiAppIndex(0);setXiaoyiVisibleFields({});} catch (err) {setXiaoyiSaveError(err instanceof Error ? err.message : t('channels.errors.loadXiaoyi'));@@ -1058,33 +1179,11 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {}, [channels, loadState, t]);const hasConfigChanges = useMemo(() => {- const baseDraft = draftFromFeishuConfig(feishuConfig);- return (- baseDraft.enabled !== draft.enabled ||- baseDraft.enable_streaming !== draft.enable_streaming ||- baseDraft.app_id !== draft.app_id ||- baseDraft.app_secret !== draft.app_secret ||- baseDraft.encrypt_key !== draft.encrypt_key ||- baseDraft.verification_token !== draft.verification_token ||- baseDraft.chat_id !== draft.chat_id ||- normalizeAllowFromText(baseDraft.allow_from).join('\n') !== normalizeAllowFromText(draft.allow_from).join('\n') ||- baseDraft.group_digital_avatar !== draft.group_digital_avatar ||- baseDraft.my_user_id !== draft.my_user_id ||- baseDraft.bot_name !== draft.bot_name ||- baseDraft.enable_memory !== draft.enable_memory- );- }, [draft, feishuConfig]);+ return JSON.stringify(feishuApps) !== JSON.stringify(feishuDraftApps.map(buildFeishuAppConfig));+ }, [feishuApps, feishuDraftApps]);const hasXiaoyiConfigChanges = useMemo(() => {- const baseDraft = draftFromXiaoyiConfig(xiaoyiConfig);- return (- baseDraft.enabled !== xiaoyiDraft.enabled ||- baseDraft.ak !== xiaoyiDraft.ak ||- baseDraft.sk !== xiaoyiDraft.sk ||- baseDraft.agent_id !== xiaoyiDraft.agent_id ||- baseDraft.api_id !== xiaoyiDraft.api_id ||- baseDraft.enable_streaming !== xiaoyiDraft.enable_streaming- );- }, [xiaoyiConfig, xiaoyiDraft]);+ return JSON.stringify(xiaoyiApps) !== JSON.stringify(xiaoyiDraftApps.map(buildXiaoyiAppConfig));+ }, [xiaoyiApps, xiaoyiDraftApps]);const hasDingtalkConfigChanges = useMemo(() => {const baseDraft = draftFromDingtalkConfig(dingtalkConfig);return (@@ -1165,8 +1264,12 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {);}, [wechatConfig, wechatDraft]);- const handleFieldChange = <K extends keyof FeishuDraft>(key: K, value: FeishuDraft[K]) => {- setDraft((prev) => ({ ...prev, [key]: value }));+ const handleFeishuAppFieldChange = <K extends keyof FeishuAppDraft>(+ index: number,+ key: K,+ value: FeishuAppDraft[K],+ ) => {+ setFeishuDraftApps((prev) => prev.map((app, i) => (i === index ? { ...app, [key]: value } : app)));if (saveError) {setSaveError(null);}@@ -1177,17 +1280,66 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {const handleCancelConfig = () => {if (!hasConfigChanges) return;- setDraft(draftFromFeishuConfig(feishuConfig));+ setFeishuDraftApps(feishuApps.map(draftFromFeishuAppConfig));+ setSaveError(null);+ setSuccess(null);+ };++ const handleAddFeishuApp = () => {+ setFeishuDraftApps((prev) => {+ const next = [+ ...prev,+ {+ ...draftFromFeishuAppConfig({+ ...DEFAULT_FEISHU_CONF,+ name: `飞书应用 ${prev.length + 1}`,+ is_default: false,+ }),+ },+ ];+ setExpandedFeishuAppIndex(next.length - 1);+ return next;+ });setSaveError(null);setSuccess(null);};- const toggleFieldVisible = (field: keyof FeishuDraft) => {+ const handleDeleteFeishuApp = (index: number) => {+ setFeishuDraftApps((prev) => {+ if (prev.length <= 1) return prev;+ const next = prev.filter((_, i) => i !== index);+ if (!next.some((app) => app.is_default) && next.length > 0) {+ next[0] = { ...next[0], is_default: true };+ }+ setExpandedFeishuAppIndex((current) => Math.max(0, Math.min(current >= index ? current - 1 : current, next.length - 1)));+ return next;+ });+ setSaveError(null);+ setSuccess(null);+ };++ const handleSetDefaultFeishuApp = (index: number) => {+ setFeishuDraftApps((prev) => prev.map((app, i) => ({ ...app, is_default: i === index })));+ setSaveError(null);+ setSuccess(null);+ };++ const draft = feishuDraftApps[0] ?? draftFromFeishuAppConfig({ ...DEFAULT_FEISHU_CONF, name: '默认飞书应用', is_default: true });++ const handleFieldChange = <K extends keyof FeishuDraft>(key: K, value: FeishuDraft[K]) => {+ handleFeishuAppFieldChange(0, key, value);+ };++ const toggleFieldVisible = (field: string) => {setVisibleFields((prev) => ({ ...prev, [field]: !prev[field] }));};- const handleXiaoyiFieldChange = <K extends keyof XiaoyiDraft>(key: K, value: XiaoyiDraft[K]) => {- setXiaoyiDraft((prev) => ({ ...prev, [key]: value }));+ const handleXiaoyiAppFieldChange = <K extends keyof XiaoyiAppDraft>(+ index: number,+ key: K,+ value: XiaoyiAppDraft[K],+ ) => {+ setXiaoyiDraftApps((prev) => prev.map((app, i) => (i === index ? { ...app, [key]: value } : app)));if (xiaoyiSaveError) {setXiaoyiSaveError(null);}@@ -1198,12 +1350,51 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {const handleCancelXiaoyiConfig = () => {if (!hasXiaoyiConfigChanges) return;- setXiaoyiDraft(draftFromXiaoyiConfig(xiaoyiConfig));+ setXiaoyiDraftApps(xiaoyiApps.map(draftFromXiaoyiAppConfig));setXiaoyiSaveError(null);setXiaoyiSuccess(null);};- const toggleXiaoyiFieldVisible = (field: keyof XiaoyiDraft) => {+ const handleAddXiaoyiApp = () => {+ setXiaoyiDraftApps((prev) => {+ const next = [+ ...prev,+ {+ ...draftFromXiaoyiAppConfig({+ ...DEFAULT_XIAOYI_CONF,+ name: `小艺应用 ${prev.length + 1}`,+ is_default: false,+ }),+ },+ ];+ setExpandedXiaoyiAppIndex(next.length - 1);+ return next;+ });+ setXiaoyiSaveError(null);+ setXiaoyiSuccess(null);+ };++ const handleDeleteXiaoyiApp = (index: number) => {+ setXiaoyiDraftApps((prev) => {+ if (prev.length <= 1) return prev;+ const next = prev.filter((_, i) => i !== index);+ if (!next.some((app) => app.is_default) && next.length > 0) {+ next[0] = { ...next[0], is_default: true };+ }+ setExpandedXiaoyiAppIndex((current) => Math.max(0, Math.min(current >= index ? current - 1 : current, next.length - 1)));+ return next;+ });+ setXiaoyiSaveError(null);+ setXiaoyiSuccess(null);+ };++ const handleSetDefaultXiaoyiApp = (index: number) => {+ setXiaoyiDraftApps((prev) => prev.map((app, i) => ({ ...app, is_default: i === index })));+ setXiaoyiSaveError(null);+ setXiaoyiSuccess(null);+ };++ const toggleXiaoyiFieldVisible = (field: string) => {setXiaoyiVisibleFields((prev) => ({ ...prev, [field]: !prev[field] }));};@@ -1346,11 +1537,11 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {setSaving(true);setSaveError(null);try {- const payload = buildFeishuPayload(draft);- const result = await webRequest<{ config?: unknown }>('channel.feishu.set_conf', payload);- const normalized = normalizeFeishuConfig(result?.config);- setFeishuConfig(normalized);- setDraft(draftFromFeishuConfig(normalized));+ const apps = feishuDraftApps.map(buildFeishuAppConfig);+ const result = await webRequest<{ config?: unknown }>('channel.feishu.set_conf', { apps });+ const normalized = normalizeFeishuAppsConfig(result?.config);+ setFeishuApps(normalized);+ setFeishuDraftApps(normalized.map(draftFromFeishuAppConfig));setSuccess(t('channels.saved.feishu'));void fetchChannels();} catch (saveErr) {@@ -1366,11 +1557,11 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {setXiaoyiSaving(true);setXiaoyiSaveError(null);try {- const payload = buildXiaoyiPayload(xiaoyiDraft);- const result = await webRequest<{ config?: unknown }>('channel.xiaoyi.set_conf', payload);- const normalized = normalizeXiaoyiConfig(result?.config);- setXiaoyiConfig(normalized);- setXiaoyiDraft(draftFromXiaoyiConfig(normalized));+ const apps = xiaoyiDraftApps.map(buildXiaoyiAppConfig);+ const result = await webRequest<{ config?: unknown }>('channel.xiaoyi.set_conf', { apps });+ const normalized = normalizeXiaoyiAppsConfig(result?.config);+ setXiaoyiApps(normalized);+ setXiaoyiDraftApps(normalized.map(draftFromXiaoyiAppConfig));setXiaoyiSuccess(t('channels.saved.xiaoyi'));void fetchChannels();} catch (saveErr) {@@ -1519,6 +1710,285 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {whatsappLoading ||wecomLoading ||wechatLoading;++ const renderToggle = (checked: boolean, onClick: () => void) => (+ <button+ type="button"+ role="switch"+ aria-checked={checked}+ onClick={onClick}+ className={`relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 focus:outline-none ${+ checked ? 'bg-ok' : 'bg-secondary'+ }`}+ >+ <span+ className={`pointer-events-none inline-block h-4 w-4 transform rounded-full bg-white shadow transition duration-200 ${+ checked ? 'translate-x-4' : 'translate-x-0'+ }`}+ />+ </button>+ );++ const renderFeishuAppField = (app: FeishuAppDraft, appIndex: number, field: keyof FeishuAppDraft) => {+ const visibilityKey = `${appIndex}.${String(field)}`;+ const value = app[field];+ if (typeof value === 'boolean') {+ return (+ <tr key={String(field)} className="border-t border-border first:border-t-0 even:bg-secondary/10">+ <td className="px-4 py-2.5 align-middle mono text-xs text-text-muted w-[32%]">{String(field)}</td>+ <td className="px-4 py-2.5 align-middle">+ {renderToggle(value, () => handleFeishuAppFieldChange(appIndex, field, !value as FeishuAppDraft[typeof field]))}+ </td>+ </tr>+ );+ }+ return (+ <tr key={String(field)} className="border-t border-border first:border-t-0 even:bg-secondary/10">+ <td className="px-4 py-2.5 align-middle mono text-xs text-text-muted w-[32%]">{String(field)}</td>+ <td className="px-4 py-2.5 break-all text-[13px] align-middle">+ <div className="relative">+ <input+ type={isSensitiveField(field) && !visibleFields[visibilityKey] ? 'password' : 'text'}+ value={String(value ?? '')}+ onChange={(e) => handleFeishuAppFieldChange(appIndex, field, e.target.value as FeishuAppDraft[typeof field])}+ placeholder={t('channels.placeholders.configValue')}+ className={`w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] outline-none focus:border-accent ${+ isSensitiveField(field) ? 'pr-10' : ''+ }`}+ />+ {isSensitiveField(field) ? (+ <button+ type="button"+ onClick={() => toggleFieldVisible(visibilityKey)}+ className="channels-panel__visibility-toggle"+ aria-label={visibleFields[visibilityKey] ? t('channels.hideValue') : t('channels.showValue')}+ title={visibleFields[visibilityKey] ? t('channels.hideValue') : t('channels.showValue')}+ >+ <VisibilityIcon visible={Boolean(visibleFields[visibilityKey])} />+ </button>+ ) : null}+ </div>+ </td>+ </tr>+ );+ };++ const renderXiaoyiAppField = (app: XiaoyiAppDraft, appIndex: number, field: keyof XiaoyiAppDraft) => {+ const visibilityKey = `${appIndex}.${String(field)}`;+ const value = app[field];+ if (typeof value === 'boolean') {+ return (+ <tr key={String(field)} className="border-t border-border first:border-t-0 even:bg-secondary/10">+ <td className="px-4 py-2.5 align-middle mono text-xs text-text-muted w-[32%]">{String(field)}</td>+ <td className="px-4 py-2.5 align-middle">+ {renderToggle(value, () => handleXiaoyiAppFieldChange(appIndex, field, !value as XiaoyiAppDraft[typeof field]))}+ </td>+ </tr>+ );+ }+ return (+ <tr key={String(field)} className="border-t border-border first:border-t-0 even:bg-secondary/10">+ <td className="px-4 py-2.5 align-middle mono text-xs text-text-muted w-[32%]">{String(field)}</td>+ <td className="px-4 py-2.5 break-all text-[13px] align-middle">+ <div className="relative">+ <input+ type={isSensitiveXiaoyiField(field) && !xiaoyiVisibleFields[visibilityKey] ? 'password' : 'text'}+ value={String(value ?? '')}+ onChange={(e) => handleXiaoyiAppFieldChange(appIndex, field, e.target.value as XiaoyiAppDraft[typeof field])}+ placeholder={t('channels.placeholders.configValue')}+ className={`w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] outline-none focus:border-accent ${+ isSensitiveXiaoyiField(field) ? 'pr-10' : ''+ }`}+ />+ {isSensitiveXiaoyiField(field) ? (+ <button+ type="button"+ onClick={() => toggleXiaoyiFieldVisible(visibilityKey)}+ className="channels-panel__visibility-toggle"+ aria-label={xiaoyiVisibleFields[visibilityKey] ? t('channels.hideValue') : t('channels.showValue')}+ title={xiaoyiVisibleFields[visibilityKey] ? t('channels.hideValue') : t('channels.showValue')}+ >+ <VisibilityIcon visible={Boolean(xiaoyiVisibleFields[visibilityKey])} />+ </button>+ ) : null}+ </div>+ </td>+ </tr>+ );+ };++ const renderFeishuAppsEditor = () => (+ <div className="space-y-3">+ {feishuDraftApps.map((app, index) => {+ const expanded = expandedFeishuAppIndex === index;+ const identifier = app.app_id.trim() || '未配置 app_id';+ return (+ <div key={`feishu-app-${index}`} className="rounded-xl border border-border bg-card overflow-hidden">+ <div className="flex items-center gap-3 px-4 py-3">+ <button+ type="button"+ onClick={() => setExpandedFeishuAppIndex(expanded ? -1 : index)}+ className="inline-flex h-7 w-7 items-center justify-center rounded-md text-text-muted hover:bg-secondary hover:text-text"+ aria-label={expanded ? '收起应用配置' : '展开应用配置'}+ title={expanded ? '收起应用配置' : '展开应用配置'}+ >+ <ChevronRight className={`h-4 w-4 transition-transform ${expanded ? 'rotate-90' : ''}`} />+ </button>+ <input+ type="text"+ value={app.name}+ onChange={(e) => handleFeishuAppFieldChange(index, 'name', e.target.value)}+ className="min-w-[160px] flex-1 rounded-md border border-border bg-bg px-3 py-2 text-sm outline-none focus:border-accent"+ placeholder="应用名称"+ />+ {app.is_default ? (+ <span className="rounded-full border border-accent bg-accent-subtle px-2.5 py-1 text-xs text-accent">+ 默认+ </span>+ ) : null}+ {!app.is_default ? (+ <button+ type="button"+ onClick={() => handleSetDefaultFeishuApp(index)}+ className="rounded-full border border-accent/50 bg-accent-subtle px-2.5 py-1 text-xs font-medium text-accent hover:border-accent hover:bg-accent/15"+ aria-label="设为默认应用"+ title="设为默认应用"+ >+ 设为默认+ </button>+ ) : null}+ <span className="mono max-w-[220px] truncate rounded-md border border-border bg-secondary px-2.5 py-1 text-xs text-text-muted">+ {identifier}+ </span>+ <span+ className={`rounded-full border px-2.5 py-1 text-xs font-medium ${+ app.enabled ? 'border-ok bg-ok-subtle text-ok' : 'border-border bg-secondary text-text-muted'+ }`}+ >+ {app.enabled ? t('channels.status.enabled') : t('channels.status.disabled')}+ </span>+ <button+ type="button"+ onClick={() => handleDeleteFeishuApp(index)}+ disabled={feishuDraftApps.length <= 1}+ className="inline-flex h-8 w-8 items-center justify-center rounded-md border border-border text-text-muted hover:bg-danger-subtle hover:text-danger disabled:cursor-not-allowed disabled:opacity-40"+ aria-label="删除应用"+ title="删除应用"+ >+ <Trash2 className="h-4 w-4" />+ </button>+ </div>+ {expanded ? (+ <div className="border-t border-border bg-bg/30">+ <table className="w-full text-sm">+ <tbody>+ {(['enabled', 'enable_streaming', 'app_id', 'app_secret', 'encrypt_key', 'verification_token', 'group_digital_avatar'] as const).map(+ (field) => renderFeishuAppField(app, index, field),+ )}+ </tbody>+ </table>+ </div>+ ) : null}+ </div>+ );+ })}+ <button+ type="button"+ onClick={handleAddFeishuApp}+ className="flex w-full items-center justify-center gap-2 rounded-xl border border-dashed border-border px-4 py-3 text-sm text-text-muted hover:border-accent hover:bg-accent-subtle hover:text-accent"+ >+ <Plus className="h-4 w-4" />+ 添加应用+ </button>+ </div>+ );++ const renderXiaoyiAppsEditor = () => (+ <div className="space-y-3">+ {xiaoyiDraftApps.map((app, index) => {+ const expanded = expandedXiaoyiAppIndex === index;+ const identifier = app.api_id.trim() || app.agent_id.trim() || '未配置 api_id';+ return (+ <div key={`xiaoyi-app-${index}`} className="rounded-xl border border-border bg-card overflow-hidden">+ <div className="flex items-center gap-3 px-4 py-3">+ <button+ type="button"+ onClick={() => setExpandedXiaoyiAppIndex(expanded ? -1 : index)}+ className="inline-flex h-7 w-7 items-center justify-center rounded-md text-text-muted hover:bg-secondary hover:text-text"+ aria-label={expanded ? '收起应用配置' : '展开应用配置'}+ title={expanded ? '收起应用配置' : '展开应用配置'}+ >+ <ChevronRight className={`h-4 w-4 transition-transform ${expanded ? 'rotate-90' : ''}`} />+ </button>+ <input+ type="text"+ value={app.name}+ onChange={(e) => handleXiaoyiAppFieldChange(index, 'name', e.target.value)}+ className="min-w-[160px] flex-1 rounded-md border border-border bg-bg px-3 py-2 text-sm outline-none focus:border-accent"+ placeholder="应用名称"+ />+ {app.is_default ? (+ <span className="rounded-full border border-accent bg-accent-subtle px-2.5 py-1 text-xs text-accent">+ 默认+ </span>+ ) : null}+ {!app.is_default ? (+ <button+ type="button"+ onClick={() => handleSetDefaultXiaoyiApp(index)}+ className="rounded-full border border-accent/50 bg-accent-subtle px-2.5 py-1 text-xs font-medium text-accent hover:border-accent hover:bg-accent/15"+ aria-label="设为默认应用"+ title="设为默认应用"+ >+ 设为默认+ </button>+ ) : null}+ <span className="mono max-w-[220px] truncate rounded-md border border-border bg-secondary px-2.5 py-1 text-xs text-text-muted">+ {identifier}+ </span>+ <span+ className={`rounded-full border px-2.5 py-1 text-xs font-medium ${+ app.enabled ? 'border-ok bg-ok-subtle text-ok' : 'border-border bg-secondary text-text-muted'+ }`}+ >+ {app.enabled ? t('channels.status.enabled') : t('channels.status.disabled')}+ </span>+ <button+ type="button"+ onClick={() => handleDeleteXiaoyiApp(index)}+ disabled={xiaoyiDraftApps.length <= 1}+ className="inline-flex h-8 w-8 items-center justify-center rounded-md border border-border text-text-muted hover:bg-danger-subtle hover:text-danger disabled:cursor-not-allowed disabled:opacity-40"+ aria-label="删除应用"+ title="删除应用"+ >+ <Trash2 className="h-4 w-4" />+ </button>+ </div>+ {expanded ? (+ <div className="border-t border-border bg-bg/30">+ <table className="w-full text-sm">+ <tbody>+ {(['enabled', 'enable_streaming', 'ak', 'sk', 'agent_id', 'api_id'] as const).map((field) =>+ renderXiaoyiAppField(app, index, field),+ )}+ </tbody>+ </table>+ </div>+ ) : null}+ </div>+ );+ })}+ <button+ type="button"+ onClick={handleAddXiaoyiApp}+ className="flex w-full items-center justify-center gap-2 rounded-xl border border-dashed border-border px-4 py-3 text-sm text-text-muted hover:border-accent hover:bg-accent-subtle hover:text-accent"+ >+ <Plus className="h-4 w-4" />+ 添加应用+ </button>+ </div>+ );+const configErrorNotice = useMemo(() => {return Array.from(new Set(@@ -1749,79 +2219,7 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {{xiaoyiLoading ? (<div className="text-sm text-text-muted">{t('channels.loading.xiaoyi')}</div>) : (- <table className="w-full text-sm">- <tbody>- <tr className="border-t border-border first:border-t-0 even:bg-secondary/10">- <td className="px-4 py-2.5 align-middle mono text-xs text-text-muted w-[32%]">enabled</td>- <td className="px-4 py-2.5 align-middle">- <button- type="button"- role="switch"- aria-checked={xiaoyiDraft.enabled}- onClick={() => handleXiaoyiFieldChange('enabled', !xiaoyiDraft.enabled)}- className={`relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 focus:outline-none ${- xiaoyiDraft.enabled ? 'bg-ok' : 'bg-secondary'- }`}- >- <span- className={`pointer-events-none inline-block h-4 w-4 transform rounded-full bg-white shadow transition duration-200 ${- xiaoyiDraft.enabled ? 'translate-x-4' : 'translate-x-0'- }`}- />- </button>- </td>- </tr>- <tr className="border-t border-border first:border-t-0 even:bg-secondary/10">- <td className="px-4 py-2.5 align-middle mono text-xs text-text-muted w-[32%]">enable_streaming</td>- <td className="px-4 py-2.5 align-middle">- <button- type="button"- role="switch"- aria-checked={xiaoyiDraft.enable_streaming}- onClick={() => handleXiaoyiFieldChange('enable_streaming', !xiaoyiDraft.enable_streaming)}- className={`relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 focus:outline-none ${- xiaoyiDraft.enable_streaming ? 'bg-ok' : 'bg-secondary'- }`}- >- <span- className={`pointer-events-none inline-block h-4 w-4 transform rounded-full bg-white shadow transition duration-200 ${- xiaoyiDraft.enable_streaming ? 'translate-x-4' : 'translate-x-0'- }`}- />- </button>- </td>- </tr>- {(['ak', 'sk', 'agent_id', 'api_id'] as const).map((field) => (- <tr key={field} className="border-t border-border first:border-t-0 even:bg-secondary/10">- <td className="px-4 py-2.5 align-middle mono text-xs text-text-muted w-[32%]">{field}</td>- <td className="px-4 py-2.5 break-all text-[13px] align-middle">- <div className="relative">- <input- type={isSensitiveXiaoyiField(field) && !xiaoyiVisibleFields[field] ? 'password' : 'text'}- value={xiaoyiDraft[field]}- onChange={(e) => handleXiaoyiFieldChange(field, e.target.value)}- placeholder={t('channels.placeholders.configValue')}- className={`w-full rounded-md border border-border bg-bg px-3 py-2 text-[13px] outline-none focus:border-accent ${- isSensitiveXiaoyiField(field) ? 'pr-10' : ''- }`}- />- {isSensitiveXiaoyiField(field) ? (- <button- type="button"- onClick={() => toggleXiaoyiFieldVisible(field)}- className="channels-panel__visibility-toggle"- aria-label={xiaoyiVisibleFields[field] ? t('channels.hideValue') : t('channels.showValue')}- title={xiaoyiVisibleFields[field] ? t('channels.hideValue') : t('channels.showValue')}- >- <VisibilityIcon visible={Boolean(xiaoyiVisibleFields[field])} />- </button>- ) : null}- </div>- </td>- </tr>- ))}- </tbody>- </table>+ renderXiaoyiAppsEditor())}</div></div>@@ -1948,6 +2346,62 @@ export function ChannelsPanel({ isConnected }: ChannelsPanelProps) {) : null}{activeChannelId === 'feishu' ? (+ <div className="w-full h-full rounded-xl border border-border bg-card/70 backdrop-blur-sm overflow-hidden shadow-sm flex flex-col">+ <div className="px-4 py-3 bg-secondary/30 border-b border-border">+ <div className="flex items-center justify-between gap-4">+ <div className="flex items-center gap-3">+ <ChannelHeaderLogo channelId="feishu" label={getChannelLabel(t, 'feishu')} />+ <div>+ <h4 className="text-sm font-medium text-text">{t('channels.config.feishuTitle')}</h4>+ <p className="text-xs text-text-muted mt-1">{t('channels.config.feishuSubtitle')}</p>+ </div>+ </div>+ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={() => void fetchFeishuConfig()}+ disabled={saving || isConfigRefreshing}+ className="btn !px-3 !py-1.5 disabled:opacity-50 disabled:cursor-not-allowed"+ >+ {feishuLoading ? t('common.refreshing') : t('common.refresh')}+ </button>+ <button+ type="button"+ onClick={handleCancelConfig}+ disabled={!hasConfigChanges || saving}+ className="btn !px-3 !py-1.5 disabled:opacity-50 disabled:cursor-not-allowed"+ >+ {t('common.cancel')}+ </button>+ <button+ type="button"+ onClick={() => void handleSaveConfig()}+ disabled={!hasConfigChanges || saving || !isConnected}+ className="btn primary !px-3 !py-1.5 disabled:opacity-50 disabled:cursor-not-allowed"+ >+ {saving ? t('common.saving') : t('common.save')}+ </button>+ </div>+ </div>+ </div>++ {success ? (+ <div className="mx-4 mt-4 rounded-md border border-[var(--border-ok)] bg-ok-subtle px-3 py-2 text-sm text-ok">+ {success}+ </div>+ ) : null}++ <div className="p-4 pt-3 flex-1 overflow-auto">+ {feishuLoading ? (+ <div className="text-sm text-text-muted">{t('channels.loading.feishu')}</div>+ ) : (+ renderFeishuAppsEditor()+ )}+ </div>+ </div>+ ) : null}++ {false && activeChannelId === 'feishu' ? (<div className="w-full h-full rounded-xl border border-border bg-card/70 backdrop-blur-sm overflow-hidden shadow-sm flex flex-col"><div className="px-4 py-3 bg-secondary/30 border-b border-border"><div className="flex items-center justify-between gap-4">diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ChatPanel.css b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ChatPanel.cssindex 17ffc262e9..729de8c7a9 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ChatPanel.css+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ChatPanel.css@@ -270,6 +270,363 @@}}+.human-share-card {+ display: flex;+ align-items: center;+ gap: 16px;+ box-sizing: border-box;+ width: calc(100% - 48px);+ max-width: 980px;+ min-height: 118px;+ margin: 12px auto 16px;+ padding: 20px 28px 18px;+ border: 1px solid rgba(25, 25, 25, 0.14);+ border-radius: 22px;+ background: color-mix(in srgb, var(--card) 96%, var(--panel) 4%);+ box-shadow: none;+}++.human-share-card__icon {+ display: none;+}++.human-share-card__content {+ min-width: 0;+ flex: 1 1 auto;+}++.human-share-card__title {+ color: var(--text);+ font-size: 16px;+ font-weight: 700;+ line-height: 24px;+}++.human-share-card__summary {+ margin-top: 14px;+ color: var(--muted);+ font-size: 16px;+ line-height: 24px;+}++.human-share-card__members {+ display: flex;+ flex-wrap: wrap;+ gap: 10px;+ margin-top: 14px;+ color: var(--muted);+ font-size: 14px;+ line-height: 20px;+}++.human-share-card__member-pill {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ min-width: 0;+}++.human-share-card__avatar {+ width: 24px;+ height: 24px;+ border-radius: 8px;+}++.human-share-card__more {+ color: var(--text-muted);+}++.human-share-card__button {+ display: inline-flex;+ height: 42px;+ flex: 0 0 auto;+ align-items: center;+ justify-content: center;+ gap: 8px;+ border: 1px solid rgba(25, 25, 25, 0.72);+ border-radius: 999px;+ padding: 0 18px;+ color: var(--text);+ background: var(--card);+ font-size: 15px;+ font-weight: 650;+ cursor: pointer;+ transition:+ background var(--duration-fast) ease,+ color var(--duration-fast) ease,+ box-shadow var(--duration-fast) ease;+}++.human-share-card__button:hover {+ color: var(--text);+ background: color-mix(in srgb, var(--secondary) 70%, transparent);+ box-shadow: 0 6px 18px rgba(15, 23, 42, 0.08);+}++.human-share-modal-backdrop {+ position: fixed;+ inset: 0;+ z-index: 1000;+ display: flex;+ align-items: flex-start;+ justify-content: center;+ overflow-y: auto;+ padding: max(24px, env(safe-area-inset-top)) 24px max(24px, env(safe-area-inset-bottom));+ background: rgba(15, 23, 42, 0.28);+}++.human-share-modal {+ width: min(760px, 100%);+ max-height: calc(100vh - 48px);+ display: flex;+ flex-direction: column;+ overflow: hidden;+ border: 1px solid var(--border);+ border-radius: 4px;+ background: var(--card);+ box-shadow: 0 24px 72px rgba(15, 23, 42, 0.24);+}++.human-share-modal__header {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 16px;+ padding: 28px 30px 10px;+ border-bottom: 0;+}++.human-share-modal__title {+ margin: 0;+ color: var(--text);+ font-size: 24px;+ font-weight: 700;+ line-height: 32px;+}++.human-share-modal__title-row {+ display: inline-flex;+ align-items: center;+ gap: 8px;+}++.human-share-modal__summary {+ margin: 10px 0 0;+ color: var(--muted);+ font-size: 16px;+ line-height: 24px;+}++.human-share-modal__close {+ display: inline-flex;+ width: 36px;+ height: 36px;+ flex: 0 0 auto;+ align-items: center;+ justify-content: center;+ border: 0;+ border-radius: 8px;+ color: var(--muted);+ background: transparent;+ cursor: pointer;+}++.human-share-modal__close:hover {+ color: var(--text);+ background: var(--secondary);+}++.human-share-modal__body {+ min-height: 0;+ overflow-y: auto;+ padding: 18px 30px 28px;+}++.human-share-modal__notice {+ display: flex;+ align-items: center;+ gap: 14px;+ min-height: 52px;+ margin-bottom: 16px;+ border-radius: 4px;+ padding: 0 20px;+ color: #1d4ed8;+ background: #dbe8ff;+ font-size: 16px;+ line-height: 24px;+}++.human-share-modal__item {+ padding: 10px 0 12px;+ border-bottom: 0;+}++.human-share-modal__item:first-child {+ padding-top: 0;+}++.human-share-modal__member {+ display: flex;+ align-items: center;+ gap: 10px;+ margin-bottom: 10px;+}++.human-share-modal__avatar {+ width: 26px;+ height: 26px;+ border-radius: 8px;+}++.human-share-modal__member-copy {+ min-width: 0;+ flex: 1 1 auto;+}++.human-share-modal__member-name {+ overflow: hidden;+ color: var(--text);+ font-size: 16px;+ font-weight: 650;+ line-height: 24px;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.human-share-modal__member-id {+ overflow: hidden;+ color: var(--muted);+ font-size: 12px;+ line-height: 18px;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.human-share-modal__badge {+ flex: 0 0 auto;+ border-radius: 5px;+ padding: 3px 9px;+ color: var(--muted);+ background: var(--secondary);+ font-size: 14px;+ font-weight: 650;+ line-height: 20px;+}++.human-share-modal__badge--joined {+ color: #047857;+ background: #d1fae5;+}++.human-share-modal__badge--left {+ color: #6b7280;+ background: #f3f4f6;+}++.human-share-modal__command-row {+ display: flex;+ align-items: stretch;+ gap: 8px;+}++.human-share-modal__command {+ min-width: 0;+ flex: 1 1 auto;+ overflow-x: auto;+ border: 1px solid var(--border);+ border-radius: 3px;+ padding: 9px 14px;+ color: var(--text);+ background: var(--card);+ font-size: 16px;+ line-height: 24px;+ white-space: nowrap;+}++.human-share-modal__copy {+ display: inline-flex;+ flex: 0 0 auto;+ align-items: center;+ justify-content: center;+ gap: 5px;+ border: 0;+ border-radius: 6px;+ padding: 0 10px;+ color: var(--text);+ background: var(--card);+ font-size: 12px;+ font-weight: 650;+ cursor: pointer;+}++.human-share-modal__copy:hover {+ background: var(--secondary);+}++.human-share-modal__command-note {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ border-radius: 8px;+ padding: 8px 10px;+ font-size: 12px;+ font-weight: 600;+ line-height: 18px;+}++.human-share-modal__command-note--joined {+ color: #047857;+ background: #ecfdf5;+}++.human-share-modal__command-note--pending {+ color: var(--muted);+ background: var(--secondary);+}++.human-share-modal__exit {+ margin-top: 16px;+}++.human-share-modal__exit-title {+ margin-bottom: 8px;+ color: var(--text);+ font-size: 13px;+ font-weight: 700;+}++@media (max-width: 640px) {+ .human-share-card {+ align-items: stretch;+ flex-direction: column;+ width: 100%;+ margin: 10px 0;+ }++ .human-share-card__button {+ width: 100%;+ }++ .human-share-modal-backdrop {+ align-items: flex-end;+ overflow-y: hidden;+ padding: 12px;+ }++ .human-share-modal {+ max-height: calc(100vh - 24px);+ border-radius: 10px;+ }++ .human-share-modal__command-row {+ flex-direction: column;+ }++ .human-share-modal__copy {+ height: 36px;+ }+}+/* Recording bar */.chat-input-recording-bar {display: flex;diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsxindex b607ab47d3..55f61ddf3f 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/index.tsx@@ -5,11 +5,13 @@*/import React, { useRef, useEffect, useLayoutEffect, useCallback, useMemo } from 'react';-import { ArrowRight, LoaderCircle, Share2, Sparkles } from 'lucide-react';+import { createPortal } from 'react-dom';+import { ArrowRight, CheckCircle2, ClipboardList, Copy, Info, LoaderCircle, Share2, Sparkles, X } from 'lucide-react';import type { TFunction } from 'i18next';import { useTranslation } from 'react-i18next';import { useChatStore, useSessionStore, useTodoStore } from '../../stores';import { AgentMode, MediaItem, Message, UserAnswer } from '../../types';+import type { HumanShareCommand } from '../../stores/sessionStore';import { MessageList } from './MessageList';import { ContextCompressionLines } from './MessageItem';import { InputArea } from './InputArea';@@ -20,6 +22,7 @@ import { HarnessProgressBar } from './HarnessProgressBar';import { AgentTeamActivityCard } from './TeamEventGroupDisplay';import { isTeamActivityMessage, parseTeamEventMessage } from './teamEventUtils';import { isTeamLeaderMember } from '../../utils/teamMemberAvatar';+import { TeamMemberAvatar } from '../TeamMemberAvatar';import './ChatPanel.css';export interface ChatHistoryPagerProps {@@ -192,6 +195,222 @@ function getShareExportTitle(return t('share.export');}+function getHumanShareStatusLabel(command: HumanShareCommand, t: TFunction): string {+ if (command.status === 'joined') return t('humanShare.status.joined');+ if (command.status === 'left') return t('humanShare.status.left');+ return t('humanShare.status.pending');+}++function getHumanShareStatusClass(command: HumanShareCommand): string {+ if (command.status === 'joined') return 'human-share-modal__badge human-share-modal__badge--joined';+ if (command.status === 'left') return 'human-share-modal__badge human-share-modal__badge--left';+ return 'human-share-modal__badge';+}++function HumanSharePanel({+ commands,+ onClose,+}: {+ commands: HumanShareCommand[];+ onClose: () => void;+}) {+ const { t } = useTranslation();+ const [copiedKey, setCopiedKey] = React.useState<string | null>(null);+ const sortedCommands = useMemo(+ () => [...commands].sort((a, b) => a.memberName.localeCompare(b.memberName)),+ [commands]+ );+ const joinedCount = sortedCommands.filter((command) => command.status === 'joined').length;+ const exitCommand =+ sortedCommands.find((command) => command.exitCommand)?.exitCommand ||+ (() => {+ const commandWithSessionRef = sortedCommands.find((command) => command.sessionRef);+ return commandWithSessionRef?.sessionRef ? `/exit ${commandWithSessionRef.sessionRef}` : '';+ })();+ const allJoined = sortedCommands.length > 0 && joinedCount === sortedCommands.length;++ useEffect(() => {+ const handleKeyDown = (event: KeyboardEvent) => {+ if (event.key === 'Escape') {+ onClose();+ }+ };++ document.addEventListener('keydown', handleKeyDown);+ return () => document.removeEventListener('keydown', handleKeyDown);+ }, [onClose]);++ const copyText = useCallback(async (key: string, text: string) => {+ if (!text) return;+ await navigator.clipboard.writeText(text);+ setCopiedKey(key);+ window.setTimeout(() => {+ setCopiedKey((current) => current === key ? null : current);+ }, 1200);+ }, []);++ return createPortal(+ <div className="human-share-modal-backdrop" role="presentation" onClick={onClose}>+ <section+ className="human-share-modal"+ role="dialog"+ aria-modal="true"+ aria-labelledby="human-share-title"+ onClick={(event) => event.stopPropagation()}+ >+ <div className="human-share-modal__header">+ <div>+ <div className="human-share-modal__title-row">+ <h2 id="human-share-title" className="human-share-modal__title">{t('humanShare.title')}</h2>+ </div>+ <p className="human-share-modal__summary">+ {allJoined+ ? t('humanShare.allJoined', { count: sortedCommands.length })+ : t('humanShare.waiting', { joined: joinedCount, total: sortedCommands.length })}+ </p>+ </div>+ <button type="button" className="human-share-modal__close" onClick={onClose} aria-label={t('common.close')}>+ <X size={18} />+ </button>+ </div>++ <div className="human-share-modal__body">+ <div className="human-share-modal__notice" role="note">+ <Info size={18} strokeWidth={2.4} />+ <span>{t('humanShare.instructionHint')}</span>+ </div>+ {sortedCommands.map((command) => {+ const displayName = command.displayName || command.memberName;+ const copied = copiedKey === `join:${command.memberName}`;+ const shouldShowJoinCommand = command.status !== 'joined' && Boolean(command.joinCommand);+ return (+ <section key={`${command.sessionId}:${command.memberName}`} className="human-share-modal__item">+ <div className="human-share-modal__member">+ <TeamMemberAvatar member={command.memberName} className="human-share-modal__avatar" />+ <div className="human-share-modal__member-copy">+ <div className="human-share-modal__member-name">{displayName}</div>+ {displayName !== command.memberName && (+ <div className="human-share-modal__member-id">{command.memberName}</div>+ )}+ </div>+ <span className={getHumanShareStatusClass(command)}>+ {getHumanShareStatusLabel(command, t)}+ </span>+ </div>+ {shouldShowJoinCommand ? (+ <div className="human-share-modal__command-row">+ <code className="human-share-modal__command">{command.joinCommand}</code>+ <button+ type="button"+ className="human-share-modal__copy"+ onClick={() => void copyText(`join:${command.memberName}`, command.joinCommand)}+ >+ {copied ? <CheckCircle2 size={15} /> : <Copy size={15} />}+ <span>{copied ? t('humanShare.copied') : t('humanShare.copy')}</span>+ </button>+ </div>+ ) : (+ <div+ className={`human-share-modal__command-note ${+ command.status === 'joined'+ ? 'human-share-modal__command-note--joined'+ : 'human-share-modal__command-note--pending'+ }`}+ >+ {command.status === 'joined' ? <CheckCircle2 size={15} /> : <ClipboardList size={15} />}+ <span>+ {command.status === 'joined'+ ? t('humanShare.joinedNote')+ : t('humanShare.commandPending')}+ </span>+ </div>+ )}+ </section>+ );+ })}++ {exitCommand && (+ <section className="human-share-modal__exit">+ <div className="human-share-modal__exit-title">{t('humanShare.exitTitle')}</div>+ <div className="human-share-modal__command-row">+ <code className="human-share-modal__command">{exitCommand}</code>+ <button+ type="button"+ className="human-share-modal__copy"+ onClick={() => void copyText('exit', exitCommand)}+ >+ {copiedKey === 'exit' ? <CheckCircle2 size={15} /> : <Copy size={15} />}+ <span>{copiedKey === 'exit' ? t('humanShare.copied') : t('humanShare.copy')}</span>+ </button>+ </div>+ </section>+ )}+ </div>+ </section>+ </div>,+ document.body+ );+}++function HumanShareCard({+ commands,+ onShare,+}: {+ commands: HumanShareCommand[];+ onShare: () => void;+}) {+ const { t } = useTranslation();+ const sortedCommands = useMemo(+ () => [...commands].sort((a, b) => a.memberName.localeCompare(b.memberName)),+ [commands]+ );+ const joinedCount = sortedCommands.filter((command) => command.status === 'joined').length;+ const pendingCount = sortedCommands.filter((command) => command.status !== 'joined').length;+ const previewMembers = sortedCommands.slice(0, 3).map((command) => command.displayName || command.memberName);++ if (sortedCommands.length === 0) {+ return null;+ }++ return (+ <section className="human-share-card" data-testid="human-share-card">+ <div className="human-share-card__icon" aria-hidden="true">+ <ClipboardList size={18} strokeWidth={2} />+ </div>+ <div className="human-share-card__content">+ <div className="human-share-card__title">{t('humanShare.cardTitle')}</div>+ <div className="human-share-card__summary">+ {t('humanShare.cardSummary', {+ pending: pendingCount,+ joined: joinedCount,+ total: sortedCommands.length,+ })}+ </div>+ <div className="human-share-card__members">+ {previewMembers.map((member) => (+ <span key={member} className="human-share-card__member-pill">+ <TeamMemberAvatar member={member} className="human-share-card__avatar" />+ <span>{member}</span>+ </span>+ ))}+ {sortedCommands.length > previewMembers.length ? (+ <span className="human-share-card__more">+{sortedCommands.length - previewMembers.length}</span>+ ) : null}+ </div>+ </div>+ <button+ type="button"+ className="human-share-card__button"+ data-testid="human-share-card-trigger"+ onClick={onShare}+ >+ <Share2 size={15} strokeWidth={2} />+ <span>{t('humanShare.shareButton')}</span>+ </button>+ </section>+ );+}+export function ChatPanel({onSendMessage,onPersistMedia,@@ -215,7 +434,7 @@ export function ChatPanel({contextCompressionRuntime,contextCompressionSummary,} = useChatStore();- const { mode } = useSessionStore();+ const { mode, teamHumanShareCommands } = useSessionStore();const messagesEndRef = useRef<HTMLDivElement>(null);const scrollContainerRef = useRef<HTMLDivElement>(null);const prependScrollSnapRef = useRef<{ sh: number; st: number } | null>(null);@@ -233,6 +452,8 @@ export function ChatPanel({];const shouldShowShareExport = Boolean(onExportShare && hasConversation);const shareExportTitle = getShareExportTitle(t, isExportingShare, canExportShare);+ const shouldShowHumanShare = mode === 'team' && teamHumanShareCommands.length > 0;+ const [humanShareOpen, setHumanShareOpen] = React.useState(false);// 跟踪用户是否正在查看历史消息(不在底部)const userScrolledUpRef = useRef(false);@@ -276,7 +497,7 @@ export function ChatPanel({behavior: historyPager?.loadedPages === 1 ? 'auto' : 'smooth',});}- }, [messages, isThinking, contextCompressionRuntime, contextCompressionSummary, historyPager]);+ }, [messages, isThinking, contextCompressionRuntime, contextCompressionSummary, historyPager, teamHumanShareCommands.length]);useLayoutEffect(() => {if (!historyPager) {@@ -331,7 +552,7 @@ export function ChatPanel({{/* HarnessProgressBar - sticky header, doesn't scroll with messages */}<div className="sticky top-0 z-10 px-3 pt-2 bg-bg/95 backdrop-blur-sm">{shouldShowShareExport && (- <div className="mb-2 flex justify-end">+ <div className="mb-2 flex justify-end gap-2"><buttontype="button"className={`icon-btn share-export-btn ${isExportingShare ? 'share-export-btn--loading' : ''}`}@@ -357,6 +578,12 @@ export function ChatPanel({)}<HarnessProgressBar /></div>+ {humanShareOpen && (+ <HumanSharePanel+ commands={teamHumanShareCommands}+ onClose={() => setHumanShareOpen(false)}+ />+ )}<div ref={scrollContainerRef} className="chat-scroll flex-1 overflow-y-auto" onScroll={handleScroll} onWheel={handleWheel}><div className={chatContentClassName}>{hasConversation ? (@@ -372,6 +599,12 @@ export function ChatPanel({{hasTimelineContent ? (<><MessageList messages={messages} />+ {shouldShowHumanShare && (+ <HumanShareCard+ commands={teamHumanShareCommands}+ onShare={() => setHumanShareOpen(true)}+ />+ )}<SubtaskProgress />{/* 内联审批卡片(演进审批 & 权限审批共用) */}<InlineQuestionCard onSubmit={onUserAnswer} />diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.tsindex 99de8006e8..4d8a9917bc 100644--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts@@ -456,6 +456,50 @@ function stableEventId(...parts: unknown[]): string {.slice(0, 180);}+function getAgentRefId(payload: Record<string, unknown>): string | undefined {+ const direct = payload.agent_ref;+ if (isRecord(direct)) {+ const id = pickString(direct.id);+ if (id) {+ return id;+ }+ }+ const nestedPayload = payload.payload;+ if (isRecord(nestedPayload)) {+ const nested = nestedPayload.agent_ref;+ if (isRecord(nested)) {+ return pickString(nested.id);+ }+ }+ return undefined;+}++function upsertHumanShareCommandFromEvent(+ payload: Record<string, unknown>,+ event: { member_id?: string; name?: string; mode?: string; timestamp?: number }+): void {+ if (event.mode !== 'human' || !event.member_id) {+ return;+ }+ const sessionId = getPayloadSessionId(payload);+ if (!sessionId) {+ return;+ }+ const teamName = getAgentRefId(payload) || 'unknown';+ const sessionRef = `team_${teamName}_session_${sessionId}`;+ useSessionStore.getState().upsertTeamHumanShareCommand({+ memberName: event.member_id,+ displayName: event.name,+ sessionId,+ teamName,+ sessionRef,+ joinCommand: `/join ${sessionRef} as ${event.member_id}`,+ exitCommand: `/exit ${sessionRef}`,+ status: 'pending',+ updatedAt: event.timestamp || Date.now(),+ });+}+function stringifyCompact(value: unknown): string {if (typeof value === 'string') {return value;@@ -1501,6 +1545,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {const currentSessionStore = useSessionStore.getState();currentSessionStore.setTeamMembers([]);currentSessionStore.setTeamTaskEvents([]);+ currentSessionStore.setTeamHumanShareCommands([]);currentSessionStore.setTeamTasks([]);currentSessionStore.setTeamMemberExecutionEvents([]);currentSessionStore.clearAllTeamMemberContextCompressionStatus();@@ -1593,6 +1638,39 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {webClient.on('chat.final', ({ payload }) => {if (!shouldHandleSessionEvent(payload)) return;+ const memberAction = pickString(payload.member_action);+ const actionMemberName = pickString(payload.member_name);+ if (+ actionMemberName &&+ (memberAction === 'joined' || memberAction === 'left')+ ) {+ const sessionId = pickString(payload.session_id) || activeSessionIdRef.current || '';+ // 使用 upsert(若 spawned 事件尚未到达则创建占位,后续 spawned 事件会补全 teamName/sessionRef 等字段)+ useSessionStore.getState().upsertTeamHumanShareCommand({+ memberName: actionMemberName,+ displayName: pickString(payload.display_name),+ sessionId,+ teamName: '',+ sessionRef: '',+ joinCommand: '',+ exitCommand: '',+ status: memberAction === 'joined' ? 'joined' : 'left',+ sourceChannel: pickString(payload.source_channel),+ userId: pickString(payload.user_id),+ updatedAt: Date.now(),+ });+ const content = normalizeFinalContent(payload);+ if (content) {+ addMessage({+ id: `team-human-${memberAction}-${Date.now()}`,+ role: 'system',+ content,+ timestamp: normalizeEventTimestampIso(payload.timestamp),+ });+ }+ return;+ }+const currentMode = useSessionStore.getState().mode;const content = normalizeFinalContent(payload);@@ -2466,6 +2544,7 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {mode?: string;};const activeSessionId = getPayloadSessionId(payload) || activeSessionIdRef.current || undefined;+ upsertHumanShareCommandFromEvent(payload, e);if (e.type === 'team.member.shutdown' && e.member_id) {applyTeamMemberShutdown(e.member_id, activeSessionId);} else if (activeSessionId && clearedTeamPanelSessionRef.current === activeSessionId) {diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.jsonindex 2f0f673b08..4c2915e457 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json@@ -1555,6 +1555,26 @@"website": "Website: {{url}}","repository": "Repository: {{url}}"},+ "humanShare": {+ "trigger": "Invite members",+ "title": "Invite members",+ "cardTitle": "Invite members",+ "cardSummary": "{{pending}} pending, {{joined}}/{{total}} joined",+ "shareButton": "Invite members",+ "waiting": "{{joined}}/{{total}} joined. Team execution is not blocked.",+ "allJoined": "All {{count}} human members have joined",+ "instructionHint": "Members will join team tasks through the JiuwenSwarm platform configured for them and participate as their assigned identity.",+ "copy": "Copy",+ "copied": "Copied",+ "joinedNote": "This member has joined. No need to send the join command again.",+ "commandPending": "Waiting for member details. The join command will appear when ready.",+ "exitTitle": "Exit command",+ "status": {+ "pending": "Pending",+ "joined": "Joined",+ "left": "Left"+ }+ },"network": {"wsError": "WebSocket connection error","connectionClosedWithCode": "Connection closed ({{code}})",diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.jsonindex a5ac1e1305..01a81e7d27 100644--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json@@ -1554,6 +1554,26 @@"website": "官网地址:{{url}}","repository": "代码仓:{{url}}"},+ "humanShare": {+ "trigger": "邀请成员",+ "title": "邀请成员",+ "cardTitle": "邀请成员",+ "cardSummary": "待加入 {{pending}} 人,已加入 {{joined}}/{{total}}",+ "shareButton": "邀请成员",+ "waiting": "已加入 {{joined}}/{{total}},不阻塞团队继续运行",+ "allJoined": "{{count}} 个人类成员已全部加入",+ "instructionHint": "成员将会通过配置有JiuwenSwarm的平台,以被分配的身份参与团队任务。",+ "copy": "复制",+ "copied": "已复制",+ "joinedNote": "该成员已加入,无需再次发送加入指令",+ "commandPending": "正在等待成员信息同步,加入指令生成后会显示",+ "exitTitle": "退出指令",+ "status": {+ "pending": "待加入",+ "joined": "已加入",+ "left": "已离开"+ }+ },"network": {"wsError": "WebSocket 连接异常","connectionClosedWithCode": "连接已关闭 ({{code}})",diff --git a/jiuwenswarm/channels/web/frontend/src/stores/sessionStore.ts b/jiuwenswarm/channels/web/frontend/src/stores/sessionStore.tsindex 7be837f99b..fc4af80363 100644--- a/jiuwenswarm/channels/web/frontend/src/stores/sessionStore.ts+++ b/jiuwenswarm/channels/web/frontend/src/stores/sessionStore.ts@@ -191,6 +191,22 @@ interface TeamMember {mode?: string;}+export type HumanShareStatus = 'pending' | 'joined' | 'left';++export interface HumanShareCommand {+ memberName: string;+ displayName?: string;+ sessionId: string;+ teamName: string;+ sessionRef: string;+ joinCommand: string;+ exitCommand: string;+ status: HumanShareStatus;+ sourceChannel?: string;+ userId?: string;+ updatedAt: number;+}+export type TeamMemberExecutionEventKind =| 'final'| 'tool_call'@@ -233,6 +249,7 @@ interface SessionState {teamTasks: TeamTask[];teamMembers: TeamMember[];teamLeaderMemberIds: string[];+ teamHumanShareCommands: HumanShareCommand[];teamMemberExecutionEvents: TeamMemberExecutionEvent[];teamMemberContextCompression: Record<string, TeamMemberContextCompressionState>;teamHistoryMessages: Message[];@@ -269,6 +286,13 @@ interface SessionState {addTeamLeaderMemberId: (memberId: string) => void;addTeamMember: (member: TeamMember) => void;updateTeamMemberStatus: (memberId: string, newStatus: string, timestamp?: number) => void;+ setTeamHumanShareCommands: (commands: HumanShareCommand[]) => void;+ upsertTeamHumanShareCommand: (command: HumanShareCommand) => void;+ updateTeamHumanShareStatus: (+ memberName: string,+ status: HumanShareStatus,+ patch?: Partial<HumanShareCommand>+ ) => void;setTeamMemberExecutionEvents: (events: TeamMemberExecutionEvent[]) => void;addTeamMemberExecutionEvent: (event: TeamMemberExecutionEvent) => void;setTeamMemberContextCompressionStatus: (@@ -309,6 +333,7 @@ export const useSessionStore = create<SessionState>((set) => ({teamTasks: [],teamMembers: [],teamLeaderMemberIds: [],+ teamHumanShareCommands: [],teamMemberExecutionEvents: [],teamMemberContextCompression: {},teamHistoryMessages: [],@@ -612,6 +637,51 @@ export const useSessionStore = create<SessionState>((set) => ({return state;});},+ setTeamHumanShareCommands: (commands) => {+ set({ teamHumanShareCommands: commands });+ },+ upsertTeamHumanShareCommand: (command) => {+ set((state) => {+ const existingIndex = state.teamHumanShareCommands.findIndex(+ (item) => item.memberName === command.memberName && item.sessionId === command.sessionId+ );+ if (existingIndex >= 0) {+ const updated = [...state.teamHumanShareCommands];+ const existing = updated[existingIndex];+ updated[existingIndex] = {+ ...existing,+ ...command,+ displayName: command.displayName || existing.displayName,+ teamName: command.teamName || existing.teamName,+ sessionRef: command.sessionRef || existing.sessionRef,+ joinCommand: command.joinCommand || existing.joinCommand,+ exitCommand: command.exitCommand || existing.exitCommand,+ status:+ command.status === 'pending' && existing.status !== 'pending'+ ? existing.status+ : command.status,+ };+ return { teamHumanShareCommands: updated };+ }+ return { teamHumanShareCommands: [...state.teamHumanShareCommands, command] };+ });+ },+ updateTeamHumanShareStatus: (memberName, status, patch = {}) => {+ const normalizedMemberName = memberName.trim();+ if (!normalizedMemberName) return;+ set((state) => ({+ teamHumanShareCommands: state.teamHumanShareCommands.map((command) =>+ command.memberName === normalizedMemberName+ ? {+ ...command,+ ...patch,+ status,+ updatedAt: Date.now(),+ }+ : command+ ),+ }));+ },setTeamMemberExecutionEvents: (events) => {set({ teamMemberExecutionEvents: dedupeTeamMemberExecutionEvents(events).slice(0, 300) });},diff --git a/jiuwenswarm/cli/chat.py b/jiuwenswarm/cli/chat.pyindex 36044b3f9b..6b9b26b8f4 100644--- a/jiuwenswarm/cli/chat.py+++ b/jiuwenswarm/cli/chat.py@@ -320,6 +320,10 @@ def _build_request(args: argparse.Namespace, prompt: str) -> dict:"cwd": cwd,"project_dir": project_dir,"trusted_dirs": trusted_dirs,+ # V2: 显式发 agent_ref,支撑同 session 切 mode 不串窗(设计 §5.2 场景 2)。+ # gateway 用 (channel, scope, agent_ref) 3 元组注册/查找,AgentServer 回带+ # 同值,切换 mode 后旧 agent 的延迟 chunk 不会错路由到新 agent 的 UI 区块。+ "agent_ref": {"mode": args.mode, "id": "default"},},}diff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.pyindex 696ea6b449..4595fe8c9a 100644--- a/jiuwenswarm/common/config.py+++ b/jiuwenswarm/common/config.py@@ -5,6 +5,7 @@ import loggingimport osimport reimport sys+import timeimport uuidfrom copy import deepcopyfrom pathlib import Path@@ -103,15 +104,35 @@ def _normalize_config(config: dict[str, Any] | None) -> None:mcc = react.get("model_client_config")if isinstance(mcc, dict) and "custom_headers" in mcc:mcc["custom_headers"] = _parse_custom_headers(mcc["custom_headers"])- # web channel enable send file tool default+ # send_file 工具默认开关:web/feishu/xiaoyi 顶层缺 send_file_allowed 时兜底 True。channels = config.get("channels", {})- if channels.get("web", {}).get("send_file_allowed") is None:- channels["web"] = {"send_file_allowed": True}+ for _ch in ("web", "feishu", "xiaoyi"):+ _ch_conf = channels.get(_ch)+ if not isinstance(_ch_conf, dict):+ _ch_conf = {}+ channels[_ch] = _ch_conf+ if _ch_conf.get("send_file_allowed") is None:+ _ch_conf["send_file_allowed"] = True+++def _read_with_retry(filepath: Path, max_attempts: int = 3) -> dict[str, Any]:+ """读取 YAML,遇解析错误重试(应对跨进程写竞态)。"""+ for attempt in range(max_attempts):+ try:+ with open(filepath, "r", encoding="utf-8") as f:+ return yaml.safe_load(f) or {}+ except yaml.YAMLError:+ if attempt < max_attempts - 1:+ time.sleep(0.05 * (attempt + 1))+ continue+ raise+ return {}def get_config():- with open(get_config_file(), "r", encoding="utf-8") as f:- config_base = yaml.safe_load(f) or {}+ """读取并解析 config.yaml(锁保护 + 跨进程降级重试)。"""+ config_base = _read_with_retry(get_config_file())+ # resolve_env_vars 和 _normalize_config 只操作内存数据,在锁外执行以缩短锁持有时间config_base = resolve_env_vars(config_base)_normalize_config(config_base)@@ -120,8 +141,7 @@ def get_config():def get_config_raw():"""读 config.yaml 原始内容(不解析环境变量),供局部更新后写回。"""- with open(CONFIG_YAML_PATH, "r", encoding="utf-8") as f:- return yaml.safe_load(f) or {}+ return _read_with_retry(CONFIG_YAML_PATH)def set_config(config):@@ -211,15 +231,24 @@ def load_yaml_round_trip(config_path: Path):def dump_yaml_round_trip(config_path: Path, data: Any) -> None:- """ruamel 写回 config,保留注释与格式。"""+ """ruamel 写回 config,保留注释与格式(原子写入:临时文件 + os.replace)。"""rt = YAML()rt.preserve_quotes = Truert.default_flow_style = False# mapping 2 空格;list 用 sequence=4 + offset=2 保证 dash 前有 2 空格(tools: 下 - todo),否则 list 会变成无缩进rt.indent(mapping=2, sequence=4, offset=2)rt.width = 4096- with open(config_path, "w", encoding="utf-8") as f:- rt.dump(data, f)+ tmp = config_path.with_name(f"{config_path.stem}.{uuid.uuid4().hex}.yaml.tmp")+ try:+ with open(tmp, "w", encoding="utf-8") as f:+ rt.dump(data, f)+ os.replace(tmp, config_path)+ except BaseException:+ try:+ os.unlink(tmp)+ except FileNotFoundError:+ pass+ raise# Backward-compat aliases — downstream modules import the underscore-prefixed names@@ -260,9 +289,13 @@ def update_channel_in_config(channel_id: str, conf: dict[str, Any]) -> None:def update_channel_subsection_in_config(channel_id: str,subsection_id: str,- conf: dict[str, Any],+ conf: dict[str, Any] | list[Any] | Any,) -> None:- """更新 channels[channel_id][subsection_id] 并写回。"""+ """更新 channels[channel_id][subsection_id] 并写回。++ 若 ``conf`` 为 dict,则合并(partial update)到现有 subsection 中;+ 若为 list 或其他非 dict 类型,则整体替换 subsection。+ """data = load_yaml_round_trip(CONFIG_YAML_PATH)if "channels" not in data:data["channels"] = {}@@ -270,14 +303,80 @@ def update_channel_subsection_in_config(if channel_id not in channels:channels[channel_id] = {}section = channels[channel_id]- if subsection_id not in section:- section[subsection_id] = {}- subsection = section[subsection_id]- for k, v in conf.items():- subsection[k] = v++ if isinstance(conf, dict):+ # 合并(partial update)—— 用于 feishu_enterprise 按 bot 维度保存状态等场景+ if subsection_id not in section:+ section[subsection_id] = {}+ for k, v in conf.items():+ section[subsection_id][k] = v+ else:+ # 整体替换 —— 用于 apps 列表等非 dict 类型+ section[subsection_id] = conf+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)+++def replace_channel_subsection_with_cleanup(+ channel_id: str,+ subsection_id: str,+ conf: dict[str, Any] | list[Any] | Any,+ keep_keys: set[str],+) -> None:+ """整体替换 channels[channel_id][subsection_id] 并清理旧字段,一次 IO 完成。++ 写入 subsection 后,删除 channels[channel_id] 下不在 ``keep_keys`` 中的字段。+ 用于多应用模式下替换 apps 并清理旧平铺字段,避免两套数据源不一致。+ """+ data = load_yaml_round_trip(CONFIG_YAML_PATH)+ if "channels" not in data:+ data["channels"] = {}+ channels = data["channels"]+ if channel_id not in channels:+ channels[channel_id] = {}+ section = channels[channel_id]++ section[subsection_id] = conf++ for k in list(section.keys()):+ if k not in keep_keys:+ del section[k]+dump_yaml_round_trip(CONFIG_YAML_PATH, data)+def update_channel_app_field(+ channel_id: str,+ app_identifier: str,+ field_values: dict[str, Any],+ *,+ app_id_key: str = "app_id",+) -> bool:+ """更新 ``channels[channel_id].apps`` 列表中某个 app 条目的字段。++ 用于多应用模式下运行时状态(如 ``last_chat_id``、``bot_open_id``)写回+ 对应 app 条目,避免所有 app 争抢同一个平铺字段。++ Args:+ channel_id: 通道 ID,如 ``"feishu"`` / ``"xiaoyi"``。+ app_identifier: app 标识值,如 ``"cli_a"``。+ field_values: 要更新的字段 dict,如 ``{"last_chat_id": "oc_xxx"}``。+ app_id_key: 匹配 app 条目的键名,默认 ``"app_id"``。++ Returns:+ ``True`` 表示更新成功,``False`` 表示未找到匹配 app。+ """+ data = load_yaml_round_trip(CONFIG_YAML_PATH)+ apps = data.get("channels", {}).get(channel_id, {}).get("apps", [])+ if not isinstance(apps, list):+ return False+ for app in apps:+ if isinstance(app, dict) and app.get(app_id_key) == app_identifier:+ app.update(field_values)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)+ return True+ return False++def update_preferred_language_in_config(lang: str) -> None:"""只更新顶层 preferred_language 并写回。非法值回退为 zh,与 set_preferred_language_in_config_file 一致。"""normalized = str(lang or "zh").strip().lower()diff --git a/jiuwenswarm/common/e2a/agent_compat.py b/jiuwenswarm/common/e2a/agent_compat.pyindex 2257db87d0..3efc2b370c 100644--- a/jiuwenswarm/common/e2a/agent_compat.py+++ b/jiuwenswarm/common/e2a/agent_compat.py@@ -61,4 +61,6 @@ def e2a_to_agent_request(env: E2AEnvelope) -> AgentRequest:is_stream=bool(env.is_stream),timestamp=_e2a_timestamp_to_float(env.timestamp),metadata=metadata,+ # V2: 透传 agent_ref 到 AgentServer,供响应侧 chunk/response 回带(设计 §6.3)。+ agent_ref=env.agent_ref,)diff --git a/jiuwenswarm/common/e2a/gateway_normalize.py b/jiuwenswarm/common/e2a/gateway_normalize.pyindex 1b2e6321ee..cc6a86ea2c 100644--- a/jiuwenswarm/common/e2a/gateway_normalize.py+++ b/jiuwenswarm/common/e2a/gateway_normalize.py@@ -150,6 +150,13 @@ def message_to_e2a(msg: "Message") -> E2AEnvelope:metadata["group_digital_avatar"] = msg.group_digital_avatarif metadata:d["metadata"] = metadata++ # ── V2: 传递 agent_ref / app_id 到 E2A 线协议 ──+ if getattr(msg, "agent_ref", None):+ d["agent_ref"] = msg.agent_ref+ if getattr(msg, "app_id", None):+ d["app_id"] = msg.app_id+return E2AEnvelope.from_dict(d)@@ -273,6 +280,8 @@ def e2a_response_from_agent_response(metadata=meta,identity_origin=IdentityOrigin.AGENT,is_stream=False,+ # V2: 非流式响应回带 agent_ref,与流式 chunk 对称(设计 §6.3)。+ agent_ref=getattr(resp, "agent_ref", None),)@@ -305,6 +314,10 @@ def e2a_response_from_agent_chunk()pl = dict(chunk.payload) if chunk.payload else {}+ # ── 从 chunk 提取 agent_ref / metadata(V2 路由用)──+ _chunk_agent_ref: dict | None = getattr(chunk, "agent_ref", None)+ _chunk_metadata: dict = getattr(chunk, "metadata", None) or {}+if chunk.is_complete and pl == {"is_complete": True}:return E2AResponse(protocol_version=E2A_PROTOCOL_VERSION,@@ -320,6 +333,8 @@ def e2a_response_from_agent_chunk(channel=chunk.channel_id or None,identity_origin=IdentityOrigin.AGENT,is_stream=is_stream,+ agent_ref=_chunk_agent_ref,+ metadata=_chunk_metadata,)if chunk.is_complete and pl.get("event_type") == "chat.error":@@ -341,6 +356,8 @@ def e2a_response_from_agent_chunk(channel=chunk.channel_id or None,identity_origin=IdentityOrigin.AGENT,is_stream=is_stream,+ agent_ref=_chunk_agent_ref,+ metadata=_chunk_metadata,)if chunk.is_complete:@@ -358,6 +375,8 @@ def e2a_response_from_agent_chunk(channel=chunk.channel_id or None,identity_origin=IdentityOrigin.AGENT,is_stream=is_stream,+ agent_ref=_chunk_agent_ref,+ metadata=_chunk_metadata,)event_type = pl.get("event_type")@@ -396,6 +415,8 @@ def e2a_response_from_agent_chunk(channel=chunk.channel_id or None,identity_origin=IdentityOrigin.AGENT,is_stream=is_stream,+ agent_ref=_chunk_agent_ref,+ metadata=_chunk_metadata,)@@ -461,6 +482,10 @@ def e2a_response_to_agent_chunk(e2a: E2AResponse) -> "AgentResponseChunk":body = dict(e2a.body or {})kind = e2a.response_kind+ # ── V2: 从 E2A 响应提取 agent_ref / metadata ──+ _agent_ref: dict | None = getattr(e2a, "agent_ref", None) or None+ _meta: dict | None = dict(e2a.metadata) if e2a.metadata else None+if kind == E2A_RESPONSE_KIND_E2A_COMPLETE and e2a.is_final:res = body.get("result")@@ -472,14 +497,14 @@ def e2a_response_to_agent_chunk(e2a: E2AResponse) -> "AgentResponseChunk":return list(b.keys()) == ["result"]if _empty_complete_marker(body, res):- return AgentResponseChunk(+ return AgentResponseChunk(agent_ref=_agent_ref, metadata=_meta,request_id=rid,channel_id=ch,payload={"is_complete": True},is_complete=True,)pl = dict(res) if isinstance(res, dict) else {}- return AgentResponseChunk(+ return AgentResponseChunk(agent_ref=_agent_ref, metadata=_meta,request_id=rid,channel_id=ch,payload=pl,@@ -489,7 +514,7 @@ def e2a_response_to_agent_chunk(e2a: E2AResponse) -> "AgentResponseChunk":if kind == E2A_RESPONSE_KIND_E2A_ERROR and e2a.is_final:det = body.get("details")pl = dict(det) if isinstance(det, dict) else dict(body)- return AgentResponseChunk(+ return AgentResponseChunk(agent_ref=_agent_ref, metadata=_meta,request_id=rid,channel_id=ch,payload=pl,@@ -515,7 +540,7 @@ def e2a_response_to_agent_chunk(e2a: E2AResponse) -> "AgentResponseChunk":_val = body.get(_key)if _val is not None:pl[_key] = _val- return AgentResponseChunk(+ return AgentResponseChunk(agent_ref=_agent_ref, metadata=_meta,request_id=rid,channel_id=ch,payload=pl,@@ -532,7 +557,7 @@ def e2a_response_to_agent_chunk(e2a: E2AResponse) -> "AgentResponseChunk":pl2["content"] = deltaif et is not None and "event_type" not in pl2:pl2["event_type"] = et- return AgentResponseChunk(+ return AgentResponseChunk(agent_ref=_agent_ref, metadata=_meta,request_id=rid,channel_id=ch,payload=pl2,@@ -547,7 +572,7 @@ def e2a_response_to_agent_chunk(e2a: E2AResponse) -> "AgentResponseChunk":"data": body.get("data"),"message": body.get("message"),}- return AgentResponseChunk(+ return AgentResponseChunk(agent_ref=_agent_ref, metadata=_meta,request_id=rid,channel_id=ch,payload=body_payload,@@ -555,7 +580,7 @@ def e2a_response_to_agent_chunk(e2a: E2AResponse) -> "AgentResponseChunk":)if kind == E2A_RESPONSE_KIND_ACP_OUTPUT_REQUEST:- return AgentResponseChunk(+ return AgentResponseChunk(agent_ref=_agent_ref, metadata=_meta,request_id=rid,channel_id=ch,payload={@@ -566,7 +591,7 @@ def e2a_response_to_agent_chunk(e2a: E2AResponse) -> "AgentResponseChunk":)if kind == E2A_RESPONSE_KIND_PLAN_APPROVAL_REQUIRED:- return AgentResponseChunk(+ return AgentResponseChunk(agent_ref=_agent_ref, metadata=_meta,request_id=rid,channel_id=ch,payload={diff --git a/jiuwenswarm/common/e2a/models.py b/jiuwenswarm/common/e2a/models.pyindex f461cfc1f0..c624b25967 100644--- a/jiuwenswarm/common/e2a/models.py+++ b/jiuwenswarm/common/e2a/models.py@@ -122,6 +122,7 @@ class E2AEnvelope:identity_origin: IdentityOrigin = IdentityOrigin.USERchannel: str | None = Noneuser_id: str | None = None+ agent_ref: dict | None = Nonechat_id: str | None = Nonesource_agent_id: str | None = None@@ -191,6 +192,7 @@ class E2AResponse:identity_origin: IdentityOrigin = IdentityOrigin.AGENTchannel: str | None = Noneuser_id: str | None = None+ agent_ref: dict | None = Nonesource_agent_id: str | None = Nonemethod: str | None = None@@ -383,6 +385,10 @@ def _envelope_from_dict(data: dict[str, Any]) -> E2AEnvelope:identity_origin=origin,channel=ch,user_id=data.get("user_id"),+ # V2: agent_ref 全链路透传——入站反序列化须补读,否则 message_to_e2a+ # 写入 d["agent_ref"] 后被 from_dict 丢弃,AgentServer 永远收不到+ # (设计 §6.3 agent_ref 全程携带;§5.2 同人多窗 via agent_ref)。+ agent_ref=data.get("agent_ref"),chat_id=data.get("chat_id"),source_agent_id=data.get("source_agent_id"),method=raw_method,@@ -436,6 +442,7 @@ def _e2a_response_from_dict(data: dict[str, Any]) -> E2AResponse:identity_origin=origin,channel=ch,user_id=data.get("user_id"),+ agent_ref=data.get("agent_ref"),source_agent_id=data.get("source_agent_id"),method=data.get("method"),projections=dict(data.get("projections") or {}),diff --git a/jiuwenswarm/common/schema/agent.py b/jiuwenswarm/common/schema/agent.pyindex 98e3bc7192..b3dbeb4733 100644--- a/jiuwenswarm/common/schema/agent.py+++ b/jiuwenswarm/common/schema/agent.py@@ -79,6 +79,8 @@ class AgentRequest:metadata: dict[str, Any] | None = Noneenable_memory: bool | None = Nonepermission_context: PermissionContext | None = None+ # V2: AgentRef(mode, id),全链路透传供响应侧回带(设计 §6.3/§5.2)。+ agent_ref: Any = None@dataclass@@ -90,6 +92,8 @@ class AgentResponse:ok: bool = Truepayload: dict | None = Nonemetadata: dict[str, Any] | None = None+ # V2: 回带请求侧 agent_ref,供 gateway 非流式响应 3 元组路由(设计 §6.3)。+ agent_ref: Any = None@dataclass@@ -100,3 +104,5 @@ class AgentResponseChunk:channel_id: strpayload: dict | None = Noneis_complete: bool = False+ agent_ref: Any = None # AgentRef(mode, id), V2 新增+ metadata: dict = field(default_factory=dict) # fan_out_targets (V1 wire key, list[LogicalTarget])diff --git a/jiuwenswarm/common/schema/message.py b/jiuwenswarm/common/schema/message.pyindex b1f478cc70..a4ca51a0b7 100644--- a/jiuwenswarm/common/schema/message.py+++ b/jiuwenswarm/common/schema/message.py@@ -175,6 +175,7 @@ class ReqMethod(Enum):TEAM_SNAPSHOT = "team.snapshot"TEAM_HISTORY_GET = "team.history.get"+ TEAM_MEMBERS_GET = "team.members.get"# Harness package managementHARNESS_PACKAGES_GET = "harness.packages.get"@@ -277,7 +278,9 @@ class Message:provider: str | None = Nonechat_id: str | None = Noneuser_id: str | None = None- bot_id: str | None = None+ bot_id: str | None = None # 已弃用,请使用 app_id + agent_ref 替代+ app_id: str | None = None # V2: 应用实例标识,从 bot_id 拆出+ agent_ref: Any = None # V2: AgentRef(mode, id),后端智能体标识payload: dict | None = Nonereq_method: ReqMethod | None = Noneevent_type: EventType | None = Nonediff --git a/jiuwenswarm/gateway/app_gateway.py b/jiuwenswarm/gateway/app_gateway.pyindex 7e5234b5a9..3f7a5e5423 100644--- a/jiuwenswarm/gateway/app_gateway.py+++ b/jiuwenswarm/gateway/app_gateway.py@@ -124,9 +124,9 @@ def _normalize_gateway_message(msg):)-def _normalize_and_forward_message(msg, channel_manager) -> bool:+async def _normalize_and_forward_message(msg, channel_manager) -> bool:normalized = _normalize_gateway_message(msg)- channel_manager.deliver_to_message_handler(normalized)+ await channel_manager.deliver_to_message_handler(normalized)logger.info("[App] Gateway inbound -> MessageHandler: id=%s channel_id=%s", msg.id, msg.channel_id)return False@@ -288,6 +288,12 @@ class RouteConfig:cleanup_handler: Callable[..., Any] | None = Nonedisconnect_handler: Callable[..., Any] | None = Nonesession_bind_handler: Callable[..., Any] | None = None+ # V2: 委托 ws 注册的外部 Channel(如 tui 的 TuiChannel)。+ # GatewayServer 仍作 ws 宿主 + 入站帧解析,但把 ws + RoutingKey 委托注册进该+ # Channel 的五维索引(_clients_by_key / _ws_by_id),出站由 ChannelManager 派发+ # 到该 Channel.send(按 delivery.ws_id 物理寻址)。None 表示该 route 无需委托+ # (如 acp 自带 _session_to_client 反查,web 有独立 WebChannel 不经此路径)。+ ws_channel: Any = None@dataclass@@ -322,8 +328,11 @@ class GatewayServer:self._running = Falseself._on_message_cb = Noneself._clients: set[Any] = set()- self._request_to_client: dict[tuple[str, str], Any] = {}- self._session_to_client: dict[tuple[str, str], Any] = {}+ # V2: key 升级为 (channel_id, session_id, agent_ref_str|None),+ # 兼容旧 2-tuple key(agent_ref 为 None 时回退)。+ self._request_to_client: dict[tuple, Any] = {}+ self._session_to_client: dict[tuple, Any] = {}+ # ACP 延迟绑定:session 在握手期先挂起,等首个 agent 请求 promote。self._pending_session_clients: dict[tuple[str, str], Any] = {}self.message_handler_ref = Noneself._acp_bridge = AcpGatewayBridge(@@ -335,12 +344,32 @@ class GatewayServer:self._install_default_route_hooks()@staticmethod- def _client_route_key(channel_id: str | None, scoped_id: str | None) -> tuple[str, str] | None:+ def _client_route_key(+ channel_id: str | None,+ scoped_id: str | None,+ agent_ref: Any = None,+ ) -> tuple | None:+ """构造客户端路由键。++ V2: 可选 agent_ref 作为第三维,支撑同 session 多 agent_ref 共存(场景 2)。+ 传入 agent_ref 时返回 (channel_id, scoped_id, agent_ref_str) 三元组;+ 不传时返回 (channel_id, scoped_id) 二元组,兼容旧路径。+ """channel = str(channel_id or "").strip()scope = str(scoped_id or "").strip()if not channel or not scope:return None- return channel, scope+ if agent_ref is not None:+ ar_str = ""+ if hasattr(agent_ref, "mode") and hasattr(agent_ref, "id"):+ ar_str = f"{agent_ref.mode}:{agent_ref.id}"+ elif isinstance(agent_ref, dict):+ ar_str = f"{agent_ref.get('mode', '')}:{agent_ref.get('id', '')}"+ elif isinstance(agent_ref, str) and agent_ref.strip():+ ar_str = agent_ref.strip()+ if ar_str:+ return (channel, scope, ar_str)+ return (channel, scope)def _find_channel_clients(self, channel_id: str) -> list[Any]:return [@@ -348,24 +377,41 @@ class GatewayServer:if isinstance(key, tuple) and key[0] == channel_id and not getattr(client_ws, "closed", False)]- def get_active_session_ids(self, channel_id: str, exclude_ws: Any = None) -> set[str]:- """返回当前已绑定到活跃连接的 session_id 集合(排除 exclude_ws 自身)。-- 用于 /resume 冲突检测:当目标 session 已在另一个 TUI 窗口打开时,- 前端可据此给出提示而非切换 session。+ def _lookup_client(+ self,+ table: dict[tuple, Any],+ channel_id: str | None,+ scope: str | None,+ agent_ref: Any = None,+ ) -> Any | None:+ """按 (channel, scope, agent_ref?) 查找客户端 ws,2↔3 元组双向兜底。++ - 优先精确匹配(agent_ref 非空时 3 元组,否则 2 元组)。+ - 3 元组 MISS → 降级 2 元组(响应侧丢 agent_ref 时仍能命中)。+ - 2 元组 MISS → 升级扫描所有以 (channel, scope) 开头的 3 元组+ (注册侧有 agent_ref、查找侧丢 agent_ref 时仍能命中)。+ - 裸 scope 字符串兜底。+ 防御性双向兜底,避免链路某环节丢 agent_ref 导致响应 dropped(设计 §6.3)。"""- result: set[str] = set()- for key, ws in self._session_to_client.items():- if not isinstance(key, tuple) or len(key) < 2 or key[0] != channel_id:- continue- if ws is exclude_ws:- continue- if bool(getattr(ws, "closed", False)):- continue- sid = str(key[1] or "").strip()- if sid:- result.add(sid)- return result+ key = self._client_route_key(channel_id, scope, agent_ref)+ if key is None:+ return None+ ws = table.get(key)+ if ws is not None:+ return ws+ # 3 → 2 降级+ if len(key) >= 3:+ ws = table.get((key[0], key[1]))+ if ws is not None:+ return ws+ # 2 → 3 升级扫描+ if len(key) == 2:+ for k, v in table.items():+ # (channel, scope, agent_ref) 三元组,前两段与 (channel, scope) 匹配+ if isinstance(k, tuple) and len(k) == 3 and k[:2] == key:+ return v+ # 裸 scope 兜底+ return table.get(scope)def is_session_bound_to_client(self, channel_id: str, session_id: str, ws: Any) -> bool:session_key = self._client_route_key(channel_id, session_id)@@ -430,8 +476,8 @@ class GatewayServer:result = await resultreturn bool(result)- def _bind_acp_session_client(self, session_id: str, ws: Any) -> None:- session_key = self._client_route_key("acp", session_id)+ def _bind_acp_session_client(self, session_id: str, ws: Any, agent_ref: Any = None) -> None:+ session_key = self._client_route_key("acp", session_id, agent_ref)if session_key is not None:self._session_to_client[session_key] = ws@@ -623,47 +669,134 @@ class GatewayServer:self._server = Nonelogger.info("[App] Gateway server stopped")- async def send(self, msg) -> None:- request_ws = None- request_key = self._client_route_key(getattr(msg, "channel_id", None), getattr(msg, "id", None))- if request_key is not None:- request_ws = self._request_to_client.get(request_key)- if request_ws is None:- request_ws = self._request_to_client.get(request_key[1])-- routing_session_id = self._extract_routing_session_id(msg, include_top_level=True)- session_key = self._client_route_key(getattr(msg, "channel_id", None), routing_session_id)- session_ws = None- if session_key is not None:- session_ws = self._session_to_client.get(session_key)- if session_ws is None:- session_ws = self._session_to_client.get(session_key[1])-- ws = request_ws if self._ws_is_open(request_ws) else None- if ws is None and self._ws_is_open(session_ws):- ws = session_ws+ async def send(self, msg, *, routing_target: "RoutingTarget | None" = None) -> None:+ # V2: 提取 agent_ref,优先 3 元组查找,2↔3 双向兜底(_lookup_client)。+ _agent_ref = getattr(msg, "agent_ref", None) or None+ _send_cid = getattr(msg, "channel_id", None)+ _send_sid = getattr(msg, "session_id", None)+ _send_id = getattr(msg, "id", None)+ ws: Any = None+ # 三级级联 fallback 查找投递目标 ws:任一级命中可用(非 None 且未关闭)ws 即短路,+ # 不再执行后续更低优先级的查找。三级依次为:+ # 1) routing_target(team fan_out 投递,经 dispatch_to_session 调用)+ # 2) request_id 精确回响应(常规 res/event 回到发起请求的 ws)+ # 3) session_id 兜底(同 session 任意活跃 ws,或无 session_id 时广播)++ # ── 第 1 级:fan_out 投递(team 模式经 dispatch_to_session 调用)──+ # GatewayServer 不像 BaseWsChannel 维护 ws_id 物理索引,这里按+ # routing_target.routing_keys 的 session_id 维度查 _session_to_client,+ # 命中任一仍活跃的 ws 即投递。保证 TUI/ACP 误入 team 路径时 GodView/+ # mention fan_out 不会因签名不符而静默丢弃。+ if routing_target is not None:+ _rt_keys = getattr(routing_target, "routing_keys", None) or []+ for _rk in _rt_keys:+ _rk_sid = getattr(_rk, "session_id", None)+ if not _rk_sid:+ continue+ _cand = self._lookup_client(+ self._session_to_client,+ getattr(_rk, "channel_id", None) or _send_cid,+ _rk_sid,+ getattr(_rk, "agent_ref", None),+ )+ if _cand is not None and not bool(getattr(_cand, "closed", False)):+ ws = _cand+ break+ # ── 第 2 级:request_id 精确回响应(回到发起该请求的 ws)──+ if ws is None:+ ws = self._lookup_client(+ self._request_to_client,+ _send_cid,+ _send_id,+ _agent_ref,+ )+ # ── 第 3 级:session_id 兜底(同 session 任意活跃 ws)──+ # 前级返回 None 或已关闭的 ws 时,仍尝试按 session 路由。+ if ws is None or bool(getattr(ws, "closed", False)):+ ws = self._lookup_client(+ self._session_to_client,+ _send_cid,+ _send_sid,+ _agent_ref,+ )+ if ws is None or bool(getattr(ws, "closed", False)):+ if ws is None:+ channel_id = getattr(msg, "channel_id", None)+ # 多 TUI 窗口:有 session_id 时精确路由;无 session_id 时广播(如 cron 推送到 TUI)。+ if channel_id and channel_id != "acp":+ if msg.type == "res":+ payload_data = dict(msg.payload or {}) if isinstance(msg.payload, dict) else {}+ frame = {"type": "res", "id": msg.id, "ok": bool(msg.ok), "payload": payload_data}+ else:+ frame = _build_event_frame(msg)++ session_id = self._extract_routing_session_id(msg, include_top_level=False)+ if session_id:+ session_key = self._client_route_key(channel_id, session_id)+ if session_key:+ client = self._session_to_client.get(session_key)+ if client is not None and not bool(getattr(client, "closed", False)):+ data = json.dumps(frame, ensure_ascii=False)+ try:+ await client.send(data)+ except Exception:+ logger.debug(+ "[GatewayServer] session-routed send failed: session_id=%s",+ session_id,+ exc_info=True,+ )+ return+ elif not self._extract_routing_session_id(msg, include_top_level=True):+ clients = self._find_channel_clients(channel_id)+ if clients:+ data = json.dumps(frame, ensure_ascii=False)+ logger.info(+ "[GatewayServer] broadcast fallback (no session_id): "+ "channel_id=%s clients=%d id=%s type=%s",+ channel_id, len(clients), getattr(msg, "id", None), msg.type,+ )+ await asyncio.gather(+ *[c.send(data) for c in clients],+ return_exceptions=True,+ )+ return+ # delivery target 没注册上:附 sess_table_keys 便于反查为何反查不到 ws+ logger.warning(+ "[GatewayServer] message dropped: no WebSocket client found for"+ " channel_id=%s session_id=%s id=%s sess_table_keys=%s",+ getattr(msg, "channel_id", None),+ getattr(msg, "session_id", None),+ getattr(msg, "id", None),+ [str(k) for k in self._session_to_client.keys()],+ )+ else:+ logger.warning(+ "[GatewayServer] ws already closed, drop: channel_id=%s id=%s session_id=%s ws=%s",+ _send_cid, _send_id, _send_sid, hex(id(ws)),+ )+ returnif getattr(msg, "channel_id", None) == "acp":- if ws is not None and await self._acp_bridge.send_message(msg, ws):+ handled = await self._acp_bridge.send_message(msg, ws)+ if handled:return# 让 route 的 outbound_interceptor 有机会拦截- if ws is not None:- for route in self.config.routes.values():- if route.channel_id == msg.channel_id and route.outbound_interceptor is not None:- try:- handled = route.outbound_interceptor(msg, ws)- if asyncio.iscoroutine(handled):- handled = await handled- if handled:- return- except Exception:- logger.warning(- "GatewayServer outbound interceptor failed: channel_id=%s",- msg.channel_id,- exc_info=True,- )- break+ for route in self.config.routes.values():+ if route.channel_id == msg.channel_id and route.outbound_interceptor is not None:+ try:+ handled = route.outbound_interceptor(msg, ws)+ if asyncio.iscoroutine(handled):+ handled = await handled+ if handled:+ return+ except Exception:+ logger.warning(+ "GatewayServer outbound interceptor failed: channel_id=%s",+ msg.channel_id,+ exc_info=True,+ )+ breakif msg.type == "res":payload = dict(msg.payload or {}) if isinstance(msg.payload, dict) else {}@@ -675,58 +808,21 @@ class GatewayServer:}if not msg.ok:frame["error"] = str(payload.get("error") or "request failed")- else:- event_name = "chat.final"- if msg.event_type is not None:- event_name = msg.event_type.value-- if isinstance(msg.payload, dict):- payload = {**msg.payload}- payload.setdefault("session_id", msg.session_id)- else:- payload = {"session_id": msg.session_id, "content": str(msg.payload or "")}-- frame = {"type": "event", "event": event_name, "payload": payload}+ await ws.send(json.dumps(frame, ensure_ascii=False))+ return- seen_ws: set[int] = set()- for target in (request_ws, session_ws):- if target is None or id(target) in seen_ws:- continue- seen_ws.add(id(target))- sent = await self._send_frame_to_ws(- target,- frame,- channel_id=getattr(msg, "channel_id", None),- request_id=getattr(msg, "id", None),- session_id=routing_session_id,- )- if sent:- return+ event_name = "chat.final"+ if msg.event_type is not None:+ event_name = msg.event_type.value- channel_id = getattr(msg, "channel_id", None)- if channel_id and channel_id != "acp":- # 多 TUI 窗口:无 session_id 时广播(如 cron 推送到 TUI)。- if not self._extract_routing_session_id(msg, include_top_level=True):- clients = self._find_channel_clients(channel_id)- if clients:- data = json.dumps(frame, ensure_ascii=False)- logger.info(- "[GatewayServer] broadcast fallback (no session_id): "- "channel_id=%s clients=%d id=%s type=%s",- channel_id, len(clients), getattr(msg, "id", None), msg.type,- )- await asyncio.gather(- *[c.send(data) for c in clients],- return_exceptions=True,- )- return+ if isinstance(msg.payload, dict):+ payload = {**msg.payload}+ payload.setdefault("session_id", msg.session_id)+ else:+ payload = {"session_id": msg.session_id, "content": str(msg.payload or "")}- logger.warning(- "[GatewayServer] message dropped: no WebSocket client found for channel_id=%s session_id=%s id=%s",- getattr(msg, "channel_id", None),- routing_session_id,- getattr(msg, "id", None),- )+ frame = {"type": "event", "event": event_name, "payload": payload}+ await ws.send(json.dumps(frame, ensure_ascii=False))async def _connection_handler(self, ws: Any, path: str | None = None) -> None:raw_path = path if path is not None else getattr(ws, "path", "")@@ -783,6 +879,17 @@ class GatewayServer:]for session_key in stale_pending_session_keys:self._pending_session_clients.pop(session_key, None)+ # V2: 委托 ws_channel(tui 的 TuiChannel)摘除死 ws + 清 per-ws writer。+ # 放在 _session_to_client 清理之后、disconnect_handler 之前;ws_channel+ # 反查不依赖 _session_to_client,顺序无强约束,但先摘可避免后续投递命中死 ws。+ if route.ws_channel is not None:+ try:+ await route.ws_channel.unregister_ws(ws)+ except Exception:+ logger.warning(+ "GatewayServer delegate unregister_ws to ws_channel failed: path=%s",+ request_path, exc_info=True,+ )if route.disconnect_handler is not None:try:# Pass stale_request_keys so the handler can recover session_ids@@ -889,7 +996,18 @@ class GatewayServer:)return- request_key = self._client_route_key(route.channel_id, req_id)+ # V2: 提取 agent_ref 用于路由键(支撑场景 2 同 session 切 mode 不串窗)。+ # 客户端未发送 agent_ref 时不合成——保持 2 元组注册,与响应查找侧+ # (AgentServer 普通模式不回带 agent_ref → msg.agent_ref=None → 2 元组)+ # 对称,避免 3/2 元组不匹配导致响应消息被丢弃(设计 §1.1 非 team 零改动)。+ _agent_ref = params.get("agent_ref")++ request_key = self._client_route_key(route.channel_id, req_id, _agent_ref)+ # 升级 session_key 为 3 元组(含 agent_ref),与 _session_to_client 键一致。+ session_key = (+ self._client_route_key(route.channel_id, session_id, _agent_ref)+ if explicit_session_id else None+ )# 检测 session 是否已在其他窗口打开:若已绑定到另一个仍活跃的连接,# 拒绝当前请求,避免多窗口 session 冲突(事件路由串台、binding 被覆盖)。# 前端 session.list 的 active_in_window 标记是"事后快照",此处是实时防线。@@ -922,9 +1040,52 @@ class GatewayServer:params = dict(params)params.setdefault("mode", mode.value)+ # V2: agent_ref 全链路透传(阶段2)。+ # tui 客户端从不发 agent_ref(_agent_ref 恒 None)→ 按 mode/agent_id 合成 AgentRef,+ # 用于:(1) 委托 _register 的 RoutingKey.agent_ref;(2) msg.agent_ref 经 E2A 透传到+ # AgentServer,chunk 回带同 agent_ref;(3) _maybe_register_godview 用 msg.agent_ref 构造+ # GodView RoutingKey.agent_ref(与入站注册同源,routing_keys 兜底能命中)。+ # acp 等非 ws_channel route 不合成(保留原 _agent_ref,走各自路径)。+ from jiuwenswarm.gateway.routing.keys import AgentRef as _AgentRef++ _resolved_agent_ref = _agent_ref+ if route.ws_channel is not None and not isinstance(_resolved_agent_ref, _AgentRef):+ _agent_id_raw = str(params.get("agent_id") or "default").strip() or "default"+ _resolved_agent_ref = _AgentRef(mode=mode.value, id=_agent_id_raw)++ # V2: 委托 ws 注册进 route.ws_channel(tui 的 TuiChannel)的五维索引。+ # GatewayServer 仍保留 _session_to_client/_request_to_client 用于入站响应反查+ # (send_response / local handler 回包),但出站 chunk 的精确路由改由+ # TuiChannel 的 _ws_by_id(物理寻址)/ _clients_by_key(五维逻辑)承担。+ # 同步把 ws_id 注入 metadata,供 _maybe_register_godview 构造带真 ws_id 的+ # TuiDeliveryTarget(修掉原 tui _kind="group" + ws_id 恒空导致投递不到)。+ _ws_id_for_metadata = ""+ if route.ws_channel is not None:+ from jiuwenswarm.gateway.routing.keys import RoutingKey++ # user_id 取 "tui":与 _maybe_register_godview 的 _user 兜底(... or _ch)+ # 同源,保证 GodView 订阅的 RoutingKey.user_id 与此处入站注册一致。+ _tui_rk = RoutingKey(+ user_id="tui",+ channel_id=route.channel_id,+ app_id="default",+ agent_ref=_resolved_agent_ref,+ session_id=session_id,+ )+ try:+ await route.ws_channel.register_ws(ws, _tui_rk)+ _ws_id_for_metadata = getattr(ws, "_jiuwen_ws_id", "") or ""+ except Exception:+ logger.warning(+ "GatewayServer delegate _register to ws_channel failed: channel_id=%s session_id=%s",+ route.channel_id, session_id, exc_info=True,+ )+# 从 params 中提取 cwd/project_dir,注入到 metadata 中# cwd 供 message_handler 解析 @file 引用;project_dir 供 session.list 按项目过滤metadata = {"method": method}+ if _ws_id_for_metadata:+ metadata["ws_id"] = _ws_id_for_metadatacwd = params.get("cwd")if cwd and isinstance(cwd, str) and cwd.strip():metadata["cwd"] = cwd.strip()@@ -954,6 +1115,11 @@ class GatewayServer:mode=mode,metadata=metadata,is_stream=is_stream,+ # V2: 透传 agent_ref 到请求 Message,经 E2A 线协议传到 AgentServer,+ # 响应侧 chunk/response 回带,gateway 查找侧 3 元组匹配(设计 §6.3)。+ # 阶段2:tui ws_channel route 用合成的 _resolved_agent_ref(与 _register /+ # GodView 同源);非 ws_channel route 保留原 _agent_ref。+ agent_ref=_resolved_agent_ref,)if self._on_message_cb is not None:@@ -1035,6 +1201,7 @@ def _build_route_config_map(bindings: list[GatewayRouteBinding]) -> dict[str, Rocleanup_handler=binding.cleanup_handler,disconnect_handler=binding.disconnect_handler,session_bind_handler=binding.session_bind_handler,+ ws_channel=binding.ws_channel,)for binding in bindings}@@ -1075,12 +1242,17 @@ async def _run(_CONFIG_SET_ENV_MAP,_FORWARD_NO_LOCAL_HANDLER_METHODS,_FORWARD_REQ_METHODS,+ _normalize_feishu_conf,+ _normalize_xiaoyi_conf,_register_web_handlers,)from jiuwenswarm.gateway.channel_manager.tui.tui_connect import (+ CLI_FORWARD_NO_LOCAL_HANDLER_METHODS,+ CLI_FORWARD_REQ_METHODS,CliRouteBindParams,build_cli_route_binding,)+ from jiuwenswarm.gateway.channel_manager.tui.tui_channel import TuiChannel, TuiChannelConfigfrom jiuwenswarm.extensions.manager import ExtensionManagerfrom jiuwenswarm.extensions.registry import ExtensionRegistryfrom jiuwenswarm.common.updater import UpdaterService@@ -1277,6 +1449,7 @@ async def _run(return Falseweb_channel = None+ tui_channel = Noneweb_config = WebChannelConfig(enabled=True, host=web_host, port=web_port, path=web_path)web_channel = WebChannel(web_config, _DummyBus())@@ -1298,12 +1471,12 @@ async def _run(no_local_methods: set[str] | frozenset[str],source_label: str,):- def _norm_and_forward(msg: Message) -> bool:+ async def _norm_and_forward(msg: Message) -> bool:method_val = getattr(getattr(msg, "req_method", None), "value", None) or ""if method_val not in forward_methods:return Falsenormalized = _normalize_gateway_message(msg)- channel_manager.deliver_to_message_handler(normalized)+ await channel_manager.deliver_to_message_handler(normalized)logger.info("[App] %s 入站 -> MessageHandler: id=%s channel_id=%s", source_label, msg.id, msg.channel_id)if method_val in no_local_methods:return True@@ -1318,6 +1491,19 @@ async def _run()channel_manager.register_channel_with_inbound(web_channel, web_norm_and_forward)+ # ── V2: TUI 独立 Channel(出站契约 + 五维索引)──+ # GatewayServer 仍是 /tui ws 宿主 + 入站帧解析 + local handler 派发(install 仍挂+ # gateway_server);TuiChannel 只接管出站 send 与 ws 五维索引,被 GatewayServer+ # 在 forward 分支委托 register_ws/unregister_ws。移除原 register_external_channel("tui",+ # gateway_server),tui 出站不再走 GatewayServer.send(其 routing_target 反查缺五维索引)。+ tui_channel = TuiChannel(TuiChannelConfig(enabled=True), _DummyBus())+ tui_norm_and_forward = _make_norm_and_forward(+ CLI_FORWARD_REQ_METHODS,+ CLI_FORWARD_NO_LOCAL_HANDLER_METHODS,+ "TUI",+ )+ channel_manager.register_channel_with_inbound(tui_channel, tui_norm_and_forward)+acp_inbound_server = _InboundGatewayServer(lambda msg: _normalize_and_forward_message(msg, channel_manager))@@ -1339,6 +1525,7 @@ async def _run(path="/tui",channel_id="tui",cron_controller=cron_controller,+ ws_channel=tui_channel,)),]@@ -1353,7 +1540,12 @@ async def _run(gateway_server.message_handler_ref = message_handlerfor binding in route_bindings:route_config = gateway_server_config.routes[binding.path]- channel_manager.register_external_channel(route_config.channel_id, gateway_server)+ # tui 出站已由 TuiChannel 接管(register_channel_with_inbound),+ # 不再把 gateway_server 注册为 tui channel;acp 等仍走 gateway_server。+ # 但 install(register_cli_handlers 注册 local handler 如 _chat_send)+ # 仍须执行——local handler 依赖 gateway_server 上的 session/request 索引。+ if route_config.channel_id != "tui":+ channel_manager.register_external_channel(route_config.channel_id, gateway_server)if binding.install is not None:binding.install(gateway_server)gateway_server.on_message(acp_inbound_server.handle_message)@@ -1506,6 +1698,16 @@ async def _run(nonlocal _last_channels_confnonlocal feishu_enterprise_channels, feishu_enterprise_tasks+ # === 新增:入口归一化(必须在 _should_restart_channel 之前) ===+ if isinstance(conf, dict):+ feishu_raw = conf.get("feishu")+ if isinstance(feishu_raw, dict):+ conf["feishu"] = _normalize_feishu_conf(feishu_raw)+ xiaoyi_raw = conf.get("xiaoyi")+ if isinstance(xiaoyi_raw, dict):+ conf["xiaoyi"] = _normalize_xiaoyi_conf(xiaoyi_raw)+ # ==========================================================+restart_pending = channel_manager.pop_channel_restart_pending()changed_channels: list[str] = []for channel_name in [@@ -1531,33 +1733,54 @@ async def _run(_last_channels_conf = dict(conf or {})if "feishu" in changed_channels:- feishu_conf = conf.get("feishu") if isinstance(conf, dict) else None- await _stop_channel(feishu_channel, feishu_task, "feishu")+ feishu_conf = conf.get("feishu") if isinstance(conf, dict) else {}++ # ---- 停止旧 apps 实例(从 channel_manager 查找) ----+ # 先 pop 再停止,避免 _stop_channel 内部 unregister_channel(channel_id)+ # 批量删除后后续 key 访问抛 KeyError+ for ch in channel_manager.pop_channels_by_id("feishu"):+ await _stop_channel(ch, getattr(ch, "start_task", None), f"feishu_app[{ch.app_id}]")+ # 统一注销 adapter(所有 feishu app 共享 "feishu" 标识)+ im_inbound.unregister_adapter("feishu")+ im_outbound.unregister_adapter("feishu")++ # 单变量置空(不再使用,但保持 nonlocal 兼容)feishu_channel, feishu_task = None, None- if isinstance(feishu_conf, dict):- enabled, reason = _is_channel_enabled(feishu_conf, ["app_id", "app_secret"])- if not enabled:- logger.info("[App] channels.feishu.%s, FeishuChannel disabled", reason)- else:+ apps = feishu_conf.get("apps") or []+ if not apps:+ logger.info("[App] channels.feishu.apps empty, FeishuChannel disabled")+ else:+ for app in apps:+ if not app.get("enabled", True):+ continue+ enabled, reason = _is_channel_enabled(app, ["app_id", "app_secret"])+ if not enabled:+ logger.info("[App] channels.feishu.apps[].%s, skipping", reason)+ continue++ app_id = str(app.get("app_id") or "").strip()+ channel_id = "feishu"+feishu_config = FeishuConfig(enabled=True,- app_id=str(feishu_conf.get("app_id") or "").strip(),- app_secret=str(feishu_conf.get("app_secret") or "").strip(),- encrypt_key=str(feishu_conf.get("encrypt_key") or "").strip(),- verification_token=str(feishu_conf.get("verification_token") or "").strip(),- allow_from=feishu_conf.get("allow_from") or [],- enable_streaming=bool(feishu_conf.get("enable_streaming", True)),- chat_id=str(feishu_conf.get("chat_id") or "").strip(),- last_chat_id=str(feishu_conf.get("last_chat_id") or "").strip(),- last_open_id=str(feishu_conf.get("last_open_id") or "").strip(),- group_digital_avatar=bool(feishu_conf.get("group_digital_avatar", False)),- my_user_id=str(feishu_conf.get("my_user_id") or feishu_conf.get("my_open_id") or "").strip(),- bot_name=str(feishu_conf.get("bot_name") or "").strip(),- enable_memory=bool(feishu_conf.get("enable_memory", False)),- message_merge_window_ms=int(feishu_conf.get("message_merge_window_ms", 15000)),+ app_id=app_id,+ app_secret=str(app.get("app_secret") or "").strip(),+ encrypt_key=str(app.get("encrypt_key") or "").strip(),+ verification_token=str(app.get("verification_token") or "").strip(),+ allow_from=app.get("allow_from") or [],+ enable_streaming=bool(app.get("enable_streaming", True)),+ chat_id=str(app.get("chat_id") or "").strip(),+ channel_id=channel_id,+ last_chat_id=str(app.get("last_chat_id") or "").strip(),+ last_open_id=str(app.get("last_open_id") or "").strip(),+ group_digital_avatar=bool(app.get("group_digital_avatar", False)),+ my_user_id=str(app.get("my_user_id") or app.get("my_open_id") or "").strip(),+ bot_name=str(app.get("bot_name") or "").strip(),+ enable_memory=bool(app.get("enable_memory", False)),+ message_merge_window_ms=int(app.get("message_merge_window_ms", 15000)),)- # 数字分身:创建 adapter 并注册到 pipeline+ # 数字分身 adapter(共享 "feishu" key)feishu_adapter = Noneif feishu_config.group_digital_avatar:from jiuwenswarm.gateway.channel_manager.im_platforms.feishu.feishu_im_adapter import \@@ -1566,14 +1789,14 @@ async def _run(my_open_id=feishu_config.my_user_id,bot_name=feishu_config.bot_name,)- im_inbound.register_adapter("feishu", feishu_adapter)- im_outbound.register_adapter("feishu", feishu_adapter)- feishu_channel = FeishuChannel(feishu_config, _DummyBus(), im_platform_adapter=feishu_adapter)- channel_manager.register_channel(feishu_channel)- feishu_task = asyncio.create_task(feishu_channel.start(), name="feishu")- logger.info("[App] FeishuChannel registered from config.yaml.channels.feishu")- else:- logger.info("[App] channels.feishu missing or invalid, FeishuChannel disabled")+ im_inbound.register_adapter(channel_id, feishu_adapter)+ im_outbound.register_adapter(channel_id, feishu_adapter)++ channel = FeishuChannel(feishu_config, _DummyBus(), im_platform_adapter=feishu_adapter)+ channel_manager.register_channel(channel)+ task = asyncio.create_task(channel.start(), name=f"feishu-{app_id}")+ channel.start_task = task # 挂到 channel 对象上,不另存 dict+ logger.info("[App] FeishuChannel(app=%s) registered from channels.feishu.apps", app_id)if "feishu_enterprise" in changed_channels:for bot_key, task in list(feishu_enterprise_tasks.items()):@@ -1656,52 +1879,62 @@ async def _run()if "xiaoyi" in changed_channels:- xiaoyi_conf = conf.get("xiaoyi") if isinstance(conf, dict) else None- await _stop_channel(xiaoyi_channel, xiaoyi_task, "xiaoyi")+ xiaoyi_conf = conf.get("xiaoyi") if isinstance(conf, dict) else {}++ # ---- 停止旧 apps 实例(从 channel_manager 查找) ----+ # 先 pop 再停止,避免 _stop_channel 内部 unregister_channel(channel_id)+ # 批量删除后后续 key 访问抛 KeyError+ for ch in channel_manager.pop_channels_by_id("xiaoyi"):+ await _stop_channel(ch, getattr(ch, "start_task", None), f"xiaoyi_app[{ch.app_id}]")++ # 单变量置空(不再使用,但保持 nonlocal 兼容)xiaoyi_channel, xiaoyi_task = None, None- if isinstance(xiaoyi_conf, dict):- enabled, reason = _is_channel_enabled(xiaoyi_conf, ["ak", "sk", "agent_id"])- if not enabled:- logger.info("[App] channels.xiaoyi.%s, XiaoyiChannel disabled", reason)- else:- if xiaoyi_conf.get("mode") == "xiaoyi_claw":- xiaoyi_config = XiaoyiChannelConfig(- enabled=True,- mode=str(xiaoyi_conf.get("mode") or "xiaoyi_claw").strip(),- api_id=str(xiaoyi_conf.get("api_id") or "").strip(),- push_id=str(xiaoyi_conf.get("push_id") or "").strip(),- push_url=str(xiaoyi_conf.get("push_url") or "").strip(),- agent_id=str(xiaoyi_conf.get("agent_id") or "").strip(),- uid=str(xiaoyi_conf.get("uid") or "").strip(),- api_key=str(xiaoyi_conf.get("api_key") or "").strip(),- file_upload_url=str(xiaoyi_conf.get("file_upload_url") or "").strip(),- ws_url1=str(xiaoyi_conf.get("ws_url1")).strip(),- ws_url2=str(xiaoyi_conf.get("ws_url2")).strip(),- enable_streaming=bool(xiaoyi_conf.get("enable_streaming", True)),- )- else:- xiaoyi_config = XiaoyiChannelConfig(- enabled=True,- mode=str(xiaoyi_conf.get("mode") or "xiaoyi_channel").strip(),- ak=str(xiaoyi_conf.get("ak") or "").strip(),- sk=str(xiaoyi_conf.get("sk") or "").strip(),- api_id=str(xiaoyi_conf.get("api_id") or "").strip(),- push_id=str(xiaoyi_conf.get("push_id") or "").strip(),- push_url=str(xiaoyi_conf.get("push_url") or "").strip(),- agent_id=str(xiaoyi_conf.get("agent_id") or "").strip(),- ws_url1=str(xiaoyi_conf.get("ws_url1") or "").strip()- or "wss://hag.cloud.huawei.com/openclaw/v1/ws/link",- ws_url2=str(xiaoyi_conf.get("ws_url2") or "").strip()- or "wss://116.63.174.231/openclaw/v1/ws/link",- enable_streaming=bool(xiaoyi_conf.get("enable_streaming", True)),- )- xiaoyi_channel = XiaoyiChannel(xiaoyi_config, _DummyBus())- channel_manager.register_channel(xiaoyi_channel)- xiaoyi_task = asyncio.create_task(xiaoyi_channel.start(), name="xiaoyi")- logger.info("[App] XiaoyiChannel registered from config.yaml.channels.xiaoyi")+ apps = xiaoyi_conf.get("apps") or []+ if not apps:+ logger.info("[App] channels.xiaoyi.apps empty, XiaoyiChannel disabled")else:- logger.info("[App] channels.xiaoyi missing or invalid, XiaoyiChannel disabled")+ for app in apps:+ if not app.get("enabled", True):+ continue+ enabled, reason = _is_channel_enabled(app, ["ak", "sk", "agent_id"])+ if not enabled:+ logger.info("[App] channels.xiaoyi.apps[].%s, skipping", reason)+ continue++ api_id = str(app.get("api_id") or "").strip()+ is_default = app.get("is_default", False) or len(apps) == 1+ if not api_id and not is_default:+ logger.warning(+ "[App] channels.xiaoyi.apps[].api_id required for non-default, skipping"+ )+ continue++ channel_id = "xiaoyi"+ config = XiaoyiChannelConfig(+ enabled=True,+ channel_id=channel_id,+ mode=str(app.get("mode") or "xiaoyi_channel").strip(),+ ak=str(app.get("ak") or "").strip(),+ sk=str(app.get("sk") or "").strip(),+ agent_id=str(app.get("agent_id") or "").strip(),+ api_id=api_id,+ enable_streaming=bool(app.get("enable_streaming", True)),+ # 以下字段 _normalize_xiaoyi_conf 会自动填充缺省值,+ # 此处显式读取以兼容直接使用 apps 格式的场景+ ws_url1=str(app.get("ws_url1") or "").strip(),+ ws_url2=str(app.get("ws_url2") or "").strip(),+ uid=str(app.get("uid") or "").strip(),+ api_key=str(app.get("api_key") or "").strip(),+ push_id=str(app.get("push_id") or "").strip(),+ push_url=str(app.get("push_url") or "").strip(),+ file_upload_url=str(app.get("file_upload_url") or "").strip(),+ )+ channel = XiaoyiChannel(config, _DummyBus())+ channel_manager.register_channel(channel)+ task = asyncio.create_task(channel.start(), name=f"xiaoyi-{api_id or 'default'}")+ channel.start_task = task # 挂到 channel 对象上,不另存 dict+ logger.info("[App] XiaoyiChannel(api_id=%s) from channels.xiaoyi.apps", api_id or "default")if "dingtalk" in changed_channels:dingtalk_conf = conf.get("dingtalk") if isinstance(conf, dict) else None@@ -1958,6 +2191,8 @@ async def _run(passawait gateway_server.stop()await acp_inbound_server.stop()+ if tui_channel is not None:+ await tui_channel.stop()if web_task is not None:web_task.cancel()try:@@ -1990,6 +2225,18 @@ async def _run(except asyncio.CancelledError:passawait xiaoyi_channel.stop()+ # ---- 从 channel_manager 清理所有动态注册的 channel 实例 ----+ for _cid in ("feishu", "xiaoyi"):+ for ch in channel_manager.pop_channels_by_id(_cid):+ task = getattr(ch, "start_task", None)+ if task is not None:+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass+ await ch.stop()+ # -----------------------------------if dingtalk_channel is not None and dingtalk_task is not None:dingtalk_task.cancel()try:diff --git a/jiuwenswarm/gateway/channel_manager/base.py b/jiuwenswarm/gateway/channel_manager/base.pyindex 938af5b597..ec032416c0 100644--- a/jiuwenswarm/gateway/channel_manager/base.py+++ b/jiuwenswarm/gateway/channel_manager/base.py@@ -9,6 +9,8 @@ from enum import Enumfrom typing import TYPE_CHECKING, Any, Callable, Awaitablefrom jiuwenswarm.common.schema.message import Message+from jiuwenswarm.gateway.routing.keys import DeliveryTarget+from jiuwenswarm.gateway.routing.session_sharing import RoutingTargetlogger = logging.getLogger(__name__)@@ -124,6 +126,7 @@ class BaseChannel(ABC):self.config = configself.bus = routerself._running = False+ self.start_task: Any = None@abstractmethodasync def start(self) -> None:@@ -142,12 +145,23 @@ class BaseChannel(ABC):"""停止Channel并清理资源"""pass- @abstractmethod- async def send(self, msg: Message) -> None:- """- 通过Channel发送消息+ async def send(+ self,+ msg: Message,+ *,+ routing_target: RoutingTarget | None = None,+ ) -> None:+ """通过 Channel 发送消息。++ V2 签名(2 参数):+ msg — 消息内容+ routing_target — RoutingTarget(自包含:intent + routing_keys + at_user_ids + delivery)"""- pass+ logger.warning(+ "[%s] send() not implemented, message dropped: id=%s",+ getattr(self, "channel_id", "unknown"),+ getattr(msg, "id", ""),+ )def is_allowed(self, sender_id: str) -> bool:"""diff --git a/jiuwenswarm/gateway/channel_manager/channel_manager.py b/jiuwenswarm/gateway/channel_manager/channel_manager.pyindex 5886183532..f726f002f7 100644--- a/jiuwenswarm/gateway/channel_manager/channel_manager.py+++ b/jiuwenswarm/gateway/channel_manager/channel_manager.py@@ -10,6 +10,8 @@ import timefrom abc import ABCfrom typing import TYPE_CHECKING, Any, Awaitable, Callable+from jiuwenswarm.gateway.routing.keys import ChannelKey+logger = logging.getLogger(__name__)if TYPE_CHECKING:@@ -34,7 +36,7 @@ class ChannelManager(ABC):on_config_updated: Callable[[dict[str, Any]], Awaitable[None]] | None = None,) -> None:self._message_handler = message_handler- self._channels: dict[str, "BaseChannel"] = {}+ self._channels: dict[ChannelKey, "BaseChannel"] = {}self._dispatch_task: asyncio.Task | None = Noneself._running = False# 统一管理 Channel 相关配置(例如 FeishuChannel / XiaoyiChannel 等)。@@ -43,6 +45,24 @@ class ChannelManager(ABC):self._on_config_updated = on_config_updated# 下一次 on_config_updated 时强制重启的 channel_id(例如微信解绑:YAML 中 bot_token 本就为空时配置 dict 对比不会变,但内存里仍有旧凭据)self._pending_channel_restart: set[str] = set()+ self._dispatch_diag_count: int = 0++ @staticmethod+ def _resolve_app_id(channel: Any) -> str:+ """从 channel 对象提取 app_id,兜底返回 'default'."""+ app_id = getattr(channel, "app_id", None)+ if app_id is None:+ config = getattr(channel, "config", None)+ if config is not None:+ app_id = getattr(config, "app_id", None)+ return app_id or "default"++ def _get_channel_by_id(self, channel_id: str) -> "BaseChannel | None":+ """根据 channel_id 字符串查找 Channel(O(n) 扫描,渐进式兼容用)。"""+ for key, ch in self._channels.items():+ if key.channel_id == channel_id:+ return ch+ return Nonedef mark_channel_restart_pending(self, channel_id: str) -> None:"""请求在下次 set_conf / set_config 触发配置应用时,无论配置快照是否变化都重启该 channel。"""@@ -56,21 +76,26 @@ class ChannelManager(ABC):return outdef _on_channel_message(self, msg: "Message") -> None:- """Channel 同步 on_message 回调:交给 MessageHandler 处理(入队并最终发往 AgentServer)."""+ """Channel on_message 回调:转异步交给 MessageHandler 处理。++ 注意: 回调本身保持同步签名,避免旧 Channel 调用方(如飞书 webhook)+ 产生 "coroutine was never awaited" 错误。+ """logger.info("[ChannelManager] Channel 消息 -> MessageHandler: id=%s channel_id=%s",msg.id, msg.channel_id,)- if not self._channels.get(msg.channel_id, None):+ if not self._get_channel_by_id(msg.channel_id):logger.info(f"[ChannelManager] Channel: {msg.channel_id} closed, cancel this user message.")return- self._message_handler.handle_message(msg)+ asyncio.create_task(self._message_handler.handle_message(msg))def register_channel(self, channel: "BaseChannel") -> None:"""注册 Channel,并为其注册「收到消息时转发给 MessageHandler」的回调."""cid = channel.channel_id- self._channels[cid] = channel+ key = ChannelKey(cid, self._resolve_app_id(channel))+ self._channels[key] = channelchannel.on_message(self._on_channel_message)logger.info("[ChannelManager] 已注册 Channel: channel_id=%s, 当前共 %d 个", cid, len(self._channels))@@ -80,30 +105,60 @@ class ChannelManager(ABC):on_message: Callable[["Message"], Any],) -> None:"""登记 Channel 并使用自定义入站回调(不替换为默认 _on_channel_message)。"""- self._channels[channel.channel_id] = channel+ key = ChannelKey(channel.channel_id, self._resolve_app_id(channel))+ self._channels[key] = channelchannel.on_message(on_message)- def register_external_channel(self, channel_id: str, channel: Any) -> None:+ def register_external_channel(self, channel_id: str | ChannelKey, channel: Any) -> None:"""登记一个已由外部完成入站装配的 channel 实例。"""- self._channels[channel_id] = channel+ if isinstance(channel_id, ChannelKey):+ key = channel_id+ else:+ key = ChannelKey(channel_id, self._resolve_app_id(channel))+ self._channels[key] = channel- def deliver_to_message_handler(self, msg: "Message") -> None:+ async def deliver_to_message_handler(self, msg: "Message") -> None:"""将消息交给 MessageHandler(供自定义入站路径使用)。"""- self._message_handler.handle_message(msg)+ await self._message_handler.handle_message(msg)- def unregister_channel(self, channel_id: str) -> None:+ def unregister_channel(self, channel_id: str | ChannelKey) -> None:"""注销指定 Channel."""- self._channels.pop(channel_id, None)+ if isinstance(channel_id, ChannelKey):+ self._channels.pop(channel_id, None)+ else:+ keys_to_remove = [k for k in self._channels if k.channel_id == channel_id]+ for k in keys_to_remove:+ del self._channels[k]logger.info("[ChannelManager] 已注销 Channel: channel_id=%s", channel_id)- def get_channel(self, channel_id: str) -> "BaseChannel | None":- """根据 channel_id 获取 Channel."""- return self._channels.get(channel_id)+ def get_channel(self, channel_id: str | ChannelKey) -> "BaseChannel | None":+ """根据 channel_id(字符串)或 ChannelKey 获取 Channel。"""+ if isinstance(channel_id, ChannelKey):+ return self._channels.get(channel_id)+ return self._get_channel_by_id(channel_id)++ def get_by_key(self, channel_key: ChannelKey) -> "BaseChannel | None":+ """按 ChannelKey 精确查找 Channel。"""+ return self._channels.get(channel_key)++ def pop_channels_by_id(self, channel_id: str) -> list["BaseChannel"]:+ """弹出并返回所有匹配 channel_id 的 Channel 实例(多应用场景下同一 channel_id 对应多个 app)。++ 先于 _stop_channel / unregister_channel 取出实例,避免后者批量删除字典后+ 后续按 key 访问抛 KeyError。+ """+ keys = [k for k in self._channels if k.channel_id == channel_id]+ out: list["BaseChannel"] = []+ for k in keys:+ ch = self._channels.pop(k, None)+ if ch is not None:+ out.append(ch)+ return out@propertydef enabled_channels(self) -> list[str]:- """当前已注册的 Channel 标识列表."""- return list(self._channels.keys())+ """当前已注册的 Channel 标识(channel_id 字符串)列表."""+ return [k.channel_id for k in self._channels.keys()]# ----- 配置管理接口 -----@@ -140,18 +195,100 @@ class ChannelManager(ABC):self._on_config_updated = callbackasync def _dispatch_robot_messages(self) -> None:- """出队派发循环:从 MessageHandler 消费 robot_messages,按 channel_id 投递到对应 Channel."""+ """出队派发循环:从 MessageHandler 消费 robot_messages,按 channel_id 投递到对应 Channel.++ V2: 支持通过 metadata.fan_out_targets 进行 team 模式多目标分发。+ """+ from jiuwenswarm.gateway.routing.session_sharing import dispatch_to_session+# 仅当 MessageHandler 提供 consume_robot_messages 时才能派发consume = getattr(self._message_handler, "consume_robot_messages", None)if not callable(consume):logger.warning("MessageHandler has no consume_robot_messages, robot_messages dispatch skipped")returnwhile self._running:+ msg = Nonetry:msg = await consume(timeout=1.0)if msg is None:continue- channel = self._channels.get(msg.channel_id)++ # payload event_type 供下方 _inject_file_delivery_fanout 判断文件/媒体注入+ _pl = getattr(msg, "payload", None) or {}+ _et = _pl.get("event_type", "") if isinstance(_pl, dict) else ""++ # ── 文件/媒体消息跨 channel 投递注入 ──+ # chat.file / chat.media 默认只投递到发起 channel(msg.channel_id),+ # team 模式下已 /join 的其他 channel(如飞书)收不到。这里在进入+ # fan_out 分发前,依据 SessionSharingRegistry 自动补齐 fan_out_targets,+ # 使文件能投递到所有已接入 channel(自动模式 godview + mention_all),或 send_file_targets 指定的目标。+ # helper 会按需写入 msg.metadata["fan_out_targets"],下方既有逻辑随之分发。+ await self._inject_file_delivery_fanout(msg, _et)++ # ── V2: fan_out_targets 分发 ──+ fan_out_raw = None+ if isinstance(msg.metadata, dict):+ fan_out_raw = msg.metadata.get("fan_out_targets")+ if fan_out_raw:+ # 阶段3: 派发循环 isinstance 取用——本进程内产出的 fan_out_targets+ # 直接挂完整 LogicalTarget 对象(join_exit_handlers 等),跳过+ # dict→LogicalTarget 重建;跨进程 E2A 过来的仍是 dict,按 dict 重建。+ from jiuwenswarm.gateway.routing.session_sharing import LogicalTarget+ fan_out: list[LogicalTarget] = []+ for item in fan_out_raw:+ if isinstance(item, LogicalTarget):+ fan_out.append(item)+ elif isinstance(item, dict):+ fan_out.append(LogicalTarget(+ intent=item.get("intent", "mention"),+ mention_all=bool(item.get("mention_all", False)),+ member_names=tuple(item.get("member_names", ())),+ speaker=item.get("speaker"),+ ))+ if fan_out:+ registry = self._message_handler.get_session_sharing_registry()+ try:+ await asyncio.wait_for(+ dispatch_to_session(+ msg, msg.session_id or "", fan_out, self, registry,+ ),+ timeout=15.0,+ )+ except asyncio.TimeoutError:+ logger.error(+ "[ChannelManager] dispatch_to_session timed out after 15s:"+ " session=%s id=%s — skipping to unblock dispatch loop",+ msg.session_id, msg.id,+ )+ except Exception:+ logger.exception(+ "[ChannelManager] dispatch_to_session failed:"+ " session=%s id=%s",+ msg.session_id, msg.id,+ )+ continue++ # ── 兜底:旧单 channel 投递(非 team 模式)──+ # V2: 优先按 ChannelKey 精确路由(多应用场景下同一 channel_id 对应多个 app)+ channel = None+ app_id = self._message_handler.resolve_app_id(msg)+ if app_id:+ channel = self.get_by_key(ChannelKey(msg.channel_id, app_id))+ if channel is not None:+ logger.debug(+ "[ChannelManager] 精确路由 ChannelKey(%s, %s) -> %s",+ msg.channel_id, app_id, getattr(channel, "channel_id", type(channel).__name__),+ )+ if channel is None:+ channel = self._get_channel_by_id(msg.channel_id)+ # 出站派发节点:定位"队列堆积/前端无输出"时,开启 DEBUG 可确认 chunk 是否+ # 被消费、命中哪个 channel 实例(tui 走 GatewayServer、web 走 WebChannel)。+ logger.debug(+ "[ChannelManager] dispatch robot_messages: channel_id=%s id=%s"+ " event_type=%s session_id=%s app_id=%s channel=%s channel_type=%s",+ msg.channel_id, msg.id, _et, getattr(msg, "session_id", None),+ app_id, bool(channel), type(channel).__name__ if channel else None,+ )if channel:try:await channel.send(msg)@@ -166,6 +303,12 @@ class ChannelManager(ABC):)except asyncio.CancelledError:break+ except Exception:+ logger.exception(+ "[ChannelManager] dispatch loop iteration error (continuing): id=%s channel_id=%s",+ getattr(msg, "id", None), getattr(msg, "channel_id", None),+ )+ continueasync def _notify_cron_delivery_error(self, original_msg: "Message", error: Exception) -> None:"""推送失败时,通过 web channel 发送 chat.error 通知前端。"""@@ -185,13 +328,94 @@ class ChannelManager(ABC):payload={"event_type": "chat.error", "error": error_text},event_type=EventType.CHAT_ERROR,)- web_channel = self._channels.get("web")+ web_channel = self._get_channel_by_id("web")if web_channel:try:await web_channel.send(error_msg)except Exception:logger.warning("[ChannelManager] 发送 cron 推送失败通知到 web 也失败了")+ async def _inject_file_delivery_fanout(self, msg: "Message", event_type_str: str) -> list | None:+ """为 chat.file / chat.media 自动注入 fan_out_targets,实现跨 channel 文件投递。++ 背景:send_file_to_user 产出的 chat.file 默认只投递到发起 channel(msg.channel_id),+ team 模式下已 /join 的其他 channel(如飞书/xiaoyi)收不到。本方法在 dispatch 进入+ fan_out 分发前,依据 SessionSharingRegistry 补齐投递目标:++ - 若 msg.metadata 已含 fan_out_targets(上游显式指定)→ 不干预。+ - 若 msg.metadata 含 send_file_targets(工具显式指定目标 channel/席位)→+ 按目标反查 Registry 的 *人类成员* 订阅(排除 GodView,避免 godview 全量广播泄漏到+ 其他 channel),构造 mention 目标;无匹配则回退 godview。+ - 否则(自动模式)→ 构造 [godview, mention_all] 双目标:godview 覆盖 web 等已注册+ GodView 的 channel;mention_all 覆盖所有 /join 的人类成员席位(飞书/xiaoyi 的+ reviewer-N)。dispatch_to_session 按物理容器去重,同一 channel 不会重复收文件。++ 非文件类事件、或 Registry 无订阅时返回 None(回退到单 channel 兜底,避免破坏纯 web 会话)。+ """+ if event_type_str not in ("chat.file", "chat.media"):+ return None+ if not isinstance(msg.metadata, dict):+ return None+ if msg.metadata.get("fan_out_targets"):+ # 上游已显式指定,保留原样+ return msg.metadata["fan_out_targets"]+ sid = msg.session_id or ""+ if not sid:+ return None+ try:+ registry = self._message_handler.get_session_sharing_registry()+ except Exception:+ return None+ all_subs = registry.lookup_all(sid) if registry else []+ if not all_subs:+ # 非团队/无订阅:保持单 channel 兜底,避免破坏纯 web 会话+ return None++ _godview_tgt = {"intent": "godview", "mention_all": False, "member_names": [], "speaker": None}+ _mention_all_tgt = {"intent": "mention", "mention_all": True, "member_names": [], "speaker": None}++ targets_hint = msg.metadata.get("send_file_targets")+ if isinstance(targets_hint, str):+ targets_hint = [targets_hint]+ if targets_hint and isinstance(targets_hint, list):+ # 显式目标:按 channel_id 或 member_name 反查 *人类成员* 订阅(排除 GodView)。+ # 排除 GodView 是为避免 lookup_member("GodView") 命中全部 godview 订阅,+ # 导致指定单 channel 时泄漏到其他 godview channel(如 web)。+ wanted = {str(x).strip() for x in targets_hint if str(x).strip()}+ matched_names: list[str] = []+ for sub in all_subs:+ if sub.is_godview:+ continue+ if sub.member_name in wanted or sub.routing_key.channel_id in wanted:+ if sub.member_name and sub.member_name not in matched_names:+ matched_names.append(sub.member_name)+ if not matched_names:+ logger.info(+ "[ChannelManager] file dispatch: send_file_targets=%s 无匹配人类成员订阅,回退 godview",+ wanted,+ )+ fan_out = [_godview_tgt]+ else:+ fan_out = [{+ "intent": "mention",+ "mention_all": False,+ "member_names": tuple(matched_names),+ "speaker": None,+ }]+ else:+ # 自动模式:godview 覆盖 web 等已注册 GodView 的 channel;+ # mention_all 覆盖所有 /join 的人类成员席位(飞书/xiaoyi 的 reviewer-N)。+ # 飞书/xiaoyi 的 GodView 订阅仅在用户后续发消息后才补注册,时序不可靠,+ # 故用 mention_all 兜底确保人类 channel 必达。+ fan_out = [_godview_tgt, _mention_all_tgt]++ msg.metadata["fan_out_targets"] = fan_out+ logger.info(+ "[ChannelManager] file dispatch: inject fan_out=%s session=%s id=%s origin_channel=%s",+ fan_out, sid, getattr(msg, "id", ""), msg.channel_id,+ )+ return fan_out+async def start_dispatch(self) -> None:"""启动出队派发任务(消费 MessageHandler.robot_messages 并发送到各 Channel)."""if self._dispatch_task is not None:diff --git a/jiuwenswarm/gateway/channel_manager/im_platforms/dingtalk/dingtalk_connect.py b/jiuwenswarm/gateway/channel_manager/im_platforms/dingtalk/dingtalk_connect.pyindex a6c6f6c264..4caad3a842 100644--- a/jiuwenswarm/gateway/channel_manager/im_platforms/dingtalk/dingtalk_connect.py+++ b/jiuwenswarm/gateway/channel_manager/im_platforms/dingtalk/dingtalk_connect.py@@ -16,6 +16,8 @@ from jiuwenswarm.gateway.channel_manager.base import RobotMessageRouter, BaseChafrom jiuwenswarm.gateway.channel_manager.im_platforms.dingtalk.dingtalk_file_service import DingTalkFileServicefrom jiuwenswarm.common.schema.message import Message, ReqMethodfrom jiuwenswarm.common.utils import get_agent_workspace_dir+from jiuwenswarm.gateway.routing.keys import DeliveryTarget+from jiuwenswarm.gateway.routing.session_sharing import RoutingTargetlogger = logging.getLogger(__name__)@@ -558,7 +560,10 @@ class DingTalkChannel(BaseChannel):except Exception as e:logger.error(f"发送钉钉消息时出错: {e}")- async def send(self, msg: Message) -> None:+ async def send(+ self, msg: Message,+ *, routing_target: RoutingTarget | None = None,+ ) -> None:"""通过钉钉发送消息"""token = await self._get_access_token()if not token:diff --git a/jiuwenswarm/gateway/channel_manager/im_platforms/discord/discord_connect.py b/jiuwenswarm/gateway/channel_manager/im_platforms/discord/discord_connect.pyindex c9f9b67ba1..0c70a4cf41 100644--- a/jiuwenswarm/gateway/channel_manager/im_platforms/discord/discord_connect.py+++ b/jiuwenswarm/gateway/channel_manager/im_platforms/discord/discord_connect.py@@ -8,6 +8,8 @@ from typing import Any, Callablefrom jiuwenswarm.gateway.channel_manager.base import BaseChannel, ChannelMetadata, RobotMessageRouterfrom jiuwenswarm.common.schema.message import EventType, Message, ReqMethod+from jiuwenswarm.gateway.routing.keys import DeliveryTarget+from jiuwenswarm.gateway.routing.session_sharing import RoutingTargetlogger = logging.getLogger(__name__)@@ -111,7 +113,7 @@ class DiscordChannel(BaseChannel):logger.warning("DiscordChannel stop failed: %s", e)logger.info("DiscordChannel stopped")- async def send(self, msg: Message) -> None:+ async def send(self, msg: Message, *, routing_target: RoutingTarget | None = None) -> None:if self._client is None or self._client.is_closed():returndiff --git a/jiuwenswarm/gateway/channel_manager/im_platforms/feishu/feishu_connect.py b/jiuwenswarm/gateway/channel_manager/im_platforms/feishu/feishu_connect.pyindex 78239ae812..f5cf2a0ca6 100644--- a/jiuwenswarm/gateway/channel_manager/im_platforms/feishu/feishu_connect.py+++ b/jiuwenswarm/gateway/channel_manager/im_platforms/feishu/feishu_connect.py@@ -1,32 +1,31 @@# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.-import loggingimport asyncioimport concurrent.futures-import os-import typesimport json+import logging+import osimport reimport threadingimport time+import typesfrom collections import OrderedDictfrom dataclasses import dataclassfrom typing import Any, Callableimport requestsfrom pydantic import BaseModel, Field--from jiuwenswarm.gateway.channel_manager.base import RobotMessageRouter, BaseChannel-from jiuwenswarm.gateway.channel_manager.im_platforms.platform_adapter.message import MessageStorefrom jiuwenswarm.common.schema.message import Message, ReqMethod, EventType+from jiuwenswarm.gateway.channel_manager.base import RobotMessageRouter, BaseChannelfrom jiuwenswarm.gateway.channel_manager.im_platforms.feishu.feishu_file_service import (FeishuFileService,is_image_file,is_audio_file,is_video_file,)--+from jiuwenswarm.gateway.channel_manager.im_platforms.platform_adapter.message import MessageStore+from jiuwenswarm.gateway.routing.keys import DeliveryTarget+from jiuwenswarm.gateway.routing.session_sharing import RoutingTargetlogger = logging.getLogger(__name__)@@ -47,6 +46,7 @@ class FeishuConfig(BaseModel):# 收消息时写入 config.yaml,用于无 metadata 时的回发兜底(与 session_id 解耦)last_chat_id: str = ""last_open_id: str = ""+ bot_open_id: str = "" # 运行时自动发现:bot 自身的 open_id(从 mention 提取)# 文件处理配置max_download_size: int = 100 * 1024 * 1024 # 最大下载文件大小(默认100MB)@@ -206,6 +206,11 @@ class FeishuChannel(BaseChannel):"""返回通道唯一标识符,用于ChannelManager注册与消息派发。"""return self._channel_id+ @property+ def app_id(self) -> str:+ """返回飞书应用ID,用于ChannelManager索引(ChannelKey.app_id)。"""+ return self.config.app_id or "default"+def on_message(self, callback: Callable[[Message], None]) -> None:"""注册消息回调函数,用于Gateway模式。@@ -269,6 +274,7 @@ class FeishuChannel(BaseChannel):chat_id=pi.origin_session_id,user_id=principal_id,bot_id=str(inbound.bot_id or self.config.app_id or ""),+ app_id=self.config.app_id,req_method=ReqMethod.CHAT_SEND,is_stream=False,metadata=_meta,@@ -294,6 +300,7 @@ class FeishuChannel(BaseChannel):chat_id=str(inbound.chat_id or ""),user_id=str(inbound.user_id or ""),bot_id=str(inbound.bot_id or self.config.app_id or ""),+ app_id=self.config.app_id,req_method=ReqMethod.CHAT_SEND,is_stream=_is_stream,metadata=_meta,@@ -357,6 +364,85 @@ class FeishuChannel(BaseChannel):config=self.config,workspace_dir=workspace_dir,)+ # bot_open_id 改为懒加载,在需要时才获取(见 _replace_mentions_with_names)++ def _fetch_bot_open_id(self) -> None:+ """+ 获取机器人自身的 open_id(用于 @bot 识别)。++ 通过飞书 bot/v3/info API 获取机器人信息。+ API: https://open.feishu.cn/open-apis/bot/v3/info+ """+ if self.config.bot_open_id: # 已经有值,跳过+ logger.debug("[_fetch_bot_open_id] bot_open_id 已配置: %s", self.config.bot_open_id)+ return++ try:+ # 1. 获取 tenant_access_token+ token_url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"+ token_resp = requests.post(+ token_url,+ json={+ "app_id": self.config.app_id,+ "app_secret": self.config.app_secret,+ },+ timeout=10,+ )+ token_data = token_resp.json()+ if token_data.get("code") != 0:+ logger.warning(+ "[_fetch_bot_open_id] 获取 tenant_access_token 失败: code=%s msg=%s",+ token_data.get("code"), token_data.get("msg")+ )+ return++ tenant_access_token = token_data.get("tenant_access_token")+ if not tenant_access_token:+ logger.warning("[_fetch_bot_open_id] tenant_access_token 为空")+ return++ # 2. 调用 bot/v3/info 获取机器人信息+ bot_info_url = "https://open.feishu.cn/open-apis/bot/v3/info"+ bot_resp = requests.get(+ bot_info_url,+ headers={"Authorization": f"Bearer {tenant_access_token}"},+ timeout=10,+ )+ bot_data = bot_resp.json()+ if bot_data.get("code") != 0:+ logger.warning(+ "[_fetch_bot_open_id] 获取机器人信息失败: code=%s msg=%s",+ bot_data.get("code"), bot_data.get("msg")+ )+ return++ bot_info = bot_data.get("bot", {})+ bot_open_id = bot_info.get("open_id", "")+ if bot_open_id:+ self.config.bot_open_id = bot_open_id+ logger.info(+ "[_fetch_bot_open_id] 成功获取机器人 open_id: %s (app_name=%s)",+ bot_open_id, bot_info.get("app_name", "")+ )+ # 持久化到配置文件(多应用模式下写入对应 app 条目)+ try:+ from jiuwenswarm.common.config import update_channel_app_field+ ok = update_channel_app_field(+ "feishu", self.config.app_id,+ {"bot_open_id": bot_open_id},+ )+ if not ok:+ logger.debug(+ "[_fetch_bot_open_id] 未找到 app=%s 条目,bot_open_id 未持久化",+ self.config.app_id,+ )+ except Exception as e:+ logger.debug("[_fetch_bot_open_id] 持久化 bot_open_id 失败(不影响运行): %s", e)+ else:+ logger.warning("[_fetch_bot_open_id] 机器人 open_id 为空")++ except Exception as e:+ logger.warning("[_fetch_bot_open_id] 获取机器人 open_id 异常: %s", e)def _start_websocket_in_thread(self) -> None:"""在独立线程中启动WebSocket客户端,避免事件循环冲突。"""@@ -594,25 +680,51 @@ class FeishuChannel(BaseChannel):or os.getenv("MY_USER_ID", "").strip())+ @staticmethod+ def _get_mention_open_id(mention: Any) -> str:+ """从飞书 mention 对象中提取 open_id。++ 飞书 SDK 的 mention 对象结构可能因版本不同而有差异:+ - mention.id.open_id (对象嵌套)+ - mention.id["open_id"] (字典嵌套)+ - mention.open_id (直接属性)+ - mention.id (字符串形式)++ Args:+ mention: 飞书 mention 对象++ Returns:+ str: open_id,如果无法获取则返回空字符串+ """+ # 方式1: mention.id 是对象,有 open_id 属性+ mention_id = getattr(mention, "id", None)+ if mention_id is not None:+ # 尝试从对象获取 open_id+ open_id = getattr(mention_id, "open_id", None)+ if open_id:+ return str(open_id).strip()+ # 尝试从字典获取 open_id+ if isinstance(mention_id, dict):+ return str(mention_id.get("open_id") or mention_id.get("id") or "").strip()+ # mention.id 本身可能是字符串形式的 open_id+ if isinstance(mention_id, str):+ return mention_id.strip()++ # 方式2: mention 直接有 open_id 属性+ open_id = getattr(mention, "open_id", None)+ if open_id:+ return str(open_id).strip()++ return ""+@staticmethoddef _extract_mentioned_users(message: Any) -> list[dict[str, str]]:"""从飞书消息事件中提取被 @ 用户的 open_id 和姓名。"""mentions = getattr(message, "mentions", None) or []users: list[dict[str, str]] = []for mention in mentions:- open_id = ""+ open_id = FeishuChannel._get_mention_open_id(mention)name = str(getattr(mention, "name", "") or "").strip()- mention_id = getattr(mention, "id", None)- if isinstance(mention_id, dict):- open_id = str(mention_id.get("open_id") or mention_id.get("id") or "").strip()- elif isinstance(mention_id, str):- open_id = mention_id.strip()- elif mention_id is not None:- nested_open_id = getattr(mention_id, "open_id", None)- if nested_open_id:- open_id = str(nested_open_id).strip()- else:- open_id = str(getattr(mention, "open_id", "") or "").strip()if open_id and all(user["open_id"] != open_id for user in users):users.append({"open_id": open_id, "name": name})return users@@ -629,54 +741,103 @@ class FeishuChannel(BaseChannel):def _replace_mentions_with_names(self, message: Any, text: str) -> str:"""将消息中的 @mentions 占位符(如 @_user_1)替换为真实用户名。- 当 @all 时,替换为数字分身用户本人的名字。- Args:- message: 飞书消息对象- text: 原始文本内容+ 处理规则:+ - @all → 替换为 @all(保留标记,用于后续判断 mention_all)+ - @机器人 → 剥除占位符/名字(便于后续命令解析,语义等同于 @team_leader)+ - @其他用户 → 替换为真实用户名- Returns:- str: 替换后的文本内容+ 群聊中 @机器人的名字从本次消息的 mentions 列表实时获取(不缓存、不配置)。+ 私聊(p2p)中飞书 SDK 不在 mentions 列表包含机器人,不做 @bot 剥除。"""mentions = getattr(message, "mentions", None) or []+ chat_type = str(getattr(message, "chat_type", "") or "")result = texttarget_user_open_id = self._get_target_user_open_id()- target_user_name = ""- if target_user_open_id:- target_user_name = self._resolve_user_display_name(target_user_open_id, "")- if "@_all" in result and target_user_name:- result = result.replace("@_all", f"@{target_user_name}")+ # 从本次消息的 mentions 列表实时提取 bot 名(局部变量,不缓存)+ bot_name_in_msg = ""- if not mentions:- return result+ # 懒加载:如果 bot_open_id 为空且有 mentions,尝试获取+ if not self.config.bot_open_id and mentions:+ self._fetch_bot_open_id()- for mention in mentions:- mention_key = getattr(mention, "key", None)+ # 有效的 bot open_id: 仅使用运行时自动发现的 bot_open_id+ # my_user_id(数字分身配置)不参与 bot 识别——bot 识别只靠 bot_open_id+ _effective_bot_open_id = self.config.bot_open_id or ""- if not mention_key:- mention_id = getattr(mention, "id", None)- if isinstance(mention_id, dict):- mention_key = mention_id.get("key", "")- elif isinstance(mention_id, str):- if "_" in mention_id:- mention_key = mention_id.split("_")[-1]+ logger.debug(+ "[_replace_mentions_with_names] chat_type=%s mentions_count=%d"+ " bot_open_id=%s",+ chat_type, len(mentions),+ _effective_bot_open_id or "",+ )- if not mention_key:- continue+ # 处理 @_all:从 mentions 列表判断 @所有人,替换占位符为 @all 标记+ # 飞书 @所有人 时 mentions 列表中有 key="_all" 的 mention 对象+ mention_all = False+ if mentions:+ for mention in mentions:+ mention_key = getattr(mention, "key", None)+ if mention_key == "_all":+ mention_all = True+ break+ # 兜底:mentions 列表可能不包含 @_all 的 mention 对象,从文本判断+ if not mention_all and "@_all" in result:+ mention_all = True+ if mention_all:+ result = result.replace("@_all", "@all")++ # 处理 mentions 列表+ if mentions:+ for mention in mentions:+ mention_key = getattr(mention, "key", None)++ if not mention_key:+ mention_id = getattr(mention, "id", None)+ if isinstance(mention_id, dict):+ mention_key = mention_id.get("key", "")+ elif isinstance(mention_id, str):+ if "_" in mention_id:+ mention_key = mention_id.split("_")[-1]++ if not mention_key:+ continue- name = str(getattr(mention, "name", "") or "").strip()- if not name:- bot_name = getattr(message, "bot_name", "") or ""- name = bot_name or mention_key+ mention_open_id = self._get_mention_open_id(mention)+ mention_name = str(getattr(mention, "name", "") or "").strip()- if mention_key.startswith("@"):- old_pattern = mention_key- else:- old_pattern = f"@{mention_key}"- new_pattern = f"@{name}"- result = result.replace(old_pattern, new_pattern)+ if mention_key.startswith("@"):+ old_pattern = mention_key+ else:+ old_pattern = f"@{mention_key}"++ # 判断是否 @ 的是机器人:+ # 仅靠 bot_open_id 精确匹配(运行时自动发现的值)。+ # 如果 bot_open_id 还没记住,则无法识别 @bot,+ # 占位符保留原样发给后端(由后端处理)。+ is_bot = bool(+ mention_open_id and _effective_bot_open_id and mention_open_id == _effective_bot_open_id+ )++ if is_bot:+ result = result.replace(old_pattern, "").strip()+ if mention_name:+ bot_name_in_msg = mention_name+ continue++ name = mention_name or mention_key+ new_pattern = f"@{name}"+ result = result.replace(old_pattern, new_pattern)++ # 剥除文本开头的 @bot名(手动输入场景:文本中直接包含 @bot名 而非 @_user_X 占位符)+ if bot_name_in_msg and result.startswith(f"@{bot_name_in_msg}"):+ result = result[len(f"@{bot_name_in_msg}"):].strip()+ logger.debug(+ "[_replace_mentions_with_names] stripped manual @bot: bot_name=%s result=%s",+ bot_name_in_msg, result[:200],+ )return result@@ -789,7 +950,7 @@ class FeishuChannel(BaseChannel):"- 更像'好的,我知道了,会准时参加会议''收到,我会跟进这件事'\n""- 不要照搬原文,保留核心动作即可\n\n""你私发给{name}的内容是:\n{content}"- ).format(+ ).format(name=target_name,content=content[:500],)@@ -959,9 +1120,11 @@ class FeishuChannel(BaseChannel):except Exception:message_content = str(message.content or "")- mention_all = "@_all" in message_content- if mention_all and target_user_open_id and target_user_open_id not in mentioned_open_ids:- mentioned_open_ids.append(target_user_open_id)+ mention_all = "@all" in message_content+ if mention_all:+ metadata["mention_all"] = True+ if target_user_open_id and target_user_open_id not in mentioned_open_ids:+ mentioned_open_ids.append(target_user_open_id)if mentioned_open_ids:metadata["mentioned_open_ids"] = mentioned_open_ids@@ -1301,6 +1464,8 @@ class FeishuChannel(BaseChannel):# 处理引用块elif stripped.startswith('> '):current_text.append(stripped[2:])+ elif stripped == '>':+ continue# 处理列表项elif stripped.startswith('- ') or stripped.startswith('* '):current_text.append(f"• {stripped[2:]}")@@ -1340,12 +1505,15 @@ class FeishuChannel(BaseChannel):}}- async def send(self, msg: Message) -> None:- """- 通过飞书发送消息。+ async def send(+ self,+ msg: Message,+ *,+ routing_target: RoutingTarget | None = None,+ ) -> None:+ """通过飞书发送消息。- Args:- msg: 要发送的消息对象+ V2: routing_target 为 team 模式分发元数据(内含 delivery + mention_member_ids)。"""if not self._api_client:logger.warning("飞书客户端未初始化")@@ -1360,6 +1528,15 @@ class FeishuChannel(BaseChannel):meta = dict(getattr(msg, "metadata", None) or {})+ # ── V2: routing_target 覆盖投递地址 ──+ route_delivery: DeliveryTarget | None = None+ route_mention_member_ids: list[str] = []+ route_mention_all: bool = False+ if routing_target is not None:+ route_delivery = routing_target.delivery+ route_mention_member_ids = list(routing_target.mention_member_ids or [])+ route_mention_all = routing_target.mention_all+# 跳过 reasoning 信息if msg.event_type == EventType.CHAT_REASONING:return@@ -1367,18 +1544,23 @@ class FeishuChannel(BaseChannel):# 处理文件消息if msg.event_type == EventType.CHAT_FILE:if self.config.enable_file_upload and self._file_service:- await self._send_file_message(msg)+ await self._send_file_message(msg, delivery=route_delivery)return# 处理媒体消息if msg.event_type == EventType.CHAT_MEDIA:if self.config.enable_file_upload and self._file_service:- await self._send_media_message(msg)+ await self._send_media_message(msg, delivery=route_delivery)return- # 处理team message+ # 处理team message — V2: 传入 routing_target 以提取 mention_member_idsif msg.event_type == EventType.TEAM_MESSAGE:- await self._send_team_message(msg)+ await self._send_team_message(+ msg,+ delivery=route_delivery,+ mention_member_ids=route_mention_member_ids,+ mention_all=route_mention_all,+ )return# 处理用户询问消息(发送确认卡片)@@ -1432,8 +1614,47 @@ class FeishuChannel(BaseChannel):content_str,)- receive_id, id_type = self._extract_receive_info(msg)+ # ── V2: routing_target.delivery 优先 ──+ if route_delivery is not None and route_delivery.chat_id:+ receive_id = route_delivery.chat_id+ id_type = route_delivery.id_type or "chat_id"+ else:+ receive_id, id_type = self._extract_receive_info(msg)payload = getattr(msg, "payload", None) or {}++ # ── V2: private intent 的 teammate 输出,用卡片格式(不带 @mention)──+ is_private_teammate_output = (+ routing_target is not None+ and routing_target.intent == "private"+ and isinstance(payload, dict)+ and payload.get("role") == "teammate"+ and event_name in ("chat.final", "chat.tool_call", "chat.tool_result")+ )+ if is_private_teammate_output and content_str.strip():+ member_name = str(payload.get("member_name") or "")+ card = {+ "config": {"wide_screen_mode": True},+ "header": {+ "title": {"tag": "plain_text", "content": f"🤖 {member_name}"},+ "template": "teal",+ },+ "elements": self._build_feishu_card_elements(content_str),+ }+ card_json = json.dumps(card, ensure_ascii=False)+ request_id = str(msg.id or "").strip()+ if request_id and msg.event_type != EventType.HEARTBEAT_RELAY:+ self._clear_group_progress_state(request_id)+ await self._create_and_send_message(+ FeishuMessageSendRequest(+ receive_id=receive_id,+ id_type=id_type,+ msg_type="interactive",+ content=card_json,+ log_label=f"teammate_private:{member_name}",+ )+ )+ return+skills_card_content = self._build_skills_list_card_content(payload, event_name)if skills_card_content:request_id = str(msg.id or "").strip()@@ -1490,7 +1711,7 @@ class FeishuChannel(BaseChannel):await self._send_file_card(receive_id, id_type, fp, os.path.basename(fp))except Exception as file_err:logger.error("飞书兜底文件发送失败: %s %s", fp, file_err)-+# 群聊数字分身回复到群聊时,@发送人if msg.group_digital_avatar and id_type == "chat_id":mention_user_id = str(@@ -1505,6 +1726,16 @@ class FeishuChannel(BaseChannel):if at_user_id and not at_user_id.startswith("bot"):content_str = f"<at id={at_user_id}></at>\n{content_str}"+ # ── V2: routing_target.mention_member_ids 注入 @ 标签 ──+ if id_type == "chat_id":+ if route_mention_all:+ # @所有人:使用飞书 <at id=all></at> 标签+ content_str = f"<at id=all></at>\n{content_str}"+ elif route_mention_member_ids:+ for uid in route_mention_member_ids:+ if uid and not uid.startswith("bot"):+ content_str = f"<at id={uid}></at> {content_str}"+card_content = self._build_card_content(content_str)await self._send_feishu_message(receive_id, id_type, card_content, msg.id)@@ -1928,6 +2159,35 @@ class FeishuChannel(BaseChannel):logger.error("飞书文件上传异常: %s path=%s", e, abs_path)return None+ async def _send_non_stream_team_hint(self, sender: Any, message: Any) -> None:+ """非流式模式下拦截 Team 相关指令(/mode team、/join)的统一提示。++ 与 /mode team 完全相同的校验与报错:当 self.config.enable_streaming 为 False 时,+ 向用户回发卡片提示并中止处理。/join 桥接 team session 同样依赖流式路径+ (agent_server 端 team 桥接只存在于 process_message_stream),非流式下无法生效,+ 故在此一并拦截。+ """+ try:+ # 提取发送者open_id+ open_id = (+ getattr(getattr(sender, "sender_id", None), "open_id", None) or ""+ )+ # 获取chat_id和判断ID类型+ chat_id = getattr(message, "chat_id", None) or ""+ if chat_id.startswith("oc_"):+ receive_id = chat_id+ id_type = "chat_id"+ else:+ # 私聊场景使用open_id+ receive_id = open_id+ id_type = "open_id"+ hint_text = "⚠️ 非流式模式下不支持 Team 模式,已保持原有模式。\n\n" \+ "如需使用 Team 模式,请在配置中开启流式输出 (enable_streaming: true)。"+ card = self._build_card_content(hint_text)+ await self._send_feishu_message(receive_id, id_type, card, message.message_id)+ except Exception as e:+ logger.warning(f"[FeishuChannel] 发送Team模式提示失败: {e}")+def _build_card_content(self, content_str: str) -> str:"""构建飞书卡片内容。@@ -2063,13 +2323,7 @@ class FeishuChannel(BaseChannel):question = questions[0]question_text = question.get("question", "")if question_text:- elements.append({- "tag": "div",- "text": {- "tag": "lark_md",- "content": question_text- }- })+ elements.extend(self._build_feishu_card_elements(question_text))# 添加分隔线elements.append({"tag": "hr"})@@ -2198,28 +2452,17 @@ class FeishuChannel(BaseChannel):# 解析消息内容(支持文件类型)content, file_info = await self._parse_message_content_with_file(message)- if content == "/mode team" and self.config.enable_streaming == False:- # 非流式情况下不支持team模式,向用户发送提示- try:- # 提取发送者open_id- open_id = (- getattr(getattr(sender, "sender_id", None), "open_id", None) or ""- )- # 获取chat_id和判断ID类型- chat_id = getattr(message, "chat_id", None) or ""- if chat_id.startswith("oc_"):- receive_id = chat_id- id_type = "chat_id"- else:- # 私聊场景使用open_id- receive_id = open_id- id_type = "open_id"- hint_text = "⚠️ 非流式模式下不支持 Team 模式,已保持原有模式。\n\n" \- "如需使用 Team 模式,请在配置中开启流式输出 (enable_streaming: true)。"- card = self._build_card_content(hint_text)- await self._send_feishu_message(receive_id, id_type, card, message.message_id)- except Exception as e:- logger.warning(f"[FeishuChannel] 发送Team模式提示失败: {e}")+ # 非流式情况下不支持 Team 模式:/mode team 与 /join(桥接 team session 同样依赖流式路径)+ # 两者共用同一套校验与报错,拦截后直接回发提示并中止处理。+ _content_stripped = (content or "").strip()+ if (+ self.config.enable_streaming == False+ and (+ _content_stripped == "/mode team"+ or _content_stripped.startswith("/join ")+ )+ ):+ await self._send_non_stream_team_hint(sender, message)returnif not content and not file_info:return@@ -2230,12 +2473,14 @@ class FeishuChannel(BaseChannel):)# 将最近一次可回发的飞书身份写入 config.yaml,供 cron 推送时使用- if self.channel_id == self.name:+ # V2 多应用:写入对应 app 条目,避免多 app 争抢同一个平铺字段+ if self.config.channel_id == "feishu" and not self.config.bot_key:try:- from jiuwenswarm.common.config import update_channel_in_config+ from jiuwenswarm.common.config import update_channel_app_field- update_channel_in_config(+ update_channel_app_field("feishu",+ self.config.app_id,{"last_chat_id": getattr(message, "chat_id", None) or "","last_open_id": open_id or "",@@ -2381,19 +2626,23 @@ class FeishuChannel(BaseChannel):}header = {}else:- card_data = self._user_question_card[request_id]- content = card_data["elements"][0].get("text", {}).get("content", "") \- if "elements" in card_data and len(card_data["elements"]) > 0 else ""- header = card_data.get("header", {})- card_data = {- "elements": [{- "tag": "div",- "text": {- "tag": "lark_md",- "content": f"{content} <br> <br> 您已选择:**{selected_label}**"- }- }]- }+ stored_card = self._user_question_card[request_id]+ # 复用原卡片除按钮外的所有元素(保留问题文本的 markdown 渲染),+ # 去掉 action 按钮区与分隔线,再追加"您已选择"提示。+ old_elements = stored_card.get("elements", []) if isinstance(stored_card, dict) else []+ kept_elements = [+ el for el in old_elements+ if isinstance(el, dict) and el.get("tag") not in ("action",)+ ]+ # 去掉尾部 hr,避免与提示紧挨出现双分隔线+ while kept_elements and isinstance(kept_elements[-1], dict) and kept_elements[-1].get("tag") == "hr":+ kept_elements.pop()+ kept_elements.append({+ "tag": "div",+ "text": {"tag": "lark_md", "content": f"您已选择:**{selected_label}**"}+ })+ header = stored_card.get("header", {}) if isinstance(stored_card, dict) else {}+ card_data = {"elements": kept_elements}self._user_question_card.pop(request_id)# 获取用户和上下文信息operator_id = event.operator.open_id if event.operator and event.operator.open_id else ""@@ -2735,12 +2984,18 @@ class FeishuChannel(BaseChannel):# ==================== 文件消息发送 ====================- async def _send_file_message(self, msg: Message) -> None:+ async def _send_file_message(+ self,+ msg: Message,+ *,+ delivery: DeliveryTarget | None = None,+ ) -> None:"""发送文件消息(支持图片/音频/视频/普通文件)。Args:msg: 包含文件信息的消息对象+ delivery: V2 分发时的投递地址(优先于 msg.metadata)。"""payload = msg.payload if isinstance(msg.payload, dict) else {}files = payload.get("files", [])@@ -2749,7 +3004,12 @@ class FeishuChannel(BaseChannel):logger.warning("飞书发送文件消息:无文件信息")return- receive_id, id_type = self._extract_receive_info(msg)+ # team 模式优先用 delivery(与 _send_team_message / chat.final 路径一致)+ if delivery is not None and getattr(delivery, "chat_id", ""):+ receive_id = delivery.chat_id+ id_type = getattr(delivery, "id_type", "") or "chat_id"+ else:+ receive_id, id_type = self._extract_receive_info(msg)logger.info(f"飞书发送文件消息: receive_id={receive_id}, id_type={id_type}")for file_info in files:@@ -3008,12 +3268,22 @@ class FeishuChannel(BaseChannel):except Exception as e:logger.error(f"发送飞书文件消息异常: {e}")- async def _send_team_message(self, msg: Message) -> None:+ async def _send_team_message(+ self,+ msg: Message,+ *,+ delivery: DeliveryTarget | None = None,+ mention_member_ids: list[str] | None = None,+ mention_all: bool = False,+ ) -> None:"""发送Agent Team消息卡片。Args:msg: 包含 team.message payload 的消息对象+ delivery: V2 分发时的投递地址(优先于 msg.metadata)+ mention_member_ids: V2 分发时的 @ 物理用户 ID 列表(飞书 open_id)+ mention_all: True 时 @所有人,忽略 mention_member_ids"""try:payload = msg.payload if isinstance(msg.payload, dict) else {}@@ -3049,14 +3319,28 @@ class FeishuChannel(BaseChannel):# 添加分隔线elements.append({"tag": "hr"})- # 消息内容- elements.append({- "tag": "div",- "text": {- "tag": "lark_md",- "content": content- }- })+ # 消息内容 — V2: 注入 @ 标签+ # @ 前缀作为独立元素(lark_md 原生支持 <at> 标签),+ # 正文走标准 markdown→飞书元素转换,避免 lark_md 不支持的语法以字面文本显示+ if mention_all:+ # @所有人:使用飞书 <at id=all></at> 标签+ elements.append({+ "tag": "div",+ "text": {"tag": "lark_md", "content": "<at id=all></at>"}+ })+ elif mention_member_ids:+ at_prefix = " ".join(+ f"<at id={uid}></at>"+ for uid in mention_member_ids+ if uid and not uid.startswith("bot")+ )+ if at_prefix:+ elements.append({+ "tag": "div",+ "text": {"tag": "lark_md", "content": at_prefix}+ })++ elements.extend(self._build_feishu_card_elements(content))# 构建卡片card = {@@ -3071,8 +3355,12 @@ class FeishuChannel(BaseChannel):"elements": elements,}- # 发送卡片- receive_id, id_type = self._extract_receive_info(msg)+ # 发送卡片 — V2 delivery 优先+ if delivery is not None and delivery.chat_id:+ receive_id = delivery.chat_id+ id_type = delivery.id_type or "chat_id"+ else:+ receive_id, id_type = self._extract_receive_info(msg)card_json = json.dumps(card, ensure_ascii=False)await self._create_and_send_message(@@ -3086,20 +3374,26 @@ class FeishuChannel(BaseChannel):)logger.info(- "[FeishuChannel] 发送Team消息卡片: type=%s, from=%s, to=%s",+ "[FeishuChannel] 发送Team消息卡片: type=%s, from=%s, to=%s receive_id=%s",message_type,from_member,to_member if message_type == "team.message.p2p" else "broadcast",+ receive_id,)except Exception as e:logger.error(f"发送Team消息卡片时发生异常: {e}", exc_info=True)- async def _send_media_message(self, msg: Message) -> None:+ async def _send_media_message(+ self,+ msg: Message,+ *,+ delivery: DeliveryTarget | None = None,+ ) -> None:"""发送媒体消息(video/audio)入口,与文件消息统一处理。"""- await self._send_file_message(msg)+ await self._send_file_message(msg, delivery=delivery)def _filter_user_info_for_group(self, content: str, metadata: dict[str, Any]) -> str:"""diff --git a/jiuwenswarm/gateway/channel_manager/im_platforms/feishu/feishu_im_adapter.py b/jiuwenswarm/gateway/channel_manager/im_platforms/feishu/feishu_im_adapter.pyindex 594be48e4b..9468a831f7 100644--- a/jiuwenswarm/gateway/channel_manager/im_platforms/feishu/feishu_im_adapter.py+++ b/jiuwenswarm/gateway/channel_manager/im_platforms/feishu/feishu_im_adapter.py@@ -13,11 +13,13 @@ from jiuwenswarm.gateway.im_pipeline.im_inbound import IMHistoryMessagetry:import lark_oapi as larkfrom lark_oapi.api.contact.v3 import GetUserRequest+ from lark_oapi.api.application.v6 import GetApplicationRequestFEISHU_AVAILABLE = Trueexcept ImportError:FEISHU_AVAILABLE = Falselark = NoneGetUserRequest = None+ GetApplicationRequest = Nonefrom jiuwenswarm.common.utils import logger@@ -94,8 +96,34 @@ class FeishuIMPlatformAdapter:)return self._target_user_name_cache+ def get_bot_name(self) -> str:+ """获取机器人名称。优先使用飞书 API 动态获取,配置的 bot_name 作为兜底。"""+ if (self._bot_name or "").strip():+ return self._bot_name.strip()++ # 尝试通过飞书 API 获取当前应用名称+ if self._api_client and FEISHU_AVAILABLE and GetApplicationRequest:+ try:+ request = (+ GetApplicationRequest.builder()+ .app_id("me")+ .lang("zh_cn")+ .build()+ )+ response = self._api_client.application.v6.application.get(request)+ if response.success() and response.data and response.data.app:+ app_name = getattr(response.data.app, "app_name", "") or ""+ if app_name.strip():+ self._bot_name = app_name.strip()+ logger.info("[FeishuIMAdapter] 从飞书 API 获取机器人名称: %s", self._bot_name)+ return self._bot_name+ except Exception as e:+ logger.debug("[FeishuIMAdapter] 从飞书 API 获取机器人名称失败: %s", e)++ return ""+def get_bot_mention_tokens(self) -> list[str]:- bot_name = (self._bot_name or "").strip()+ bot_name = self.get_bot_name()return [f"@{bot_name}"] if bot_name else []def load_recent_messages(diff --git a/jiuwenswarm/gateway/channel_manager/im_platforms/telegram/telegram_connect.py b/jiuwenswarm/gateway/channel_manager/im_platforms/telegram/telegram_connect.pyindex 1e4743d956..8575e2edb0 100644--- a/jiuwenswarm/gateway/channel_manager/im_platforms/telegram/telegram_connect.py+++ b/jiuwenswarm/gateway/channel_manager/im_platforms/telegram/telegram_connect.py@@ -13,6 +13,8 @@ import loggingfrom jiuwenswarm.gateway.channel_manager.base import BaseChannel, ChannelMetadata, RobotMessageRouterfrom jiuwenswarm.common.schema.message import Message, ReqMethod+from jiuwenswarm.gateway.routing.keys import DeliveryTarget+from jiuwenswarm.gateway.routing.session_sharing import RoutingTargetlogger = logging.getLogger(__name__)@@ -153,7 +155,7 @@ class TelegramChannel(BaseChannel):logger.info("Telegram Bot 已停止")- async def send(self, msg: Message) -> None:+ async def send(self, msg: Message, *, routing_target: RoutingTarget | None = None) -> None:"""通过 Telegram 发送消息."""if not self._application or not self._running:logger.warning("Telegram Bot not initialized or not running")diff --git a/jiuwenswarm/gateway/channel_manager/im_platforms/wechat/wechat_connect.py b/jiuwenswarm/gateway/channel_manager/im_platforms/wechat/wechat_connect.pyindex d7e5338026..4a735f005a 100644--- a/jiuwenswarm/gateway/channel_manager/im_platforms/wechat/wechat_connect.py+++ b/jiuwenswarm/gateway/channel_manager/im_platforms/wechat/wechat_connect.py@@ -17,6 +17,8 @@ from aiohttp.client_exceptions import ContentTypeErrorfrom pydantic import BaseModel, Fieldfrom jiuwenswarm.common.schema.message import EventType, Message, ReqMethod+from jiuwenswarm.gateway.routing.keys import DeliveryTarget+from jiuwenswarm.gateway.routing.session_sharing import RoutingTargetfrom jiuwenswarm.gateway.channel_manager.base import BaseChannel, ChannelMetadata, RobotMessageRouterlogger = logging.getLogger(__name__)@@ -467,7 +469,7 @@ class WechatChannel(BaseChannel):raise RuntimeError("WechatChannel HTTP client is not initialized")return http- async def send(self, msg: Message) -> None:+ async def send(self, msg: Message, *, routing_target: RoutingTarget | None = None) -> None:"""delta 聚合;enable_streaming 时与原先一致:工具调用/结果会即时下发并在边界冲刷 delta;关闭时仅 chat.final / interrupt 等完结事件合并下发(对齐飞书非流式)。"""if not self._http or not self.config.bot_token:logger.warning("WechatChannel 未就绪,跳过发送")diff --git a/jiuwenswarm/gateway/channel_manager/im_platforms/wecom/wecom_connect.py b/jiuwenswarm/gateway/channel_manager/im_platforms/wecom/wecom_connect.pyindex 095a26b5d4..1666cf1391 100644--- a/jiuwenswarm/gateway/channel_manager/im_platforms/wecom/wecom_connect.py+++ b/jiuwenswarm/gateway/channel_manager/im_platforms/wecom/wecom_connect.py@@ -22,6 +22,8 @@ from jiuwenswarm.gateway.channel_manager.base import BaseChannel, ChannelMetadatfrom jiuwenswarm.gateway.channel_manager.im_platforms.platform_adapter.message import MessageStorefrom jiuwenswarm.common.schema.message import Message, ReqMethod, EventTypefrom jiuwenswarm.common.utils import get_agent_workspace_dir+from jiuwenswarm.gateway.routing.keys import DeliveryTarget+from jiuwenswarm.gateway.routing.session_sharing import RoutingTargetlogger = logging.getLogger(__name__)@@ -1115,8 +1117,17 @@ class WecomChannel(BaseChannel):meta = getattr(msg, "metadata", None) or {}return (meta.get("wecom_req_id") or "").strip() or None- async def send(self, msg: Message) -> None:- """通过企业微信发送消息。支持流式(reply_stream)与非流式(send_message)。"""+ async def send(+ self,+ msg: Message,+ *,+ routing_target: RoutingTarget | None = None,+ ) -> None:+ """通过企业微信发送消息。支持流式(reply_stream)与非流式(send_message)。++ V2: resolved/delivery 为 team 模式分发元数据,企微通道当前通过+ msg.metadata 获取投递信息,暂不直接消费。+ """if not self._ws_client or not getattr(self._ws_client, "is_connected", False):logger.warning("WecomChannel 未连接,跳过发送")returndiff --git a/jiuwenswarm/gateway/channel_manager/im_platforms/whatsapp/whatsapp_connect.py b/jiuwenswarm/gateway/channel_manager/im_platforms/whatsapp/whatsapp_connect.pyindex fb9d026e58..4b188cca6a 100644--- a/jiuwenswarm/gateway/channel_manager/im_platforms/whatsapp/whatsapp_connect.py+++ b/jiuwenswarm/gateway/channel_manager/im_platforms/whatsapp/whatsapp_connect.py@@ -14,6 +14,8 @@ from typing import Any, Callablefrom jiuwenswarm.gateway.channel_manager.base import BaseChannel, ChannelMetadata, RobotMessageRouterfrom jiuwenswarm.common.schema.message import EventType, Message, ReqMethod+from jiuwenswarm.gateway.routing.keys import DeliveryTarget+from jiuwenswarm.gateway.routing.session_sharing import RoutingTargetlogger = logging.getLogger(__name__)@@ -102,7 +104,7 @@ class WhatsAppChannel(BaseChannel):self._set_connection_state("stopped", bridge_ws_connected=False, whatsapp_connected=False, qr_pending=False)logger.info("WhatsAppChannel stopped")- async def send(self, msg: Message) -> None:+ async def send(self, msg: Message, *, routing_target: RoutingTarget | None = None) -> None:if self._ws is None:returnif not self._whatsapp_connected:diff --git a/jiuwenswarm/gateway/channel_manager/im_platforms/xiaoyi/xiaoyi_connect.py b/jiuwenswarm/gateway/channel_manager/im_platforms/xiaoyi/xiaoyi_connect.pyindex c5c12de16a..126043d786 100644--- a/jiuwenswarm/gateway/channel_manager/im_platforms/xiaoyi/xiaoyi_connect.py+++ b/jiuwenswarm/gateway/channel_manager/im_platforms/xiaoyi/xiaoyi_connect.py@@ -12,6 +12,7 @@ import hashlibimport inspectimport jsonimport os+import reimport sslimport timeimport uuid@@ -23,6 +24,8 @@ import aiohttpfrom jiuwenswarm.gateway.channel_manager.base import BaseChannel, ChannelMetadata, RobotMessageRouterfrom jiuwenswarm.common.schema.message import EventType, Message, ReqMethod+from jiuwenswarm.gateway.routing.keys import XiaoyiDeliveryTarget+from jiuwenswarm.gateway.routing.session_sharing import RoutingTargetfrom jiuwenswarm.gateway.channel_manager.im_platforms.xiaoyi.xiaoyi_utils.push import XiaoYiPushService, PushConfigfrom jiuwenswarm.gateway.channel_manager.im_platforms.xiaoyi.xiaoyi_utils.formatter import (get_status_state_for_event,@@ -55,13 +58,13 @@ FILE_TYPE_TO_MIME_TYPE: dict[str, str] = {"mp4": "video/mp4",}-# 全局 XiaoyiChannel 实例引用(供手机端工具调用使用)-_xiaoyi_channel_instance: Optional["XiaoyiChannel"] = None+# 全局 XiaoyiChannel 实例字典(供手机端工具调用使用)+_xiaoyi_channel_instances: dict[str, "XiaoyiChannel"] = {}-def get_xiaoyi_channel() -> Optional["XiaoyiChannel"]:- """获取全局 XiaoyiChannel 实例(供手机端工具调用使用)."""- return _xiaoyi_channel_instance+def get_xiaoyi_channel(channel_id: str = "xiaoyi") -> Optional["XiaoyiChannel"]:+ """获取指定 channel_id 的 XiaoyiChannel 实例(供手机端工具调用使用)."""+ return _xiaoyi_channel_instances.get(channel_id)@dataclass@@ -79,6 +82,7 @@ class XiaoyiChannelConfig:"""小艺通道配置(客户端模式)."""enabled: bool = False+ channel_id: str = "" # 路由标识,始终为 "xiaoyi"mode: str = "xiaoyi_channel" # xiaoyi_channel or xiaoyi_clawak: str = ""sk: str = ""@@ -238,6 +242,9 @@ class XiaoyiChannel(BaseChannel):self._session_heartbeat_tasks: dict[str, asyncio.Task] = {} # Response heartbeat tasks for each sessionself._stream_text_buffers: dict[str, str] = {}self._task_last_activity: dict[str, float] = {}+ # V2: team ws 流式合并缓冲(task_id → 累积 delta 文本 + 延迟 flush 任务)+ self._ws_flush_buffers: dict[str, str] = {}+ self._ws_flush_tasks: dict[str, asyncio.Task] = {}self._on_message_cb: Callable[[Message], Any] | None = None# Task timeout managementself._session_active: set[str] = set() # Active sessions (concurrent request detection)@@ -256,6 +263,25 @@ class XiaoyiChannel(BaseChannel):self.api_id = config.api_idself.push_id = config.push_idself._accumulated_texts: dict[str, str] = {} # Accumulated text per session for push notification+ # V2 Stream Routing: agent_id → (顶层 sessionId, task_id, push_id, ts) 活跃映射,出站判定 ws vs push 用+ self._active_push_sessions: dict[str, tuple[str, str, str, float]] = {}+ # V2: team 投递 ws 活跃窗口——最近 N 秒内有该 agent_id 的 inbound 视为手机端在线,走 ws;超窗走 push。+ # 手机端收到 final 或长时间无消息会主动关 ws(网关无法直接感知手机 ws 状态),靠 inbound 活跃度间接判断。+ self._team_ws_alive_window: float = float(+ getattr(config, "team_ws_alive_window", 60) or 60+ )+ # V2: 活跃映射超时清理任务,定期清掉异常断开的 stale 条目+ self._active_push_cleanup_task: asyncio.Task | None = None+ # V2: ws 保活任务——周期向活跃 agent_id 发 status-update(空内容),重置手机端空闲计时,+ # 避免手机端因长时间无消息主动关 ws(部分终端不能用 push,只能靠 ws 维持)。+ self._team_ws_keepalive_interval: float = float(+ getattr(config, "team_ws_keepalive_interval", 20) or 20+ )+ self._ws_keepalive_task: asyncio.Task | None = None+ # V2: push 合并窗口缓冲 push_id → [(ts, content, summary)],避免短时多条 push 轰炸+ self._push_merge_buffers: dict[str, list[tuple[float, str, str]]] = {}+ # V2: push 延迟 flush 任务 push_id → asyncio.Task,窗口到期统一发送+ self._push_flush_tasks: dict[str, asyncio.Task] = {}# Data-event 处理器:intent_name -> list of handlersself._data_event_handlers: dict[str, List[Callable[[DataEvent], Any]]] = {}# InvokeJarvisGUIAgentResponse 原始事件回调列表@@ -265,7 +291,15 @@ class XiaoyiChannel(BaseChannel):@propertydef channel_id(self) -> str:- return self.name+ return self.config.channel_id or self.name++ @property+ def app_id(self) -> str:+ """V2: app_id 维度,与 inbound bot_id=config.agent_id 对齐,+ 使 ChannelManager 注册的 ChannelKey("xiaoyi", agent_id) 与+ Subscription 的 RoutingKey.app_id 一致,dispatch 时能命中。+ """+ return self.config.agent_id or "default"@propertydef gui_tool_lock(self) -> asyncio.Lock:@@ -293,24 +327,25 @@ class XiaoyiChannel(BaseChannel):self._running = True# 注册全局实例(供 tools 使用)- global _xiaoyi_channel_instance- _xiaoyi_channel_instance = self+ _xiaoyi_channel_instances[self.channel_id] = selflogger.info("XiaoyiChannel 已注册为全局实例")# Start dual channel connectionsfor url_key, url in [("ws_url1", self.config.ws_url1), ("ws_url2", self.config.ws_url2)]:if url:self._connect_tasks[url_key] = asyncio.create_task(self._reconnect_loop(url_key, url))+ # V2: 启动活跃映射超时清理任务,每小时清掉异常断开的 stale 条目+ self._active_push_cleanup_task = asyncio.create_task(self._cleanup_active_push_sessions())+ # V2: 启动 ws 保活任务,周期发 status-update 重置手机端空闲计时+ if self._team_ws_keepalive_interval > 0:+ self._ws_keepalive_task = asyncio.create_task(self._ws_keepalive_loop())logger.info("XiaoyiChannel 已启动(客户端模式,双通道)")async def stop(self) -> None:- global _xiaoyi_channel_instance-self._running = False# 注销全局实例- if _xiaoyi_channel_instance is self:- _xiaoyi_channel_instance = None- logger.info("XiaoyiChannel 已注销全局实例")+ _xiaoyi_channel_instances.pop(self.channel_id, None)+ logger.info("XiaoyiChannel 已注销")# Cancel all heartbeat tasksfor url_key in list(self._heartbeat_tasks.keys()):if self._heartbeat_tasks[url_key]:@@ -354,8 +389,93 @@ class XiaoyiChannel(BaseChannel):self._sessions_waiting_for_push.clear()self._sessions_marked_for_cleanup.clear()self._accumulated_texts.clear()+ # V2: 清理 push 合并窗口任务+ for _aid in list(self._push_flush_tasks.keys()):+ if self._push_flush_tasks[_aid]:+ self._push_flush_tasks[_aid].cancel()+ self._push_flush_tasks.clear()+ self._push_merge_buffers.clear()+ self._active_push_sessions.clear()+ # V2: 取消活跃映射超时清理任务+ if self._active_push_cleanup_task and not self._active_push_cleanup_task.done():+ self._active_push_cleanup_task.cancel()+ self._active_push_cleanup_task = None+ # V2: 取消 ws 保活任务+ if self._ws_keepalive_task and not self._ws_keepalive_task.done():+ self._ws_keepalive_task.cancel()+ self._ws_keepalive_task = None+ # V2: 清理 ws 流式合并缓冲+ for _tid in list(self._ws_flush_tasks.keys()):+ if self._ws_flush_tasks[_tid]:+ self._ws_flush_tasks[_tid].cancel()+ self._ws_flush_tasks.clear()+ self._ws_flush_buffers.clear()logger.info("XiaoyiChannel 已停止")+ async def _cleanup_active_push_sessions(self) -> None:+ """定期清理 _active_push_sessions 中超时的 stale 条目。++ 异常断开的 agent_id(未走 final 清理)会在映射里残留。+ 每小时扫描,清掉 1 小时无更新的条目,避免多用户长期运行内存累积。+ """+ try:+ while self._running:+ await asyncio.sleep(3600)+ cutoff = time.time() - 3600+ stale = [+ aid for aid, entry in self._active_push_sessions.items()+ if entry[3] < cutoff+ ]+ for aid in stale:+ self._active_push_sessions.pop(aid, None)+ if stale:+ logger.info("[XiaoyiChannel] 清理 %d 个 stale 活跃映射条目", len(stale))+ except asyncio.CancelledError:+ pass++ async def _ws_keepalive_loop(self) -> None:+ """周期向活跃 agent_id 发 status-update(空内容)保活。++ 手机端长时间无消息会主动关 ws,部分终端不能用 push 只能靠 ws。+ 每个保活周期扫描 _active_push_sessions,对 ws 仍连接的 agent_id 发一条+ kind=status-update(message 空),重置手机端空闲计时。+ 仅在 ws_alive 窗口内的 agent_id 保活(超窗说明手机端可能已关,保活发不到)。+ """+ try:+ while self._running:+ await asyncio.sleep(self._team_ws_keepalive_interval)+ if not self._ws_connections:+ continue+ # ws 连接是否可用(任一 OPEN)+ ws_usable = any(ws is not None for ws in self._ws_connections.values())+ if not ws_usable:+ continue+ now = time.time()+ # 快照活跃映射,避免迭代中修改+ snapshot = list(self._active_push_sessions.items())+ kept = 0+ for aid, entry in snapshot:+ sid, tid, _, ts = entry+ # 仅对窗口内的 agent_id 保活(ws 大概率还开着)。+ # 保活成功后刷新 last_seen,使 ws_active 持续为 True(防超窗后误走 push)。+ if (now - ts) >= self._team_ws_alive_window:+ continue+ try:+ for url_key, ws in self._ws_connections.items():+ if ws:+ await self._send_status_update_with_state(+ tid, sid, "", "working", url_key,+ )+ # 保活发出即视为链路仍活,刷新 last_seen 维持 ws_active+ self._active_push_sessions[aid] = (sid, tid, entry[2], time.time())+ kept += 1+ except Exception as e:+ logger.debug("[XiaoyiChannel] ws keepalive 失败 agent_id=%s: %s", (aid or "")[:8], e)+ if kept:+ logger.info("[XiaoyiChannel] ws keepalive sent: %d agents", kept)+ except asyncio.CancelledError:+ pass+def _extract_platform_receive_info(self, msg: Message) -> tuple[str, str]:"""从消息中提取小艺平台会话 ID 与任务 ID。@@ -373,10 +493,26 @@ class XiaoyiChannel(BaseChannel):session_id = self._session_task_map.get(task_id, task_id)return session_id, task_id- async def send(self, msg: Message) -> None:- """发送消息到小艺服务端(A2A 格式,双通道发送)."""+ async def send(self, msg: Message, *, routing_target: RoutingTarget | None = None) -> None:+ """发送消息到小艺服务端(A2A 格式,双通道发送).++ V2 Stream Routing:+ - routing_target 为空(非 team 模式)→ 走 _send_legacy 原有单值路径+ - routing_target 非空(team 模式)→ 双通道投递:+ 活跃会话走 ws 流式,非活跃走 push webhook 全文 final+ """+ # ── team 模式:双通道投递 ──+ if routing_target is not None:+ await self._send_team(msg, routing_target)+ return++ # ── 非 team 模式:原有单值路径 ──if not self._ws_connections:return+ await self._send_legacy(msg)++ async def _send_legacy(self, msg: Message) -> None:+ """非 team 模式原有单值投递路径(保留兼容)."""logger.info(f"XiaoyiChannel 发送消息: {msg}")session_id, task_id = self._extract_platform_receive_info(msg)# Handle chat.file event@@ -497,6 +633,343 @@ class XiaoyiChannel(BaseChannel):# Clear accumulated textself._accumulated_texts.pop(session_id, None)+ # V2: 清理活跃映射(按 sessionId 反查 agent_id)+ _aid_to_clean = [+ aid for aid, (sid, _, _, _) in self._active_push_sessions.items()+ if sid == session_id+ ]+ for aid in _aid_to_clean:+ self._active_push_sessions.pop(aid, None)++ # ==================== V2 Stream Routing: team 双通道投递 ====================++ # team member 场景只投递结果类消息,丢弃中间过程(对齐飞书 team 卡片语义)。+ # 保留:TEAM_MESSAGE(团队消息)/ CHAT_FINAL(最终正文)/ CHAT_FILE(文件)/+ # CHAT_ERROR(错误)/ CHAT_TOOL_CALL/RESULT(status 透传)/ CHAT_PROCESSING_STATUS(终态信号)。+ # 丢弃:CHAT_REASONING / CHAT_DELTA / CHAT_ASK_USER_QUESTION / usage / todo / symphony_status 等。+ _TEAM_ALLOWED_EVENTS = frozenset({+ EventType.TEAM_MESSAGE,+ EventType.CHAT_FINAL,+ EventType.CHAT_FILE,+ EventType.CHAT_ERROR,+ EventType.CHAT_TOOL_CALL,+ EventType.CHAT_TOOL_RESULT,+ EventType.CHAT_PROCESSING_STATUS,+ })++ async def _send_team(self, msg: Message, routing_target: RoutingTarget) -> None:+ """team 模式双通道投递:活跃会话走 ws 流式,非活跃走 push webhook 全文 final."""+ delivery = routing_target.delivery+ if delivery is None or not isinstance(delivery, XiaoyiDeliveryTarget):+ logger.warning(+ "[XiaoyiChannel] _send_team drop: delivery invalid type=%s event=%s intent=%s",+ type(delivery).__name__, msg.event_type, routing_target.intent,+ )+ return++ # 白名单过滤:team member 场景丢弃中间过程,只投递结果类消息+ if msg.event_type not in self._TEAM_ALLOWED_EVENTS:+ return++ agent_id = delivery.agent_id+ content = self._extract_team_content(msg)+ # 预解析活跃映射,供诊断日志与通道判定共用+ ws_session, ws_task, last_seen = self._resolve_active_ws(agent_id, delivery)+ # 手机端在线判定:最近 _team_ws_alive_window 秒内有该 agent_id 的 inbound。+ # 手机端收到 final 或长时间无消息会主动关 ws(网关无法直接感知手机 ws 状态),+ # 只能靠 inbound 活跃度间接判断:最近发过消息 → ws 大概率还开着 → 走 ws;否则走 push。+ now = time.time()+ ws_active = bool(+ ws_session and ws_task and last_seen+ and (now - last_seen) < self._team_ws_alive_window+ )+ logger.info(+ "[XiaoyiChannel] _send_team enter: event=%s intent=%s agent_id=%s content_len=%d "+ "ws_active=%s last_seen=%s push_id=%s",+ msg.event_type, routing_target.intent, (agent_id or "")[:8], len(content),+ ws_active, (f"{now - last_seen:.1f}s" if last_seen else "none"), bool(delivery.push_id),+ )++ # status_update / file 类事件透传(不参与 push 合并)+ if should_send_as_status_update(msg.event_type):+ if ws_session and ws_task:+ status_text = get_status_text_for_event(msg.event_type, msg.payload)+ status_state = get_status_state_for_event(msg.event_type, msg.payload)+ for url_key in list(self._ws_connections.keys()):+ await self._send_status_update_with_state(+ ws_task, ws_session, status_text, status_state, url_key+ )+ return+ if msg.event_type == EventType.CHAT_FILE:+ if ws_session and ws_task:+ files = msg.payload.get("files", {}) if isinstance(msg.payload, dict) else {}+ for file_info in files:+ for url_key, ws in self._ws_connections.items():+ if ws:+ try:+ await self._send_file_response(ws_session, ws_task, file_info, url_key)+ except Exception as e:+ logger.warning(f"XiaoyiChannel 发送文件响应失败 ({url_key}): {e}")+ return++ # 判定投递通道+ if ws_active:+ # ① 活跃会话 → ws 流式投递+ logger.info("[XiaoyiChannel] _send_team → ws: agent_id=%s sid=%s", (agent_id or "")[:8],+ (ws_session or "")[:8])+ await self._send_ws_to_user(ws_session, ws_task, msg, content)+ else:+ # ② 后台 → push webhook 全文 final(带 per-agent_id 合并窗口)+ # push_id 优先用 delivery 的,否则从活跃映射取(最后一次已知值)+ push_id = delivery.push_id+ if not push_id and agent_id:+ active = self._active_push_sessions.get(agent_id)+ if active:+ push_id = active[2]+ if push_id and agent_id:+ logger.info("[XiaoyiChannel] _send_team → push: agent_id=%s push_id=%s", (agent_id or "")[:8],+ push_id[:8])+ await self._send_push_to_user(agent_id, push_id, content)+ elif self._ws_connections:+ # ③ 兜底:无 push_id 且无活跃会话,走 legacy(按 metadata 投递)+ logger.info("[XiaoyiChannel] _send_team → legacy fallback: agent_id=%s", (agent_id or "")[:8])+ await self._send_legacy(msg)+ else:+ logger.warning("[XiaoyiChannel] _send_team drop: no ws/push/legacy available agent_id=%s",+ (agent_id or "")[:8])++ def _resolve_active_ws(+ self, agent_id: str, delivery: XiaoyiDeliveryTarget+ ) -> tuple[str, str, float]:+ """解析当前活跃的 (顶层 sessionId, task_id, 最后 inbound 时间戳)。++ 优先用 _active_push_sessions[agent_id] 的最新值(inbound 实时维护),+ 避免 /join 时冻结的旧 sessionId 导致 team 异步消息 ws 投递路由不到。+ delivery.xiaoyi_session_id 仅在无活跃映射时兜底(用户从未发消息的纯 /join 场景)。+ task_id 始终从活跃映射取(请求级临时值,不进 Subscription)。+ 时间戳用于 team 投递 ws 活跃窗口判定:超窗说明手机端可能已关 ws,应降级 push。+ """+ active = self._active_push_sessions.get(agent_id) if agent_id else None+ if active:+ return active[0], active[1], active[3]+ return delivery.xiaoyi_session_id, "", 0.0++ def _extract_team_content(self, msg: Message) -> str:+ """从 Message.payload 抽取 team 消息文本内容.++ team.message 走 event.* 结构化字段(与飞书 _send_team_message 对齐),+ 普通 chat 仍走 payload.content/delta。+ """+ if not isinstance(msg.payload, dict):+ return str(msg.payload) if msg.payload else ""+ event = msg.payload.get("event", {})+ if isinstance(event, dict) and str(event.get("type", "")).startswith("team.message"):+ msg_type = event.get("type", "")+ from_member = event.get("from_member", "") or "team"+ to_member = event.get("to_member", "")+ content = str(event.get("content", "") or "")+ if msg_type == "team.message.broadcast":+ recipient = "📢 全员"+ elif msg_type == "team.message.p2p":+ recipient = f"👾 {to_member}" if to_member else "👾 —"+ else:+ recipient = f"👾 {to_member}" if to_member else "👾 —"+ bar = "─" * 20+ return f"\n---\n╭{bar}╮\n│ 🤖 {from_member} → {recipient}\n╰{bar}╯\n{content}\n"+ content = msg.payload.get("content", "") or msg.payload.get("delta", "")+ if isinstance(content, dict):+ content = content.get("output", str(content))+ return str(content)++ async def _send_ws_to_user(+ self, session_id: str, task_id: str, msg: Message, content: str+ ) -> None:+ """活跃会话 ws 流式投递(复用 _send_text_response)。++ 流式合并:delta chunk 用 16ms(≈60fps)短窗口累积合并发送,+ 缓解高频小 chunk 导致的客户端卡顿,同时保持人眼连续的流式实时性。+ final 消息立即冲刷缓冲并发送,保证结尾不延迟。+ """+ last_chunk = msg.event_type == EventType.CHAT_FINAL+ is_final = False+ if isinstance(msg.payload, dict):+ is_final = bool(msg.payload.get("is_complete", False))+ if is_final:+ last_chunk = True++ # team.message 是完整的逻辑消息(monitor 转发全文,非流式 delta),+ if msg.event_type == EventType.TEAM_MESSAGE:+ last_chunk = True+ is_final = False++ # final 消息:冲刷缓冲 + 立即发送+ if is_final or last_chunk:+ buf = self._ws_flush_buffers.pop(task_id, "")+ merged = (buf + content) if buf else content+ # 末尾加换行,分隔多条 final 消息,避免客户端连在一起显示+ if merged and not merged.endswith("\n"):+ merged = merged + "\n"+ # 取消未决 flush 任务,避免重复发送+ t = self._ws_flush_tasks.pop(task_id, None)+ if t and not t.done():+ t.cancel()+ for url_key, ws in self._ws_connections.items():+ if ws:+ try:+ await self._send_text_response(+ session_id, task_id, merged, url_key,+ append=True, last_chunk=last_chunk, is_final=is_final,+ )+ logger.info(+ "[XiaoyiChannel] team ws sent: event=%s sid=%s task_id=%s "+ "append=True last=%s final=%s len=%d",+ msg.event_type, (session_id or "")[:8], task_id,+ last_chunk, is_final, len(merged),+ )+ except Exception as e:+ logger.warning(f"XiaoyiChannel team ws 发送失败 ({url_key}): {e}")+ return++ # delta chunk:累积进缓冲。超过阈值(200 字符)立即同步冲刷,避免 ws.send+ # 阻塞时 buffer 持续积压导致延迟;否则调度 16ms 延迟 flush 合并高频小 chunk。+ self._ws_flush_buffers[task_id] = self._ws_flush_buffers.get(task_id, "") + content+ if len(self._ws_flush_buffers[task_id]) >= 200:+ buf = self._ws_flush_buffers.pop(task_id, "")+ t = self._ws_flush_tasks.pop(task_id, None)+ if t and not t.done():+ t.cancel()+ for url_key, ws in self._ws_connections.items():+ if ws:+ try:+ await self._send_text_response(+ session_id, task_id, buf, url_key,+ append=True, last_chunk=False, is_final=False,+ )+ except Exception as e:+ logger.warning(f"XiaoyiChannel team ws 即时冲刷失败 ({url_key}): {e}")+ return+ if task_id not in self._ws_flush_tasks or self._ws_flush_tasks[task_id].done():+ self._ws_flush_tasks[task_id] = asyncio.create_task(+ self._flush_ws_buffer(session_id, task_id, delay=0.016)+ )++ async def _flush_ws_buffer(+ self, session_id: str, task_id: str, delay: float = 0.0+ ) -> None:+ """冲刷 ws 流式缓冲,合并发送累积的 delta 文本。"""+ try:+ if delay > 0:+ await asyncio.sleep(delay)+ buf = self._ws_flush_buffers.pop(task_id, "")+ if not buf:+ return+ for url_key, ws in self._ws_connections.items():+ if ws:+ try:+ await self._send_text_response(+ session_id, task_id, buf, url_key,+ append=True, last_chunk=False, is_final=False,+ )+ except Exception as e:+ logger.warning(f"XiaoyiChannel team ws flush 发送失败 ({url_key}): {e}")+ except asyncio.CancelledError:+ pass+ finally:+ self._ws_flush_tasks.pop(task_id, None)++ async def _send_push_to_user(self, agent_id: str, push_id: str, content: str) -> None:+ """后台 push webhook 投递全文 final,带 per-agent_id 合并窗口。++ 同一 agent_id 在 message_merge_window_ms 内的多条消息累积进 buffer,+ 第一条到达时调度延迟 flush 任务,窗口到期统一合并发送一次,+ 避免短时多条 mention 轰炸。push_id 作为 webhook 寻址 token 随 flush 一并发出。+ """+ if not self.config.api_id:+ logger.debug("[PUSH] team push 跳过:api_id 未配置")+ return+ if not content.strip():+ return++ now = time.time()+ buf = self._push_merge_buffers.setdefault(agent_id, [])+ buf.append((now, content, content[:30], push_id))++ # 若已有 pending flush 任务,复用之(继续累积);否则调度延迟 flush+ if agent_id not in self._push_flush_tasks or self._push_flush_tasks[agent_id].done():+ window_ms = getattr(self.config, "message_merge_window_ms", 15000) or 15000+ self._push_flush_tasks[agent_id] = asyncio.create_task(+ self._flush_push_buffer(agent_id, window_ms / 1000)+ )++ async def _flush_push_buffer(self, agent_id: str, window_s: float) -> None:+ """延迟 window 秒后合并发送 buffer 全部内容。"""+ try:+ await asyncio.sleep(window_s)+ buf = self._push_merge_buffers.pop(agent_id, [])+ if not buf:+ return+ # buffer 在 flush 后整体 pop 清空,不存在跨窗口残留,无需按时间过滤+ merged_content = "\n\n".join(b[1] for b in buf)+ summary = self._build_push_summary(buf[0][1]) or (+ merged_content[:30] + "..." if len(merged_content) > 30 else merged_content)+ # push_id 取 buffer 中最近一次的非空值(同一用户 push_id 稳定)+ push_id = ""+ for entry in reversed(buf):+ if entry[3]:+ push_id = entry[3]+ break+ if not push_id:+ logger.warning("[PUSH] team push flush 跳过:buffer 中无有效 push_id (agent_id=%s)", agent_id[:8])+ return+ push_config = PushConfig(+ mode=self.config.mode,+ api_id=self.config.api_id,+ push_id=push_id,+ push_url=self.config.push_url,+ ak=self.config.ak,+ sk=self.config.sk,+ uid=self.config.uid,+ api_key=self.config.api_key,+ )+ await XiaoYiPushService(push_config).send_push(summary, merged_content)+ except asyncio.CancelledError:+ pass+ except Exception as e:+ logger.error(f"[PUSH] team push flush 失败 (agent_id=%s): %s", agent_id[:8], e)+ finally:+ self._push_flush_tasks.pop(agent_id, None)++ @staticmethod+ def _build_push_summary(content: str) -> str:+ """从 _extract_team_content 拼好的 team 消息里提取 summary。++ 格式 @recipient content截断...,取第一条消息的 recipient + 正文前 30 字。+ content 结构:╭{bar}╮\\n│ 🤖 {from} → {recipient}\\n╰{bar}╯\\n{正文}\\n---\\n+ (recipient 可能带 👾 前缀,如 "👾 human-wolf";广播为 "📢 全员")+ 提取失败回退空串(由调用方用截断 merged_content 兜底)。+ """+ if not content:+ return ""+ # recipient:│ ... → {recipient} 行的 → 之后部分(可能含 👾 前缀)+ recipient = ""+ for line in content.split("\n"):+ if "→" in line and "🤖" in line:+ recipient = line.split("→", 1)[1].strip()+ break+ # 正文:╰...╯ 之后的行(排除尾部分隔符 ---)+ body = ""+ m = re.search(r"╯\s*\n(.*)", content, re.DOTALL)+ if m:+ tail = m.group(1)+ # 去掉结尾的 \n---\n+ tail = re.sub(r"\n---\s*\n?$", "", tail).strip()+ body = tail+ if not recipient and not body:+ return ""+ if not body:+ return f"@{recipient}" if recipient else ""+ snippet = body[:30] + "..." if len(body) > 30 else body+ return f"@{recipient} {snippet}" if recipient else snippetdef get_metadata(self) -> ChannelMetadata:return ChannelMetadata(@@ -669,8 +1142,19 @@ class XiaoyiChannel(BaseChannel):async def _handle_message_stream(self, message: dict[str, Any]) -> None:"""处理 message/stream 消息,转换为 JiuwenSwarm Message."""- session_id = message.get("sessionId") or message.get("params", {}).get("sessionId", "")- task_id = message.get("params", {}).get("id", ) or ""+ # V2: 区分两层 sessionId —— 顶层 sessionId 是物理回发地址(临时),+ # conversationId / params.sessionId 是逻辑会话(跨请求稳定)。+ top_session_id = message.get("sessionId", "") or ""+ conversation_id = (+ message.get("conversationId")+ or message.get("params", {}).get("sessionId", "")+ or ""+ )+ # 兼容旧逻辑:inbound 的 session_id 取顶层(物理),逻辑会话独立存 metadata+ session_id = top_session_id or conversation_id+ task_id = message.get("params", {}).get("id", "") or message.get("id", "") or ""+ agent_id = message.get("agentId", "") or self.config.agent_id+ device_id = message.get("deviceId", "") or ""user_message = message.get("params", {}).get("message", {})parts = user_message.get("parts", [])@@ -680,6 +1164,7 @@ class XiaoyiChannel(BaseChannel):# ==================== PROCESS PARTS (TEXT & FILES) ====================text = ""+ push_id = "" # V2: 从 data part 的 systemVariables 提取,webhook 推送寻址 tokenfile_attachments: list[str] = []media_files: list[dict[str, Any]] = []@@ -720,10 +1205,18 @@ class XiaoyiChannel(BaseChannel):elif kind == "data":data = part.get("data", {})if isinstance(data, dict):- push_id = data.get("variables", {}).get("systemVariables", {}).get("push_id", "")- self.config.push_id = push_id if push_id else self.config.push_id+ pid = data.get("variables", {}).get("systemVariables", {}).get("push_id", "")+ if pid:+ push_id = pid# =================================================================+ # V2: 维护 agent_id → (顶层 sessionId, task_id, push_id, ts) 活跃映射,出站判定 ws vs push 用+ # ts 用于超时清理,避免异常断开的 stale 条目累积(多用户长期运行)+ if agent_id:+ self._active_push_sessions[agent_id] = (top_session_id, task_id, push_id, time.time())+ if push_id:+ self.config.push_id = push_id # 内存态保持最新,供 cron 推送兜底+# Log summary of processed attachmentsif file_attachments:logger.info(f"XiaoYi: Processed {len(file_attachments)} file(s): {', '.join(file_attachments)}")@@ -764,23 +1257,35 @@ class XiaoyiChannel(BaseChannel):from jiuwenswarm.common.config import update_channel_in_configrpc_id = message.get("id")- update_channel_in_config(- "xiaoyi",- {- "last_session_id": session_id or "",- "last_task_id": task_id or "",- "last_message_id": str(rpc_id) if rpc_id is not None else "",- },- )+ conf_update: dict[str, Any] = {+ "last_session_id": session_id or "",+ "last_task_id": task_id or "",+ "last_message_id": str(rpc_id) if rpc_id is not None else "",+ }+ # V2: 首次收到非空 push_id 时持久化(webhook 推送 token,供 cron 推送兜底)+ if push_id:+ conf_update["push_id"] = push_id+ update_channel_in_config("xiaoyi", conf_update)except Exception as config_error:logger.warning(f"XiaoyiChannel 更新配置失败: {config_error}")# ==================== BUILD MESSAGE AND ROUTE ====================+ # V2 Stream Routing: 填充 5 维字段 ——+ # user_id = agentId(per-user agent 标识,RoutingKey.user_id 维度)+ # bot_id = config.agent_id(让 MessageHandler._resolve_app_id 兜底拿到 app_id)+ # session_id = 逻辑会话(conversationId,非 team 兜底更稳定)+ # chat_id = 顶层 sessionId(物理回发兜底)# 平台身份写入 metadata,供回发时使用(与 session_id 解耦,\new_session 后仍可正确回发)+ user_id = agent_id+ logical_session = conversation_id or session_idmetadata = {"method": "message/stream",- "xiaoyi_session_id": session_id,+ "xiaoyi_session_id": top_session_id, # 顶层 sessionId(物理回发)"xiaoyi_task_id": task_id,+ "xiaoyi_conversation_id": conversation_id, # 逻辑会话+ "xiaoyi_push_id": push_id, # webhook 推送 token+ "xiaoyi_device_id": device_id, # 设备标识(备用)+ "im_sender_user_id": user_id, # MessageHandler whoami 用}# Add media payload to metadataparams = {"query": text, "task_id": task_id}@@ -791,13 +1296,16 @@ class XiaoyiChannel(BaseChannel):id=message.get("id", ""),type="req",channel_id=self.channel_id,- session_id=session_id,+ session_id=logical_session, # 逻辑会话(非 team 兜底)+ user_id=user_id, # agentId+ bot_id=self.config.agent_id, # ← _resolve_app_id 兜底拿 app_id+ app_id=self.app_id,params=params,timestamp=time.time(),is_stream=self.config.enable_streaming,ok=True,req_method=ReqMethod.CHAT_SEND,- chat_id=session_id,+ chat_id=session_id, # 顶层 sessionId(物理回发兜底)metadata=metadata,)diff --git a/jiuwenswarm/gateway/channel_manager/im_platforms/xiaoyi/xiaoyi_utils/push.py b/jiuwenswarm/gateway/channel_manager/im_platforms/xiaoyi/xiaoyi_utils/push.pyindex 0ad9ef397d..ef0b848e27 100644--- a/jiuwenswarm/gateway/channel_manager/im_platforms/xiaoyi/xiaoyi_utils/push.py+++ b/jiuwenswarm/gateway/channel_manager/im_platforms/xiaoyi/xiaoyi_utils/push.py@@ -122,7 +122,8 @@ class XiaoYiPushService:logger.info("[PUSH] Push notification sent successfully")return Trueelse:- logger.error(f"[PUSH] Failed: HTTP {response.status}")+ body = await response.text()+ logger.error(f"[PUSH] Failed: HTTP {response.status}, response: {body}")return Falseexcept aiohttp.ClientError as e:diff --git a/jiuwenswarm/gateway/channel_manager/protocol/a2a/a2a_connect.py b/jiuwenswarm/gateway/channel_manager/protocol/a2a/a2a_connect.pyindex 7cbc8a881d..2719e0724d 100644--- a/jiuwenswarm/gateway/channel_manager/protocol/a2a/a2a_connect.py+++ b/jiuwenswarm/gateway/channel_manager/protocol/a2a/a2a_connect.py@@ -9,6 +9,8 @@ from typing import Anyfrom jiuwenswarm.gateway.channel_manager.base import BaseChannelfrom jiuwenswarm.common.schema.message import EventType, Message, ReqMethod+from jiuwenswarm.gateway.routing.keys import DeliveryTarget+from jiuwenswarm.gateway.routing.session_sharing import RoutingTargetlogger = logging.getLogger(__name__)@@ -335,7 +337,7 @@ class A2AChannel(BaseChannel):self._pending.clear()logger.info("[A2AChannel] stopped")- async def send(self, msg: Message) -> None:+ async def send(self, msg: Message, *, routing_target: RoutingTarget | None = None) -> None:pending = self._pending.get(str(msg.id))if pending is None:returndiff --git a/jiuwenswarm/gateway/channel_manager/protocol/acp/acp_connect.py b/jiuwenswarm/gateway/channel_manager/protocol/acp/acp_connect.pyindex dd36ad106f..5080f6de3f 100644--- a/jiuwenswarm/gateway/channel_manager/protocol/acp/acp_connect.py+++ b/jiuwenswarm/gateway/channel_manager/protocol/acp/acp_connect.py@@ -41,6 +41,8 @@ from jiuwenswarm.common.e2a.constants import ()from jiuwenswarm.common.e2a.models import E2AEnvelope, E2AProvenance, E2AResponse, utc_now_isofrom jiuwenswarm.common.schema.message import EventType, Message, Mode, ReqMethod+from jiuwenswarm.gateway.routing.keys import DeliveryTarget+from jiuwenswarm.gateway.routing.session_sharing import RoutingTargetlogger = logging.getLogger(__name__)@@ -766,7 +768,7 @@ class AcpChannel(BaseChannel):for session_id in affected_sessions:await self._maybe_finalize_deferred_prompts(session_id)- async def send(self, msg: Message) -> None:+ async def send(self, msg: Message, *, routing_target: RoutingTarget | None = None) -> None:ctx = self._request_ctx.get(str(msg.id))if ctx is None:logger.debug("[ACP] skip outbound without request context: id=%s", msg.id)diff --git a/jiuwenswarm/gateway/channel_manager/tui/tui_channel.py b/jiuwenswarm/gateway/channel_manager/tui/tui_channel.pynew file mode 100644index 0000000000..68b2f6241c--- /dev/null+++ b/jiuwenswarm/gateway/channel_manager/tui/tui_channel.py@@ -0,0 +1,203 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""TuiChannel —— TUI 终端 WebSocket 通道(出站契约 + 五维索引).++架构定位(见 .claude/plans/tui-channel-impl-2commit.md):+- GatewayServer 仍是 /tui ws 宿主 + 入站帧解析 + local handler 派发(前端无感)。+- TuiChannel 继承 BaseWsChannel,只负责「出站 send(按 delivery.ws_id 物理寻址 / 五维+ routing_keys 精确查)」+「被 GatewayServer 委托 register_ws/unregister_ws 维护五维索引」。+- 不自己起端口;ws 连接信息由 GatewayServer 在 forward 分支委托注册进来。++这样 tui 出站与 web 出站共用同一套 BaseWsChannel 反查机制(_ws_by_id + _clients_by_key),+消除「GatewayServer 既是 ws 宿主又是 Channel」的架构断裂。+"""++from __future__ import annotations++import json+import logging+from dataclasses import dataclass+from typing import Any, Callable++from jiuwenswarm.gateway.channel_manager.base import RobotMessageRouter+from jiuwenswarm.gateway.routing.base_ws_channel import BaseWsChannel+from jiuwenswarm.gateway.routing.session_sharing import RoutingTarget++logger = logging.getLogger(__name__)+++@dataclass+class TuiChannelConfig:+ """TuiChannel 配置(占位——ws 宿主由 GatewayServer 承担,此处仅满足 BaseChannel 契约)."""++ enabled: bool = True+++class TuiChannel(BaseWsChannel):+ """TUI 终端通道.++ 出站最后一跳:把 Message 序列化为 tui 前端 wire frame({"type":"event",...} /+ {"type":"res",...}),按 routing_target 物理寻址投递到对应 ws。+ """++ name = "tui"+ channel_id = "tui"++ def __init__(self, config: TuiChannelConfig | None = None, router: RobotMessageRouter | None = None) -> None:+ super().__init__(config or TuiChannelConfig(), router or RobotMessageRouter())+ self.config: TuiChannelConfig = config or TuiChannelConfig()+ self._on_message_cb: Callable[[Any], Any] | None = None++ def on_message(self, callback: Callable[[Any], Any]) -> None:+ self._on_message_cb = callback++ # ── Channel 生命周期 ──++ async def start(self) -> None:+ """TuiChannel 不起端口(ws 宿主是 GatewayServer),start 仅标记 running."""+ self._running = True+ logger.info("[TuiChannel] 已就绪(ws 宿主由 GatewayServer 承担,出站走五维索引)")++ async def stop(self) -> None:+ """停止:清理五维索引 + 兜底清理 writer 协程."""+ self._running = False+ self._clients_by_key.clear()+ self._ws_by_id.clear()+ self._id_by_ws.clear()+ await self._shutdown_all_writers()+ logger.info("[TuiChannel] 已停止")++ # ── 出站 ──++ async def send(+ self,+ msg: Any,+ *,+ routing_target: RoutingTarget | None = None,+ ) -> None:+ """向 TUI 客户端发送消息.++ team 模式(routing_target 非空):优先 delivery.ws_id 物理寻址(_ws_by_id),+ miss 再按 routing_keys 五维精确查 _clients_by_key。+ 非团队模式(routing_target 为空):扫 _clients_by_key 按 session_id 命中+ (对齐 WebChannel,不再广播,避免串窗)。+ """+ ws_set: set[Any] = set()++ if routing_target is not None:+ # ── 优先:按 delivery.ws_id 物理寻址 ──+ delivery = routing_target.delivery+ if delivery is not None:+ ws_id = getattr(delivery, "ws_id", "")+ if ws_id:+ ws = self._ws_by_id.get(ws_id)+ if ws is not None and not getattr(ws, "closed", False):+ ws_set.add(ws)++ # ── 兜底:按 routing_keys 5 维逻辑查 _clients_by_key ──+ if not ws_set:+ for rk in routing_target.routing_keys:+ ws_list = self._clients_by_key.get(rk) or []+ for w in ws_list:+ if not getattr(w, "closed", False):+ ws_set.add(w)++ if ws_set:+ frame_data = self._serialize_frame(+ msg, routing_target, member_names=list(routing_target.member_names),+ )+ for w in ws_set:+ self._enqueue_send(w, frame_data)+ return++ logger.debug(+ "[TuiChannel] team routing miss: ws_id=%s routing_keys=%d — falling back to session_id=%s",+ getattr(delivery, "ws_id", "") if delivery else "",+ len(routing_target.routing_keys),+ getattr(msg, "session_id", ""),+ )++ # ── 非团队模式 / team 路由 miss:按 session_id 兜底(不广播)──+ session_id = getattr(msg, "session_id", None)+ if not session_id:+ logger.warning(+ "[TuiChannel] msg has no session_id and no routing_target, cannot route -- dropping id=%s",+ getattr(msg, "id", ""),+ )+ return+ for rk, ws_list in self._clients_by_key.items():+ if rk.session_id == session_id:+ for w in ws_list:+ if not getattr(w, "closed", False):+ ws_set.add(w)+ if not ws_set:+ logger.debug(+ "[TuiChannel] session_id=%s has no connected ws, dropping msg id=%s",+ session_id, getattr(msg, "id", ""),+ )+ return++ frame_data = self._serialize_frame(msg, routing_target, member_names=None)+ for w in ws_set:+ self._enqueue_send(w, frame_data)++ # ── BaseWsChannel 抽象方法 ──++ def _serialize_frame(+ self,+ msg: Any,+ routing_target: RoutingTarget | None = None,+ *,+ member_names: list[str] | None = None,+ ) -> str:+ """将 Message 序列化为 TUI 前端 JSON 帧.++ 对齐 GatewayServer.send 原有 wire 协议:+ - res 帧:{"type":"res","id":..,"ok":..,"payload":..,"error"?,"code"?}+ - event 帧:{"type":"event","event":event_name,"payload":..}(复用 _build_event_frame 语义)+ """+ if getattr(msg, "type", None) == "res":+ payload = msg.payload+ if isinstance(payload, dict):+ res_payload = {**payload}+ elif payload is None:+ res_payload = {}+ else:+ res_payload = {"content": str(payload)}+ frame: dict[str, Any] = {+ "type": "res",+ "id": getattr(msg, "id", ""),+ "ok": bool(getattr(msg, "ok", True)),+ "payload": res_payload,+ }+ if not frame["ok"]:+ error_text = res_payload.get("error") if isinstance(res_payload, dict) else None+ if isinstance(error_text, str) and error_text:+ frame["error"] = error_text+ code_text = res_payload.get("code") if isinstance(res_payload, dict) else None+ if isinstance(code_text, str) and code_text:+ frame["code"] = code_text+ return json.dumps(frame, ensure_ascii=False)++ # event 帧+ event_name = "chat.final"+ if getattr(msg, "event_type", None) is not None:+ event_name = msg.event_type.value+ payload = msg.payload+ if isinstance(payload, dict):+ out_payload = {**payload}+ out_payload.setdefault("session_id", getattr(msg, "session_id", None))+ else:+ out_payload = {+ "session_id": getattr(msg, "session_id", None),+ "content": str(payload or ""),+ }+ # 透传 agent_ref(与 WebChannel 一致,供前端区分成员/串窗)+ agent_ref = getattr(msg, "agent_ref", None)+ if agent_ref:+ out_payload["agent_ref"] = agent_ref if isinstance(agent_ref, dict) else {+ "mode": getattr(agent_ref, "mode", ""),+ "id": getattr(agent_ref, "id", ""),+ }+ frame = {"type": "event", "event": event_name, "payload": out_payload}+ return json.dumps(frame, ensure_ascii=False)diff --git a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.pyindex 2e3de56323..43104d61bd 100644--- a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py+++ b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py@@ -408,6 +408,10 @@ class CliRouteBindParams:path: str = "/tui"channel_id: str = "tui"cron_controller: Any = None+ # V2: 委托 ws 注册的 TuiChannel 实例。GatewayServer 仍作 /tui ws 宿主 + 入站帧解析,+ # 但把 ws + RoutingKey 委托注册进 TuiChannel 的五维索引,出站由 ChannelManager+ # 派发到 TuiChannel.send(按 delivery.ws_id 物理寻址)。+ ws_channel: Any = None@dataclass@@ -2998,4 +3002,5 @@ def build_cli_route_binding(bind: CliRouteBindParams) -> GatewayRouteBinding:install=_install,disconnect_handler=_tui_disconnect,session_bind_handler=_tui_session_bound,+ ws_channel=bind.ws_channel,)diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.pyindex 5158019668..cbdd7d0021 100644--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py@@ -33,6 +33,7 @@ from jiuwenswarm.common.config import (update_default_models_in_config,update_heartbeat_in_config,update_channel_in_config,+ replace_channel_subsection_with_cleanup,update_browser_in_config,update_preferred_language_in_config,update_context_engine_enabled_in_config,@@ -724,6 +725,200 @@ def _make_session_id() -> str:return f"sess_{ts}_{suffix}"+# ---------------------------------------------------------------------------+# 飞书 Feishu / 小艺 Xiaoyi 多应用配置 — 默认值 & 归一化函数+# ---------------------------------------------------------------------------++_FEISHU_APP_DEFAULTS: dict[str, Any] = {+ "name": "默认应用",+ "is_default": False,+ "enabled": True,+ "app_id": "",+ "app_secret": "",+ "encrypt_key": "",+ "verification_token": "",+ "allow_from": ["0.0.0.0/0"],+ "enable_streaming": True,+ "group_digital_avatar": False,+ "my_user_id": "",+ "bot_name": "",+ "enable_memory": False,+}+++def _merge_apps_by_id(+ new_apps: list[dict],+ existing_apps: list[dict],+) -> list[dict]:+ """将新 apps 与已有 apps 按 app_id 合并,保留前端未显式发送的字段。++ 各 channel 的 ``_normalize_*_conf`` 会用对应的 ``_*_APP_DEFAULTS`` 空值填充+ 前端未发的字段。合并以已有值为基座、新值覆盖,避免已配置的敏感字段(如+ app_secret / sk 等)被默认空值覆盖丢失。++ Parameters+ ----------+ new_apps : list[dict]+ 前端提交并经归一化的新 apps 列表。+ existing_apps : list[dict]+ 从 cm.get_conf (或 config.yaml) 读出的已有 apps 列表。++ Returns+ -------+ list[dict]+ 合并后的 apps 列表。+ """+ if not isinstance(existing_apps, list) or not existing_apps:+ return new_apps++ existing_by_app_id = {+ a["app_id"]: a+ for a in existing_apps+ if isinstance(a, dict) and a.get("app_id")+ }+ if not existing_by_app_id:+ return new_apps++ return [+ {**existing_by_app_id[app["app_id"]], **app}+ if isinstance(app, dict) and app.get("app_id") in existing_by_app_id+ else app+ for app in new_apps+ ]+++def _normalize_feishu_conf(raw: dict) -> dict:+ """将 channels.feishu 统一为 apps 格式,并为每个 app 补充缺省字段。++ 输入可以是旧平铺格式(``{"app_id": "xxx", "app_secret": "yyy"}``)+ 或新多应用格式(``{"apps": [...]}``)。返回结果始终包含 ``apps`` 列表。+ 若输入为空或非 dict,返回 ``{"apps": []}``。+ """+ if not isinstance(raw, dict):+ logger.debug("[normalize_feishu] 输入非 dict (%s), 返回空 apps", type(raw).__name__)+ return {"apps": []}+ if "apps" in raw:+ apps_raw = raw["apps"]+ app_names = [a.get("name", "?") for a in apps_raw] if isinstance(apps_raw, list) else []+ logger.debug(+ "[normalize_feishu] 多应用格式, apps=%d, names=%s",+ len(apps_raw) if isinstance(apps_raw, list) else -1,+ app_names,+ )+ apps = [+ {**_FEISHU_APP_DEFAULTS, **app}+ for app in apps_raw+ ]+ return {**raw, "apps": apps}+ # 旧平铺格式 → 转为 apps+ keys_present = [k for k in ("app_id", "app_secret", "encrypt_key", "verification_token") if k in raw]+ logger.debug("[normalize_feishu] 旧平铺格式, keys=%s, 转为单 app", keys_present)+ return {+ **raw,+ "apps": [_normalize_single_feishu_to_app(raw)],+ }+++def _normalize_single_feishu_to_app(raw: dict) -> dict:+ """将单个平铺飞书配置转为 apps 列表项。"""+ return {+ **_FEISHU_APP_DEFAULTS,+ "is_default": True,+ "name": raw.get("name", "默认应用"),+ "enabled": bool(raw.get("enabled", True)),+ "app_id": raw.get("app_id", ""),+ "app_secret": raw.get("app_secret", ""),+ "encrypt_key": raw.get("encrypt_key", ""),+ "verification_token": raw.get("verification_token", ""),+ "allow_from": raw.get("allow_from") or ["0.0.0.0/0"],+ "enable_streaming": bool(raw.get("enable_streaming", True)),+ "group_digital_avatar": bool(raw.get("group_digital_avatar", False)),+ "my_user_id": raw.get("my_user_id", ""),+ "bot_name": raw.get("bot_name", ""),+ "enable_memory": bool(raw.get("enable_memory", False)),+ **raw,+ }+++_XIAOYI_APP_DEFAULTS: dict[str, Any] = {+ "name": "默认应用",+ "is_default": False,+ "enabled": True,+ "ak": "",+ "sk": "",+ "app_id": "",+ "api_id": "",+ "agent_id": "",+ "enable_streaming": True,+ "mode": "xiaoyi_channel",+ "push_id": "",+ "ws_url1": "wss://hag.cloud.huawei.com/openclaw/v1/ws/link",+ "ws_url2": "wss://116.63.174.231/openclaw/v1/ws/link",+ "phone_tools_enabled": False,+ "uid": "",+ "api_key": "",+ "push_url": "",+ "file_upload_url": "",+}+++def _normalize_xiaoyi_conf(raw: dict) -> dict:+ """将 channels.xiaoyi 统一为 apps 格式,并为每个 app 补充缺省字段。++ 输入可以是旧平铺格式或新多应用格式。返回结果始终包含 ``apps`` 列表。+ 若输入为空或非 dict,返回 ``{"apps": []}``。+ """+ if not isinstance(raw, dict):+ logger.debug("[normalize_xiaoyi] 输入非 dict (%s), 返回空 apps", type(raw).__name__)+ return {"apps": []}+ if "apps" in raw:+ apps_raw = raw["apps"]+ app_names = [a.get("name", "?") for a in apps_raw] if isinstance(apps_raw, list) else []+ logger.debug(+ "[normalize_xiaoyi] 多应用格式, apps=%d, names=%s",+ len(apps_raw) if isinstance(apps_raw, list) else -1,+ app_names,+ )+ apps = [+ {**_XIAOYI_APP_DEFAULTS, **app}+ for app in apps_raw+ ]+ return {**raw, "apps": apps}+ # 旧平铺格式 → 转为 apps+ keys_present = [k for k in ("ak", "sk", "agent_id") if k in raw]+ logger.debug("[normalize_xiaoyi] 旧平铺格式, keys=%s, 转为单 app", keys_present)+ return {+ **raw,+ "apps": [_normalize_single_xiaoyi_to_app(raw)],+ }+++def _normalize_single_xiaoyi_to_app(raw: dict) -> dict:+ """将单个平铺小艺配置转为 apps 列表项。"""+ return {+ **_XIAOYI_APP_DEFAULTS,+ "is_default": True,+ "name": raw.get("name", "默认应用"),+ "enabled": bool(raw.get("enabled", True)),+ "ak": raw.get("ak", ""),+ "sk": raw.get("sk", ""),+ "app_id": raw.get("app_id", ""),+ "api_id": str(raw.get("api_id") or ""),+ "agent_id": raw.get("agent_id", ""),+ "enable_streaming": bool(raw.get("enable_streaming", True)),+ "mode": raw.get("mode", "xiaoyi_channel"),+ "push_id": raw.get("push_id", ""),+ "ws_url1": raw.get("ws_url1", "wss://hag.cloud.huawei.com/openclaw/v1/ws/link"),+ "ws_url2": raw.get("ws_url2", "wss://116.63.174.231/openclaw/v1/ws/link"),+ "phone_tools_enabled": bool(raw.get("phone_tools_enabled", False)),+ "uid": raw.get("uid", ""),+ "api_key": raw.get("api_key", ""),+ "push_url": raw.get("push_url", ""),+ "file_upload_url": raw.get("file_upload_url", ""),+ **raw,+ }++@dataclassclass WebHandlersBindParams:"""Named bundle for :func:`_register_web_handlers` (avoids long positional / keyword lists)."""@@ -793,7 +988,11 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:if ac is None or not getattr(ac, "server_ready", False):logger.debug("[_on_connect] Agent 未就绪,跳过 connection.ack")return- sid = _make_session_id()+ # V2: 复用 ws 握手时注册的占位 session_id,而不是另 make 一个新 sid。+ # 原实现凭空生成 sid_B 与 ws 在 _clients_by_key 中注册的 sid_A 不一致,+ # 导致 send() 按 session_id 反查落空、ACK 被丢弃,前端收不到 connection.ack。+ # 复用 sid_A 后,ACK 走标准 send 流程即可命中本 ws,无需特殊路由兜底。+ sid = getattr(ws, "_jiuwen_initial_sid", None) or _make_session_id()ack_msg = Message(id=f"ack-{sid}",@@ -1958,10 +2157,27 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:error=str(e), code="INTERNAL_ERROR")+ def _mask_sensitive(params: dict | list, sensitive_keys: frozenset[str]) -> dict | list:+ """递归脱敏,替换敏感字段值为 ``****``。"""+ if isinstance(params, dict):+ return {+ k: (_mask_sensitive(v, sensitive_keys) if isinstance(v, (dict, list))+ else "****" if k in sensitive_keys else v)+ for k, v in params.items()+ }+ if isinstance(params, list):+ return [_mask_sensitive(item, sensitive_keys) if isinstance(item, (dict, list)) else item+ for item in params]+ return params++ _feishu_sensitive_keys: frozenset[str] = frozenset({"app_secret", "encrypt_key", "verification_token"})+ _xiaoyi_sensitive_keys: frozenset[str] = frozenset({"sk", "api_key"})+async def _channel_feishu_get_conf(ws, req_id, params, session_id):"""返回 FeishuChannel 的当前配置(由 ChannelManager 管理)。"""cm = _resolve(channel_manager)if cm is None:+ logger.warning("[channel.feishu.get_conf] channel_manager not available, req_id=%s", req_id)await channel.send_response(ws,req_id,@@ -1971,16 +2187,27 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:)returntry:- conf = cm.get_conf("feishu")+ raw = cm.get_conf("feishu")+ conf = _normalize_feishu_conf(raw)+ apps = conf.get("apps", [])+ app_names = [a.get("name", "?") for a in apps]+ logger.debug(+ "[channel.feishu.get_conf] ok, req_id=%s, apps=%d, names=%s",+ req_id, len(apps), app_names,+ )await channel.send_response(ws, req_id, ok=True, payload={"config": conf})except Exception as e: # noqa: BLE001- logger.exception("[channel.feishu.get_conf] %s", e)+ logger.exception("[channel.feishu.get_conf] 异常, req_id=%s: %s", req_id, e)await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")async def _channel_feishu_set_conf(ws, req_id, params, session_id):- """更新 FeishuChannel 的配置,并按新配置重新实例化通道。"""+ """更新 FeishuChannel 的配置,并按新配置重新实例化通道。++ ``params`` 必须含 ``apps`` 键,保存到 channels.feishu.apps。+ """cm = _resolve(channel_manager)if cm is None:+ logger.warning("[channel.feishu.set_conf] channel_manager not available, req_id=%s", req_id)await channel.send_response(ws,req_id,@@ -1999,27 +2226,40 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:)returntry:- await cm.set_conf("feishu", params)- conf = cm.get_conf("feishu")+ # 多应用模式:params 必须含 apps 键+ apps = params["apps"]+ app_names = [a.get("name", "?") for a in apps]+ logger.debug(+ "[channel.feishu.set_conf] req_id=%s, apps=%d, names=%s",+ req_id, len(apps), app_names,+ )+ # 先归一化(用 _FEISHU_APP_DEFAULTS 补充前端未发送的字段),再持久化+ normalized_apps = _normalize_feishu_conf({"apps": apps})["apps"]+ # 从 cm 读取已有 apps,按 app_id 合并保留未发送的敏感字段+ existing_feishu = cm.get_conf("feishu")+ existing_apps = existing_feishu.get("apps", []) if isinstance(existing_feishu, dict) else []+ merged_apps = _merge_apps_by_id(normalized_apps, existing_apps)+ await cm.set_conf("feishu", {"apps": merged_apps})should_clear_agent_config_cache = Falsetry:- update_channel_in_config("feishu", conf)+ replace_channel_subsection_with_cleanup("feishu", "apps", merged_apps, {"apps", "send_file_allowed"})should_clear_agent_config_cache = Trueexcept Exception as e: # noqa: BLE001- logger.warning("[channel.feishu.set_conf] 写回 config.yaml 失败: %s", e)+ logger.warning("[channel.feishu.set_conf] 写回 config.yaml apps 失败: %s", e)try:- await channel.send_response(ws, req_id, ok=True, payload={"config": conf})+ await channel.send_response(ws, req_id, ok=True, payload={"config": {"apps": merged_apps}})finally:if should_clear_agent_config_cache:_schedule_clear_agent_config_cache("channel.feishu.set_conf")except Exception as e: # noqa: BLE001- logger.exception("[channel.feishu.set_conf] %s", e)+ logger.exception("[channel.feishu.set_conf] 异常, req_id=%s: %s", req_id, e)await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")async def _channel_xiaoyi_get_conf(ws, req_id, params, session_id):"""返回 XiaoyiChannel 的当前配置(由 ChannelManager 管理)。"""cm = _resolve(channel_manager)if cm is None:+ logger.warning("[channel.xiaoyi.get_conf] channel_manager not available, req_id=%s", req_id)await channel.send_response(ws,req_id,@@ -2029,16 +2269,27 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:)returntry:- conf = cm.get_conf("xiaoyi")+ raw = cm.get_conf("xiaoyi")+ conf = _normalize_xiaoyi_conf(raw)+ apps = conf.get("apps", [])+ app_names = [a.get("name", "?") for a in apps]+ logger.debug(+ "[channel.xiaoyi.get_conf] ok, req_id=%s, apps=%d, names=%s",+ req_id, len(apps), app_names,+ )await channel.send_response(ws, req_id, ok=True, payload={"config": conf})except Exception as e: # noqa: BLE001- logger.exception("[channel.xiaoyi.get_conf] %s", e)+ logger.exception("[channel.xiaoyi.get_conf] 异常, req_id=%s: %s", req_id, e)await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")async def _channel_xiaoyi_set_conf(ws, req_id, params, session_id):- """更新 XiaoyiChannel 的配置,并按新配置重新实例化通道。"""+ """更新 XiaoyiChannel 的配置,并按新配置重新实例化通道。++ ``params`` 必须含 ``apps`` 键,保存到 channels.xiaoyi.apps。+ """cm = _resolve(channel_manager)if cm is None:+ logger.warning("[channel.xiaoyi.set_conf] channel_manager not available, req_id=%s", req_id)await channel.send_response(ws,req_id,@@ -2057,16 +2308,28 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:)returntry:- await cm.set_conf("xiaoyi", params)- conf = cm.get_conf("xiaoyi")+ # 多应用模式:params 必须含 apps 键+ apps = params["apps"]+ app_names = [a.get("name", "?") for a in apps]+ logger.debug(+ "[channel.xiaoyi.set_conf] req_id=%s, apps=%d, names=%s",+ req_id, len(apps), app_names,+ )+ # 先归一化(用 _XIAOYI_APP_DEFAULTS 补充前端未发送的字段),再持久化+ normalized_apps = _normalize_xiaoyi_conf({"apps": apps})["apps"]+ # 从 cm 读取已有 apps,按 app_id 合并保留未发送的敏感字段+ existing_xiaoyi = cm.get_conf("xiaoyi")+ existing_apps = existing_xiaoyi.get("apps", []) if isinstance(existing_xiaoyi, dict) else []+ merged_apps = _merge_apps_by_id(normalized_apps, existing_apps)+ await cm.set_conf("xiaoyi", {"apps": merged_apps})try:- update_channel_in_config("xiaoyi", conf)+ replace_channel_subsection_with_cleanup("xiaoyi", "apps", merged_apps, {"apps", "send_file_allowed"})await _clear_agent_config_cache(_resolve(agent_client))except Exception as e: # noqa: BLE001- logger.warning("[channel.xiaoyi.set_conf] 写回 config.yaml 失败: %s", e)- await channel.send_response(ws, req_id, ok=True, payload={"config": conf})+ logger.warning("[channel.xiaoyi.set_conf] 写回 config.yaml apps 失败: %s", e)+ await channel.send_response(ws, req_id, ok=True, payload={"config": {"apps": merged_apps}})except Exception as e: # noqa: BLE001- logger.exception("[channel.xiaoyi.set_conf] %s", e)+ logger.exception("[channel.xiaoyi.set_conf] 异常, req_id=%s: %s", req_id, e)await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")async def _channel_telegram_get_conf(ws, req_id, params, session_id):diff --git a/jiuwenswarm/gateway/channel_manager/web/web_connect.py b/jiuwenswarm/gateway/channel_manager/web/web_connect.pyindex 3aeac91135..2d3963b15f 100644--- a/jiuwenswarm/gateway/channel_manager/web/web_connect.py+++ b/jiuwenswarm/gateway/channel_manager/web/web_connect.py@@ -23,7 +23,10 @@ import aiohttpfrom websockets.exceptions import ConnectionClosed as WebSocketConnectionClosedfrom jiuwenswarm.common.utils import get_agent_workspace_dir-from jiuwenswarm.gateway.channel_manager.base import BaseChannel, ChannelMetadata, RobotMessageRouter+from jiuwenswarm.gateway.channel_manager.base import ChannelMetadata, RobotMessageRouter+from jiuwenswarm.gateway.routing.base_ws_channel import BaseWsChannel+from jiuwenswarm.gateway.routing.keys import AgentRef, DeliveryTarget, RoutingKey+from jiuwenswarm.gateway.routing.session_sharing import RoutingTargetfrom jiuwenswarm.common.security.ws_origin import (extract_handshake_request,forbidden_origin_response,@@ -58,7 +61,7 @@ class WebChannelConfig:allow_from: list[str] = field(default_factory=list)-class WebChannel(BaseChannel):+class WebChannel(BaseWsChannel):"""Web 前端 WebSocket 通道.核心职责:@@ -66,15 +69,16 @@ class WebChannel(BaseChannel):2. 解析帧协议 (req / res / event)3. 将入站消息发布到 RobotMessageRouter4. 将方法路由委托给通过 `register_method` 注册的处理器+ 5. V2: 基于 _clients_by_key[RoutingKey] 的 5 维精确路由"""name = "web"+ channel_id = "web"def __init__(self, config: WebChannelConfig, router: RobotMessageRouter):super().__init__(config, router)self.config: WebChannelConfig = configself._server: Any = None- self._clients: set[Any] = set()self._on_message_cb: Callable[[Message], Any] | None = Noneself._method_handlers: dict[str, MethodHandler] = {}self._connect_hooks: list[ConnectHook] = []@@ -84,15 +88,15 @@ class WebChannel(BaseChannel):# ── 公共属性 ──────────────────────────────────────────- @property- def channel_id(self) -> str:- """返回唯一 Channel 标识."""- return self.name+ # channel_id 属性由 name 提供,BaseWsChannel.channel_id 通过 __init_subclass__ 或直接赋值为 "web"@propertydef clients(self) -> set[Any]:- """当前活跃的 WebSocket 客户端集合(只读副本)."""- return set(self._clients)+ """当前活跃的 WebSocket 客户端集合(从 _clients_by_key 推导,只读副本)."""+ result: set[Any] = set()+ for ws_list in self._clients_by_key.values():+ result.update(ws_list)+ return result# ── 扩展注册 API ──────────────────────────────────────@@ -154,7 +158,7 @@ class WebChannel(BaseChannel):if code:frame["code"] = codetry:- await ws.send(json.dumps(frame, ensure_ascii=False))+ self._enqueue_send(ws, json.dumps(frame, ensure_ascii=False))except Exception as e:if bool(getattr(ws, "closed", False)):logger.debug(@@ -184,7 +188,7 @@ class WebChannel(BaseChannel):if stream_id is not None:frame["stream_id"] = stream_idtry:- await ws.send(json.dumps(frame, ensure_ascii=False))+ self._enqueue_send(ws, json.dumps(frame, ensure_ascii=False))except Exception as e:if bool(getattr(ws, "closed", False)):logger.debug(@@ -286,7 +290,7 @@ class WebChannel(BaseChannel):self.config.port,process_request=self._process_request,ping_interval=20,- ping_timeout=20,+ ping_timeout=60,max_size=ws_max_size,)self._running = True@@ -299,15 +303,18 @@ class WebChannel(BaseChannel):"""停止 WebSocket 服务并清理连接."""self._running = False- close_tasks = [client.close(code=1001, reason="server shutdown") for client in list(self._clients)]+ all_clients = list(self.clients)+ close_tasks = [client.close(code=1001, reason="server shutdown") for client in all_clients]if close_tasks:await asyncio.gather(*close_tasks, return_exceptions=True)- self._clients.clear()+ self._clients_by_key.clear()if self._server is not None:self._server.close()await self._server.wait_closed()self._server = None+ # 兜底清理未走正常断连路径的 writer 协程(正常断连已由 unregister_ws 清理)+ await self._shutdown_all_writers()logger.info("WebChannel 已停止")async def connect(self) -> None:@@ -351,10 +358,82 @@ class WebChannel(BaseChannel):)return forbidden_origin_response(args)- async def send(self, msg: Message) -> None:- """向客户端发送消息(默认封装为 event 帧广播)."""- if not self._clients:+ async def send(+ self,+ msg: Message,+ *,+ routing_target: RoutingTarget | None = None,+ ) -> None:+ """向客户端发送消息。++ V2: 当 routing_target 非空时,按其 routing_keys 精确路由(_clients_by_key)。+ 否则回退到全量广播(向后兼容)。+ """+ _pl = getattr(msg, "payload", None) or {}+ _et = _pl.get("event_type", "") if isinstance(_pl, dict) else ""+ _has_fanout = bool((getattr(msg, "metadata", None) or {}).get("fan_out_targets"))+ logger.debug(+ "[WebChannel] send() called: id=%s event_type=%s payload_et=%s has_fanout=%s"+ " has_routing_target=%s client_count=%s",+ getattr(msg, "id", ""), getattr(msg, "event_type", None), _et,+ _has_fanout, routing_target is not None, len(self.clients),+ )+ # ── V2 精确路由 ──+ if routing_target is not None:+ routing_keys = routing_target.routing_keys+ member_names = list(routing_target.member_names)++ # ── 优先:按 delivery.ws_id 物理寻址 ──+ ws_set: set[Any] = set()+ delivery = routing_target.delivery+ if delivery is not None:+ ws_id = getattr(delivery, "ws_id", "")+ if ws_id:+ ws = self._ws_by_id.get(ws_id)+ if ws is not None and not getattr(ws, "closed", False):+ ws_set.add(ws)++ # ── 兜底:按 routing_keys 5 维逻辑查 _clients_by_key ──+ if not ws_set and routing_keys:+ for rk in routing_keys:+ ws_list = self._clients_by_key.get(rk) or []+ for w in ws_list:+ if not getattr(w, "closed", False):+ ws_set.add(w)+ if ws_set:+ frame_data = self._serialize_frame(msg, routing_target, member_names=member_names)+ for w in ws_set:+ self._enqueue_send(w, frame_data)+ return+ # V2 精确路由未命中 —— 回退到 session_id 路由+ logger.debug(+ "[WebChannel] V2 routing miss: looked up %d routing_keys + ws_id=%s,"+ " ws_set empty — falling back to session_id=%s",+ len(routing_keys), getattr(delivery, "ws_id", "") if delivery else "",+ getattr(msg, "session_id", ""),+ )++ # ── 旧路径:按 session_id 精确路由(不再全量广播)──+ if not msg.session_id:+ logger.warning(+ "[WebChannel] msg has no session_id, cannot route -- "+ "dropping msg id=%s to avoid cross-session broadcast",+ getattr(msg, "id", ""),+ )+ return+ ws_set: set[Any] = set()+ for rk, ws_list in self._clients_by_key.items():+ if rk.session_id == msg.session_id:+ for w in ws_list:+ if not getattr(w, "closed", False):+ ws_set.add(w)+ if not ws_set:+ logger.debug(+ "[WebChannel] session_id=%s has no connected ws, dropping msg id=%s",+ msg.session_id, getattr(msg, "id", ""),+ )return+ all_clients = ws_set# 响应帧:优先按 res 语义透传,避免误封装为 chat.finalif msg.type == "res":@@ -378,7 +457,7 @@ class WebChannel(BaseChannel):code_text = res_payload.get("code")if isinstance(code_text, str) and code_text:frame["code"] = code_text- await self._broadcast(frame)+ await self._broadcast_to(frame, all_clients)return# 确定事件名称@@ -391,7 +470,7 @@ class WebChannel(BaseChannel):event_name = payload_event_type.strip()# 根据事件类型构造 payload- payload = {}+ payload: dict[str, Any] = {}if isinstance(msg.payload, dict):# 对于需要传递完整结构化数据的事件类型@@ -423,7 +502,7 @@ class WebChannel(BaseChannel):"content": content,}# teammate 消息:保留 role 和 member_name 供前端区分成员- for _key in ("role", "member_name"):+ for _key in ("role", "member_name", "member_action", "source_channel", "user_id", "display_name"):_val = msg.payload.get(_key)if _val is not None:payload[_key] = _val@@ -454,22 +533,34 @@ class WebChannel(BaseChannel):"content": content,}- frame = {+ # ── V2: 诊断日志 ──+ if routing_target is not None:+ logger.info(+ "[WebChannel] frame: id=%s event=%s intent=%s",+ getattr(msg, "id", ""), event_name, routing_target.intent,+ )+ if getattr(msg, "agent_ref", None):+ payload["agent_ref"] = msg.agent_ref if isinstance(msg.agent_ref, dict) else {+ "mode": getattr(msg.agent_ref, "mode", ""),+ "id": getattr(msg.agent_ref, "id", ""),+ }++ frame_data: dict[str, Any] = {"type": "event","event": event_name,"payload": payload,}- await self._broadcast(frame)+ await self._broadcast_to(frame_data, all_clients)# interrupt_result 根据 intent 决定 is_processing 状态if event_name == "chat.interrupt_result":intent = payload.get("intent", "cancel") if isinstance(payload, dict) else "cancel"is_processing = intent in ("pause", "supplement", "resume")- await self._broadcast({+ await self._broadcast_to({"type": "event","event": "chat.processing_status","payload": {"session_id": msg.session_id, "is_processing": is_processing},- })+ }, all_clients)def get_metadata(self) -> ChannelMetadata:"""获取 Channel 元数据."""@@ -491,9 +582,30 @@ class WebChannel(BaseChannel):query = parse_qs(parsed.query)remote = getattr(ws, "remote_address", None)- self._clients.add(ws)logger.info(f"WebChannel 新连接: remote={remote} query={query}")+ # ── V2: 从 query 提取身份字段,构造默认 RoutingKey ──+ # session_id 和 agent_id 可能在首条消息中更新+ _flat_query = {k: (v[0] if v else "") for k, v in query.items()}+ _user_id = _flat_query.get("user_id", str(remote or "unknown"))+ _app_id = _flat_query.get("app_id", "default")+ _mode = _flat_query.get("mode", "agent")+ _agent_id = _flat_query.get("agent_id", "default")+ _initial_sid = _flat_query.get("session_id", self._make_session_id())+ _initial_rk = RoutingKey(+ user_id=_user_id,+ channel_id=self.channel_id,+ app_id=_app_id,+ agent_ref=AgentRef(mode=_mode, id=_agent_id),+ session_id=_initial_sid,+ )+ await self.register_ws(ws, _initial_rk)+ # 将握手阶段占位 session_id 挂到 ws 上,供 _on_connect 等连接级钩子复用,+ # 确保 connection.ack 与 ws 在 _clients_by_key 中的注册 key 一致,+ # 否则 send() 按 session_id 反查会落空导致 ACK 丢弃。+ # 注:此 sid 仅为传输层占位,首条 chat.send 携带真实 session_id 时会 re-register 覆盖。+ setattr(ws, "_jiuwen_initial_sid", _initial_sid)+# 触发连接钩子(如发送 connection.ack)for hook in self._connect_hooks:try:@@ -532,11 +644,21 @@ class WebChannel(BaseChannel):),)finally:- self._clients.discard(ws)+ await self.unregister_ws(ws)++ # 触发断开钩子+ for hook in self._disconnect_hooks:+ try:+ result = hook(ws)+ if inspect.isawaitable(result):+ await result+ except Exception as e:+ logger.warning("WebChannel on_disconnect hook error: %s", e)+logger.info("WebChannel 连接清理完成: %s",format_ws_diagnostics(- {"remote": remote, "path": request_path, "clients": len(self._clients)},+ {"remote": remote, "path": request_path, "clients": len(self._clients_by_key)},describe_ws_peer(ws),),)@@ -585,9 +707,17 @@ class WebChannel(BaseChannel):if not isinstance(params, dict):params = {}- session_id = params.get("session_id")- if not isinstance(session_id, str) or not session_id:- session_id = self._make_session_id()+ # ── V2: session_id 解析 ──+ # 请求自带 session_id(如 chat.send)→ 用它更新 ws 路由注册。+ # 请求未带 session_id(如 memory.compute 心跳、updater.check、config.get+ # 等 ws 层 keepalive / 拉取请求)→ 这类请求与 session 无关,+ # 仅合成一个临时 id 供后续 Message 构造使用,但【不】参与 register_ws,+ # 保留 ws 上一次的真实 RoutingKey,避免把 ws 从其所属 team session 摘除。+ _explicit_session_id = params.get("session_id")+ has_explicit_session = (+ isinstance(_explicit_session_id, str) and bool(_explicit_session_id)+ )+ session_id = _explicit_session_id if has_explicit_session else self._make_session_id()# 追踪 ws → session_id 映射,用于断连时清理ws_id = id(ws)@@ -599,6 +729,24 @@ class WebChannel(BaseChannel):params = await self._process_files(params)+ # ── V2: 用实际的 session_id / mode / agent_id 更新 ws 注册 ──+ _flat_query = {k: (v[0] if v else "") for k, v in query.items()}+ _mode = params.get("mode", "agent")+ _agent_id = params.get("agent_id", "default")+ _app_id = _flat_query.get("app_id", "default")+ if has_explicit_session:+ _rk = RoutingKey(+ user_id=_flat_query.get(+ "user_id", str(getattr(ws, "remote_address", "unknown"))+ ),+ channel_id=self.channel_id,+ app_id=_app_id,+ agent_ref=AgentRef(mode=_mode, id=_agent_id),+ session_id=session_id,+ )+ await self.register_ws(ws, _rk)+ # else: ws 层心跳 / 拉取请求,不更新路由注册,沿用 ws 已有的 RoutingKey。+user_message = Message(id=req_id,type="req",@@ -609,7 +757,14 @@ class WebChannel(BaseChannel):ok=True,req_method=self._parse_req_method(method),mode=self._parse_mode(params.get("mode")),- metadata={"query": query, "method": method},+ app_id=_app_id,+ agent_ref={"mode": _mode, "id": _agent_id},+ metadata={+ "query": query,+ "method": method,+ # V2: 注入 ws_id 供 MessageHandler 构造 WebDeliveryTarget(ws_id=真值)。+ "ws_id": getattr(ws, "_jiuwen_ws_id", ""),+ },)# 发布到 route 或回调@@ -668,11 +823,55 @@ class WebChannel(BaseChannel):error=f"unknown method: {method}", code="METHOD_NOT_FOUND",)- async def _broadcast(self, frame: dict[str, Any]) -> None:+ async def _broadcast_to(self, frame: dict[str, Any], clients: set[Any]) -> None:+ """向指定 clients 集合广播帧(走 per-ws writer,非阻塞入队)."""data = json.dumps(frame, ensure_ascii=False)- if not self._clients:+ if not clients:return- await asyncio.gather(*[client.send(data) for client in list(self._clients)], return_exceptions=True)+ for client in clients:+ self._enqueue_send(client, data)++ # ── BaseWsChannel 抽象方法 ──++ def _serialize_frame(+ self,+ msg: Any,+ routing_target: RoutingTarget | None = None,+ *,+ member_names: list[str] | None = None,+ ) -> str:+ """将 Message 序列化为 Web 前端 JSON 帧."""+ event_name = "chat.final"+ if getattr(msg, "event_type", None) is not None:+ event_name = msg.event_type.value+ elif isinstance(getattr(msg, "payload", None), dict):+ et = msg.payload.get("event_type")+ if isinstance(et, str) and et.strip():+ event_name = et.strip()++ payload: dict[str, Any] = {}+ if isinstance(msg.payload, dict):+ payload = {**msg.payload}+ if "session_id" not in payload and getattr(msg, "session_id", None):+ payload["session_id"] = msg.session_id+ elif getattr(msg, "payload", None) is not None:+ payload = {"session_id": getattr(msg, "session_id", None), "content": str(msg.payload)}+ else:+ payload = {"session_id": getattr(msg, "session_id", None), "content": ""}++ agent_ref = getattr(msg, "agent_ref", None)+ if agent_ref:+ payload["agent_ref"] = agent_ref if isinstance(agent_ref, dict) else {+ "mode": getattr(agent_ref, "mode", ""),+ "id": getattr(agent_ref, "id", ""),+ }++ frame: dict[str, Any] = {+ "type": "event",+ "event": event_name,+ "payload": payload,+ }+ return json.dumps(frame, ensure_ascii=False)@staticmethoddef _parse_req_method(method: str) -> ReqMethod | None:diff --git a/jiuwenswarm/gateway/cron/scheduler.py b/jiuwenswarm/gateway/cron/scheduler.pyindex 38b069176a..23676b967b 100644--- a/jiuwenswarm/gateway/cron/scheduler.py+++ b/jiuwenswarm/gateway/cron/scheduler.py@@ -586,13 +586,13 @@ class CronSchedulerService:push_dt, wake_dt, next_run_id = self._compute_next_run(job, now_ts=self._now_fn())self._schedule_event(wake_dt, "wake", job.id, next_run_id)self._schedule_event(push_dt, "push", job.id, next_run_id)- except Exception as exc: # noqa: BLE001 # 兜底:reschedule 失败不阻断本次 tick 结果(下个 reload 会重排)+ except Exception as exc: # 兜底:reschedule 失败不阻断本次 tick 结果(下个 reload 会重排)if self._is_croniter_no_next_date(exc):try:job.enabled = Falsejob.expired = Trueawait self._store.update_job(job.id, {"enabled": False, "expired": True})- except Exception as update_exc: # noqa: BLE001 # 兜底:标记过期失败仅告警,不影响主流程+ except Exception as update_exc: # 兜底:标记过期失败仅告警,不影响主流程logger.warning("[Cron] mark expired after proactive.tick failed job=%s: %s", job.id, update_exc)else:logger.warning("[Cron] reschedule after proactive.tick failed job=%s: %s", job.id, exc)@@ -1132,14 +1132,37 @@ class CronSchedulerService:cfg = get_config_raw() or {}channels_cfg = cfg.get("channels") or {}ch_cfg = channels_cfg.get(channel_id) or {}- if channel_id == "feishu":- last_chat_id = str(ch_cfg.get("last_chat_id") or "").strip()- last_open_id = str(ch_cfg.get("last_open_id") or "").strip()- if last_chat_id or last_open_id:- metadata = {- "feishu_chat_id": last_chat_id,- "feishu_open_id": last_open_id,- }+ if channel_id == "feishu" or channel_id.startswith("feishu:"):+ # V2 多应用:从 apps 列表取对应 app 的 last_*(而非平铺字段)+ target_app_id = ""+ if channel_id.startswith("feishu:") and not channel_id.startswith("feishu_enterprise:"):+ target_app_id = channel_id.split(":", 1)[1].strip()+ apps = ch_cfg.get("apps") or []+ if isinstance(apps, list):+ for app in apps:+ if not isinstance(app, dict):+ continue+ if target_app_id and app.get("app_id") != target_app_id:+ continue+ if not target_app_id and not app.get("is_default", False):+ continue+ last_chat_id = str(app.get("last_chat_id") or "").strip()+ last_open_id = str(app.get("last_open_id") or "").strip()+ if last_chat_id or last_open_id:+ metadata = {+ "feishu_chat_id": last_chat_id,+ "feishu_open_id": last_open_id,+ }+ break+ # 兜底:如果 apps 列表为空或无匹配,回退到旧平铺字段+ if metadata is None:+ last_chat_id = str(ch_cfg.get("last_chat_id") or "").strip()+ last_open_id = str(ch_cfg.get("last_open_id") or "").strip()+ if last_chat_id or last_open_id:+ metadata = {+ "feishu_chat_id": last_chat_id,+ "feishu_open_id": last_open_id,+ }elif channel_id.startswith("feishu_enterprise:"):app_id = channel_id.split(":", 1)[1].strip()enterprise_cfg = channels_cfg.get("feishu_enterprise") or {}diff --git a/jiuwenswarm/gateway/message_handler/command_parser/slash_command.py b/jiuwenswarm/gateway/message_handler/command_parser/slash_command.pyindex 1cf7e8b457..42b256def0 100644--- a/jiuwenswarm/gateway/message_handler/command_parser/slash_command.py+++ b/jiuwenswarm/gateway/message_handler/command_parser/slash_command.py@@ -10,6 +10,7 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom enum import Enum+import refrom typing import Any, Literal@@ -30,6 +31,8 @@ class GatewaySlashCommand(str, Enum):REWIND = "/rewind"REVIEW = "/review"SECURITY_REVIEW = "/security-review"+ JOIN = "/join"+ EXIT = "/exit"class ModeSubcommand(str, Enum):@@ -71,6 +74,8 @@ CONTROL_MESSAGE_TEXTS: frozenset[str] = frozenset(GatewaySlashCommand.SKILLS_LIST.value,GatewaySlashCommand.BRANCH.value,GatewaySlashCommand.REWIND.value,+ GatewaySlashCommand.JOIN.value,+ GatewaySlashCommand.EXIT.value,})@@ -95,6 +100,10 @@ class ParsedControlAction(str, Enum):REVIEW_BAD = "review_bad"SECURITY_REVIEW_OK = "security_review_ok"SECURITY_REVIEW_BAD = "security_review_bad"+ JOIN_OK = "join_ok"+ JOIN_BAD = "join_bad"+ EXIT_OK = "exit_ok"+ EXIT_BAD = "exit_bad"@dataclass(frozen=True)@@ -116,6 +125,10 @@ class ParsedChannelControl:"""review_ok 时为用户指定的 PR 编号、URL 或自由文本;空字符串表示未指定,将展示 PR 列表。"""security_review_arg: str | None = None"""security_review_ok 时为用户可选附加说明;空字符串表示未指定。"""+ session_ref: str | None = None+ """join/exit 时的 session 引用。"""+ member_name: str | None = None+ """join 时的席位名。"""_PR_ARG_MAX_LEN = 2048@@ -230,6 +243,47 @@ def parse_channel_control_text(text: str) -> ParsedChannelControl:if sanitized is None:return ParsedChannelControl(ParsedControlAction.REVIEW_BAD)return ParsedChannelControl(ParsedControlAction.REVIEW_OK, pr_arg=sanitized)+ # /join <session_ref> as <member_name>+ # 支持两种格式:+ # 完整: /join team_<name>_session_<id> as <member_name>+ # 简化: /join <session_id> as <member_name>+ if t.startswith(GatewaySlashCommand.JOIN.value):+ parts = t.split()+ if (+ len(parts) == 4+ and parts[0] == GatewaySlashCommand.JOIN.value+ and parts[2] == "as"+ ):+ session_ref = parts[1]+ member_name = parts[3]+ # 接受完整格式 team_*_session_* 或简化格式(任意 session_id)+ if re.match(r'^team_[A-Za-z0-9_-]+_session_[A-Za-z0-9_-]+$', session_ref) or \+ re.match(r'^[A-Za-z0-9_-]+$', session_ref):+ return ParsedChannelControl(+ ParsedControlAction.JOIN_OK,+ session_ref=session_ref,+ member_name=member_name,+ )+ return ParsedChannelControl(ParsedControlAction.JOIN_BAD)+ # /exit [session_ref]+ # 支持三种格式:+ # 不带参数: /exit(使用当前 session)+ # 完整: /exit team_<name>_session_<id>+ # 简化: /exit <session_id>+ if t.startswith(GatewaySlashCommand.EXIT.value):+ parts = t.split()+ if len(parts) == 1 and parts[0] == GatewaySlashCommand.EXIT.value:+ # /exit 不带 session_id → handler 用当前 session 兜底+ return ParsedChannelControl(ParsedControlAction.EXIT_OK)+ if len(parts) == 2 and parts[0] == GatewaySlashCommand.EXIT.value:+ session_ref = parts[1]+ if re.match(r'^team_[A-Za-z0-9_-]+_session_[A-Za-z0-9_-]+$', session_ref) or \+ re.match(r'^[A-Za-z0-9_-]+$', session_ref):+ return ParsedChannelControl(+ ParsedControlAction.EXIT_OK,+ session_ref=session_ref,+ )+ return ParsedChannelControl(ParsedControlAction.EXIT_BAD)return ParsedChannelControl(ParsedControlAction.NONE)@@ -264,6 +318,10 @@ def is_control_like_for_im_batching(text: str) -> bool:return Trueif t.startswith(GatewaySlashCommand.SECURITY_REVIEW.value):return True+ if t.startswith(GatewaySlashCommand.JOIN.value):+ return True+ if t.startswith(GatewaySlashCommand.EXIT.value):+ return Truereturn Falsediff --git a/jiuwenswarm/gateway/message_handler/join_exit_handlers.py b/jiuwenswarm/gateway/message_handler/join_exit_handlers.pynew file mode 100644index 0000000000..07fcc654a2--- /dev/null+++ b/jiuwenswarm/gateway/message_handler/join_exit_handlers.py@@ -0,0 +1,587 @@+"""团队成员 /join /exit 处理逻辑。++从 message_handler.py 拆出的独立维护单元,涵盖:+- /join /exit slash 指令处理(席位注册 / 注销 / 跨 session 容器去重 / 成员名校验)+- GodView 成员加入 / 离开通知(走 V2 fan_out 路由)+- 加入前的团队历史消息推送与格式化++设计为组合而非继承:MessageHandler 在 __init__ 中创建 JoinExitHandlers(self),+通过 self._h 访问宿主能力(get_session_sharing_registry / agent_client / send_channel_notice /+publish_robot_messages / resolve_app_id / extract_*_from_ref),避免循环引用与重复代码。+"""+from __future__ import annotations++import asyncio+import logging+import secrets+import time+from typing import TYPE_CHECKING, Any++from jiuwenswarm.gateway.message_handler.command_parser.slash_command import (+ ParsedControlAction,+)+from jiuwenswarm.gateway.routing.keys import AgentRef, RoutingKey, make_delivery_target+from jiuwenswarm.gateway.routing.session_sharing import LogicalTarget++if TYPE_CHECKING:+ from jiuwenswarm.common.schema.message import Message+ from jiuwenswarm.gateway.message_handler.command_parser.slash_command import (+ ParsedChannelControl,+ )+ from jiuwenswarm.gateway.message_handler.message_handler import MessageHandler++logger = logging.getLogger(__name__)+++# 已 /join 认领 team 席位后仍允许执行的控制指令白名单。+# 其余会改变 session/mode/分支/对话历史或向 Agent 注入 query 的执行类指令一律拒绝+# (破坏席位绑定或扰乱 team 流程),必须先 /exit 退出当前 session 再切换。+# 开闭原则:新增执行类指令默认被拒,新增只读/无副作用指令时在此声明放行。+_ALLOWED_WHEN_JOINED: frozenset[ParsedControlAction] = frozenset(+ {+ ParsedControlAction.EXIT_OK, # 退出本身,正是要鼓励的+ ParsedControlAction.JOIN_OK, # 重复 /join,由 container 去重已处理+ ParsedControlAction.SKILLS_OK, # /skills list 只读+ ParsedControlAction.REWIND_CANCEL, # 取消回退,无副作用+ ParsedControlAction.NONE, # 非控制指令,走正常消息流程+ # 各 *_BAD 仅为格式错误回执,无状态变更,放行让其正常报错+ ParsedControlAction.NEW_SESSION_BAD,+ ParsedControlAction.MODE_BAD,+ ParsedControlAction.SWITCH_BAD,+ ParsedControlAction.REWIND_BAD,+ ParsedControlAction.REVIEW_BAD,+ ParsedControlAction.SECURITY_REVIEW_BAD,+ ParsedControlAction.JOIN_BAD,+ ParsedControlAction.EXIT_BAD,+ }+)+++class JoinExitHandlers:+ """/join /exit 团队成员管理。++ 组合到 MessageHandler 上(宿主通过 self._join_exit 持有本类实例)。+ 运行时通过 self._h 引用宿主,依赖宿主提供以下成员:+ - self._h.get_session_sharing_registry() : SessionSharingRegistry+ - self._h.agent_client : AgentServerClient+ - self._h.send_channel_notice() : async 通知+ - self._h.publish_robot_messages(): async 广播+ - self._h.resolve_app_id() : staticmethod+ - self._h.extract_session_id_from_ref() / extract_team_name_from_ref(): staticmethod+ """++ def __init__(self, handler: "MessageHandler") -> None:+ self._h = handler++ @staticmethod+ def is_allowed_when_joined(action: ParsedControlAction) -> bool:+ """该控制指令是否允许在已 /join 认领 team 席位的状态下执行。++ 白名单见模块级 _ALLOWED_WHEN_JOINED。执行类指令(改 session/mode/分支/历史、+ 注入 query)默认拒绝,必须先 /exit。+ """+ return action in _ALLOWED_WHEN_JOINED++ def sender_has_joined(self, msg: "Message") -> bool:+ """发送者是否已通过 /join 认领了某 team member 席位。++ 复用 resolve_member_by_user(已排除 GodView 订阅,只命中 /join 真实席位),+ 命中即说明该用户在某 session 持有 member 订阅,应拒绝执行类控制指令。+ """+ meta = msg.metadata if isinstance(msg.metadata, dict) else {}+ result = self._h.get_session_sharing_registry().resolve_member_by_user(+ msg.channel_id,+ self._h.resolve_app_id(msg),+ msg.user_id or meta.get("im_sender_user_id", ""),+ chat_id=meta.get("im_thread_id", ""),+ )+ return result is not None++ async def join_slash_handler(+ self,+ user_infos: dict[str, Any],+ channel_id: str,+ msg: "Message",+ parsed: "ParsedChannelControl",+ ) -> None:+ """处理 /join 指令:注册到 SessionSharingRegistry 并发送确认."""+ sid = self._h.extract_session_id_from_ref(parsed.session_ref)+ if not sid or not parsed.member_name:+ await self._h.send_channel_notice(+ user_infos, channel_id, msg.session_id,+ "⚠️ join 指令格式错误",+ )+ return+ rk = RoutingKey(+ user_id=msg.user_id or msg.metadata.get("im_sender_user_id", ""),+ channel_id=msg.channel_id,+ app_id=self._h.resolve_app_id(msg),+ agent_ref=AgentRef("team", self._h.extract_team_name_from_ref(parsed.session_ref)),+ session_id=sid,+ )+ _dt_extra: dict[str, Any] = {}+ if msg.channel_id == "xiaoyi":+ _meta = msg.metadata if isinstance(msg.metadata, dict) else {}+ _dt_extra = {+ "push_id": _meta.get("xiaoyi_push_id", ""),+ "conversation_id": _meta.get("xiaoyi_conversation_id", ""),+ }+ dt = make_delivery_target(+ msg.channel_id,+ chat_id=getattr(msg, "chat_id", None) or "",+ physical_user_id=msg.user_id or msg.metadata.get("im_sender_user_id", ""),+ **_dt_extra,+ )+ # ── V2: 跨 session 容器去重 ──+ # 同一物理容器(如飞书 chat_id)不能同时加入多个 session 或认领多个席位,+ # 必须先 /exit 退出当前 session 才能重新 /join。+ _container_id = dt.get_container_id()+ if _container_id:+ _existing = self._h.get_session_sharing_registry().lookup_by_container(+ rk.channel_id, rk.app_id, _container_id,+ )+ for _exist_sid, _exist_member, _ in _existing:+ if _exist_sid != sid or _exist_member != parsed.member_name:+ await self._h.send_channel_notice(+ user_infos, channel_id, msg.session_id,+ f"⚠️ 当前会话已加入 session **{_exist_sid}**(席位:**{_exist_member}**),"+ f"请先执行 **/exit** 再加入。",+ )+ return+ # ── 成员名校验:member_name 必须是 team 当前 human_agent 席位 ──+ # 实时从 AgentServer 查询 monitor 的成员列表(不读配置),严格模式下+ # 取不到列表(runtime 未起 / monitor 未就绪 / 接口报错)直接拒绝 /join。+ human_member_names = await self.fetch_team_human_members(msg.channel_id, sid)+ if human_member_names is None:+ await self._h.send_channel_notice(+ user_infos, channel_id, msg.session_id,+ f"⚠️ 团队尚未就绪,无法校验成员 **{parsed.member_name}**。请先发起一轮团队对话后再 **/join**。",+ )+ return+ if parsed.member_name not in human_member_names:+ await self._h.send_channel_notice(+ user_infos, channel_id, msg.session_id,+ f"⚠️ 成员 **{parsed.member_name}** 不存在。可用席位:{', '.join(human_member_names)}",+ )+ return+ # 检查席位占用状态(V2 §8.1)+ joining_user_id = msg.user_id or msg.metadata.get("im_sender_user_id", "")+ existing_subs = self._h.get_session_sharing_registry().lookup_member(sid, parsed.member_name)+ for sub in existing_subs:+ if sub.routing_key.user_id != joining_user_id:+ await self._h.send_channel_notice(+ user_infos, channel_id, msg.session_id,+ f"⚠️ 席位 **{parsed.member_name}** 已被其他人认领,无法加入。",+ )+ return+ # 同一个 user_id 已持有此席位 → 幂等,不重复注册+ # 避免同一用户重复 /join 产生多条 Subscription 导致重复消息+ await self._h.send_channel_notice(+ user_infos, channel_id, msg.session_id,+ f"⚠️ 你已是 **{sid}** 的 **{parsed.member_name}**,无需重复加入。",+ )+ return+ try:+ await self._h.get_session_sharing_registry().register(sid, parsed.member_name, rk, dt)+ # register 返回即实时转发对该 member 生效;紧跟取水位(中间无 await,+ # event loop 不切走,不会有 history 写入插进 [register, anchor] 窗口)。+ # 历史推送只发 timestamp < anchor 的记录:anchor 之后的消息走实时、+ # 不进历史,避免同一条消息既实时又历史造成重复。+ anchor_ts = time.time()+ logger.info(+ "[MessageHandler] /join registered via _handle_channel_control: "+ "session=%s member=%s channel=%s",+ sid, parsed.member_name, msg.channel_id,+ )+ await self._h.send_channel_notice(+ user_infos, channel_id, msg.session_id,+ f"已加入 session {sid},席位:{parsed.member_name}。"+ f"后续消息将以 {parsed.member_name} 身份参与团队对话。"+ f"可通过 @team-leader 询问成员信息和任务状态。",+ )+ # ── V2: 同步通知 godview(web 端 leader 视角)──+ await self.notify_godview_member_join(+ sid, parsed.member_name, msg.channel_id,+ user_id=msg.user_id or msg.metadata.get("im_sender_user_id", ""),+ display_name=msg.metadata.get("im_sender_name", "") or msg.metadata.get("sender_name", ""),+ agent_ref=rk.agent_ref,+ )+ # ── V2: 推送该 member 加入前的团队历史消息 ──+ asyncio.create_task(+ self.push_join_history(+ user_infos, msg,+ sid, parsed.member_name, anchor_ts,+ )+ )+ except Exception as exc:+ logger.exception("[MessageHandler] /join register failed: %s", exc)+ await self._h.send_channel_notice(+ user_infos, channel_id, msg.session_id,+ f"⚠️ **加入失败**:{exc}",+ )++ async def _notify_godview_member_action(+ self,+ session_id: str,+ member_name: str,+ source_channel: str,+ action: str,+ *,+ user_id: str = "",+ display_name: str = "",+ agent_ref: Any = None,+ ) -> None:+ """向所有 GodView 订阅者发送成员动作通知(走 V2 fan_out 路由).++ action: "joined" | "left",控制消息 ID 前缀、emoji/动词和 member_action 字段。+ """+ from jiuwenswarm.common.schema.message import Message, EventType++ # 根据动作类型设置不同的显示内容+ if action == "joined":+ emoji, verb = "👤", "加入了"+ id_prefix = "join"+ else:+ emoji, verb = "👋", "离开了"+ id_prefix = "exit"++ content = f"{emoji} {member_name} {verb}团队(来自 {source_channel})"+ notice = Message(+ id=f"{id_prefix}_godview_{session_id}_{member_name}_{int(time.time() * 1000):x}",+ type="event",+ channel_id="web",+ session_id=session_id,+ params={},+ timestamp=time.time(),+ ok=True,+ payload={+ "content": content,+ "is_complete": True,+ "member_name": member_name,+ "source_channel": source_channel,+ "user_id": user_id,+ "display_name": display_name or member_name,+ "member_action": action, # 前端用于区分 join/exit+ },+ event_type=EventType.CHAT_FINAL,+ agent_ref=agent_ref,+ # V2: 通过 fan_out_targets 精确路由到所有 GodView 订阅者,+ # 而非走旧路径依赖 session_id 广播(web ws 可能还未注册该 session_id)+ # 阶段3: 直接挂完整 LogicalTarget 对象,不拆散成 dict——本进程内+ # publish_robot_messages → _dispatch_robot_messages 消费,无需跨进程序列化;+ # 派发循环按 isinstance(LogicalTarget) 取用,跳过 dict→LogicalTarget 重建。+ metadata={"fan_out_targets": [LogicalTarget(intent="godview")]},+ )+ await self._h.publish_robot_messages(notice)+ logger.info(+ "[MessageHandler] godview %s notice: session=%s member=%s source=%s user=%s display=%s",+ action, session_id, member_name, source_channel, user_id, display_name,+ )++ async def notify_godview_member_join(+ self,+ session_id: str,+ member_name: str,+ source_channel: str,+ *,+ user_id: str = "",+ display_name: str = "",+ agent_ref: Any = None,+ ) -> None:+ """向所有 GodView 订阅者发送成员加入通知(走 V2 fan_out 路由)."""+ await self._notify_godview_member_action(+ session_id, member_name, source_channel, "joined",+ user_id=user_id, display_name=display_name, agent_ref=agent_ref,+ )++ async def notify_godview_member_exit(+ self,+ session_id: str,+ member_name: str,+ source_channel: str,+ *,+ user_id: str = "",+ display_name: str = "",+ agent_ref: Any = None,+ ) -> None:+ """向所有 GodView 订阅者发送成员离开通知(走 V2 fan_out 路由)."""+ await self._notify_godview_member_action(+ session_id, member_name, source_channel, "left",+ user_id=user_id, display_name=display_name, agent_ref=agent_ref,+ )++ async def push_join_history(+ self,+ user_infos: dict[str, Any],+ msg: "Message",+ session_id: str,+ member_name: str,+ anchor_ts: float = 0.0,+ ) -> None:+ """向刚加入的成员推送其加入前的团队历史消息。++ 通过 team.history.get WS 命令向 AgentServer 查询,+ 仅返回该 member 相关的记录(p2p / @all 广播 / teammate 输出)。++ 回执地址(channel_id / reply_session_id)取自 msg,避免参数过多。+ anchor_ts 为 register 返回后紧取的水位(Unix epoch 秒),只推送+ timestamp < anchor_ts 的记录:anchor 之后的消息已走实时 fan_out 转发,+ 不再进历史,避免同一条消息既实时又历史造成重复。+ """+ from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fields+ from jiuwenswarm.common.schema.message import ReqMethod++ channel_id = msg.channel_id+ reply_session_id = msg.session_id+ try:+ env = e2a_from_agent_fields(+ request_id=f"join-history-{int(time.time() * 1000):x}-{secrets.token_hex(3)}",+ channel_id=channel_id,+ session_id=session_id,+ req_method=ReqMethod.TEAM_HISTORY_GET,+ params={+ "session_id": session_id,+ "member_name": member_name,+ },+ )+ resp = await self._h.agent_client.send_request(env)+ if not resp.ok:+ logger.warning(+ "[MessageHandler] _push_join_history: agent_server returned error "+ "session=%s member=%s error=%s",+ session_id, member_name,+ resp.payload.get("error", "") if isinstance(resp.payload, dict) else resp.payload,+ )+ return++ payload = resp.payload if isinstance(resp.payload, dict) else {}+ records = payload.get("records", [])+ if not isinstance(records, list) or not records:+ logger.info(+ "[MessageHandler] _push_join_history: no history for session=%s member=%s",+ session_id, member_name,+ )+ return++ # 只保留 register 生效之前的记录:anchor 之后的消息走实时 fan_out,+ # 不进历史,避免同一条消息既实时又历史造成重复+ if anchor_ts:+ before_anchor = []+ for r in records:+ if isinstance(r, dict) and float(r.get("timestamp") or 0) < anchor_ts:+ before_anchor.append(r)+ records = before_anchor+ if not records:+ logger.info(+ "[MessageHandler] _push_join_history: all filtered by anchor_ts=%s "+ "session=%s member=%s",+ anchor_ts, session_id, member_name,+ )+ return++ # 格式化历史消息并推送+ lines = self.format_join_history_lines(records, member_name)+ if lines:+ await self._h.send_channel_notice(+ user_infos, channel_id, reply_session_id,+ "\n".join(lines),+ )+ logger.info(+ "[MessageHandler] _push_join_history: pushed %d records for session=%s member=%s",+ len(records), session_id, member_name,+ )+ except Exception as exc:+ logger.warning(+ "[MessageHandler] _push_join_history failed: session=%s member=%s error=%s",+ session_id, member_name, exc,+ )++ async def fetch_team_human_members(+ self,+ channel_id: str,+ session_id: str,+ ) -> list[str] | None:+ """向 AgentServer 查询 team 当前 role==human_agent 的成员名列表。++ 用于 /join 成员名校验:member_name 必须命中其中一个席位。+ 走 unary RPC(team.members.get),响应只回到本调用点,不进 streaming chunk 流、不影响前端。+ 返回 None 表示取不到成员列表(runtime 未起 / monitor 未就绪 / 接口报错 / 空列表),+ 调用方按"严格"策略拒绝 /join。+ """+ from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fields+ from jiuwenswarm.common.schema.message import ReqMethod++ try:+ env = e2a_from_agent_fields(+ request_id=f"join-members-{int(time.time() * 1000):x}-{secrets.token_hex(3)}",+ channel_id=channel_id,+ session_id=session_id,+ req_method=ReqMethod.TEAM_MEMBERS_GET,+ params={"session_id": session_id},+ )+ resp = await self._h.agent_client.send_request(env)+ if not resp.ok:+ logger.warning(+ "[MessageHandler] _fetch_team_human_members: agent_server returned error "+ "session=%s error=%s",+ session_id,+ resp.payload.get("error", "") if isinstance(resp.payload, dict) else resp.payload,+ )+ return None+ payload = resp.payload if isinstance(resp.payload, dict) else {}+ members = payload.get("members")+ if not isinstance(members, list) or not members:+ return None+ names: list[str] = []+ for m in members:+ if (isinstance(m, dict)+ and m.get("role") == "human_agent"+ and m.get("member_id")):+ names.append(str(m.get("member_id")))+ return names or None+ except Exception as exc:+ logger.warning(+ "[MessageHandler] _fetch_team_human_members failed: session=%s error=%s",+ session_id, exc,+ )+ return None++ @staticmethod+ def format_join_history_lines(+ records: list[dict[str, Any]], member_name: str+ ) -> list[str]:+ """将历史记录格式化为推送给飞书的文本行.++ 每行加 ⏪ 前缀标记为历史消息,与实时 team 消息卡片区分;+ 不显示时间戳以避免服务器/用户时区不一致造成的解析困扰。+ 只保留对话类内容(p2p / @all 广播 / teammate 输出),不含+ team.member / team.task 上下文事件。+ 内容完整显示不截断。+ 标题"(N 条)"以实际渲染出的正文行数为准,与正文严格一致,+ 避免 records 中存在空 content / 空 tool_name 的记录时,标题计数+ 大于实际可见行数造成"条数对不上"的困惑。+ """+ # ⏪ 标记历史消息,与实时输出区分;不附带时间避免时区问题+ hist = "⏪ "+ # 先收集正文行,再用其长度填标题,保证计数与正文严格一致+ body: list[str] = []++ for item in records:+ if not isinstance(item, dict):+ continue+ et = item.get("event_type", "")++ if et == "team.message":+ # team.message 记录内容全在 event 内层:顶层 content 恒为空,+ # type/from_member/to_member/content 都在 event 里+ inner = item.get("event")+ if not isinstance(inner, dict):+ continue+ msg_type = inner.get("type", "")+ from_member = str(inner.get("from_member", "") or "").strip()+ to_member = str(inner.get("to_member", "") or "").strip()+ content = str(inner.get("content", "") or "").strip()+ if msg_type == "team.message.broadcast":+ # 广播:谁 @all+ who = f"@{from_member}" if from_member else ""+ prefix = f"{hist}📢 {who} @all" if who else f"{hist}📢 @all"+ else:+ # p2p:谁 @谁(带 @ 结构,体现发给谁)+ who = f"@{from_member}" if from_member else ""+ target = f"@{to_member}" if to_member else "@你"+ prefix = f"{hist}💬 {who} → {target}"+ if content:+ body.append(f"{prefix}:{content}")+ elif et == "chat.final":+ # teammate 流式输出:content/member_name 在顶层+ content = str(item.get("content", "") or "").strip()+ display_member = str(item.get("member_name", "") or "").strip()+ who = f"@{display_member}" if display_member else ""+ label = f"{hist}🤖 {who}" if who else f"{hist}🤖"+ if content:+ body.append(f"{label}:{content}")+ elif et in ("chat.tool_call", "chat.tool_result"):+ # tool_call 工具名在 tool_call.name;tool_result 工具名在顶层 tool_name+ tool_call = item.get("tool_call")+ tool_name = (+ str(tool_call.get("name", "") or "").strip()+ if isinstance(tool_call, dict)+ else str(item.get("tool_name", "") or "").strip()+ )+ display_member = str(item.get("member_name", "") or "").strip()+ who = f"@{display_member}" if display_member else ""+ label = f"{hist}🛠️ {who}" if who else f"{hist}🛠️"+ if tool_name:+ body.append(f"{label} 工具调用:{tool_name}")++ if not body:+ return [] # 无实际内容,不推送+ return [f"{hist}📋 **加入前的团队历史消息**({len(body)} 条)", *body]++ async def exit_slash_handler(+ self,+ user_infos: dict[str, Any],+ channel_id: str,+ msg: "Message",+ parsed: "ParsedChannelControl",+ ) -> None:+ """处理 /exit 指令:从 SessionSharingRegistry 注销并发送确认."""+ sid = self._h.extract_session_id_from_ref(parsed.session_ref)+ if not sid:+ # 不带 session_ref:直接用 msg.session_id。handle_message 入队前已对已 /join+ # 用户调 resolve_member_by_user 命中,把 msg.session_id 改写为逻辑 session+ # (feishu_xxx)并写入 metadata["member_name"];未 /join 时保持入站物理+ # chat_id(oc_xxx),unregister 返回空走下方"无需退出"分支。+ sid = msg.session_id+ if not sid:+ await self._h.send_channel_notice(+ user_infos, channel_id, msg.session_id,+ "exit 指令格式错误:缺少 session_id,且当前未加入任何 team session。",+ )+ return+ # 只退出当前用户所处的 member_name,不踢掉同一身份的其他席位。+ # member_name 由 handle_message 在已 /join 时写入 metadata,确定可用。+ _member_name = ""+ if isinstance(msg.metadata, dict):+ _member_name = (msg.metadata.get("member_name") or "").strip()+ try:+ results = await self._h.get_session_sharing_registry().unregister_all_for_identity(+ msg.channel_id,+ self._h.resolve_app_id(msg),+ msg.user_id or msg.metadata.get("im_sender_user_id", "") if isinstance(msg.metadata, dict) else "",+ session_id=sid,+ member_name=_member_name or None,+ )+ if results:+ member_names = ", ".join(r.member_name for r in results)+ await self._h.send_channel_notice(+ user_infos, channel_id, msg.session_id,+ f"已退出 session {sid},释放席位:{member_names}。",+ )+ # ── V2: 同步通知 godview(web 端 leader 视角)──+ for r in results:+ await self.notify_godview_member_exit(+ r.session_id, r.member_name, msg.channel_id,+ user_id=msg.user_id or msg.metadata.get("im_sender_user_id", ""),+ display_name=msg.metadata.get("im_sender_name", "") or msg.metadata.get("sender_name", ""),+ agent_ref=AgentRef("team", self._h.extract_team_name_from_ref(parsed.session_ref)),+ )+ else:+ # 未命中订阅:用户确实没 /join 该 session。提示用 channel state 的+ # 逻辑 session_id(feishu_xxx),避免显示入站物理 chat_id(oc_xxx)。+ _display_sid = self._h.get_or_create_channel_state(msg).session_id or sid+ await self._h.send_channel_notice(+ user_infos, channel_id, msg.session_id,+ f"你未加入 session {_display_sid},无需退出。",+ )+ logger.info(+ "[MessageHandler] /exit unregistered via _handle_channel_control: "+ "session=%s channel=%s results=%s",+ sid, msg.channel_id, [(r.session_id, r.member_name) for r in results],+ )+ except Exception as exc:+ logger.exception("[MessageHandler] /exit unregister failed: %s", exc)+ await self._h.send_channel_notice(+ user_infos, channel_id, msg.session_id,+ f"退出失败:{exc}",+ )diff --git a/jiuwenswarm/gateway/message_handler/message_handler.py b/jiuwenswarm/gateway/message_handler/message_handler.pyindex e189426fb6..53f47fb58b 100644--- a/jiuwenswarm/gateway/message_handler/message_handler.py+++ b/jiuwenswarm/gateway/message_handler/message_handler.py@@ -23,6 +23,7 @@ from jiuwenswarm.gateway.routing.session_map import SessionMapfrom jiuwenswarm.gateway.routing.agent_request_timeout import (send_agent_request_with_timeout,)+from jiuwenswarm.gateway.message_handler.join_exit_handlers import JoinExitHandlersfrom jiuwenswarm.gateway.message_handler.command_parser.slash_command import (ParsedControlAction,parse_channel_control_text,@@ -43,6 +44,8 @@ from jiuwenswarm.extensions.hook_event import GatewayHookEventsfrom jiuwenswarm.extensions.hooks_context import GatewayChatHookContextfrom jiuwenswarm.common.hooks_config import load_hooks_configfrom jiuwenswarm.gateway.hooks.handler import GatewayHookHandler+from jiuwenswarm.gateway.routing.keys import DeliveryTarget, RoutingKey, AgentRef, make_delivery_target+from jiuwenswarm.gateway.routing.session_sharing import SessionSharingRegistry, SubRolelogger = logging.getLogger(__name__)@@ -164,7 +167,7 @@ class MessageHandler(ABC):if getattr(self, "_singleton_initialized", False):returnself._singleton_initialized = True- self._agent_client = agent_client+ self.agent_client = agent_clientself._user_messages: asyncio.Queue["Message"] = asyncio.Queue()self._robot_messages: asyncio.Queue["Message"] = asyncio.Queue()self._running = False@@ -176,6 +179,7 @@ class MessageHandler(ABC):self._stream_modes: dict[str, str] = {} # request_id -> modeself._stream_emits_processing_status: dict[str, bool] = {} # request_id -> emits chat.processing_statusself._disconnect_cancel_tasks: dict[tuple[str, str], asyncio.Task] = {}+ self._stream_app_ids: dict[str, str] = {} # request_id -> app_id, 多应用流式精确路由self._fire_and_forget_tasks: set[asyncio.Task] = set() # prevent GC of fire-and-forget tasksself._evolution_approval = EvolutionApprovalCoordinator()self._session_last_user_query: dict[str, str] = {}@@ -198,6 +202,9 @@ class MessageHandler(ABC):})self._channel_states: Dict[str, ChannelControlState] = {}self._session_map = SessionMap()+ self._session_sharing = SessionSharingRegistry()+ # 组合:/join /exit 团队成员管理逻辑(独立文件维护,通过 self._h 访问宿主能力)+ self._join_exit = JoinExitHandlers(self)self._cron_controller = None# IM Pipeline(数字分身)— None 时不执行,不影响原有逻辑@@ -214,6 +221,10 @@ class MessageHandler(ABC):logger.warning("[MessageHandler] Failed to init GatewayHookHandler: %s", e)self._gateway_hook_handler = None+ def get_session_sharing_registry(self) -> SessionSharingRegistry:+ """返回 SessionSharingRegistry 实例,供 V2 共享会话路由使用."""+ return self._session_sharing+def trigger_session_start_hook(self, session_id: str, source: str = "startup") -> None:"""供 Channel 层调用,触发 SessionStart hook."""if self._gateway_hook_handler:@@ -236,8 +247,8 @@ class MessageHandler(ABC):from jiuwenswarm.gateway.routing.agent_client import WebSocketAgentServerClient- if isinstance(self._agent_client, WebSocketAgentServerClient):- self._agent_client.set_server_push_handler(self._handle_agent_server_push)+ if isinstance(self.agent_client, WebSocketAgentServerClient):+ self.agent_client.set_server_push_handler(self._handle_agent_server_push)@classmethoddef get_instance(cls, agent_client: "AgentServerClient | None" = None) -> "MessageHandler":@@ -254,8 +265,57 @@ class MessageHandler(ABC):)return cls(agent_client)- def handle_message(self, msg: "Message") -> None:+ @staticmethod+ def extract_session_id_from_ref(session_ref: str | None) -> str | None:+ """从 session_ref 提取 session_id。++ 支持两种格式:+ - 完整: team_<name>_session_<id> → 提取 <id>+ - 简化: <session_id> → 直接返回+ """+ if not session_ref:+ return None+ parts = session_ref.split("_session_")+ if len(parts) == 2:+ return parts[1]+ # 简化格式:直接就是 session_id(如 sess_xxx)+ return session_ref++ @staticmethod+ def extract_team_name_from_ref(session_ref: str | None) -> str:+ if not session_ref:+ return "unknown"+ prefix = session_ref.replace("team_", "", 1)+ return prefix.split("_session_")[0]++ @staticmethod+ def resolve_app_id(msg: "Message") -> str:+ """从 Message 提取有效的 app_id。++ msg.app_id 是 V2 新增字段,渠道尚未迁移填充(始终为 None);+ 兜底读 msg.bot_id——渠道已将其设为 channel.config.app_id。+ 修复后后续可将 msg.bot_id 逐步迁移为 msg.app_id。+ """+ return getattr(msg, "app_id", None) or getattr(msg, "bot_id", None) or "default"++ async def handle_message(self, msg: "Message") -> None:"""Channel 同步回调:将消息放入 user_messages 队列,由转发循环发给 AgentServer."""+ # 非控制指令: 反查发送者身份+ result = self._session_sharing.resolve_member_by_user(+ msg.channel_id,+ MessageHandler.resolve_app_id(msg),+ msg.user_id or msg.metadata.get("im_sender_user_id", ""),+ chat_id=msg.metadata.get("im_thread_id", "") if isinstance(msg.metadata, dict) else "",+ )+ if result:+ sid, mname = result+ # V2: whoami 命中时始终覆盖为 team session_id,+ # 因为 IM 消息的 session_id 是 chat_id(如 oc_xxx),+ # 不加覆盖则消息发到错误 session,LLM 视为普通对话。+ msg.session_id = sid+ msg.metadata = dict(msg.metadata or {})+ msg.metadata["member_name"] = mname+self._remember_user_query_context(msg)self._user_messages.put_nowait(msg)logger.info(@@ -263,6 +323,85 @@ class MessageHandler(ABC):msg.id, msg.channel_id, msg.session_id,)+ async def _maybe_register_godview(self, msg: "Message") -> None:+ """V2: auto-register a GodView subscriber for the channel.++ Called from _forward_loop after _apply_channel_state, so msg.session_id is+ already the real team session_id (not the inbound chat_id like oc_xxx) and+ msg.params.mode has been injected. Registering here ensures GodView lands+ under the same session_id that team-event dispatch uses, so fan_out's+ godview intent can resolve.++ Trigger when:+ - params.mode == "team", or+ - session already has subscribers (already a team session; web mode may be "agent")+ """+ if not msg.session_id:+ return+ # member 已通过 /join 认领席位(resolve_member_by_user 命中),其消息走+ # mention/private intent 精确投递即可,无需再为本 channel 注册 GodView+ # (否则 member 会多收一份 godview 全量输出,飞书端还会与 mention/private+ # 拼到同一 buffer 串台)。单人 /mode team 无 member_name,正常注册 GodView。+ 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()+ _session_has_subs = bool(self._session_sharing.lookup_all(msg.session_id))+ if not (_mode == "team" or _session_has_subs):+ return+ godview_subs = self._session_sharing.lookup_member(msg.session_id, SubRole.GODVIEW)+ _ch = msg.channel_id or "web"+ _has_godview_for_this_channel = any(+ s.routing_key.channel_id == _ch for s in godview_subs+ )+ if _has_godview_for_this_channel:+ logger.info(+ "[MessageHandler] GodView already registered for channel %s: session=%s count=%d",+ _ch, msg.session_id, len(godview_subs),+ )+ return+ _app = MessageHandler.resolve_app_id(msg)+ # ws_id is generated by Channel handshake and injected into msg.metadata;+ # send resolves by delivery.ws_id first. IM channel has no ws_id, uses chat_id+ # as container.+ _ws_id = (msg.metadata or {}).get("ws_id", "")+ _user = (+ (msg.metadata or {}).get("user_id")+ or msg.user_id+ or str(getattr(msg, "chat_id", None) or _ch)+ )+ # V2: tui 同 web 走 ws 物理寻址——TuiChannel 持有 _ws_by_id,GodView 订阅+ # 需带真 ws_id 才能让 team 出站 dispatch_to_session → TuiChannel.send 命中 ws。+ # GatewayServer forward 分支已把 ws_id 注入 msg.metadata(委托 TuiChannel._register)。+ _kind = "ws" if _ch in ("web", "tui") else "group"+ # 阶段2: GodView RoutingKey.agent_ref 与入站 _register 的 rk.agent_ref 同源+ # (用 msg.agent_ref,tui 已在 GatewayServer forward 分支按 mode/agent_id 合成),+ # 使出站 routing_keys 兜底能命中 _clients_by_key。msg.agent_ref 缺失/非 AgentRef+ # 时回退 AgentRef("team","default")(IM 等非 ws_channel 路径原语义)。+ _godview_agent_ref = getattr(msg, "agent_ref", None)+ if not isinstance(_godview_agent_ref, AgentRef):+ _godview_agent_ref = AgentRef("team", "default")+ rk = RoutingKey(+ user_id=_user,+ channel_id=_ch,+ app_id=_app,+ agent_ref=_godview_agent_ref,+ session_id=msg.session_id,+ )+ dt = make_delivery_target(+ _ch,+ chat_id=getattr(msg, "chat_id", None) or "",+ ws_id=_ws_id if _kind == "ws" else "",+ )+ await self._session_sharing.register(msg.session_id, SubRole.GODVIEW, rk, dt)+ logger.info(+ "[MessageHandler] GodView auto-registered: session=%s channel=%s user=%s app=%s kind=%s"+ " rk_full=%s",+ msg.session_id, _ch, _user, _app, _kind,+ {"user_id": rk.user_id, "channel_id": rk.channel_id, "app_id": rk.app_id,+ "agent_ref": str(rk.agent_ref), "session_id": rk.session_id},+ )+# ---------- Channel 控制状态:\new_session / \mode ----------def _remember_user_query_context(self, msg: "Message") -> None:@@ -363,7 +502,7 @@ class MessageHandler(ABC):return f"{channel_id}:{conversation_id}"return channel_id- def _get_or_create_channel_state(self, msg: "Message") -> ChannelControlState:+ def get_or_create_channel_state(self, msg: "Message") -> ChannelControlState:"""获取或创建消息对应 channel 状态(使用复合键)。conversation_id 从 msg.metadata 获取,如 feishu 的 feishu_chat_id。@@ -432,7 +571,7 @@ class MessageHandler(ABC):return providerreturn str(getattr(msg, "channel_id", "") or "")- async def _send_channel_notice(+ async def send_channel_notice(self,user_infos: dict,channel_id: str,@@ -446,12 +585,15 @@ class MessageHandler(ABC):"""from jiuwenswarm.common.schema.message import Message, EventType+ # 小艺 channel 按 payload.is_complete 判定任务结束(收到 True 即关闭接收周期)。+ _default_complete = False if channel_id == "xiaoyi" else Trueif isinstance(text_or_payload, dict):payload = dict(text_or_payload)- payload.setdefault("is_complete", True)+ payload.setdefault("is_complete", _default_complete)else:- payload = {"content": text_or_payload, "is_complete": True}+ payload = {"content": text_or_payload, "is_complete": _default_complete}+ _app_id = user_infos.get("app_id") or user_infos.get("bot_id", "")msg = Message(id=user_infos['id'],type="event",@@ -462,7 +604,8 @@ class MessageHandler(ABC):ok=True,payload=payload,event_type=EventType.CHAT_FINAL,- metadata=user_infos['meta_data']+ metadata=user_infos['meta_data'],+ app_id=_app_id or None,)await self.publish_robot_messages(msg)@@ -473,6 +616,7 @@ class MessageHandler(ABC):self._stream_sessions.pop(rid, None)self._stream_metadata.pop(rid, None)self._stream_emits_processing_status.pop(rid, None)+ self._stream_app_ids.pop(rid, None)self._stream_modes.pop(rid, None)@staticmethod@@ -765,6 +909,7 @@ class MessageHandler(ABC):resp,sid_for_agent,request_metadata=msg.metadata,+ app_id=msg.app_id or "",)await self.publish_robot_messages(out)logger.info(@@ -983,7 +1128,7 @@ class MessageHandler(ABC):params.old_sid,publish_interrupt_result=False,)- await self._send_channel_notice(+ await self.send_channel_notice(params.user_infos,params.channel_id,params.reply_session_id,@@ -1001,7 +1146,7 @@ class MessageHandler(ABC):params.old_sid,publish_interrupt_result=False,)- await self._send_channel_notice(+ await self.send_channel_notice(params.user_infos,params.channel_id,params.reply_session_id,@@ -1019,7 +1164,12 @@ class MessageHandler(ABC):True: 该消息是控制指令,已处理完毕,不需要转发给 Agent。False: 非控制指令,继续正常处理。"""- user_infos = {"id": msg.id, "meta_data": msg.metadata}+ user_infos = {+ "id": msg.id,+ "meta_data": msg.metadata,+ "app_id": getattr(msg, "app_id", None) or getattr(msg, "bot_id", None) or "",+ "bot_id": getattr(msg, "bot_id", None) or "",+ }ch = msg.channel_idchannel_type = self._resolve_control_channel_type(msg)@@ -1049,7 +1199,24 @@ class MessageHandler(ABC):return True# 获取当前会话的状态(使用复合键)- state = self._get_or_create_channel_state(msg)+ state = self.get_or_create_channel_state(msg)++ # /join 已认领 team 席位后,除白名单(/exit、只读 /skills list 等)外的控制指令+ # 一律拒绝——执行类指令会改 session/mode/分支/历史或注入 query,破坏席位绑定+ # 或扰乱 team 流程。必须先 /exit。白名单与判定收敛在 JoinExitHandlers,见该类。+ if (+ not self._join_exit.is_allowed_when_joined(parsed.action)+ and self._join_exit.sender_has_joined(msg)+ ):+ asyncio.create_task(+ self.send_channel_notice(+ user_infos,+ ch,+ msg.session_id,+ "⚠️ 当前已加入 team session,不能执行该指令。请先执行 **/exit** 退出后再试。",+ )+ )+ return Trueif parsed.action is ParsedControlAction.NEW_SESSION_OK:old_sid = state.session_id@@ -1080,7 +1247,7 @@ class MessageHandler(ABC):return Trueif parsed.action is ParsedControlAction.NEW_SESSION_BAD:asyncio.create_task(- self._send_channel_notice(+ self.send_channel_notice(user_infos,ch,msg.session_id,@@ -1102,7 +1269,7 @@ class MessageHandler(ABC):"code.team",):asyncio.create_task(- self._send_channel_notice(+ self.send_channel_notice(user_infos,ch,msg.session_id,@@ -1144,7 +1311,7 @@ class MessageHandler(ABC):)else:asyncio.create_task(- self._send_channel_notice(+ self.send_channel_notice(user_infos,ch,msg.session_id,@@ -1183,7 +1350,7 @@ class MessageHandler(ABC):target_mode = ChannelMode.CODE_TEAMif target_mode is None:asyncio.create_task(- self._send_channel_notice(+ self.send_channel_notice(user_infos,ch,msg.session_id,@@ -1210,7 +1377,7 @@ class MessageHandler(ABC):)else:asyncio.create_task(- self._send_channel_notice(+ self.send_channel_notice(user_infos,ch,msg.session_id,@@ -1220,7 +1387,7 @@ class MessageHandler(ABC):return Trueif parsed.action in (ParsedControlAction.MODE_BAD, ParsedControlAction.SWITCH_BAD):asyncio.create_task(- self._send_channel_notice(+ self.send_channel_notice(user_infos,ch,msg.session_id,@@ -1262,7 +1429,7 @@ class MessageHandler(ABC):if parsed.action is ParsedControlAction.REWIND_CANCEL:# 用户取消 rewindasyncio.create_task(- self._send_channel_notice(+ self.send_channel_notice(user_infos, ch, msg.session_id,"[收到 /rewind cancel] 已取消回退操作。",)@@ -1271,7 +1438,7 @@ class MessageHandler(ABC):if parsed.action is ParsedControlAction.REWIND_BAD:asyncio.create_task(- self._send_channel_notice(+ self.send_channel_notice(user_infos,ch,msg.session_id,@@ -1280,9 +1447,10 @@ class MessageHandler(ABC):)return True+ # ── origin/develop: /review / /security-review 指令 ──if parsed.action is ParsedControlAction.REVIEW_BAD:asyncio.create_task(- self._send_channel_notice(+ self.send_channel_notice(user_infos,ch,msg.session_id,@@ -1291,6 +1459,35 @@ class MessageHandler(ABC):)return True+ # ── V2: /join / /exit 共享会话指令 ──+ if parsed.action is ParsedControlAction.JOIN_OK:+ asyncio.create_task(+ self._join_exit.join_slash_handler(user_infos, ch, msg, parsed)+ )+ return True+ if parsed.action is ParsedControlAction.JOIN_BAD:+ asyncio.create_task(+ self.send_channel_notice(+ user_infos, ch, msg.session_id,+ "⚠️ join 指令格式错误",+ )+ )+ return True+ if parsed.action is ParsedControlAction.EXIT_OK:+ asyncio.create_task(+ self._join_exit.exit_slash_handler(user_infos, ch, msg, parsed)+ )+ return True+ if parsed.action is ParsedControlAction.EXIT_BAD:+ asyncio.create_task(+ self.send_channel_notice(+ user_infos, ch, msg.session_id,+ "exit 指令格式错误。正确格式:/exit <session_id>",+ )+ )+ return True++ # ── origin/develop: /review / /security-review 指令 ──if parsed.action is ParsedControlAction.REVIEW_OK:# /review [args]:注入 review prompt,转发 Agent 执行 gh pr list/view/diff 并分析pr_arg = parsed.pr_arg or ""@@ -1307,7 +1504,7 @@ class MessageHandler(ABC):if parsed.action is ParsedControlAction.SECURITY_REVIEW_BAD:asyncio.create_task(- self._send_channel_notice(+ self.send_channel_notice(user_infos,ch,msg.session_id,@@ -1332,7 +1529,7 @@ class MessageHandler(ABC):None, build_security_review_prompt, extra_arg, cwd)except GitPreExecError as exc:- await self._send_channel_notice(+ await self.send_channel_notice(user_infos,ch,msg.session_id,@@ -1409,12 +1606,12 @@ class MessageHandler(ABC):notice_payload["content"] = format_skills_list_for_notice(notice_payload if isinstance(notice_payload, dict) else None)- await self._send_channel_notice(+ await self.send_channel_notice(user_infos, channel_id, reply_session_id, notice_payload)except Exception as exc: # noqa: BLE001logger.exception("[MessageHandler] /skills list 请求失败: %s", exc)- await self._send_channel_notice(+ await self.send_channel_notice(user_infos,channel_id,reply_session_id,@@ -1439,10 +1636,10 @@ class MessageHandler(ABC):from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fieldsfrom jiuwenswarm.common.schema.message import ReqMethod- state = self._get_or_create_channel_state(msg)+ state = self.get_or_create_channel_state(msg)source_sid = state.session_idif not source_sid:- await self._send_channel_notice(+ await self.send_channel_notice(user_infos, channel_id, reply_session_id,{"error": "当前无活跃会话,无法分叉"},)@@ -1479,7 +1676,7 @@ class MessageHandler(ABC):await self._cancel_agent_work_for_session(msg, old_sid)- await self._send_channel_notice(+ await self.send_channel_notice(user_infos, channel_id, reply_session_id,f"[收到 /branch 指令] 已分叉会话「{fork_title}」,当前已切换到新会话。",)@@ -1488,13 +1685,13 @@ class MessageHandler(ABC):source_sid, fork_sid, fork_title,)except ValueError as e:- await self._send_channel_notice(+ await self.send_channel_notice(user_infos, channel_id, reply_session_id,{"error": f"分叉失败:{e}"},)except Exception as exc: # noqa: BLE001logger.exception("[MessageHandler] /branch 失败: %s", exc)- await self._send_channel_notice(+ await self.send_channel_notice(user_infos, channel_id, reply_session_id,{"error": f"分叉失败:{exc}"},)@@ -1512,16 +1709,16 @@ class MessageHandler(ABC):IM 渠道 /rewind 是不可逆操作,需要确认后才执行。"""- state = self._get_or_create_channel_state(msg)+ state = self.get_or_create_channel_state(msg)target_sid = state.session_idif not target_sid:- await self._send_channel_notice(+ await self.send_channel_notice(user_infos, channel_id, reply_session_id,{"error": "当前无活跃会话,无法回退"},)return- await self._send_channel_notice(+ await self.send_channel_notice(user_infos, channel_id, reply_session_id,f"[收到 /rewind {turn_index} 指令] 确认要回退到第 {turn_index} 轮吗?\n"f"此操作不可逆,将删除第 {turn_index} 轮及之后的所有对话。\n"@@ -1548,10 +1745,10 @@ class MessageHandler(ABC):from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fieldsfrom jiuwenswarm.common.schema.message import ReqMethod- state = self._get_or_create_channel_state(msg)+ state = self.get_or_create_channel_state(msg)target_sid = state.session_idif not target_sid:- await self._send_channel_notice(+ await self.send_channel_notice(user_infos, channel_id, reply_session_id,{"error": "当前无活跃会话,无法回退"},)@@ -1580,7 +1777,7 @@ class MessageHandler(ABC):removed = pl.get("removed_records", 0)context_ok = pl.get("rewind_context", False)- await self._send_channel_notice(+ await self.send_channel_notice(user_infos, channel_id, reply_session_id,f"[收到 /rewind 指令] 已回退到第 {turn_index} 轮"f'("{preview[:50]}")'@@ -1603,7 +1800,7 @@ class MessageHandler(ABC):remaining = result.get("remaining_records", 0)removed = result.get("removed_records", 0)- await self._send_channel_notice(+ await self.send_channel_notice(user_infos, channel_id, reply_session_id,f"[收到 /rewind 指令] 已回退到第 {turn_index} 轮"f'("{preview[:50]}")'@@ -1615,13 +1812,13 @@ class MessageHandler(ABC):target_sid, turn_index, remaining, removed,)except ValueError as e:- await self._send_channel_notice(+ await self.send_channel_notice(user_infos, channel_id, reply_session_id,{"error": f"回退失败:{e}"},)except Exception as exc: # noqa: BLE001logger.exception("[MessageHandler] /rewind 失败: %s", exc)- await self._send_channel_notice(+ await self.send_channel_notice(user_infos, channel_id, reply_session_id,{"error": f"回退失败:{exc}"},)@@ -1631,7 +1828,18 @@ class MessageHandler(ABC):channel_type = self._resolve_control_channel_type(msg)if channel_type not in self._control_channel_types:return- state = self._get_or_create_channel_state(msg)++ # V2: 若 resolve_member_by_user 已识别为 team 成员(metadata 含 member_name),+ # 则 session_id 和 mode 已由 handle_message 正确设置,不覆盖。+ if isinstance(msg.metadata, dict) and msg.metadata.get("member_name"):+ # 确保 mode=team,否则 AgentServer 不会走 process_team_message_stream+ if msg.params is None:+ msg.params = {}+ if isinstance(msg.params, dict):+ msg.params["mode"] = "team"+ return++ state = self.get_or_create_channel_state(msg)# 仅 _session_map_channel_types 中的通道族使用 SessionMap;其它受控通道仍按 config/state 与入站 session_id。cid = str(getattr(msg, "channel_id", "") or "")@@ -2041,11 +2249,15 @@ class MessageHandler(ABC):session_id: str | None,*,request_metadata: dict[str, Any] | None = None,+ app_id: str | None = None,) -> "Message":from jiuwenswarm.common.schema.message import Message, EventTypemetadata = MessageHandler._merge_agent_metadata(request_metadata, resp.metadata)+ # ── V2: 合并 resp 的 agent_ref ──+ resp_agent_ref = getattr(resp, "agent_ref", None)+# 从 metadata 中提取 group_digital_avatar 和 enable_memory 字段# 这些字段在 message_to_e2a 中被放入 metadata,需要在这里提取出来group_digital_avatar = bool(metadata.get("group_digital_avatar", False)) if metadata else False@@ -2075,6 +2287,8 @@ class MessageHandler(ABC):payload=payload,event_type=event_type,metadata=metadata,+ app_id=app_id,+ agent_ref=resp_agent_ref,group_digital_avatar=group_digital_avatar,enable_memory=enable_memory,)@@ -2094,6 +2308,8 @@ class MessageHandler(ABC):payload=payload,event_type=EventType.CHAT_FINAL,metadata=metadata,+ app_id=app_id,+ agent_ref=resp_agent_ref,group_digital_avatar=group_digital_avatar,enable_memory=enable_memory,)@@ -2153,14 +2369,28 @@ class MessageHandler(ABC):if not await self._handle_evolution_chunk(chunk, session_id, bus_metadata):return+ # 多应用:push 重建 Message 时补 app_id,否则 _resolve_app_id 兜底 "default",+ # channel_manager 精确路由 ChannelKey(channel_id, "default") 在多 app 场景拿不到+ # 正确 channel 实例(feishu config.app_id 非空时注册 key 是真实 app_id),+ # 退到 _get_channel_by_id 扫描会命中第一个实例,导致 send_user_file 等工具 push+ # 投递到错误 app 的 channel(config.chat_id/last_chat_id 不符)→ 文件发错人或发不出。+ # 流式请求取 _stream_app_ids[rid](与 process_stream 一致);非流式请求+ # _stream_app_ids 未注册,回退 request_metadata["app_id"](入站已透传)。+ _push_app_id = (+ self._stream_app_ids.get(rid, "")+ or (request_metadata.get("app_id") if isinstance(request_metadata, dict) else "")+ or (resp_md.get("app_id") if isinstance(resp_md, dict) else "")+ )out = self._chunk_to_message(- chunk, session_id=session_id, metadata=bus_metadata+ chunk, session_id=session_id, metadata=bus_metadata,+ app_id=_push_app_id,)await self.publish_robot_messages(out)logger.info(- "[MessageHandler] server_push 已写入 robot_messages: request_id=%s channel_id=%s",+ "[MessageHandler] server_push 已写入 robot_messages: request_id=%s channel_id=%s app_id=%s",rid,chunk.channel_id,+ _push_app_id,)def set_cron_controller(self, controller: Any) -> None:@@ -2232,7 +2462,9 @@ class MessageHandler(ABC):def _chunk_to_message(chunk: AgentResponseChunk,session_id: str | None,+ *,metadata: dict[str, Any] | None = None,+ app_id: str | None = None,) -> Message:"""将 AgentResponseChunk 转换为 Message(用于流式处理)。metadata 传入 request 的 metadata,供 Feishu/Xiaoyi 等通道回发时使用平台身份。@@ -2244,6 +2476,14 @@ class MessageHandler(ABC):group_digital_avatar = bool(metadata.get("group_digital_avatar", False)) if metadata else Falseenable_memory = bool(metadata.get("enable_memory", True)) if metadata else True+ # ── V2: 合并 chunk.metadata(含 fan_out_targets)+ chunk.agent_ref ──+ chunk_md = getattr(chunk, "metadata", None) or {}+ merged_metadata: dict[str, Any] | None = None+ if metadata or chunk_md:+ merged_metadata = {**(metadata or {}), **chunk_md}++ chunk_agent_ref = getattr(chunk, "agent_ref", None)+# 从 payload 中提取 event_type(如果存在)event_type = Nonepayload = chunk.payload@@ -2269,7 +2509,9 @@ class MessageHandler(ABC):ok=True,payload=payload,event_type=event_type,- metadata=metadata,+ metadata=merged_metadata,+ app_id=app_id,+ agent_ref=chunk_agent_ref,group_digital_avatar=group_digital_avatar,enable_memory=enable_memory,)@@ -2311,6 +2553,7 @@ class MessageHandler(ABC):chunk,session_id=session_id,metadata=request_metadata,+ app_id=self._stream_app_ids.get(chunk.request_id, ""),)await self.publish_robot_messages(out)return True@@ -2525,6 +2768,7 @@ class MessageHandler(ABC):promoted_chunk,session_id=msg.session_id,metadata=promoted_approval.metadata,+ app_id=msg.app_id or "",)await self.publish_robot_messages(out)logger.info(@@ -2538,6 +2782,7 @@ class MessageHandler(ABC):msg.session_id,msg.channel_id,is_processing=False,+ app_id=msg.app_id or "",)return@@ -2570,6 +2815,7 @@ class MessageHandler(ABC):msg.session_id,msg.channel_id,is_processing=False,+ app_id=msg.app_id or "",)@staticmethod@@ -2680,7 +2926,7 @@ class MessageHandler(ABC):env: "E2AEnvelope",) -> "AgentResponse":return await send_agent_request_with_timeout(- self._agent_client,+ self.agent_client,env,label="MessageHandler",)@@ -2693,6 +2939,7 @@ class MessageHandler(ABC):resp,session_id=msg.session_id,request_metadata=msg.metadata,+ app_id=msg.app_id or "",)await self.publish_robot_messages(out)logger.info(@@ -2748,6 +2995,11 @@ class MessageHandler(ABC):# 将当前 Channel 的控制状态应用到消息上self._apply_channel_state(msg)+ # V2: _apply_channel_state has resolved msg.session_id to the real team+ # session_id and injected params.mode; register GodView now so it lands+ # under the same session team-event dispatch uses.+ await self._maybe_register_godview(msg)+# Gateway hook: UserPromptSubmitif self._gateway_hook_handler:try:@@ -3008,7 +3260,7 @@ class MessageHandler(ABC):parsed = parse_channel_control_text(stripped)if parsed.action is ParsedControlAction.REVIEW_BAD:asyncio.create_task(- self._send_channel_notice(+ self.send_channel_notice({"id": msg.id, "meta_data": msg.metadata},msg.channel_id,msg.session_id,@@ -3032,7 +3284,7 @@ class MessageHandler(ABC):)elif parsed.action is ParsedControlAction.SECURITY_REVIEW_BAD:asyncio.create_task(- self._send_channel_notice(+ self.send_channel_notice({"id": msg.id, "meta_data": msg.metadata},msg.channel_id,msg.session_id,@@ -3060,7 +3312,7 @@ class MessageHandler(ABC):))except GitPreExecError as exc:- await self._send_channel_notice(+ await self.send_channel_notice({"id": msg.id, "meta_data": msg.metadata},msg.channel_id,msg.session_id,@@ -3156,7 +3408,8 @@ class MessageHandler(ABC):emit_processing_status = self._should_emit_processing_status_for_stream(msg)if emit_processing_status:await self._send_processing_status(- stream_rid, msg.session_id, msg.channel_id, is_processing=True,+ stream_rid, msg.session_id, msg.channel_id,+ is_processing=True, app_id=msg.app_id or "",)task = asyncio.create_task(self.process_stream(@@ -3171,6 +3424,7 @@ class MessageHandler(ABC):self._stream_sessions[stream_rid] = msg.session_idself._stream_metadata[stream_rid] = msg.metadataself._stream_emits_processing_status[stream_rid] = emit_processing_status+ self._stream_app_ids[stream_rid] = msg.app_id or ""self._stream_modes[stream_rid] = (msg.params.get("mode", "plan") if isinstance(msg.params, dict) else "plan")@@ -3219,15 +3473,25 @@ class MessageHandler(ABC):"""rid = env.request_id or ""channel_id = env.channel or ""+ stream_app_id = self._stream_app_ids.get(rid, "") # 提前捕获,_pop_stream_tracking 后会清除cancelled = False- has_processing_status_false = False # 追踪 AgentServer 是否已发送 processing_status=false+ has_processing_status_false = False+ _proc_count = 0+ logger.info(+ "[MessageHandler] process_stream started: request_id=%s channel=%s session=%s",+ rid, channel_id, session_id,+ )try:- async for chunk in self._agent_client.send_request_stream(env):- if self._is_terminal_stream_chunk(chunk):- logger.debug(- "[MessageHandler] 跳过终止 chunk: request_id=%s",- chunk.request_id,+ async for chunk in self.agent_client.send_request_stream(env):+ _proc_count += 1+ if _proc_count <= 3:+ _pl = getattr(chunk, "payload", None) or {}+ _et = _pl.get("event_type", "") if isinstance(_pl, dict) else ""+ logger.info(+ "[MessageHandler] process_stream chunk #%s: request_id=%s event_type=%s",+ _proc_count, rid, _et,)+ if self._is_terminal_stream_chunk(chunk):continuepublished = await self.publish_stream_chunk(chunk,@@ -3253,25 +3517,24 @@ class MessageHandler(ABC):has_processing_status_false = Truecontinue+ _has_fanout = bool((getattr(chunk, "metadata", None) or {}).get("fan_out_targets"))logger.debug(- "[MessageHandler] Stream chunk 已写入 robot_messages: request_id=%s event_type=%s",+ "[MessageHandler] Stream chunk 已写入 robot_messages:"+ " request_id=%s event_type=%s has_fanout=%s",chunk.request_id,payload.get("event_type") if isinstance(payload, dict) else None,+ _has_fanout,)logger.info(- "[MessageHandler] Stream 正常完成: request_id=%s",- rid,+ "[MessageHandler] Stream 正常完成: request_id=%s total_chunks=%s",+ rid, _proc_count,)except asyncio.CancelledError:cancelled = Truelogger.info(- "[MessageHandler] Stream 被取消: request_id=%s",- rid,- )- await self._publish_stream_cancelled_final(- rid, channel_id, session_id, request_metadata,+ "[MessageHandler] Stream 被取消: request_id=%s total_chunks=%s",+ rid, _proc_count,)- raise # 重新抛出,让调用者知道任务被取消except RuntimeError as exc:if "AgentServer WebSocket connection closed" not in str(exc):raise@@ -3282,6 +3545,15 @@ class MessageHandler(ABC):request_metadata,str(exc),)+ except Exception as exc:+ logger.exception(+ "[MessageHandler] Stream 异常: request_id=%s total_chunks=%s error=%s",+ rid, _proc_count, exc,+ )+ await self._publish_stream_cancelled_final(+ rid, channel_id, session_id, request_metadata,+ )+ raise # 重新抛出,让调用者知道任务被取消finally:if (not cancelled@@ -3325,7 +3597,8 @@ class MessageHandler(ABC):)if not session_has_active_tasks:await self._send_processing_status(- rid, session_id, channel_id, is_processing=False,+ rid, session_id, channel_id,+ is_processing=False, app_id=stream_app_id,)logger.info("[MessageHandler] 该 session 流式任务已完成,已发送 is_processing=false: session_id=%s",@@ -3433,15 +3706,17 @@ class MessageHandler(ABC):)async def _send_processing_status(- self, request_id: str, session_id: str | None, channel_id: str, *, is_processing: bool,+ self, request_id: str, session_id: str | None, channel_id: str, *,+ is_processing: bool, app_id: str = "",) -> None:- """发送 chat.processing_status 事件到客户端."""+ """发送 chat.processing_status 事件到客户端。"""from jiuwenswarm.common.schema.message import Message, EventTypestatus_msg = Message(id=request_id,type="event",channel_id=channel_id,+ app_id=app_id,session_id=session_id,params={},timestamp=time.time(),@@ -3481,6 +3756,7 @@ class MessageHandler(ABC):ok=False,payload=payload,metadata=msg.metadata,+ app_id=msg.app_id or "",)def _build_tool_result_message(diff --git a/jiuwenswarm/gateway/routing/agent_client.py b/jiuwenswarm/gateway/routing/agent_client.pyindex 39b65f333a..2d9d84b17f 100644--- a/jiuwenswarm/gateway/routing/agent_client.py+++ b/jiuwenswarm/gateway/routing/agent_client.py@@ -481,6 +481,14 @@ class WebSocketAgentServerClient(AgentServerClient):raise RuntimeError("AgentServer WebSocket connection closed") from data.excchunk = parse_agent_server_wire_chunk(data)chunk_count += 1+ if chunk_count <= 3:+ _pl = getattr(chunk, "payload", None) or {}+ _et = _pl.get("event_type", "") if isinstance(_pl, dict) else ""+ logger.info(+ "[WebSocketAgentServerClient] stream chunk received:"+ " request_id=%s seq=%s event_type=%s",+ rid, chunk_count, _et,+ )yield chunkif chunk.is_complete:saw_complete = Truediff --git a/jiuwenswarm/gateway/routing/base_ws_channel.py b/jiuwenswarm/gateway/routing/base_ws_channel.pynew file mode 100644index 0000000000..0940d22ae9--- /dev/null+++ b/jiuwenswarm/gateway/routing/base_ws_channel.py@@ -0,0 +1,360 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""BaseWsChannel —— WebSocket 类 Channel 共享基类。++提供 _clients_by_key (5 维 RoutingKey → list[ws]) 双向索引,+以及 register_ws / unregister_ws / send 的默认实现。+"""++from __future__ import annotations++import asyncio+import logging+import uuid+from abc import abstractmethod+from typing import Any++from jiuwenswarm.gateway.channel_manager.base import BaseChannel+from jiuwenswarm.gateway.routing.keys import DeliveryTarget, RoutingKey+from jiuwenswarm.gateway.routing.session_sharing import RoutingTarget++logger = logging.getLogger(__name__)++# 兼容标识:子类可覆写 defaults,或由 GatewayServer 注入+_BROADCAST_FALLBACK_CHANNEL_IDS: frozenset[str] = frozenset()+++class BaseWsChannel(BaseChannel):+ """WebSocket 通道共享基类。++ 继承 BaseChannel,提供 _clients_by_key (5 维 RoutingKey → list[ws]) 双向索引,+ 以及 register_ws / unregister_ws / send 的默认实现。++ 子类(WebChannel / TuiChannel)需覆写:+ - _serialize_frame() — 将 Message 转为 wire frame(str/bytes)+ - 可覆写 _broadcast_fallback_enabled — 控制是否启用查找失败时广播兜底(默认关闭)+ """++ # 子类应覆写+ channel_id: str = ""++ def __init__(self, config: Any, router: Any) -> None:+ super().__init__(config, router)+ self._clients_by_key: dict[RoutingKey, list[Any]] = {}+ # ws_id ↔ ws 双向映射:物理寻址层,send 优先按 delivery.ws_id 查 ws+ self._ws_by_id: dict[str, Any] = {}+ self._id_by_ws: dict[int, str] = {}+ self._lock = asyncio.Lock()+ # per-ws 出站队列 + 常驻 writer 协程:解耦 dispatch loop 与 ws.send 慢 IO。+ # dispatch 调 send 只 put_nowait 入队即返回(微秒级),writer 串行 await ws.send+ # ——同一连接帧顺序严格保留(legacy websockets 写锁本就串行,这里显式化并隔离+ # 背压到 writer,不阻塞 dispatch loop)。详见 doc/analysis/ws-send-backpressure.md+ self._send_queues: dict[str, "asyncio.Queue[str | bytes | None]"] = {}+ self._writers: dict[str, asyncio.Task] = {}+ self._outbound_lock = asyncio.Lock()++ # ── ws 池管理 ──++ async def register_ws(+ self,+ ws: Any,+ routing_key: RoutingKey,+ *,+ evict_previous: bool = False,+ ) -> None:+ """握手时注册 ws → RoutingKey 映射,并生成 ws_id 挂到 ws 上.++ 默认 ``evict_previous=False``:一个 ws 可同时挂在多个 session_id 桶里,+ 支持多 session 共存(Web 多 tab 语义)。投递精准度由 ``send`` 的+ ``delivery.ws_id`` 物理寻址保证,不依赖摘链。++ ``evict_previous=True``:注册前先从所有旧 RoutingKey 条目中移除该 ws,+ 用于显式窗口级切换(``\\new_session`` 控制命令、ACP 单用户通道)——+ 旧 session 的延迟 chunk 不应再路由到该 ws。ws_id 映射不受影响,+ 断连重连后物理寻址仍可命中。+ """+ async with self._lock:+ ws_key = id(ws)+ ws_id = self._id_by_ws.get(ws_key)+ if ws_id is None:+ ws_id = uuid.uuid4().hex+ setattr(ws, "_jiuwen_ws_id", ws_id)+ self._ws_by_id[ws_id] = ws+ self._id_by_ws[ws_key] = ws_id+ # 新 ws:建出站队列 + 起常驻 writer 协程+ self._send_queues[ws_id] = asyncio.Queue()+ self._writers[ws_id] = asyncio.create_task(+ self._writer_loop(ws, ws_id), name=f"ws-writer-{ws_id}"+ )+ # 仅显式窗口级切换才摘链:把这个 ws 从所有其他 session 桶里移除。+ # Web 普通请求(chat.send / history.get / session.create)不摘,+ # 让同一 ws 的多 session 在途流式输出互不干扰。+ if evict_previous:+ for rk, ws_list in list(self._clients_by_key.items()):+ try:+ ws_list.remove(ws)+ except ValueError:+ continue+ if not ws_list:+ del self._clients_by_key[rk]+ bucket = self._clients_by_key.setdefault(routing_key, [])+ if ws not in bucket:+ bucket.append(ws)+ logger.info(+ "[%s] ws registered: user_id=%s session_id=%s agent_ref=%s ws_id=%s evict=%s",+ self.channel_id,+ routing_key.user_id,+ routing_key.session_id,+ routing_key.agent_ref,+ ws_id,+ evict_previous,+ )++ async def unregister_ws(self, ws: Any) -> list[RoutingKey]:+ """断连时扫描 _clients_by_key 摘除死 ws,并清理 ws_id 映射。++ 返回受影响的 RoutingKey 列表(供子类 on_disconnect 使用)。++ 收尾顺序(关键):先 flush 残余帧 → 再 cancel writer + 清队列。+ 若先取消 writer,队尾帧将永远送不出去(残留 bug)。ws 已断时 flush+ 会快速失败退出,不会卡住。+ """+ affected: list[RoutingKey] = []+ async with self._lock:+ for rk, ws_list in list(self._clients_by_key.items()):+ try:+ ws_list.remove(ws)+ except ValueError:+ continue+ affected.append(rk)+ if not ws_list:+ del self._clients_by_key[rk]+ # 清理 ws_id ↔ ws 映射+ ws_key = id(ws)+ ws_id = self._id_by_ws.pop(ws_key, None)+ if ws_id:+ self._ws_by_id.pop(ws_id, None)+ # 在锁外 flush + 清理 writer(flush 要 await,避免长持锁)+ if ws_id:+ await self._drain_and_cleanup_writer(ws, ws_id)+ if affected:+ logger.info(+ "[%s] ws unregistered: removed from %d routing keys ws_id=%s",+ self.channel_id,+ len(affected),+ ws_id,+ )+ return affected++ # ── 出站 ──++ def _broadcast_fallback_enabled(self) -> bool:+ """子类可覆写控制是否启用广播兜底."""+ return self.channel_id in _BROADCAST_FALLBACK_CHANNEL_IDS++ async def send(+ self,+ msg: Any, # Message(跨协议兼容)+ *,+ routing_target: RoutingTarget | None = None,+ ) -> None:+ """默认 ws send:按 resolved.routing_keys 查 ws 列表,写序列化后的帧。++ V2: send(msg, routing_target=RoutingTarget),2 参数,RoutingTarget 自包含 delivery。+ 不再平铺 at_user_ids / member_names / routing_keys 等散参数。+ """+ if routing_target is None:+ return++ routing_keys = routing_target.routing_keys+ member_names = list(routing_target.member_names)++ ws_set: set[Any] = set()++ # ── 优先:按 delivery.ws_id 物理寻址(V2 §3.1 职责分界)──+ delivery = routing_target.delivery+ if delivery is not None:+ ws_id = getattr(delivery, "ws_id", "")+ if ws_id:+ ws = self._ws_by_id.get(ws_id)+ if ws is not None and not getattr(ws, "closed", False):+ ws_set.add(ws)++ # ── 兜底:按 routing_keys 5 维逻辑查 _clients_by_key ──+ if not ws_set:+ for rk in routing_keys:+ ws_list = self._clients_by_key.get(rk) or []+ for w in ws_list:+ if not getattr(w, "closed", False):+ ws_set.add(w)++ if not ws_set and self._broadcast_fallback_enabled():+ for ws_list in self._clients_by_key.values():+ for w in ws_list:+ if not getattr(w, "closed", False):+ ws_set.add(w)++ if not ws_set:+ return++ frame = self._serialize_frame(msg, routing_target, member_names=member_names)+ # 非阻塞入队:dispatch loop 不 await IO,背压隔离在 writer 协程内+ for w in ws_set:+ self._enqueue_send(w, frame)++ # ── per-ws writer:出站背压隔离 ──++ def _enqueue_send(self, ws: Any, data: str | bytes) -> None:+ """非阻塞入队一帧到 ws 的出站队列,立即返回。++ ws 已关闭或队列缺失时静默丢弃(与旧 _safe_send 忽略 closed ws 语义一致)。+ """+ if getattr(ws, "closed", False):+ return+ ws_id = getattr(ws, "_jiuwen_ws_id", "")+ q = self._send_queues.get(ws_id)+ if q is None:+ return+ try:+ q.put_nowait(data)+ except asyncio.QueueFull:+ logger.warning(+ "[%s] outbound queue full, dropping frame ws_id=%s", self.channel_id, ws_id,+ )++ async def _writer_loop(self, ws: Any, ws_id: str) -> None:+ """常驻 writer:串行 await ws.send,保证同连接帧顺序。++ - get() 阻塞时无残余帧(队列空),断连时由 unregister_ws → _drain_and_cleanup_writer+ 唤醒并 flush。+ - None 是哨兵:取出即退出循环(用于收尾)。+ - ws.send 异常(连接已断):记录后退出,不再消费剩余帧。+ """+ q = self._send_queues[ws_id]+ while True:+ data = await q.get()+ if data is None: # 收尾哨兵+ return+ # 默认 _coalesce 只取刚 get 的这 1 帧;子类可覆写批量合并流式 chunk+ frames = [data] + self._coalesce(q)+ if getattr(ws, "closed", False):+ logger.debug("[%s] writer skip on closed ws ws_id=%s", self.channel_id, ws_id)+ return+ for frame in frames:+ if frame is None:+ continue+ try:+ await asyncio.wait_for(ws.send(frame), timeout=10.0)+ except asyncio.TimeoutError:+ logger.warning(+ "[%s] ws.send timed out 10s, dropping writer ws_id=%s",+ self.channel_id, ws_id,+ )+ return+ except Exception as e:+ if bool(getattr(ws, "closed", False)):+ logger.debug(+ "[%s] writer exit on closed ws ws_id=%s err=%s",+ self.channel_id, ws_id, e,+ )+ else:+ logger.warning(+ "[%s] writer ws.send error, exiting ws_id=%s err=%s",+ self.channel_id, ws_id, e,+ )+ return++ def _coalesce(self, q: "asyncio.Queue") -> list:+ """chunk 合并扩展点:从队列取若干帧合并为一帧,减小 ws.send 次数。++ 默认实现:只取 1 帧(不合并)。子类可覆写对 chat.delta/chat.reasoning+ 批量 get_nowait 合并 content,缓解高频流式 chunk 的背压。+ 队列为空时返回 [],不阻塞(writer 已 get 主帧)。+ """+ try:+ return [q.get_nowait()]+ except asyncio.QueueEmpty:+ return []++ async def _drain_and_cleanup_writer(self, ws: Any, ws_id: str) -> None:+ """收尾:flush 残余帧 → 取消 writer → 移除队列。++ 顺序关键:先投 None 哨兵让 writer 把残余帧发完再退出;若 ws 已断,+ writer 的 ws.send 会快速失败退出,flush 立即结束,不会卡住。+ 最后 cancel 兜底(writer 可能已自行退出)+ pop 队列防止泄漏。+ """+ q = self._send_queues.get(ws_id)+ writer = self._writers.get(ws_id)+ if q is not None and writer is not None and not writer.done():+ try:+ q.put_nowait(None) # 哨兵:发完残余帧后退出+ except asyncio.QueueFull:+ pass+ try:+ # 给 writer 一个 flush 窗口;ws 已断时它会快速失败退出+ await asyncio.wait_for(writer, timeout=5.0)+ except asyncio.TimeoutError:+ logger.warning(+ "[%s] writer flush timed out 5s, cancelling ws_id=%s", self.channel_id, ws_id,+ )+ writer.cancel()+ try:+ await writer+ except (asyncio.CancelledError, Exception):+ pass+ except Exception:+ pass # writer 内部异常已记录,此处吞掉避免影响断连流程+ if writer is not None and not writer.done():+ writer.cancel()+ self._writers.pop(ws_id, None)+ self._send_queues.pop(ws_id, None)++ async def _shutdown_all_writers(self) -> None:+ """通道关闭时批量清理所有 writer 协程 + 队列,防止泄漏。++ 正常断连由 _connection_handler finally → unregister_ws 逐个清理;+ 此处兜底处理 stop() 时未走正常断连路径的残留 writer。+ """+ ws_ids = list(self._writers.keys())+ if not ws_ids:+ return+ for ws_id in ws_ids:+ writer = self._writers.get(ws_id)+ if writer is not None and not writer.done():+ writer.cancel()+ for ws_id in ws_ids:+ writer = self._writers.pop(ws_id, None)+ if writer is not None and not writer.done():+ try:+ await writer+ except (asyncio.CancelledError, Exception):+ pass+ self._send_queues.pop(ws_id, None)+ logger.info(+ "[%s] shutdown %d writers on channel stop", self.channel_id, len(ws_ids),+ )++ # ── 子类覆写 ──++ @abstractmethod+ def _serialize_frame(+ self,+ msg: Any,+ routing_target: RoutingTarget | None,+ *,+ member_names: list[str] | None = None,+ ) -> str | bytes:+ """将 Message 序列化为 wire frame。子类必须实现."""++ # ── 内部工具 ──++ @staticmethod+ async def _safe_send(ws: Any, data: str | bytes) -> None:+ """[已废弃] 旧同步 send 路径,保留供未迁移子类兜底。++ 新出站走 _enqueue_send + per-ws writer,不再阻塞 dispatch loop。+ """+ try:+ await asyncio.wait_for(ws.send(data), timeout=5.0)+ except Exception as e:+ logger.debug("safe_send ignored ws.send error: %s", e)diff --git a/jiuwenswarm/gateway/routing/keys.py b/jiuwenswarm/gateway/routing/keys.pynew file mode 100644index 0000000000..5a77f87a9c--- /dev/null+++ b/jiuwenswarm/gateway/routing/keys.py@@ -0,0 +1,367 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""路由核心值对象:5 维路由键、Agent 标识、Channel 索引、物理投递地址."""++from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any++WILDCARD = "*"+APP_ID_DEFAULT = "default"+++@dataclass(frozen=True)+class AgentRef:+ """后端智能体标识。++ mode: 'agent' | 'code' | 'team'+ id: mode='agent'/'code' 时为 agent_id;mode='team' 时为 team_name+ """++ mode: str+ id: str++ @classmethod+ def default(cls) -> "AgentRef":+ return cls(mode="agent", id="default")++ def __repr__(self) -> str:+ return f"AgentRef({self.mode}:{self.id})"+++@dataclass(frozen=True)+class RoutingKey:+ """5 维路由键:(user_id, channel_id, app_id, agent_ref, session_id)。++ 不可变值对象。通配符 '*' 为监管等高级场景预留,主干路径全用精确值。+ """++ user_id: str+ channel_id: str+ app_id: str+ agent_ref: AgentRef+ session_id: str++ @property+ def channel_key(self) -> "ChannelKey":+ return ChannelKey(self.channel_id, self.app_id)++ @property+ def identity(self) -> "IdentityKey":+ return IdentityKey(self.channel_id, self.app_id, self.user_id)++ def to_dict(self) -> dict[str, Any]:+ return {+ "user_id": self.user_id,+ "channel_id": self.channel_id,+ "app_id": self.app_id,+ "agent_ref": {"mode": self.agent_ref.mode, "id": self.agent_ref.id},+ "session_id": self.session_id,+ }+++@dataclass(frozen=True)+class ChannelKey:+ """渠道实例标识,用于 ChannelManager._channels 索引."""++ channel_id: str # 'feishu' | 'web' | 'wecom' | ...+ app_id: str # 'cli_xxx' | 'default' | ...++ def __repr__(self) -> str:+ return f"{self.channel_id}:{self.app_id}"+++@dataclass(frozen=True)+class IdentityKey:+ """用户身份三元组,用于 SessionSharingRegistry.resolve_member_by_user() 反查."""++ channel_id: str+ app_id: str+ user_id: str+++# ── DeliveryTarget 基类 ──────────────────────────────────────+++@dataclass(frozen=True)+class DeliveryTarget:+ """物理投递地址基类。++ 每渠道独立子类,字段按渠道私有定义。+ Channel 的 send() 通过 isinstance() 判断具体子类后读取专属字段。+ """++ channel_id: str++ @property+ def container_kind(self) -> str:+ raise NotImplementedError++ def get_container_id(self) -> str:+ """物理容器去重标识,用于同容器合并投递."""+ raise NotImplementedError+++# ── ws 类 DeliveryTarget ──+++@dataclass(frozen=True)+class WebDeliveryTarget(DeliveryTarget):+ """Web ws 投递地址."""+ channel_id: str = "web"+ ws_id: str = ""++ @property+ def container_kind(self) -> str:+ return "ws"++ def get_container_id(self) -> str:+ return self.ws_id+++@dataclass(frozen=True)+class TuiDeliveryTarget(DeliveryTarget):+ """TUI 终端投递地址."""+ channel_id: str = "tui"+ ws_id: str = ""++ @property+ def container_kind(self) -> str:+ return "cli"++ def get_container_id(self) -> str:+ return self.ws_id+++@dataclass(frozen=True)+class AcpDeliveryTarget(DeliveryTarget):+ """ACP 协议投递地址."""+ channel_id: str = "acp"+ request_id: str = ""++ @property+ def container_kind(self) -> str:+ return "cli"++ def get_container_id(self) -> str:+ return self.request_id+++@dataclass(frozen=True)+class XiaoyiDeliveryTarget(DeliveryTarget):+ """小艺 ws/push 双通道投递地址.++ 字段对应小艺 message/stream 真实消息样本:+ - agent_id ← 消息 agentId(per-user agent 标识,= RoutingKey.user_id,去重主键)+ - push_id ← systemVariables.push_id(webhook 推送 token,随请求携带)+ - xiaoyi_session_id ← 顶层 sessionId(物理回发,临时,ws 投递用)+ - conversation_id ← conversationId / params.sessionId(逻辑会话,跨请求稳定)+ - url_key ← ws 连接键(空=双通道都发)+ """+ channel_id: str = "xiaoyi"+ agent_id: str = ""+ push_id: str = ""+ xiaoyi_session_id: str = ""+ conversation_id: str = ""+ url_key: str = ""++ @property+ def container_kind(self) -> str:+ return "ws"++ def get_container_id(self) -> str:+ # 按 agent_id 去重:per-user 稳定(push_id 随请求携带可能为空,不作主键)+ return self.agent_id or self.push_id+++# ── IM 类 DeliveryTarget ──+++@dataclass(frozen=True)+class FeishuDeliveryTarget(DeliveryTarget):+ """飞书 / 飞书企业版 投递地址(按 channel_id 区分)."""+ channel_id: str = "feishu" # 'feishu' | 'feishu_enterprise'+ chat_type: str = "group" # 'group' | 'p2p'+ chat_id: str = "" # 群: oc_xxx;私聊: oc_p2p_xxx+ receive_id: str = "" # SDK receive_id+ id_type: str = "chat_id" # 'chat_id' | 'open_id'+ physical_user_id: str = "" # 飞书 open_id(@ 标签注入用)++ @property+ def container_kind(self) -> str:+ return self.chat_type++ def get_container_id(self) -> str:+ return self.chat_id or self.receive_id+++@dataclass(frozen=True)+class WecomDeliveryTarget(DeliveryTarget):+ """企业微信投递地址."""+ channel_id: str = "wecom"+ chat_type: str = "group" # 'group' | 'p2p'+ chat_id: str = "" # 群 chat_id(appchat)+ user_id: str = "" # p2p 投递 user_id+ physical_user_id: str = "" # 企微 userid(@ 标签注入用)++ @property+ def container_kind(self) -> str:+ return self.chat_type++ def get_container_id(self) -> str:+ return self.chat_id or self.user_id+++@dataclass(frozen=True)+class DingTalkDeliveryTarget(DeliveryTarget):+ """钉钉投递地址."""+ channel_id: str = "dingtalk"+ chat_type: str = "group"+ open_conversation_id: str = ""+ sender_staff_id: str = ""+ physical_user_id: str = ""++ @property+ def container_kind(self) -> str:+ return self.chat_type++ def get_container_id(self) -> str:+ return self.open_conversation_id or self.sender_staff_id+++@dataclass(frozen=True)+class TelegramDeliveryTarget(DeliveryTarget):+ """Telegram 投递地址."""+ channel_id: str = "telegram"+ chat_id: int = 0 # 群: <0;私聊: >0+ physical_user_id: str = ""++ @property+ def container_kind(self) -> str:+ return "group" if self.chat_id < 0 else "p2p"++ def get_container_id(self) -> str:+ return str(self.chat_id)+++@dataclass(frozen=True)+class DiscordDeliveryTarget(DeliveryTarget):+ """Discord 投递地址."""+ channel_id: str = "discord"+ chat_type: str = "group"+ target_channel_id: int = 0+ physical_user_id: str = ""++ @property+ def container_kind(self) -> str:+ return self.chat_type++ def get_container_id(self) -> str:+ return str(self.target_channel_id)+++@dataclass(frozen=True)+class WhatsAppDeliveryTarget(DeliveryTarget):+ """WhatsApp 投递地址."""+ channel_id: str = "whatsapp"+ target_jid: str = ""++ @property+ def container_kind(self) -> str:+ return "group" if self.target_jid.endswith("@g.us") else "p2p"++ def get_container_id(self) -> str:+ return self.target_jid+++@dataclass(frozen=True)+class WechatDeliveryTarget(DeliveryTarget):+ """微信投递地址(仅私聊,无群聊)."""+ channel_id: str = "wechat"+ user_id: str = ""++ @property+ def container_kind(self) -> str:+ return "p2p"++ def get_container_id(self) -> str:+ return self.user_id+++# ── 工厂函数 ──+++def make_delivery_target(+ channel_id: str,+ *,+ chat_id: str = "",+ receive_id: str = "",+ physical_user_id: str = "",+ ws_id: str = "",+ **kwargs: Any,+) -> DeliveryTarget:+ """按 channel_id 构造对应渠道的 DeliveryTarget 子类实例。++ 各渠道只传自己需要的字段,其余由子类默认值填充。+ """+ _ch = channel_id or "web"+ if _ch in ("web",):+ return WebDeliveryTarget(channel_id=_ch, ws_id=ws_id)+ if _ch in ("tui",):+ return TuiDeliveryTarget(channel_id=_ch, ws_id=ws_id)+ if _ch in ("acp",):+ return AcpDeliveryTarget(channel_id=_ch, request_id=kwargs.get("request_id", ""))+ if _ch in ("xiaoyi",):+ return XiaoyiDeliveryTarget(+ channel_id=_ch,+ agent_id=physical_user_id,+ push_id=kwargs.get("push_id", ""),+ xiaoyi_session_id=kwargs.get("xiaoyi_session_id", "") or chat_id,+ conversation_id=kwargs.get("conversation_id", ""),+ url_key=kwargs.get("url_key", ""),+ )+ if _ch in ("feishu", "feishu_enterprise"):+ return FeishuDeliveryTarget(+ channel_id=_ch,+ chat_type="group" if chat_id else "p2p",+ chat_id=chat_id,+ receive_id=receive_id or chat_id or physical_user_id,+ id_type="chat_id" if chat_id else "open_id",+ physical_user_id=physical_user_id,+ )+ if _ch in ("wecom",):+ return WecomDeliveryTarget(+ channel_id=_ch,+ chat_type="group" if chat_id else "p2p",+ chat_id=chat_id,+ physical_user_id=physical_user_id,+ )+ if _ch in ("dingtalk",):+ return DingTalkDeliveryTarget(+ channel_id=_ch,+ physical_user_id=physical_user_id,+ )+ if _ch in ("telegram",):+ return TelegramDeliveryTarget(+ channel_id=_ch,+ chat_id=int(chat_id or "0"),+ physical_user_id=physical_user_id,+ )+ if _ch in ("discord",):+ return DiscordDeliveryTarget(+ channel_id=_ch,+ physical_user_id=physical_user_id,+ )+ if _ch in ("whatsapp",):+ return WhatsAppDeliveryTarget(+ channel_id=_ch,+ target_jid=chat_id or receive_id,+ )+ if _ch in ("wechat",):+ return WechatDeliveryTarget(+ channel_id=_ch,+ user_id=physical_user_id or receive_id,+ )+ # fallback: 未知渠道,返回基础实例(不推荐)+ return WebDeliveryTarget(channel_id=_ch, ws_id=ws_id)diff --git a/jiuwenswarm/gateway/routing/route_binding.py b/jiuwenswarm/gateway/routing/route_binding.pyindex b8f52ca1c8..09536ee807 100644--- a/jiuwenswarm/gateway/routing/route_binding.py+++ b/jiuwenswarm/gateway/routing/route_binding.py@@ -18,3 +18,5 @@ class GatewayRouteBinding:disconnect_handler: Callable[..., Any] | None = Nonesession_bind_handler: Callable[..., Any] | None = Noneinstall: Callable[[Any], None] | None = None+ # V2: 委托 ws 注册的外部 Channel(tui 的 TuiChannel)。None = 不委托。+ ws_channel: Any = Nonediff --git a/jiuwenswarm/gateway/routing/session_sharing.py b/jiuwenswarm/gateway/routing/session_sharing.pynew file mode 100644index 0000000000..bee8b8ed1c--- /dev/null+++ b/jiuwenswarm/gateway/routing/session_sharing.py@@ -0,0 +1,499 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""共享会话订阅表 + 分发意图 + 响应分发入口."""++from __future__ import annotations++import asyncio+import logging+import time+import uuid+from dataclasses import dataclass, field+from typing import Optional++from jiuwenswarm.gateway.routing.keys import ChannelKey, DeliveryTarget, IdentityKey, RoutingKey++logger = logging.getLogger(__name__)+++# ── 订阅角色常量 ──────────────────────────────────────────────+# 两种订阅角色,决定消息分发语义:+# GODVIEW — 直接 ws/webhook 接入的上帝视角端,接收全部消息(含默认无 fan_out 的流式输出)+# MEMBER — 通过 /join 认领 HumanAgent 席位的成员,仅接收 @mention 自己的消息+++class SubRole:+ """订阅角色常量。++ 不同角色决定 dispatch 时的订阅者选择逻辑:+ - GODVIEW: 查 registry.lookup_member(session, SubRole.GODVIEW) → 默认分发目标+ - MEMBER: 查 registry.lookup_member(session, member_name) → @mention 精准投递+ """++ GODVIEW = "GodView"+ MEMBER = "member" # member_name 由 /join 时指定,如 "reviewer-1"+++# ── Subscription ──────────────────────────────────────────────+++@dataclass(frozen=True)+class Subscription:+ """一条投递订阅。++ 同一 member_name 可以有多条 Subscription(多窗口/多设备)。+ 每条独立注册、独立注销。++ member_name 语义:+ - SubRole.GODVIEW ("GodView") — 上帝视角订阅者,接收所有消息+ - 其他 — HumanAgent 席位名,仅接收 @mention 自己的消息+ """++ sub_id: str+ member_name: str+ routing_key: RoutingKey+ delivery: DeliveryTarget+ joined_at: float = field(default_factory=time.time)++ @property+ def identity(self) -> IdentityKey:+ return self.routing_key.identity++ @property+ def is_godview(self) -> bool:+ return self.member_name == SubRole.GODVIEW+++# ── LogicalTarget ──────────────────────────────────────────────+# V1 概念:线协议上的逻辑投递目标,由 AgentServer team_helpers 产出,经 E2A metadata 传到 Gateway。+# V2 简化:intent 从三态 (broadcast/mention/private) 减为二态 (godview/mention),+# 增补 mention_all / speaker 字段以覆盖 @all 和 HumanAgent 定向消息场景。+++@dataclass+class LogicalTarget:+ """线协议逻辑投递目标(V1 概念,V2 字段简化)。++ AgentServer 能从 OpenJiuwen interaction.payload 直接得知的逻辑信息,+ 不含任何物理寻址(无 RoutingKey、无物理 user_id)。+ """++ intent: str # 'godview' | 'mention' | 'private'+ mention_all: bool = False # True = @all,忽略 member_names+ member_names: tuple[str, ...] = () # 点名席位(mention_all=False 时有效)+ speaker: str | None = None # 发言人 member_name+++# ── RoutingTarget ─────────────────────────────────────────────+# V1 概念:LogicalTarget 经 Registry 反查后的物理投递结果,Gateway 进程内构造。+# V2 改进:routing_keys 是 list(容器级聚合多成员),V1 是单一 RoutingKey(成员级)。+++@dataclass+class RoutingTarget:+ """物理投递目标——聚合结果,自包含。++ LogicalTarget 经 Registry 反查 → 按容器分组去重 → 组装为此结构。+ 一个 RoutingTarget 对应一个物理容器,内含该容器所需的一切投递信息。+ """++ intent: str # 'godview' | 'mention'+ member_names: tuple[str, ...] = () # 逻辑收件席位+ speaker: str | None = None+ mention_all: bool = False+ routing_keys: list[RoutingKey] = field(default_factory=list)+ mention_member_ids: list[str] = field(default_factory=list) # 物理 @ 用户 ID 列表(飞书 open_id / 企微 userid)+ delivery: DeliveryTarget | None = None # 物理地址(容器级,与 routing_keys 配对)++ @classmethod+ def from_logical(cls, target: LogicalTarget) -> "RoutingTarget":+ return cls(+ intent=target.intent,+ member_names=target.member_names,+ speaker=target.speaker,+ mention_all=target.mention_all,+ )+++# ── SessionSharingRegistry ────────────────────────────────────+++@dataclass(frozen=True)+class _UnregisterResult:+ session_id: str+ member_name: str+ slot_freed: bool # True = 该 member 的所有订阅都已清除+++class SessionSharingRegistry:+ """共享会话订阅表。++ 内部结构::++ {+ session_id: {+ member_name: [Subscription, ...]+ }+ }++ - 同一 session 下的同一 member_name 可以有多条 Subscription+ - 注册/注销以 sub_id 为精确单位+ - 纯内存态,asyncio.Lock 保护,Gateway 重启需重新 /join+ """++ def __init__(self) -> None:+ self._subs: dict[str, dict[str, list[Subscription]]] = {}+ self._lock = asyncio.Lock()++ # ── 注册 / 注销 ──++ async def register(+ self,+ session_id: str,+ member_name: str,+ routing_key: RoutingKey,+ delivery: DeliveryTarget,+ ) -> Subscription:+ sub = Subscription(+ sub_id=uuid.uuid4().hex[:12],+ member_name=member_name,+ routing_key=routing_key,+ delivery=delivery,+ )+ async with self._lock:+ self._subs.setdefault(session_id, {}).setdefault(member_name, []).append(sub)+ logger.info(+ "[Registry] register: session=%s member=%s sub_id=%s",+ session_id, member_name, sub.sub_id,+ )+ return sub++ async def unregister(self, sub_id: str) -> Optional[_UnregisterResult]:+ """按 sub_id 精确移除一条订阅."""+ async with self._lock:+ for sid, members in self._subs.items():+ for mname, subs in list(members.items()):+ for s in subs:+ if s.sub_id == sub_id:+ subs.remove(s)+ release = _UnregisterResult(sid, mname, not subs)+ if not subs:+ del members[mname]+ if not members:+ del self._subs[sid]+ logger.info(+ "[Registry] unregister: session=%s member=%s sub_id=%s slot_freed=%s",+ sid, mname, sub_id, release.slot_freed,+ )+ return release+ return None++ async def unregister_all_for_identity(+ self, channel_id: str, app_id: str, user_id: str,+ session_id: str | None = None,+ member_name: str | None = None,+ ) -> list[_UnregisterResult]:+ """移除该身份的所有订阅(/exit 时用)。++ 若指定 session_id,仅移除该 session 下的订阅;+ 若指定 member_name,仅移除该 member 的订阅(防止踢掉同一身份的其他席位)。+ """+ results: list[_UnregisterResult] = []+ async with self._lock:+ _sessions = (+ {session_id: self._subs.get(session_id, {})}+ if session_id+ else self._subs+ )+ for sid, members in list(_sessions.items()):+ for mname, subs in list(members.items()):+ if member_name and mname != member_name:+ continue+ removed = []+ for s in subs:+ if s.routing_key.channel_id != channel_id:+ continue+ if s.routing_key.app_id != app_id:+ continue+ if s.routing_key.user_id != user_id:+ continue+ removed.append(s)+ for s in removed:+ subs.remove(s)+ slot_freed = not subs+ if slot_freed:+ del members[mname]+ results.append(_UnregisterResult(sid, mname, slot_freed))+ if not members:+ del self._subs[sid]+ for r in results:+ logger.info(+ "[Registry] unregister_all_for_identity: session=%s member=%s slot_freed=%s",+ r.session_id, r.member_name, r.slot_freed,+ )+ return results++ # ── 查询 ──++ def lookup_member(self, session_id: str, member_name: str) -> list[Subscription]:+ """取某 session 下某 member 的所有订阅."""+ return list(self._subs.get(session_id, {}).get(member_name, []))++ def lookup_all(self, session_id: str) -> list[Subscription]:+ """取某 session 下全部订阅."""+ result: list[Subscription] = []+ for members in self._subs.get(session_id, {}).values():+ result.extend(members)+ return result++ def lookup_by_container(+ self, channel_id: str, app_id: str, container_id: str,+ ) -> list[tuple[str, str, Subscription]]:+ """按物理容器查找所有订阅(跨 session)。++ 用于 /join 前检查同一物理容器(如飞书 chat_id)是否已在其他 session 注册。+ 返回 [(session_id, member_name, subscription), ...]++ 排除 GodView 订阅:GodView 是 _maybe_register_godview 自动注册的通道级伪+ member(接收全量输出),不是 /join 认领的真实席位,不应参与"同一容器不能+ 同时占多个 session"的去重约束。否则飞书群 /mode team 自动注册 GodView 后,+ 再 /join 真实 member 会被自己的 GodView 挡住(报"已加入 session 席位:GodView")。+ 与 resolve_member_by_user 的 is_godview 跳过保持一致。+ """+ if not container_id:+ return []+ results: list[tuple[str, str, Subscription]] = []+ for sid, members in self._subs.items():+ for mname, subs in members.items():+ for s in subs:+ if s.is_godview:+ continue+ if s.routing_key.channel_id != channel_id:+ continue+ if s.routing_key.app_id != app_id:+ continue+ if s.delivery.get_container_id() == container_id:+ results.append((sid, mname, s))+ return results++ def resolve_member_by_user(+ self, channel_id: str, app_id: str, user_id: str,+ chat_id: str = "",+ ) -> Optional[tuple[str, str]]:+ """按物理用户信息反查 (session_id, member_name)。++ 用于 MessageHandler 请求侧自动补 member_name。+ 若同一用户在多个 chat 下有不同席位(如私聊 reviewer-1 / 群聊 reviewer-2),+ 通过 chat_id 精确匹配当前对话应有的 member_name。+ """+ # 第一遍:精确匹配 chat_id(群聊/私聊各自的上下文)+ # GodView 是系统自动注册的外部调用者伪 member,不是 /join 认领的真实席位,+ # 不应被反查命中(否则会注入 member_name=GodView 触发 $GodView 前缀,+ # team 把它当 member 去 interact → human_agent_not_enabled)。+ if chat_id:+ for sid, members in self._subs.items():+ for _mname, subs in members.items():+ for s in subs:+ if s.is_godview:+ continue+ rk = s.routing_key+ if (+ rk.channel_id == channel_id+ and rk.app_id == app_id+ and rk.user_id == user_id+ ):+ _cid = getattr(s.delivery, "get_container_id", lambda: "")()+ if _cid == chat_id:+ return (sid, s.member_name)+ # 第二遍:兜底匹配(无 chat_id 或不匹配时回退)+ for sid, members in self._subs.items():+ for _mname, subs in members.items():+ for s in subs:+ if s.is_godview:+ continue+ rk = s.routing_key+ if (+ rk.channel_id == channel_id+ and rk.app_id == app_id+ and rk.user_id == user_id+ ):+ return (sid, s.member_name)+ return None+++# ── 响应分发入口 ──────────────────────────────────────────────+++async def dispatch_to_session(+ msg, # Message+ session_id: str,+ fan_out: list, # list[LogicalTarget]+ channel_manager, # ChannelManager+ registry: SessionSharingRegistry,+) -> None:+ """响应分发入口 —— 由 _dispatch_robot_messages() 调用。++ 薄封装,转调 SessionDispatcher.dispatch,保留模块级函数签名以兼容现有调用方。+ 逻辑见 SessionDispatcher。+ """+ await SessionDispatcher.dispatch(msg, session_id, fan_out, channel_manager, registry)+++class SessionDispatcher:+ """team 响应分发器:把 fan_out (LogicalTarget 列表) 投递到各物理容器。++ 流程:按 intent 选订阅 → 按物理容器分组去重 → 组装 RoutingTarget →+ channel.send。无实例状态,全部静态方法。+ """++ @dataclass(frozen=True)+ class _ContainerKey:+ """物理容器去重键:(channel_id, app_id, container_id)。++ 命名而非裸 tuple,避免下游 ChannelKey(key[0], key[1]) 这种魔法索引。+ """+ channel_id: str+ app_id: str+ container_id: str++ @staticmethod+ async def dispatch(+ msg,+ session_id: str,+ fan_out: list, # list[LogicalTarget]+ channel_manager,+ registry: SessionSharingRegistry,+ ) -> None:+ """对每个 LogicalTarget 查 Registry → 按物理容器去重 → 组装 RoutingTarget →+ 调 channel.send(msg, routing_target=RoutingTarget)。+ """+ if not fan_out:+ return++ godview_subs = registry.lookup_member(session_id, SubRole.GODVIEW)+ # 已发送的物理容器集合,跨 intent 去重:broadcast 的 fan_out=[godview, mention_all]+ # 可能打到同一个 IM 群,godview 先发到群 G、mention_all 又发到群 G → 重复+ sent_containers: set[SessionDispatcher._ContainerKey] = set()++ for target in fan_out:+ subs = SessionDispatcher._select_subs(target, godview_subs, registry, session_id)+ if not subs:+ # 未认领的 LLM target 无 GodView 抄送,静默跳过(流式 chunk 高频路径)+ continue+ for container_key, _delivery, group_subs in SessionDispatcher._group_by_container(subs):+ if container_key in sent_containers:+ continue+ sent_containers.add(container_key)+ await SessionDispatcher._send_to_container(+ msg, target, group_subs, container_key, channel_manager,+ )++ @staticmethod+ def _select_subs(+ target: LogicalTarget,+ godview_subs: list[Subscription],+ registry: SessionSharingRegistry,+ session_id: str,+ ) -> list[Subscription]:+ """按 LogicalTarget.intent 取该 target 命中的订阅列表."""+ if target.intent == "godview":+ return list(godview_subs)+ if target.mention_all:+ # @all:本 session 全部 member 订阅;排除 GodView(godview intent 已单独投递)+ return [s for s in registry.lookup_all(session_id) if not s.is_godview]+ # 点名 mention:收集所有被 @ member 的订阅+ subs: list[Subscription] = []+ for name in target.member_names:+ subs.extend(registry.lookup_member(session_id, name))+ return subs++ @staticmethod+ def _group_by_container(+ subs: list[Subscription],+ ) -> list[tuple["_ContainerKey", DeliveryTarget, list[Subscription]]]:+ """按物理容器分组订阅,同一容器合并为一次投递.++ 返回 [(container_key, delivery, [subs...]), ...]——delivery 取该组首条订阅的+ (同容器同 channel/app,delivery 等价)。+ """+ groups: dict[SessionDispatcher._ContainerKey, tuple[DeliveryTarget, list[Subscription]]] = {}+ for s in subs:+ key = SessionDispatcher._ContainerKey(+ s.routing_key.channel_id,+ s.routing_key.app_id,+ s.delivery.get_container_id(),+ )+ if key not in groups:+ groups[key] = (s.delivery, [])+ groups[key][1].append(s)+ return [(k, delivery, group) for k, (delivery, group) in groups.items()]++ @staticmethod+ async def _send_to_container(+ msg,+ target: LogicalTarget,+ group_subs: list[Subscription],+ container_key: "_ContainerKey",+ channel_manager,+ ) -> None:+ """向单个物理容器发送一条消息(组装 RoutingTarget 后调 channel.send).++ delivery 取 group_subs[0].delivery(同容器同 channel/app,组内等价),+ 避免把 _group_by_container 的同源字段重复作为参数传入。+ """+ delivery = group_subs[0].delivery+ channel = channel_manager.get_channel(+ ChannelKey(container_key.channel_id, container_key.app_id),+ )+ if channel is None:+ logger.warning(+ "[dispatch] channel not found: channel_id=%s app_id=%s"+ " (registered: %s)",+ container_key.channel_id, container_key.app_id,+ channel_manager.enabled_channels,+ )+ return++ routing_target = SessionDispatcher._build_routing_target(target, group_subs, delivery)+ try:+ await asyncio.wait_for(+ channel.send(msg, routing_target=routing_target),+ timeout=10.0,+ )+ except asyncio.TimeoutError:+ logger.error(+ "[dispatch] send timed out after 10s: channel=%s app=%s intent=%s"+ " — skipping to unblock dispatch loop",+ container_key.channel_id, container_key.app_id, target.intent,+ )+ except Exception:+ logger.exception(+ "[dispatch] send failed: channel=%s app=%s intent=%s",+ container_key.channel_id, container_key.app_id, target.intent,+ )++ @staticmethod+ def _build_routing_target(+ target: LogicalTarget,+ group_subs: list[Subscription],+ delivery: DeliveryTarget,+ ) -> RoutingTarget:+ """从 LogicalTarget + 一组 Subscription + DeliveryTarget 组装 RoutingTarget。"""+ mention_member_ids: list[str] = []+ # "private" intent 不发 @mention,避免对 human 成员不必要的打扰+ if target.intent != "private":+ for s in group_subs:+ # physical_user_id 仅 IM 子类有,ws 子类(Web/TUI 等)无此属性+ puid = getattr(s.delivery, "physical_user_id", "")+ if puid and puid not in mention_member_ids:+ mention_member_ids.append(puid)++ return RoutingTarget(+ intent=target.intent,+ member_names=tuple(s.member_name for s in group_subs),+ speaker=target.speaker,+ mention_all=target.mention_all,+ routing_keys=[s.routing_key for s in group_subs],+ mention_member_ids=mention_member_ids,+ delivery=delivery,+ )diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yamlindex 73171fe05e..4bac708f5f 100644--- a/jiuwenswarm/resources/config.yaml+++ b/jiuwenswarm/resources/config.yaml@@ -298,13 +298,13 @@ agents:workspace:stable_base: truemax_iterations: 200- completion_timeout: 600.0+ completion_timeout: 6000.0agent_teammate:workspace:stable_base: truemax_iterations: 200- completion_timeout: 600.0+ completion_timeout: 6000.0telemetry:enabled: false # 总开关(环境变量 OTEL_ENABLED 优先)@@ -537,20 +537,22 @@ channels:web:send_file_allowed: truefeishu:- # 飞书应用配置- app_id:- app_secret:- encrypt_key:- verification_token:- allow_from:- enable_streaming: false- enabled: falsesend_file_allowed: true- # 群聊数字分身(默认关闭)- group_digital_avatar: false- my_user_id: ""- bot_name: ""- enable_memory: false+ apps:+ - name: 飞书默认应用+ # 飞书应用配置+ app_id:+ app_secret:+ encrypt_key:+ verification_token:+ allow_from:+ enable_streaming: false+ enabled: false+ # 群聊数字分身(默认关闭)+ group_digital_avatar: false+ my_user_id: ""+ bot_name: ""+ enable_memory: falsefeishu_enterprise:# 企业飞书多 Bot 配置(每个 bot 会注册为独立 channel: feishu_enterprise:<app_id>)# bot_a:@@ -563,25 +565,28 @@ channels:# chat_id:# enabled: falsexiaoyi:- # 华为小艺 A2A 配置- mode: xiaoyi_channel- ak:- sk:- api_id:- push_id:- agent_id:- ws_url1: wss://hag.cloud.huawei.com/openclaw/v1/ws/link- ws_url2: wss://116.63.174.231/openclaw/v1/ws/link- enable_streaming: true- enabled: false- # xiaoyi_claw配置- uid:- api_key:- push_url:- file_upload_url:- # 小艺手机端插件tools调用,会添加相关tools到系统提示词- phone_tools_enabled: falsesend_file_allowed: true+ apps:+ - name: 小艺默认应用+ # 华为小艺 A2A 配置+ app_id:+ mode: xiaoyi_channel+ ak:+ sk:+ api_id:+ push_id:+ agent_id:+ ws_url1: wss://hag.cloud.huawei.com/openclaw/v1/ws/link+ ws_url2: wss://116.63.174.231/openclaw/v1/ws/link+ enable_streaming: true+ enabled: false+ # xiaoyi_claw配置+ uid:+ api_key:+ push_url:+ file_upload_url:+ # 小艺手机端插件tools调用,会添加相关tools到系统提示词+ phone_tools_enabled: falsedingtalk:# 钉钉应用配置client_id:diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.pyindex f34214d807..7d0e09fb14 100644--- a/jiuwenswarm/server/agent_ws_server.py+++ b/jiuwenswarm/server/agent_ws_server.py@@ -53,6 +53,7 @@ from jiuwenswarm.server.runtime.session.session_history import (append_compact_history_records,history_exists,load_history_records,+ read_member_history_records,read_team_history_records,)from jiuwenswarm.server.runtime.agent_adapter.sysop_builder import (@@ -882,9 +883,8 @@ class AgentWebSocketServer:self._acp_client_capabilities_by_ws: dict[int, dict[str, Any]] = {}# AgentManager 实例self._agent_manager = AgentManager()- # session_id → (正在运行的流式 asyncio.Task, 停止信号 Event),用于 interrupt 时精确取消- # Event 用于通知 heartbeat_loop 提前退出,避免 stream task 卡住时 keepalive 持续发送- self._session_stream_tasks: dict[str, tuple[asyncio.Task, asyncio.Event]] = {}+ # session_id → 正在运行的流式 asyncio.Task,用于 interrupt 时精确取消+ self._session_stream_tasks: dict[str, asyncio.Task] = {}# Scheduler service instance (for scheduled auto_harness tasks)self._scheduler_service: Optional[AutoHarnessService] = None# Model cache for scheduled task execution (same approach as interface_deep)@@ -1408,6 +1408,9 @@ class AgentWebSocketServer:if request.req_method == ReqMethod.TEAM_HISTORY_GET:await self._handle_team_history_get(ws, request, send_lock)return+ if request.req_method == ReqMethod.TEAM_MEMBERS_GET:+ await self._handle_team_members_get(ws, request, send_lock)+ returnif request.req_method == ReqMethod.COMMAND_ADD_DIR:await self._handle_command_add_dir(ws, request, send_lock)return@@ -1567,23 +1570,14 @@ class AgentWebSocketServer:# 只有 cancel/supplement 才取消流式任务# pause/resume 不取消,因为任务仍在运行(pause 在 checkpoint 阻塞,resume 解除阻塞)stream_task: asyncio.Task | None = None- stream_stop_event: asyncio.Event | None = Noneif intent in ("cancel", "supplement"):- entry = self._session_stream_tasks.get(sid)- if entry is not None:- if isinstance(entry, tuple):- stream_task, stream_stop_event = entry- else:- stream_task = entry+ stream_task = self._session_stream_tasks.get(sid)if stream_task is not None and not stream_task.done():logger.info("[AgentWebSocketServer] cancel: 终止 session 流式任务: session_id=%s intent=%s",sid,intent,)- # 先通知 heartbeat_loop 退出,避免 stream task 卡住时 keepalive 持续发送- if stream_stop_event is not None:- stream_stop_event.set()stream_task.cancel()# 专门处理 cancel,复用已有 agent(不再 fallthrough 到 _handle_unary)@@ -1729,54 +1723,6 @@ class AgentWebSocketServer:raise ValueError("Failed to get agent for cancel request")resp = await agent.process_message(request)-- # Team 模式下 cancel/supplement 需要额外清理 team runtime,- # 否则旧 session 的 Runner pool 条目和 stream task 不会被移除,导致 session 泄露。- # _handle_cancel 绕过了 interface._process_team_interrupt,所以在此补充清理逻辑。- # 注意:Gateway 转发的 cancel 请求可能丢失 mode/team 参数,因此不能仅依赖 params 判断,- # 而是直接检查 team_manager 中是否有该 session 的 active/pending runtime。- params = request.params if isinstance(request.params, dict) else {}- intent = params.get("intent", "cancel")- has_team_runtime = False- if request.session_id and intent in ("cancel", "supplement"):- try:- from jiuwenswarm.agents.harness.team import get_team_manager- team_manager = get_team_manager(channel_id)- has_team_runtime = (- team_manager.is_runtime_active(request.session_id)- or team_manager.is_runtime_pending(request.session_id)- )- except Exception as exc:- logger.warning(- "[AgentWebSocketServer] check team runtime failed: session_id=%s error=%s",- request.session_id, exc,- )- if has_team_runtime and request.session_id:- try:- from jiuwenswarm.agents.harness.team import get_team_manager- team_manager = get_team_manager(channel_id)- if intent == "cancel":- cancelled = await team_manager.cancel_session_runtime(- request.session_id, reason=f"_handle_cancel(intent={intent}): "- )- logger.info(- "[AgentWebSocketServer] cancel: team 会话已取消: session_id=%s cancelled=%s",- request.session_id, cancelled,- )- else:- terminated = await team_manager.terminate_session_runtime(- request.session_id, reason=f"_handle_cancel(intent={intent}): "- )- logger.info(- "[AgentWebSocketServer] supplement: team 会话已终止: session_id=%s terminated=%s",- request.session_id, terminated,- )- except Exception as exc:- logger.warning(- "[AgentWebSocketServer] team 会话清理失败: session_id=%s error=%s",- request.session_id, exc,- )-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))@@ -2012,16 +1958,6 @@ class AgentWebSocketServer:return restored_after_approval- @staticmethod- def _is_stateless_method_request(request: AgentRequest) -> bool:- """skills / skilldev / plugins / symphony 为无状态 RPC,无需 mode 解析与 adapter. """- return (- request.req_method is not None- and request.req_method.value.startswith(- ("skills.", "skilldev.", "plugins.", "symphony.")- )- )-async def _handle_unary(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:"""非流式处理:调用 process_message,返回一条 E2AResponse 线 JSON。"""channel_id = request.channel_id or "default"@@ -2042,20 +1978,6 @@ class AgentWebSocketServer:await self._handle_acp_tool_response(ws, request, send_lock)return- # 无状态请求(skills / skilldev / plugins / symphony)不需要 mode 解析和- # code mode 状态管理,直接走 process_message 即可。- if self._is_stateless_method_request(request):- agent = await self._agent_manager.get_agent(channel_id=channel_id, mode="agent")- resp = await agent.process_message(request)- 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)@@ -2071,6 +1993,11 @@ class AgentWebSocketServer:# Push plan.mode_exited if exit_plan_mode restored mode during processingawait self._check_post_process_plan_exit(request, agent)+ # V2: 非流式响应回带请求侧 agent_ref,供 gateway 3 元组路由(设计 §6.3)。+ # is None 守卫:保留 agent 层显式设置的 agent_ref(如 team 模式由事件派生)。+ 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))@@ -2084,22 +2011,16 @@ class AgentWebSocketServer:channel_id = request.channel_id or "default"session_id = request.session_id or "default"current_task = asyncio.current_task()- # 停止信号:cancel stream task 时 set,通知 heartbeat_loop 立即退出- stream_stop_event = asyncio.Event()if current_task is not None:- self._session_stream_tasks[session_id] = (current_task, stream_stop_event)+ self._session_stream_tasks[session_id] = current_task- # 无状态流式请求(skills / skilldev / plugins / symphony)不需要 mode 解析和- # code mode 状态管理,直接走 process_message_stream 即可。- if self._is_stateless_method_request(request):- agent = await self._agent_manager.get_agent(channel_id=channel_id, mode="agent")- 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)+ 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)chunk_count = 0# 心跳控制:当有真实 chunk 发送时重置,空闲时发送心跳@@ -2107,46 +2028,40 @@ class AgentWebSocketServer:heartbeat_task: asyncio.Task | None = Noneasync def _heartbeat_loop() -> None:- """后台心跳任务:在空闲期间定期发送 keepalive chunk.-- 通过 stream_stop_event 与 stream task 绑定:- - stream task 正常完成或被 cancel 时 set stream_stop_event- - heartbeat_loop 检测到 stop 信号后立即退出,避免僵尸 keepalive- """+ """后台心跳任务:在空闲期间定期发送 keepalive chunk."""try:while True:- # 同时等待心跳间隔和停止信号,任一先到即唤醒- done, _ = await asyncio.wait(- [- asyncio.ensure_future(heartbeat_event.wait()),- asyncio.ensure_future(stream_stop_event.wait()),- ],- timeout=_STREAM_HEARTBEAT_INTERVAL_SECONDS,- )- if stream_stop_event.is_set():- break- if heartbeat_event.is_set():+ # 等待心跳间隔,如果期间有真实 chunk 发送则 heartbeat_event 被设置,重置等待+ try:+ await asyncio.wait_for(+ heartbeat_event.wait(),+ timeout=_STREAM_HEARTBEAT_INTERVAL_SECONDS,+ )# 有真实 chunk 发送,重置 event 继续等待heartbeat_event.clear()- continue- # 超时:空闲超过心跳间隔,发送 keepalive chunk- heartbeat_chunk = AgentResponseChunk(- request_id=request.request_id,- channel_id=channel_id,- payload={"event_type": "keepalive"},- is_complete=False,- )- wire = encode_agent_chunk_for_wire(- heartbeat_chunk,- response_id=request.request_id,- sequence=-1, # 心跳使用特殊序列号 -1- )- async with send_lock:- await ws.send(json.dumps(wire, ensure_ascii=False))- logger.info(- "[AgentWebSocketServer] keepalive chunk 发送: request_id=%s",- request.request_id,- )+ except asyncio.TimeoutError:+ # 超时:空闲超过心跳间隔,发送 keepalive chunk+ heartbeat_chunk = AgentResponseChunk(+ request_id=request.request_id,+ channel_id=channel_id,+ payload={"event_type": "keepalive"},+ is_complete=False,+ )+ # V2: 心跳 chunk 也回带 agent_ref,避免切换 mode 后+ # 旧 session 心跳错路由到新 agent 窗口(设计 §5.2 场景 2)。+ if heartbeat_chunk.agent_ref is None:+ heartbeat_chunk.agent_ref = request.agent_ref+ wire = encode_agent_chunk_for_wire(+ heartbeat_chunk,+ response_id=request.request_id,+ sequence=-1, # 心跳使用特殊序列号 -1+ )+ async with send_lock:+ await ws.send(json.dumps(wire, ensure_ascii=False))+ logger.info(+ "[AgentWebSocketServer] keepalive chunk 发送: request_id=%s",+ request.request_id,+ )except asyncio.CancelledError:passexcept WebSocketConnectionClosed:@@ -2163,11 +2078,26 @@ class AgentWebSocketServer:chunk_count += 1# 通知心跳任务有真实 chunk 发送,重置心跳计时heartbeat_event.set()+ # V2: chunk 回带请求侧 agent_ref,供 gateway 3 元组精确路由+ # (设计 §6.3)。is None 守卫:保留 team 模式由事件派生的 agent_ref+ # (_build_team_event_chunk_meta 已设值),不覆盖。+ if chunk.agent_ref is None:+ chunk.agent_ref = request.agent_refwire = encode_agent_chunk_for_wire(chunk,response_id=request.request_id,sequence=chunk_count - 1,)+ # 诊断:打印前 3 个和每 50 个 chunk 的发送情况+ if chunk_count <= 3 or chunk_count % 50 == 0:+ _pl = getattr(chunk, "payload", None) or {}+ _et = _pl.get("event_type", "") if isinstance(_pl, dict) else ""+ logger.info(+ "[AgentWebSocketServer] chunk sent: request_id=%s seq=%s"+ " event_type=%s wire_keys=%s",+ request.request_id, chunk_count - 1, _et,+ list(wire.keys())[:10] if isinstance(wire, dict) else "non-dict",+ )try:async with send_lock:await ws.send(json.dumps(wire, ensure_ascii=False))@@ -2180,8 +2110,6 @@ class AgentWebSocketServer:# 清除 event,让心跳任务重新开始计时heartbeat_event.clear()finally:- # 通知 heartbeat_loop 立即退出(即使 stream task 卡在 process_message_stream 中)- stream_stop_event.set()# 停止心跳任务if heartbeat_task is not None:heartbeat_task.cancel()@@ -2192,10 +2120,8 @@ class AgentWebSocketServer:except WebSocketConnectionClosed:pass# 清除 session 流式任务追踪(仅清除自身,避免误删后续新任务)- if self._session_stream_tasks.get(session_id) is not None:- stored = self._session_stream_tasks[session_id]- if isinstance(stored, tuple) and stored[0] is current_task:- self._session_stream_tasks.pop(session_id, None)+ if self._session_stream_tasks.get(session_id) is current_task:+ self._session_stream_tasks.pop(session_id, None)# Push plan.mode_exited if exit_plan_mode restored mode during processingawait self._check_post_process_plan_exit(request, agent)@@ -2993,6 +2919,78 @@ class AgentWebSocketServer:async with send_lock:await ws.send(json.dumps(wire, ensure_ascii=False))+ async def _handle_team_members_get(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:+ """Return the live team member list for /join seat validation.++ Unlike ``team.snapshot`` (a full snapshot for frontend restore), this+ is an internal unary RPC consumed only by the gateway's /join handler.+ It calls ``get_member_list()`` (members only, no tasks) and filters+ down to ``role == "human_agent"``, since the caller only needs the+ names of seats a human may claim. Not touching ``get_team_snapshot()``+ keeps /join validation independent of the team task table — a missing+ ``team_task_*`` table must not block member seat validation.+ """+ from jiuwenswarm.agents.harness.team import (+ get_all_team_managers,+ get_team_manager,+ )++ params = request.params if isinstance(request.params, dict) else {}+ session_id = params.get("session_id") or request.session_id or ""+ channel_id = request.channel_id or "web"++ # TeamManager 按 channel_id 隔离,但 session_id 全局唯一:/join 的来源+ # channel(如飞书)可能不同于 team 创建时的 channel(如 web)。因此先按+ # 请求 channel 取快路径,未命中则遍历所有 manager 找持有该 session 的+ # monitor,避免跨 channel /join 时查到空列表而误判"团队未就绪"。+ team_manager = get_team_manager(channel_id)+ monitor_handler = team_manager.get_monitor_handler(session_id)+ if monitor_handler is None and session_id:+ for mgr in get_all_team_managers():+ if mgr is team_manager:+ continue+ candidate = mgr.get_monitor_handler(session_id)+ if candidate is not None:+ monitor_handler = candidate+ break++ if monitor_handler is None or not monitor_handler.is_running:+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=channel_id,+ ok=True,+ payload={"members": [], "team_id": None},+ )+ 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))+ return++ try:+ members_raw = await monitor_handler.get_member_list()+ members = [+ m for m in (members_raw or [])+ if isinstance(m, dict) and m.get("role") == "human_agent"+ ]+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=channel_id,+ ok=True,+ payload={"members": members},+ )+ except Exception as e:+ logger.warning("[AgentWebSocketServer] team.members.get failed: %s", e)+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=channel_id,+ ok=True,+ payload={"members": []},+ )++ 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))+async def _handle_command_workflows(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:"""Handle command.workflows RPC request — return workflow_run_snapshot."""from jiuwenswarm.agents.harness.team import get_team_manager@@ -3097,9 +3095,14 @@ class AgentWebSocketServer:await ws.send(json.dumps(wire, ensure_ascii=False))async def _handle_team_history_get(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:- """Return a bounded page of team history records for panel restore."""+ """返回 team 模式历史记录的分页,避免与 history.get 并发竞争。++ 支持可选 member_name 参数:传入时仅返回与该 member 相关的记录+ (p2p 消息 / @all 广播 / teammate 输出)。+ """params = request.params if isinstance(request.params, dict) else {}session_id = params.get("session_id")+ member_name = params.get("member_name")channel_id = request.channel_id or "web"if not isinstance(session_id, str) or not session_id.strip():@@ -3116,7 +3119,12 @@ class AgentWebSocketServer:session_id = session_id.strip()try:- records = await asyncio.to_thread(read_team_history_records, session_id)+ if member_name and isinstance(member_name, str) and member_name.strip():+ records = await asyncio.to_thread(+ read_member_history_records, session_id, str(member_name).strip()+ )+ else:+ records = await asyncio.to_thread(read_team_history_records, session_id)except Exception as exc: # noqa: BLE001logger.warning("[team.history.get] read failed: session_id=%s error=%s", session_id, exc)records = []@@ -3153,13 +3161,9 @@ class AgentWebSocketServer:session_id=session_id,)logger.debug(- "[team.history.get] session_id=%s total=%d cursor=%d returned=%d next_cursor=%d max_bytes=%d",- session_id,- total,- cursor,- len(page_records),- next_cursor,- max_bytes,+ "[team.history.get] session_id=%s member=%s total=%d cursor=%d returned=%d next_cursor=%d max_bytes=%d",+ session_id, str(member_name or ""), total, cursor,+ len(page_records), next_cursor, max_bytes,)resp = AgentResponse(@@ -5707,7 +5711,7 @@ class AgentWebSocketServer:try:from jiuwenswarm.server.runtime.proactive_adapter import build_proactive_agentself._proactive_engine.rebuild_proactive_agent(build_proactive_agent)- except Exception as exc: # noqa: BLE001+ except Exception as exc:logger.warning("[AgentWebSocketServer] proactive agent rebuild failed: %s", exc)resp = AgentResponse(@@ -5716,7 +5720,7 @@ class AgentWebSocketServer:ok=True,payload={"reloaded": True},)- except Exception as e: # noqa: BLE001+ except Exception as e:logger.exception("[AgentWebSocketServer] agent.reload_config failed: %s", e)resp = AgentResponse(request_id=request.request_id,diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex 1fa71c9f20..04678c7c44 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -1833,8 +1833,18 @@ class JiuWenSwarm:durable_final_content = pending_textasync def run_stream_task():+ logger.info("[JiuWenSwarm] run_stream_task started: request_id=%s session_id=%s", rid, session_id)+ _put_count = 0try:async for chunk in adapter.process_message_stream_impl(request, inputs):+ _put_count += 1+ if _put_count <= 3:+ _pl = getattr(chunk, "payload", None) or {}+ _et = _pl.get("event_type", "") if isinstance(_pl, dict) else ""+ logger.info(+ "[JiuWenSwarm] run_stream_task chunk #%s: request_id=%s event_type=%s",+ _put_count, rid, _et,+ )await stream_queue.put(("chunk", chunk))except asyncio.CancelledError:logger.info("[JiuWenSwarm] 流式任务被取消: request_id=%s session_id=%s", rid, session_id)@@ -1843,6 +1853,10 @@ class JiuWenSwarm:logger.exception("[JiuWenSwarm] 流式任务异常: %s", exc)await stream_queue.put(("error", exc))finally:+ logger.info(+ "[JiuWenSwarm] run_stream_task finished: request_id=%s total_chunks=%s",+ rid, _put_count,+ )stream_done.set()# Team 模式: 后续请求直接执行,绕过 Session Manager 队列@@ -1866,6 +1880,11 @@ class JiuWenSwarm:suppress_a2ui_stream = Falsea2ui_pending_render_sent = Falsea2ui_stream_probe = ""+ _yielded_from_queue = 0+ logger.info(+ "[JiuWenSwarm] consumer loop starting: request_id=%s is_team=%s is_first=%s",+ rid, is_team_mode, is_team_first_request,+ )try:while not stream_done.is_set() or not stream_queue.empty():try:@@ -1874,6 +1893,14 @@ class JiuWenSwarm:continueevent_type, data = item+ _yielded_from_queue += 1+ if _yielded_from_queue <= 3:+ _pl = getattr(data, "payload", None) if event_type == "chunk" else None+ _et = _pl.get("event_type", "") if isinstance(_pl, dict) else ""+ logger.info(+ "[JiuWenSwarm] consumer loop yield #%s: request_id=%s event_type=%s item_type=%s",+ _yielded_from_queue, rid, _et, event_type,+ )if event_type == "error":if isinstance(data, asyncio.CancelledError):diff --git a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.pyindex e95d74d47c..ec2fd4f520 100644--- a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py+++ b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py@@ -77,8 +77,13 @@ from jiuwenswarm.server.runtime.agent_adapter.evolution_slash import (logger = logging.getLogger(__name__)-_pending_waiters: dict[tuple[str, str], list[tuple[str, asyncio.Queue]]] = {}-_cron_team_completion: dict[tuple[str, str], dict[str, Any]] = {}+# Waiter + cron-team-completion state lives on the singleton TeamManager+# (TeamManager._pending_waiters / TeamManager._cron_team_completion), indexed+# by session_id. TeamManager is process-wide and shared across channels, so a+# bridged follow-up (e.g. /join from feishu while the web stream is alive)+# finds the originating channel's waiter regardless of arrival channel. There+# is no module-level global waiter registry — reach it via+# get_team_manager(channel_id) or the team_manager handle passed in._WORKFLOW_RUNS_STATE_KEY = "workflow_runs"_TEAM_CREATE_KINDS = {@@ -107,8 +112,125 @@ _INTERACT_REASON_ERROR_MAP: dict[str, str] = {"unknown_human_agent": "Member not found, please check the name","human_agent_not_enabled": "Human agent is not yet available, please try again later","no_team_backend": "Team backend not ready, please try again later",+ "agent_unavailable": "Target member not available, please check the member name",}+# ── fan_out 规则(表驱动)──────────────────────────────────────+# 所有 team 事件均显式产出 fan_out,godview 始终在 fan_out 中(不靠 Gateway 兜底)。+# 规则按两个独立维度组织,分别用一张表:+# 1. _INNER_TYPE_FANOUT —— 按 event.event.type(team.message 内层子类型)+# 2. _ROLE_FANOUT —— 按 event.role(外层角色)+# _build_logical_targets 依次查这两张表,命中即返回;都未命中走 godview 兜底。+#+# intent 语义(三态,见 session_sharing.LogicalTarget / _build_routing_target):+# - godview : 投递给 GodView 订阅者,不带 @+# - mention : 投递给被点名成员 + 带 @(飞书 <at>);monitor 转发的 P2P 消息用此+# - private : 投递给被点名成员但不带 @;纯 teammate LLM 输出用此,不打扰人类用户+# 区分 mention/private 的关键:前者 @ 用户,后者不 @,由 _build_routing_target 按 intent 决定。+++def _tgt_godview() -> dict:+ return {"intent": "godview"}+++def _tgt_mention(+ member_names, *, mention_all: bool = False, speaker: str | None = None+) -> dict:+ """mention intent:投递给被点名成员并带 @(飞书 <at>)。"""+ tgt: dict = {+ "intent": "mention",+ "member_names": list(member_names),+ "speaker": speaker,+ }+ if mention_all:+ tgt["mention_all"] = True+ return tgt+++def _tgt_private(member_names, *, speaker: str | None = None) -> dict:+ """private intent:投递给被点名成员但不带 @。"""+ return {+ "intent": "private",+ "member_names": list(member_names),+ "speaker": speaker,+ }+++def _p2p_fanout(inner: dict) -> list[dict]:+ """P2P 消息 fan_out:godview + 收件人(mention, 带 @) + 发送方(private, 不带 @)。++ - 收件人用 mention:被 @ 提醒,飞书渲染 <at>。+ - 发送方用 private:自己发的消息不该 @ 自己(private intent 在+ ``_build_routing_target`` 里不注入 mention_member_ids),零打扰,+ 仅用于发送方在自己的 /join 窗口看到自己发出的 P2P 卡片。+ - from_member 缺失时不追加 private([None]),避免把 None 当 member_name+ 查 Registry 留下调试噪音(见 dispatch_to_session 的 lookup_member)。+ - from/to 落同一物理容器(飞书群、同一 ws)时,dispatch_to_session 的+ sent_containers 跨 intent 去重,先到的 intent 标记容器已发,后到跳过,+ 至少显示一次,不会双发。+ """+ targets = [+ _tgt_godview(),+ _tgt_mention([inner["to_member"]], speaker=inner.get("from_member")),+ ]+ fm = inner.get("from_member")+ if fm:+ targets.append(_tgt_private([fm], speaker=fm))+ return targets+++# 维度 1:按 event.event.type 分发(team.message 内层子类型)+_INNER_TYPE_FANOUT: dict[str, Any] = {+ # monitor 转发的 P2P 消息 → godview + 收件人(mention,带@) + 发送方(private,不带@)+ "team.message.p2p": _p2p_fanout,+ # 广播 → godview + mention_all+ "team.message.broadcast": lambda inner: [+ _tgt_godview(),+ _tgt_mention([], mention_all=True, speaker=inner.get("from_member")),+ ],+}++# 维度 2:按 event.role 分发(外层角色)+# teammate LLM 输出 → godview + private(该 teammate 席位,不带 @)。+# HumanAgent 需要看到自己扮演的 agent 的输出才能进行自对话;纯 agent 输出不打扰人类。+_ROLE_FANOUT: dict[str, Any] = {+ "teammate": lambda ev: [+ _tgt_godview(),+ _tgt_private([ev["member_name"]], speaker=ev["member_name"]),+ ],+}++_GODVIEW_TARGET = [_tgt_godview()]+++def _build_logical_targets(event: dict) -> list[dict]:+ """所有 team 事件 → fan_out 规则(表驱动,依次查两维后兜底 godview)。++ 查询顺序(命中即返回):+ 1. event.event.type ∈ _INNER_TYPE_FANOUT —— team.message.p2p/broadcast+ 2. event.role ∈ _ROLE_FANOUT —— teammate 输出 → private+ 3. 兜底 → [godview] —— leader 输出、team.member、team.task 等++ p2p 用 mention(带 @),teammate 输出用 private(不带 @),broadcast 用 mention_all。+ """+ # 维度 1:team.message 内层子类型+ if event.get("event_type") == "team.message":+ inner = event.get("event", {}) or {}+ fn = _INNER_TYPE_FANOUT.get(inner.get("type", ""))+ if fn:+ return fn(inner)++ # 维度 2:外层角色+ role = str(event.get("role", "")).strip().lower()+ fn = _ROLE_FANOUT.get(role)+ if fn:+ member_name = str(event.get("member_name", "")).strip()+ if member_name:+ return fn(event)++ # 兜底:其余所有 team 消息都带 godview+ return _GODVIEW_TARGET+def _is_followup_delivery_boundary_reason(reason: str | None) -> bool:"""Return whether follow-up delivery likely hit a runtime boundary."""@@ -160,6 +282,37 @@ async def _wait_for_team_first_request_condition(return not await _team_session_has_runtime(team_manager, session_id)+def _build_team_event_chunk_meta(event: Any) -> tuple[dict | None, dict]:+ """从 team event 统一推导 (agent_ref, metadata),供所有 team 事件产出路径调用。++ - agent_ref: 成员身份标识。前端 team.member.spawned 用 agent_ref.id 拼接+ /join team_<name>_session_<sid>,取不到会 fallback 'unknown'。+ - metadata: fan_out_targets 路由元数据,由 _build_logical_targets 产出。++ 按设计(§10/§14.2.3/§13.3)agent_ref 是 server 层统一注入,不在 monitor 层加。+ 非 team 事件(chat.error / processing_status / completion 等控制信号)返回+ (None, {}),不注入。+ """+ if not isinstance(event, dict):+ return None, {}+ ev_type = event.get("event_type", "")+ role = event.get("role", "")+ if role == "teammate":+ agent_ref: dict | None = {"mode": "team", "id": event.get("member_name", "teammate")}+ elif ev_type in ("team.member", "team.task"):+ # team_id 嵌套在 event.event 内层+ inner = event.get("event", {}) or {}+ agent_ref = {"mode": "team", "id": inner.get("team_id", "team")}+ elif ev_type == "team.message":+ inner = event.get("event", {}) or {}+ agent_ref = {"mode": "team", "id": inner.get("from_member", "team")}+ else:+ agent_ref = None+ fan_out = _build_logical_targets(event)+ metadata = {"fan_out_targets": fan_out} if fan_out else {}+ return agent_ref, metadata++def _strip_directive(query: str, prefix: str) -> tuple[str, bool]:"""Strip a leading slash directive from a query string.@@ -612,8 +765,7 @@ async def _finish_cron_team_stream_after_delegation_grace("""Wait briefly after a solo harness final before ending the cron team stream."""await asyncio.sleep(_CRON_DELEGATION_GRACE_SECONDS)resolved_channel_id = _resolve_channel_id(channel_id)- waiter_key = (resolved_channel_id, session_id)- completion = _cron_team_completion.get(waiter_key)+ completion = get_team_manager(channel_id).get_cron_completion(session_id)if completion is None:returnif completion.get("tasks_ever_created"):@@ -632,10 +784,9 @@ async def _finish_cron_team_stream_after_round() -> None:"""Cancel the background team stream once cron SwarmFlow + leader report are done."""resolved_channel_id = _resolve_channel_id(channel_id)- waiter_key = (resolved_channel_id, session_id)+ team_manager = get_team_manager(channel_id)try:- tm = get_team_manager(channel_id)- stream_task = tm.pop_stream_task(session_id)+ stream_task = team_manager.pop_stream_task(session_id)if stream_task is not None and not stream_task.done():stream_task.cancel()try:@@ -666,7 +817,7 @@ async def _finish_cron_team_stream_after_round(exc,)finally:- _cron_team_completion.pop(waiter_key, None)+ team_manager.pop_cron_completion(session_id)def _try_finish_cron_team_stream(@@ -675,13 +826,13 @@ def _try_finish_cron_team_stream(event: dict[str, Any],) -> None:"""End persistent team streams for cron once workflow completes and leader reports."""- waiter_key = (_resolve_channel_id(channel_id), session_id)- waiters = _pending_waiters.get(waiter_key, [])+ team_manager = get_team_manager(channel_id)+ waiters = team_manager.get_waiters(session_id)if not any(_is_cron_request_id(request_id) for request_id, _ in waiters):return- completion = _cron_team_completion.setdefault(- waiter_key,+ completion = team_manager.setdefault_cron_completion(+ session_id,{**new_cron_team_round_state(),"round_id": None,@@ -702,7 +853,7 @@ def _try_finish_cron_team_stream(session_id,round_id,),- name=f"cron-team-grace-{waiter_key[0]}-{session_id}",+ name=f"cron-team-grace-{session_id}",)returnasyncio.create_task(@@ -711,26 +862,15 @@ def _try_finish_cron_team_stream(session_id,round_id,),- name=f"cron-team-finish-{waiter_key[0]}-{session_id}",+ name=f"cron-team-finish-{session_id}",)def _broadcast_event(channel_id: str | None, session_id: str, event: dict[str, Any]) -> None:- """Broadcast an event to all request queues waiting on the same channel/session."""- waiter_key = (_resolve_channel_id(channel_id), session_id)- waiters = _pending_waiters.get(waiter_key, [])- for request_id, queue in waiters:- try:- queue.put_nowait(dict(event))- except Exception:- logger.debug(- "[TeamHelpers] broadcast failed: channel_id=%s session_id=%s request_id=%s",- waiter_key[0],- session_id,- request_id,- )+ """Broadcast an event to all request queues waiting on the same session."""+ get_team_manager(channel_id).broadcast_event(session_id, event)_try_finish_cron_team_stream(channel_id, session_id, event)@@ -1096,14 +1236,11 @@ async def _start_team_stream_round(sync_team_observability()await team_manager.prepare_runtime_activation(session_id, team_name)request_queue: asyncio.Queue = asyncio.Queue()- waiter_key = (_resolve_channel_id(channel_id), session_id)- if waiter_key not in _pending_waiters:- _pending_waiters[waiter_key] = []- _pending_waiters[waiter_key].append((request_id, request_queue))+ team_manager.add_waiter(session_id, request_id, request_queue)logger.info("[TeamHelpers] %s team request: channel_id=%s session_id=%s",source,- waiter_key[0],+ _resolve_channel_id(channel_id),session_id,)@@ -1157,9 +1294,16 @@ async def process_team_message_stream(session_id,exc,)- is_first_request = not await _team_session_has_runtime(- team_manager,- session_id,+ # is_first_request 判断:+ # 1. stream task 存在 → False+ # 2. 已有同 session 的 waiter → False+ # 3. session 已初始化过 team runtime → False+ # 4. 否则 → True(首次请求,需要创建 team spec + stream)+ has_active_waiters = team_manager.has_waiters(session_id)+ is_first_request = (+ not team_manager.has_stream_task(session_id)+ and not has_active_waiters+ and not team_manager.is_session_initialized(session_id))request_queue: asyncio.Queue | None = None@@ -1187,6 +1331,22 @@ async def process_team_message_stream(try:request_metadata = dict(request.metadata or {})+ # V2: 若请求携带 member_name(由 Gateway resolve_member_by_user 反查注入),+ # 在前拼接 $sender,让 OpenJiuwen 识别发言人身份。+ # 规则:+ # - 消息中有 @mention → $member_name @target body(保留显式 @)+ # - 消息中无 @ → $member_name body(不自动拼接 @team_leader,+ # HumanAgent 可直接与自己扮演的 agent 对话,如 $reviewer-1 看一下当前有哪些任务)+ member_name = str(request_metadata.get("member_name") or "").strip()+ if member_name and query_text and not query_text.startswith("$"):+ query = f"${member_name} {query_text}"+ query_text = query if isinstance(query, str) else str(query)+ logger.info(+ "[TeamHelpers] prefixed query with member identity: member=%s session=%s query_preview=%s",+ member_name,+ session_id,+ _safe_query_preview(query),+ )if isinstance(getattr(request, "params", None), dict):request_metadata.setdefault("mode", request.params.get("mode"))resolved_mode = str(request_metadata.get("mode") or "").strip()@@ -1304,6 +1464,12 @@ async def process_team_message_stream(_resolve_channel_id(channel_id),session_id,)+ # V2: follow-up 不创建 waiter —— 一个 session 只保留一个 waiter(原始 stream 的)。+ # follow-up 的唯一目的是 interact() 把 query 发给 team,+ # 后续的 team events 由原始 waiter 的 while 循环产出,+ # 通过 Gateway 的 fan_out 路由机制分发到各 channel。+ # 之前 follow-up 也创建 waiter 导致 _broadcast_event 广播到两个 queue,+ # 同一事件被 yield 两次 → Gateway dispatch 两次 → 重复消息。if query:success, reason = await team_manager.interact(session_id, query)if not success:@@ -1377,12 +1543,11 @@ async def process_team_message_stream(if not is_first_request:if _is_cron_request_id(rid):request_queue = asyncio.Queue()- waiter_key = (_resolve_channel_id(channel_id), session_id)- _pending_waiters.setdefault(waiter_key, []).append((rid, request_queue))+ team_manager.add_waiter(session_id, rid, request_queue)logger.info("[TeamHelpers] cron follow-up team request waits for round: ""channel_id=%s session_id=%s request_id=%s",- waiter_key[0],+ _resolve_channel_id(channel_id),session_id,rid,)@@ -1395,19 +1560,17 @@ async def process_team_message_stream(channel_id=channel_id,session_id=session_id,):+ _cron_agent_ref, _cron_meta = _build_team_event_chunk_meta(event)yield AgentResponseChunk(request_id=rid,channel_id=channel_id,payload=event,+ agent_ref=_cron_agent_ref,+ metadata=_cron_meta,is_complete=False,)finally:- waiters = _pending_waiters.get(waiter_key, [])- _pending_waiters[waiter_key] = [- (req_id, queue) for req_id, queue in waiters if req_id != rid- ]- if not _pending_waiters.get(waiter_key, []):- _pending_waiters.pop(waiter_key, None)+ team_manager.remove_waiter(session_id, rid)yield AgentResponseChunk(request_id=rid,channel_id=channel_id,@@ -1478,27 +1641,35 @@ async def process_team_message_stream(channel_id=channel_id,session_id=session_id,):+ _cron_agent_ref, _cron_meta = _build_team_event_chunk_meta(event)yield AgentResponseChunk(request_id=rid,channel_id=channel_id,payload=event,+ agent_ref=_cron_agent_ref,+ metadata=_cron_meta,is_complete=False,)else:+ # while 循环:仅 first-request 使用,依赖 stream_task 生命周期。+ # follow-up 已在上方 return,不再进入此循环。while team_manager.has_stream_task(session_id):if request_queue is None:breaktry:event = await asyncio.wait_for(request_queue.get(), timeout=0.1)+ # ── 统一推导 (agent_ref, fan_out_targets) ──+ _agent_ref, _metadata = _build_team_event_chunk_meta(event)yield AgentResponseChunk(request_id=rid,channel_id=channel_id,payload=event,+ agent_ref=_agent_ref,+ metadata=_metadata,is_complete=False,)- if isinstance(event, dict):- if event.get("event_type") == "team.error":- break+ if isinstance(event, dict) and event.get("event_type") == "team.error":+ breakexcept asyncio.TimeoutError:if not team_manager.has_stream_task(session_id):break@@ -1567,18 +1738,20 @@ async def process_team_message_stream(payload=None,is_complete=True,)+ # 当前 stream 已结束,清除初始化标记,+ # 下次请求需重新创建 stream task(gate 在 stream 结束时已关闭)。+ team_manager.clear_session_initialized(session_id)+ logger.info(+ "[TeamHelpers] stream ended, cleared init marker: "+ "channel_id=%s session_id=%s",+ _resolve_channel_id(channel_id), session_id,+ )finally:if request_queue is not None:- waiter_key = (_resolve_channel_id(channel_id), session_id)- waiters = _pending_waiters.get(waiter_key, [])- _pending_waiters[waiter_key] = [- (req_id, queue) for req_id, queue in waiters if req_id != rid- ]- if not _pending_waiters.get(waiter_key, []):- _pending_waiters.pop(waiter_key, None)+ team_manager.remove_waiter(session_id, rid)+ if not team_manager.has_waiters(session_id):logger.info(- "[TeamHelpers] cleared waiter set: channel_id=%s session_id=%s",- waiter_key[0],+ "[TeamHelpers] cleared waiter set: session_id=%s",session_id,)@@ -1634,9 +1807,24 @@ async def _consume_stream_with_query(stream_logger=lg,):received_chunks += 1+ # 诊断:每 30 个 chunk 或首个 chunk 时打印进度+ if received_chunks == 1 or received_chunks % 30 == 0:+ _role = getattr(chunk, "role", None)+ logger.info(+ "[TeamHelpers] stream progress: channel_id=%s session_id=%s"+ " received=%s role=%s type=%s",+ _resolve_channel_id(channel_id), session_id,+ received_chunks, _role, getattr(chunk, "type", None),+ )is_leader = _is_leader_output(chunk)is_teammate = _is_teammate_output(chunk)if not is_leader and not is_teammate:+ if received_chunks <= 3:+ logger.info(+ "[TeamHelpers] stream chunk filtered (non-leader/non-teammate):"+ " session_id=%s role=%s type=%s",+ session_id, getattr(chunk, "role", None), getattr(chunk, "type", None),+ )continue# Optional: filter out all non-leader frames so the frontend only# sees leader output. Leader-level control events@@ -1658,6 +1846,10 @@ async def _consume_stream_with_query(parsed["rid"] = round_idif is_teammate:parsed = _enrich_teammate_event(parsed, chunk)+ elif is_leader:+ # 标记 role=leader,使 _build_logical_targets() 走 godview 兜底+ # (leader 不在 _ROLE_FANOUT 中,落到 [godview])。+ parsed["role"] = TeamRole.LEADER.valueparsed = _truncate_team_tool_result_event(parsed)if parsed.get("event_type") == "team.runtime_ready":ready_team_name = str(parsed.get("team_name") or team_spec.team_name)diff --git a/jiuwenswarm/server/runtime/session/session_history.py b/jiuwenswarm/server/runtime/session/session_history.pyindex 30bd468769..f8357636d7 100644--- a/jiuwenswarm/server/runtime/session/session_history.py+++ b/jiuwenswarm/server/runtime/session/session_history.py@@ -294,6 +294,64 @@ def _read_history_by_path(path: Path) -> list[dict[str, Any]]:return _read_history(path)+def _is_member_relevant(item: dict[str, Any], member_name: str) -> bool:+ """判断一条 team 历史记录是否与指定 member 相关(用于飞书 /join 历史推送)。++ 与实时 fan_out 投递语义一致:每个 member 只看到"涉及自己的对话":+ - team.message.p2p 且 to_member 或 from_member == member_name →+ 发给/由该成员发出的私聊(与 fan_out+ [godview, mention(to_member), private(from_member)] 对齐:收件人和+ 发送方都能看到 P2P 卡片)+ - team.message.broadcast → @all 广播,所有人都能看到+ - chat.* teammate 流式输出 且 member_name == 该成员 →+ 该成员扮演的 agent 的输出(与 fan_out [godview, private(member)] 对齐)++ 不含 team.member/team.task 上下文事件(不会发给飞书,避免刷屏)。+ """+ et = item.get("event_type")+ if not isinstance(et, str):+ return False++ if et == "team.message":+ inner = item.get("event", {}) if isinstance(item.get("event"), dict) else {}+ msg_type = inner.get("type", "") or item.get("type", "")+ if msg_type == "team.message.broadcast":+ return True+ if msg_type == "team.message.p2p":+ to_m = item.get("to_member", "") or inner.get("to_member", "")+ from_m = item.get("from_member", "") or inner.get("from_member", "")+ return member_name in {to_m, from_m}+ return False++ # chat.* teammate outputs: 已在 _is_team_relevant 中按 role/mode 过滤。+ # 实时投递只发给该 member 的 private 席位,历史同样只对该 member 可见。+ if et in {"chat.final", "chat.tool_call", "chat.tool_result", "chat.file", "chat.tracer_agent"}:+ src_member = str(item.get("member_name", "") or "").strip()+ return bool(src_member) and src_member == member_name++ # 注意:team.member / team.task / team.event 不包含,+ # 这些是上下文事件,飞书端不需要看到,避免刷屏。+ return False+++def read_member_history_records(session_id: str, member_name: str) -> list[dict[str, Any]]:+ """读取 team 历史记录,仅返回与指定 member 相关的记录。++ 与实时 fan_out 投递语义一致:+ - 发给/由该 member 发出的 p2p 消息+ - @all 广播消息+ - 该 member 扮演的 teammate 的流式输出++ 不含 team.member/team.task 上下文事件,也不含其他 member 的输出。+ 无 member_name 时回退到 read_team_history_records(供 web 前端面板恢复用)。+ """+ if not member_name or not isinstance(member_name, str):+ return read_team_history_records(session_id)+ all_team_records = read_team_history_records(session_id)+ mn = member_name.strip()+ return [item for item in all_team_records if _is_member_relevant(item, mn)]++def read_session_history_records(session_id: str) -> list[dict[str, Any]]:"""读取指定会话的历史记录,返回所有记录。diff --git a/tests/unit_tests/agentserver/test_monitor_handler.py b/tests/unit_tests/agentserver/test_monitor_handler.pyindex 38d4878204..a16c465153 100644--- a/tests/unit_tests/agentserver/test_monitor_handler.py+++ b/tests/unit_tests/agentserver/test_monitor_handler.py@@ -24,12 +24,13 @@ class _FakeMessage:class _FakeMember:def __init__(self, member_name: str, display_name: str = "", status: str = "ready",- execution_status: str | None = None, mode: str = "normal"):+ execution_status: str | None = None, mode: str = "normal", role: str = "teammate"):self.member_name = member_nameself.display_name = display_nameself.status = statusself.execution_status = execution_statusself.mode = mode+ self.role = roleclass _FakeTask:@@ -74,6 +75,12 @@ class _FakeMonitor:async def get_members(self) -> list[_FakeMember]:return list(self._members)+ async def get_member(self, member_name: str, team_name: str | None = None) -> _FakeMember | None:+ for m in self._members:+ if m.member_name == member_name:+ return m+ return None+async def get_team_info(self):if self._leader_member_name is None:return None@@ -107,6 +114,7 @@ async def test_get_team_snapshot_filters_leader_member() -> None:"status": "ready","execution_status": None,"mode": "normal",+ "role": "teammate",}],"tasks": [@@ -144,6 +152,7 @@ async def test_get_team_snapshot_keeps_members_when_team_info_unavailable() -> N"status": "ready","execution_status": None,"mode": "normal",+ "role": "teammate",},{"member_id": "worker-2",@@ -151,6 +160,7 @@ async def test_get_team_snapshot_keeps_members_when_team_info_unavailable() -> N"status": "ready","execution_status": None,"mode": "normal",+ "role": "teammate",},],"tasks": [],@@ -269,3 +279,60 @@ async def test_convert_plain_protocol_message_keeps_json_like_text_unchanged() -assert converted["event"]["content"] == raw_contentfinally:await handler.stop()+++async def test_member_spawned_event_includes_mode_for_human_agent() -> None:+ """验证 member_spawned 事件对 human_agent 成员返回 mode="human"."""+ event = MonitorEvent(+ event_type=MonitorEventType.MEMBER_SPAWNED,+ team_name="team-1",+ timestamp=123,+ member_name="HumanPlayer_A",+ )+ handler = TeamMonitorHandler(+ _FakeMonitor(+ members=[_FakeMember("HumanPlayer_A", role="human_agent")],+ leader_member_name=None,+ events=[event],+ ),+ "sess-monitor",+ )++ await handler.start()+ try:+ converted = await anext(handler.events())++ assert converted["event"]["member_id"] == "HumanPlayer_A"+ assert converted["event"]["mode"] == "human"+ finally:+ await handler.stop()+++async def test_member_spawned_event_includes_mode_for_ai_member() -> None:+ """验证 member_spawned 事件对 AI 成员返回 mode=role(teammate/leader 等)。"""+ event = MonitorEvent(+ event_type=MonitorEventType.MEMBER_SPAWNED,+ team_name="team-1",+ timestamp=123,+ member_name="Werewolf_AI_1",+ )+ handler = TeamMonitorHandler(+ _FakeMonitor(+ members=[_FakeMember("Werewolf_AI_1", role="teammate")],+ leader_member_name=None,+ events=[event],+ ),+ "sess-monitor",+ )++ await handler.start()+ try:+ converted = await anext(handler.events())++ assert converted["event"]["member_id"] == "Werewolf_AI_1"+ # AI 成员(role=teammate)返回 mode=role 值+ assert converted["event"]["mode"] == "teammate"+ finally:+ await handler.stop()diff --git a/tests/unit_tests/agentserver/test_team_helpers.py b/tests/unit_tests/agentserver/test_team_helpers.pyindex 69fec3f42a..5c318913e1 100644--- a/tests/unit_tests/agentserver/test_team_helpers.py+++ b/tests/unit_tests/agentserver/test_team_helpers.py@@ -29,6 +29,50 @@ class _InactiveTeamRuntimeManagerMixin:_ = session_idreturn False+ @staticmethod+ def has_waiters(session_id: str) -> bool:+ return False++ @staticmethod+ def get_waiters(session_id: str) -> list[tuple[str, asyncio.Queue]]:+ return []++ @staticmethod+ def add_waiter(session_id: str, request_id: str, queue: asyncio.Queue) -> None:+ pass++ @staticmethod+ def remove_waiter(session_id: str, request_id: str) -> None:+ pass++ @staticmethod+ def broadcast_event(session_id: str, event: dict) -> None:+ pass++ @staticmethod+ def is_session_initialized(session_id: str) -> bool:+ return False++ @staticmethod+ def clear_session_initialized(session_id: str) -> None:+ pass++ @staticmethod+ def setdefault_cron_completion(session_id: str, default: dict) -> dict:+ return default++ @staticmethod+ def pop_cron_completion(session_id: str) -> dict | None:+ return None++ @staticmethod+ def get_cron_completion(session_id: str) -> dict | None:+ return None++ @staticmethod+ def pop_stream_task(session_id: str) -> asyncio.Task | None:+ return None+class _FakeTransport:pushes: list[dict] = []@@ -147,9 +191,14 @@ class _TeamHelpersTestApi:waiter_key: tuple[str, str],request_id: str,) -> None:- pending = getattr(team_helpers, "_pending_waiters")- pending[waiter_key] = [(request_id, asyncio.Queue())]- getattr(team_helpers, "_cron_team_completion").clear()+ """Seed a cron waiter on the shared _CronFakeManager.++ waiter_key is (channel_id, session_id); the waiter is registered by+ session_id (matching production TeamManager.get_waiters).+ """+ _channel_id, session_id = waiter_key+ _CronFakeManager._waiters[session_id] = [(request_id, asyncio.Queue())]+ _CronFakeManager._completion.clear()@staticmethoddef try_finish_cron_team_stream(@@ -162,8 +211,43 @@ class _TeamHelpersTestApi:@staticmethoddef clear_cron_team_waiter(waiter_key: tuple[str, str]) -> None:- getattr(team_helpers, "_pending_waiters").pop(waiter_key, None)- getattr(team_helpers, "_cron_team_completion").pop(waiter_key, None)+ _channel_id, session_id = waiter_key+ _CronFakeManager._waiters.pop(session_id, None)+ _CronFakeManager._completion.pop(session_id, None)+++class _CronFakeManager(_InactiveTeamRuntimeManagerMixin):+ """Fake TeamManager with waiter + completion state for cron team stream tests."""++ _waiters: dict[str, list[tuple[str, asyncio.Queue]]] = {}+ _completion: dict[str, dict] = {}+ _stream_tasks: dict[str, asyncio.Task] = {}++ @classmethod+ def reset(cls) -> None:+ cls._waiters.clear()+ cls._completion.clear()+ cls._stream_tasks.clear()++ @classmethod+ def get_waiters(cls, session_id: str) -> list[tuple[str, asyncio.Queue]]:+ return cls._waiters.get(session_id, [])++ @classmethod+ def setdefault_cron_completion(cls, session_id: str, default: dict) -> dict:+ return cls._completion.setdefault(session_id, default)++ @classmethod+ def pop_cron_completion(cls, session_id: str) -> dict | None:+ return cls._completion.pop(session_id, None)++ @classmethod+ def get_cron_completion(cls, session_id: str) -> dict | None:+ return cls._completion.get(session_id)++ @classmethod+ def pop_stream_task(cls, session_id: str) -> asyncio.Task | None:+ return cls._stream_tasks.pop(session_id, None)def _write_team_skill(tmp_path, name: str, *, records: list[dict] | None = None) -> str:@@ -1277,10 +1361,10 @@ async def test_process_team_message_stream_emits_deferred_marker_for_followup(moassert _FakeManager.interact_calls == [("sess-team-followup", "$human-reporter claim task"),]- # follow-up short stream must NOT emit is_processing=False directly;- # it emits an internal deferred marker so the Gateway suppresses the- # auto-complete signal. The real round-complete event is broadcast- # later by the background team stream on team.completed.+ # follow-up short stream emits chat.processing_status_deferred+ # to tell the Gateway not to auto-emit is_processing=False, preventing+ # "finished -> wait -> running again" flashing. See+ # team_helpers.process_team_message_stream.assert len(chunks) == 2assert chunks[0].payload == {"event_type": "chat.processing_status_deferred",@@ -2058,6 +2142,10 @@ async def test_process_team_message_stream_recovers_paused_runtime_for_interactiassert _FakeManager.interact_calls == [("sess-team-plan-recover", approval_input),]+ # follow-up short stream emits chat.processing_status_deferred+ # so the Gateway does not auto-emit is_processing=False, preventing+ # "finished -> wait -> running again" flashing. See+ # team_helpers.process_team_message_stream.assert chunks[0].payload == {"event_type": "chat.processing_status_deferred","session_id": "sess-team-plan-recover",@@ -2210,6 +2298,10 @@ async def test_process_team_message_stream_converts_a2ui_followup_event(monkeypaassert "A2UI" in promptassert "submitDietForm" in promptassert "dietType" in prompt+ # follow-up short stream emits chat.processing_status_deferred+ # so the Gateway does not auto-emit is_processing=False, preventing+ # "finished -> wait -> running again" flashing. See+ # team_helpers.process_team_message_stream.assert chunks[0].payload == {"event_type": "chat.processing_status_deferred","session_id": "sess-team-a2ui",@@ -3348,27 +3440,26 @@ def _make_cancellable_stream_task(*, cancelled: list[str], session_id: str) -> _@pytest.mark.anyioasync def test_try_finish_cron_team_stream_cancels_background_task(monkeypatch):"""Cron waiter should end the team stream once workflow completes and leader reports."""+ _CronFakeManager.reset()channel_id = "tui"session_id = "sess-cron-finish"waiter_key = (channel_id, session_id)- _TeamHelpersTestApi.seed_cron_team_waiter(waiter_key, "cron-job-1:123")cancelled: list[str] = []processing_done: list[dict[str, object]] = []- class _FakeTeamManager:- @staticmethod- def pop_stream_task(sid: str):- assert sid == session_id- return _make_cancellable_stream_task(cancelled=cancelled, session_id=session_id)-- monkeypatch.setattr(team_helpers, "get_team_manager", lambda cid: _FakeTeamManager())+ _CronFakeManager._stream_tasks[session_id] = _make_cancellable_stream_task(+ cancelled=cancelled, session_id=session_id,+ )+ monkeypatch.setattr(team_helpers, "get_team_manager", lambda cid: _CronFakeManager)monkeypatch.setattr(team_helpers,"_broadcast_event",lambda cid, sid, event: processing_done.append(event),)+ _TeamHelpersTestApi.seed_cron_team_waiter(waiter_key, "cron-job-1:123")+_TeamHelpersTestApi.try_finish_cron_team_stream(channel_id,session_id,@@ -3409,21 +3500,18 @@ async def test_try_finish_cron_team_stream_cancels_background_task(monkeypatch):@pytest.mark.anyioasync def test_try_finish_cron_team_stream_on_leader_final_without_team_completed(monkeypatch):"""Harness teams may emit chat.final without team.completed."""+ _CronFakeManager.reset()channel_id = "tui"session_id = "sess-cron-final-only"waiter_key = (channel_id, session_id)- _TeamHelpersTestApi.seed_cron_team_waiter(waiter_key, "cron-job-2:456")cancelled: list[str] = []processing_done: list[dict[str, object]] = []- class _FakeTeamManager:- @staticmethod- def pop_stream_task(sid: str):- assert sid == session_id- return _make_cancellable_stream_task(cancelled=cancelled, session_id=session_id)-- monkeypatch.setattr(team_helpers, "get_team_manager", lambda cid: _FakeTeamManager())+ _CronFakeManager._stream_tasks[session_id] = _make_cancellable_stream_task(+ cancelled=cancelled, session_id=session_id,+ )+ monkeypatch.setattr(team_helpers, "get_team_manager", lambda cid: _CronFakeManager)monkeypatch.setattr(team_helpers,"_broadcast_event",@@ -3431,6 +3519,8 @@ async def test_try_finish_cron_team_stream_on_leader_final_without_team_complete)monkeypatch.setattr(team_helpers, "_CRON_DELEGATION_GRACE_SECONDS", 0.0)+ _TeamHelpersTestApi.seed_cron_team_waiter(waiter_key, "cron-job-2:456")+_TeamHelpersTestApi.try_finish_cron_team_stream(channel_id,session_id,diff --git a/tests/unit_tests/agentserver/test_team_helpers_p2p_echo.py b/tests/unit_tests/agentserver/test_team_helpers_p2p_echo.pynew file mode 100644index 0000000000..b8177fe03c--- /dev/null+++ b/tests/unit_tests/agentserver/test_team_helpers_p2p_echo.py@@ -0,0 +1,218 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Unit tests for P2P sender-window echo in team fan_out and /join history.++Covers two aligned changes that make a ``team.message.p2p`` card visible in the+*sender's* window as well as the recipient's:++1. ``team_helpers._p2p_fanout`` appends a ``private`` target for ``from_member``+ so the sender's /join window receives its own P2P card.+2. ``session_history._is_member_relevant`` treats a p2p record as relevant to+ both ``to_member`` and ``from_member`` so the /join history replay matches the+ live fan_out semantics.+"""++from __future__ import annotations++from typing import Any++import pytest++from jiuwenswarm.server.runtime.agent_adapter import team_helpers+from jiuwenswarm.server.runtime.session import session_history+++def _p2p_event(*, from_member: str, to_member: str) -> dict[str, Any]:+ """Build a ``team.message`` event wrapping a p2p inner payload."""+ return {+ "event_type": "team.message",+ "session_id": "sess-p2p",+ "event": {+ "type": "team.message.p2p",+ "team_id": "demo-team",+ "from_member": from_member,+ "to_member": to_member,+ "message_id": "msg-1",+ "content": "hi",+ },+ }+++def _broadcast_event(*, from_member: str | None = None) -> dict[str, Any]:+ """Build a ``team.message`` event wrapping a broadcast inner payload."""+ return {+ "event_type": "team.message",+ "session_id": "sess-broadcast",+ "event": {+ "type": "team.message.broadcast",+ "team_id": "demo-team",+ "from_member": from_member,+ "message_id": "msg-2",+ "content": "hello all",+ },+ }+++def _target_summary(targets: list[dict]) -> list[tuple[str, tuple[str, ...], str | None]]:+ """Reduce LogicalTarget list to (intent, member_names, speaker) tuples."""+ summaries: list[tuple[str, tuple[str, ...], str | None]] = []+ for tgt in targets:+ names = tuple(tgt.get("member_names") or [])+ summaries.append((tgt["intent"], names, tgt.get("speaker")))+ return summaries+++def test_p2p_fanout_echoes_sender_via_private():+ """p2p (from=reviewer-2, to=reviewer-1) → godview / mention(to) / private(from)."""+ event = _p2p_event(from_member="reviewer-2", to_member="reviewer-1")++ targets = team_helpers._build_logical_targets(event)++ assert _target_summary(targets) == [+ ("godview", (), None),+ ("mention", ("reviewer-1",), "reviewer-2"),+ ("private", ("reviewer-2",), "reviewer-2"),+ ]+ # The sender target must be private (no @ self) — mention carries the+ # recipient; broadcast-like mention_all must not be set on any target.+ assert not any(t.get("mention_all") for t in targets)+++def test_p2p_fanout_order_is_godview_then_recipient_then_sender():+ """godview first, recipient (mention) second, sender (private) last.++ Order matters for same-container dedup: the recipient intent is dispatched+ before the sender's private intent so that, when both share one physical+ container, the recipient view wins and the sender's private is deduped to a+ no-op rather than the other way around.+ """+ event = _p2p_event(from_member="reviewer-2", to_member="reviewer-1")++ targets = team_helpers._build_logical_targets(event)+ intents = [t["intent"] for t in targets]++ assert intents == ["godview", "mention", "private"]+ assert targets[-1]["member_names"] == ["reviewer-2"]+++def test_p2p_fanout_skips_private_when_from_member_missing():+ """Missing from_member must not produce a private([None]) target."""+ inner = {+ "type": "team.message.p2p",+ "team_id": "demo-team",+ "to_member": "reviewer-1",+ # from_member intentionally absent+ }++ targets = team_helpers._p2p_fanout(inner)++ assert _target_summary(targets) == [+ ("godview", (), None),+ ("mention", ("reviewer-1",), None),+ ]+ # No target should carry a None member name.+ assert all(None not in (t.get("member_names") or []) for t in targets)+++def test_p2p_fanout_skips_private_when_from_member_is_falsy():+ """Empty-string from_member is treated as missing."""+ inner = {+ "type": "team.message.p2p",+ "team_id": "demo-team",+ "from_member": "",+ "to_member": "reviewer-1",+ }++ targets = team_helpers._p2p_fanout(inner)++ assert len(targets) == 2+ assert all(t["intent"] != "private" for t in targets)+++def test_broadcast_fanout_unchanged_by_p2p_echo_change():+ """broadcast fan_out stays [godview, mention_all] — sender echo is p2p-only."""+ event = _broadcast_event(from_member="reviewer-1")++ targets = team_helpers._build_logical_targets(event)++ assert len(targets) == 2+ assert targets[0]["intent"] == "godview"+ assert targets[1]["intent"] == "mention"+ assert targets[1].get("mention_all") is True+ assert targets[1].get("member_names") == []+ assert targets[1].get("speaker") == "reviewer-1"+ # No private target for broadcast.+ assert not any(t["intent"] == "private" for t in targets)+++# ---------------------------------------------------------------------------+# session_history._is_member_relevant+# ---------------------------------------------------------------------------+++def _history_item(msg_type: str, *, from_member: str = "", to_member: str = "") -> dict[str, Any]:+ """Build a flat history item mirroring append_history_record's extra spread.++ ``append_history_record`` flattens the event inner dict onto the item top+ level via ``item.update(serialized_extra)``, so ``from_member``/``to_member``+ are present both at the item top level and inside ``event``.+ """+ return {+ "event_type": "team.message",+ "type": msg_type,+ "from_member": from_member,+ "to_member": to_member,+ "event": {+ "type": msg_type,+ "from_member": from_member,+ "to_member": to_member,+ },+ }+++def test_is_member_relevant_p2p_visible_to_recipient_and_sender():+ item = _history_item("team.message.p2p", from_member="reviewer-2", to_member="reviewer-1")++ assert session_history._is_member_relevant(item, "reviewer-1") is True # recipient+ assert session_history._is_member_relevant(item, "reviewer-2") is True # sender+ assert session_history._is_member_relevant(item, "reviewer-3") is False # bystander+++def test_is_member_relevant_p2p_uses_inner_fields_when_top_level_absent():+ """When only the nested ``event`` carries member names, relevance still holds."""+ item = {+ "event_type": "team.message",+ "event": {+ "type": "team.message.p2p",+ "from_member": "reviewer-2",+ "to_member": "reviewer-1",+ },+ }++ assert session_history._is_member_relevant(item, "reviewer-1") is True+ assert session_history._is_member_relevant(item, "reviewer-2") is True+ assert session_history._is_member_relevant(item, "reviewer-3") is False+++def test_is_member_relevant_broadcast_visible_to_all():+ item = _history_item("team.message.broadcast", from_member="reviewer-1")++ assert session_history._is_member_relevant(item, "reviewer-1") is True+ assert session_history._is_member_relevant(item, "reviewer-2") is True+ assert session_history._is_member_relevant(item, "reviewer-3") is True+++def test_is_member_relevant_bystander_teammate_output_only_for_self():+ """chat.* teammate output stays visible only to the member who owns it."""+ item = {+ "event_type": "chat.final",+ "role": "teammate",+ "member_name": "reviewer-2",+ }++ assert session_history._is_member_relevant(item, "reviewer-2") is True+ assert session_history._is_member_relevant(item, "reviewer-1") is False+++if __name__ == "__main__":+ pytest.main([__file__, "-v"])diff --git a/tests/unit_tests/agentserver/test_team_manager_registry.py b/tests/unit_tests/agentserver/test_team_manager_registry.pyindex f007834944..a6f1ee8395 100644--- a/tests/unit_tests/agentserver/test_team_manager_registry.py+++ b/tests/unit_tests/agentserver/test_team_manager_registry.py@@ -96,7 +96,12 @@ def teardown_function() -> None:reset_team_manager()-def test_get_team_manager_is_scoped_by_channel() -> None:+def test_get_team_manager_is_singleton() -> None:+ # TeamManager is a process-wide singleton shared across channels so that+ # bridged follow-up requests (e.g. a /join member replying from feishu+ # while the originating web stream is still alive) can see the+ # originating channel's runtime markers and avoid being misidentified as+ # a first request.web_manager = get_team_manager("web")feishu_manager = get_team_manager("feishu")web_manager_again = get_team_manager("web")@@ -104,7 +109,11 @@ def test_get_team_manager_is_scoped_by_channel() -> None:assert isinstance(web_manager, TeamManager)assert isinstance(feishu_manager, TeamManager)assert web_manager is web_manager_again- assert web_manager is not feishu_manager+ assert web_manager is feishu_manager # singleton: same instance regardless of channel++ reset_team_manager()+ after_reset = get_team_manager("web")+ assert after_reset is not web_manager # reset yields a fresh instance@pytest.mark.asyncio@@ -476,7 +485,7 @@ async def test_create_team_does_not_run_global_runtime_cleanup(monkeypatch: pyte@staticmethoddef build():- return object()+ return SimpleNamespace()return _Spec()@@ -515,7 +524,7 @@ async def test_create_team_appends_session_id_to_team_name(monkeypatch: pytest.Mdef build(self):created_team_names.append(self.team_name)- return object()+ return SimpleNamespace()monkeypatch.setattr(TeamManager, "_load_team_spec", staticmethod(lambda _session_id: _Spec()))monkeypatch.setattr(@@ -551,7 +560,7 @@ async def test_create_team_appends_session_id_to_web_team_name(monkeypatch: pytedef build(self):created_team_names.append(self.team_name)- return object()+ return SimpleNamespace()monkeypatch.setattr(TeamManager, "_load_team_spec", staticmethod(lambda _session_id: _Spec()))monkeypatch.setattr(diff --git a/tests/unit_tests/agentserver/test_team_members_get.py b/tests/unit_tests/agentserver/test_team_members_get.pynew file mode 100644index 0000000000..e4f1603e11--- /dev/null+++ b/tests/unit_tests/agentserver/test_team_members_get.py@@ -0,0 +1,197 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Tests for AgentWebSocketServer._handle_team_members_get (/join seat validation)."""++from __future__ import annotations++import asyncio+import json+from typing import Any+from unittest import mock++import pytest++from jiuwenswarm.common.schema.agent import AgentRequest+from jiuwenswarm.common.schema.message import ReqMethod+++class _FakeMonitorHandler:+ """Minimal stand-in for TeamMonitorHandler."""++ def __init__(self, *, is_running: bool, snapshot: dict[str, Any] | None) -> None:+ self.is_running = is_running+ self._snapshot = snapshot++ async def get_team_snapshot(self) -> dict[str, Any] | None:+ return self._snapshot++ async def get_member_list(self) -> list[dict[str, Any]] | None:+ # /join 校验走 get_member_list(仅 members,无 tasks/team_id);+ # 沿用 snapshot 里的 members 项以复用既有 fixture。+ if self._snapshot is None:+ return None+ return list(self._snapshot.get("members", []))+++class _FakeTeamManager:+ def __init__(self, monitor_handler: _FakeMonitorHandler | None) -> None:+ self._monitor_handler = monitor_handler++ def get_monitor_handler(self, session_id: str) -> _FakeMonitorHandler | None:+ return self._monitor_handler+++class _FakeWS:+ def __init__(self) -> None:+ self.sent: list[str] = []++ async def send(self, data: str) -> None:+ self.sent.append(data)+++def _make_request(session_id: str = "sess-1", channel_id: str = "feishu") -> AgentRequest:+ return AgentRequest(+ request_id="req-1",+ session_id=session_id,+ channel_id=channel_id,+ req_method=ReqMethod.TEAM_MEMBERS_GET,+ params={"session_id": session_id},+ )+++async def _invoke(monitor_handler: _FakeMonitorHandler | None):+ """Call _handle_team_members_get without instantiating AgentWebSocketServer.++ Returns the decoded AgentResponse that the gateway would observe.+ """+ from jiuwenswarm.common.e2a.wire_codec import parse_agent_server_wire_unary+ from jiuwenswarm.server import agent_ws_server++ ws = _FakeWS()+ lock = asyncio.Lock()+ request = _make_request()+ fake_tm = _FakeTeamManager(monitor_handler)+ with mock.patch(+ "jiuwenswarm.agents.harness.team.get_team_manager",+ return_value=fake_tm,+ ):+ # handler body does not use `self`; call the underlying function.+ await agent_ws_server.AgentWebSocketServer._handle_team_members_get(+ None, ws, request, lock+ )+ assert len(ws.sent) == 1+ return parse_agent_server_wire_unary(json.loads(ws.sent[0]))+++async def test_filters_only_human_agent_members() -> None:+ snapshot = {+ "members": [+ {"member_id": "leader-1", "name": "Leader", "role": "teammate"},+ {"member_id": "reviewer-1", "name": "Reviewer 1", "role": "human_agent"},+ {"member_id": "coder-1", "name": "Coder 1", "role": "teammate"},+ {"member_id": "pm-1", "name": "PM", "role": "human_agent"},+ ],+ "tasks": [{"task_id": "t-1"}],+ "team_id": "team-x",+ }+ resp = await _invoke(_FakeMonitorHandler(is_running=True, snapshot=snapshot))++ assert resp.request_id == "req-1"+ assert resp.ok is True+ payload = resp.payload+ # 成功路径只回 members(/join 不依赖 team_id/tasks,见 _handle_team_members_get)+ assert [m["member_id"] for m in payload["members"]] == ["reviewer-1", "pm-1"]+ assert "tasks" not in payload+ assert "team_id" not in payload+++async def test_no_live_monitor_returns_empty_members() -> None:+ resp = await _invoke(monitor_handler=None)++ assert resp.ok is True+ assert resp.payload == {"members": [], "team_id": None}+++async def test_cross_channel_finds_monitor_in_other_manager() -> None:+ """跨 channel /join:请求 channel 的 manager 无此 session,应遍历其他 manager 找到。++ 场景:team 在 web channel 创建(monitor 注册在 web 的 TeamManager),飞书 /join+ 发来的 request.channel_id=feishu。若只查 feishu 的 manager 会拿空列表误判"团队未就绪";+ 修复后应遍历所有 manager 命中 web 那个,返回真实 human_agent 成员。+ """+ snapshot = {+ "members": [+ {"member_id": "human-player-1", "role": "human_agent"},+ {"member_id": "ai-player-1", "role": "teammate"},+ ],+ "tasks": [],+ "team_id": "team-web",+ }+ live_handler = _FakeMonitorHandler(is_running=True, snapshot=snapshot)++ # feishu 的 manager(请求 channel)没有这个 session+ feishu_tm = _FakeTeamManager(monitor_handler=None)+ # web 的 manager 持有该 session 的 monitor+ web_tm = _FakeTeamManager(monitor_handler=live_handler)++ from jiuwenswarm.common.e2a.wire_codec import parse_agent_server_wire_unary+ from jiuwenswarm.server import agent_ws_server++ ws = _FakeWS()+ lock = asyncio.Lock()+ request = _make_request(session_id="sess-1", channel_id="feishu")+ with mock.patch(+ "jiuwenswarm.agents.harness.team.get_team_manager",+ return_value=feishu_tm,+ ), mock.patch(+ "jiuwenswarm.agents.harness.team.get_all_team_managers",+ return_value=[feishu_tm, web_tm],+ ):+ await agent_ws_server.AgentWebSocketServer._handle_team_members_get(+ None, ws, request, lock+ )+ assert len(ws.sent) == 1+ resp = parse_agent_server_wire_unary(json.loads(ws.sent[0]))++ assert resp.ok is True+ assert [m["member_id"] for m in resp.payload["members"]] == ["human-player-1"]+++async def test_stopped_monitor_returns_empty_members() -> None:+ resp = await _invoke(_FakeMonitorHandler(is_running=False, snapshot=None))++ assert resp.ok is True+ assert resp.payload == {"members": [], "team_id": None}+++async def test_snapshot_raises_returns_empty_members() -> None:+ class _BoomHandler(_FakeMonitorHandler):+ async def get_member_list(self) -> list[dict[str, Any]] | None:+ raise RuntimeError("boom")++ resp = await _invoke(_BoomHandler(is_running=True, snapshot=None))++ assert resp.ok is True+ # get_member_list 抛错时降级返回空 members(不含 team_id)+ assert resp.payload == {"members": []}+++async def test_no_human_agent_seats_returns_empty_members() -> None:+ snapshot = {+ "members": [+ {"member_id": "leader-1", "role": "teammate"},+ {"member_id": "coder-1", "role": "teammate"},+ ],+ "tasks": [],+ "team_id": "team-y",+ }+ resp = await _invoke(_FakeMonitorHandler(is_running=True, snapshot=snapshot))++ assert resp.ok is True+ assert resp.payload["members"] == []diff --git a/tests/unit_tests/channel/test_web_channel_symphony_status.py b/tests/unit_tests/channel/test_web_channel_symphony_status.pyindex ef2f6bce0a..de60e59e21 100644--- a/tests/unit_tests/channel/test_web_channel_symphony_status.py+++ b/tests/unit_tests/channel/test_web_channel_symphony_status.py@@ -1,3 +1,4 @@+import asyncioimport jsonimport pytest@@ -8,11 +9,14 @@ from jiuwenswarm.gateway.channel_manager.web.web_connect import (WebChannel,WebChannelConfig,)+from jiuwenswarm.gateway.routing.keys import RoutingKey+from jiuwenswarm.gateway.routing.session_sharing import RoutingTargetclass _FakeClient:def __init__(self):self.frames = []+ self.closed = Falseasync def send(self, data):self.frames.append(json.loads(data))@@ -22,39 +26,61 @@ class _FakeClient:async def test_web_channel_preserves_symphony_status_payload():channel = WebChannel(WebChannelConfig(enabled=True), RobotMessageRouter())client = _FakeClient()- getattr(channel, "_clients").add(client)-- await channel.send(- Message(- id="req-1",- type="event",- channel_id="web",- session_id="sess-1",- params={},- timestamp=0.0,- ok=True,- payload={- "source": "symphony_compose_score",- "operation_id": "call-1",- "phase": "checking_score",- "content": "Symphony status",- "status": "in_progress",- },- event_type=EventType.CHAT_SYMPHONY_STATUS,- )+ routing_key = RoutingKey(+ channel_id="web",+ app_id="default",+ user_id="test_user",+ session_id="sess-1",+ agent_ref=None,)- assert client.frames == [- {- "type": "event",- "event": "chat.symphony_status",- "payload": {- "source": "symphony_compose_score",- "operation_id": "call-1",- "phase": "checking_score",- "content": "Symphony status",- "status": "in_progress",- "session_id": "sess-1",- },- }- ]+ msg = Message(+ id="req-1",+ type="event",+ channel_id="web",+ session_id="sess-1",+ params={},+ timestamp=0.0,+ ok=True,+ payload={+ "source": "symphony_compose_score",+ "operation_id": "call-1",+ "phase": "checking_score",+ "content": "Symphony status",+ "status": "in_progress",+ },+ event_type=EventType.CHAT_SYMPHONY_STATUS,+ )++ # 创建 RoutingTarget 包含 routing_keys+ routing_target = RoutingTarget(+ intent="godview", # 必需参数+ routing_keys=[routing_key],+ member_names=(),+ )++ # 走真实 _register 建 ws 映射 + 起 per-ws writer(send 现在是非阻塞入队)+ await channel.register_ws(client, routing_key)+ try:+ await channel.send(msg, routing_target=routing_target)+ # writer 异步送出,flush 一下再断言+ for _ in range(20):+ if client.frames:+ break+ await asyncio.sleep(0.005)+ assert client.frames == [+ {+ "type": "event",+ "event": "chat.symphony_status",+ "payload": {+ "source": "symphony_compose_score",+ "operation_id": "call-1",+ "phase": "checking_score",+ "content": "Symphony status",+ "status": "in_progress",+ "session_id": "sess-1",+ },+ }+ ]+ finally:+ await channel.unregister_ws(client)diff --git a/tests/unit_tests/gateway/test_channel_manager_file_fanout.py b/tests/unit_tests/gateway/test_channel_manager_file_fanout.pynew file mode 100644index 0000000000..10d1c519d8--- /dev/null+++ b/tests/unit_tests/gateway/test_channel_manager_file_fanout.py@@ -0,0 +1,186 @@+"""Unit tests for cross-channel file delivery fan_out injection.++Covers ``ChannelManager._inject_file_delivery_fanout`` and+``SendFileToolkit._normalize_target_channels`` — the core of the fix that+makes ``send_file_to_user`` route files to all channels joined to a team+session (e.g. Feishu) instead of only the originating channel.+"""+from __future__ import annotations++import pytest++from jiuwenswarm.agents.harness.common.tools.send_file_to_user import SendFileToolkit+from jiuwenswarm.common.schema.message import EventType, Message+from jiuwenswarm.gateway.channel_manager.channel_manager import ChannelManager+from jiuwenswarm.gateway.routing.keys import AgentRef, RoutingKey, make_delivery_target+from jiuwenswarm.gateway.routing.session_sharing import SessionSharingRegistry, SubRole+++class _FakeMessageHandler:+ """Minimal MessageHandler exposing only the registry accessor."""++ def __init__(self, registry: SessionSharingRegistry) -> None:+ self._session_sharing = registry++ def get_session_sharing_registry(self) -> SessionSharingRegistry:+ return self._session_sharing+++async def _make_subscription(+ registry: SessionSharingRegistry, session_id: str, member_name: str, channel_id: str,+) -> None:+ rk = RoutingKey(+ user_id=f"u_{channel_id}",+ channel_id=channel_id,+ app_id="default",+ agent_ref=AgentRef("team", "default"),+ session_id=session_id,+ )+ dt = make_delivery_target(channel_id, chat_id=f"chat_{channel_id}", physical_user_id=f"u_{channel_id}")+ await registry.register(session_id, member_name, rk, dt)+++def _make_channel_manager(registry: SessionSharingRegistry) -> ChannelManager:+ return ChannelManager(_FakeMessageHandler(registry))+++def _make_file_msg(session_id: str, channel_id: str = "web", metadata: dict | None = None) -> Message:+ return Message(+ id="req-1",+ type="event",+ channel_id=channel_id,+ session_id=session_id,+ params={},+ timestamp=0.0,+ ok=True,+ payload={"event_type": "chat.file", "files": [{"path": "/tmp/a.txt", "name": "a.txt"}]},+ event_type=EventType.CHAT_FILE,+ metadata=metadata if metadata is not None else {},+ )+++# ---------- _normalize_target_channels ----------+++ "raw,expected",+ [+ (None, []),+ ("", []),+ ("feishu", ["feishu"]),+ ('["feishu","web"]', ["feishu", "web"]),+ (["feishu", "web"], ["feishu", "web"]),+ ([" feishu ", "", "web"], ["feishu", "web"]),+ ("reviewer-1", ["reviewer-1"]),+ ],+)+def test_normalize_target_channels(raw, expected):+ assert SendFileToolkit._normalize_target_channels(raw) == expected+++# ---------- _inject_file_delivery_fanout ----------+++async def test_inject_returns_none_for_non_file_event():+ reg = SessionSharingRegistry()+ cm = _make_channel_manager(reg)+ msg = _make_file_msg("s1")+ result = await cm._inject_file_delivery_fanout(msg, "chat.final")+ assert result is None+ assert "fan_out_targets" not in (msg.metadata or {})+++async def test_inject_returns_none_when_registry_empty():+ reg = SessionSharingRegistry()+ cm = _make_channel_manager(reg)+ msg = _make_file_msg("s1")+ result = await cm._inject_file_delivery_fanout(msg, "chat.file")+ assert result is None+ # 纯 web 会话(无订阅)保持单 channel 兜底+ assert "fan_out_targets" not in (msg.metadata or {})+++async def test_inject_auto_targets_godview_and_all_members():+ reg = SessionSharingRegistry()+ await _make_subscription(reg, "s1", SubRole.GODVIEW, "web")+ await _make_subscription(reg, "s1", "reviewer-1", "feishu")+ await _make_subscription(reg, "s1", "reviewer-2", "xiaoyi")+ cm = _make_channel_manager(reg)+ msg = _make_file_msg("s1", channel_id="web")+ result = await cm._inject_file_delivery_fanout(msg, "chat.file")+ # godview 覆盖 web;mention_all 覆盖所有人类成员(飞书/xiaoyi)+ assert result == [+ {"intent": "godview", "mention_all": False, "member_names": [], "speaker": None},+ {"intent": "mention", "mention_all": True, "member_names": [], "speaker": None},+ ]+ assert msg.metadata["fan_out_targets"] == result+++async def test_inject_respects_explicit_send_file_targets_by_channel():+ reg = SessionSharingRegistry()+ await _make_subscription(reg, "s1", SubRole.GODVIEW, "web")+ await _make_subscription(reg, "s1", "reviewer-1", "feishu")+ cm = _make_channel_manager(reg)+ msg = _make_file_msg("s1", channel_id="web", metadata={"send_file_targets": ["feishu"]})+ result = await cm._inject_file_delivery_fanout(msg, "chat.file")+ assert result and result[0]["intent"] == "mention"+ assert "reviewer-1" in result[0]["member_names"]+++async def test_inject_respects_explicit_send_file_targets_by_member_name():+ reg = SessionSharingRegistry()+ await _make_subscription(reg, "s1", SubRole.GODVIEW, "web")+ await _make_subscription(reg, "s1", "reviewer-1", "feishu")+ cm = _make_channel_manager(reg)+ msg = _make_file_msg("s1", channel_id="web", metadata={"send_file_targets": ["reviewer-1"]})+ result = await cm._inject_file_delivery_fanout(msg, "chat.file")+ assert result and result[0]["intent"] == "mention"+ assert "reviewer-1" in result[0]["member_names"]+++async def test_inject_explicit_target_no_match_falls_back_to_godview():+ reg = SessionSharingRegistry()+ await _make_subscription(reg, "s1", SubRole.GODVIEW, "web")+ await _make_subscription(reg, "s1", "reviewer-1", "feishu")+ cm = _make_channel_manager(reg)+ msg = _make_file_msg("s1", channel_id="web", metadata={"send_file_targets": ["dingtalk"]})+ result = await cm._inject_file_delivery_fanout(msg, "chat.file")+ assert result == [{"intent": "godview", "mention_all": False, "member_names": [], "speaker": None}]+++async def test_inject_explicit_target_excludes_godview_to_avoid_leak():+ # 飞书同时有 godview 订阅 + 人类成员订阅;指定 ["feishu"] 应只命中人类成员,+ # 不应把 "GodView" 放入 member_names(否则 lookup_member("GodView") 会广播到 web)。+ reg = SessionSharingRegistry()+ await _make_subscription(reg, "s1", SubRole.GODVIEW, "web")+ await _make_subscription(reg, "s1", SubRole.GODVIEW, "feishu")+ await _make_subscription(reg, "s1", "reviewer-1", "feishu")+ cm = _make_channel_manager(reg)+ msg = _make_file_msg("s1", channel_id="web", metadata={"send_file_targets": ["feishu"]})+ result = await cm._inject_file_delivery_fanout(msg, "chat.file")+ assert result and result[0]["intent"] == "mention"+ assert "reviewer-1" in result[0]["member_names"]+ assert "GodView" not in result[0]["member_names"]+++async def test_inject_auto_reaches_member_only_channel_without_godview():+ # 飞书只有人类成员订阅(/join 后未再发消息,godview 尚未补注册)。+ # 自动模式必须仍能覆盖飞书(靠 mention_all),不能只靠 godview。+ reg = SessionSharingRegistry()+ await _make_subscription(reg, "s1", SubRole.GODVIEW, "web")+ await _make_subscription(reg, "s1", "reviewer-1", "feishu")+ cm = _make_channel_manager(reg)+ msg = _make_file_msg("s1", channel_id="web")+ result = await cm._inject_file_delivery_fanout(msg, "chat.file")+ intents = [t["intent"] for t in result]+ assert "godview" in intents and any(t["mention_all"] for t in result)+++async def test_inject_preserves_existing_fan_out_targets():+ reg = SessionSharingRegistry()+ await _make_subscription(reg, "s1", SubRole.GODVIEW, "web")+ cm = _make_channel_manager(reg)+ existing = [{"intent": "mention", "mention_all": True, "member_names": [], "speaker": None}]+ msg = _make_file_msg("s1", channel_id="web", metadata={"fan_out_targets": existing})+ result = await cm._inject_file_delivery_fanout(msg, "chat.file")+ assert result is existing\ No newline at end of filediff --git a/tests/unit_tests/gateway/test_join_exit_godview_container.py b/tests/unit_tests/gateway/test_join_exit_godview_container.pynew file mode 100644index 0000000000..87c5af965b--- /dev/null+++ b/tests/unit_tests/gateway/test_join_exit_godview_container.py@@ -0,0 +1,128 @@+"""验证 GodView(通道级伪 member)不参与 /join 容器去重,以及 /exit 正确性基础。++背景:GodView 由 _maybe_register_godview 自动注册,接收全量输出,不是 /join 认领+的真实席位。两个 bug 同源:++1. /join 容器去重(lookup_by_container)曾未排除 GodView,导致飞书群 /mode team+ 自动注册 GodView 后,再 /join 真实 member 被自己的 GodView 挡住(报+ "已加入 session 席位:GodView")。+2. /exit 不带 session_ref 时曾误以为 msg.session_id 是物理 chat_id。实际+ handle_message 入队前已调 resolve_member_by_user 把已 /join 用户的+ msg.session_id 改写为逻辑 session 并写入 member_name,故 /exit 直接用+ msg.session_id 即可;只需在未命中(未 /join)时用 channel state 的逻辑 session+ 做提示,避免显示物理 chat_id。++Fix 1:lookup_by_container 跳过 is_godview,与 resolve_member_by_user 一致。+Fix 2:依赖 resolve_member_by_user 返回逻辑 session 且不命中 GodView(下面验证+ 这条契约;handler 层的改动是去掉冗余反查兜底,不再单独测)。+"""+from __future__ import annotations++import pytest++from jiuwenswarm.gateway.routing.keys import AgentRef, RoutingKey, make_delivery_target+from jiuwenswarm.gateway.routing.session_sharing import SessionSharingRegistry, SubRole+++def _rk(channel_id: str, user_id: str, session_id: str) -> RoutingKey:+ return RoutingKey(+ user_id=user_id,+ channel_id=channel_id,+ app_id="default",+ agent_ref=AgentRef("team", "default"),+ session_id=session_id,+ )+++async def _register(+ reg: SessionSharingRegistry, session_id: str, member_name: str,+ channel_id: str, user_id: str, chat_id: str,+) -> None:+ rk = _rk(channel_id, user_id, session_id)+ dt = make_delivery_target(channel_id, chat_id=chat_id, physical_user_id=user_id)+ await reg.register(session_id, member_name, rk, dt)+++# ---------- Fix 1: lookup_by_container 排除 GodView ----------+++async def test_lookup_by_container_skips_godview():+ """GodView 订阅不应被 /join 容器去重命中。++ 模拟飞书群 /mode team 已注册 GodView(逻辑 session feishu_xxx,+ delivery.chat_id=oc_xxx),同一容器再 /join 真实 member 时,+ lookup_by_container 应返回空(不被 GodView 挡)。+ """+ reg = SessionSharingRegistry()+ await _register(reg, "feishu_xxx", SubRole.GODVIEW, "feishu", "u1", "oc_group1")++ found = reg.lookup_by_container("feishu", "default", "oc_group1")+ assert found == [], f"GodView 不应参与容器去重, got {found}"+++async def test_lookup_by_container_still_finds_real_member_cross_session():+ """排除 GodView 后,同一容器跨 session 的真实 member 仍能被挡(去重约束保留)。++ 用户用同一飞书群 chat_id 在 session_A /join 了 reviewer-1,又想在 session_B+ /join reviewer-2 → lookup_by_container 应命中 session_A 的真实 member 订阅。+ """+ reg = SessionSharingRegistry()+ await _register(reg, "session_A", "reviewer-1", "feishu", "u1", "oc_group1")+ # 同容器还有 GodView(不应干扰)+ await _register(reg, "session_A", SubRole.GODVIEW, "feishu", "u1", "oc_group1")++ found = reg.lookup_by_container("feishu", "default", "oc_group1")+ # 只命中真实 member,不含 GodView+ assert len(found) == 1+ sid, mname, _sub = found[0]+ assert sid == "session_A"+ assert mname == "reviewer-1"+++async def test_lookup_by_container_empty_container_id_returns_empty():+ reg = SessionSharingRegistry()+ await _register(reg, "s1", "reviewer-1", "feishu", "u1", "oc_group1")+ assert reg.lookup_by_container("feishu", "default", "") == []+++# ---------- Fix 2: resolve_member_by_user 语义(/exit 正确性的基础) ----------+#+# /exit 不带 session_ref 时用 msg.session_id。这之所以正确,是因为 handle_message+# 在入队前调 resolve_member_by_user:已 /join 用户命中 → msg.session_id 被改写为+# 逻辑 session + metadata["member_name"] 写入。下面验证该反查返回的是逻辑 session+# (feishu_xxx)而非物理 chat_id(oc_xxx),且不命中 GodView。+++async def test_resolve_member_by_user_returns_logical_session_not_chat_id():+ """反查命中的 session_id 是逻辑 session(feishu_xxx),不是物理 chat_id(oc_xxx)。++ handle_message 据此把 msg.session_id 改写为逻辑 session,/exit 直接用即可。+ """+ reg = SessionSharingRegistry()+ # member 注册在逻辑 session feishu_xxx 下,delivery.chat_id=oc_xxx+ await _register(reg, "feishu_xxx", "reviewer-1", "feishu", "ou_user1", "oc_group1")++ resolved = reg.resolve_member_by_user("feishu", "default", "ou_user1", chat_id="oc_group1")+ assert resolved is not None+ sid, mname = resolved+ assert sid == "feishu_xxx", "反查应返回逻辑 session, 不是物理 chat_id oc_xxx"+ assert mname == "reviewer-1"+++async def test_resolve_member_by_user_skips_godview():+ """GodView 不被反查命中(否则会注入 member_name=GodView 触发 $GodView 前缀)。++ 用户只注册了 GodView(没 /join 真实 member)→ 反查返回 None → handle_message+ 不改写 msg.session_id(保持物理 chat_id)、不写 member_name → /exit 走"无需退出"。+ """+ reg = SessionSharingRegistry()+ await _register(reg, "feishu_xxx", SubRole.GODVIEW, "feishu", "ou_user1", "oc_group1")++ assert reg.resolve_member_by_user("feishu", "default", "ou_user1", chat_id="oc_group1") is None+ # 无 chat_id 兜底也不命中+ assert reg.resolve_member_by_user("feishu", "default", "ou_user1") is Nonediff --git a/tests/unit_tests/test_app_web_handlers.py b/tests/unit_tests/test_app_web_handlers.pyindex 1d8bee3b90..43fffd3535 100644--- a/tests/unit_tests/test_app_web_handlers.py+++ b/tests/unit_tests/test_app_web_handlers.py@@ -6,8 +6,12 @@ import pytestfrom jiuwenswarm.gateway.channel_manager.web.app_web_handlers import (WebHandlersBindParams,+ _FEISHU_APP_DEFAULTS,+ _XIAOYI_APP_DEFAULTS,_flatten_modes_team_for_config_panel,_flatten_symphony_for_config_panel,+ _normalize_feishu_conf,+ _normalize_xiaoyi_conf,_register_web_handlers,)@@ -82,7 +86,7 @@ class FakeHeartbeatService:@pytest.mark.parametrize(("method", "params"),[- ("channel.feishu.set_conf", {"enabled": False, "app_id": "app-1"}),+ ("channel.feishu.set_conf", {"apps": [{"app_id": "app-1"}]}),("channel.dingtalk.set_conf", {"enabled": False, "client_id": "client-1"}),("heartbeat.set_conf", {"every": 30, "target": "web"}),],@@ -98,6 +102,10 @@ async def test_config_save_handlers_respond_before_agent_reload_finishes(monkeyp"jiuwenswarm.gateway.channel_manager.web.app_web_handlers.update_channel_in_config",lambda channel_id, conf: persisted.append((channel_id, dict(conf))),)+ monkeypatch.setattr(+ "jiuwenswarm.gateway.channel_manager.web.app_web_handlers.replace_channel_subsection_with_cleanup",+ lambda channel_id, subsection, conf, keep_keys: persisted.append((channel_id, conf)),+ )monkeypatch.setattr("jiuwenswarm.gateway.channel_manager.web.app_web_handlers.update_heartbeat_in_config",lambda payload: persisted.append(("heartbeat", dict(payload))),@@ -322,3 +330,509 @@ async def test_config_set_routes_symphony_payload_to_config_helper(monkeypatch):"error": None,"code": None,}+++# =====================================================================+# _normalize_feishu_conf 纯函数测试+# =====================================================================+++def test_normalize_feishu_conf_empty():+ """空配置 → 返回含单默认应用的 apps 列表。"""+ result = _normalize_feishu_conf({})+ assert "apps" in result+ assert len(result["apps"]) == 1+ app = result["apps"][0]+ assert app["name"] == "默认应用"+ assert app["is_default"] is True+ assert app["enabled"] is True+ assert app["allow_from"] == ["0.0.0.0/0"]+++def test_normalize_feishu_conf_non_dict():+ """非 dict 输入 → 返回 {"apps": []}。"""+ assert _normalize_feishu_conf(None) == {"apps": []}+ assert _normalize_feishu_conf("") == {"apps": []}+ assert _normalize_feishu_conf([]) == {"apps": []}+++def test_normalize_feishu_conf_flat_to_apps():+ """旧平铺格式 → 转为 apps 格式,补充缺省字段。"""+ raw = {+ "enabled": True,+ "app_id": "cli_xxx",+ "app_secret": "my_secret",+ "encrypt_key": "enc_key",+ "verification_token": "verify_token",+ }+ result = _normalize_feishu_conf(raw)+ assert "apps" in result+ assert len(result["apps"]) == 1+ app = result["apps"][0]+ assert app["is_default"] is True+ assert app["app_id"] == "cli_xxx"+ assert app["app_secret"] == "my_secret"+ assert app["allow_from"] == ["0.0.0.0/0"]+ assert app["enable_streaming"] is True+ assert app["group_digital_avatar"] is False+ # 原始平铺字段仍保留在顶层+ assert result["app_id"] == "cli_xxx"+++def test_normalize_feishu_conf_apps_fills_defaults():+ """已有 apps 列表 → 为每个 app 补充缺省字段。"""+ raw = {+ "apps": [+ {+ "name": "默认应用",+ "is_default": True,+ "app_id": "cli_xxx",+ "app_secret": "xxx",+ "encrypt_key": "key",+ "verification_token": "token",+ },+ {+ "name": "业务应用",+ "is_default": False,+ "app_id": "cli_yyy",+ "app_secret": "yyy",+ "encrypt_key": "key2",+ "verification_token": "token2",+ },+ ]+ }+ result = _normalize_feishu_conf(raw)+ assert len(result["apps"]) == 2++ # 第一个 app:缺省字段被填充+ app0 = result["apps"][0]+ assert app0["name"] == "默认应用"+ assert app0["enable_streaming"] is True+ assert app0["group_digital_avatar"] is False+ assert app0["allow_from"] == ["0.0.0.0/0"]++ # 第二个 app:同样补全+ app1 = result["apps"][1]+ assert app1["name"] == "业务应用"+ assert app1["enable_streaming"] is True+++def test_normalize_feishu_conf_apps_empty_list():+ """空 apps 列表 → 返回 {"apps": []}。"""+ result = _normalize_feishu_conf({"apps": []})+ assert result == {"apps": []}+++def test_normalize_feishu_conf_apps_preserves_extra_fields():+ """apps 中额外非标准字段应被保留(未来扩展)。"""+ raw = {"apps": [{"name": "test", "is_default": True, "app_id": "x", "app_secret": "x",+ "encrypt_key": "x", "verification_token": "x", "custom_tag": "hello"}]}+ result = _normalize_feishu_conf(raw)+ assert result["apps"][0]["custom_tag"] == "hello"+ assert result["apps"][0]["enable_streaming"] is True # 默认值仍在+++# =====================================================================+# _normalize_xiaoyi_conf 纯函数测试+# =====================================================================+++def test_normalize_xiaoyi_conf_empty():+ """空配置 → 返回含单默认应用的 apps 列表。"""+ result = _normalize_xiaoyi_conf({})+ assert "apps" in result+ assert len(result["apps"]) == 1+ app = result["apps"][0]+ assert app["name"] == "默认应用"+ assert app["is_default"] is True+ assert app["mode"] == "xiaoyi_channel"+ assert app["ws_url1"] == "wss://hag.cloud.huawei.com/openclaw/v1/ws/link"+++def test_normalize_xiaoyi_conf_non_dict():+ """非 dict 输入 → 返回 {"apps": []}。"""+ assert _normalize_xiaoyi_conf(None) == {"apps": []}+ assert _normalize_xiaoyi_conf(42) == {"apps": []}+++def test_normalize_xiaoyi_conf_flat_to_apps():+ """旧平铺格式 → 转为 apps 格式,补充缺省字段。"""+ raw = {+ "enabled": True,+ "ak": "access_key",+ "sk": "secret_key",+ "agent_id": "agent_default",+ "app_id": "app_xxx",+ }+ result = _normalize_xiaoyi_conf(raw)+ assert "apps" in result+ assert len(result["apps"]) == 1+ app = result["apps"][0]+ assert app["is_default"] is True+ assert app["ak"] == "access_key"+ assert app["sk"] == "secret_key"+ assert app["agent_id"] == "agent_default"+ assert app["mode"] == "xiaoyi_channel"+ assert app["phone_tools_enabled"] is False+++def test_normalize_xiaoyi_conf_apps_fills_defaults():+ """已有 apps 列表 → 为每个 app 补充缺省字段。"""+ raw = {+ "apps": [+ {+ "name": "默认应用",+ "is_default": True,+ "ak": "ak_1",+ "sk": "sk_1",+ "app_id": "app_1",+ "agent_id": "agent_1",+ }+ ]+ }+ result = _normalize_xiaoyi_conf(raw)+ assert len(result["apps"]) == 1+ app = result["apps"][0]+ assert app["mode"] == "xiaoyi_channel"+ assert app["enable_streaming"] is True+ assert app["phone_tools_enabled"] is False+ assert app["push_id"] == ""+ assert app["ws_url1"] == "wss://hag.cloud.huawei.com/openclaw/v1/ws/link"+++def test_normalize_xiaoyi_conf_apps_empty_list():+ """空 apps 列表 → 返回 {"apps": []}。"""+ assert _normalize_xiaoyi_conf({"apps": []}) == {"apps": []}+++# =====================================================================+# get_conf 处理程序 — 验证归一化在读取时生效+# =====================================================================+++async def test_channel_feishu_get_conf_normalizes(monkeypatch):+ channel = FakeWebChannel()+ cm = FakeChannelManager()+ # 预置旧平铺配置+ cm.configs["feishu"] = {"app_id": "old_id", "app_secret": "old_secret"}+ _register_web_handlers(WebHandlersBindParams(channel=channel, channel_manager=cm))++ await channel.methods["channel.feishu.get_conf"](object(), "req-1", {}, "sess-1")++ assert channel.responses[-1]["ok"] is True+ payload = channel.responses[-1]["payload"]+ assert "config" in payload+ assert "apps" in payload["config"]+ assert len(payload["config"]["apps"]) == 1+ app = payload["config"]["apps"][0]+ assert app["app_id"] == "old_id"+ assert app["app_secret"] == "old_secret"+ # 验证归一化补充了缺省字段+ assert app["allow_from"] == ["0.0.0.0/0"]+ assert app["enable_streaming"] is True+ assert app["is_default"] is True+++async def test_channel_feishu_get_conf_empty_returns_default_apps(monkeypatch):+ channel = FakeWebChannel()+ cm = FakeChannelManager()+ _register_web_handlers(WebHandlersBindParams(channel=channel, channel_manager=cm))++ await channel.methods["channel.feishu.get_conf"](object(), "req-1", {}, "sess-1")++ assert channel.responses[-1]["ok"] is True+ payload = channel.responses[-1]["payload"]+ assert "apps" in payload["config"]+ # 空配置 → 返回一个默认应用+ assert len(payload["config"]["apps"]) == 1+ assert payload["config"]["apps"][0]["is_default"] is True+++async def test_channel_xiaoyi_get_conf_normalizes(monkeypatch):+ channel = FakeWebChannel()+ cm = FakeChannelManager()+ cm.configs["xiaoyi"] = {"ak": "ak_1", "sk": "sk_1", "agent_id": "agent_1"}+ _register_web_handlers(WebHandlersBindParams(channel=channel, channel_manager=cm))++ await channel.methods["channel.xiaoyi.get_conf"](object(), "req-1", {}, "sess-1")++ assert channel.responses[-1]["ok"] is True+ payload = channel.responses[-1]["payload"]+ assert "config" in payload+ assert "apps" in payload["config"]+ app = payload["config"]["apps"][0]+ assert app["ak"] == "ak_1"+ assert app["mode"] == "xiaoyi_channel"+++async def test_channel_xiaoyi_get_conf_empty_returns_default_apps(monkeypatch):+ channel = FakeWebChannel()+ cm = FakeChannelManager()+ _register_web_handlers(WebHandlersBindParams(channel=channel, channel_manager=cm))++ await channel.methods["channel.xiaoyi.get_conf"](object(), "req-1", {}, "sess-1")++ assert channel.responses[-1]["ok"] is True+ assert len(channel.responses[-1]["payload"]["config"]["apps"]) == 1+++# =====================================================================+# set_conf 处理程序 — 多应用模式(apps 键)+# =====================================================================+++async def test_channel_feishu_set_conf_apps_mode(monkeypatch):+ """feishu.set_conf 带 apps → 写 channels.feishu.apps,返回归一化配置。"""+ channel = FakeWebChannel()+ cm = FakeChannelManager()+ recorded_subsection: list[tuple] = []++ monkeypatch.setattr(+ "jiuwenswarm.gateway.channel_manager.web.app_web_handlers.replace_channel_subsection_with_cleanup",+ lambda cid, sub, conf, keep_keys: recorded_subsection.append((cid, sub, conf, keep_keys)),+ )++ _register_web_handlers(WebHandlersBindParams(channel=channel, channel_manager=cm))++ apps_payload = [+ {"name": "应用A", "is_default": True, "app_id": "cli_a",+ "app_secret": "sec_a", "encrypt_key": "key_a", "verification_token": "token_a"},+ {"name": "应用B", "is_default": False, "app_id": "cli_b",+ "app_secret": "sec_b", "encrypt_key": "key_b", "verification_token": "token_b"},+ ]+ await channel.methods["channel.feishu.set_conf"](+ object(), "req-apps", {"apps": apps_payload}, "sess-1"+ )++ # 验证写入了归一化后的 subsection(默认字段已填充)+ assert len(recorded_subsection) == 1+ assert recorded_subsection[0][0] == "feishu"+ assert recorded_subsection[0][1] == "apps"+ written_apps = recorded_subsection[0][2]+ assert len(written_apps) == 2+ assert written_apps[0]["name"] == "应用A"+ assert written_apps[0]["app_id"] == "cli_a"+ assert written_apps[0]["enabled"] is True # 默认值已补充+ assert written_apps[0]["allow_from"] == ["0.0.0.0/0"] # 默认值已补充+ assert written_apps[1]["name"] == "应用B"++ # 验证 cm 中存储了归一化后的 apps+ assert "apps" in cm.configs.get("feishu", {})+ cm_apps = cm.configs["feishu"]["apps"]+ assert len(cm_apps) == 2++ # 验证响应包含归一化后的完整配置+ assert channel.responses[-1]["ok"] is True+ config = channel.responses[-1]["payload"]["config"]+ assert len(config["apps"]) == 2+ # 缺省字段已被填充+ assert config["apps"][0]["allow_from"] == ["0.0.0.0/0"]+ assert config["apps"][0]["enable_streaming"] is True+++async def test_channel_xiaoyi_set_conf_apps_mode(monkeypatch):+ """xiaoyi.set_conf 带 apps → 写 channels.xiaoyi.apps,返回归一化配置。"""+ channel = FakeWebChannel()+ cm = FakeChannelManager()+ recorded_subsection: list[tuple] = []++ monkeypatch.setattr(+ "jiuwenswarm.gateway.channel_manager.web.app_web_handlers.replace_channel_subsection_with_cleanup",+ lambda cid, sub, conf, keep_keys: recorded_subsection.append((cid, sub, conf, keep_keys)),+ )+ monkeypatch.setattr(+ "jiuwenswarm.gateway.channel_manager.web.app_web_handlers._clear_agent_config_cache",+ lambda *a, **kw: None,+ )++ _register_web_handlers(WebHandlersBindParams(channel=channel, channel_manager=cm))++ apps_payload = [+ {"name": "默认应用", "is_default": True, "ak": "ak_1", "sk": "sk_1",+ "app_id": "app_1", "agent_id": "agent_1"},+ ]+ await channel.methods["channel.xiaoyi.set_conf"](+ object(), "req-apps", {"apps": apps_payload}, "sess-1"+ )++ assert len(recorded_subsection) == 1+ assert recorded_subsection[0][0] == "xiaoyi"+ assert recorded_subsection[0][1] == "apps"+ # 验证持久化的数据已归一化(默认字段被填充)+ written_apps = recorded_subsection[0][2]+ assert len(written_apps) == 1+ assert written_apps[0]["name"] == "默认应用"+ assert written_apps[0]["ak"] == "ak_1"+ assert written_apps[0]["mode"] == "xiaoyi_channel" # 默认值已补充+ assert written_apps[0]["phone_tools_enabled"] is False # 默认值已补充+ assert written_apps[0]["ws_url1"] == "wss://hag.cloud.huawei.com/openclaw/v1/ws/link" # 默认值已补充+ assert written_apps[0]["enable_streaming"] is True # 默认值已补充++ assert channel.responses[-1]["ok"] is True+ config = channel.responses[-1]["payload"]["config"]+ assert len(config["apps"]) == 1+ # 缺省字段被填充+ assert config["apps"][0]["mode"] == "xiaoyi_channel"+ assert config["apps"][0]["phone_tools_enabled"] is False++# =====================================================================+# set_conf 处理程序 — 边界场景+# =====================================================================+++async def test_channel_feishu_set_conf_apps_empty_list(monkeypatch):+ """空 apps 列表 → 保存并返回空列表。"""+ channel = FakeWebChannel()+ cm = FakeChannelManager()+ recorded_subsection: list[tuple] = []++ monkeypatch.setattr(+ "jiuwenswarm.gateway.channel_manager.web.app_web_handlers.replace_channel_subsection_with_cleanup",+ lambda cid, sub, conf, keep_keys: recorded_subsection.append((cid, sub, conf, keep_keys)),+ )++ _register_web_handlers(WebHandlersBindParams(channel=channel, channel_manager=cm))++ await channel.methods["channel.feishu.set_conf"](+ object(), "req-empty", {"apps": []}, "sess-1"+ )++ assert recorded_subsection[0][2] == []+ assert channel.responses[-1]["ok"] is True+ assert channel.responses[-1]["payload"]["config"]["apps"] == []+++async def test_channel_set_conf_channel_manager_unavailable(monkeypatch):+ """cm 为 None → 返回 SERVICE_UNAVAILABLE。"""+ channel = FakeWebChannel()+ # 不传 channel_manager,_resolve 返回 None+ _register_web_handlers(WebHandlersBindParams(channel=channel))++ await channel.methods["channel.feishu.set_conf"](object(), "req-1", {"apps": []}, "sess-1")+ assert channel.responses[-1]["ok"] is False+ assert channel.responses[-1]["code"] == "SERVICE_UNAVAILABLE"+++async def test_channel_set_conf_invalid_params():+ """params 非 dict → 返回 BAD_REQUEST。"""+ channel = FakeWebChannel()+ _register_web_handlers(WebHandlersBindParams(channel=channel, channel_manager=FakeChannelManager()))++ for invalid in [None, "string", 123, []]:+ channel.responses.clear()+ await channel.methods["channel.feishu.set_conf"](object(), "req-1", invalid, "sess-1")+ assert channel.responses[-1]["ok"] is False+ assert channel.responses[-1]["code"] == "BAD_REQUEST"+++# =====================================================================+# 落盘测试 — 验证 update_channel_subsection_in_config 真实写回文件+# =====================================================================+++def test_update_channel_subsection_in_config_persists_to_disk(tmp_path, monkeypatch):+ """验证 update_channel_subsection_in_config 确实将数据写到 config.yaml 文件。"""+ import yaml+ from jiuwenswarm.common import config as cfg++ # 1. 准备一个临时的 config.yaml,包含已有内容+ temp_config = tmp_path / "config.yaml"+ initial_data = {+ "app_version": "1.0.0",+ "channels": {+ "web": {"enabled": True},+ },+ }+ with open(temp_config, "w", encoding="utf-8") as f:+ yaml.dump(initial_data, f)++ # 2. monkeypatch CONFIG_YAML_PATH 指向临时文件+ monkeypatch.setattr(cfg, "CONFIG_YAML_PATH", temp_config)++ # 3. 调用被测试函数——写入 feishu apps 配置+ feishu_apps = [+ {"name": "应用A", "is_default": True, "app_id": "cli_a", "app_secret": "sec_a"},+ {"name": "应用B", "is_default": False, "app_id": "cli_b", "app_secret": "sec_b"},+ ]+ cfg.update_channel_subsection_in_config("feishu", "apps", feishu_apps)++ # 4. 读回文件,验证数据已落盘+ with open(temp_config, "r", encoding="utf-8") as f:+ saved = yaml.safe_load(f)++ # 4a. 验证 channels.feishu.apps 存在且内容正确+ assert "channels" in saved+ assert "feishu" in saved["channels"]+ assert "apps" in saved["channels"]["feishu"]+ assert len(saved["channels"]["feishu"]["apps"]) == 2+ assert saved["channels"]["feishu"]["apps"][0]["name"] == "应用A"+ assert saved["channels"]["feishu"]["apps"][0]["app_id"] == "cli_a"+ assert saved["channels"]["feishu"]["apps"][1]["name"] == "应用B"++ # 4b. 验证已有内容未被破坏(round-trip 安全)+ assert saved["app_version"] == "1.0.0"+ assert saved["channels"]["web"]["enabled"] is True+++def test_update_channel_subsection_in_config_creates_missing_sections(tmp_path, monkeypatch):+ """当 channels / channel_id / subsection 不存在时,应自动创建。"""+ import yaml+ from jiuwenswarm.common import config as cfg++ temp_config = tmp_path / "config.yaml"+ # 只有顶层字段,没有任何 channels+ with open(temp_config, "w", encoding="utf-8") as f:+ yaml.dump({"app_version": "2.0.0"}, f)++ monkeypatch.setattr(cfg, "CONFIG_YAML_PATH", temp_config)++ cfg.update_channel_subsection_in_config("xiaoyi", "apps", [{"name": "默认应用", "ak": "ak_1"}])++ with open(temp_config, "r", encoding="utf-8") as f:+ saved = yaml.safe_load(f)++ assert "channels" in saved+ assert "xiaoyi" in saved["channels"]+ assert "apps" in saved["channels"]["xiaoyi"]+ assert saved["channels"]["xiaoyi"]["apps"][0]["name"] == "默认应用"+ # 原始顶层字段保留+ assert saved["app_version"] == "2.0.0"+++def test_update_channel_subsection_in_config_overwrites_existing(tmp_path, monkeypatch):+ """相同 subsection 多次写入应覆盖而不是追加。"""+ import yaml+ from jiuwenswarm.common import config as cfg++ temp_config = tmp_path / "config.yaml"+ initial_data = {+ "channels": {+ "feishu": {+ "apps": [{"name": "旧应用", "app_id": "old_id"}],+ },+ },+ }+ with open(temp_config, "w", encoding="utf-8") as f:+ yaml.dump(initial_data, f)++ monkeypatch.setattr(cfg, "CONFIG_YAML_PATH", temp_config)++ # 写入新数据覆盖+ new_apps = [{"name": "新应用", "app_id": "new_id"}]+ cfg.update_channel_subsection_in_config("feishu", "apps", new_apps)++ with open(temp_config, "r", encoding="utf-8") as f:+ saved = yaml.safe_load(f)++ assert len(saved["channels"]["feishu"]["apps"]) == 1+ assert saved["channels"]["feishu"]["apps"][0]["name"] == "新应用"+ assert saved["channels"]["feishu"]["apps"][0]["app_id"] == "new_id"