Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix(cron): 修复飞书,web侧定时任务推送异常

openJiuwen-bot032f808a5c3f
diff --git a/jiuwenswarm/agents/harness/common/tools/cron/cron_runtime.py b/jiuwenswarm/agents/harness/common/tools/cron/cron_runtime.py
index 029ec24594..bec747b9af 100644
--- a/jiuwenswarm/agents/harness/common/tools/cron/cron_runtime.py
+++ b/jiuwenswarm/agents/harness/common/tools/cron/cron_runtime.py
@@ -40,11 +40,13 @@ class _CronToolsCronBackend(CronToolBackend):
else None
)
chat_type = str(metadata.get("chat_type") or "").strip() or None
+ app_id = str(metadata.get("app_id") or "").strip()
return CronToolRoute(
request_id=request_id,
channel_id=channel_id,
session_id=session_id,
chat_type=chat_type,
+ app_id=app_id,
)
async def list_jobs(self, *, include_disabled: bool = True) -> list[dict[str, Any]]:
@@ -319,6 +321,12 @@ def _extract_legacy_params(
out["session_id"],
)
+ # 飞书多应用:传递 app_id,用于调度器定位正确的 app 配置
+ context_metadata = getattr(context, "metadata", None) or {}
+ context_app_id = str(context_metadata.get("app_id") or "").strip() if isinstance(context_metadata, dict) else ""
+ if context_app_id:
+ out["app_id"] = context_app_id
+
context_mode = getattr(context, "mode", None)
mode_resolved = context_mode or data.get("mode") or CRON_JOB_DEFAULT_MODE
out["mode"] = coerce_cron_job_mode(mode_resolved, default=CRON_JOB_DEFAULT_MODE)
diff --git a/jiuwenswarm/agents/harness/common/tools/cron/cron_tools.py b/jiuwenswarm/agents/harness/common/tools/cron/cron_tools.py
index ae6d5fcd2f..7719cda4a6 100644
--- a/jiuwenswarm/agents/harness/common/tools/cron/cron_tools.py
+++ b/jiuwenswarm/agents/harness/common/tools/cron/cron_tools.py
@@ -35,12 +35,13 @@ _cron_route_ctx: contextvars.ContextVar[CronToolRoute | None] = contextvars.Cont
@dataclass(frozen=True, slots=True)
class CronToolRoute:
- """当前请求同步到 Gateway 时使用的路由(request_id / channel / session / chat_type)。"""
+ """当前请求同步到 Gateway 时使用的路由(request_id / channel / session / chat_type / app_id)。"""
request_id: str = ""
channel_id: str = CronTargetChannel.WEB.value
session_id: str | None = None
chat_type: str | None = None # "group" 表示群聊, "p2p" 或 None 表示私聊
+ app_id: str = ""
class CronTools:
@@ -251,12 +252,16 @@ class CronTools:
targets_str,
)
session_kw: dict[str, Any] = {}
- sid = self._route().session_id
+ r = self._route()
+ sid = r.session_id
if isinstance(sid, str) and sid.strip():
session_kw["session_id"] = sid.strip()
- chat_type = self._route().chat_type
+ chat_type = r.chat_type
if chat_type:
session_kw["chat_type"] = chat_type
+ app_id = str(getattr(r, "app_id", None) or "").strip()
+ if app_id:
+ session_kw["app_id"] = app_id
mode_kw: dict[str, Any] = {}
mode_raw = normalized.get("mode")
if mode_raw is not None and str(mode_raw).strip():
diff --git a/jiuwenswarm/common/e2a/models.py b/jiuwenswarm/common/e2a/models.py
index d4a3bf7ff6..ba2e5b66cd 100644
--- a/jiuwenswarm/common/e2a/models.py
+++ b/jiuwenswarm/common/e2a/models.py
@@ -352,7 +352,7 @@ def _envelope_from_dict(data: dict[str, Any]) -> E2AEnvelope:
_meta=dict(auth_raw.get("_meta") or {}),
)
- # channel_context:合并 wire 顶层 metadata 中尚未出现的键。
+ # channel_context:合并 wire 顶层 metadata + app_id 中尚未出现的键。
channel_context = dict(data.get("channel_context") or {})
meta_top = data.get("metadata")
if isinstance(meta_top, dict) and meta_top:
@@ -361,6 +361,9 @@ def _envelope_from_dict(data: dict[str, Any]) -> E2AEnvelope:
continue
if k not in channel_context:
channel_context[k] = v
+ app_id = data.get("app_id")
+ if app_id and "app_id" not in channel_context:
+ channel_context["app_id"] = app_id
ch = data.get("channel")
if ch is None:
diff --git a/jiuwenswarm/gateway/cron/controller.py b/jiuwenswarm/gateway/cron/controller.py
index 0141fcfe43..240f6f673f 100644
--- a/jiuwenswarm/gateway/cron/controller.py
+++ b/jiuwenswarm/gateway/cron/controller.py
@@ -153,6 +153,7 @@ class CronController:
chat_type = params.get("chat_type")
delete_after_run = params.get("delete_after_run")
timeout_seconds = params.get("timeout_seconds")
+ app_id = str(params.get("app_id") or "").strip()
job = await self._store.create_job(
job_id=str(params.get("id") or "").strip() or None,
name=name,
@@ -167,6 +168,7 @@ class CronController:
mode=mode,
delete_after_run=delete_after_run,
timeout_seconds=timeout_seconds,
+ app_id=app_id,
)
await self._scheduler.reload()
return job.to_dict()
diff --git a/jiuwenswarm/gateway/cron/models.py b/jiuwenswarm/gateway/cron/models.py
index ade4578999..8cae43a780 100644
--- a/jiuwenswarm/gateway/cron/models.py
+++ b/jiuwenswarm/gateway/cron/models.py
@@ -216,6 +216,8 @@ class CronJob:
delete_after_run: bool = False
# 单次执行超时(秒);未配置时普通模式 10 分钟,team 模式 20 分钟
timeout_seconds: int | None = None
+ # 飞书多应用场景:创建该定时任务的 app_id,用于推送时定位到正确的 app 配置
+ app_id: str = ""
def to_dict(self) -> dict[str, Any]:
d: dict[str, Any] = {
@@ -241,6 +243,8 @@ class CronJob:
d["delete_after_run"] = bool(self.delete_after_run)
if self.timeout_seconds is not None:
d["timeout_seconds"] = int(self.timeout_seconds)
+ if self.app_id:
+ d["app_id"] = self.app_id
return d
@staticmethod
@@ -320,6 +324,9 @@ class CronJob:
if timeout_seconds_raw is not None:
timeout_seconds = normalize_cron_job_timeout_seconds(timeout_seconds_raw)
+ app_id_raw = data.get("app_id", "")
+ job_app_id = str(app_id_raw).strip() if isinstance(app_id_raw, str) else ""
+
return CronJob(
id=job_id,
name=name,
@@ -337,6 +344,7 @@ class CronJob:
mode=job_mode,
delete_after_run=delete_after_run,
timeout_seconds=timeout_seconds,
+ app_id=job_app_id,
)
diff --git a/jiuwenswarm/gateway/cron/scheduler.py b/jiuwenswarm/gateway/cron/scheduler.py
index 23676b967b..778a06c0ae 100644
--- a/jiuwenswarm/gateway/cron/scheduler.py
+++ b/jiuwenswarm/gateway/cron/scheduler.py
@@ -1103,11 +1103,12 @@ class CronSchedulerService:
# 企业飞书:优先用作业里绑定的 SessionMap session_id(feishu::chat_id::bot_id::...),
# 避免多群共用 bot 时误用 config 中的 last_*(最近一条消息的会话)。
- # Web/TUI:不绑定 session_id,否则新会话或重启后 session_id 与旧不同,消息会被前端过滤。
+ # TUI:不绑定 session_id,否则 TUI 重启后新 session_id 与旧不同,消息会被前端过滤。
+ # Web:绑定 session_id,只投递到创建定时任务的会话,避免多窗口干扰。
metadata: dict | None = None
msg_session_id: str | None = None
routing_sid = str(getattr(job, "session_id", None) or "").strip()
- if routing_sid and channel_id not in ("web", "tui"):
+ if routing_sid and channel_id != "tui":
msg_session_id = routing_sid
if channel_id.startswith("feishu_enterprise:") and routing_sid and "::" in routing_sid:
parts = routing_sid.split("::")
@@ -1134,9 +1135,10 @@ class CronSchedulerService:
ch_cfg = channels_cfg.get(channel_id) or {}
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()
+ target_app_id = str(getattr(job, "app_id", None) or "").strip()
+ if not 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:
@@ -1295,6 +1297,7 @@ class CronSchedulerService:
job.chat_type, channel_id, job.id,
)
+ _msg_app_id = str(getattr(job, "app_id", None) or "").strip() or None
msg = Message(
id=f"cron-push-{state.run_id}-{channel_id}",
type="event",
@@ -1307,5 +1310,6 @@ class CronSchedulerService:
event_type=EventType.CHAT_FINAL,
metadata=metadata,
group_digital_avatar=_group_digital_avatar,
+ app_id=_msg_app_id,
)
await self._message_handler.publish_robot_messages(msg)
diff --git a/jiuwenswarm/gateway/cron/store.py b/jiuwenswarm/gateway/cron/store.py
index cd38c3044b..91e0fbb3f1 100644
--- a/jiuwenswarm/gateway/cron/store.py
+++ b/jiuwenswarm/gateway/cron/store.py
@@ -71,6 +71,7 @@ class CronJobStore:
mode: str | None = None,
delete_after_run: bool | None = None,
timeout_seconds: int | None = None,
+ app_id: str = "",
) -> CronJob:
now = time.time()
sid = str(session_id).strip() if isinstance(session_id, str) and session_id.strip() else None
@@ -98,6 +99,7 @@ class CronJobStore:
mode=m,
delete_after_run=dar,
timeout_seconds=timeout,
+ app_id=str(app_id or "").strip(),
)
# validate via round-trip
CronJob.from_dict(job.to_dict())
diff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.py
index 7237a48042..4188b4fded 100644
--- a/jiuwenswarm/server/agent_ws_server.py
+++ b/jiuwenswarm/server/agent_ws_server.py
@@ -707,6 +707,13 @@ def _payload_to_request(data: dict[str, Any]) -> AgentRequest:
if key not in E2A_WIRE_INTERNAL_METADATA_KEYS
} or None
+ # 将 app_id 注入 metadata,供 cron 路由等下游使用
+ app_id = data.get("app_id")
+ if app_id:
+ if metadata is None:
+ metadata = {}
+ metadata.setdefault("app_id", app_id)
+
return AgentRequest(
request_id=data["request_id"],
channel_id=data.get("channel_id", "web"),