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:定时任务假成功问题

hanjiahuia3d8cdc80ee5
diff --git a/jiuwenswarm/agents/harness/common/tools/cron/cron_tools.py b/jiuwenswarm/agents/harness/common/tools/cron/cron_tools.py
index a638527938..98f068a349 100644
--- a/jiuwenswarm/agents/harness/common/tools/cron/cron_tools.py
+++ b/jiuwenswarm/agents/harness/common/tools/cron/cron_tools.py
@@ -21,6 +21,7 @@ from jiuwenswarm.gateway.cron.models import (
is_valid_target_channel_id,
normalize_cron_job_mode,
normalize_target_channel_id,
+ validate_cron_job_payload,
validate_cron_model,
)
from jiuwenswarm.server.gateway_push import (
@@ -623,6 +624,31 @@ class CronTools:
resolved_project_id = binding.project_id
work_mode = binding.work_mode
+ # Shared field hard-rules before enterprise push / local write so Deep tools
+ # (cron / cron_create_job) fail as tool results instead of optimistic success.
+ timezone_val = (
+ str(normalized.get("timezone") or "Asia/Shanghai").strip() or "Asia/Shanghai"
+ )
+ preflight: dict[str, Any] = {
+ "id": job_id,
+ "name": str(normalized.get("name") or "").strip(),
+ "cron_expr": str(normalized.get("cron_expr") or "").strip(),
+ "timezone": timezone_val,
+ "description": str(normalized.get("description") or ""),
+ "targets": targets_str,
+ "enabled": bool(normalized.get("enabled", True)),
+ "wake_offset_seconds": normalized.get("wake_offset_seconds", 0),
+ "delete_after_run": normalized.get("delete_after_run"),
+ "project_id": resolved_project_id,
+ "work_mode": work_mode,
+ **session_kw,
+ **mode_kw,
+ **model_kw,
+ }
+ if "timeout_seconds" in normalized:
+ preflight["timeout_seconds"] = normalized.get("timeout_seconds")
+ validate_cron_job_payload(preflight, strict_mode=True)
+
if self._enterprise_ready():
identity = self._require_enterprise_identity()
push_payload = {
@@ -697,11 +723,13 @@ class CronTools:
if existing_row is None:
raise KeyError("job not found")
existing_work_mode = str(existing_row.get("work_mode") or "")
+ existing_for_preflight: dict[str, Any] = dict(existing_row)
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 ""
+ existing_for_preflight = existing.to_dict()
channel_id_val = self._resolve_channel_id() or "web"
from jiuwenswarm.server.runtime.session.project_store import resolve_cron_job_patch
@@ -718,6 +746,26 @@ class CronTools:
chat_type = self._route().chat_type
normalized_patch["chat_type"] = chat_type if chat_type else None
+ # Normalize incomplete existing rows (e.g. trimmed enterprise mocks / sparse
+ # mirrors) before full-payload hard-rules, so rename-only updates are not
+ # rejected solely because targets/timezone were absent on the baseline dict.
+ merged_preflight = {**existing_for_preflight, **normalized_patch}
+ merged_preflight["id"] = str(
+ existing_for_preflight.get("id") or job_id or ""
+ ).strip()
+ if not str(merged_preflight.get("targets") or "").strip():
+ merged_preflight["targets"] = self._normalize_targets_param(
+ merged_preflight.get("targets")
+ )
+ if not str(merged_preflight.get("timezone") or "").strip():
+ merged_preflight["timezone"] = "Asia/Shanghai"
+ if merged_preflight.get("wake_offset_seconds") is None:
+ merged_preflight["wake_offset_seconds"] = 0
+ # Lenient on the merged baseline so rename-only updates keep working for
+ # legacy rows with unknown modes (from_dict coerce path). Patch ``mode``
+ # is already strictly checked above via normalize_cron_job_mode when present.
+ validate_cron_job_payload(merged_preflight, strict_mode=False)
+
if self._enterprise_ready():
patch_payload = self._sync_patch_payload(normalized_patch)
data = await self._dispatch_enterprise_action(
diff --git a/jiuwenswarm/gateway/cron/models.py b/jiuwenswarm/gateway/cron/models.py
index fb116b98b4..d92583dc10 100644
--- a/jiuwenswarm/gateway/cron/models.py
+++ b/jiuwenswarm/gateway/cron/models.py
@@ -103,6 +103,80 @@ _CRON_JOB_MODE_ALIASES: dict[str, str] = {
}
+def validate_cron_job_payload(
+ data: dict[str, Any],
+ *,
+ strict_mode: bool = False,
+) -> None:
+ """Validate cron job field constraints shared by deserialize and create/update.
+
+ Does not mutate ``data``. Raises ``ValueError`` on violation.
+
+ * ``strict_mode=False`` (``CronJob.from_dict``, Agent update merged preflight):
+ field hard-rules only; ``mode`` stays lenient so legacy rows with unknown
+ modes can still load / be renamed via coerce. Patch ``mode`` is still
+ strictly checked separately when present on update.
+ * ``strict_mode=True`` (Agent create preflight): also reject invalid ``mode``
+ via ``normalize_cron_job_mode`` (aligned with create APIs).
+ """
+ # Align with build_new_cron_job: missing/None → 0 (not "must be int").
+ wake_offset_seconds_raw = data.get("wake_offset_seconds", 0)
+ if wake_offset_seconds_raw is None:
+ wake_offset_seconds_raw = 0
+ try:
+ int(wake_offset_seconds_raw)
+ except Exception as exc: # noqa: BLE001
+ raise ValueError("wake_offset_seconds must be int") from exc
+
+ description = str(data.get("description") or "").strip()
+ if not description:
+ raise ValueError("description is required")
+ if len(description) > CRON_JOB_DESCRIPTION_MAX_LENGTH:
+ raise ValueError(
+ f"description must be at most {CRON_JOB_DESCRIPTION_MAX_LENGTH} characters"
+ )
+
+ targets_raw = data.get("targets", "")
+ targets_str = ""
+ if isinstance(targets_raw, str):
+ targets_str = targets_raw.strip()
+ elif isinstance(targets_raw, list):
+ for item in targets_raw:
+ if isinstance(item, dict):
+ ch = str(item.get("channel_id") or "").strip()
+ if ch:
+ targets_str = ch
+ break
+
+ job_id = str(data.get("id") or "").strip()
+ name = str(data.get("name") or "").strip()
+ cron_expr = str(data.get("cron_expr") or "").strip()
+ timezone = str(data.get("timezone") or "").strip()
+
+ if not job_id:
+ raise ValueError("id is required")
+ if not name:
+ raise ValueError("name is required")
+ if len(name) > CRON_JOB_NAME_MAX_LENGTH:
+ raise ValueError(f"name must be at most {CRON_JOB_NAME_MAX_LENGTH} characters")
+ if not cron_expr:
+ raise ValueError("cron_expr is required")
+ if not timezone:
+ raise ValueError("timezone is required")
+ validate_cron_expression(cron_expr, timezone=timezone)
+ if not targets_str:
+ raise ValueError("targets is required")
+
+ timeout_seconds_raw = data.get("timeout_seconds", None)
+ if timeout_seconds_raw is not None:
+ normalize_cron_job_timeout_seconds(timeout_seconds_raw)
+
+ if strict_mode:
+ mode_raw = data.get("mode", None)
+ if mode_raw is not None and str(mode_raw).strip():
+ normalize_cron_job_mode(mode_raw)
+
+
def normalize_cron_job_mode(raw: Any, *, default: str = CRON_JOB_DEFAULT_MODE) -> str:
"""Normalize and validate a cron job execution mode (strict, for create/update APIs).
@@ -348,6 +422,9 @@ class CronJob:
@staticmethod
def from_dict(data: dict[str, Any]) -> "CronJob":
+ # Shared field hard-rules (lenient mode: do not reject unknown legacy modes).
+ validate_cron_job_payload(data, strict_mode=False)
+
job_id = str(data.get("id") or "").strip()
name = str(data.get("name") or "").strip()
cron_expr = str(data.get("cron_expr") or "").strip()
@@ -356,20 +433,13 @@ class CronJob:
expired = bool(data.get("expired", False))
wake_offset_seconds_raw = data.get("wake_offset_seconds", 0)
- try:
- wake_offset_seconds = int(wake_offset_seconds_raw)
- except Exception as exc: # noqa: BLE001
- raise ValueError("wake_offset_seconds must be int") from exc
+ if wake_offset_seconds_raw is None:
+ wake_offset_seconds_raw = 0
+ wake_offset_seconds = int(wake_offset_seconds_raw)
if wake_offset_seconds < 0:
wake_offset_seconds = 0
description = str(data.get("description") or "").strip()
- if not description:
- raise ValueError("description is required")
- if len(description) > CRON_JOB_DESCRIPTION_MAX_LENGTH:
- raise ValueError(
- f"description must be at most {CRON_JOB_DESCRIPTION_MAX_LENGTH} characters"
- )
# targets 新格式是字符串;旧格式是 list[dict],此处做兼容。
targets_raw = data.get("targets", "")
@@ -407,20 +477,6 @@ class CronJob:
next_run_at_f = _epoch_field("next_run_at")
last_run_at_f = _epoch_field("last_run_at")
- if not job_id:
- raise ValueError("id is required")
- if not name:
- raise ValueError("name is required")
- if len(name) > CRON_JOB_NAME_MAX_LENGTH:
- raise ValueError(f"name must be at most {CRON_JOB_NAME_MAX_LENGTH} characters")
- if not cron_expr:
- raise ValueError("cron_expr is required")
- if not timezone:
- raise ValueError("timezone is required")
- validate_cron_expression(cron_expr, timezone=timezone)
- if not targets_str:
- raise ValueError("targets is required")
-
targets_str = _normalize_targets_str(targets_str)
sid_raw = data.get("session_id", None)
diff --git a/tests/unit/agentserver/test_enterprise_cron_tools.py b/tests/unit/agentserver/test_enterprise_cron_tools.py
index d4f1f800be..d1bd48dd7b 100644
--- a/tests/unit/agentserver/test_enterprise_cron_tools.py
+++ b/tests/unit/agentserver/test_enterprise_cron_tools.py
@@ -5,6 +5,7 @@ from unittest.mock import AsyncMock
import pytest
from jiuwenswarm.agents.harness.common.tools.cron.cron_tools import CronToolRoute, CronTools
+from jiuwenswarm.gateway.cron.models import CRON_JOB_DESCRIPTION_MAX_LENGTH
from jiuwenswarm.gateway.cron.store import CronJobStore
from jiuwenswarm.gateway.cron.tenant_registry import CronTenantRegistry
@@ -45,6 +46,7 @@ _ENTERPRISE_JOB = {
"cron_expr": "0 9 * * *",
"timezone": "Asia/Shanghai",
"description": "喝水",
+ "targets": "web",
"enabled": True,
"work_mode": "work",
"mode": "agent",
@@ -114,6 +116,30 @@ async def test_enterprise_list_uses_bound_route_filters(tmp_path, monkeypatch) -
assert captured["filters"] == {"group_id": "g1", "bot_id": "b1", "user_id": "u1"}
+async def test_enterprise_create_rejects_overlong_description_before_push(
+ tmp_path, monkeypatch
+) -> None:
+ tools, push = _make_tools(tmp_path, monkeypatch, enterprise=True)
+ token = tools.push_cron_route(
+ CronToolRoute(group_id="g1", bot_id="b1", user_id="u1", session_id="sess-1")
+ )
+ try:
+ with pytest.raises(ValueError, match="description must be at most"):
+ await tools.create_job(
+ {
+ "name": "每日阅读提醒",
+ "cron_expr": "0 0 9 * * ? *",
+ "timezone": "Asia/Shanghai",
+ "description": "x" * (CRON_JOB_DESCRIPTION_MAX_LENGTH + 1),
+ "targets": "web",
+ }
+ )
+ finally:
+ tools.reset_cron_route(token)
+ assert push.payloads == []
+
+
@pytest.mark.asyncio
async def test_enterprise_update_does_not_require_local_json(tmp_path, monkeypatch) -> None:
tools, push = _make_tools(tmp_path, monkeypatch, enterprise=True)
@@ -142,6 +168,75 @@ async def test_enterprise_update_does_not_require_local_json(tmp_path, monkeypat
assert body["user_id"] == "u1"
+async def test_enterprise_update_tolerates_sparse_existing_row_without_targets(
+ tmp_path, monkeypatch
+) -> None:
+ """Rename-only update must not fail solely because the baseline dict omits targets."""
+ tools, push = _make_tools(tmp_path, monkeypatch, enterprise=True)
+ sparse = {
+ "id": "job-1",
+ "name": "drink",
+ "cron_expr": "0 9 * * *",
+ "timezone": "Asia/Shanghai",
+ "description": "喝水",
+ "enabled": True,
+ "mode": "agent",
+ }
+ monkeypatch.setattr(
+ tools,
+ "_get_job_enterprise",
+ AsyncMock(side_effect=[dict(sparse), {**sparse, "name": "renamed", "targets": "web"}]),
+ )
+ 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 push.payloads[-1]["body"]["data"]["patch"]["name"] == "renamed"
+
+
+async def test_enterprise_update_tolerates_legacy_unknown_mode_on_rename(
+ tmp_path, monkeypatch
+) -> None:
+ """Rename-only must not reject historical unknown modes that from_dict still loads."""
+ tools, push = _make_tools(tmp_path, monkeypatch, enterprise=True)
+ legacy = {
+ **_ENTERPRISE_JOB,
+ "mode": "legacy.custom",
+ }
+ monkeypatch.setattr(
+ tools,
+ "_get_job_enterprise",
+ AsyncMock(side_effect=[dict(legacy), {**legacy, "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 push.payloads[-1]["body"]["data"]["patch"]["name"] == "renamed"
+ assert "mode" not in push.payloads[-1]["body"]["data"]["patch"]
+
+
+async def test_enterprise_update_still_rejects_invalid_mode_in_patch(
+ 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:
+ with pytest.raises(ValueError, match="Invalid cron job mode"):
+ await tools.update_job("job-1", {"mode": "not-a-mode"})
+ finally:
+ tools.reset_cron_route(token)
+ assert push.payloads == []
+
+
@pytest.mark.asyncio
async def test_enterprise_delete_returns_true_only_after_job_absent(
tmp_path, monkeypatch
diff --git a/tests/unit_tests/gateway/test_validate_cron_job_payload.py b/tests/unit_tests/gateway/test_validate_cron_job_payload.py
new file mode 100644
index 0000000000..6c0fa9ac9b
--- /dev/null
+++ b/tests/unit_tests/gateway/test_validate_cron_job_payload.py
@@ -0,0 +1,73 @@
+from __future__ import annotations
+
+import pytest
+
+from jiuwenswarm.gateway.cron.models import (
+ CRON_JOB_DESCRIPTION_MAX_LENGTH,
+ CRON_JOB_NAME_MAX_LENGTH,
+ CronJob,
+ validate_cron_job_payload,
+)
+
+
+def _valid_payload(**overrides):
+ base = {
+ "id": "job-1",
+ "name": "drink",
+ "cron_expr": "0 0 9 * * ? *",
+ "timezone": "Asia/Shanghai",
+ "description": "remind to drink water",
+ "targets": "web",
+ "enabled": True,
+ "mode": "agent",
+ }
+ base.update(overrides)
+ return base
+
+
+def test_validate_accepts_valid_payload() -> None:
+ validate_cron_job_payload(_valid_payload(), strict_mode=True)
+
+
+def test_validate_rejects_overlong_description() -> None:
+ with pytest.raises(ValueError, match="description must be at most"):
+ validate_cron_job_payload(
+ _valid_payload(description="x" * (CRON_JOB_DESCRIPTION_MAX_LENGTH + 1)),
+ strict_mode=True,
+ )
+
+
+def test_validate_rejects_overlong_name() -> None:
+ with pytest.raises(ValueError, match="name must be at most"):
+ validate_cron_job_payload(
+ _valid_payload(name="n" * (CRON_JOB_NAME_MAX_LENGTH + 1)),
+ strict_mode=True,
+ )
+
+
+def test_validate_strict_mode_rejects_invalid_mode() -> None:
+ with pytest.raises(ValueError, match="Invalid cron job mode"):
+ validate_cron_job_payload(_valid_payload(mode="not-a-mode"), strict_mode=True)
+
+
+def test_validate_lenient_mode_allows_unknown_mode_for_from_dict() -> None:
+ # Deserialize path must still load legacy unknown modes via coerce.
+ validate_cron_job_payload(_valid_payload(mode="legacy.custom"), strict_mode=False)
+ job = CronJob.from_dict(_valid_payload(mode="legacy.custom"))
+ assert job.mode == "legacy.custom"
+
+
+def test_from_dict_still_rejects_overlong_description() -> None:
+ with pytest.raises(ValueError, match="description must be at most"):
+ CronJob.from_dict(
+ _valid_payload(description="y" * (CRON_JOB_DESCRIPTION_MAX_LENGTH + 1))
+ )
+
+
+def test_validate_treats_null_wake_offset_as_zero() -> None:
+ validate_cron_job_payload(
+ _valid_payload(wake_offset_seconds=None),
+ strict_mode=True,
+ )
+ job = CronJob.from_dict(_valid_payload(wake_offset_seconds=None))
+ assert job.wake_offset_seconds == 0