JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(cron/feishu): 修复飞书/web/tui 多应用场景下心跳/定时任务异常
openJiuwen-bot3f8387d5abe4
diff --git a/jiuwenswarm/gateway/channel_manager/channel_manager.py b/jiuwenswarm/gateway/channel_manager/channel_manager.pyindex f726f002f7..b663cec234 100644--- a/jiuwenswarm/gateway/channel_manager/channel_manager.py+++ b/jiuwenswarm/gateway/channel_manager/channel_manager.py@@ -4,6 +4,7 @@from __future__ import annotations+import dataclassesimport loggingimport asyncioimport time@@ -155,6 +156,14 @@ class ChannelManager(ABC):out.append(ch)return out+ def get_channels_by_id(self, channel_id: str) -> list["BaseChannel"]:+ """返回所有匹配 channel_id 的 Channel 实例(只读,不删除)。++ 多应用场景下同一 channel_id(如 "feishu")对应多个 app 实例,+ _get_channel_by_id 只返回第一个,此方法返回全部,供 fan-out 使用。+ """+ return [ch for k, ch in self._channels.items() if k.channel_id == channel_id]+@propertydef enabled_channels(self) -> list[str]:"""当前已注册的 Channel 标识(channel_id 字符串)列表."""@@ -268,6 +277,55 @@ class ChannelManager(ABC):)continue+ # ── 飞书 cron 推送 / 心跳 relay fan-out:同 channel_id 全部 app 各自投递(各用各的 last_*)。+ # 仅普通飞书(channel_id == "feishu"):多 app 共享同一 channel_id,精确路由只到创建 app+ # (cron-push 的 app_id)或第一个实例(心跳 relay 无 app_id → resolve_app_id='default'),+ # 其余 app 收不到。fan-out 前清掉 metadata 里创建 app 的 feishu_chat_id,使各 app 走+ # _extract_receive_info 回退链第 3 档(各 app 自己的 last_*)。+ # ── 企业飞书(feishu_enterprise:<app_id>)不进此分支:一 channel_id 一 bot 无需 fan-out,+ # 且其 cron 推送的 feishu_chat_id 是创建任务时绑定的特定群(来自 routing_sid 的+ # feishu::chat_id::bot_id::...,见 scheduler._push_to_targets),清掉会误投到 last_* 的群。+ from jiuwenswarm.common.schema.message import EventType as _EventType+ _is_feishu_fanout = (+ isinstance(msg.channel_id, str)+ and msg.channel_id == "feishu"+ and (+ (getattr(msg, "id", "") or "").startswith("cron-push-")+ or getattr(msg, "event_type", None) == _EventType.HEARTBEAT_RELAY+ )+ )+ if _is_feishu_fanout:+ targets = self.get_channels_by_id(msg.channel_id)+ if not targets:+ logger.warning(+ "[ChannelManager] 飞书 fan-out: 无 channel channel_id=%s id=%s",+ msg.channel_id, getattr(msg, "id", ""),+ )+ continue+ # 清掉创建 app 的平台身份,让每个 app 各走自己的 last_*+ fanout_meta = dict(getattr(msg, "metadata", None) or {})+ for _k in (+ "feishu_chat_id", "feishu_open_id",+ "reply_candidate_feishu_open_id", "reply_feishu_open_id",+ "reply_candidate_reason", "reply_target_name",+ ):+ fanout_meta.pop(_k, None)+ fanout_msg = dataclasses.replace(msg, metadata=fanout_meta)+ logger.info(+ "[ChannelManager] 飞书 fan-out: channel_id=%s targets=%d id=%s",+ msg.channel_id, len(targets), getattr(msg, "id", ""),+ )+ for ch in targets:+ try:+ await ch.send(fanout_msg)+ except Exception as e:+ logger.error(+ "[ChannelManager] 飞书 fan-out 投递失败: channel_id=%s app=%s id=%s: %s",+ msg.channel_id, getattr(ch, "app_id", "?"),+ getattr(msg, "id", ""), e, exc_info=True,+ )+ continue+# ── 兜底:旧单 channel 投递(非 team 模式)──# V2: 优先按 ChannelKey 精确路由(多应用场景下同一 channel_id 对应多个 app)channel = Nonediff --git a/jiuwenswarm/gateway/channel_manager/tui/tui_channel.py b/jiuwenswarm/gateway/channel_manager/tui/tui_channel.pyindex 68b2f6241c..2bbc8fd1ca 100644--- a/jiuwenswarm/gateway/channel_manager/tui/tui_channel.py+++ b/jiuwenswarm/gateway/channel_manager/tui/tui_channel.py@@ -19,6 +19,7 @@ import loggingfrom dataclasses import dataclassfrom typing import Any, Callable+from jiuwenswarm.common.schema.message import EventTypefrom jiuwenswarm.gateway.channel_manager.base import RobotMessageRouterfrom jiuwenswarm.gateway.routing.base_ws_channel import BaseWsChannelfrom jiuwenswarm.gateway.routing.session_sharing import RoutingTarget@@ -81,7 +82,37 @@ class TuiChannel(BaseWsChannel):miss 再按 routing_keys 五维精确查 _clients_by_key。非团队模式(routing_target 为空):扫 _clients_by_key 按 session_id 命中(对齐 WebChannel,不再广播,避免串窗)。++ 例外:定时任务推送(CHAT_FINAL + payload.cron)。scheduler 对 tui 置空+ session_id(避免 TUI 重启后旧 session_id 与新不同被前端过滤),但下方非团队+ 路径要求 session_id 才能精确匹配,会导致 cron 推送被直接丢弃。仿 WebChannel+ 的 cron 广播分支,对此类消息广播给所有 tui 客户端——多开终端都会收到结果,+ 前端按当前活跃会话展示。"""+ # ── 定时任务推 tui:scheduler 对 tui 置空 msg.session_id(见 scheduler+ # _push_to_targets 的 routing_sid 注释),按 session_id 路由会被丢弃。+ # cron 推送(占位 + 结果)带 payload.cron 标记,普通对话 chat.final 不带,+ # 以此为识别条件广播给所有 tui 客户端,与 WebChannel.send 对称。+ if (+ getattr(msg, "event_type", None) == EventType.CHAT_FINAL+ and isinstance(getattr(msg, "payload", None), dict)+ and isinstance(msg.payload.get("cron"), dict)+ ):+ frame = self._serialize_frame(msg, None)+ clients: set[Any] = set()+ for ws_list in self._clients_by_key.values():+ for w in ws_list:+ if not getattr(w, "closed", False):+ clients.add(w)+ for w in clients:+ self._enqueue_send(w, frame)+ logger.debug(+ "[TuiChannel] cron push broadcast to %d client(s) id=%s run_id=%s",+ len(clients), getattr(msg, "id", ""),+ (msg.payload.get("cron") or {}).get("run_id", ""),+ )+ return+ws_set: set[Any] = set()if routing_target is not None:diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.pyindex bdace9b8ee..c32a4f4d60 100644--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py@@ -2164,10 +2164,25 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:try:raw = get_config_raw() or {}ch_cfg = (raw.get("channels") or {}).get("feishu") or {}- has_target = bool(- str(ch_cfg.get("last_chat_id") or "").strip()- or str(ch_cfg.get("chat_id") or "").strip()- )+ # V2 多应用:心跳 relay 会 fan-out 到同 channel_id 的全部 app,每个 app 各走+ # 自己的 last_chat_id/chat_id 投递;故要求「每个 app 都有目标」才算可用,+ # 否则缺失目标的 app 每次 tick 都会静默投递失败。+ apps = ch_cfg.get("apps") or []+ if isinstance(apps, list) and apps:+ has_target = all(+ isinstance(app, dict)+ and (+ bool(str(app.get("last_chat_id") or "").strip())+ or bool(str(app.get("chat_id") or "").strip())+ )+ for app in apps+ )+ else:+ # 旧平铺格式(单应用):兜底看顶层 last_chat_id/chat_id。+ has_target = bool(+ str(ch_cfg.get("last_chat_id") or "").strip()+ or str(ch_cfg.get("chat_id") or "").strip()+ )if not has_target:await channel.send_response(ws, req_id, ok=False,diff --git a/jiuwenswarm/gateway/channel_manager/web/web_connect.py b/jiuwenswarm/gateway/channel_manager/web/web_connect.pyindex 5e3a977b03..6b0a356ab5 100644--- a/jiuwenswarm/gateway/channel_manager/web/web_connect.py+++ b/jiuwenswarm/gateway/channel_manager/web/web_connect.py@@ -34,7 +34,7 @@ from jiuwenswarm.common.security.ws_origin import (is_origin_check_enabled,is_allowed_browser_origin,)-from jiuwenswarm.common.schema.message import Message, Mode, ReqMethod+from jiuwenswarm.common.schema.message import EventType, Message, Mode, ReqMethodfrom jiuwenswarm.common.ws_diagnostics import (describe_ws_exception,describe_ws_peer,@@ -443,6 +443,41 @@ class WebChannel(BaseWsChannel):getattr(msg, "id", ""), getattr(msg, "event_type", None), _et,_has_fanout, routing_target is not None, len(self.clients),)+ # ── 心跳 relay:临时 session_id(heartbeat_{ts}_{suffix})不匹配任何前端连接,+ # 按常规 session_id 路由会被当作"无连接"丢弃。心跳状态是全局的(非会话级),+ # 前端 setHeartbeatStatus 也是全局 store,因此直接广播给所有 web 客户端。+ # 与 wechat 等 IM 渠道在 send() 中对 HEARTBEAT_RELAY 的专属分支对齐。+ if msg.event_type == EventType.HEARTBEAT_RELAY:+ frame = self._serialize_frame(msg, None) # 已是 json 字符串+ clients = self.clients+ for w in clients:+ self._enqueue_send(w, frame)+ logger.debug(+ "[WebChannel] heartbeat.relay broadcast to %d client(s) id=%s",+ len(clients), getattr(msg, "id", ""),+ )+ return++ # ── 定时任务推 web:原设计绑定 job.session_id,但关闭 tab/换设备后旧会话再无连接,+ # 按 session_id 路由会被丢弃。cron 推送(占位 + 结果)带 payload.cron 标记,普通对话+ # chat.final 不带,以此为识别条件广播给所有 web 客户端。前端 _push_to_targets 已对 web+ # 置空 session_id,shouldHandleSessionEvent 放行,消息进当前活跃会话流(含 placeholder 替换)。+ if (+ msg.event_type == EventType.CHAT_FINAL+ and isinstance(msg.payload, dict)+ and isinstance(msg.payload.get("cron"), dict)+ ):+ frame = self._serialize_frame(msg, None) # 已是 json 字符串+ clients = self.clients+ for w in clients:+ self._enqueue_send(w, frame)+ logger.debug(+ "[WebChannel] cron push broadcast to %d client(s) id=%s run_id=%s",+ len(clients), getattr(msg, "id", ""),+ (msg.payload.get("cron") or {}).get("run_id", ""),+ )+ return+if msg.type == "res":if isinstance(msg.payload, dict):res_payload = {**msg.payload}diff --git a/jiuwenswarm/gateway/cron/scheduler.py b/jiuwenswarm/gateway/cron/scheduler.pyindex a5429a289f..acd06e18cd 100644--- a/jiuwenswarm/gateway/cron/scheduler.py+++ b/jiuwenswarm/gateway/cron/scheduler.py@@ -1117,11 +1117,13 @@ class CronSchedulerService:# 企业飞书:优先用作业里绑定的 SessionMap session_id(feishu::chat_id::bot_id::...),# 避免多群共用 bot 时误用 config 中的 last_*(最近一条消息的会话)。# TUI:不绑定 session_id,否则 TUI 重启后新 session_id 与旧不同,消息会被前端过滤。- # Web:绑定 session_id,只投递到创建定时任务的会话,避免多窗口干扰。+ # Web:不绑定 session_id——WebChannel.send 对带 payload.cron 的推送会广播给所有 web 客户端,+ # 绑定旧 session_id 反而会让前端 shouldHandleSessionEvent 因 session 不匹配而丢弃。+ # 关闭 tab/换设备后旧会话再无连接,置空 session_id 让消息进当前活跃会话流。metadata: dict | None = Nonemsg_session_id: str | None = Nonerouting_sid = str(getattr(job, "session_id", None) or "").strip()- if routing_sid and channel_id != "tui":+ if routing_sid and channel_id != "tui" and channel_id != "web":msg_session_id = routing_sidif channel_id.startswith("feishu_enterprise:") and routing_sid and "::" in routing_sid:parts = routing_sid.split("::")