Skip to content

Your lightweight open-source personal agent.

fix(cron): preserve pending runs when editing automation details (#5751)

beemines93b51121d1b3
diff --git a/nanobot/channels/websocket/tests/test_websocket_http_routes.py b/nanobot/channels/websocket/tests/test_websocket_http_routes.py
index 450f7b527..bbfde53a9 100644
--- a/nanobot/channels/websocket/tests/test_websocket_http_routes.py
+++ b/nanobot/channels/websocket/tests/test_websocket_http_routes.py
@@ -2416,6 +2416,60 @@ async def test_session_delete_removes_unpersisted_new_chat(
assert channel.gateway.workspaces.scope_for_session_key(key).project_path == tmp_path.resolve()
[email protected]("kind", ["every", "cron", "at"])
+async def test_webui_automation_edit_keeps_pending_run(bus, tmp_path, monkeypatch, kind):
+ now = 1_900_000_000_000
+ monkeypatch.setattr("nanobot.cron.service._now_ms", lambda: now)
+ schedules = {
+ "every": CronSchedule(kind="every", every_ms=60_000),
+ "cron": CronSchedule(kind="cron", expr="* * * * *", tz="UTC"),
+ "at": CronSchedule(kind="at", at_ms=now + 60_000),
+ }
+ cron = CronService(tmp_path / "cron" / "jobs.json")
+ job = cron.add_job(
+ name="Report",
+ schedule=schedules[kind],
+ message="Write the report",
+ session_key="websocket:report",
+ origin_channel="websocket",
+ origin_chat_id="report",
+ )
+ due_at = job.state.next_run_at_ms
+ assert due_at is not None
+ now = due_at + 1_000
+ channel = _ch(bus, cron_service=cron, workspace_path=tmp_path)
+ try:
+ response = await _webui_mutate(
+ channel,
+ "automation.update",
+ {
+ "id": job.id,
+ "values": {
+ "name": "Updated report",
+ "message": "Include the latest figures",
+ "schedule": {
+ "kind": kind,
+ "every_ms": job.schedule.every_ms,
+ "at_ms": job.schedule.at_ms,
+ "expr": job.schedule.expr,
+ "tz": job.schedule.tz,
+ },
+ },
+ },
+ )
+ assert response.status_code == 200
+ row = next(item for item in response.json()["jobs"] if item["id"] == job.id)
+ assert row["name"] == "Updated report"
+ assert row["payload"]["message"] == "Include the latest figures"
+ assert row["state"]["next_run_at_ms"] == due_at
+ persisted = CronService(cron.store_path).get_job(job.id)
+ assert persisted is not None
+ assert persisted.state.next_run_at_ms == due_at
+ finally:
+ await channel.stop()
+
+
@pytest.mark.asyncio
async def test_webui_automation_result_is_authenticated_and_returns_only_selected_response(
bus: MagicMock, tmp_path: Path,
diff --git a/nanobot/cron/service.py b/nanobot/cron/service.py
index 0b19ce3b0..bb8057d31 100644
--- a/nanobot/cron/service.py
+++ b/nanobot/cron/service.py
@@ -813,6 +813,7 @@ class CronService:
For ``channel`` and ``to``, pass an explicit value (including ``None``)
to update; omit (sentinel ``...``) to leave unchanged.
+ Preserve the next occurrence unless the schedule actually changes.
"""
store = self._require_store()
job = next((j for j in store.jobs if j.id == job_id), None)
@@ -821,6 +822,7 @@ class CronService:
if job.payload.kind == "system_event":
return "protected"
+ schedule_changed = schedule is not None and schedule != job.schedule
if schedule is not None:
_validate_schedule_for_add(schedule)
job.schedule = schedule
@@ -840,10 +842,10 @@ class CronService:
self._enforce_agent_binding(job)
job.updated_at_ms = _now_ms()
- if job.enabled:
- job.state.next_run_at_ms = _compute_next_run(job.schedule, _now_ms())
- else:
+ if not job.enabled:
job.state.next_run_at_ms = None
+ elif schedule_changed:
+ job.state.next_run_at_ms = _compute_next_run(job.schedule, _now_ms())
if self._should_persist_store():
self._save_store()
diff --git a/tests/cron/test_cron_edit_deadlines.py b/tests/cron/test_cron_edit_deadlines.py
new file mode 100644
index 000000000..abe679460
--- /dev/null
+++ b/tests/cron/test_cron_edit_deadlines.py
@@ -0,0 +1,66 @@
+"""Editing task instructions must not postpone or drop an existing occurrence."""
+
+from dataclasses import replace
+
+import pytest
+
+from nanobot.cron.service import CronService
+from nanobot.cron.types import CronJob, CronSchedule
+
+
[email protected]("kind", ["every", "cron", "at"])
[email protected]("resend_schedule", [False, True])
+async def test_metadata_edit_preserves_due_occurrence(tmp_path, monkeypatch, kind, resend_schedule):
+ now = 1_900_000_000_000
+ monkeypatch.setattr("nanobot.cron.service._now_ms", lambda: now)
+ schedules = {
+ "every": CronSchedule(kind="every", every_ms=60_000),
+ "cron": CronSchedule(kind="cron", expr="* * * * *", tz="UTC"),
+ "at": CronSchedule(kind="at", at_ms=now + 60_000),
+ }
+ store_path = tmp_path / "cron" / "jobs.json"
+ service = CronService(store_path)
+ job = service.add_job(
+ name="Daily report",
+ schedule=schedules[kind],
+ message="Summarize yesterday",
+ session_key="websocket:report",
+ origin_channel="websocket",
+ origin_chat_id="report",
+ delete_after_run=kind == "at",
+ )
+ due_at = job.state.next_run_at_ms
+ assert due_at is not None
+ now = due_at + 1_000
+
+ updated = service.update_job(
+ job.id,
+ name="Updated report",
+ message="Include the latest figures",
+ schedule=replace(job.schedule) if resend_schedule else None,
+ )
+ assert isinstance(updated, CronJob)
+ assert updated.state.next_run_at_ms == due_at
+
+ calls = []
+
+ async def execute(job):
+ calls.append((job.id, job.name, job.payload.message))
+
+ # A separate service consumes the persisted edit, as the gateway does.
+ reader = CronService(store_path, on_job=execute)
+ loaded = reader.get_job(job.id)
+ assert loaded is not None
+ assert loaded.state.next_run_at_ms == due_at
+ await reader._on_timer()
+ await reader._on_timer()
+ assert calls == [(job.id, "Updated report", "Include the latest figures")]
+
+ finished = reader.get_job(job.id)
+ if kind == "at":
+ assert finished is None
+ else:
+ assert finished is not None
+ assert finished.state.next_run_at_ms > now
+ assert len(finished.state.run_history) == 1
+ assert finished.state.last_status == "ok"