Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(cron): preserve schedules edited during execution
fhgffya3ead61580aa
diff --git a/nanobot/cron/service.py b/nanobot/cron/service.pyindex 399b2cf03..c76b75e68 100644--- a/nanobot/cron/service.py+++ b/nanobot/cron/service.py@@ -6,7 +6,7 @@ import timeimport uuidfrom contextlib import suppressfrom copy import deepcopy-from dataclasses import asdict+from dataclasses import asdict, replacefrom datetime import datetimefrom pathlib import Pathfrom types import EllipsisType@@ -604,6 +604,7 @@ class CronService:async def _execute_job(self, job: CronJob) -> None:"""Execute a single job."""+ schedule = job.schedulestart_ms = _now_ms()logger.info("Cron: executing job '{}' ({})", job.name, job.id)result: str | CronRunResult | None = None@@ -646,6 +647,10 @@ class CronService:))job.state.run_history = job.state.run_history[-self._MAX_RUN_HISTORY:]+ # Completion belongs to the schedule that started this run.+ if job.schedule is not schedule:+ return+# Handle one-shot jobsif job.schedule.kind == "at":if job.delete_after_run:@@ -895,7 +900,8 @@ class CronService:schedule_changed = schedule is not None and schedule != job.scheduleif schedule is not None:_validate_schedule_for_add(schedule)- job.schedule = schedule+ if schedule_changed:+ job.schedule = replace(schedule)if name is not None:job.name = nameif message is not None:diff --git a/tests/cron/test_cron_edit_deadlines.py b/tests/cron/test_cron_edit_deadlines.pyindex abe679460..4ea8df32e 100644--- a/tests/cron/test_cron_edit_deadlines.py+++ b/tests/cron/test_cron_edit_deadlines.py@@ -1,6 +1,8 @@"""Editing task instructions must not postpone or drop an existing occurrence."""+import asynciofrom dataclasses import replace+from pathlib import Pathimport pytest@@ -64,3 +66,79 @@ async def test_metadata_edit_preserves_due_occurrence(tmp_path, monkeypatch, kinassert finished.state.next_run_at_ms > nowassert len(finished.state.run_history) == 1assert finished.state.last_status == "ok"++[email protected]("original_kind,delete_after_run", [("at", False), ("at", True), ("every", False)])[email protected]("replacement_kind", ["at", "every"])[email protected]("roundtrip", [False, True])+async def test_reschedule_during_execution_preserves_new_occurrence(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ original_kind: str,+ delete_after_run: bool,+ replacement_kind: str,+ roundtrip: bool,+) -> None:+ now = 1_900_000_000_000+ monkeypatch.setattr("nanobot.cron.service._now_ms", lambda: now)+ entered = asyncio.Event()+ release = asyncio.Event()+ calls: list[str] = []++ async def execute(job: CronJob) -> None:+ calls.append(job.id)+ entered.set()+ await release.wait()++ service = CronService(tmp_path / "cron" / "jobs.json", on_job=execute)+ original = (+ CronSchedule(kind="at", at_ms=now + 60_000)+ if original_kind == "at"+ else CronSchedule(kind="every", every_ms=60_000)+ )+ job = service.add_job(+ name="Report",+ schedule=original,+ message="Summarize the latest figures",+ session_key="websocket:report",+ origin_channel="websocket",+ origin_chat_id="report",+ delete_after_run=delete_after_run,+ )+ pending = asyncio.create_task(service.run_job(job.id))+ try:+ async with asyncio.timeout(2):+ await entered.wait()+ replacement = (+ CronSchedule(kind="at", at_ms=now + 120_000)+ if replacement_kind == "at"+ else CronSchedule(kind="every", every_ms=120_000)+ )+ updated = service.update_job(job.id, schedule=replacement)+ assert isinstance(updated, CronJob)+ if roundtrip:+ now += 5_000+ replacement = original+ updated = service.update_job(job.id, schedule=original)+ assert isinstance(updated, CronJob)+ next_run = updated.state.next_run_at_ms+ assert next_run is not None+ now += 10_000+ release.set()+ assert await pending+ finally:+ release.set()+ await asyncio.gather(pending, return_exceptions=True)++ restored = CronService(service.store_path, on_job=execute)+ saved = restored.get_job(job.id)+ assert saved is not None+ assert saved.enabled+ assert saved.schedule == replacement+ assert saved.state.next_run_at_ms == next_run+ assert saved.state.last_status == "ok"+ assert len(saved.state.run_history) == 1++ now = next_run+ await restored._on_timer()+ assert calls == [job.id, job.id]