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 工具带上当前身份读写任务库
liutaod5ab33fafa01
diff --git a/jiuwenswarm/agents/harness/common/tools/cron/cron_runtime.py b/jiuwenswarm/agents/harness/common/tools/cron/cron_runtime.pyindex f9cb06eab5..c780778653 100644--- a/jiuwenswarm/agents/harness/common/tools/cron/cron_runtime.py+++ b/jiuwenswarm/agents/harness/common/tools/cron/cron_runtime.py@@ -2,8 +2,10 @@ from __future__ import annotationsimport asyncioimport time+from collections.abc import Awaitable, Callablefrom copy import deepcopy-from typing import Any, Optional+from types import SimpleNamespace+from typing import Any, Optional, TypeVarfrom openjiuwen.harness.tools.cron import CronToolBackend, CronToolContext, create_cron_tools@@ -24,6 +26,35 @@ from jiuwenswarm.common.schema.message import Message, ReqMethodfrom jiuwenswarm.common.utils import loggerfrom jiuwenswarm.server.runtime.tenant_agent_pool import TenantAgentPool+_T = TypeVar("_T")+++def _bound_request_context() -> Any | None:+ """Use the live request ContextVar binding when DeepAgent omits ``context``.++ Only the current bound invocation is trusted. Unbound leftover ContextVars+ are ignored; session adapters inject the same-request proxy instead.+ """+ try:+ from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (+ _CRON_TOOL_BOUND,+ _CRON_TOOL_MODE,+ get_runtime_tool_channel_id,+ get_runtime_tool_metadata,+ get_runtime_tool_session_id,+ )+ except Exception:+ return None+ if not _CRON_TOOL_BOUND.get():+ return None+ metadata = get_runtime_tool_metadata()+ return SimpleNamespace(+ channel_id=get_runtime_tool_channel_id(),+ session_id=get_runtime_tool_session_id(),+ metadata=dict(metadata) if isinstance(metadata, dict) else metadata,+ mode=_CRON_TOOL_MODE.get(),+ )+def _normalize_tenant_scope(service_id: str | None,@@ -88,7 +119,7 @@ class _CronToolsCronBackend(CronToolBackend):app_id = str(metadata.get("app_id") or "").strip()from jiuwenswarm.gateway.cron.enterprise_gate import extract_routing_triple- group_id, bot_id, user_id = extract_routing_triple(metadata, context)+ group_id, bot_id, user_id = extract_routing_triple(metadata)return CronToolRoute(request_id=request_id,channel_id=channel_id,@@ -103,18 +134,59 @@ class _CronToolsCronBackend(CronToolBackend):user_id=user_id,)- async def list_jobs(self, *, include_disabled: bool = True) -> list[dict[str, Any]]:- jobs = await self._cron_tools.list_jobs()- rows = [self._to_backend_job(job) for job in jobs]- if include_disabled:- return rows- return [job for job in rows if job.get("enabled", True)]+ def _assert_enterprise_route(self, route: CronToolRoute) -> None:+ ready_fn = getattr(self._cron_tools, "_enterprise_ready", None)+ if not callable(ready_fn) or not ready_fn():+ return+ from jiuwenswarm.gateway.cron.enterprise_gate import routing_triple_complete++ if not str(route.session_id or "").strip() or not routing_triple_complete(+ route.group_id, route.bot_id, route.user_id+ ):+ raise ValueError("enterprise cron requires an authenticated session")- async def get_job(self, job_id: str) -> dict[str, Any] | None:- job = await self._cron_tools.get_job(job_id)- if job is None:- return None- return self._to_backend_job(job)+ async def _with_route(+ self,+ context: CronToolContext | None,+ op: Callable[[], Awaitable[_T]],+ ) -> _T:+ effective = context if context is not None else _bound_request_context()+ route = self._route_from_context(effective)+ self._assert_enterprise_route(route)+ token = self._cron_tools.push_cron_route(route)+ try:+ return await op()+ finally:+ self._cron_tools.reset_cron_route(token)++ async def list_jobs(+ self,+ *,+ include_disabled: bool = True,+ context: CronToolContext | None = None,+ ) -> list[dict[str, Any]]:+ async def _run() -> list[dict[str, Any]]:+ jobs = await self._cron_tools.list_jobs()+ rows = [self._to_backend_job(job) for job in jobs]+ if include_disabled:+ return rows+ return [job for job in rows if job.get("enabled", True)]++ return await self._with_route(context, _run)++ async def get_job(+ self,+ job_id: str,+ *,+ context: CronToolContext | None = None,+ ) -> dict[str, Any] | None:+ async def _run() -> dict[str, Any] | None:+ job = await self._cron_tools.get_job(job_id)+ if job is None:+ return None+ return self._to_backend_job(job)++ return await self._with_route(context, _run)async def create_job(self,@@ -142,12 +214,12 @@ class _CronToolsCronBackend(CronToolBackend):payload.get("id"),payload.get("name"),)- token = self._cron_tools.push_cron_route(self._route_from_context(context))- try:++ async def _run() -> dict[str, Any]:job = await self._cron_tools.create_job(payload)- finally:- self._cron_tools.reset_cron_route(token)- return self._to_backend_job(job)+ return self._to_backend_job(job)++ return await self._with_route(context, _run)async def update_job(self,@@ -157,36 +229,66 @@ class _CronToolsCronBackend(CronToolBackend):context: CronToolContext | None = None,) -> dict[str, Any]:payload = _extract_legacy_params(dict(patch or {}), context=context, require_schedule=False)- token = self._cron_tools.push_cron_route(self._route_from_context(context))- try:++ async def _run() -> dict[str, Any]:job = await self._cron_tools.update_job(job_id, payload)- finally:- self._cron_tools.reset_cron_route(token)- return self._to_backend_job(job)+ return self._to_backend_job(job)- async def delete_job(self, job_id: str) -> bool:- return bool(await self._cron_tools.delete_job(job_id))+ return await self._with_route(context, _run)- async def toggle_job(self, job_id: str, enabled: bool) -> dict[str, Any]:- job = await self._cron_tools.toggle_job(job_id, enabled)- return self._to_backend_job(job)+ async def delete_job(+ self,+ job_id: str,+ *,+ context: CronToolContext | None = None,+ ) -> bool:+ async def _run() -> bool:+ return bool(await self._cron_tools.delete_job(job_id))- async def preview_job(self, job_id: str, count: int = 5) -> list[dict[str, Any]]:- rows = await self._cron_tools.preview_job(job_id, count)- return list(rows or [])+ return await self._with_route(context, _run)- async def run_now(self, job_id: str) -> str:- token = self._cron_tools.push_cron_route(CronToolRoute())- try:+ async def toggle_job(+ self,+ job_id: str,+ enabled: bool,+ *,+ context: CronToolContext | None = None,+ ) -> dict[str, Any]:+ async def _run() -> dict[str, Any]:+ job = await self._cron_tools.toggle_job(job_id, enabled)+ return self._to_backend_job(job)++ return await self._with_route(context, _run)++ async def preview_job(+ self,+ job_id: str,+ count: int = 5,+ *,+ context: CronToolContext | None = None,+ ) -> list[dict[str, Any]]:+ async def _run() -> list[dict[str, Any]]:+ rows = await self._cron_tools.preview_job(job_id, count)+ return list(rows or [])++ return await self._with_route(context, _run)++ async def run_now(+ self,+ job_id: str,+ *,+ context: CronToolContext | None = None,+ ) -> str:+ async def _run() -> str:run_result = await self._cron_tools.run_now(job_id)- finally:- self._cron_tools.reset_cron_route(token)- if isinstance(run_result, dict):- return str(run_result.get("run_id") or "")- return str(run_result or "")+ if isinstance(run_result, dict):+ return str(run_result.get("run_id") or "")+ return str(run_result or "")++ return await self._with_route(context, _run)- async def status(self) -> dict[str, Any]:- jobs = await self._cron_tools.list_jobs()+ async def status(self, *, context: CronToolContext | None = None) -> dict[str, Any]:+ jobs = await self.list_jobs(include_disabled=True, context=context)return {"running": False,"job_count": len(jobs),@@ -264,6 +366,115 @@ class _CronToolsCronBackend(CronToolBackend):return row+class _ContextInjectingCronBackend:+ """Fill omitted DeepAgent context from the session adapter proxy.++ openjiuwen ``create_cron_tools`` only forwards ``context=`` on create/update/wake.+ list/get/delete/toggle/preview/status/run call the backend without it, so+ ``_with_route`` would otherwise see an empty CronToolRoute. The adapter's+ ``_RuntimeCronToolContext`` already remembers per-request identity for+ create; wrap the shared tenant backend with that same object at tool-build+ time so invoke_tool list/get reuse it. Personal edition is unchanged: extra+ identity on the route is unused when enterprise cron is off.+ """++ def __init__(self, inner: CronToolBackend, context: Any) -> None:+ self._inner = inner+ self._context = context++ def __getattr__(self, name: str) -> Any:+ return getattr(self._inner, name)++ def _ctx(self, context: CronToolContext | None) -> Any:+ return context if context is not None else self._context++ async def list_jobs(+ self,+ *,+ include_disabled: bool = True,+ context: CronToolContext | None = None,+ ) -> list[dict[str, Any]]:+ return await self._inner.list_jobs(+ include_disabled=include_disabled,+ context=self._ctx(context),+ )++ async def get_job(+ self,+ job_id: str,+ *,+ context: CronToolContext | None = None,+ ) -> dict[str, Any] | None:+ return await self._inner.get_job(job_id, context=self._ctx(context))++ async def create_job(+ self,+ params: dict[str, Any],+ *,+ context: CronToolContext | None = None,+ ) -> dict[str, Any]:+ return await self._inner.create_job(params, context=self._ctx(context))++ async def update_job(+ self,+ job_id: str,+ patch: dict[str, Any],+ *,+ context: CronToolContext | None = None,+ ) -> dict[str, Any]:+ return await self._inner.update_job(job_id, patch, context=self._ctx(context))++ async def delete_job(+ self,+ job_id: str,+ *,+ context: CronToolContext | None = None,+ ) -> bool:+ return await self._inner.delete_job(job_id, context=self._ctx(context))++ async def toggle_job(+ self,+ job_id: str,+ enabled: bool,+ *,+ context: CronToolContext | None = None,+ ) -> dict[str, Any]:+ return await self._inner.toggle_job(+ job_id, enabled, context=self._ctx(context)+ )++ async def preview_job(+ self,+ job_id: str,+ count: int = 5,+ *,+ context: CronToolContext | None = None,+ ) -> list[dict[str, Any]]:+ return await self._inner.preview_job(+ job_id, count, context=self._ctx(context)+ )++ async def run_now(+ self,+ job_id: str,+ *,+ context: CronToolContext | None = None,+ ) -> str:+ return await self._inner.run_now(job_id, context=self._ctx(context))++ async def status(self, *, context: CronToolContext | None = None) -> dict[str, Any]:+ return await self._inner.status(context=self._ctx(context))++ async def wake(+ self,+ text: str,+ *,+ context: CronToolContext | None = None,+ mode: str | None = None,+ ) -> dict[str, Any]:+ return await self._inner.wake(text, context=self._ctx(context), mode=mode)++def _extract_legacy_params(payload: dict[str, Any],*,@@ -545,6 +756,8 @@ class CronRuntimeBridge:getattr(context, "tool_scope", "unknown"),)self.ensure_scheduler_started(service_id=sid, agent_id=aid)+ if context is not None:+ backend = _ContextInjectingCronBackend(backend, context)tools = create_cron_tools(backend,context=context,diff --git a/jiuwenswarm/agents/harness/common/tools/cron/cron_tools.py b/jiuwenswarm/agents/harness/common/tools/cron/cron_tools.pyindex df7bb506bd..a638527938 100644--- a/jiuwenswarm/agents/harness/common/tools/cron/cron_tools.py+++ b/jiuwenswarm/agents/harness/common/tools/cron/cron_tools.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport asyncioimport contextvarsimport logging+import timeimport uuidfrom dataclasses import dataclassfrom datetime import datetime, timedelta@@ -33,6 +34,9 @@ from jiuwenswarm.common.utils import (logger = logging.getLogger(__name__)+_ENTERPRISE_MUTATION_CONFIRM_SECONDS = 5.0+_ENTERPRISE_MUTATION_POLL_INTERVAL = 0.1+def resolve_cron_jobs_path(service_id: str,@@ -253,6 +257,84 @@ class CronTools:out["user_id"] = r.user_idreturn out+ def _require_enterprise_identity(self) -> dict[str, str]:+ from jiuwenswarm.gateway.cron.enterprise_gate import (+ extract_routing_triple,+ routing_triple_complete,+ )++ identity = self._routing_identity_payload()+ group_id, bot_id, user_id = extract_routing_triple(identity)+ if not routing_triple_complete(group_id, bot_id, user_id):+ raise ValueError("enterprise cron requires group_id, bot_id and user_id")+ return identity++ @staticmethod+ def _enterprise_registry():+ try:+ from jiuwenswarm.gateway.cron.tenant_registry import CronTenantRegistry++ return CronTenantRegistry.try_get_instance()+ except Exception:+ return None++ async def _dispatch_enterprise_action(+ self,+ action: str,+ params: dict[str, Any],+ ) -> Any:+ """Apply an enterprise mutation via in-process registry, else Gateway push.++ Returns the controller result when the Gateway registry is in-process.+ Returns None after a successful push; the caller must confirm via PG.+ """+ identity = self._require_enterprise_identity()+ merged = dict(params or {})+ for key in ("group_id", "bot_id", "user_id"):+ merged.pop(key, None)+ merged.update(identity)+ registry = self._enterprise_registry()+ if registry is not None:+ data = await registry.handle_push_action(+ action=action,+ params=merged,+ service_id=self._service_id,+ agent_id=self._agent_id,+ mirror_to_agent=False,+ )+ if isinstance(data, dict) and data.get("error"):+ raise RuntimeError(str(data["error"]))+ return data+ forwarded = await self._send(action, merged)+ if isinstance(forwarded, dict) and forwarded.get("delivered") == 0:+ raise RuntimeError("enterprise cron request was not delivered to gateway")+ return None++ async def _wait_enterprise_job(+ self,+ job_id: str,+ *,+ expect_absent: bool = False,+ predicate: Any | None = None,+ ) -> dict[str, Any] | None:+ deadline = time.monotonic() + _ENTERPRISE_MUTATION_CONFIRM_SECONDS+ while True:+ row = await self._get_job_enterprise(job_id)+ if expect_absent:+ if row is None:+ return None+ elif row is not None and (predicate is None or predicate(row)):+ return row+ if time.monotonic() >= deadline:+ if expect_absent:+ raise RuntimeError(+ f"enterprise cron delete was not confirmed for job_id={job_id}"+ )+ raise RuntimeError(+ f"enterprise cron update was not confirmed for job_id={job_id}"+ )+ await asyncio.sleep(_ENTERPRISE_MUTATION_POLL_INTERVAL)+async def _list_jobs_enterprise(self) -> list[dict[str, Any]]:from jiuwenswarm.gateway.cron.db_store import _row_to_jobfrom jiuwenswarm.gateway.cron.enterprise_gate import (@@ -274,6 +356,44 @@ class CronTools:out.append(job.to_dict())return out+ async def _get_job_enterprise(self, job_id: str) -> dict[str, Any] | None:+ wanted = str(job_id or "").strip()+ if not wanted:+ return None+ for item in await self._list_jobs_enterprise():+ if str(item.get("id") or "") == wanted:+ return item+ return None++ @staticmethod+ def _preview_schedule(job: Any, count: int) -> list[dict[str, Any]]:+ if isinstance(job, dict):+ cron_expr = str(job.get("cron_expr") or "").strip()+ timezone = str(job.get("timezone") or "Asia/Shanghai").strip() or "Asia/Shanghai"+ wake_offset = job.get("wake_offset_seconds")+ else:+ cron_expr = str(getattr(job, "cron_expr", "") or "").strip()+ timezone = str(getattr(job, "timezone", None) or "Asia/Shanghai").strip() or "Asia/Shanghai"+ wake_offset = getattr(job, "wake_offset_seconds", None)+ count = max(1, min(int(count), 50))+ tz = ZoneInfo(timezone)+ base = datetime.now(tz=tz)+ out: list[dict[str, Any]] = []+ push_dt = base+ for _ in range(count):+ try:+ push_dt = _cron_next_push_dt(cron_expr, push_dt)+ except Exception as exc: # noqa: BLE001+ msg = str(exc)+ if "CroniterBadDateError" in msg or "failed to find next date" in msg:+ break+ raise+ if out and push_dt.isoformat() == out[-1]["push_at"]:+ break+ wake_dt = push_dt - timedelta(seconds=max(0, int(wake_offset or 0)))+ out.append({"wake_at": wake_dt.isoformat(), "push_at": push_dt.isoformat()})+ return out+async def _send_split(self, action: str, params: dict[str, Any]) -> dict[str, Any]:from jiuwenswarm.common.e2a.constants import E2A_RESPONSE_KIND_CRON@@ -296,8 +416,22 @@ class CronTools:"message": "",},}- await self._gateway_push.send_push(payload)- return {"action": action, "status": "forwarded", "data": None, "message": "cron request forwarded to gateway"}+ delivered = await self._gateway_push.send_push(payload)+ result: dict[str, Any] = {+ "action": action,+ "status": "forwarded",+ "data": None,+ "message": "cron request forwarded to gateway",+ }+ if isinstance(delivered, int):+ result["delivered"] = delivered+ if delivered == 0:+ logger.warning(+ "[CronTools] cron push delivered to 0 subscribers action=%s job_id=%s",+ action,+ data.get("job_id") or data.get("id"),+ )+ return resultasync def _send(self, action: str, params: dict[str, Any]) -> dict[str, Any]:return await self._send_split(action, params)@@ -407,11 +541,7 @@ class CronTools:async def get_job(self, job_id: str) -> Any:if self._enterprise_ready():- jobs = await self._list_jobs_enterprise()- for item in jobs:- if str(item.get("id") or "") == str(job_id or "").strip():- return item- return None+ return await self._get_job_enterprise(job_id)job = await self._local_store.get_job(job_id)return job.to_dict() if job else None@@ -422,6 +552,8 @@ class CronTools:# 避免多副本扇出导致重复落库。与个人版"id 在 AgentServer 生成"保持一致。job_id = str(normalized.get("id") or "").strip() or uuid.uuid4().hexnormalized.pop("session_id", None)+ for key in ("group_id", "bot_id", "user_id"):+ normalized.pop(key, None)normalized["targets"] = self._normalize_targets_param(normalized.get("targets"))normalized["cron_expr"] = normalize_cron_expr(str(normalized.get("cron_expr") or "").strip())# 与手动创建规格对齐:LLM 工具 schema 无 delete_after_run 字段,未显式传入时@@ -492,6 +624,7 @@ class CronTools:work_mode = binding.work_modeif self._enterprise_ready():+ identity = self._require_enterprise_identity()push_payload = {**normalized,"id": job_id,@@ -501,7 +634,7 @@ class CronTools:**mode_kw,**model_kw,}- push_payload.update(self._routing_identity_payload())+ push_payload.update(identity)await self._send("create", push_payload)return push_payload@@ -538,6 +671,8 @@ class CronTools:async def update_job(self, job_id: str, patch: dict[str, Any]) -> Any:normalized_patch = dict(patch or {})normalized_patch.pop("session_id", None)+ for key in ("group_id", "bot_id", "user_id"):+ normalized_patch.pop(key, None)if "cron_expr" in normalized_patch:normalized_patch["cron_expr"] = normalize_cron_expr(str(normalized_patch["cron_expr"]).strip())if "targets" in normalized_patch:@@ -557,15 +692,22 @@ class CronTools:# work_mode / project_id / project_dir 重解析(共享 helper):# 与 CronController.update_job 共用同一 ``resolve_cron_job_patch``,# 确保 AgentTool 与 Web RPC 两条链路逻辑一致。- existing = await self._local_store.get_job(job_id)- if existing is None:- raise KeyError("job not found")+ if self._enterprise_ready():+ existing_row = await self.get_job(job_id)+ if existing_row is None:+ raise KeyError("job not found")+ existing_work_mode = str(existing_row.get("work_mode") or "")+ else:+ existing = await self._local_store.get_job(job_id)+ if existing is None:+ raise KeyError("job not found")+ existing_work_mode = existing.work_mode or ""channel_id_val = self._resolve_channel_id() or "web"from jiuwenswarm.server.runtime.session.project_store import resolve_cron_job_patchresolve_cron_job_patch(normalized_patch,- existing_work_mode=existing.work_mode or "",+ existing_work_mode=existing_work_mode,resolve_work_mode_fn=self._resolve_work_mode_from_params,channel_id=channel_id_val,)@@ -576,13 +718,39 @@ class CronTools:chat_type = self._route().chat_typenormalized_patch["chat_type"] = chat_type if chat_type else None- identity = self._routing_identity_payload()if self._enterprise_ready():- await self._send(+ patch_payload = self._sync_patch_payload(normalized_patch)+ data = await self._dispatch_enterprise_action("update",- {"job_id": job_id, "patch": self._sync_patch_payload(normalized_patch), **identity},+ {"job_id": job_id, "patch": patch_payload},)- return {"job_id": job_id, "status": "forwarded"}+ if isinstance(data, dict) and data.get("id"):+ return data++ compare_keys = (+ "name",+ "enabled",+ "cron_expr",+ "timezone",+ "description",+ "targets",+ "mode",+ "model_name",+ "project_id",+ "work_mode",+ "wake_offset_seconds",+ "delete_after_run",+ )++ def _updated(row: dict[str, Any]) -> bool:+ return all(+ row.get(key) == patch_payload[key]+ for key in compare_keys+ if key in patch_payload+ )++ confirmed = await self._wait_enterprise_job(job_id, predicate=_updated)+ return confirmedjob = await self._local_store.update_job(job_id, normalized_patch)try:@@ -599,9 +767,17 @@ class CronTools:return job.to_dict()async def delete_job(self, job_id: str) -> Any:- identity = self._routing_identity_payload()if self._enterprise_ready():- await self._send("delete", {"job_id": job_id, **identity})+ existing = await self.get_job(job_id)+ if existing is None:+ return False+ data = await self._dispatch_enterprise_action("delete", {"job_id": job_id})+ if isinstance(data, dict) and "deleted" in data:+ deleted = data["deleted"]+ if not isinstance(deleted, bool):+ raise RuntimeError("invalid cron delete response")+ return deleted+ await self._wait_enterprise_job(job_id, expect_absent=True)return Truedeleted = await self._local_store.delete_job(job_id)try:@@ -617,15 +793,30 @@ class CronTools:async def toggle_job(self, job_id: str, enabled: bool) -> Any:# proactive.tick job 的开关由 config 的 proactive_recommendation.enabled 驱动,# 禁止手动 toggle——否则会与 config 开关不一致。引导用户去设置关开关。- existing = await self._local_store.get_job(job_id)- if existing is not None and str(getattr(existing, "mode", "") or "").strip().lower() == "proactive.tick":+ if self._enterprise_ready():+ existing_row = await self.get_job(job_id)+ if existing_row is None:+ raise KeyError("job not found")+ mode = str(existing_row.get("mode") or "").strip().lower()+ else:+ existing = await self._local_store.get_job(job_id)+ mode = str(getattr(existing, "mode", "") or "").strip().lower() if existing is not None else ""+ if mode == "proactive.tick":raise RuntimeError("主动推荐定时任务由设置→主动推荐开关控制,不能手动启停;请到设置→主动推荐操作。")- identity = self._routing_identity_payload()if self._enterprise_ready():- await self._send("toggle", {"job_id": job_id, "enabled": bool(enabled), **identity})- return {"job_id": job_id, "enabled": bool(enabled), "status": "forwarded"}+ data = await self._dispatch_enterprise_action(+ "toggle",+ {"job_id": job_id, "enabled": bool(enabled)},+ )+ if isinstance(data, dict) and data.get("id"):+ return data+ confirmed = await self._wait_enterprise_job(+ job_id,+ predicate=lambda row: bool(row.get("enabled")) is bool(enabled),+ )+ return confirmedjob = await self._local_store.update_job(job_id, {"enabled": bool(enabled)})try:await self._send("toggle", {"job_id": job_id, "enabled": bool(enabled)})@@ -638,29 +829,22 @@ class CronTools:return job.to_dict()async def preview_job(self, job_id: str, count: int = 5) -> Any:+ if self._enterprise_ready():+ job = await self.get_job(job_id)+ if job is None:+ raise KeyError("job not found")+ return self._preview_schedule(job, count)job = await self._local_store.get_job(job_id)if job is None:raise KeyError("job not found")- count = max(1, min(int(count), 50))- tz = ZoneInfo(job.timezone)- base = datetime.now(tz=tz)- out: list[dict[str, Any]] = []- push_dt = base- for _ in range(count):- try:- push_dt = _cron_next_push_dt(job.cron_expr, push_dt)- except Exception as exc: # noqa: BLE001- msg = str(exc)- if "CroniterBadDateError" in msg or "failed to find next date" in msg:- break- raise- if out and push_dt.isoformat() == out[-1]["push_at"]:- break- wake_dt = push_dt - timedelta(seconds=max(0, int(job.wake_offset_seconds or 0)))- out.append({"wake_at": wake_dt.isoformat(), "push_at": push_dt.isoformat()})- return out+ return self._preview_schedule(job, count)async def run_now(self, job_id: str) -> Any:+ if self._enterprise_ready():+ data = await self._dispatch_enterprise_action("run_now", {"job_id": job_id})+ if data is not None:+ return data+ return {"job_id": job_id, "status": "forwarded"}return await self._send("run_now", {"job_id": job_id})async def _create_job_tool(self, **kwargs: Any) -> Any:diff --git a/jiuwenswarm/agents/harness/flash/tools/cron_flash.py b/jiuwenswarm/agents/harness/flash/tools/cron_flash.pyindex 3db5db8271..c32f98cc41 100644--- a/jiuwenswarm/agents/harness/flash/tools/cron_flash.py+++ b/jiuwenswarm/agents/harness/flash/tools/cron_flash.py@@ -591,7 +591,7 @@ async def _cron_dispatch(if action == "status":_reject_unknown_fields(scoped, set(), scope="status")- status = await backend.status()+ status = await backend.status(context=context)# The shared backend currently cannot observe scheduler liveness and# reports a constant ``running=false``. Flash exposes only the field# it can state truthfully rather than presenting that placeholder as@@ -602,11 +602,11 @@ async def _cron_dispatch(include = scoped.get("include_disabled", False)if not isinstance(include, bool):raise ValueError("include_disabled must be a boolean")- return {"jobs": await backend.list_jobs(include_disabled=include)}+ return {"jobs": await backend.list_jobs(include_disabled=include, context=context)}if action == "get":_reject_unknown_fields(scoped, {"job_id"}, scope="get")job_id = _required_text(scoped, "job_id")- return await backend.get_job(job_id)+ return await backend.get_job(job_id, context=context)if action == "add":create_input = _translate_to_native(scoped, is_update=False, context=context)return await backend.create_job(create_input, context=context)@@ -618,25 +618,25 @@ async def _cron_dispatch(if action == "remove":_reject_unknown_fields(scoped, {"job_id"}, scope="remove")job_id = _required_text(scoped, "job_id")- return {"deleted": await backend.delete_job(job_id)}+ return {"deleted": await backend.delete_job(job_id, context=context)}if action == "toggle":_reject_unknown_fields(scoped, {"job_id", "enabled"}, scope="toggle")job_id = _required_text(scoped, "job_id")enabled = scoped.get("enabled")if not isinstance(enabled, bool):raise ValueError("enabled must be a boolean")- return await backend.toggle_job(job_id, enabled)+ return await backend.toggle_job(job_id, enabled, context=context)if action == "preview":_reject_unknown_fields(scoped, {"job_id", "count"}, scope="preview")job_id = _required_text(scoped, "job_id")count = scoped.get("count", 5)if not isinstance(count, int) or isinstance(count, bool) or not 1 <= count <= 50:raise ValueError("count must be an integer between 1 and 50")- return await backend.preview_job(job_id, count)+ return await backend.preview_job(job_id, count, context=context)if action == "run":_reject_unknown_fields(scoped, {"job_id"}, scope="run")job_id = _required_text(scoped, "job_id")- return {"run_id": await backend.run_now(job_id)}+ return {"run_id": await backend.run_now(job_id, context=context)}if action == "wake":_reject_unknown_fields(scoped, {"text"}, scope="wake")text = _required_text(scoped, "text")diff --git a/jiuwenswarm/gateway/cron/tenant_registry.py b/jiuwenswarm/gateway/cron/tenant_registry.pyindex d892276045..6c16669b32 100644--- a/jiuwenswarm/gateway/cron/tenant_registry.py+++ b/jiuwenswarm/gateway/cron/tenant_registry.py@@ -59,6 +59,11 @@ class CronTenantRegistry:)return cls._instance+ @classmethod+ def try_get_instance(cls) -> CronTenantRegistry | None:+ """Return the live registry when Gateway is in-process; else None."""+ return cls._instance+@classmethoddef reset_instance(cls) -> None:cls._instance = None@@ -188,14 +193,18 @@ class CronTenantRegistry:request_mode: str | None = None,mirror_to_agent: bool = False,) -> Any:+ from jiuwenswarm.gateway.cron.enterprise_gate import extract_routing_triple+controller = await self.get_controller(service_id, agent_id)+ params = dict(params or {})+ group_id, bot_id, user_id = extract_routing_triple(params)+ routing = {"group_id": group_id, "bot_id": bot_id, "user_id": user_id}if action == "list":- return await controller.list_jobs()+ return await controller.list_jobs(routing)if action == "get":- return await controller.get_job(str(params.get("job_id") or ""))+ return await controller.get_job(str(params.get("job_id") or ""), **routing)if action == "create":if request_mode:- params = dict(params)params["mode"] = request_modedata = await controller.create_job(params)if mirror_to_agent:@@ -206,7 +215,7 @@ class CronTenantRegistry:if action == "update":job_id = str(params.get("job_id") or "")patch = dict(params.get("patch") or {})- data = await controller.update_job(job_id, patch)+ data = await controller.update_job(job_id, patch, **routing)if mirror_to_agent:await self._mirror_after_mutation(service_id=service_id, agent_id=agent_id, job=data@@ -214,7 +223,7 @@ class CronTenantRegistry:return dataif action == "delete":job_id = str(params.get("job_id") or "")- deleted = await controller.delete_job(job_id)+ deleted = await controller.delete_job(job_id, **routing)if mirror_to_agent and deleted:await self._mirror_after_mutation(service_id=service_id,@@ -225,7 +234,7 @@ class CronTenantRegistry:if action == "toggle":job_id = str(params.get("job_id") or "")enabled = bool(params.get("enabled"))- data = await controller.toggle_job(job_id, enabled)+ data = await controller.toggle_job(job_id, enabled, **routing)if mirror_to_agent:await self._mirror_after_mutation(service_id=service_id, agent_id=agent_id, job=data@@ -235,9 +244,15 @@ class CronTenantRegistry:return await controller.preview_job(str(params.get("job_id") or ""),int(params.get("count", 5)),+ **routing,)if action == "run_now":- return {"run_id": await controller.run_now(str(params.get("job_id") or ""))}+ return {+ "run_id": await controller.run_now(+ str(params.get("job_id") or ""),+ **routing,+ )+ }return {"error": f"unknown cron action: {action}"}async def web_create_job(diff --git a/jiuwenswarm/server/gateway_push/transport.py b/jiuwenswarm/server/gateway_push/transport.pyindex 03b9f20e65..5b147bc845 100644--- a/jiuwenswarm/server/gateway_push/transport.py+++ b/jiuwenswarm/server/gateway_push/transport.py@@ -17,7 +17,7 @@ class GatewayPushTransport(Protocol):class WebSocketGatewayPushTransport:"""通过进程内 AgentWebSocketServer 单例推送(分离部署 + WebSocket 默认路径)。"""- async def send_push(self, msg: dict[str, Any]) -> None:+ async def send_push(self, msg: dict[str, Any]) -> int:from jiuwenswarm.server.agent_ws_server import AgentWebSocketServer- await AgentWebSocketServer.get_instance().send_push(msg)+ return int(await AgentWebSocketServer.get_instance().send_push(msg))diff --git a/tests/unit/agentserver/test_cron_runtime.py b/tests/unit/agentserver/test_cron_runtime.pyindex 5f5533275e..3d898352d9 100644--- a/tests/unit/agentserver/test_cron_runtime.py+++ b/tests/unit/agentserver/test_cron_runtime.py@@ -7,6 +7,7 @@ from zoneinfo import ZoneInfoimport pytestfrom jiuwenswarm.agents.harness.common.tools.cron.cron_runtime import (+ _ContextInjectingCronBackend,_CronToolsCronBackend,_extract_legacy_params,)@@ -46,6 +47,9 @@ class _FakeCronTools:self.reset_tokens: list[str] = []self.create_payloads: list[dict] = []+ def _enterprise_ready(self) -> bool:+ return False+def push_cron_route(self, route):self.routes.append(route)return "token-1"@@ -736,3 +740,167 @@ class TestComputeNextRunMissedTriggerWindow:assert push_dt.minute == 35assert wake_dt == push_dt+++def _identity_context(session_id: str = "sess-9") -> SimpleNamespace:+ return SimpleNamespace(+ channel_id="web",+ session_id=session_id,+ metadata={+ "request_id": "req-9",+ "user_id": "u1",+ "routing": {"group_id": "g1", "bot_id": "b1"},+ },+ )+++async def test_cron_backend_binds_route_for_list_get_delete_toggle_preview_run_now() -> None:+ cron_tools = _FakeCronTools()+ backend = _CronToolsCronBackend(cron_tools=cron_tools, message_handler=None)+ context = _identity_context()++ await backend.list_jobs(context=context)+ await backend.get_job("job-1", context=context)+ await backend.delete_job("job-1", context=context)+ await backend.toggle_job("job-1", False, context=context)+ await backend.preview_job("job-1", 3, context=context)+ await backend.run_now("job-1", context=context)++ assert len(cron_tools.routes) == 6+ assert all(route.session_id == "sess-9" for route in cron_tools.routes)+ assert all(route.group_id == "g1" for route in cron_tools.routes)+ assert all(route.bot_id == "b1" for route in cron_tools.routes)+ assert all(route.user_id == "u1" for route in cron_tools.routes)+ assert cron_tools.reset_tokens == ["token-1"] * 6+++async def test_cron_backend_list_uses_bound_request_context() -> None:+ from jiuwenswarm.server.runtime.agent_adapter import interface_deep as deep++ cron_tools = _FakeCronTools()+ backend = _CronToolsCronBackend(cron_tools=cron_tools, message_handler=None)+ tokens = [+ deep._CRON_TOOL_CHANNEL_ID.set("web"),+ deep._CRON_TOOL_SESSION_ID.set("sess-bound"),+ deep._CRON_TOOL_METADATA.set(+ {+ "request_id": "req-bound",+ "user_id": "u1",+ "routing": {"group_id": "g1", "bot_id": "b1"},+ }+ ),+ deep._CRON_TOOL_BOUND.set(True),+ ]+ try:+ await backend.list_jobs()+ await backend.delete_job("job-1")+ finally:+ deep._CRON_TOOL_BOUND.reset(tokens[3])+ deep._CRON_TOOL_METADATA.reset(tokens[2])+ deep._CRON_TOOL_SESSION_ID.reset(tokens[1])+ deep._CRON_TOOL_CHANNEL_ID.reset(tokens[0])++ assert [route.session_id for route in cron_tools.routes] == ["sess-bound", "sess-bound"]+ assert cron_tools.routes[0].user_id == "u1"+ assert cron_tools.routes[0].group_id == "g1"+ assert cron_tools.reset_tokens == ["token-1", "token-1"]+++class _FallbackAdapterContext:+ """Mirrors _RuntimeCronToolContext fallback when invoke_tool has no BOUND flag."""++ channel_id = "web"+ session_id = "sess-adapter"+ mode = "agent"+ metadata = {+ "request_id": "req-adapter",+ "user_id": "u1",+ "routing": {"group_id": "g1", "bot_id": "b1"},+ }+++async def test_context_injecting_backend_fills_openjiuwen_omitted_context() -> None:+ cron_tools = _FakeCronTools()+ inner = _CronToolsCronBackend(cron_tools=cron_tools, message_handler=None)+ backend = _ContextInjectingCronBackend(inner, _FallbackAdapterContext())++ await backend.list_jobs()+ await backend.get_job("job-1")+ await backend.delete_job("job-1")+ await backend.toggle_job("job-1", False)+ await backend.preview_job("job-1", 3)+ await backend.run_now("job-1")+ await backend.status()++ assert len(cron_tools.routes) == 7+ assert all(route.session_id == "sess-adapter" for route in cron_tools.routes)+ assert all(route.group_id == "g1" for route in cron_tools.routes)+ assert all(route.bot_id == "b1" for route in cron_tools.routes)+ assert all(route.user_id == "u1" for route in cron_tools.routes)+++async def test_context_injecting_backend_keeps_explicit_context() -> None:+ cron_tools = _FakeCronTools()+ inner = _CronToolsCronBackend(cron_tools=cron_tools, message_handler=None)+ backend = _ContextInjectingCronBackend(inner, _FallbackAdapterContext())++ await backend.list_jobs(context=_identity_context("sess-explicit"))++ assert cron_tools.routes[0].session_id == "sess-explicit"+ assert cron_tools.routes[0].user_id == "u1"+++class _EnterpriseFakeCronTools(_FakeCronTools):+ def _enterprise_ready(self) -> bool:+ return True+++async def test_enterprise_backend_rejects_missing_authenticated_session() -> None:+ cron_tools = _EnterpriseFakeCronTools()+ backend = _CronToolsCronBackend(cron_tools=cron_tools, message_handler=None)+ with pytest.raises(ValueError, match="authenticated session"):+ await backend.list_jobs()+ with pytest.raises(ValueError, match="authenticated session"):+ await backend.list_jobs(+ context=SimpleNamespace(+ channel_id="web",+ session_id="sess-1",+ metadata={"request_id": "req-1"},+ )+ )+ assert cron_tools.routes == []+++async def test_enterprise_backend_does_not_take_identity_from_non_metadata_context() -> None:+ cron_tools = _EnterpriseFakeCronTools()+ backend = _CronToolsCronBackend(cron_tools=cron_tools, message_handler=None)+ context = SimpleNamespace(+ channel_id="web",+ session_id="sess-1",+ metadata={"request_id": "req-1"},+ group_id="attacker-g",+ bot_id="attacker-b",+ user_id="attacker-u",+ params={"group_id": "attacker-g", "bot_id": "attacker-b", "user_id": "attacker-u"},+ )+ with pytest.raises(ValueError, match="authenticated session"):+ await backend.list_jobs(context=context)+++async def test_enterprise_injecting_backend_uses_adapter_proxy_identity() -> None:+ cron_tools = _EnterpriseFakeCronTools()+ inner = _CronToolsCronBackend(cron_tools=cron_tools, message_handler=None)+ backend = _ContextInjectingCronBackend(inner, _FallbackAdapterContext())+ await backend.list_jobs()+ assert cron_tools.routes[0].session_id == "sess-adapter"+ assert cron_tools.routes[0].group_id == "g1"+ assert cron_tools.routes[0].bot_id == "b1"+ assert cron_tools.routes[0].user_id == "u1"+diff --git a/tests/unit/agentserver/test_enterprise_cron_tools.py b/tests/unit/agentserver/test_enterprise_cron_tools.pynew file mode 100644index 0000000000..d4f1f800be--- /dev/null+++ b/tests/unit/agentserver/test_enterprise_cron_tools.py@@ -0,0 +1,320 @@+from __future__ import annotations++from unittest.mock import AsyncMock++import pytest++from jiuwenswarm.agents.harness.common.tools.cron.cron_tools import CronToolRoute, CronTools+from jiuwenswarm.gateway.cron.store import CronJobStore+from jiuwenswarm.gateway.cron.tenant_registry import CronTenantRegistry+++class _FakeGatewayPush:+ def __init__(self) -> None:+ self.payloads: list[dict] = []++ async def send_push(self, payload: dict) -> None:+ self.payloads.append(payload)+++def _make_tools(tmp_path, monkeypatch, *, enterprise: bool) -> tuple[CronTools, _FakeGatewayPush]:+ push = _FakeGatewayPush()+ tools = CronTools(gateway_push=push, agent_client=object(), message_handler=object())+ tools._local_store = CronJobStore(path=tmp_path / "cron_jobs.json")++ async def _noop_reload() -> None:+ return None++ monkeypatch.setattr(tools, "_reload_scheduler", _noop_reload)+ monkeypatch.setattr(+ "jiuwenswarm.gateway.cron.enterprise_gate.enterprise_cron_enabled",+ lambda **_kwargs: enterprise,+ )+ monkeypatch.setattr(tools, "_enterprise_ready", lambda: enterprise)+ monkeypatch.setattr(+ CronTenantRegistry,+ "try_get_instance",+ classmethod(lambda cls: None),+ )+ return tools, push+++_ENTERPRISE_JOB = {+ "id": "job-1",+ "name": "drink",+ "cron_expr": "0 9 * * *",+ "timezone": "Asia/Shanghai",+ "description": "喝水",+ "enabled": True,+ "work_mode": "work",+ "mode": "agent",+}+++async def test_personal_list_update_delete_preview_still_use_local_store(+ tmp_path, monkeypatch+) -> None:+ tools, push = _make_tools(tmp_path, monkeypatch, enterprise=False)+ await tools._local_store.create_job(+ job_id="job-1",+ name="daily",+ cron_expr="0 9 * * *",+ timezone="Asia/Shanghai",+ description="hello",+ targets="web",+ )++ listed = await tools.list_jobs()+ assert listed[0]["id"] == "job-1"++ updated = await tools.update_job("job-1", {"name": "renamed"})+ assert updated["name"] == "renamed"+ local = await tools._local_store.get_job("job-1")+ assert local is not None and local.name == "renamed"++ preview = await tools.preview_job("job-1", 2)+ assert len(preview) >= 1+ assert "push_at" in preview[0]++ assert await tools.delete_job("job-1") is True+ assert await tools._local_store.get_job("job-1") is None+ assert push.payloads # personal still best-effort syncs to gateway+++async def test_enterprise_list_requires_route_identity(tmp_path, monkeypatch) -> None:+ tools, _push = _make_tools(tmp_path, monkeypatch, enterprise=True)+ with pytest.raises(ValueError, match="requires group_id, bot_id and user_id"):+ await tools.list_jobs()+++async def test_enterprise_list_uses_bound_route_filters(tmp_path, monkeypatch) -> None:+ tools, _push = _make_tools(tmp_path, monkeypatch, enterprise=True)+ captured: dict = {}++ async def _list_records(table, filters=None, order_by=None):+ captured["table"] = table+ captured["filters"] = filters+ return []++ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.enterprise_config.db_queries.list_records",+ _list_records,+ )+ token = tools.push_cron_route(+ CronToolRoute(group_id="g1", bot_id="b1", user_id="u1", session_id="sess-1")+ )+ try:+ assert await tools.list_jobs() == []+ finally:+ tools.reset_cron_route(token)+ assert captured["table"] == "cron_job"+ assert captured["filters"] == {"group_id": "g1", "bot_id": "b1", "user_id": "u1"}+++async def test_enterprise_update_does_not_require_local_json(tmp_path, monkeypatch) -> None:+ tools, push = _make_tools(tmp_path, monkeypatch, enterprise=True)+ monkeypatch.setattr(+ tools,+ "_get_job_enterprise",+ AsyncMock(+ side_effect=[+ dict(_ENTERPRISE_JOB),+ {**_ENTERPRISE_JOB, "name": "renamed"},+ ]+ ),+ )+ token = tools.push_cron_route(CronToolRoute(group_id="g1", bot_id="b1", user_id="u1"))+ try:+ result = await tools.update_job("job-1", {"name": "renamed"})+ finally:+ tools.reset_cron_route(token)++ assert result["name"] == "renamed"+ assert await tools._local_store.get_job("job-1") is None+ body = push.payloads[-1]["body"]["data"]+ assert body["job_id"] == "job-1"+ assert body["patch"]["name"] == "renamed"+ assert body["group_id"] == "g1"+ assert body["user_id"] == "u1"+++async def test_enterprise_delete_returns_true_only_after_job_absent(+ tmp_path, monkeypatch+) -> None:+ tools, push = _make_tools(tmp_path, monkeypatch, enterprise=True)+ present = {"value": True}++ async def _get(job_id: str):+ _ = job_id+ return dict(_ENTERPRISE_JOB) if present["value"] else None++ async def _send_push(payload: dict) -> None:+ push.payloads.append(payload)+ present["value"] = False++ tools._gateway_push.send_push = _send_push # type: ignore[method-assign]+ monkeypatch.setattr(tools, "_get_job_enterprise", _get)+ token = tools.push_cron_route(CronToolRoute(group_id="g1", bot_id="b1", user_id="u1"))+ try:+ assert await tools.delete_job("job-1") is True+ finally:+ tools.reset_cron_route(token)+ assert push.payloads[-1]["body"]["data"]["job_id"] == "job-1"+ assert push.payloads[-1]["body"]["data"]["group_id"] == "g1"+++async def test_enterprise_delete_does_not_lie_when_job_still_present(+ tmp_path, monkeypatch+) -> None:+ tools, _push = _make_tools(tmp_path, monkeypatch, enterprise=True)+ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.common.tools.cron.cron_tools._ENTERPRISE_MUTATION_CONFIRM_SECONDS",+ 0.05,+ )+ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.common.tools.cron.cron_tools._ENTERPRISE_MUTATION_POLL_INTERVAL",+ 0.01,+ )+ monkeypatch.setattr(tools, "_get_job_enterprise", AsyncMock(return_value=dict(_ENTERPRISE_JOB)))+ token = tools.push_cron_route(CronToolRoute(group_id="g1", bot_id="b1", user_id="u1"))+ try:+ with pytest.raises(RuntimeError, match="delete was not confirmed"):+ await tools.delete_job("job-1")+ finally:+ tools.reset_cron_route(token)+++async def test_enterprise_delete_missing_job_returns_false(tmp_path, monkeypatch) -> None:+ tools, push = _make_tools(tmp_path, monkeypatch, enterprise=True)+ monkeypatch.setattr(tools, "_get_job_enterprise", AsyncMock(return_value=None))+ token = tools.push_cron_route(CronToolRoute(group_id="g1", bot_id="b1", user_id="u1"))+ try:+ assert await tools.delete_job("missing") is False+ finally:+ tools.reset_cron_route(token)+ assert push.payloads == []+++async def test_enterprise_delete_inprocess_registry_returns_controller_result(+ tmp_path, monkeypatch+) -> None:+ tools, push = _make_tools(tmp_path, monkeypatch, enterprise=True)+ monkeypatch.setattr(tools, "_get_job_enterprise", AsyncMock(return_value=dict(_ENTERPRISE_JOB)))++ class _Registry:+ def __init__(self) -> None:+ self.calls: list[dict] = []++ async def handle_push_action(self, **kwargs):+ self.calls.append(kwargs)+ return {"deleted": True}++ registry = _Registry()+ monkeypatch.setattr(+ CronTenantRegistry, "try_get_instance", classmethod(lambda cls: registry)+ )+ token = tools.push_cron_route(CronToolRoute(group_id="g1", bot_id="b1", user_id="u1"))+ try:+ assert await tools.delete_job("job-1") is True+ finally:+ tools.reset_cron_route(token)+ assert push.payloads == []+ assert registry.calls[0]["action"] == "delete"+ assert registry.calls[0]["params"]["group_id"] == "g1"+++async def test_enterprise_delete_rejects_non_bool_controller_result(+ tmp_path, monkeypatch+) -> None:+ tools, push = _make_tools(tmp_path, monkeypatch, enterprise=True)+ monkeypatch.setattr(tools, "_get_job_enterprise", AsyncMock(return_value=dict(_ENTERPRISE_JOB)))++ class _Registry:+ async def handle_push_action(self, **kwargs):+ _ = kwargs+ return {"deleted": "false"}++ monkeypatch.setattr(+ CronTenantRegistry, "try_get_instance", classmethod(lambda cls: _Registry())+ )+ token = tools.push_cron_route(CronToolRoute(group_id="g1", bot_id="b1", user_id="u1"))+ try:+ with pytest.raises(RuntimeError, match="invalid cron delete response"):+ await tools.delete_job("job-1")+ finally:+ tools.reset_cron_route(token)+ assert push.payloads == []+++async def test_enterprise_update_ignores_identity_in_patch(tmp_path, monkeypatch) -> None:+ tools, push = _make_tools(tmp_path, monkeypatch, enterprise=True)+ monkeypatch.setattr(+ tools,+ "_get_job_enterprise",+ AsyncMock(+ side_effect=[+ dict(_ENTERPRISE_JOB),+ {**_ENTERPRISE_JOB, "name": "renamed"},+ ]+ ),+ )+ token = tools.push_cron_route(CronToolRoute(group_id="g1", bot_id="b1", user_id="u1"))+ try:+ await tools.update_job(+ "job-1",+ {"name": "renamed", "group_id": "attacker", "user_id": "other"},+ )+ finally:+ tools.reset_cron_route(token)+ body = push.payloads[-1]["body"]["data"]+ assert body["group_id"] == "g1"+ assert body["user_id"] == "u1"+ assert "group_id" not in body["patch"]+ assert "user_id" not in body["patch"]+++async def test_enterprise_preview_uses_job_store_not_local_json(tmp_path, monkeypatch) -> None:+ tools, _push = _make_tools(tmp_path, monkeypatch, enterprise=True)+ monkeypatch.setattr(tools, "_get_job_enterprise", AsyncMock(return_value=dict(_ENTERPRISE_JOB)))+ token = tools.push_cron_route(CronToolRoute(group_id="g1", bot_id="b1", user_id="u1"))+ try:+ rows = await tools.preview_job("job-1", 2)+ finally:+ tools.reset_cron_route(token)+ assert len(rows) >= 1+ assert "push_at" in rows[0]+ assert await tools._local_store.get_job("job-1") is None+++async def test_enterprise_toggle_forwards_identity_and_confirms(tmp_path, monkeypatch) -> None:+ tools, push = _make_tools(tmp_path, monkeypatch, enterprise=True)+ monkeypatch.setattr(+ tools,+ "_get_job_enterprise",+ AsyncMock(+ side_effect=[+ dict(_ENTERPRISE_JOB),+ {**_ENTERPRISE_JOB, "enabled": False},+ ]+ ),+ )+ token = tools.push_cron_route(CronToolRoute(group_id="g1", bot_id="b1", user_id="u1"))+ try:+ result = await tools.toggle_job("job-1", False)+ finally:+ tools.reset_cron_route(token)+ assert result["enabled"] is False+ assert push.payloads[-1]["body"]["data"]["enabled"] is False+ assert push.payloads[-1]["body"]["data"]["bot_id"] == "b1"diff --git a/tests/unit_tests/agentserver/test_flash_cron_tool.py b/tests/unit_tests/agentserver/test_flash_cron_tool.pyindex 6943b23bae..b0c70dd5ae 100644--- a/tests/unit_tests/agentserver/test_flash_cron_tool.py+++ b/tests/unit_tests/agentserver/test_flash_cron_tool.py@@ -35,31 +35,31 @@ class _Backend:self.calls.append(("wake", text, mode))return {"queued": True}- async def status(self):+ async def status(self, *, context=None):self.calls.append(("status",))return {"running": False, "job_count": 3, "run_count": 0}- async def list_jobs(self, *, include_disabled=True):+ async def list_jobs(self, *, include_disabled=True, context=None):self.calls.append(("list", include_disabled))return []- async def get_job(self, job_id):+ async def get_job(self, job_id, *, context=None):self.calls.append(("get", job_id))return {}- async def delete_job(self, job_id):+ async def delete_job(self, job_id, *, context=None):self.calls.append(("remove", job_id))return True- async def toggle_job(self, job_id, enabled):+ async def toggle_job(self, job_id, enabled, *, context=None):self.calls.append(("toggle", job_id, enabled))return {}- async def preview_job(self, job_id, count=5):+ async def preview_job(self, job_id, count=5, *, context=None):self.calls.append(("preview", job_id, count))return []- async def run_now(self, job_id):+ async def run_now(self, job_id, *, context=None):self.calls.append(("run", job_id))return "run-id"@@ -81,6 +81,28 @@ class _RouteCapturingCronTools:self.payloads.append(payload)return payload+ async def list_jobs(self):+ return []++ async def get_job(self, job_id: str):+ _ = job_id+ return None++ async def delete_job(self, job_id: str):+ _ = job_id+ return True++ async def toggle_job(self, job_id: str, enabled: bool):+ return {"id": job_id, "enabled": enabled}++ async def preview_job(self, job_id: str, count: int = 5):+ _ = (job_id, count)+ return []++ async def run_now(self, job_id: str):+ _ = job_id+ return {"run_id": "r-1"}+def test_description_is_default_and_not_duplicated(monkeypatch) -> None:monkeypatch.delenv("CRON_FLASH_SCHEMA_STYLE", raising=False)@@ -239,6 +261,30 @@ async def test_flat_create_passes_session_and_app_via_backend_route() -> None:assert cron_tools.reset_tokens == ["route-token"]+async def test_flat_list_and_remove_pass_session_via_backend_route() -> None:+ cron_tools = _RouteCapturingCronTools()+ backend = _CronToolsCronBackend(cron_tools=cron_tools, message_handler=None)+ context = SimpleNamespace(+ channel_id="web",+ session_id="session-list",+ metadata={+ "request_id": "request-list",+ "user_id": "u1",+ "routing": {"group_id": "g1", "bot_id": "b1"},+ },+ mode="agent",+ )++ await _cron_dispatch(backend, context, {"list": {"include_disabled": True}})+ await _cron_dispatch(backend, context, {"remove": {"job_id": "job-1"}})++ assert [route.session_id for route in cron_tools.routes] == ["session-list", "session-list"]+ assert cron_tools.routes[0].group_id == "g1"+ assert cron_tools.routes[0].user_id == "u1"+ assert cron_tools.reset_tokens == ["route-token", "route-token"]++def test_translate_at_and_timeout() -> None:context = SimpleNamespace(mode="team")translated = _translate_to_native(diff --git a/tests/unit_tests/gateway/test_cron_tenant_registry.py b/tests/unit_tests/gateway/test_cron_tenant_registry.pyindex e2f716dbe5..781545e3cc 100644--- a/tests/unit_tests/gateway/test_cron_tenant_registry.py+++ b/tests/unit_tests/gateway/test_cron_tenant_registry.py@@ -146,3 +146,108 @@ async def test_web_create_mirrors_to_agent_home(tmp_path, monkeypatch) -> None:assert agent_path.exists(), f"missing agent mirror at {agent_path}"assert job["service_id"] == "default"assert job["agent_id"] == "office"+++async def test_handle_push_action_passes_routing_triple(tmp_path, monkeypatch) -> None:+ monkeypatch.setattr(+ "jiuwenswarm.common.utils.get_user_workspace_dir", lambda: tmp_path+ )+ monkeypatch.setattr(+ "jiuwenswarm.gateway.cron.tenant_registry.CronSchedulerService.start",+ AsyncMock(),+ )+ monkeypatch.setattr(+ "jiuwenswarm.gateway.cron.tenant_registry.CronSchedulerService.stop",+ AsyncMock(),+ )++ registry = CronTenantRegistry.get_instance(+ agent_client=MagicMock(),+ message_handler=MagicMock(),+ )+ controller = MagicMock()+ controller.list_jobs = AsyncMock(return_value=[])+ controller.get_job = AsyncMock(return_value={"id": "job-1"})+ controller.update_job = AsyncMock(return_value={"id": "job-1", "name": "n2"})+ controller.delete_job = AsyncMock(return_value=True)+ controller.toggle_job = AsyncMock(return_value={"id": "job-1", "enabled": False})+ controller.preview_job = AsyncMock(return_value=[{"push_at": "x"}])+ controller.run_now = AsyncMock(return_value="run-1")+ registry.get_controller = AsyncMock(return_value=controller)++ identity = {"job_id": "job-1", "group_id": "g1", "bot_id": "b1", "user_id": "u1"}+ routing = {"group_id": "g1", "bot_id": "b1", "user_id": "u1"}++ await registry.handle_push_action(+ action="list", params=identity, service_id="default", agent_id="office"+ )+ controller.list_jobs.assert_awaited_once_with(routing)++ await registry.handle_push_action(+ action="get", params=identity, service_id="default", agent_id="office"+ )+ controller.get_job.assert_awaited_once_with("job-1", **routing)++ await registry.handle_push_action(+ action="update",+ params={**identity, "patch": {"name": "n2"}},+ service_id="default",+ agent_id="office",+ )+ controller.update_job.assert_awaited_once_with("job-1", {"name": "n2"}, **routing)++ deleted = await registry.handle_push_action(+ action="delete", params=identity, service_id="default", agent_id="office"+ )+ assert deleted == {"deleted": True}+ controller.delete_job.assert_awaited_once_with("job-1", **routing)++ await registry.handle_push_action(+ action="toggle",+ params={**identity, "enabled": False},+ service_id="default",+ agent_id="office",+ )+ controller.toggle_job.assert_awaited_once_with("job-1", False, **routing)++ await registry.handle_push_action(+ action="preview",+ params={**identity, "count": 3},+ service_id="default",+ agent_id="office",+ )+ controller.preview_job.assert_awaited_once_with("job-1", 3, **routing)++ ran = await registry.handle_push_action(+ action="run_now", params=identity, service_id="default", agent_id="office"+ )+ assert ran == {"run_id": "run-1"}+ controller.run_now.assert_awaited_once_with("job-1", **routing)+++async def test_handle_push_action_personal_delete_allows_empty_triple(+ tmp_path, monkeypatch+) -> None:+ monkeypatch.setattr(+ "jiuwenswarm.common.utils.get_user_workspace_dir", lambda: tmp_path+ )+ registry = CronTenantRegistry.get_instance(+ agent_client=MagicMock(),+ message_handler=MagicMock(),+ )+ controller = MagicMock()+ controller.delete_job = AsyncMock(return_value=True)+ registry.get_controller = AsyncMock(return_value=controller)++ result = await registry.handle_push_action(+ action="delete",+ params={"job_id": "job-1"},+ service_id="default",+ agent_id="office",+ )+ assert result == {"deleted": True}+ controller.delete_job.assert_awaited_once_with(+ "job-1", group_id=None, bot_id=None, user_id=None+ )