AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(platform): run a scheduled chat less often from its usage-limit note (#15400)
Nicholas Tindle46cf1bf4555d
diff --git a/autogpt_platform/backend/backend/api/features/experts/routines.py b/autogpt_platform/backend/backend/api/features/experts/routines.pyindex 365c5a38cf..a144528fed 100644--- a/autogpt_platform/backend/backend/api/features/experts/routines.py+++ b/autogpt_platform/backend/backend/api/features/experts/routines.py@@ -274,6 +274,15 @@ async def enable_routine(# without this the row would say PINNED and behave like FRESH. The tool# always supplies one; this closes the RPC path, which does not.raise ValueError("A PINNED routine needs the chat it should fire into.")+ # A THREAD routine that stays one keeps the thread its first fire minted,+ # through a new cadence or prompt: its jobs name no chat, since each fire+ # reads the row's, so the row is what has to keep it.+ thread = (+ row.sessionId+ if mode == prisma.enums.ExpertRoutineSession.THREAD+ and row.sessionMode == prisma.enums.ExpertRoutineSession.THREAD+ else None+ )schedule_ids = await create_routine_schedules(user_id=user_id,expert_id=expert_id,@@ -291,7 +300,7 @@ async def enable_routine("runAt": resolved_run_at,"scheduleIds": schedule_ids,"sessionMode": mode,- "sessionId": pinned,+ "sessionId": pinned or thread,"enabledAt": now,# Re-arming a spent one-shot makes it pending again; leaving the old# stamp would enable a row that still reads as already run.diff --git a/autogpt_platform/backend/backend/api/features/schedules/model.py b/autogpt_platform/backend/backend/api/features/schedules/model.pyindex eecb4719f8..ad65cf4530 100644--- a/autogpt_platform/backend/backend/api/features/schedules/model.py+++ b/autogpt_platform/backend/backend/api/features/schedules/model.py@@ -26,6 +26,13 @@ class ResumeScheduledChatResponse(pydantic.BaseModel):resumed: bool+class SetScheduledChatCadenceRequest(pydantic.BaseModel):+ cron: str = pydantic.Field(+ description="One of the cadences offered for this chat, as returned by "+ "getScheduledChatCadence"+ )++class ScheduleUpdateRequest(pydantic.BaseModel):"""Fields to change on an existing schedule; omitted fields keep their value."""diff --git a/autogpt_platform/backend/backend/api/features/schedules/routes.py b/autogpt_platform/backend/backend/api/features/schedules/routes.pyindex 09ed2da7f6..582ce6cbe9 100644--- a/autogpt_platform/backend/backend/api/features/schedules/routes.py+++ b/autogpt_platform/backend/backend/api/features/schedules/routes.py@@ -4,7 +4,12 @@ from typing import Annotated, Anyfrom autogpt_libs.auth import get_request_context, get_user_id, requires_userfrom autogpt_libs.auth.models import RequestContextfrom fastapi import APIRouter, Body, Depends, HTTPException, Path, Security-from starlette.status import HTTP_404_NOT_FOUND, HTTP_503_SERVICE_UNAVAILABLE+from starlette.status import (+ HTTP_400_BAD_REQUEST,+ HTTP_404_NOT_FOUND,+ HTTP_409_CONFLICT,+ HTTP_503_SERVICE_UNAVAILABLE,+)from backend.api.features.experts import experts_dbfrom backend.api.features.schedule_visibility import visible_graph_schedules@@ -12,9 +17,10 @@ from backend.api.features.schedules.model import (ResumeScheduledChatResponse,ScheduleCreationRequest,ScheduleUpdateRequest,+ SetScheduledChatCadenceRequest,)from backend.copilot.rate_limit import enforce_payment_paywall-from backend.copilot.scheduled_chats import forget+from backend.copilot.scheduled_chats import cadence_service, forgetfrom backend.copilot.scheduled_chats import service as scheduled_chatsfrom backend.data import graph as graph_dbfrom backend.data.onboarding import OnboardingStep, complete_onboarding_step@@ -217,6 +223,65 @@ async def resume_scheduled_chat(return ResumeScheduledChatResponse(resumed=True)+ path="/schedules/followups/{schedule_key}/cadence",+ summary="How often a scheduled chat runs, and how it could run less often",+ operation_id="getScheduledChatCadence",+)+async def get_scheduled_chat_cadence(+ user_id: Annotated[str, Security(get_user_id)],+ schedule_key: str = Path(+ ..., description="The routine's id, or the follow-up's schedule id"+ ),+) -> cadence_service.ScheduledChatCadence:+ try:+ return await cadence_service.get_cadence(user_id, schedule_key)+ except Exception as e:+ raise _cadence_error(e, schedule_key) from e+++ dependencies=[Depends(enforce_payment_paywall)],+ path="/schedules/followups/{schedule_key}/cadence",+ summary="Run a scheduled chat less often",+ operation_id="setScheduledChatCadence",+)+async def set_scheduled_chat_cadence(+ user_id: Annotated[str, Security(get_user_id)],+ body: SetScheduledChatCadenceRequest,+ schedule_key: str = Path(+ ..., description="The routine's id, or the follow-up's schedule id"+ ),+) -> cadence_service.ScheduledChatCadence:+ try:+ return await cadence_service.set_cadence(user_id, schedule_key, body.cron)+ except Exception as e:+ raise _cadence_error(e, schedule_key) from e+++def _cadence_error(error: Exception, schedule_key: str) -> HTTPException:+ if isinstance(error, cadence_service.CadenceNotOffered):+ return HTTPException(+ status_code=HTTP_400_BAD_REQUEST,+ detail="That cadence is not one this scheduled chat can switch to.",+ )+ if isinstance(error, cadence_service.CadenceNotFound):+ return HTTPException(+ status_code=HTTP_404_NOT_FOUND,+ detail="This scheduled chat has no cadence to change.",+ )+ if isinstance(error, cadence_service.ScheduledChatPaused):+ return HTTPException(+ status_code=HTTP_409_CONFLICT,+ detail="This scheduled chat is paused. Resume it first.",+ )+ logger.exception("Could not change the cadence of scheduled chat %s", schedule_key)+ return HTTPException(+ status_code=HTTP_503_SERVICE_UNAVAILABLE,+ detail="Its cadence could not be changed just now. Try again.",+ )++@router.delete(path="/schedules/{schedule_id}",summary="Delete execution schedule",diff --git a/autogpt_platform/backend/backend/api/features/schedules/routes_test.py b/autogpt_platform/backend/backend/api/features/schedules/routes_test.pyindex 9f4f6efd14..4ecb79b0de 100644--- a/autogpt_platform/backend/backend/api/features/schedules/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/schedules/routes_test.py@@ -11,6 +11,7 @@ from fastapi.routing import APIRoutefrom backend.api.features.schedules.routes import routerfrom backend.api.rest_api import app as real_app+from backend.copilot.scheduled_chats import cadence_servicefrom backend.copilot.scheduled_chats.service import PausedScheduledChatfrom backend.executor import schedulerfrom backend.util.exceptions import NotAuthorizedError, NotFoundError@@ -60,6 +61,14 @@ EXPECTED_OPERATIONS = {"post","/api/schedules/followups/{schedule_key}/resume",): "resumeScheduledChat",+ (+ "get",+ "/api/schedules/followups/{schedule_key}/cadence",+ ): "getScheduledChatCadence",+ (+ "post",+ "/api/schedules/followups/{schedule_key}/cadence",+ ): "setScheduledChatCadence",("delete", "/api/schedules/{schedule_id}"): "deleteV1Delete execution schedule",("patch", "/api/schedules/{schedule_id}"): "patchV1Update execution schedule",}@@ -363,6 +372,77 @@ def test_a_resume_the_scheduler_refuses_can_be_tried_again(assert response.status_code == 503+def _cadence(**overrides) -> cadence_service.ScheduledChatCadence:+ fields = dict(+ schedule_key="routine-1",+ title="Discord monitor",+ current="Every minute",+ timezone="America/Chicago",+ options=[+ cadence_service.CadenceOption(cron="0 * * * *", label="Every hour"),+ ],+ )+ fields.update(overrides)+ return cadence_service.ScheduledChatCadence(**fields)+++def test_get_cadence_offers_the_callers_chat_its_cadences(+ mocker: pytest_mock.MockFixture, test_user_id: str+) -> None:+ get = mocker.patch(+ "backend.api.features.schedules.routes.cadence_service.get_cadence",+ AsyncMock(return_value=_cadence()),+ )++ response = client.get("/schedules/followups/routine-1/cadence")++ assert response.status_code == 200+ assert response.json()["options"] == [{"cron": "0 * * * *", "label": "Every hour"}]+ get.assert_awaited_once_with(test_user_id, "routine-1")+++def test_set_cadence_applies_the_chosen_one(+ mocker: pytest_mock.MockFixture, test_user_id: str+) -> None:+ set_ = mocker.patch(+ "backend.api.features.schedules.routes.cadence_service.set_cadence",+ AsyncMock(return_value=_cadence(current="Every hour", options=[])),+ )++ response = client.post(+ "/schedules/followups/routine-1/cadence", json={"cron": "0 * * * *"}+ )++ assert response.status_code == 200+ assert response.json()["current"] == "Every hour"+ set_.assert_awaited_once_with(test_user_id, "routine-1", "0 * * * *")+++ ("error", "status"),+ [+ (cadence_service.CadenceNotOffered("* * * * *"), 400),+ (cadence_service.CadenceNotFound("routine-1"), 404),+ (cadence_service.ScheduledChatPaused("routine-1"), 409),+ (RuntimeError("scheduler down"), 503),+ ],+ ids=["not-offered", "not-found", "paused", "scheduler-down"],+)+def test_set_cadence_maps_each_refusal(+ mocker: pytest_mock.MockFixture, error: Exception, status: int+) -> None:+ mocker.patch(+ "backend.api.features.schedules.routes.cadence_service.set_cadence",+ AsyncMock(side_effect=error),+ )++ response = client.post(+ "/schedules/followups/routine-1/cadence", json={"cron": "* * * * *"}+ )++ assert response.status_code == status++def test_delete_schedule_maps_not_found_to_404(mocker: pytest_mock.MockFixture,) -> None:diff --git a/autogpt_platform/backend/backend/api/paywall_routes_test.py b/autogpt_platform/backend/backend/api/paywall_routes_test.pyindex a60f3d277e..fc28044764 100644--- a/autogpt_platform/backend/backend/api/paywall_routes_test.py+++ b/autogpt_platform/backend/backend/api/paywall_routes_test.py@@ -220,6 +220,7 @@ OPEN_WHILE_PAYWALLED = {"GET /api/schedules","GET /api/schedules/followups","GET /api/schedules/followups/paused",+ "GET /api/schedules/followups/{schedule_key}/cadence","GET /api/skill-learning/decisions","GET /api/skill-learning/history","GET /api/skill-learning/skills/{name}",diff --git a/autogpt_platform/backend/backend/copilot/executor/scheduled_turn_alert.py b/autogpt_platform/backend/backend/copilot/executor/scheduled_turn_alert.pyindex 9957f58ed3..95a37d0aa6 100644--- a/autogpt_platform/backend/backend/copilot/executor/scheduled_turn_alert.py+++ b/autogpt_platform/backend/backend/copilot/executor/scheduled_turn_alert.py@@ -99,11 +99,15 @@ class ScheduledTurnWatch:returnif not isinstance(chunk, StreamToolOutputAvailable):return+ # The CLI's own tools stay out, whatever they return: a missed Read or+ # Grep is the model probing, and a file it read can hold anything,+ # an error payload included.+ if not _ours(chunk.toolName):+ returnerror_type = tool_error_type(chunk.output)# A platform tool can also fail without an ErrorResponse payload (a- # login prompt, a held read, a plain-text error). The CLI's own tools- # stay out: a missed Read or Grep is the model probing, not a failure.- if error_type is None and not chunk.success and _ours(chunk.toolName):+ # login prompt, a held read, a plain-text error).+ if error_type is None and not chunk.success:error_type = UNCLASSIFIEDtool = chunk.toolName or "unknown"if error_type is not None:@@ -112,7 +116,7 @@ class ScheduledTurnWatch:error_type=UNCLASSIFIED, text_hash=text_hash(chunk.output))self._failure_details.append((tool, detail))- elif _ours(chunk.toolName) and chunk.toolName not in _LOOKUP_TOOLS:+ elif chunk.toolName not in _LOOKUP_TOOLS:self._tool_successes += 1def outcome(self, turn_error: str | None) -> RunOutcome:diff --git a/autogpt_platform/backend/backend/copilot/executor/scheduled_turn_alert_test.py b/autogpt_platform/backend/backend/copilot/executor/scheduled_turn_alert_test.pyindex a04fa94b4b..8eb94c12c2 100644--- a/autogpt_platform/backend/backend/copilot/executor/scheduled_turn_alert_test.py+++ b/autogpt_platform/backend/backend/copilot/executor/scheduled_turn_alert_test.py@@ -160,6 +160,24 @@ def test_a_compacted_history_is_not_work_done():assert outcome.failure is not None and outcome.whole_run+def test_a_cli_tool_that_returns_an_error_payload_is_not_a_failure():+ """Read can return a file that holds an ErrorResponse; that is the file,+ not the run failing."""+ watch = ScheduledTurnWatch.for_entry(_entry(_weekly()))+ assert watch is not None+ watch.observe(+ StreamToolOutputAvailable(+ toolCallId="c",+ toolName="Read",+ output=ErrorResponse(+ message="refused", error="credential_rejected"+ ).model_dump_json(),+ )+ )++ assert watch.tool_failures == []++def _looked_up(tool: str) -> StreamToolOutputAvailable:return StreamToolOutputAvailable(toolCallId=f"call-{tool}", toolName=tool, output='{"type": "capabilities"}'diff --git a/autogpt_platform/backend/backend/copilot/scheduled_chats/cadence.py b/autogpt_platform/backend/backend/copilot/scheduled_chats/cadence.pynew file mode 100644index 0000000000..a8462fb27e--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/scheduled_chats/cadence.py@@ -0,0 +1,283 @@+"""How often a scheduled chat runs, and the cadences that run it less often+(SECRT-2879).++A chat skipped because its owner's usage limit ran out has a way out besides+upgrading: run less often, so its runs fit the allowance. This counts how often+the schedule fires in a week and offers the rungs of a short ladder below that,+at a time the schedule already uses, and never more often on any day than it+runs now.++Crons are stored as Unix cron, and the scheduler hands them to APScheduler with+their weekdays renumbered. Two things still differ from Unix cron, and croniter+is told both, so it counts the fires the scheduler makes: APScheduler fires when+the day of the month and the day of the week both match, not either, and it+counts a step over every weekday from Monday. The cadences offered name their+weekdays (``mon-fri``), which both read the same way.++Fires are counted on the zone's clock as it stands now, at a fixed offset, so+the week the clocks change has no hour twice or missing: an hourly schedule+still runs 168 times a week, at the minute it always does.+"""++from datetime import datetime, timedelta+from datetime import timezone as fixed_offset+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError++from croniter import croniter+from pydantic import BaseModel++# Every rung of the ladder fires well under this many times a week, so a cron+# counted this far runs more often than all of them: stop there.+_COUNT_CAP = 1000+# The busiest rung runs this often a day: a day counted this far has room for+# every rung.+_BUSIEST_DAY = 96+_WEEK = timedelta(days=7)+_DAY = timedelta(days=1)+_DAYS = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")+_DAY_NAMES = (+ "Monday",+ "Tuesday",+ "Wednesday",+ "Thursday",+ "Friday",+ "Saturday",+ "Sunday",+)+# A schedule with a handful of times a day keeps one of them; anything busier+# gets a once-a-day time at the start of a working day.+_FEW_TIMES = 4+_MORNING_HOUR = 9+# Where a day's times start: a 06:00 run comes before a 00:30 one.+_DAY_STARTS = (6, 0)+_HOURLY = 7 * 24+++class Cadence(BaseModel):+ cron: str+ label: str+ # Monday first.+ runs_per_day: list[int]++ @property+ def runs_per_week(self) -> int:+ return sum(self.runs_per_day)+++def less_often(crons: list[str], timezone: str, now: datetime) -> list[Cadence]:+ """The cadences that run the schedule less often, most often first.++ Empty when there is nothing to offer: a one-off, a schedule that fires+ once a week or less, or crons that do not parse.+ """+ fires = _fires(crons, timezone, now)+ if not fires:+ return []+ per_day = _runs_per_day(crons, timezone, now)+ hour, minute = _anchor_time(fires)+ day = _anchor_day(per_day)+ at = f"{hour:02d}:{minute:02d}"+ ladder = [+ Cadence(cron="*/15 * * * *", label="Every 15 minutes", runs_per_day=_on(96)),+ Cadence(cron=f"{minute} * * * *", label="Every hour", runs_per_day=_on(24)),+ Cadence(cron=f"{minute} */4 * * *", label="Every 4 hours", runs_per_day=_on(6)),+ Cadence(+ cron=f"{minute} {hour} * * *",+ label=f"Every day at {at}",+ runs_per_day=_on(1),+ ),+ Cadence(+ cron=f"{minute} {hour} * * mon-fri",+ label=f"Weekdays at {at}",+ runs_per_day=_on(1, days=range(5)),+ ),+ Cadence(+ cron=f"{minute} {hour} * * {_DAYS[day]}",+ label=f"Every {_DAY_NAMES[day]} at {at}",+ runs_per_day=_on(1, days=[day]),+ ),+ ]+ # Less often in all, and on no day more often than now: a rung that ran+ # on a day the schedule leaves free would spend that day's allowance.+ return [+ rung+ for rung in ladder+ if rung.runs_per_week < len(fires)+ and all(runs <= limit for runs, limit in zip(rung.runs_per_day, per_day))+ ]+++def runs_more_than_weekly(crons: list[str], timezone: str, now: datetime) -> bool:+ """Whether ``less_often`` has something to offer, without building the+ ladder: a schedule that runs more than once a week can run once a week on+ its busiest day."""+ return len(_fires(crons, timezone, now, limit=2)) >= 2+++def describe(crons: list[str], timezone: str, now: datetime) -> str | None:+ """How often the schedule runs, in words: "Every minute", "Every day at+ 08:30", "Twice a day". None for one that runs less than twice a week and+ not on a weekly beat, such as a monthly one.++ Each cron is read for at most ``_COUNT_CAP`` runs. A beat found within+ them stands for the week only if the schedule runs every day, and a count+ that reaches the cap says so."""+ if len(crons) == 1:+ # Two weeks, so every gap in a week's runs falls between two of them+ # whatever day it is read on: weekdays read on a Saturday do not pass+ # for daily. A weekly beat needs weeks to show.+ beat = _fires(crons, timezone, now, span=2 * _WEEK)+ if len(beat) < 3:+ beat = _fires(crons, timezone, now, span=4 * _WEEK, limit=3)+ gaps = {later - earlier for earlier, later in zip(beat, beat[1:])}+ if len(beat) >= 3 and len(gaps) == 1:+ every = _every(gaps.pop(), beat[0])+ # Cut short at the cap, every minute on Saturdays beats like every+ # minute: the beat holds only if it runs every day.+ whole = len(beat) < _COUNT_CAP or all(_runs_per_day(crons, timezone, now))+ if every is not None and whole:+ return every+ runs = len(_fires(crons, timezone, now))+ if runs < 2:+ return None+ if runs >= _COUNT_CAP:+ return f"At least {_COUNT_CAP} times a week"+ # A day's runs only when every day has them: seven on Mondays is not+ # once a day.+ if runs % 7 == 0 and len(set(_runs_per_day(crons, timezone, now))) == 1:+ per_day = runs // 7+ if per_day <= 2:+ return "Once a day" if per_day == 1 else "Twice a day"+ return f"{per_day} times a day"+ return f"{runs} times a week"+++def _fires(+ crons: list[str],+ timezone: str,+ now: datetime,+ *,+ span: timedelta = _WEEK,+ limit: int = _COUNT_CAP,+) -> list[datetime]:+ """Each cron's fires from *now* until *span* after it, at most *limit* of+ each, soonest first, in *timezone*. One due right now counts.++ Whole seconds, croniter's own step: within the second a run fires, *now*+ would otherwise count that run and the one a week on, eight days' worth.+ The cadences offered when the dialog opened must still be offered when+ the owner saves.+ """+ start = _on_its_clock(now, timezone).replace(microsecond=0)+ return _fires_from(crons, start, span=span, limit=limit)+++def _fires_from(+ crons: list[str], start: datetime, *, span: timedelta, limit: int+) -> list[datetime]:+ end = start + span+ fires: list[datetime] = []+ for cron in crons:+ try:+ # croniter starts after the time it is given; a cron second is+ # the smallest step it takes.+ schedule = croniter(+ _as_scheduled(cron), start - timedelta(seconds=1), day_or=False+ )+ for _ in range(limit):+ fire = schedule.get_next(datetime)+ if fire >= end:+ break+ fires.append(fire)+ except (ValueError, KeyError):+ # Unreadable, or a date that never comes (31 February), which+ # croniter only finds out once it steps.+ return []+ return sorted(fires)+++def _as_scheduled(cron: str) -> str:+ """*cron* with a step over every weekday spelled out as the days APScheduler+ fires it on, counting from Monday: ``*/2`` is Monday, Wednesday, Friday and+ Sunday there, where Unix cron means Sunday, Tuesday, Thursday and Saturday.+ The scheduler renumbers every other weekday form itself."""+ parts = cron.split()+ if len(parts) != 5:+ return cron+ parts[4] = ",".join(_scheduled_days(token) for token in parts[4].split(","))+ return " ".join(parts)+++def _scheduled_days(token: str) -> str:+ body, _, step = token.partition("/")+ if body not in ("*", "?") or not step.isdigit():+ return token+ # APScheduler's Monday is 0; Unix cron's Sunday is.+ return ",".join(str((day + 1) % 7) for day in range(0, 7, int(step)))+++def _anchor_time(fires: list[datetime]) -> tuple[int, int]:+ times = sorted({(fire.hour, fire.minute) for fire in fires})+ if len(times) <= _FEW_TIMES:+ # Its first time from the morning on.+ daytime = [time for time in times if time >= _DAY_STARTS]+ return (daytime or times)[0]+ # A routine that runs at most hourly keeps its minute, which was picked to+ # spread the load; one that runs more often has no minute of its own. The+ # least of its minutes, so the next run does not decide.+ minute = min(fire.minute for fire in fires) if len(fires) <= _HOURLY else 0+ return _MORNING_HOUR, minute+++def _anchor_day(runs_per_day: list[int]) -> int:+ """The weekday it runs on most, as ``_runs_per_day`` counts; Monday first+ when that is a tie."""+ return min(range(7), key=lambda day: (-runs_per_day[day], day))+++def _runs_per_day(crons: list[str], timezone: str, now: datetime) -> list[int]:+ """How often it runs on each of the coming seven days, Monday first, on+ the zone's clock as it stands now. Each day is counted as far as the+ busiest rung runs in a day: past that, no rung runs more that day."""+ midnight = _on_its_clock(now, timezone).replace(+ hour=0, minute=0, second=0, microsecond=0+ )+ runs = [0] * 7+ for offset in range(7):+ day = midnight + offset * _DAY+ fires = _fires_from(crons, day, span=_DAY, limit=_BUSIEST_DAY)+ runs[day.weekday()] = min(len(fires), _BUSIEST_DAY)+ return runs+++def _on(runs: int, *, days: range | list[int] = range(7)) -> list[int]:+ """A rung's runs on each weekday, Monday first."""+ return [runs if day in days else 0 for day in range(7)]+++def _on_its_clock(now: datetime, timezone: str) -> datetime:+ """*now* on the zone's clock as it stands, at that fixed offset."""+ try:+ zone = ZoneInfo(timezone)+ except (ZoneInfoNotFoundError, ValueError):+ zone = ZoneInfo("UTC")+ offset = now.astimezone(zone).utcoffset() or timedelta(0)+ return now.astimezone(fixed_offset(offset))+++def _every(gap: timedelta, first: datetime) -> str | None:+ minutes = int(gap.total_seconds() // 60)+ at = f"{first.hour:02d}:{first.minute:02d}"+ if minutes == 1:+ return "Every minute"+ if minutes < 60:+ return f"Every {minutes} minutes"+ if minutes == 60:+ return "Every hour"+ if minutes < 24 * 60 and minutes % 60 == 0:+ return f"Every {minutes // 60} hours"+ if minutes == 24 * 60:+ return f"Every day at {at}"+ if minutes == 7 * 24 * 60:+ return f"Every {_DAY_NAMES[first.weekday()]} at {at}"+ return Nonediff --git a/autogpt_platform/backend/backend/copilot/scheduled_chats/cadence_service.py b/autogpt_platform/backend/backend/copilot/scheduled_chats/cadence_service.pynew file mode 100644index 0000000000..2c0ce7c4d5--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/scheduled_chats/cadence_service.py@@ -0,0 +1,163 @@+"""Run a scheduled chat less often (SECRT-2879).++The note a chat leaves when its owner's usage limit ran out offers this beside+Upgrade. It reads how often the chat runs, offers the cadences below that+(``cadence``), and applies the one the owner picks: a routine through+``enable_routine``, the path every change to a routine's cadence takes, and a+follow-up in the scheduler, in place, so it keeps its id.++Runs in the REST API, which has both the database and the scheduler.+"""++from datetime import datetime, timezone++from prisma.models import ScheduledChatStreak+from pydantic import BaseModel++from backend.api.features.experts import routines+from backend.api.features.experts.models import ExpertRoutine+from backend.copilot.scheduled_chats.cadence import describe, less_often+from backend.copilot.scheduled_chats.notices import schedule_title+from backend.data.user import get_user_by_id+from backend.executor.scheduler import CopilotTurnJobInfo+from backend.util.clients import get_scheduler_client+from backend.util.exceptions import NotFoundError+from backend.util.timezone_utils import get_user_timezone_or_utc+++class CadenceOption(BaseModel):+ cron: str+ # "Every day at 09:00", on the chat's own clock.+ label: str+++class ScheduledChatCadence(BaseModel):+ schedule_key: str+ title: str+ # How often it runs now, in words, when that can be said.+ current: str | None+ # The zone its times are in.+ timezone: str+ # Least drastic first; empty when it already runs once a week or less.+ options: list[CadenceOption]+++class CadenceNotFound(Exception):+ """Nothing here to run less often: not the caller's, gone, switched off,+ or a one-off."""+++class CadenceNotOffered(ValueError):+ """Not one of the cadences offered for this chat."""+++class ScheduledChatPaused(Exception):+ """Paused after failing the same way: resuming it comes first."""+++class _Schedule(BaseModel):+ key: str+ title: str+ crons: list[str]+ timezone: str+ # Set for a routine, whose row owns its crons.+ routine: ExpertRoutine | None = None+++async def get_cadence(user_id: str, schedule_key: str) -> ScheduledChatCadence:+ return _cadence(await _schedule(user_id, schedule_key))+++async def set_cadence(+ user_id: str, schedule_key: str, cron: str+) -> ScheduledChatCadence:+ """Switch the chat to *cron*, one of the cadences it was offered."""+ schedule = await _schedule(user_id, schedule_key)+ offered = less_often(schedule.crons, schedule.timezone, datetime.now(timezone.utc))+ if cron not in {rung.cron for rung in offered}:+ raise CadenceNotOffered(cron)+ if schedule.routine is not None:+ try:+ await routines.enable_routine(+ user_id, schedule.routine.expert_id, schedule.routine.id, crons=[cron]+ )+ except routines.RoutineNotFoundError as e:+ raise CadenceNotFound(schedule_key) from e+ else:+ try:+ await get_scheduler_client().update_copilot_turn_cron(+ schedule_key, user_id=user_id, cron=cron+ )+ except NotFoundError as e:+ # Deleted since it was read.+ raise CadenceNotFound(schedule_key) from e+ return _cadence(schedule.model_copy(update={"crons": [cron]}))+++def _cadence(schedule: _Schedule) -> ScheduledChatCadence:+ now = datetime.now(timezone.utc)+ return ScheduledChatCadence(+ schedule_key=schedule.key,+ title=schedule.title,+ current=describe(schedule.crons, schedule.timezone, now),+ timezone=schedule.timezone,+ options=[+ CadenceOption(cron=rung.cron, label=rung.label)+ for rung in less_often(schedule.crons, schedule.timezone, now)+ ],+ )+++async def _schedule(user_id: str, schedule_key: str) -> _Schedule:+ """The caller's scheduled chat behind *schedule_key*: a routine's id, or a+ follow-up's schedule id."""+ streak = await ScheduledChatStreak.prisma().find_unique(+ where={"userId_scheduleKey": {"userId": user_id, "scheduleKey": schedule_key}}+ )+ if streak is not None and streak.pausedAt is not None:+ raise ScheduledChatPaused(schedule_key)+ routine = await routines.get_routine(schedule_key)+ if routine is not None:+ return await _routine_schedule(user_id, routine)+ return await _follow_up_schedule(user_id, schedule_key)+++async def _routine_schedule(user_id: str, routine: ExpertRoutine) -> _Schedule:+ # ``get_routine`` is unscoped; this is the routines' own ownership rule.+ owned = await routines.list_routines(user_id, routine.expert_id)+ if not any(row.id == routine.id for row in owned):+ raise CadenceNotFound(routine.id)+ if not routine.enabled or not routine.crons:+ raise CadenceNotFound(routine.id)+ # The zone ``enable_routine`` will put the new cadence in.+ user = await get_user_by_id(user_id)+ return _Schedule(+ key=routine.id,+ title=routine.title,+ crons=list(routine.crons),+ timezone=get_user_timezone_or_utc(user.timezone if user else None),+ routine=routine,+ )+++async def _follow_up_schedule(user_id: str, schedule_key: str) -> _Schedule:+ jobs = await get_scheduler_client().get_execution_schedules(+ user_id=user_id, kind="copilot_turn"+ )+ job = next(+ (+ job+ for job in jobs+ if isinstance(job, CopilotTurnJobInfo) and job.id == schedule_key+ ),+ None,+ )+ if job is None or job.cron is None or job.routine_id is not None:+ raise CadenceNotFound(schedule_key)+ return _Schedule(+ key=job.id,+ title=schedule_title(routine_title=None, message=job.message),+ crons=[job.cron],+ # The scheduler puts the new cadence in this zone too.+ timezone=job.user_timezone or job.timezone,+ )diff --git a/autogpt_platform/backend/backend/copilot/scheduled_chats/cadence_service_test.py b/autogpt_platform/backend/backend/copilot/scheduled_chats/cadence_service_test.pynew file mode 100644index 0000000000..4060469146--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/scheduled_chats/cadence_service_test.py@@ -0,0 +1,265 @@+"""Running a scheduled chat less often, against a real database (SECRT-2879).++The scheduler is mocked; the routine rows, their ownership and the streak are+real.+"""++import logging+from datetime import datetime, timezone+from unittest.mock import AsyncMock, MagicMock+from uuid import uuid4++import pytest+from prisma.errors import UniqueViolationError+from prisma.models import ExpertRoutine, ScheduledChatStreak, User++from backend.copilot.scheduled_chats.cadence_service import (+ CadenceNotFound,+ CadenceNotOffered,+ ScheduledChatPaused,+ get_cadence,+ set_cadence,+)+from backend.executor.scheduler import CopilotTurnJobInfo+from backend.util.exceptions import NotFoundError+from backend.util.test import SpinTestServer++logger = logging.getLogger(__name__)++_SERVICE = "backend.copilot.scheduled_chats.cadence_service"+_ROUTINE_JOBS = "backend.api.features.experts.routine_jobs"+# The service reads the real clock; a zone without daylight saving keeps an+# hourly beat even in the week the clocks change.+_TOKYO = "Asia/Tokyo"+++def scheduler(mocker) -> MagicMock:+ client = MagicMock(+ get_execution_schedules=AsyncMock(return_value=[]),+ update_copilot_turn_cron=AsyncMock(),+ add_copilot_turn_schedule=AsyncMock(return_value=MagicMock(id="job-new")),+ delete_schedule=AsyncMock(),+ )+ mocker.patch(f"{_SERVICE}.get_scheduler_client", return_value=client)+ mocker.patch(f"{_ROUTINE_JOBS}.get_scheduler_client", return_value=client)+ return client+++async def _owner() -> str:+ user_id = f"cadence-{uuid4()}"+ try:+ await User.prisma().create(+ data={+ "id": user_id,+ "email": f"{user_id}@example.com",+ "name": "Cadence",+ "timezone": _TOKYO,+ }+ )+ except UniqueViolationError:+ pass+ return user_id+++async def _cleanup(user_id: str) -> None:+ try:+ await User.prisma().delete_many(where={"id": user_id})+ except Exception as exc:+ logger.warning("cleanup for %s failed: %s", user_id, exc)+++async def _hourly_routine(user_id: str, *, enabled: bool = True) -> ExpertRoutine:+ return await ExpertRoutine.prisma().create(+ data={+ "userId": user_id,+ "title": "Inbox sweep",+ "prompt": "Sweep the inbox.",+ "crons": ["17 * * * *"],+ "asks": [],+ "scheduleIds": ["job-old"],+ "enabledAt": datetime.now(timezone.utc) if enabled else None,+ }+ )+++def _every_minute_follow_up(user_id: str, **overrides) -> CopilotTurnJobInfo:+ fields = dict(+ id="job-1",+ name="copilot turn",+ next_run_time="2026-10-12T09:00:00+00:00",+ timezone=_TOKYO,+ schedule_id="job-1",+ user_id=user_id,+ message="Check Discord for new messages.",+ cron="* * * * *",+ user_timezone=_TOKYO,+ )+ fields.update(overrides)+ return CopilotTurnJobInfo(**fields)++[email protected](loop_scope="session")+async def test_an_hourly_routine_runs_daily_from_now_on(+ server: SpinTestServer, scheduler: MagicMock+):+ user_id = await _owner()+ try:+ routine = await _hourly_routine(user_id)++ offered = await get_cadence(user_id, routine.id)+ assert offered.title == "Inbox sweep"+ assert offered.current == "Every hour"+ assert offered.timezone == _TOKYO+ assert [option.label for option in offered.options] == [+ "Every 4 hours",+ "Every day at 09:17",+ "Weekdays at 09:17",+ "Every Monday at 09:17",+ ]++ changed = await set_cadence(user_id, routine.id, "17 9 * * *")++ assert changed.current == "Every day at 09:17"+ row = await ExpertRoutine.prisma().find_unique(where={"id": routine.id})+ assert row is not None+ assert row.crons == ["17 9 * * *"] and row.scheduleIds == ["job-new"]+ # The new job is armed before the old one goes.+ calls = [name for name, _, _ in scheduler.mock_calls]+ assert calls == ["add_copilot_turn_schedule", "delete_schedule"]+ scheduler.delete_schedule.assert_awaited_once_with("job-old", user_id=user_id)+ finally:+ await _cleanup(user_id)++[email protected](loop_scope="session")+async def test_a_routine_that_keeps_one_thread_keeps_it_at_its_new_cadence(+ server: SpinTestServer, scheduler: MagicMock+):+ """A THREAD routine's first fire mints the chat every later fire goes+ to. Running it less often must not start that conversation over."""+ user_id = await _owner()+ try:+ routine = await _hourly_routine(user_id)+ await ExpertRoutine.prisma().update(+ where={"id": routine.id}, data={"sessionId": "thread-1"}+ )++ await set_cadence(user_id, routine.id, "17 9 * * *")++ row = await ExpertRoutine.prisma().find_unique(where={"id": routine.id})+ assert row is not None and row.sessionId == "thread-1"+ # Its jobs still name no chat: each fire reads the row's.+ assert (+ scheduler.add_copilot_turn_schedule.await_args.kwargs["session_id"] is None+ )+ finally:+ await _cleanup(user_id)++[email protected](loop_scope="session")+async def test_a_follow_up_is_changed_in_place(+ server: SpinTestServer, scheduler: MagicMock+):+ user_id = await _owner()+ scheduler.get_execution_schedules.return_value = [_every_minute_follow_up(user_id)]+ try:+ offered = await get_cadence(user_id, "job-1")+ assert offered.title == "Check Discord for new messages."+ assert offered.current == "Every minute"+ assert offered.options[0].label == "Every 15 minutes"++ await set_cadence(user_id, "job-1", "0 * * * *")++ scheduler.update_copilot_turn_cron.assert_awaited_once_with(+ "job-1", user_id=user_id, cron="0 * * * *"+ )+ finally:+ await _cleanup(user_id)++[email protected](loop_scope="session")+async def test_a_follow_up_deleted_since_it_was_read_reads_as_not_found(+ server: SpinTestServer, scheduler: MagicMock+):+ """Not a 503 that says to try again: trying again finds nothing."""+ user_id = await _owner()+ scheduler.get_execution_schedules.return_value = [_every_minute_follow_up(user_id)]+ scheduler.update_copilot_turn_cron.side_effect = NotFoundError("gone")+ try:+ with pytest.raises(CadenceNotFound):+ await set_cadence(user_id, "job-1", "0 * * * *")+ finally:+ await _cleanup(user_id)++[email protected](loop_scope="session")+async def test_only_an_offered_cadence_is_taken(+ server: SpinTestServer, scheduler: MagicMock+):+ """Faster is not "less often", and neither is anything made up."""+ user_id = await _owner()+ try:+ routine = await _hourly_routine(user_id)++ for cron in ("* * * * *", "17 9 * * sat"):+ with pytest.raises(CadenceNotOffered):+ await set_cadence(user_id, routine.id, cron)++ scheduler.add_copilot_turn_schedule.assert_not_awaited()+ finally:+ await _cleanup(user_id)++[email protected](loop_scope="session")+async def test_nothing_to_change_reads_as_not_found(+ server: SpinTestServer, scheduler: MagicMock+):+ """Someone else's routine, one switched off, a routine's own job, a+ one-shot, and a key that names nothing."""+ user_id = await _owner()+ other = await _owner()+ try:+ theirs = await _hourly_routine(other)+ off = await _hourly_routine(user_id, enabled=False)+ scheduler.get_execution_schedules.return_value = [+ _every_minute_follow_up(user_id, id="routine-job", routine_id=off.id),+ _every_minute_follow_up(+ user_id, id="one-shot", cron=None, run_at=datetime.now(timezone.utc)+ ),+ ]++ for key in (theirs.id, off.id, "routine-job", "one-shot", "nothing"):+ with pytest.raises(CadenceNotFound):+ await get_cadence(user_id, key)+ finally:+ await _cleanup(user_id)+ await _cleanup(other)++[email protected](loop_scope="session")+async def test_a_paused_chat_is_resumed_first(+ server: SpinTestServer, scheduler: MagicMock+):+ user_id = await _owner()+ try:+ routine = await _hourly_routine(user_id)+ await ScheduledChatStreak.prisma().create(+ data={+ "userId": user_id,+ "scheduleKey": routine.id,+ "scheduleIds": ["job-old"],+ "title": "Inbox sweep",+ "failureKey": "connection:gmail",+ "failureKind": "connection",+ "provider": "gmail",+ "failures": 3,+ "wholeRunFailures": 3,+ "pausedAt": datetime.now(timezone.utc),+ }+ )++ with pytest.raises(ScheduledChatPaused):+ await set_cadence(user_id, routine.id, "17 9 * * *")+ finally:+ await _cleanup(user_id)diff --git a/autogpt_platform/backend/backend/copilot/scheduled_chats/cadence_test.py b/autogpt_platform/backend/backend/copilot/scheduled_chats/cadence_test.pynew file mode 100644index 0000000000..6c777d576d--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/scheduled_chats/cadence_test.py@@ -0,0 +1,277 @@+from datetime import datetime, timedelta, timezone+from zoneinfo import ZoneInfo++import pytest++from backend.copilot.scheduled_chats.cadence import (+ _fires,+ _runs_per_day,+ describe,+ less_often,+ runs_more_than_weekly,+)+from backend.executor.scheduler import _build_trigger++_CHICAGO = "America/Chicago"+# A Sunday afternoon in Chicago.+_NOW = datetime(2026, 10, 11, 13, 0, tzinfo=ZoneInfo(_CHICAGO))+++def _labels(crons: list[str]) -> list[str]:+ return [rung.label for rung in less_often(crons, _CHICAGO, _NOW)]+++def test_the_every_minute_monitor_is_offered_the_whole_ladder():+ assert _labels(["* * * * *"]) == [+ "Every 15 minutes",+ "Every hour",+ "Every 4 hours",+ "Every day at 09:00",+ "Weekdays at 09:00",+ "Every Monday at 09:00",+ ]+++def test_an_hourly_routine_keeps_the_minute_it_was_spread_to():+ rungs = less_often(["17 * * * *"], _CHICAGO, _NOW)++ assert [(rung.cron, rung.label) for rung in rungs] == [+ ("17 */4 * * *", "Every 4 hours"),+ ("17 9 * * *", "Every day at 09:17"),+ ("17 9 * * mon-fri", "Weekdays at 09:17"),+ ("17 9 * * mon", "Every Monday at 09:17"),+ ]+++def test_a_routine_with_two_times_a_day_keeps_its_morning_one():+ assert _labels(["0 13 * * *", "30 8 * * *"]) == [+ "Every day at 08:30",+ "Weekdays at 08:30",+ "Every Monday at 08:30",+ ]+++def test_a_night_run_gives_way_to_the_first_one_after_six():+ assert _labels(["30 0 * * *", "0 18 * * *"])[0] == "Every day at 18:00"+++def test_weekdays_can_only_drop_to_once_a_week_on_the_day_it_already_runs():+ # Unix numbering, as stored: 1-5 is Monday to Friday.+ assert _labels(["0 9 * * 1-5"]) == ["Every Monday at 09:00"]+ assert _labels(["0 9,17 * * 4"]) == ["Every Thursday at 09:00"]+++ "crons",+ [["0 9 * * mon"], ["0 9 1 * *"], [], ["not a cron"]],+ ids=["weekly", "monthly", "one-off", "unreadable"],+)+def test_nothing_runs_less_often_than_once_a_week(crons):+ assert less_often(crons, _CHICAGO, _NOW) == []+++def test_a_date_that_never_comes_reads_as_unreadable():+ """31 February parses, and croniter only refuses it once it steps."""+ assert less_often(["0 9 * * *", "0 0 31 2 *"], _CHICAGO, _NOW) == []+ assert describe(["0 0 31 2 *"], _CHICAGO, _NOW) is None+++def test_times_stay_on_the_schedules_own_clock():+ utc_now = _NOW.astimezone(timezone.utc)++ assert less_often(["30 8 * * *"], _CHICAGO, utc_now)[0].cron == "30 8 * * mon-fri"+++def test_each_rung_runs_as_often_as_it_says():+ for rung in less_often(["* * * * *"], _CHICAGO, _NOW):+ assert len(_fires([rung.cron], _CHICAGO, _NOW)) == rung.runs_per_week+ assert _runs_per_day([rung.cron], _CHICAGO, _NOW) == rung.runs_per_day+++ "now",+ [+ _NOW.replace(minute=16, second=59, microsecond=999_999),+ _NOW.replace(minute=17),+ _NOW.replace(minute=17, microsecond=50_000),+ _NOW.replace(minute=17, second=1),+ ],+ ids=["just-before-a-run", "on-a-run", "inside-its-second", "just-after"],+)+def test_the_offer_holds_through_the_second_a_run_fires(now):+ """CI opened the dialog at 20:16:59 and saved at 20:17:00.05: counting from+ a second before then caught the 20:17 run and the one a week on, so the+ hour it offered was gone by the save."""+ assert [rung.cron for rung in less_often(["17 * * * *"], _CHICAGO, now)] == [+ "17 */4 * * *",+ "17 9 * * *",+ "17 9 * * mon-fri",+ "17 9 * * mon",+ ]+++def test_the_offer_does_not_depend_on_which_run_is_next():+ # Its next run is 14:17 at 14:10, and 14:47 at 14:30.+ early = less_often(["17,47 */2 * * *"], _CHICAGO, _NOW.replace(hour=14, minute=10))+ late = less_often(["17,47 */2 * * *"], _CHICAGO, _NOW.replace(hour=14, minute=30))++ assert [rung.cron for rung in early] == [rung.cron for rung in late]+ assert early[0].cron == "17 */4 * * *"+++ ("crons", "labels"),+ [+ (["*/5 * * * sat"], ["Every Saturday at 09:00"]),+ # Past the weekly cap: it still runs on Saturdays only.+ (["* * * * sat"], ["Every Saturday at 09:00"]),+ (["0 * * * sat"], ["Every Saturday at 09:00"]),+ (["*/5 * * * mon-fri"], ["Weekdays at 09:00", "Every Monday at 09:00"]),+ ],+ ids=[+ "every-5-min-saturdays",+ "every-minute-saturdays",+ "hourly-saturdays",+ "weekdays",+ ],+)+def test_running_less_often_adds_no_runs_on_a_day_it_leaves_free(crons, labels):+ """Every hour has fewer runs in a week than every five minutes on+ Saturdays, but runs on six days that had none, spending their allowance.+ Its weekly rung is on the day it runs."""+ assert _labels(crons) == labels+++ "now",+ [+ datetime(2026, 10, 30, 13, 0, tzinfo=ZoneInfo(_CHICAGO)),+ datetime(2027, 3, 12, 13, 0, tzinfo=ZoneInfo(_CHICAGO)),+ ],+ ids=["clocks-fall-back", "clocks-spring-forward"],+)+def test_the_week_the_clocks_change_reads_like_any_other(now):+ """Counted on the zone's own clock, Chicago's fall-back Sunday has 01:17+ twice and its spring-forward one none, so an hourly schedule was offered+ "Every hour" and lost its minute."""+ rungs = less_often(["17 * * * *"], _CHICAGO, now)++ assert [rung.label for rung in rungs] == [+ "Every 4 hours",+ "Every day at 09:17",+ "Weekdays at 09:17",+ "Every Monday at 09:17",+ ]+ assert describe(["17 * * * *"], _CHICAGO, now) == "Every hour"+ assert describe(["30 1 * * *"], _CHICAGO, now) == "Every day at 01:30"+++ ("crons", "words"),+ [+ (["* * * * *"], "Every minute"),+ (["*/15 * * * *"], "Every 15 minutes"),+ (["17 * * * *"], "Every hour"),+ (["0 */4 * * *"], "Every 4 hours"),+ (["30 8 * * *"], "Every day at 08:30"),+ (["0 9 * * mon"], "Every Monday at 09:00"),+ (["30 8 * * *", "0 13 * * *"], "Twice a day"),+ (["0 9 * * 1-5"], "5 times a week"),+ # Seven runs, all on Mondays.+ (["0 9-15 * * mon"], "7 times a week"),+ # Every minute for 21 hours a day: more runs than are counted.+ (["* 0-20 * * *"], "At least 1000 times a week"),+ (["0 9 1 * *"], None),+ ],+)+def test_describe(crons, words):+ assert describe(crons, _CHICAGO, _NOW) == words+++def test_a_busy_beat_cut_short_at_the_cap_is_not_read_as_continuous():+ """A thousand runs of every minute on Saturdays are all a minute apart, all+ on one Saturday."""+ assert describe(["* * * * sat"], _CHICAGO, _NOW) == "At least 1000 times a week"+ assert (+ describe(["*/2 * * * mon-fri"], _CHICAGO, _NOW) == "At least 1000 times a week"+ )+ assert describe(["*/2 * * * *"], _CHICAGO, _NOW) == "Every 2 minutes"+++ "now",+ [+ datetime(2026, 10, 16, 10, 0, tzinfo=ZoneInfo(_CHICAGO)),+ datetime(2026, 10, 17, 10, 0, tzinfo=ZoneInfo(_CHICAGO)),+ ],+ ids=["friday-after-its-run", "saturday"],+)+def test_weekdays_read_late_in_the_week_do_not_pass_for_daily(now):+ """The weekend falls after their last run of the week, and must still+ fall between two runs of the ones read."""+ assert describe(["0 9 * * 1-5"], _CHICAGO, now) == "5 times a week"+ assert describe(["*/30 * * * mon-fri"], _CHICAGO, now) == "240 times a week"+++ "crons",+ [+ ["* * * * *"],+ ["17 * * * *"],+ ["0 9 * * 1-5"],+ ["0 9,17 * * 4"],+ ["*/5 * * * sat"],+ ["* * * * sat"],+ ["0 9 * * mon"],+ ["0 9 * * mon", "0 9 * * thu"],+ ["0 9 1 * *"],+ [],+ ["not a cron"],+ ],+)+def test_the_skip_note_offers_run_less_often_exactly_when_the_ladder_has_a_rung(+ crons,+):+ """The note asks the cheap question on every skipped run; the dialog+ builds the ladder. They must agree, or the button opens on nothing."""+ assert runs_more_than_weekly(crons, _CHICAGO, _NOW) == bool(+ less_often(crons, _CHICAGO, _NOW)+ )+++def _scheduled(cron: str, start: datetime, end: datetime) -> list[datetime]:+ """When the scheduler's own trigger fires *cron* between *start* and *end*."""+ trigger = _build_trigger(cron=cron, run_at=None, user_timezone="UTC")+ fires: list[datetime] = []+ previous = None+ while True:+ fire = trigger.get_next_fire_time(previous, previous or start)+ if fire is None or fire >= end:+ return fires+ fires.append(fire)+ previous = fire+++ "cron",+ [+ # The first Monday of the month: both days must match, not either.+ "0 9 1-7 * mon",+ # A step over every weekday counts from Monday.+ "0 9 * * */2",+ "0 9 * * */3",+ "0 9 * * 5-2",+ "0 9 * * 1-5",+ "0 9 * * 1-5/2",+ "0 9 * * 7",+ "0 9 1,15 * *",+ "*/30 * * * mon-fri",+ ],+)+def test_runs_are_counted_as_the_scheduler_fires_them(cron):+ start = datetime(2026, 10, 11, tzinfo=timezone.utc)+ four_weeks = timedelta(weeks=4)++ counted = _fires([cron], "UTC", start, span=four_weeks)++ assert counted == _scheduled(cron, start, start + four_weeks)diff --git a/autogpt_platform/backend/backend/copilot/scheduled_chats/notices.py b/autogpt_platform/backend/backend/copilot/scheduled_chats/notices.pyindex a6823e7a1e..cbfeb95006 100644--- a/autogpt_platform/backend/backend/copilot/scheduled_chats/notices.py+++ b/autogpt_platform/backend/backend/copilot/scheduled_chats/notices.py@@ -18,6 +18,7 @@ from zoneinfo import ZoneInfo, ZoneInfoNotFoundErrorfrom pydantic import BaseModel, Fieldfrom backend.copilot.hidden_rows import HIDDEN_FROM_MODEL_KEY+from backend.copilot.scheduled_chats.cadence import runs_more_than_weeklyfrom backend.copilot.turn_queue import TurnRefusalfrom backend.data.db_accessors import chat_db@@ -73,8 +74,17 @@ class NoticeReconnect(BaseModel):provider: str+class NoticeRunLessOften(BaseModel):+ """A button that offers cadences that run the scheduled chat less often,+ so its runs fit the owner's usage limit."""++ kind: Literal["run_less_often"] = "run_less_often"+ label: str = "Run less often"++NoticeAction = Annotated[- Union[NoticeLink, NoticeResume, NoticeReconnect], Field(discriminator="kind")+ Union[NoticeLink, NoticeResume, NoticeReconnect, NoticeRunLessOften],+ Field(discriminator="kind"),]@@ -115,13 +125,25 @@ def skip_notice(now: datetime,run: SkippedRun,user_timezone: str | None = None,+ crons: list[str] | None = None,) -> ScheduledChatNotice | None:"""What to tell the owner about a run *refusal* stopped, or None whenthere is nothing for them to do (a banned account, or an outage on ourside). Times are in *user_timezone*, the one the schedule was made in, else- UTC."""+ UTC. *crons* are the schedule's, for offering to run it less often."""if refusal.kind == "usage" and refusal.window in ("daily", "weekly"):- return _usage_notice(refusal, title=title, run=run, user_timezone=user_timezone)+ notice = _usage_notice(+ refusal, title=title, run=run, user_timezone=user_timezone+ )+ # Its runs could fit the allowance: only a repeating schedule, with+ # something less often than it to offer. Every skipped run gets here+ # and its window's note is written once, so the dialog builds the+ # ladder, not this.+ if run == "recurring" and runs_more_than_weekly(+ crons or [], user_timezone or "UTC", now+ ):+ notice.actions.append(NoticeRunLessOften())+ return noticeif refusal.kind == "usage":return _plan_notice(title=title,diff --git a/autogpt_platform/backend/backend/copilot/scheduled_chats/notices_test.py b/autogpt_platform/backend/backend/copilot/scheduled_chats/notices_test.pyindex 181267fa21..c7c732c0e5 100644--- a/autogpt_platform/backend/backend/copilot/scheduled_chats/notices_test.py+++ b/autogpt_platform/backend/backend/copilot/scheduled_chats/notices_test.py@@ -39,6 +39,51 @@ def test_a_daily_limit_says_when_the_schedule_runs_again():assert [(a.label, a.href) for a in notice.actions] == [("Upgrade", BILLING_PATH)]+def test_a_schedule_that_could_fit_the_limit_is_offered_to_run_less_often():+ notice = skip_notice(+ _usage("daily"),+ title="Discord monitor",+ now=_NOW,+ run="recurring",+ user_timezone="America/Chicago",+ crons=["* * * * *"],+ )++ assert notice is not None+ assert [action.model_dump() for action in notice.actions] == [+ {"kind": "link", "label": "Upgrade", "href": BILLING_PATH},+ {"kind": "run_less_often", "label": "Run less often"},+ ]+++ ("refusal", "run", "crons"),+ [+ (_usage("daily"), "recurring", ["0 9 * * mon"]),+ (_usage("weekly", _MONDAY), "recurring", None),+ (_usage("daily"), "waits_for_reset", ["* * * * *"]),+ (_usage("daily"), "dropped", ["* * * * *"]),+ (_usage("trial"), "recurring", ["* * * * *"]),+ (TurnRefusal(reason="paywalled", kind="no_plan"), "recurring", ["* * * * *"]),+ ],+ ids=[+ "weekly-already",+ "no-crons",+ "one-shot-waits",+ "one-shot-gone",+ "trial",+ "no-plan",+ ],+)+def test_run_less_often_is_offered_only_where_it_would_help(refusal, run, crons):+ """Once a week is the bottom of the ladder; a one-shot runs once anyway;+ no cadence brings a used-up trial or a missing plan back."""+ notice = skip_notice(refusal, title="Briefing", now=_NOW, run=run, crons=crons)++ assert notice is not None+ assert "run_less_often" not in [action.kind for action in notice.actions]++def test_a_weekly_limit_names_the_day_it_resets():notice = skip_notice(_usage("weekly", _MONDAY), title="Briefing", now=_NOW, run="recurring"diff --git a/autogpt_platform/backend/backend/copilot/scheduled_chats/service_test.py b/autogpt_platform/backend/backend/copilot/scheduled_chats/service_test.pyindex a39fc5f1b3..53fb4c7423 100644--- a/autogpt_platform/backend/backend/copilot/scheduled_chats/service_test.py+++ b/autogpt_platform/backend/backend/copilot/scheduled_chats/service_test.py@@ -534,6 +534,30 @@ async def test_a_chat_resumed_some_other_way_starts_over(await _cleanup(user_id)[email protected](loop_scope="session")+async def test_a_chat_resumed_some_other_way_that_runs_idle_is_not_called_paused(+ server: SpinTestServer, scheduler: MagicMock+):+ """Its next run only repeated that Discord needs connecting. The chat runs+ again, so neither the Scheduled page nor its alert may call it paused."""+ user_id, session_id = await _owner()+ try:+ failed = RunOutcome(failure=_DISCORD, whole_run=True)+ for _ in range(3):+ await record_scheduled_run(_run(user_id, session_id, failed))+ scheduler.get_execution_schedules.return_value = [MagicMock(id="sched-1")]++ await record_scheduled_run(_run(user_id, session_id, RunOutcome(idle=True)))++ assert await list_paused_scheduled_chats(user_id) == []+ row = await ScheduledChatStreak.prisma().find_first(where={"userId": user_id})+ assert row is not None and row.failures == 1 and row.pausedAt is None+ alert = await _alert(user_id)+ assert alert is not None and alert.status == AlertConditionStatus.RESOLVED+ finally:+ await _cleanup(user_id)++@pytest.mark.asyncio(loop_scope="session")async def test_a_pause_whose_card_failed_has_its_alert_withdrawn_when_it_ends(server: SpinTestServer, scheduler: MagicMock, mockerdiff --git a/autogpt_platform/backend/backend/copilot/scheduled_chats/streaks.py b/autogpt_platform/backend/backend/copilot/scheduled_chats/streaks.pyindex ff573a3966..788c3d0456 100644--- a/autogpt_platform/backend/backend/copilot/scheduled_chats/streaks.py+++ b/autogpt_platform/backend/backend/copilot/scheduled_chats/streaks.py@@ -10,6 +10,9 @@ asks what this run changes, and carries it out (``service``).* A run that worked clears the streak. One that called no tool continues anopen connection failure, and otherwise changes nothing.* A neutral run (cancelled, our outage) changes nothing.+* The caller lets a run on a paused streak through only once the chat's jobs+ fire again: it was resumed some other way. Unless the run is neutral, the+ pause is over and the run counts from the start."""from pydantic import BaseModel@@ -51,7 +54,13 @@ def advance(streak: Streak | None, outcome: RunOutcome) -> StreakStep:if failure is None:if not outcome.idle:return StreakStep(streak=None, ended_notified=_was_told(streak))- if streak is None or not _idle_continues(streak):+ if streak is None:+ return StreakStep(streak=None)+ if not _idle_continues(streak):+ if streak.paused:+ # Its pause is over, and a run that called no tool starts+ # nothing of its own.+ return StreakStep(streak=None, ended_notified=_was_told(streak))return StreakStep(streak=streak)failure, whole_run = streak.failure, Trueended_notified = False@@ -85,7 +94,7 @@ def advance(streak: Streak | None, outcome: RunOutcome) -> StreakStep:def _idle_continues(streak: Streak) -> bool:- return not streak.paused and streak.failure.kind in _IDLE_CONTINUES+ return streak.failure.kind in _IDLE_CONTINUESdef _was_told(streak: Streak | None) -> bool:diff --git a/autogpt_platform/backend/backend/copilot/scheduled_chats/streaks_test.py b/autogpt_platform/backend/backend/copilot/scheduled_chats/streaks_test.pyindex ecf63fea86..a17b9f3614 100644--- a/autogpt_platform/backend/backend/copilot/scheduled_chats/streaks_test.py+++ b/autogpt_platform/backend/backend/copilot/scheduled_chats/streaks_test.py@@ -143,3 +143,29 @@ def test_a_run_after_a_resume_the_streak_did_not_see_starts_over():assert step.streak is not Noneassert step.streak.failures == 1 and not step.streak.pausedassert step.ended_notified+++def test_an_idle_run_after_a_resume_the_streak_did_not_see_starts_over():+ """Resumed some other way and still not connected, the monitor only+ repeats that from history. Its pause is over, so it is counted afresh,+ and the third such run pauses it again."""+ paused = Streak(+ failure=_DISCORD, failures=3, whole_run_failures=3, notified=True, paused=True+ )++ steps = _drive([_IDLE, _IDLE, _IDLE], paused)++ assert steps[0].ended_notified+ first = steps[0].streak+ assert first is not None and first.failures == 1 and not first.paused+ assert [s.pause for s in steps] == [False, False, True]+++def test_an_idle_run_after_a_resume_ends_a_streak_it_does_not_continue():+ paused = Streak(+ failure=_BUDGET, failures=3, whole_run_failures=3, notified=True, paused=True+ )++ step = advance(paused, _IDLE)++ assert step.streak is None and step.ended_notifieddiff --git a/autogpt_platform/backend/backend/executor/scheduler.py b/autogpt_platform/backend/backend/executor/scheduler.pyindex 989146ab64..b3d34a9c4d 100644--- a/autogpt_platform/backend/backend/executor/scheduler.py+++ b/autogpt_platform/backend/backend/executor/scheduler.py@@ -832,6 +832,12 @@ async def _tell_owner_why_skipped(now=datetime.now(tz=timezone.utc),run=run,user_timezone=args.user_timezone,+ # A routine's every fire time, not just this job's.+ crons=(+ list(routine.crons)+ if routine is not None+ else [args.cron] if args.cron else None+ ),)if notice is None:return@@ -3573,6 +3579,45 @@ class Scheduler(AppService):self._invalidate_jobs_cache()return True+ @expose+ def update_copilot_turn_cron(+ self, schedule_id: str, user_id: str, cron: str+ ) -> CopilotTurnJobInfo:+ """Give a repeating follow-up a new cadence, in place.++ The job keeps its id, which is what its failure streak, its notes and+ Resume all name it by. A paused one stays paused: changing how often it+ runs is not the same thing as starting it again. A routine's jobs are+ not changed here; its row owns their crons.+ """+ job, info = self._authorized_job(schedule_id, user_id, action="reschedule")+ if not isinstance(info, CopilotTurnJobInfo) or info.cron is None:+ raise NotFoundError(f"Job #{schedule_id} is not a repeating follow-up.")+ if info.routine_id is not None:+ raise NotFoundError(f"Job #{schedule_id} belongs to a routine.")+ # The zone the dialog showed its times in: a follow-up saved before+ # user_timezone existed keeps its zone on the trigger alone.+ trigger = _build_trigger(+ cron=cron, run_at=None, user_timezone=info.user_timezone or info.timezone+ )+ args = CopilotTurnJobArgs.model_validate(job.kwargs).model_copy(+ update={"cron": cron}+ )+ changes: dict[str, object] = {+ "trigger": trigger,+ "kwargs": args.model_dump(mode="json"),+ }+ if job.next_run_time is not None:+ changes["next_run_time"] = trigger.get_next_fire_time(+ None, datetime.now(timezone.utc)+ )+ logger.info(f"Changing the cadence of job {schedule_id}")+ updated = self.scheduler.modify_job(+ schedule_id, jobstore=Jobstores.EXECUTION.value, **changes+ )+ self._invalidate_jobs_cache()+ return CopilotTurnJobInfo.from_db(args, updated)+@exposedef get_graph_execution_schedules(self,@@ -4747,6 +4792,7 @@ class SchedulerClient(AppServiceClient):)pause_schedule = endpoint_to_async(Scheduler.pause_execution_schedule)resume_schedule = endpoint_to_async(Scheduler.resume_execution_schedule)+ update_copilot_turn_cron = endpoint_to_async(Scheduler.update_copilot_turn_cron)# Graph-only typed list — for legacy callers that need GraphExecutionJobInfo.get_graph_execution_schedules = endpoint_to_async(Scheduler.get_graph_execution_schedulesdiff --git a/autogpt_platform/backend/backend/executor/scheduler_cadence_test.py b/autogpt_platform/backend/backend/executor/scheduler_cadence_test.pynew file mode 100644index 0000000000..94c792cb9b--- /dev/null+++ b/autogpt_platform/backend/backend/executor/scheduler_cadence_test.py@@ -0,0 +1,116 @@+"""A repeating follow-up gets a new cadence in place (SECRT-2879).++Against a real APScheduler with an in-memory job store, so the trigger, the+stored kwargs and the next run time are the scheduler's own.+"""++from collections.abc import Iterator+from contextlib import contextmanager+from zoneinfo import ZoneInfo++import pytest+from apscheduler.jobstores.memory import MemoryJobStore+from apscheduler.schedulers.background import BackgroundScheduler++from backend.executor.scheduler import (+ CopilotTurnJobArgs,+ Jobstores,+ Scheduler,+ _build_trigger,+ execute_copilot_turn,+)+from backend.util.exceptions import NotAuthorizedError, NotFoundError++_CHICAGO = "America/Chicago"+_STORE = Jobstores.EXECUTION.value+++@contextmanager+def _scheduler() -> Iterator[Scheduler]:+ aps = BackgroundScheduler()+ aps.add_jobstore(MemoryJobStore(), _STORE)+ aps.start(paused=True)+ scheduler = Scheduler.__new__(Scheduler)+ scheduler.scheduler = aps+ try:+ yield scheduler+ finally:+ aps.shutdown(wait=False)+++def _add(+ scheduler: Scheduler,+ *,+ routine_id: str | None = None,+ user_timezone: str | None = _CHICAGO,+) -> None:+ args = CopilotTurnJobArgs(+ schedule_id="job-1",+ user_id="user-1",+ message="Check Discord for new messages.",+ cron="* * * * *",+ user_timezone=user_timezone,+ routine_id=routine_id,+ )+ scheduler.scheduler.add_job(+ execute_copilot_turn,+ kwargs=args.model_dump(mode="json"),+ trigger=_build_trigger(cron=args.cron, run_at=None, user_timezone=_CHICAGO),+ jobstore=_STORE,+ id="job-1",+ )+++def test_a_follow_up_runs_on_its_new_cadence_under_the_same_id():+ with _scheduler() as scheduler:+ _add(scheduler)++ info = scheduler.update_copilot_turn_cron("job-1", "user-1", "0 9 * * mon-fri")++ job = scheduler.scheduler.get_job("job-1", jobstore=_STORE)+ assert info.id == "job-1" and info.cron == "0 9 * * mon-fri"+ assert job.kwargs["cron"] == "0 9 * * mon-fri"+ next_run = job.next_run_time.astimezone(ZoneInfo(_CHICAGO))+ assert (next_run.hour, next_run.minute) == (9, 0)+ assert next_run.weekday() < 5+++def test_a_follow_up_saved_without_its_zone_keeps_the_triggers():+ """Older follow-ups have no user_timezone; their trigger still has the+ zone, and the dialog showed its times in it. 09:00 there, not UTC."""+ with _scheduler() as scheduler:+ _add(scheduler, user_timezone=None)++ scheduler.update_copilot_turn_cron("job-1", "user-1", "0 9 * * *")++ job = scheduler.scheduler.get_job("job-1", jobstore=_STORE)+ next_run = job.next_run_time.astimezone(ZoneInfo(_CHICAGO))+ assert (next_run.hour, next_run.minute) == (9, 0)+++def test_a_paused_follow_up_stays_paused():+ with _scheduler() as scheduler:+ _add(scheduler)+ scheduler.scheduler.pause_job("job-1", jobstore=_STORE)++ scheduler.update_copilot_turn_cron("job-1", "user-1", "0 9 * * *")++ job = scheduler.scheduler.get_job("job-1", jobstore=_STORE)+ assert job.next_run_time is None+ assert job.kwargs["cron"] == "0 9 * * *"+++def test_a_routines_job_is_left_to_its_routine():+ with _scheduler() as scheduler:+ _add(scheduler, routine_id="routine-1")++ with pytest.raises(NotFoundError):+ scheduler.update_copilot_turn_cron("job-1", "user-1", "0 9 * * *")+++def test_nobody_else_can_change_it():+ with _scheduler() as scheduler:+ _add(scheduler)++ with pytest.raises(NotAuthorizedError):+ scheduler.update_copilot_turn_cron("job-1", "someone-else", "0 9 * * *")diff --git a/autogpt_platform/backend/backend/executor/scheduler_unit_test.py b/autogpt_platform/backend/backend/executor/scheduler_unit_test.pyindex 09ece8e402..b78248f8b0 100644--- a/autogpt_platform/backend/backend/executor/scheduler_unit_test.py+++ b/autogpt_platform/backend/backend/executor/scheduler_unit_test.py@@ -2994,6 +2994,39 @@ async def test_a_routine_is_named_by_its_title_and_keyed_by_its_id(assert kwargs["title"] == "Morning briefing"+async def test_an_hourly_schedule_over_its_limit_is_offered_to_run_less_often(+ owner_gate, post_notice+):+ _over_a_cap(owner_gate)+ await _fire_hourly("session-1", "platform")++ actions = [action.kind for action in post_notice.call_args.args[0].actions]+ assert actions == ["link", "run_less_often"]+++async def test_a_routine_is_offered_less_often_by_all_of_its_times(+ owner_gate, post_notice+):+ """Each job carries one fire time; whether the routine can run less often+ depends on all of them. Two weekly times make twice a week, which can."""+ _over_a_cap(owner_gate)+ routine = ExpertRoutine(+ id="routine-1",+ title="Weekly review",+ prompt="Review the week.",+ crons=["0 9 * * mon", "0 9 * * thu"],+ enabled=True,+ )+ store = MagicMock(get_routine=AsyncMock(return_value=routine))+ with patch(f"{_SCHEDULER_PATH}.experts_db", return_value=store):+ await _fire(_args(routine_id="routine-1", run_at=None, cron="0 9 * * mon"))++ actions = [action.kind for action in post_notice.call_args.args[0].actions]+ assert actions == ["link", "run_less_often"]++@pytest.mark.asyncioasync def test_a_note_that_cannot_be_posted_does_not_fail_the_tick(owner_gate, post_notice, caplogdiff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/ScheduledChatNoticeCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/ScheduledChatNoticeCard.tsxindex 030725c92c..a15100b166 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/ScheduledChatNoticeCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/ScheduledChatNoticeCard.tsx@@ -12,6 +12,7 @@ import {PlugSocketIcon,} from "@hugeicons/core-free-icons";import type { IconSvgElement } from "@hugeicons/react";+import { RunLessOftenDialog } from "./components/RunLessOftenDialog/RunLessOftenDialog";import type { NoticeAction, ScheduledChatNotice } from "./helpers";import { useScheduledChatNoticeCard } from "./useScheduledChatNoticeCard";@@ -53,6 +54,18 @@ export function ScheduledChatNoticeCard({ notice, sessionID = null }: Props) {</Button>);}+ if (action.kind === "run_less_often") {+ return (+ <Button+ key="run-less-often"+ variant="secondary"+ size="small"+ onClick={() => card.setLessOftenOpen(true)}+ >+ {action.label}+ </Button>+ );+ }if (action.kind === "reconnect") {return (<Button@@ -96,6 +109,13 @@ export function ScheduledChatNoticeCard({ notice, sessionID = null }: Props) {) : null}</div></div>+ {notice.scheduleKey && card.lessOftenOpen ? (+ <RunLessOftenDialog+ scheduleKey={notice.scheduleKey}+ isOpen+ setIsOpen={card.setLessOftenOpen}+ />+ ) : null}{card.connectProvider ? (<ConnectServiceDialogopendiff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/__tests__/ScheduledChatNoticeCard.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/__tests__/ScheduledChatNoticeCard.test.tsxindex 00e86a0d0f..50ac0791f3 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/__tests__/ScheduledChatNoticeCard.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/__tests__/ScheduledChatNoticeCard.test.tsx@@ -3,7 +3,12 @@ import {getGetV1ListProvidersMockHandler,} from "@/app/api/__generated__/endpoints/integrations/integrations.msw";import { getGetHomeDashboardQueryKey } from "@/app/api/__generated__/endpoints/home/home";-import { getResumeScheduledChatMockHandler } from "@/app/api/__generated__/endpoints/schedules/schedules.msw";+import {+ getGetScheduledChatCadenceMockHandler,+ getResumeScheduledChatMockHandler,+ getSetScheduledChatCadenceMockHandler,+} from "@/app/api/__generated__/endpoints/schedules/schedules.msw";+import type { ScheduledChatCadence } from "@/app/api/__generated__/models/scheduledChatCadence";import { QueryClient } from "@tanstack/react-query";import { server } from "@/mocks/mock-server";import {@@ -36,10 +41,46 @@ const PAUSED: ScheduledChatNotice = {],};+const OVER_LIMIT: ScheduledChatNotice = {+ ...SKIPPED,+ actions: [+ { kind: "link", label: "Upgrade", href: "/settings/billing" },+ { kind: "run_less_often", label: "Run less often" },+ ],+};++const CADENCE: ScheduledChatCadence = {+ schedule_key: "routine-1",+ title: "Discord monitor",+ current: "Every minute",+ timezone: "America/Chicago",+ options: [+ { cron: "*/15 * * * *", label: "Every 15 minutes" },+ { cron: "0 * * * *", label: "Every hour" },+ { cron: "0 9 * * *", label: "Every day at 09:00" },+ { cron: "0 9 * * mon-fri", label: "Weekdays at 09:00" },+ ],+};++const toastMock = vi.fn();+vi.mock("@/components/molecules/Toast/use-toast", async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("@/components/molecules/Toast/use-toast")+ >();+ return { ...actual, toast: (...args: unknown[]) => toastMock(...args) };+});+afterEach(() => {server.resetHandlers();+ toastMock.mockClear();});+async function openRunLessOften(notice: ScheduledChatNotice = OVER_LIMIT) {+ render(<ScheduledChatNoticeCard notice={notice} sessionID="session-1" />);+ fireEvent.click(screen.getByRole("button", { name: "Run less often" }));+}+describe("ScheduledChatNoticeCard", () => {it("says why the run was skipped and links to the fix", () => {render(<ScheduledChatNoticeCard notice={SKIPPED} />);@@ -53,6 +94,117 @@ describe("ScheduledChatNoticeCard", () => {).toBe("/settings/billing");});+ it("runs the chat less often, at the cadence picked", async () => {+ let posted: unknown = null;+ server.use(+ getGetScheduledChatCadenceMockHandler(CADENCE),+ getSetScheduledChatCadenceMockHandler(async ({ params, request }) => {+ posted = { key: params.scheduleKey, body: await request.json() };+ return { ...CADENCE, current: "5 times a week", options: [] };+ }),+ );+ await openRunLessOften();++ expect(+ await screen.findByText("Run “Discord monitor” less often"),+ ).toBeDefined();+ expect(screen.getByText(/It runs every minute now/)).toBeDefined();+ expect(screen.getByRole("button", { name: "Save" })).toHaveProperty(+ "disabled",+ true,+ );++ fireEvent.click(screen.getByRole("radio", { name: "Weekdays at 09:00" }));+ fireEvent.click(screen.getByRole("button", { name: "Save" }));++ await waitFor(() =>+ expect(posted).toEqual({+ key: "routine-1",+ body: { cron: "0 9 * * mon-fri" },+ }),+ );+ // The choice in the owner's words, not "5 times a week".+ await waitFor(() =>+ expect(toastMock).toHaveBeenCalledWith(+ expect.objectContaining({+ description: "“Discord monitor” now runs weekdays at 09:00.",+ }),+ ),+ );+ });++ it("says so when there is nothing less often to switch to", async () => {+ server.use(+ getGetScheduledChatCadenceMockHandler({+ ...CADENCE,+ current: "Every Monday at 09:00",+ options: [],+ }),+ );+ await openRunLessOften();++ expect(await screen.findByText(/nothing less often/)).toBeDefined();+ expect(screen.queryByRole("button", { name: "Save" })).toBeNull();+ });++ it("says so when how often it runs can't be read", async () => {+ server.use(+ http.get("*/api/schedules/followups/:scheduleKey/cadence", () =>+ HttpResponse.json({ detail: "boom" }, { status: 500 }),+ ),+ );+ await openRunLessOften();++ expect(+ await screen.findByText(/Couldn't load how often it runs/),+ ).toBeDefined();+ expect(screen.queryByRole("radio")).toBeNull();+ });++ it.each([+ [409, "It's paused. Resume it first."],+ [404, "It no longer runs on a schedule this can change."],+ ])(+ "says why when it can't be read to change (%i)",+ async (status, reason) => {+ server.use(+ http.get("*/api/schedules/followups/:scheduleKey/cadence", () =>+ HttpResponse.json({ detail: "refused" }, { status }),+ ),+ );+ await openRunLessOften();++ expect(await screen.findByText(reason)).toBeDefined();+ expect(screen.queryByText(/Couldn't load how often it runs/)).toBeNull();+ expect(screen.queryByRole("button", { name: "Save" })).toBeNull();+ },+ );++ it("asks for a paused chat to be resumed first", async () => {+ server.use(+ getGetScheduledChatCadenceMockHandler(CADENCE),+ http.post("*/api/schedules/followups/:scheduleKey/cadence", () =>+ HttpResponse.json(+ { detail: "This scheduled chat is paused. Resume it first." },+ { status: 409 },+ ),+ ),+ );+ await openRunLessOften();++ fireEvent.click(await screen.findByRole("radio", { name: "Every hour" }));+ fireEvent.click(screen.getByRole("button", { name: "Save" }));++ await waitFor(() =>+ expect(toastMock).toHaveBeenCalledWith(+ expect.objectContaining({+ variant: "destructive",+ description: "It's paused. Resume it first.",+ }),+ ),+ );+ });+it("resumes the paused chat it is about", async () => {let resumedKey: string | null = null;server.use(diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/__tests__/helpers.test.tsindex 17d5601785..65bd15e537 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/__tests__/helpers.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/__tests__/helpers.test.ts@@ -69,9 +69,26 @@ describe("getScheduledChatNotice", () => {actions: [{ kind: "resume", label: "Resume" },{ kind: "reconnect", label: "Reconnect" },+ { kind: "run_less_often", label: "Run less often" },],});expect(notice?.actions).toEqual([]);});++ it("reads a skipped chat's offer to run less often", () => {+ const notice = getScheduledChatNotice({+ ...NOTICE,+ schedule_key: "routine-1",+ actions: [+ { kind: "link", label: "Upgrade", href: "/settings/billing" },+ { kind: "run_less_often", label: "Run less often" },+ ],+ });++ expect(notice?.actions).toEqual([+ { kind: "link", label: "Upgrade", href: "/settings/billing" },+ { kind: "run_less_often", label: "Run less often" },+ ]);+ });});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/components/RunLessOftenDialog/RunLessOftenDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/components/RunLessOftenDialog/RunLessOftenDialog.tsxnew file mode 100644index 0000000000..1840ff54eb--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/components/RunLessOftenDialog/RunLessOftenDialog.tsx@@ -0,0 +1,139 @@+"use client";++import type { ScheduledChatCadence } from "@/app/api/__generated__/models/scheduledChatCadence";+import { Button } from "@/components/atoms/Button/Button";+import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";+import { Text } from "@/components/atoms/Text/Text";+import { Dialog } from "@/components/molecules/Dialog/Dialog";+import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";+import { cn } from "@/lib/utils";+import { useId } from "react";+import { lowerFirst } from "./helpers";+import { useRunLessOftenDialog } from "./useRunLessOftenDialog";++interface Props {+ scheduleKey: string;+ isOpen: boolean;+ setIsOpen: (open: boolean) => void;+}++export function RunLessOftenDialog({ scheduleKey, isOpen, setIsOpen }: Props) {+ const dialog = useRunLessOftenDialog({+ scheduleKey,+ isOpen,+ onDone: () => setIsOpen(false),+ });+ const canChoose = (dialog.cadence?.options.length ?? 0) > 0;++ return (+ <Dialog+ controlled={{ isOpen, set: setIsOpen }}+ styling={{ maxWidth: "28rem" }}+ title={+ dialog.cadence+ ? `Run “${dialog.cadence.title}” less often`+ : "Run less often"+ }+ >+ <Dialog.Content>+ {dialog.isLoading ? (+ <div className="flex flex-col gap-2" data-testid="cadence-loading">+ <Skeleton className="h-10 w-full" />+ <Skeleton className="h-10 w-full" />+ </div>+ ) : dialog.refusal ? (+ <Text variant="body" className="text-zinc-600">+ {dialog.refusal}+ </Text>+ ) : dialog.isError || !dialog.cadence ? (+ <ErrorCard+ responseError={{ message: "Couldn't load how often it runs." }}+ context="its schedule"+ />+ ) : (+ <CadenceChoices+ cadence={dialog.cadence}+ selected={dialog.selected}+ onSelect={dialog.select}+ />+ )}+ <Dialog.Footer>+ <Button+ type="button"+ variant="secondary"+ size="small"+ onClick={() => setIsOpen(false)}+ >+ Cancel+ </Button>+ {canChoose ? (+ <Button+ type="button"+ variant="primary"+ size="small"+ disabled={!dialog.selected}+ loading={dialog.isSaving}+ onClick={dialog.save}+ >+ Save+ </Button>+ ) : null}+ </Dialog.Footer>+ </Dialog.Content>+ </Dialog>+ );+}++interface ChoicesProps {+ cadence: ScheduledChatCadence;+ selected: string | null;+ onSelect: (cron: string) => void;+}++function CadenceChoices({ cadence, selected, onSelect }: ChoicesProps) {+ const groupName = useId();++ if (cadence.options.length === 0) {+ return (+ <Text variant="body" className="text-zinc-600">+ “{cadence.title}” already runs once a week or less, so there is nothing+ less often to switch it to.+ </Text>+ );+ }+ return (+ <div className="flex flex-col gap-3">+ <Text variant="body" className="text-zinc-600">+ {cadence.current ? `It runs ${lowerFirst(cadence.current)} now. ` : ""}+ Fewer runs use less of your allowance. Times are in {cadence.timezone}.+ </Text>+ <div+ role="radiogroup"+ aria-label="How often it runs"+ className="flex flex-col gap-2"+ >+ {cadence.options.map((option) => (+ <label+ key={option.cron}+ className={cn(+ "flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-2.5 text-sm text-zinc-900",+ selected === option.cron+ ? "border-zinc-900 bg-zinc-50"+ : "border-zinc-200 hover:bg-zinc-50",+ )}+ >+ <input+ type="radio"+ name={groupName}+ value={option.cron}+ checked={selected === option.cron}+ onChange={() => onSelect(option.cron)}+ className="size-4 accent-zinc-900"+ />+ {option.label}+ </label>+ ))}+ </div>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/components/RunLessOftenDialog/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/components/RunLessOftenDialog/helpers.tsnew file mode 100644index 0000000000..af0b995016--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/components/RunLessOftenDialog/helpers.ts@@ -0,0 +1,22 @@+import { ApiError } from "@/lib/autogpt-server-api/helpers";++// "Every Monday at 09:00" reads "every Monday at 09:00" mid-sentence.+export function lowerFirst(text: string): string {+ return text.charAt(0).toLowerCase() + text.slice(1);+}++// Why the API won't touch this chat's cadence, read or change.+export function refusalText(error: unknown): string | null {+ if (!(error instanceof ApiError)) return null;+ if (error.status === 409) return "It's paused. Resume it first.";+ if (error.status === 404)+ return "It no longer runs on a schedule this can change.";+ return null;+}++// The refusals the API names; anything else is ours.+export function changeErrorText(error: unknown): string | null {+ if (error instanceof ApiError && error.status === 400)+ return "Pick one of the options shown.";+ return refusalText(error);+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/components/RunLessOftenDialog/useRunLessOftenDialog.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/components/RunLessOftenDialog/useRunLessOftenDialog.tsnew file mode 100644index 0000000000..646fe0da29--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/components/RunLessOftenDialog/useRunLessOftenDialog.ts@@ -0,0 +1,84 @@+import { getGetHomeDashboardQueryKey } from "@/app/api/__generated__/endpoints/home/home";+import {+ getGetScheduledChatCadenceQueryKey,+ useGetScheduledChatCadence,+ useSetScheduledChatCadence,+} from "@/app/api/__generated__/endpoints/schedules/schedules";+import { okData } from "@/app/api/helpers";+import { toast } from "@/components/molecules/Toast/use-toast";+import { invalidateAllScheduleQueries } from "@/services/schedules/invalidate-schedules";+import * as Sentry from "@sentry/nextjs";+import { useQueryClient } from "@tanstack/react-query";+import { useState } from "react";+import { changeErrorText, lowerFirst, refusalText } from "./helpers";++interface Args {+ scheduleKey: string;+ isOpen: boolean;+ onDone: () => void;+}++export function useRunLessOftenDialog({ scheduleKey, isOpen, onDone }: Args) {+ const queryClient = useQueryClient();+ const [selected, setSelected] = useState<string | null>(null);++ const cadenceQuery = useGetScheduledChatCadence(scheduleKey, {+ query: { enabled: isOpen, select: (res) => okData(res) },+ });+ const cadence = cadenceQuery.data;++ const { mutate, isPending } = useSetScheduledChatCadence({+ mutation: {+ onSuccess: (res, { data }) => {+ const changed = okData(res);+ // The choice in the owner's words: "Weekdays at 09:00" reads back as+ // that, not as "5 times a week".+ const chosen = cadence?.options.find(+ (option) => option.cron === data.cron,+ );+ queryClient.invalidateQueries({+ queryKey: getGetScheduledChatCadenceQueryKey(scheduleKey),+ });+ queryClient.invalidateQueries({+ queryKey: getGetHomeDashboardQueryKey(),+ });+ void invalidateAllScheduleQueries(queryClient);+ const runs = chosen?.label ?? changed?.current;+ toast({+ title: "It runs less often now",+ description:+ changed && runs+ ? `“${changed.title}” now runs ${lowerFirst(runs)}.`+ : undefined,+ });+ setSelected(null);+ onDone();+ },+ onError: (error) => {+ const known = changeErrorText(error);+ if (known === null) Sentry.captureException(error);+ toast({+ variant: "destructive",+ title: "Couldn't change how often it runs",+ description: known ?? "Please try again.",+ });+ },+ },+ });++ function save() {+ if (!selected || isPending) return;+ mutate({ scheduleKey, data: { cron: selected } });+ }++ return {+ cadence,+ isLoading: cadenceQuery.isLoading,+ refusal: refusalText(cadenceQuery.error),+ isError: cadenceQuery.isError,+ selected,+ select: setSelected,+ save,+ isSaving: isPending,+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/helpers.tsindex 1507b3103e..973b97df3e 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/helpers.ts@@ -15,10 +15,16 @@ export interface NoticeReconnectAction {provider: string;}+export interface NoticeRunLessOftenAction {+ kind: "run_less_often";+ label: string;+}+export type NoticeAction =| NoticeLinkAction| NoticeResumeAction- | NoticeReconnectAction;+ | NoticeReconnectAction+ | NoticeRunLessOftenAction;export interface ScheduledChatNotice {reason: string;@@ -41,6 +47,8 @@ function toAction(value: unknown): NoticeAction | null {const label = asString(action.label);if (!label) return null;if (action.kind === "resume") return { kind: "resume", label };+ if (action.kind === "run_less_often")+ return { kind: "run_less_often", label };if (action.kind === "reconnect") {const provider = asString(action.provider);return provider ? { kind: "reconnect", label, provider } : null;@@ -74,8 +82,12 @@ export function getScheduledChatNotice(? meta.actions.map(toAction).filter((action): action is NoticeAction => action !== null)- // Resume needs to know which scheduled chat it resumes.- .filter((action) => action.kind !== "resume" || scheduleKey !== null)+ // Resume and Run less often need to know which scheduled chat.+ .filter(+ (action) =>+ (action.kind !== "resume" && action.kind !== "run_less_often") ||+ scheduleKey !== null,+ ): [];return {diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/useScheduledChatNoticeCard.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/useScheduledChatNoticeCard.tsindex 54dab23b97..f375314d71 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/useScheduledChatNoticeCard.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/useScheduledChatNoticeCard.ts@@ -20,6 +20,7 @@ export function useScheduledChatNoticeCard({ scheduleKey, sessionID }: Args) {const queryClient = useQueryClient();const [connectProvider, setConnectProvider] = useState<string | null>(null);const [resumed, setResumed] = useState(false);+ const [lessOftenOpen, setLessOftenOpen] = useState(false);// A resume that follows a reconnect is quiet when there was nothing to// resume: a chat that was only warned, never paused, answers 404.const quietRef = useRef(false);@@ -85,5 +86,7 @@ export function useScheduledChatNoticeCard({ scheduleKey, sessionID }: Args) {resume: () => resume(),isResuming: isPending,resumed,+ lessOftenOpen,+ setLessOftenOpen,};}diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 5d60f30824..0e6aa7d9c6 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -14723,6 +14723,102 @@"security": [{ "HTTPBearerJWT": [] }]}},+ "/api/schedules/followups/{schedule_key}/cadence": {+ "get": {+ "tags": ["v1", "schedules"],+ "summary": "How often a scheduled chat runs, and how it could run less often",+ "operationId": "getScheduledChatCadence",+ "security": [{ "HTTPBearerJWT": [] }],+ "parameters": [+ {+ "name": "schedule_key",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "description": "The routine's id, or the follow-up's schedule id",+ "title": "Schedule Key"+ },+ "description": "The routine's id, or the follow-up's schedule id"+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ScheduledChatCadence"+ }+ }+ }+ },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ }+ },+ "post": {+ "tags": ["v1", "schedules"],+ "summary": "Run a scheduled chat less often",+ "operationId": "setScheduledChatCadence",+ "security": [{ "HTTPBearerJWT": [] }],+ "parameters": [+ {+ "name": "schedule_key",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "description": "The routine's id, or the follow-up's schedule id",+ "title": "Schedule Key"+ },+ "description": "The routine's id, or the follow-up's schedule id"+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SetScheduledChatCadenceRequest"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ScheduledChatCadence"+ }+ }+ }+ },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ }+ }+ },"/api/schedules/followups/{schedule_key}/resume": {"post": {"tags": ["v1", "schedules"],@@ -20790,6 +20886,15 @@"required": ["file_ids"],"title": "BulkMoveFilesRequest"},+ "CadenceOption": {+ "properties": {+ "cron": { "type": "string", "title": "Cron" },+ "label": { "type": "string", "title": "Label" }+ },+ "type": "object",+ "required": ["cron", "label"],+ "title": "CadenceOption"+ },"CancelSessionResponse": {"properties": {"cancelled": { "type": "boolean", "title": "Cancelled" },@@ -31778,6 +31883,25 @@"title": "ScheduleUpdateRequest","description": "Fields to change on an existing schedule; omitted fields keep their value."},+ "ScheduledChatCadence": {+ "properties": {+ "schedule_key": { "type": "string", "title": "Schedule Key" },+ "title": { "type": "string", "title": "Title" },+ "current": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Current"+ },+ "timezone": { "type": "string", "title": "Timezone" },+ "options": {+ "items": { "$ref": "#/components/schemas/CadenceOption" },+ "type": "array",+ "title": "Options"+ }+ },+ "type": "object",+ "required": ["schedule_key", "title", "current", "timezone", "options"],+ "title": "ScheduledChatCadence"+ },"SchedulesListResponse": {"properties": {"schedules": {@@ -32049,6 +32173,18 @@"required": ["active_graph_version"],"title": "SetGraphActiveVersion"},+ "SetScheduledChatCadenceRequest": {+ "properties": {+ "cron": {+ "type": "string",+ "title": "Cron",+ "description": "One of the cadences offered for this chat, as returned by getScheduledChatCadence"+ }+ },+ "type": "object",+ "required": ["cron"],+ "title": "SetScheduledChatCadenceRequest"+ },"SetUserTierRequest": {"properties": {"user_id": { "type": "string", "title": "User Id" },