diff --git a/changes/413.fixed.md b/changes/413.fixed.md new file mode 100644 index 000000000..5e0a3a693 --- /dev/null +++ b/changes/413.fixed.md @@ -0,0 +1 @@ +**Pausing a task stops planning and ignores in-flight watch checks.** Pausing a task while it is being planned now stops before the next model call and leaves a note to resume, resuming picks up planning where it left off. A running watch check that finishes while its task is paused no longer starts an unexpected run. diff --git a/sentient/tasks/repo.py b/sentient/tasks/repo.py index ac2a0f597..7fbb1ea4d 100644 --- a/sentient/tasks/repo.py +++ b/sentient/tasks/repo.py @@ -122,7 +122,9 @@ async def update_task(self, task_id: str, fields: dict) -> None: sets = ", ".join(f"{k} = ?" for k in data) await self.store.execute(f"UPDATE tasks SET {sets} WHERE id = ?", (*data.values(), task_id)) - async def update_task_if_status(self, task_id: str, statuses: set[str] | list[str], fields: dict) -> bool: + async def update_task_if_status( + self, task_id: str, statuses: set[str] | list[str], fields: dict, *, enabled: bool | None = None + ) -> bool: """Update only while the task is still in one of ``statuses`` (guards background jobs against user actions that happened meanwhile). Returns True when a row changed.""" data = {k: v for k, v in fields.items() if k in TASK_COLUMNS} @@ -135,9 +137,12 @@ async def update_task_if_status(self, task_id: str, statuses: set[str] | list[st wanted = list(statuses) sets = ", ".join(f"{k} = ?" for k in data) marks = ", ".join("?" for _ in wanted) - cur = await self.store.execute( - f"UPDATE tasks SET {sets} WHERE id = ? AND status IN ({marks})", (*data.values(), task_id, *wanted) - ) + where = f"WHERE id = ? AND status IN ({marks})" + params = [*data.values(), task_id, *wanted] + if enabled is not None: + where += " AND enabled = ?" + params.append(1 if enabled else 0) + cur = await self.store.execute(f"UPDATE tasks SET {sets} {where}", tuple(params)) return bool(getattr(cur, "rowcount", 1)) async def delete_task(self, task_id: str) -> None: diff --git a/sentient/tasks/service.py b/sentient/tasks/service.py index 0ad7e9b3d..34821d60c 100644 --- a/sentient/tasks/service.py +++ b/sentient/tasks/service.py @@ -222,6 +222,7 @@ def __init__(self, app: Any): self._runs: dict[str, asyncio.Task] = {} self._cancel_requested: set[str] = set() self._holding: set[str] = set() # runs whose task was paused: they stop at their next safe point (#408) + self._paused_scripts: set[str] = set() # watch checks whose task was paused: they don't start a run self._locks: dict[str, asyncio.Lock] = {} self._sem: asyncio.Semaphore | None = None self._bus_subscription: Any = None @@ -742,6 +743,7 @@ async def update(self, task_id: str, fields: dict, *, reapprove_script: bool = F if resuming: for run in await self.repo.processing_runs(task_id): # resumed before it reached a safe point: it goes on self._holding.discard(run["id"]) + self._paused_scripts.discard(task_id) await self._carry_on(task_id, held) if needs_approval: await self.publish(task_id) @@ -896,7 +898,7 @@ async def run_now(self, task_id: str) -> dict: if task.get("task_type") == "script": if not self._runnable(task): raise TaskConflict("Task has no check script to run.") - await self._start_script(task) + await self._start_script(task, manual=True) return await self.get_and_publish(task_id) if not task.get("plan"): raise TaskConflict("Task has no plan to run.") @@ -1525,11 +1527,19 @@ def _waits_on_approval(run: dict) -> bool: async def _pause_work(self, task_id: str) -> None: """The user paused the task (#408): a run working right now stops at its next safe point, before its next model or tool call, never in the middle of one (``holding``, ``_held_by_pause``), and a run waiting on an - approval is held at once. Both end like work a restart held (#304). A swarm's run, and a one-call run whose + approval is held at once. Both end like work a restart held (#304). A task being planned stays in planning + with the note, and a running check script does not start a run. A swarm's run, and a one-call run whose call already started, can't stop part-way: they finish, and their log says so.""" task = await self.repo.get_task(task_id) if task is None: return + if task["status"] == "planning": + if task.get("error") != PLAN_PAUSED_NOTE: + await self._set(task_id, {"error": PLAN_PAUSED_NOTE}) + await self.publish(task_id) + return + if self._job_running("script", task_id): + self._paused_scripts.add(task_id) for run in await self.repo.processing_runs(task_id): live = self._runs.get(run["id"]) if live is None or live.done(): @@ -1650,9 +1660,28 @@ async def _refine(self, prompt: str) -> dict: "schedule": schedule, } - async def _refine_and_plan(self, task_id: str, *, auto_approve: bool = False) -> None: + async def _planning_paused(self, task_id: str) -> bool: + """True when the task is not in planning or has been paused: leaves the note and stops planning (#405).""" task = await self.repo.get_task(task_id) if task is None or task["status"] != "planning": + return True + if not task["enabled"]: + if task.get("error") != PLAN_PAUSED_NOTE: + await self._set(task_id, {"error": PLAN_PAUSED_NOTE}) + await self.publish(task_id) + return True + if task.get("error") == PLAN_PAUSED_NOTE: + await self._set(task_id, {"error": None}) + await self.publish(task_id) + return False + + async def _refine_and_plan(self, task_id: str, *, auto_approve: bool = False) -> None: + if await self._planning_paused(task_id): + return + task = await self.repo.get_task(task_id) + if task is None or task["status"] != "planning" or not task.get("enabled", True): + if task is not None and not task.get("enabled", True): + await self._planning_paused(task_id) return prompt = task.get("original_prompt") or task.get("description") or task.get("name") or "" try: @@ -1662,6 +1691,8 @@ async def _refine_and_plan(self, task_id: str, *, auto_approve: bool = False) -> details = {"schedule": spoken_schedule(normalize_schedule(None, self.tz_name()), prompt)} await self._set(task_id, details) await self.publish(task_id) + if await self._planning_paused(task_id): + return await self._plan_job(task_id, auto_approve=auto_approve) async def _plan_job(self, task_id: str, *, auto_approve: bool = False) -> None: @@ -1676,16 +1707,19 @@ async def _plan_job(self, task_id: str, *, auto_approve: bool = False) -> None: async def _plan_failed(self, task_id: str, error: str) -> None: task = await self.repo.get_task(task_id) - if task is None or task["status"] != "planning": - return # the user declined/archived/edited it meanwhile + if task is None or task["status"] != "planning" or not task["enabled"]: + return # the user declined/archived/edited/paused it meanwhile if not await self.repo.update_task_if_status( - task_id, {"planning"}, {"status": "error", "error": error, "updated_at": self.now_iso()} + task_id, {"planning"}, {"status": "error", "error": error, "updated_at": self.now_iso()}, enabled=True ): - return # changed while we were failing + await self._planning_paused(task_id) + return # changed or paused while we were failing await self.publish(task_id) await self._notify(task, f"I couldn't create a plan for '{task.get('name')}'. {error}", "Planning failed", "planning_failed") async def _plan(self, task_id: str, *, auto_approve: bool = False) -> None: + if await self._planning_paused(task_id): + return task = await self.repo.get_task(task_id) if task is None or task["status"] != "planning" or task.get("task_type") == "swarm": return @@ -1725,14 +1759,20 @@ async def _plan(self, task_id: str, *, auto_approve: bool = False) -> None: parts.append("Answers to your clarifying questions:\n" + "\n".join( f"- Q: {q.get('text')}\n A: {q.get('answer')}" for q in answered )) + if await self._planning_paused(task_id): + return data = await complete_json_object(self.app.llm, "planner", [{"role": "system", "content": system}, {"role": "user", "content": "\n\n".join(parts)}], keys=("plan", "steps", "clarifying_questions"), ) + if await self._planning_paused(task_id): + return if not isinstance(data, dict): raise TypeError(f"Planner agent returned invalid JSON: {str(data)[:200]}") script, data, script_tools = await self._planned_script(task, data, system, parts) + if await self._planning_paused(task_id): + return no_script = script_tools is not None raw_plan = data.get("plan") or data.get("steps") if raw_plan is None and data.get("tool"): # a lone step object @@ -1742,6 +1782,8 @@ async def _plan(self, task_id: str, *, auto_approve: bool = False) -> None: plan = self._no_script_plan(task, script_tools, plan) new_questions = normalize_questions(data.get("clarifying_questions"), start=len(questions) if answered else 0) + if await self._planning_paused(task_id): + return current = await self.repo.get_task(task_id) if current is None or current["status"] != "planning": return # deleted or changed while the model was thinking @@ -1755,8 +1797,10 @@ async def _plan(self, task_id: str, *, auto_approve: bool = False) -> None: if not await self.repo.update_task_if_status( task_id, {"planning"}, {"status": "clarification_pending", "clarifying_questions": merged, "updated_at": self.now_iso()}, + enabled=True, ): - return # declined, archived or edited while the planner was running + await self._planning_paused(task_id) + return # declined, archived, paused or edited while the planner was running await self.publish(task_id) await self._notify( task, f"I need a bit more information to plan '{display_name}'. Please answer the questions in the task.", @@ -1800,8 +1844,13 @@ async def _plan(self, task_id: str, *, auto_approve: bool = False) -> None: fields["name"] = name if str(data.get("description") or "").strip(): fields["description"] = str(data["description"]).strip() - if not await self.repo.update_task_if_status(task_id, {"planning"}, {**fields, "updated_at": self.now_iso()}): - return # declined, archived or edited while the planner was running + if await self._planning_paused(task_id): + return + if not await self.repo.update_task_if_status( + task_id, {"planning"}, {**fields, "updated_at": self.now_iso()}, enabled=True + ): + await self._planning_paused(task_id) + return # declined, archived, paused or edited while the planner was running # a plan written from someone's email, or from an MCP app's prompt, always waits for the # user's approval (#159, #443) if (auto_approve or not cfg.tasks.require_plan_approval) and not email_inbox.is_email_task(task) \ @@ -1841,6 +1890,8 @@ async def _planned_script( script = normalize_script(raw, previous, model_written=True, request=request) return self._default_condition(task, script), data, None except ScriptInvalid as exc: + if await self._planning_paused(task["id"]): + return previous, data, None log.info("planner script for task %s rejected, asking for a fix: %s", task["id"], exc) retry = [*parts, ( f"Your previous reply included this `script` code:\n```python\n{str(raw.get('code'))[:4000]}\n```\n" @@ -1852,6 +1903,8 @@ async def _planned_script( [{"role": "system", "content": system}, {"role": "user", "content": "\n\n".join(retry)}], keys=("plan", "steps", "clarifying_questions"), ) + if await self._planning_paused(task["id"]): + return previous, data, None if not isinstance(fixed, dict): raise TypeError(f"Planner agent returned invalid JSON: {str(fixed)[:200]}") codes = [str(raw.get("code"))] @@ -2385,9 +2438,9 @@ async def _publish_run_finished(self, task_id: str, run_id: str, status: str) -> log.exception("could not publish task.run_finished for run %s", run_id) # ------------------------------------------------------------------ script jobs - async def _start_script(self, task: dict, *, trigger_data: dict | None = None) -> None: + async def _start_script(self, task: dict, *, trigger_data: dict | None = None, manual: bool = False) -> None: await self._set(task["id"], {"status": "processing", "last_execution_at": self.now_iso(), "error": None}) - self._spawn(self._script_job(task["id"], trigger_data), f"script:{task['id']}") + self._spawn(self._script_job(task["id"], trigger_data, manual=manual), f"script:{task['id']}") def _script_tool_names(self) -> list[str]: return [ @@ -2414,10 +2467,10 @@ async def _sandbox_run(self, code: str, trigger_data: dict | None = None) -> dic return {**SANDBOX_RESULT, "error": "the code runner returned an unexpected result"} return {**SANDBOX_RESULT, **out} - async def _script_job(self, task_id: str, trigger_data: dict | None) -> None: + async def _script_job(self, task_id: str, trigger_data: dict | None, *, manual: bool = False) -> None: try: async with self._lock(task_id): - await self._script_check(task_id, trigger_data) + await self._script_check(task_id, trigger_data, manual=manual) except asyncio.CancelledError: if self.app.stopped: # Stop everything: settle the task now (a shutdown leaves it to recovery) await self._after_run(task_id, "cancelled", None) @@ -2427,6 +2480,24 @@ async def _script_job(self, task_id: str, trigger_data: dict | None) -> None: log.exception("script job %s crashed", task_id) await self._after_run(task_id, "error", "The check script could not be run.") await self.publish(task_id) + finally: + self._paused_scripts.discard(task_id) + + def _script_paused(self, task_id: str, current: dict | None, manual: bool) -> bool: + if manual: + return False + return task_id in self._paused_scripts or not bool((current or {}).get("enabled", True)) + + async def _stale_check(self, task_id: str, original: dict) -> dict | None: + """Returns the current task, or None if the task is gone or its check settings changed while running.""" + current = await self.repo.get_task(task_id) + if current is None or current.get("task_type") != "script" or _check_settings(current) != _check_settings(original): + # the user changed the check while it ran (or while the model judged it): drop this stale decision, the + # next check decides with the new settings + await self._after_run(task_id, "completed", None) + await self.publish(task_id) + return None + return current async def _save_script_state(self, task_id: str, code: str, state: dict) -> None: """Store check state unless the code was edited while the check ran (that resets the state).""" @@ -2439,16 +2510,18 @@ async def _save_script_state(self, task_id: str, code: str, state: dict) -> None script.update(state) await self._set(task_id, {"script": script}) - async def _script_check(self, task_id: str, trigger_data: dict | None) -> None: + async def _script_check(self, task_id: str, trigger_data: dict | None, *, manual: bool = False) -> None: """One check: run the code with no model, act on the condition, record state, settle the task.""" task = await self.repo.get_task(task_id) if task is None or task.get("task_type") != "script": return + if manual: + self._paused_scripts.discard(task_id) script = dict(task.get("script") or {}) code = str(script.get("code") or "") name = task.get("name") or "Untitled task" if reason := await self._missing_source(task, trigger_data): - await self._check_source_missing(task, script, code, reason) # its checklist decides (#161) + await self._check_source_missing(task, script, code, reason, manual=manual) # its checklist decides (#161) return outcome = await self._sandbox_run(code, trigger_data) now = self.now_iso() @@ -2459,7 +2532,8 @@ async def _script_check(self, task_id: str, trigger_data: dict | None) -> None: await self._save_script_state(task_id, code, {"last_run_at": now, "last_error": error, "checks": checks}) await self._after_run(task_id, "error", error) await self.publish(task_id) - if not previous_error: # tell once; recovery is announced below + current = await self.repo.get_task(task_id) or task + if not previous_error and not self._script_paused(task_id, current, manual): # tell once; recovery is announced below await self._notify( task, f"The check for '{name}' failed. {error}\n\nI'll keep checking on schedule and tell you when it works again.", "Check failed", "script_failed", @@ -2471,18 +2545,22 @@ async def _script_check(self, task_id: str, trigger_data: dict | None) -> None: act = scripts.should_act(condition, value, previous) message = scripts.alert_message(name, condition, value) if act else "" outcome_name, note = self._check_outcome(condition, act, value, previous) + current = await self._stale_check(task_id, task) + if current is None: + return + paused = self._script_paused(task_id, current, manual) if act and condition == "noteworthy": # something changed: the fast model judges whether it matters - act, change = await self._judge_change(task, previous, value) - outcome_name, note = ("changed", change) if act else ("minor", change) - if act and change: - message = change - current = await self.repo.get_task(task_id) - if current is None or current.get("task_type") != "script" or _check_settings(current) != _check_settings(task): - # the user changed the check while it ran (or while the model judged it): drop this stale decision, the - # next check decides with the new settings - await self._after_run(task_id, "completed", None) - await self.publish(task_id) + if paused: + act = False + else: + act, change = await self._judge_change(task, previous, value) + outcome_name, note = ("changed", change) if act else ("minor", change) + if act and change: + message = change + current = await self._stale_check(task_id, task) + if current is None: return + paused = paused or self._script_paused(task_id, current, manual) state: dict[str, Any] = { "last_run_at": now, "last_error": None, "checks": scripts.add_check(script.get("checks"), outcome_name, now, note), @@ -2490,21 +2568,31 @@ async def _script_check(self, task_id: str, trigger_data: dict | None) -> None: if value is not None or condition not in scripts.COMPARING: # an empty result keeps the baseline state["last_result"] = value await self._save_script_state(task_id, code, state) - if previous_error: + current = await self._stale_check(task_id, task) + if current is None: + return + paused = paused or self._script_paused(task_id, current, manual) + if previous_error and not paused: await self._notify(task, f"The check for '{name}' is working again.", "Check recovered", "script_recovered") - if act: - if script.get("then") == "run": - context: dict[str, Any] = {"script_result": value, "message": message} - if trigger_data: - context["trigger_event"] = trigger_data - fresh = await self.repo.get_task(task_id) or task - await self._start_run(fresh, trigger_data=context, next_execution_at=_KEEP) - else: - await self._notify(task, message, name, "script_alert", {"result": value}) + current = await self.repo.get_task(task_id) or current + paused = paused or self._script_paused(task_id, current, manual) + if act and not paused: + fresh = await self.repo.get_task(task_id) or current + if not self._script_paused(task_id, fresh, manual): + if script.get("then") == "run": + context: dict[str, Any] = {"script_result": value, "message": message} + if trigger_data: + context["trigger_event"] = trigger_data + await self._start_run(fresh, trigger_data=context, next_execution_at=_KEEP) + else: + await self._notify(task, message, name, "script_alert", {"result": value}) + self._paused_scripts.discard(task_id) await self._after_run(task_id, "completed", None) await self.publish(task_id) - async def _check_source_missing(self, task: dict, script: dict, code: str, reason: str) -> None: + async def _check_source_missing( + self, task: dict, script: dict, code: str, reason: str, *, manual: bool = False + ) -> None: """A check script's page (or app, or folder) isn't there (#161): the check is ``skipped`` in its history, and the checklist's ``if_missing`` decides the rest, as for a run: nothing more, a notification, or an earlier check (``tasks.source_retry_minutes`` from now, at most ``tasks.source_retries`` in a row, then a notice). A @@ -2539,7 +2627,8 @@ async def _check_source_missing(self, task: dict, script: dict, code: str, reaso if current.get("status") == "active" and due is not None and sooner < due: await self._set(task_id, {"next_execution_at": iso(sooner)}) await self.publish(task_id) - if tell: + current = await self.repo.get_task(task_id) or task + if tell and not self._script_paused(task_id, current, manual): await self._tell_missing(task, error, reason, policy) @staticmethod diff --git a/tests/tasks/test_pause_stops_run.py b/tests/tasks/test_pause_stops_run.py index a2c67f994..294154b87 100644 --- a/tests/tasks/test_pause_stops_run.py +++ b/tests/tasks/test_pause_stops_run.py @@ -13,10 +13,11 @@ from sentient.tasks import ask from sentient.tasks.prompts import PAUSE_RESUMED_NOTE -from sentient.tasks.service import CALL_FINISHES_NOTE, PAUSED_NOTE +from sentient.tasks.scripts import normalize_script +from sentient.tasks.service import CALL_FINISHES_NOTE, PAUSED_NOTE, PLAN_PAUSED_NOTE from sentient.tools.base import Risk, ToolContext, ToolPlugin, tool from tests.conftest import FakeProvider -from tests.tasks.conftest import RESULT, GatedProvider, stream_calls +from tests.tasks.conftest import PLAN_FILES, REFINE_ONCE, RESULT, GatedProvider, stream_calls def write(name: str, n: int) -> list[dict]: @@ -207,3 +208,303 @@ async def test_a_question_to_the_user_keeps_waiting_when_paused(make_app): await app.tasks.update(task_id, {"enabled": False}) task = await app.tasks.get(task_id) assert task["status"] == "waiting_for_user" and task["runs"][-1]["status"] == "waiting_for_user" + + +class GatedJsonProvider(FakeProvider): + def __init__(self, *args, block_on_call: int | None = None, **kwargs): + super().__init__(*args, **kwargs) + self.block_on_call = block_on_call + self.json_call_count = 0 + self.gate = asyncio.Event() + self.blocked = asyncio.Event() + + async def complete_json(self, role, messages, *, model=None): + self.json_call_count += 1 + if self.block_on_call is not None and self.json_call_count == self.block_on_call: + self.blocked.set() + await self.gate.wait() + return await super().complete_json(role, messages, model=model) + + +async def test_pausing_a_task_being_planned_stops_before_the_next_model_call_and_resume_plans_it(make_app): + # Call 1 is refine, call 2 is planner. Block on call 1. + llm = GatedJsonProvider(json_replies=[REFINE_ONCE, PLAN_FILES], block_on_call=1) + app = await make_app(llm) + task = await app.tasks.create_task("Save notes to a.txt") + task_id = task["task_id"] + await asyncio.wait_for(llm.blocked.wait(), 5) + + # Pausing while refine is in flight leaves the task in planning with PLAN_PAUSED_NOTE + task = await app.tasks.update(task_id, {"enabled": False}) + assert task["status"] == "planning" and not task["enabled"] + assert task["error"] == PLAN_PAUSED_NOTE + + # Unblock call 1: the planner checks if the task is paused before its next model call (call 2) + llm.gate.set() + await app.tasks.drain() + + # No second model call was made! + assert len(llm.calls) == 1 + task = await app.tasks.get(task_id) + assert task["status"] == "planning" and not task["enabled"] + assert task["error"] == PLAN_PAUSED_NOTE + + # Resuming the task carries on planning it + task = await app.tasks.update(task_id, {"enabled": True}) + await app.tasks.drain() + assert len(llm.calls) == 2 + task = await app.tasks.get(task_id) + assert task["status"] == "approval_pending" and task["enabled"] + assert task["error"] is None + assert task["plan"] + + +async def test_pausing_during_planner_call_stops_and_leaves_task_in_planning(make_app): + # Call 1 is refine, call 2 is planner. Block on call 2 (planner in flight). + llm = GatedJsonProvider(json_replies=[REFINE_ONCE, PLAN_FILES, PLAN_FILES], block_on_call=2) + app = await make_app(llm) + task = await app.tasks.create_task("Save notes to a.txt") + task_id = task["task_id"] + await asyncio.wait_for(llm.blocked.wait(), 5) + + # Call 2 is in flight: pause now + task = await app.tasks.update(task_id, {"enabled": False}) + assert task["status"] == "planning" and not task["enabled"] + + # Release call 2: planner returns, but seeing task is paused, leaves it in planning + llm.gate.set() + await app.tasks.drain() + + task = await app.tasks.get(task_id) + assert task["status"] == "planning" and not task["enabled"] + assert task["error"] == PLAN_PAUSED_NOTE + + # Resuming plans it + task = await app.tasks.update(task_id, {"enabled": True}) + await app.tasks.drain() + task = await app.tasks.get(task_id) + assert task["status"] == "approval_pending" and task["enabled"] and task["plan"] + assert task["error"] is None + + +async def test_watch_check_finishing_on_paused_task_does_not_start_a_run(make_app): + llm = FakeProvider(replies=["Logged price."], json_replies=[dict(RESULT)]) + app = await make_app(llm) + + started = asyncio.Event() + release = asyncio.Event() + + async def slow_sandbox(*args, **kwargs): + started.set() + await release.wait() + return {"ok": True, "result": {"price": 90}} + + app.sandbox.run = slow_sandbox + script = normalize_script({"code": "result({'price': 90})", "condition": "changed", "then": "run"}) + schedule = {"type": "recurring", "frequency": "interval", "interval_minutes": 60, "timezone": "UTC"} + now = app.tasks.now_iso() + task_id = await app.tasks.repo.insert_task({ + "name": "Price watch", "description": "Watch price", "status": "active", + "task_type": "script", "script": {**script, "last_result": {"price": 100}}, + "schedule": schedule, "plan": [{"tool": "files", "description": "Log price"}], + "created_at": now, "updated_at": now, "enabled": True, + }) + + # The check starts running in the background + task = await app.tasks.repo.get_task(task_id) + await app.tasks._start_script(task) + await asyncio.wait_for(started.wait(), 5) + + # While the check is in flight, the user pauses the task + await app.tasks.update(task_id, {"enabled": False}) + + # Release the check + release.set() + await app.tasks.drain() + + # The check finished, but because the task was paused, no run was started + task = await app.tasks.get(task_id) + assert task["runs"] == [] + assert not task["enabled"] + assert llm.calls == [] + + # "Run now" on a paused task still works as today because the user explicitly asked for it + async def fast_sandbox(*args, **kwargs): + return {"ok": True, "result": {"price": 80}} + + app.sandbox.run = fast_sandbox + await app.tasks.run_now(task_id) + await app.tasks.drain() + task = await app.tasks.get(task_id) + assert len(task["runs"]) == 1 + assert task["runs"][0]["status"] == "completed" + + +async def test_pause_before_plan_commit_leaves_task_in_planning(make_app): + """If the task is paused right before the plan is committed, enabled=True in update_task_if_status + prevents the commit/approval, leaving the task in planning with PLAN_PAUSED_NOTE.""" + llm = FakeProvider(json_replies=[REFINE_ONCE, PLAN_FILES]) + app = await make_app(llm) + task = await app.tasks.create_task("Save notes to a.txt") + task_id = task["task_id"] + + orig_update_if_status = app.tasks.repo.update_task_if_status + + async def update_with_pause(tid, statuses, fields, **kwargs): + if "plan" in fields: + # Simulate a concurrent pause right as the plan is being committed + await app.tasks.repo.update_task(tid, {"enabled": 0}) + return await orig_update_if_status(tid, statuses, fields, **kwargs) + + app.tasks.repo.update_task_if_status = update_with_pause + await app.tasks.drain() + + task = await app.tasks.get(task_id) + assert task["status"] == "planning" and not task["enabled"] + assert task["error"] == PLAN_PAUSED_NOTE + assert not task["plan"] + + +async def test_pause_during_save_script_state_does_not_start_a_run(make_app): + """Pausing during _save_script_state rechecks task pause state before deciding to act, + preventing any run or notification.""" + llm = FakeProvider(replies=["Logged price."], json_replies=[dict(RESULT)]) + app = await make_app(llm) + + orig_save = app.tasks._save_script_state + + async def save_with_pause(tid, code, state): + res = await orig_save(tid, code, state) + # User pauses while state was saving + await app.tasks.update(tid, {"enabled": False}) + return res + + app.tasks._save_script_state = save_with_pause + + async def fast_sandbox(*args, **kwargs): + return {"ok": True, "result": {"price": 90}} + + app.sandbox.run = fast_sandbox + script = normalize_script({"code": "result({'price': 90})", "condition": "changed", "then": "run"}) + schedule = {"type": "recurring", "frequency": "interval", "interval_minutes": 60, "timezone": "UTC"} + now = app.tasks.now_iso() + task_id = await app.tasks.repo.insert_task({ + "name": "Price watch", "description": "Watch price", "status": "active", + "task_type": "script", "script": {**script, "last_result": {"price": 100}}, + "schedule": schedule, "plan": [{"tool": "files", "description": "Log price"}], + "created_at": now, "updated_at": now, "enabled": True, + }) + + task = await app.tasks.repo.get_task(task_id) + await app.tasks._start_script(task) + await app.tasks.drain() + + task = await app.tasks.get(task_id) + assert task["runs"] == [] + assert not task["enabled"] + assert llm.calls == [] + + +async def test_paused_check_early_exit_error_does_not_notify(make_app): + """An in-flight check that errors on a paused task records the error in history but sends no notification.""" + app = await make_app() + + started = asyncio.Event() + release = asyncio.Event() + + async def slow_sandbox(*args, **kwargs): + started.set() + await release.wait() + return {"ok": False, "error": "Endpoint 500 error"} + + app.sandbox.run = slow_sandbox + script = normalize_script({"code": "fetch()", "condition": "alert", "then": "notify"}) + schedule = {"type": "recurring", "frequency": "interval", "interval_minutes": 60, "timezone": "UTC"} + now = app.tasks.now_iso() + task_id = await app.tasks.repo.insert_task({ + "name": "Error watch", "description": "Watch endpoint", "status": "active", + "task_type": "script", "script": script, + "schedule": schedule, "plan": [], + "created_at": now, "updated_at": now, "enabled": True, + }) + + task = await app.tasks.repo.get_task(task_id) + await app.tasks._start_script(task) + await asyncio.wait_for(started.wait(), 5) + + # User pauses while check is running + await app.tasks.update(task_id, {"enabled": False}) + + release.set() + await app.tasks.drain() + + task = await app.tasks.get(task_id) + assert not task["enabled"] + assert "Endpoint 500 error" in task["script"]["last_error"] + notes = [n for n in await app.notifications.list() if (n.get("payload") or {}).get("event") == "script_failed"] + assert notes == [] + + +async def test_pause_during_recovery_notification_does_not_start_a_run(make_app): + """If a task is paused while its 'working again' recovery notification is in flight, + it must not start a run or send alerts on the paused task.""" + llm = FakeProvider(replies=["Logged price."], json_replies=[dict(RESULT)]) + app = await make_app(llm) + + orig_notify = app.tasks._notify + + async def notify_with_pause(task, message, title, event, *args, **kwargs): + if event == "script_recovered": + # Simulate user pausing during the recovery notification + await app.tasks.update(task["id"], {"enabled": False}) + return await orig_notify(task, message, title, event, *args, **kwargs) + + app.tasks._notify = notify_with_pause + + async def fast_sandbox(*args, **kwargs): + return {"ok": True, "result": {"price": 90}} + + app.sandbox.run = fast_sandbox + script = normalize_script({"code": "result({'price': 90})", "condition": "changed", "then": "run"}) + schedule = {"type": "recurring", "frequency": "interval", "interval_minutes": 60, "timezone": "UTC"} + now = app.tasks.now_iso() + task_id = await app.tasks.repo.insert_task({ + "name": "Price watch", "description": "Watch price", "status": "active", + "task_type": "script", "script": {**script, "last_result": {"price": 100}, "last_error": "failed previously"}, + "schedule": schedule, "plan": [{"tool": "files", "description": "Log price"}], + "created_at": now, "updated_at": now, "enabled": True, + }) + + task = await app.tasks.repo.get_task(task_id) + await app.tasks._start_script(task) + await app.tasks.drain() + + task = await app.tasks.get(task_id) + assert not task["enabled"] + assert task["runs"] == [] + assert llm.calls == [] + + +async def test_pause_before_refine_leaves_task_in_planning(make_app): + """If a task is paused right as refinement starts, checking enabled on the fetched task + prevents model calls, leaving the task in planning with PLAN_PAUSED_NOTE.""" + llm = FakeProvider(json_replies=[REFINE_ONCE, PLAN_FILES]) + app = await make_app(llm) + + orig_get_task = app.tasks.repo.get_task + + async def get_task_with_pause(tid): + task = await orig_get_task(tid) + if task and task["status"] == "planning" and task["enabled"]: + await app.tasks.repo.update_task(tid, {"enabled": 0}) + task["enabled"] = 0 + return task + + app.tasks.repo.get_task = get_task_with_pause + task = await app.tasks.create_task("Save notes to a.txt") + await app.tasks.drain() + + task = await app.tasks.get(task["task_id"]) + assert task["status"] == "planning" and not task["enabled"] + assert task["error"] == PLAN_PAUSED_NOTE + assert llm.calls == []