Skip to content

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.

fix(platform): make editing a schedule work end to end (#15395)

Nicholas Tindleff2b6b25341c
diff --git a/autogpt_platform/backend/backend/api/features/schedules/model.py b/autogpt_platform/backend/backend/api/features/schedules/model.py
index 35ad166376..10e347c619 100644
--- a/autogpt_platform/backend/backend/api/features/schedules/model.py
+++ b/autogpt_platform/backend/backend/api/features/schedules/model.py
@@ -20,3 +20,17 @@ class ScheduleCreationRequest(pydantic.BaseModel):
default=None,
description="Attribute this schedule (and every run it fires) to a hired expert owned by the caller. If omitted, resolved automatically when exactly one active hired expert has this graph installed as a workflow.",
)
+
+
+class ScheduleUpdateRequest(pydantic.BaseModel):
+ """Fields to change on an existing schedule; omitted fields keep their value."""
+
+ name: Optional[ScheduleName] = None
+ cron: Optional[str] = None
+ inputs: Optional[dict[str, Any]] = None
+ credentials: Optional[dict[str, CredentialsMetaInput]] = None
+ timezone: Optional[str] = pydantic.Field(
+ default=None,
+ min_length=1,
+ description="Timezone to evaluate the cron in (e.g., 'America/New_York'). If not provided, the schedule keeps its current timezone.",
+ )
diff --git a/autogpt_platform/backend/backend/api/features/schedules/routes.py b/autogpt_platform/backend/backend/api/features/schedules/routes.py
index 992988a774..bf4b8aa7a5 100644
--- a/autogpt_platform/backend/backend/api/features/schedules/routes.py
+++ b/autogpt_platform/backend/backend/api/features/schedules/routes.py
@@ -7,20 +7,23 @@ from starlette.status import HTTP_404_NOT_FOUND
from backend.api.features.experts import experts_db
from backend.api.features.schedule_visibility import visible_graph_schedules
-from backend.api.features.schedules.model import ScheduleCreationRequest
+from backend.api.features.schedules.model import (
+ ScheduleCreationRequest,
+ ScheduleUpdateRequest,
+)
from backend.data import graph as graph_db
from backend.data.onboarding import OnboardingStep, complete_onboarding_step
from backend.data.tenancy import get_user_team_ids
from backend.data.user import get_user_by_id
from backend.executor import scheduler
from backend.util.clients import get_scheduler_client
-from backend.util.exceptions import NotFoundError
+from backend.util.exceptions import NotAuthorizedError, NotFoundError
from backend.util.timezone_utils import (
convert_utc_time_to_user_timezone,
get_user_timezone_or_utc,
)
-# This router mounts at /api and keeps the section's full paths: its five routes
+# This router mounts at /api and keeps the section's full paths: its six routes
# span two prefixes (/schedules and /graphs/{graph_id}/schedules), so a prefixed
# mount would have to move one of them.
router = APIRouter(dependencies=[Security(requires_user)])
@@ -179,3 +182,37 @@ async def delete_graph_execution_schedule(
detail=f"Schedule #{schedule_id} not found",
)
return {"id": schedule_id}
+
+
+ path="/schedules/{schedule_id}",
+ summary="Update execution schedule",
+)
+async def update_graph_execution_schedule(
+ user_id: Annotated[str, Security(get_user_id)],
+ schedule_id: str = Path(..., description="ID of the schedule to update"),
+ update: ScheduleUpdateRequest = Body(),
+) -> scheduler.GraphExecutionJobInfo:
+ """Change an agent schedule's name, timing or inputs. Only the schedule's
+ owner can edit it; anyone else gets the same 404 as a missing schedule."""
+ try:
+ result = await get_scheduler_client().update_execution_schedule(
+ schedule_id=schedule_id,
+ user_id=user_id,
+ name=update.name,
+ cron=update.cron,
+ user_timezone=update.timezone,
+ input_data=update.inputs,
+ input_credentials=update.credentials,
+ )
+ except (NotFoundError, NotAuthorizedError):
+ raise HTTPException(
+ status_code=HTTP_404_NOT_FOUND,
+ detail=f"Schedule #{schedule_id} not found",
+ )
+
+ if result.next_run_time:
+ result.next_run_time = convert_utc_time_to_user_timezone(
+ result.next_run_time, result.timezone
+ )
+ return result
diff --git a/autogpt_platform/backend/backend/api/features/schedules/routes_test.py b/autogpt_platform/backend/backend/api/features/schedules/routes_test.py
index 9c92efcc36..e6e2cc77fe 100644
--- a/autogpt_platform/backend/backend/api/features/schedules/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/schedules/routes_test.py
@@ -11,7 +11,7 @@ from fastapi.routing import APIRoute
from backend.api.features.schedules.routes import router
from backend.api.rest_api import app as real_app
from backend.executor import scheduler
-from backend.util.exceptions import NotFoundError
+from backend.util.exceptions import NotAuthorizedError, NotFoundError
app = fastapi.FastAPI()
app.include_router(router)
@@ -54,6 +54,7 @@ EXPECTED_OPERATIONS = {
("get", "/api/schedules"): "getV1List execution schedules for a user",
("get", "/api/schedules/followups"): "listCopilotFollowupSchedules",
("delete", "/api/schedules/{schedule_id}"): "deleteV1Delete execution schedule",
+ ("patch", "/api/schedules/{schedule_id}"): "patchV1Update execution schedule",
}
@@ -244,6 +245,71 @@ def test_delete_schedule_maps_not_found_to_404(
assert response.status_code == 404
+def test_update_schedule_rejects_an_empty_timezone(
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ """An empty timezone is a bad value, not an omitted one: it must not be
+ silently ignored while the rest of the edit is saved."""
+ sched = _patch_scheduler(mocker, update_execution_schedule=AsyncMock())
+
+ response = client.patch("/schedules/sched-1", json={"timezone": ""})
+
+ assert response.status_code == 422
+ sched.update_execution_schedule.assert_not_awaited()
+
+
+def test_update_schedule_forwards_only_the_sent_fields(
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ """Omitted fields go through as None so the scheduler keeps them, and the
+ next run comes back in the schedule's own timezone, as on create."""
+ updated = scheduler.GraphExecutionJobInfo(
+ id="sched-1",
+ name="Evening report",
+ next_run_time="2026-10-12T22:30:00+00:00",
+ timezone="America/New_York",
+ user_id="test-user-id",
+ graph_id="graph-1",
+ graph_version=1,
+ cron="30 18 * * 1,2,3,4,5",
+ input_data={},
+ )
+ sched = _patch_scheduler(
+ mocker, update_execution_schedule=AsyncMock(return_value=updated)
+ )
+
+ response = client.patch(
+ "/schedules/sched-1",
+ json={"name": "Evening report", "cron": "30 18 * * 1,2,3,4,5"},
+ )
+
+ assert response.status_code == 200
+ assert response.json()["next_run_time"] == "2026-10-12T18:30:00-04:00"
+ kwargs = sched.update_execution_schedule.await_args.kwargs
+ assert kwargs["schedule_id"] == "sched-1"
+ assert (kwargs["name"], kwargs["cron"]) == ("Evening report", "30 18 * * 1,2,3,4,5")
+ assert (
+ kwargs["user_timezone"],
+ kwargs["input_data"],
+ kwargs["input_credentials"],
+ ) == (None, None, None)
+
+
+ "error", [NotFoundError("gone"), NotAuthorizedError("not yours")]
+)
+def test_update_schedule_hides_other_users_schedules_behind_404(
+ mocker: pytest_mock.MockFixture, error: Exception
+) -> None:
+ """A schedule someone else owns must look exactly like a missing one, so
+ ids can't be probed by editing them."""
+ _patch_scheduler(mocker, update_execution_schedule=AsyncMock(side_effect=error))
+
+ response = client.patch("/schedules/sched-1", json={"cron": "0 9 * * 1-5"})
+
+ assert response.status_code == 404
+
+
def test_create_schedule_returns_404_for_an_unknown_graph(
mocker: pytest_mock.MockFixture,
) -> None:
diff --git a/autogpt_platform/backend/backend/executor/scheduler.py b/autogpt_platform/backend/backend/executor/scheduler.py
index cd8ccff76d..52bc567a64 100644
--- a/autogpt_platform/backend/backend/executor/scheduler.py
+++ b/autogpt_platform/backend/backend/executor/scheduler.py
@@ -10,8 +10,9 @@ from collections.abc import Callable
from concurrent.futures import Future
from datetime import datetime, timedelta, timezone
from enum import Enum
-from typing import Annotated, Literal, Optional, Union
+from typing import Annotated, Any, Literal, Optional, Union
from urllib.parse import parse_qs, urlencode, urlparse, urlunparse
+from zoneinfo import ZoneInfoNotFoundError
from apscheduler.events import (
EVENT_JOB_ERROR,
@@ -2011,11 +2012,37 @@ def _build_trigger(
) -> Union[CronTrigger, DateTrigger]:
if (cron is None) == (run_at is None):
raise ValueError("Exactly one of `cron` or `run_at` must be provided")
- if cron is not None:
- return CronTrigger.from_crontab(
- _normalize_cron_day_of_week(cron), timezone=user_timezone
- )
- return DateTrigger(run_date=run_at, timezone=user_timezone)
+ try:
+ if cron is not None:
+ return CronTrigger.from_crontab(
+ _normalize_cron_day_of_week(cron), timezone=user_timezone
+ )
+ return DateTrigger(run_date=run_at, timezone=user_timezone)
+ except ZoneInfoNotFoundError as e:
+ # A KeyError, which the API would turn into a 500, not a 400.
+ raise ValueError(f"Unknown timezone {user_timezone!r}") from e
+
+
+def _updated_graph_job_args(
+ info: GraphExecutionJobInfo,
+ *,
+ name: str | None,
+ cron: str | None,
+ input_data: GraphInput | None,
+ input_credentials: dict[str, CredentialsMetaInput] | None,
+) -> GraphExecutionJobArgs:
+ """The stored job args with each provided field replaced. Identity fields
+ (schedule id, owner, graph, tenancy, expert) are never editable."""
+ current = info.model_dump(include=set(GraphExecutionJobArgs.model_fields))
+ overrides = {
+ "agent_name": normalize_schedule_name(name) if name else None,
+ "cron": cron,
+ "input_data": input_data,
+ "input_credentials": input_credentials,
+ }
+ return GraphExecutionJobArgs.model_validate(
+ current | {k: v for k, v in overrides.items() if v is not None}
+ )
def _job_to_info(
@@ -2617,6 +2644,72 @@ class Scheduler(AppService):
self._invalidate_jobs_cache()
return info
+ @expose
+ def update_graph_execution_schedule(
+ self,
+ schedule_id: str,
+ user_id: str,
+ name: Optional[str] = None,
+ cron: Optional[str] = None,
+ user_timezone: Optional[str] = None,
+ input_data: Optional[GraphInput] = None,
+ input_credentials: Optional[dict[str, CredentialsMetaInput]] = None,
+ ) -> GraphExecutionJobInfo:
+ """Change an agent schedule's name, timing or inputs in place.
+
+ The job keeps its id, owner, graph and tenancy, so every reference to
+ it (Library links, the schedule index, run attribution) stays valid.
+ Trigger, kwargs and name land in one ``modify_job`` call, which the
+ jobstore writes as a single row update: a concurrent reader sees the
+ old schedule or the new one, never a mix. Omitted fields keep their
+ current value, and a paused schedule stays paused.
+ """
+ job, info = self._authorized_job(schedule_id, user_id, action="update")
+ if not isinstance(info, GraphExecutionJobInfo):
+ raise NotFoundError(f"Agent schedule #{schedule_id} not found.")
+
+ job_args = _updated_graph_job_args(
+ info,
+ name=name,
+ cron=cron,
+ input_data=input_data,
+ input_credentials=input_credentials,
+ )
+ if input_data is not None or input_credentials is not None:
+ run_async(
+ execution_utils.validate_and_construct_node_execution_input(
+ graph_id=job_args.graph_id,
+ user_id=user_id,
+ graph_inputs=job_args.input_data,
+ graph_version=job_args.graph_version,
+ graph_credentials_inputs=job_args.input_credentials,
+ )
+ )
+
+ changes: dict[str, Any] = {"kwargs": job_args.model_dump(mode="json")}
+ if name:
+ changes["name"] = job_args.agent_name
+ if cron is not None or user_timezone:
+ trigger = _build_trigger(
+ cron=job_args.cron,
+ run_at=None,
+ user_timezone=user_timezone or info.timezone,
+ )
+ changes["trigger"] = trigger
+ if job.next_run_time is not None:
+ changes["next_run_time"] = trigger.get_next_fire_time(
+ None, datetime.now(timezone.utc)
+ )
+ updated = self.scheduler.modify_job(
+ schedule_id, jobstore=Jobstores.EXECUTION.value, **changes
+ )
+ self._invalidate_jobs_cache()
+ logger.info(
+ f"Updated job {schedule_id}: cron '{job_args.cron}' in timezone "
+ f"{_timezone_from_job(updated)}"
+ )
+ return GraphExecutionJobInfo.from_db(job_args, updated)
+
def _authorized_job(
self, schedule_id: str, user_id: str, *, action: str
) -> tuple[JobObj, Union[GraphExecutionJobInfo, CopilotTurnJobInfo]]:
@@ -3592,6 +3685,9 @@ class SchedulerClient(AppServiceClient):
add_execution_schedule = endpoint_to_async(Scheduler.add_graph_execution_schedule)
add_copilot_turn_schedule = endpoint_to_async(Scheduler.add_copilot_turn_schedule)
delete_schedule = endpoint_to_async(Scheduler.delete_graph_execution_schedule)
+ update_execution_schedule = endpoint_to_async(
+ Scheduler.update_graph_execution_schedule
+ )
pause_schedule = endpoint_to_async(Scheduler.pause_execution_schedule)
resume_schedule = endpoint_to_async(Scheduler.resume_execution_schedule)
# Graph-only typed list — for legacy callers that need GraphExecutionJobInfo.
diff --git a/autogpt_platform/backend/backend/executor/scheduler_test.py b/autogpt_platform/backend/backend/executor/scheduler_test.py
index 4472697a37..15c05812f2 100644
--- a/autogpt_platform/backend/backend/executor/scheduler_test.py
+++ b/autogpt_platform/backend/backend/executor/scheduler_test.py
@@ -8,14 +8,18 @@ from apscheduler.triggers.cron import CronTrigger
from backend.api.model import CreateGraph
from backend.data import db
+from backend.data.execution import get_graph_executions
from backend.executor.scheduler import (
+ GraphExecutionJobArgs,
Jobstores,
Scheduler,
_build_trigger,
+ _execute_graph,
_normalize_cron_day_of_week,
)
from backend.usecases.sample import create_test_graph, create_test_user
from backend.util.clients import get_scheduler_client
+from backend.util.exceptions import NotAuthorizedError, NotFoundError
from backend.util.test import SpinTestServer
@@ -97,6 +101,121 @@ async def test_paused_schedule_excluded_unless_include_paused(server: SpinTestSe
assert [s.id for s in active_after_resume] == [schedule.id]
[email protected](loop_scope="session")
+async def test_update_schedule_changes_timing_and_inputs_in_place(
+ server: SpinTestServer,
+):
+ """#15281: editing a schedule rewrites its cron, timezone, inputs and name
+ on the same job, and the next run moves to the new time."""
+ await db.connect()
+ test_user = await create_test_user()
+ test_graph = await server.agent_server.test_create_graph(
+ create_graph=CreateGraph(graph=create_test_graph()),
+ user_id=test_user.id,
+ )
+ scheduler = get_scheduler_client()
+ schedule = await scheduler.add_execution_schedule(
+ graph_id=test_graph.id,
+ user_id=test_user.id,
+ graph_version=1,
+ cron="0 9 * * 1-5",
+ input_data={"input": "data"},
+ input_credentials={},
+ name="Weekday report",
+ user_timezone="UTC",
+ )
+
+ try:
+ await scheduler.update_execution_schedule(
+ schedule_id=schedule.id,
+ user_id=test_user.id,
+ name="Evening report",
+ cron="30 18 * * 1-5",
+ user_timezone="America/New_York",
+ input_data={"input": "changed"},
+ )
+
+ [stored] = await scheduler.get_execution_schedules(test_graph.id, test_user.id)
+ assert stored.id == schedule.id
+ assert (stored.name, stored.cron, stored.timezone) == (
+ "Evening report",
+ "30 18 * * 1-5",
+ "America/New_York",
+ )
+ assert stored.input_data == {"input": "changed"}
+ next_run = datetime.fromisoformat(stored.next_run_time).astimezone(
+ pytz.timezone("America/New_York")
+ )
+ assert (next_run.hour, next_run.minute) == (18, 30)
+ assert next_run.weekday() < 5
+
+ # Fire the stored job the way APScheduler does: the run it starts
+ # must carry the edited inputs and point back at this schedule.
+ await _execute_graph(
+ **stored.model_dump(include=set(GraphExecutionJobArgs.model_fields))
+ )
+ [fired] = await get_graph_executions(
+ graph_id=test_graph.id, user_id=test_user.id
+ )
+ assert fired.trigger_ref == schedule.id
+ assert fired.inputs == {"input": "changed"}
+ finally:
+ await scheduler.delete_schedule(schedule.id, user_id=test_user.id)
+
+
[email protected](loop_scope="session")
+async def test_update_schedule_is_owner_only_and_all_or_nothing(
+ server: SpinTestServer,
+):
+ """Another user can't edit the schedule, a bad cron changes nothing (not
+ even the name sent with it), and editing a paused schedule keeps it
+ paused instead of silently re-arming it."""
+ await db.connect()
+ owner = await create_test_user()
+ other = await create_test_user(alt_user=True)
+ test_graph = await server.agent_server.test_create_graph(
+ create_graph=CreateGraph(graph=create_test_graph()),
+ user_id=owner.id,
+ )
+ scheduler = get_scheduler_client()
+ schedule = await scheduler.add_execution_schedule(
+ graph_id=test_graph.id,
+ user_id=owner.id,
+ graph_version=1,
+ cron="0 9 * * 1-5",
+ input_data={"input": "data"},
+ input_credentials={},
+ name="Weekday report",
+ user_timezone="UTC",
+ )
+
+ try:
+ with pytest.raises(NotAuthorizedError):
+ await scheduler.update_execution_schedule(
+ schedule_id=schedule.id, user_id=other.id, cron="0 1 * * *"
+ )
+ with pytest.raises(ValueError):
+ await scheduler.update_execution_schedule(
+ schedule_id=schedule.id,
+ user_id=owner.id,
+ name="Renamed",
+ cron="not a cron",
+ )
+ [stored] = await scheduler.get_execution_schedules(test_graph.id, owner.id)
+ assert (stored.name, stored.cron) == ("Weekday report", "0 9 * * 1-5")
+
+ assert await scheduler.pause_schedule(schedule.id, user_id=owner.id)
+ await scheduler.update_execution_schedule(
+ schedule_id=schedule.id, user_id=owner.id, cron="0 7 * * *"
+ )
+ [paused] = await scheduler.get_execution_schedules(
+ test_graph.id, owner.id, include_paused=True
+ )
+ assert (paused.cron, paused.next_run_time) == ("0 7 * * *", "")
+ finally:
+ await scheduler.delete_schedule(schedule.id, user_id=owner.id)
+
+
# ---------------------------------------------------------------------------
# Community rebuild @expose methods — lightweight unit tests
#
@@ -168,6 +287,104 @@ class TestAddCopilotTurnScheduleExpertAttribution:
assert self._persisted_args().expert_id is None
+def test_build_trigger_reports_an_unknown_timezone_as_bad_input():
+ """APScheduler raises ZoneInfoNotFoundError (a KeyError) for an unknown
+ zone. Creating or editing a schedule with one must be a 400, not a 500."""
+ with pytest.raises(ValueError, match="Unknown timezone"):
+ _build_trigger(cron="0 9 * * *", run_at=None, user_timezone="Mars/Olympus")
+
+
+class TestUpdateGraphExecutionSchedule:
+ """In-process checks of the change set ``update_graph_execution_schedule``
+ hands APScheduler. The end-to-end behavior is covered against the real
+ scheduler service above; these pin the branches that matter for a
+ single, minimal ``modify_job`` write."""
+
+ @staticmethod
+ def _job(*, paused: bool = False, kind: str = "graph") -> MagicMock:
+ job = MagicMock(id="sched-1")
+ job.name = "Weekday report"
+ job.trigger = _build_trigger(
+ cron="0 9 * * 1,2,3,4,5", run_at=None, user_timezone="UTC"
+ )
+ job.next_run_time = None if paused else datetime.now(timezone.utc)
+ if kind == "graph":
+ job.kwargs = GraphExecutionJobArgs(
+ schedule_id="sched-1",
+ user_id="user-1",
+ graph_id="graph-1",
+ graph_version=1,
+ agent_name="Weekday report",
+ cron="0 9 * * 1,2,3,4,5",
+ input_data={"input": "data"},
+ ).model_dump(mode="json")
+ else:
+ job.kwargs = {
+ "kind": "copilot_turn",
+ "schedule_id": "sched-1",
+ "user_id": "user-1",
+ "message": "hi",
+ "cron": "0 9 * * *",
+ }
+ return job
+
+ def _update(self, job: MagicMock, **fields):
+ s = _stub_scheduler()
+ s.scheduler.get_job.return_value = job
+ s.scheduler.modify_job.return_value = job
+ with (
+ patch.object(s, "_invalidate_jobs_cache"),
+ patch("backend.executor.scheduler.run_async") as run_async,
+ ):
+ s.update_graph_execution_schedule(
+ schedule_id="sched-1", user_id="user-1", **fields
+ )
+ return s.scheduler.modify_job.call_args.kwargs, run_async
+
+ def test_new_time_and_timezone_move_the_next_run(self) -> None:
+ changes, run_async = self._update(
+ self._job(), cron="30 18 * * 1,2,3,4,5", user_timezone="America/New_York"
+ )
+ assert str(changes["trigger"].timezone) == "America/New_York"
+ assert changes["kwargs"]["cron"] == "30 18 * * 1,2,3,4,5"
+ next_run = changes["next_run_time"].astimezone(
+ pytz.timezone("America/New_York")
+ )
+ assert (next_run.hour, next_run.minute, next_run.weekday() < 5) == (
+ 18,
+ 30,
+ True,
+ )
+ assert "name" not in changes
+ run_async.assert_not_called()
+
+ def test_a_paused_schedule_stays_paused(self) -> None:
+ changes, _ = self._update(self._job(paused=True), cron="0 7 * * *")
+ assert "trigger" in changes
+ assert "next_run_time" not in changes
+
+ def test_a_rename_leaves_the_timing_alone(self) -> None:
+ changes, _ = self._update(self._job(), name=" Evening report ")
+ assert changes["name"] == "Evening report"
+ assert changes["kwargs"]["agent_name"] == "Evening report"
+ assert changes["kwargs"]["input_data"] == {"input": "data"}
+ assert "trigger" not in changes
+
+ def test_new_inputs_are_validated_against_the_graph(self) -> None:
+ changes, run_async = self._update(self._job(), input_data={"input": "new"})
+ assert changes["kwargs"]["input_data"] == {"input": "new"}
+ run_async.assert_called_once()
+
+ def test_a_copilot_follow_up_is_not_an_agent_schedule(self) -> None:
+ s = _stub_scheduler()
+ s.scheduler.get_job.return_value = self._job(kind="copilot_turn")
+ with pytest.raises(NotFoundError):
+ s.update_graph_execution_schedule(
+ schedule_id="sched-1", user_id="user-1", cron="0 7 * * *"
+ )
+ s.scheduler.modify_job.assert_not_called()
+
+
class TestAddCommunityRebuildSchedule:
def test_registers_with_expected_cron_and_jobstore(self) -> None:
s = _stub_scheduler()
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/ScheduleAgentModal/components/ModalScheduleSection/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/ScheduleAgentModal/components/ModalScheduleSection/helpers.ts
index 2ab489784c..e74bb661e1 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/ScheduleAgentModal/components/ModalScheduleSection/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/ScheduleAgentModal/components/ModalScheduleSection/helpers.ts
@@ -26,25 +26,3 @@ export function validateSchedule(
}
return fieldErrors;
}
-
-export type ParsedCron = {
- repeat: "daily" | "weekly";
- selectedDays: string[]; // for weekly, 0-6 (0=Sun) as strings
- time: string; // HH:MM
-};
-
-export function parseCronToForm(cron: string): ParsedCron | undefined {
- if (!cron) return undefined;
- const parts = cron.trim().split(/\s+/);
- if (parts.length !== 5) return undefined;
- const [minute, hour, _dom, _mon, dow] = parts;
- const hh = String(hour ?? "0").padStart(2, "0");
- const mm = String(minute ?? "0").padStart(2, "0");
- const time = `${hh}:${mm}`; // Cron is stored in UTC; we keep raw HH:MM
-
- if (dow && dow !== "*") {
- return { repeat: "weekly", selectedDays: dow.split(","), time };
- }
-
- return { repeat: "daily", selectedDays: [], time };
-}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedScheduleView/components/EditScheduleModal/EditScheduleModal.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedScheduleView/components/EditScheduleModal/EditScheduleModal.tsx
index d7fd90d012..ceeec81f97 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedScheduleView/components/EditScheduleModal/EditScheduleModal.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedScheduleView/components/EditScheduleModal/EditScheduleModal.tsx
@@ -6,6 +6,7 @@ import { Button } from "@/components/atoms/Button/Button";
import { Input } from "@/components/atoms/Input/Input";
import { MultiToggle } from "@/components/molecules/MultiToggle/MultiToggle";
import { Select } from "@/components/atoms/Select/Select";
+import { Text } from "@/components/atoms/Text/Text";
import { GraphExecutionJobInfo } from "@/app/api/__generated__/models/graphExecutionJobInfo";
import { useEditScheduleModal } from "./useEditScheduleModal";
import { PencilEdit02Icon } from "@hugeicons/core-free-icons";
@@ -15,18 +16,22 @@ type Props = {
graphId: string;
schedule: GraphExecutionJobInfo;
triggerClassName?: string;
+ iconOnly?: boolean;
};
export function EditScheduleModal({
graphId,
schedule,
triggerClassName,
+ iconOnly = false,
}: Props) {
const {
isOpen,
setIsOpen,
name,
setName,
+ canEditTiming,
+ recurrenceLabel,
repeat,
setRepeat,
selectedDays,
@@ -36,7 +41,7 @@ export function EditScheduleModal({
errors,
repeatOptions,
dayItems,
- mutateAsync,
+ handleSave,
isPending,
} = useEditScheduleModal(graphId, schedule);
@@ -47,13 +52,19 @@ export function EditScheduleModal({
styling={{ maxWidth: "22rem" }}
>
<Dialog.Trigger>
- <Button
- variant="ghost"
- size="small"
- className={triggerClassName ?? "absolute -right-2 -top-2"}
- >
- <Icon icon={PencilEdit02Icon} className="size-4" /> Edit schedule
- </Button>
+ {iconOnly ? (
+ <Button variant="icon" size="icon" aria-label="Edit schedule">
+ <Icon icon={PencilEdit02Icon} size={18} className="text-zinc-700" />
+ </Button>
+ ) : (
+ <Button
+ variant="ghost"
+ size="small"
+ className={triggerClassName ?? "absolute -right-2 -top-2"}
+ >
+ <Icon icon={PencilEdit02Icon} className="size-4" /> Edit schedule
+ </Button>
+ )}
</Dialog.Trigger>
<Dialog.Content>
<div className="flex flex-col gap-6">
@@ -64,29 +75,45 @@ export function EditScheduleModal({
onChange={(e) => setName(e.target.value)}
error={errors.scheduleName}
/>
- <Select
- id="repeat"
- label="Repeats"
- value={repeat}
- onValueChange={setRepeat}
- options={repeatOptions}
- />
- {repeat === "weekly" && (
- <MultiToggle
- items={dayItems}
- selectedValues={selectedDays}
- onChange={setSelectedDays}
- aria-label="Select days"
- />
+ {canEditTiming ? (
+ <>
+ <Select
+ id="repeat"
+ label="Repeats"
+ value={repeat}
+ onValueChange={setRepeat}
+ options={repeatOptions}
+ />
+ {repeat === "weekly" && (
+ <div className="flex flex-col gap-1">
+ <MultiToggle
+ items={dayItems}
+ selectedValues={selectedDays}
+ onChange={setSelectedDays}
+ aria-label="Select days"
+ />
+ {errors.days && (
+ <Text variant="small" tone="danger">
+ {errors.days}
+ </Text>
+ )}
+ </div>
+ )}
+ <Input
+ id="schedule-time"
+ label="At"
+ value={time}
+ onChange={(e) => setTime(e.target.value.trim())}
+ placeholder="00:00"
+ error={errors.time}
+ />
+ </>
+ ) : (
+ <Text variant="body" tone="muted">
+ Repeats {recurrenceLabel.toLowerCase()}. This timing can&apos;t be
+ changed here, so saving only renames the schedule.
+ </Text>
)}
- <Input
- id="schedule-time"
- label="At"
- value={time}
- onChange={(e) => setTime(e.target.value.trim())}
- placeholder="00:00"
- error={errors.time}
- />
</div>
<Dialog.Footer>
<div className="flex w-full justify-end gap-2">
@@ -101,7 +128,7 @@ export function EditScheduleModal({
<Button
variant="primary"
size="small"
- onClick={() => mutateAsync()}
+ onClick={handleSave}
loading={isPending}
className="min-w-32"
>
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedScheduleView/components/EditScheduleModal/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedScheduleView/components/EditScheduleModal/helpers.ts
new file mode 100644
index 0000000000..a55f60903b
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedScheduleView/components/EditScheduleModal/helpers.ts
@@ -0,0 +1,67 @@
+import type { GraphExecutionJobInfo } from "@/app/api/__generated__/models/graphExecutionJobInfo";
+
+export const REPEAT_OPTIONS = [
+ { value: "daily", label: "Daily" },
+ { value: "weekly", label: "Weekly" },
+];
+
+export const DAY_ITEMS = [
+ { value: "0", label: "Su" },
+ { value: "1", label: "Mo" },
+ { value: "2", label: "Tu" },
+ { value: "3", label: "We" },
+ { value: "4", label: "Th" },
+ { value: "5", label: "Fr" },
+ { value: "6", label: "Sa" },
+];
+
+export interface EditScheduleForm {
+ name: string;
+ // False when the cron is something this form can't express (hourly,
+ // monthly, ranges, steps...). Saving then sends the name only, so the
+ // schedule's timing is never rewritten into a daily or weekly one.
+ canEditTiming: boolean;
+ repeat: string;
+ selectedDays: string[];
+ time: string;
+}
+
+export function formFromSchedule(
+ schedule: GraphExecutionJobInfo,
+): EditScheduleForm {
+ const timing = parseEditableCron(schedule.cron);
+ return {
+ name: schedule.name,
+ canEditTiming: timing !== undefined,
+ repeat: timing?.repeat ?? "daily",
+ selectedDays: timing?.selectedDays ?? [],
+ time: timing?.time ?? "00:00",
+ };
+}
+
+export function buildCron(form: EditScheduleForm): string {
+ const [hh, mm] = form.time.split(":");
+ const minute = Number(mm || 0);
+ const hour = Number(hh || 0);
+ const days =
+ form.repeat === "weekly"
+ ? [...form.selectedDays].sort((a, b) => Number(a) - Number(b)).join(",")
+ : "*";
+ return `${minute} ${hour} * * ${days}`;
+}
+
+function parseEditableCron(cron: string) {
+ const parts = cron.trim().split(/\s+/);
+ if (parts.length !== 5) return undefined;
+ const [minute, hour, dayOfMonth, month, dayOfWeek] = parts;
+ if (!/^\d{1,2}$/.test(minute) || !/^\d{1,2}$/.test(hour)) return undefined;
+ if (dayOfMonth !== "*" || month !== "*") return undefined;
+ if (Number(minute) > 59 || Number(hour) > 23) return undefined;
+
+ const time = `${hour.padStart(2, "0")}:${minute.padStart(2, "0")}`;
+ if (dayOfWeek === "*") return { repeat: "daily", selectedDays: [], time };
+
+ const days = dayOfWeek.split(",");
+ if (!days.every((day) => /^[0-6]$/.test(day))) return undefined;
+ return { repeat: "weekly", selectedDays: days, time };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedScheduleView/components/EditScheduleModal/useEditScheduleModal.test.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedScheduleView/components/EditScheduleModal/useEditScheduleModal.test.tsx
index b9ecd2fe5e..2bb4478605 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedScheduleView/components/EditScheduleModal/useEditScheduleModal.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedScheduleView/components/EditScheduleModal/useEditScheduleModal.test.tsx
@@ -1,14 +1,17 @@
+import { getPatchV1UpdateExecutionScheduleMockHandler } from "@/app/api/__generated__/endpoints/schedules/schedules.msw";
import type { GraphExecutionJobInfo } from "@/app/api/__generated__/models/graphExecutionJobInfo";
+import { server } from "@/mocks/mock-server";
import * as invalidateSchedules from "@/services/schedules/invalidate-schedules";
import { act, renderHook, waitFor } from "@/tests/integrations/test-utils";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { http, HttpResponse } from "msw";
import type { ReactNode } from "react";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { useEditScheduleModal } from "./useEditScheduleModal";
function wrapper({ children }: { children: ReactNode }) {
const client = new QueryClient({
- defaultOptions: { queries: { retry: false } },
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
});
return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
}
@@ -25,9 +28,6 @@ vi.mock("@/components/molecules/Toast/use-toast", async (importOriginal) => {
};
});
-const fetchMock = vi.fn();
-const originalFetch = globalThis.fetch;
-
const schedule = {
id: "sched-1",
name: "Daily",
@@ -35,22 +35,27 @@ const schedule = {
} as unknown as GraphExecutionJobInfo;
beforeEach(() => {
- fetchMock.mockReset();
toastMock.mockClear();
- globalThis.fetch = fetchMock as unknown as typeof globalThis.fetch;
});
afterEach(() => {
vi.restoreAllMocks();
- globalThis.fetch = originalFetch;
});
describe("useEditScheduleModal", () => {
- test("successful PATCH invalidates ALL schedule queries (regression: previously only invalidated per-graph)", async () => {
- fetchMock.mockResolvedValueOnce({
- ok: true,
- json: async () => ({}),
- });
+ test("saves the new name and time through the schedules PATCH endpoint", async () => {
+ let received: { scheduleId: unknown; body: unknown } | undefined;
+ server.use(
+ getPatchV1UpdateExecutionScheduleMockHandler(
+ async ({ request, params }) => {
+ received = {
+ scheduleId: params.scheduleId,
+ body: await request.json(),
+ };
+ return { ...schedule, cron: "30 18 * * *" };
+ },
+ ),
+ );
const invalidateSpy = vi.spyOn(
invalidateSchedules,
"invalidateAllScheduleQueries",
@@ -60,9 +65,12 @@ describe("useEditScheduleModal", () => {
() => useEditScheduleModal("graph-xyz", schedule),
{ wrapper },
);
-
- await act(async () => {
- await result.current.mutateAsync();
+ act(() => {
+ result.current.setName("Evening");
+ result.current.setTime("18:30");
+ });
+ act(() => {
+ result.current.handleSave();
});
await waitFor(() => {
@@ -71,17 +79,18 @@ describe("useEditScheduleModal", () => {
"graph-xyz",
);
});
- expect(fetchMock).toHaveBeenCalledWith(
- "/api/schedules/sched-1",
- expect.objectContaining({ method: "PATCH" }),
- );
+ expect(received).toEqual({
+ scheduleId: "sched-1",
+ body: { name: "Evening", cron: "30 18 * * *" },
+ });
});
- test("failed PATCH surfaces destructive toast and does NOT invalidate", async () => {
- fetchMock.mockResolvedValueOnce({
- ok: false,
- json: async () => ({ message: "Bad cron" }),
- });
+ test("a rejected save shows the server's reason and does not invalidate", async () => {
+ server.use(
+ http.patch("/api/proxy/api/schedules/:scheduleId", () =>
+ HttpResponse.json({ detail: "Invalid cron" }, { status: 400 }),
+ ),
+ );
const invalidateSpy = vi.spyOn(
invalidateSchedules,
"invalidateAllScheduleQueries",
@@ -91,20 +100,92 @@ describe("useEditScheduleModal", () => {
() => useEditScheduleModal("graph-xyz", schedule),
{ wrapper },
);
-
- await expect(
- act(async () => {
- await result.current.mutateAsync();
- }),
- ).rejects.toThrow();
+ act(() => {
+ result.current.handleSave();
+ });
await waitFor(() => {
expect(toastMock).toHaveBeenCalledWith(
expect.objectContaining({
+ description: expect.stringContaining("Invalid cron"),
variant: "destructive",
}),
);
});
expect(invalidateSpy).not.toHaveBeenCalled();
});
+
+ test("reopening after the selected schedule changes loads that schedule, not the last one", async () => {
+ const other = {
+ ...schedule,
+ id: "sched-2",
+ name: "Weekly sync",
+ cron: "15 7 * * 1,3",
+ } as GraphExecutionJobInfo;
+ const { result, rerender } = renderHook(
+ ({ current }) => useEditScheduleModal("graph-xyz", current),
+ { wrapper, initialProps: { current: schedule } },
+ );
+ act(() => {
+ result.current.setIsOpen(true);
+ result.current.setName("Half-typed");
+ });
+
+ rerender({ current: other });
+ act(() => {
+ result.current.setIsOpen(false);
+ });
+ act(() => {
+ result.current.setIsOpen(true);
+ });
+
+ expect(result.current.name).toBe("Weekly sync");
+ expect(result.current.repeat).toBe("weekly");
+ expect(result.current.selectedDays).toEqual(["1", "3"]);
+ expect(result.current.time).toBe("07:15");
+ });
+
+ test("a timing the form can't express is never rewritten: saving sends the name only", async () => {
+ let body: unknown;
+ server.use(
+ getPatchV1UpdateExecutionScheduleMockHandler(async ({ request }) => {
+ body = await request.json();
+ return schedule;
+ }),
+ );
+ const everyQuarterHour = {
+ ...schedule,
+ cron: "*/15 * * * *",
+ } as GraphExecutionJobInfo;
+
+ const { result } = renderHook(
+ () => useEditScheduleModal("graph-xyz", everyQuarterHour),
+ { wrapper },
+ );
+ expect(result.current.canEditTiming).toBe(false);
+ act(() => {
+ result.current.setName("Renamed");
+ });
+ act(() => {
+ result.current.handleSave();
+ });
+
+ await waitFor(() => expect(body).toEqual({ name: "Renamed" }));
+ });
+
+ test("weekly with no days asks for a day instead of saving a daily schedule", () => {
+ const { result } = renderHook(
+ () => useEditScheduleModal("graph-xyz", schedule),
+ { wrapper },
+ );
+ act(() => {
+ result.current.setRepeat("weekly");
+ result.current.setSelectedDays([]);
+ });
+ act(() => {
+ result.current.handleSave();
+ });
+
+ expect(result.current.errors.days).toBe("Pick at least one day");
+ });
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedScheduleView/components/EditScheduleModal/useEditScheduleModal.ts b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedScheduleView/components/EditScheduleModal/useEditScheduleModal.ts
index a6912fcf78..34cfa5ef34 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedScheduleView/components/EditScheduleModal/useEditScheduleModal.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedScheduleView/components/EditScheduleModal/useEditScheduleModal.ts
@@ -1,15 +1,27 @@
"use client";
import { getGetV1ListGraphExecutionsQueryKey } from "@/app/api/__generated__/endpoints/graphs/graphs";
+import { usePatchV1UpdateExecutionSchedule } from "@/app/api/__generated__/endpoints/schedules/schedules";
import type { GraphExecutionJobInfo } from "@/app/api/__generated__/models/graphExecutionJobInfo";
import { useToast } from "@/components/molecules/Toast/use-toast";
+import { safeHumanizeCronExpression } from "@/lib/cron-expression-utils";
import { invalidateAllScheduleQueries } from "@/services/schedules/invalidate-schedules";
-import { useMutation, useQueryClient } from "@tanstack/react-query";
-import { useMemo, useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { useState } from "react";
+import { validateSchedule } from "../../../../modals/ScheduleAgentModal/components/ModalScheduleSection/helpers";
import {
- parseCronToForm,
- validateSchedule,
-} from "../../../../modals/ScheduleAgentModal/components/ModalScheduleSection/helpers";
+ buildCron,
+ DAY_ITEMS,
+ type EditScheduleForm,
+ formFromSchedule,
+ REPEAT_OPTIONS,
+} from "./helpers";
+
+interface FormErrors {
+ scheduleName?: string;
+ time?: string;
+ days?: string;
+}
export function useEditScheduleModal(
graphId: string,
@@ -18,108 +30,84 @@ export function useEditScheduleModal(
const queryClient = useQueryClient();
const { toast } = useToast();
const [isOpen, setIsOpen] = useState(false);
- const [name, setName] = useState(schedule.name);
-
- const parsed = useMemo(() => parseCronToForm(schedule.cron), [schedule.cron]);
- const [repeat, setRepeat] = useState<string>(parsed?.repeat || "daily");
- const [selectedDays, setSelectedDays] = useState<string[]>(
- parsed?.selectedDays || [],
- );
- const [time, setTime] = useState<string>(parsed?.time || "00:00");
- const [errors, setErrors] = useState<{
- scheduleName?: string;
- time?: string;
- }>({});
-
- const repeatOptions = useMemo(
- () => [
- { value: "daily", label: "Daily" },
- { value: "weekly", label: "Weekly" },
- ],
- [],
- );
+ const [form, setForm] = useState(() => formFromSchedule(schedule));
+ const [errors, setErrors] = useState<FormErrors>({});
- const dayItems = useMemo(
- () => [
- { value: "0", label: "Su" },
- { value: "1", label: "Mo" },
- { value: "2", label: "Tu" },
- { value: "3", label: "We" },
- { value: "4", label: "Th" },
- { value: "5", label: "Fr" },
- { value: "6", label: "Sa" },
- ],
- [],
- );
+ function update(fields: Partial<EditScheduleForm>) {
+ setForm((current) => ({ ...current, ...fields }));
+ }
- function humanizeToCron(): string {
- const [hh, mm] = time.split(":");
- const minute = Number(mm || 0);
- const hour = Number(hh || 0);
- if (repeat === "weekly") {
- const dow = selectedDays.length ? selectedDays.join(",") : "*";
- return `${minute} ${hour} * * ${dow}`;
+ // The dialog stays mounted while the selected schedule changes, so the form
+ // reloads from whichever schedule is current each time it opens.
+ function handleOpenChange(open: boolean) {
+ if (open) {
+ setForm(formFromSchedule(schedule));
+ setErrors({});
}
- return `${minute} ${hour} * * *`;
+ setIsOpen(open);
}
- const { mutateAsync, isPending } = useMutation({
- mutationKey: ["patchSchedule", schedule.id],
- mutationFn: async () => {
- const errorsNow = validateSchedule({ scheduleName: name, time });
- setErrors(errorsNow);
- if (Object.keys(errorsNow).length > 0) throw new Error("Invalid form");
+ const { mutate: updateSchedule, isPending } =
+ usePatchV1UpdateExecutionSchedule({
+ mutation: {
+ onSuccess: async () => {
+ invalidateAllScheduleQueries(queryClient, graphId);
+ const runsKey = getGetV1ListGraphExecutionsQueryKey(graphId);
+ await queryClient.invalidateQueries({ queryKey: runsKey });
+ setIsOpen(false);
+ },
+ onError: (error) => {
+ toast({
+ title: "Failed to update schedule",
+ description:
+ error instanceof Error
+ ? error.message
+ : "An unexpected error occurred.",
+ variant: "destructive",
+ });
+ },
+ },
+ });
- const cron = humanizeToCron();
- const res = await fetch(`/api/schedules/${schedule.id}`, {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ name, cron }),
- });
- if (!res.ok) {
- let message = "Failed to update schedule";
- try {
- const data = await res.json();
- message = data?.message || data?.detail || message;
- } catch {
- try {
- message = await res.text();
- } catch {}
- }
- throw new Error(message);
- }
- return res.json();
- },
- onSuccess: async () => {
- invalidateAllScheduleQueries(queryClient, graphId);
- const runsKey = getGetV1ListGraphExecutionsQueryKey(graphId);
- await queryClient.invalidateQueries({ queryKey: runsKey });
- setIsOpen(false);
- },
- onError: (error: any) => {
- toast({
- title: "❌ Failed to update schedule",
- description: error?.message || "An unexpected error occurred.",
- variant: "destructive",
- });
- },
- });
+ function handleSave() {
+ const errorsNow: FormErrors = validateSchedule({
+ scheduleName: form.name,
+ time: form.canEditTiming ? form.time : undefined,
+ });
+ if (
+ form.canEditTiming &&
+ form.repeat === "weekly" &&
+ form.selectedDays.length === 0
+ ) {
+ errorsNow.days = "Pick at least one day";
+ }
+ setErrors(errorsNow);
+ if (Object.keys(errorsNow).length > 0) return;
+ updateSchedule({
+ scheduleId: schedule.id,
+ data: form.canEditTiming
+ ? { name: form.name, cron: buildCron(form) }
+ : { name: form.name },
+ });
+ }
return {
isOpen,
- setIsOpen,
- name,
- setName,
- repeat,
- setRepeat,
- selectedDays,
- setSelectedDays,
- time,
- setTime,
+ setIsOpen: handleOpenChange,
+ name: form.name,
+ setName: (name: string) => update({ name }),
+ canEditTiming: form.canEditTiming,
+ recurrenceLabel: safeHumanizeCronExpression(schedule.cron),
+ repeat: form.repeat,
+ setRepeat: (repeat: string) => update({ repeat }),
+ selectedDays: form.selectedDays,
+ setSelectedDays: (selectedDays: string[]) => update({ selectedDays }),
+ time: form.time,
+ setTime: (time: string) => update({ time }),
errors,
- repeatOptions,
- dayItems,
- mutateAsync,
+ repeatOptions: REPEAT_OPTIONS,
+ dayItems: DAY_ITEMS,
+ handleSave,
isPending,
- } as const;
+ };
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedScheduleView/components/SelectedScheduleActions/SelectedScheduleActions.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedScheduleView/components/SelectedScheduleActions/SelectedScheduleActions.tsx
index 4d0cea77c5..e2ddf4b0c3 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedScheduleView/components/SelectedScheduleActions/SelectedScheduleActions.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedScheduleView/components/SelectedScheduleActions/SelectedScheduleActions.tsx
@@ -8,6 +8,7 @@ import { Text } from "@/components/atoms/Text/Text";
import { Dialog } from "@/components/molecules/Dialog/Dialog";
import { AgentActionsDropdown } from "../../../AgentActionsDropdown";
import { SelectedActionsWrap } from "../../../SelectedActionsWrap";
+import { EditScheduleModal } from "../EditScheduleModal/EditScheduleModal";
import { useSelectedScheduleActions } from "./useSelectedScheduleActions";
import { Delete02Icon, EyeIcon, PlayIcon } from "@hugeicons/core-free-icons";
import { Icon } from "@/components/atoms/Icon/Icon";
@@ -71,6 +72,13 @@ export function SelectedScheduleActions({
<Icon icon={EyeIcon} size={18} className="text-zinc-700" />
</Button>
)}
+ {schedule && (
+ <EditScheduleModal
+ graphId={agent.graph_id}
+ schedule={schedule}
+ iconOnly
+ />
+ )}
<Button
variant="icon"
size="icon"
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 5298c5a18b..830cb2c862 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -14248,6 +14248,57 @@
}
}
}
+ },
+ "patch": {
+ "tags": ["v1", "schedules"],
+ "summary": "Update execution schedule",
+ "description": "Change an agent schedule's name, timing or inputs. Only the schedule's\nowner can edit it; anyone else gets the same 404 as a missing schedule.",
+ "operationId": "patchV1Update execution schedule",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "schedule_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "description": "ID of the schedule to update",
+ "title": "Schedule Id"
+ },
+ "description": "ID of the schedule to update"
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/ScheduleUpdateRequest" }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/GraphExecutionJobInfo"
+ }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
}
},
"/api/search/global": {
@@ -29506,6 +29557,48 @@
"required": ["message", "schedule_id", "paused"],
"title": "ScheduleToggledResponse"
},
+ "ScheduleUpdateRequest": {
+ "properties": {
+ "name": {
+ "anyOf": [
+ { "type": "string", "minLength": 1, "pattern": "\\S" },
+ { "type": "null" }
+ ],
+ "title": "Name"
+ },
+ "cron": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Cron"
+ },
+ "inputs": {
+ "anyOf": [
+ { "additionalProperties": true, "type": "object" },
+ { "type": "null" }
+ ],
+ "title": "Inputs"
+ },
+ "credentials": {
+ "anyOf": [
+ {
+ "additionalProperties": {
+ "$ref": "#/components/schemas/CredentialsMetaInput"
+ },
+ "type": "object"
+ },
+ { "type": "null" }
+ ],
+ "title": "Credentials"
+ },
+ "timezone": {
+ "anyOf": [{ "type": "string", "minLength": 1 }, { "type": "null" }],
+ "title": "Timezone",
+ "description": "Timezone to evaluate the cron in (e.g., 'America/New_York'). If not provided, the schedule keeps its current timezone."
+ }
+ },
+ "type": "object",
+ "title": "ScheduleUpdateRequest",
+ "description": "Fields to change on an existing schedule; omitted fields keep their value."
+ },
"SchedulesListResponse": {
"properties": {
"schedules": {
diff --git a/autogpt_platform/frontend/src/playwright/journeys/schedules-journey.spec.ts b/autogpt_platform/frontend/src/playwright/journeys/schedules-journey.spec.ts
new file mode 100644
index 0000000000..6e45ffb03f
--- /dev/null
+++ b/autogpt_platform/frontend/src/playwright/journeys/schedules-journey.spec.ts
@@ -0,0 +1,218 @@
+import { randomBytes } from "crypto";
+import type { Page } from "@playwright/test";
+import { expect, test } from "../coverage-fixture";
+import { createUniqueAgentName } from "../pages/build.page";
+import { LibraryPage } from "../pages/library.page";
+
+const TIMEZONE = "America/New_York";
+const STORE_VALUE_BLOCK_ID = "1ff065e9-88e8-4358-9d82-8dc91f622ba9";
+
+test.use({ storageState: { cookies: [], origins: [] }, timezoneId: TIMEZONE });
+
+interface Schedule {
+ id: string;
+ name: string;
+ cron: string;
+ next_run_time: string;
+}
+
+test.describe("schedules journey", () => {
+ test("a weekday schedule can be created, edited, and deleted from the Library, and every change survives a reload", async ({
+ page,
+ }) => {
+ test.setTimeout(90_000);
+ await signUpJourneyUser(page);
+ const agentName = createUniqueAgentName("Journey schedule");
+ const graphId = await createAgent(page, agentName);
+
+ await new LibraryPage(page).openSavedAgent(agentName);
+ await page
+ .getByRole("button", { name: /Setup your task|New agent task/i })
+ .first()
+ .click();
+ await page.getByRole("button", { name: "Schedule Task" }).click();
+ const createDialog = page.getByRole("dialog", { name: "Schedule Run" });
+ await createDialog.getByLabel("Schedule Name").fill("Weekday report");
+ await selectOption(page, createDialog.locator("#repeat"), "Weekly");
+ await createDialog.getByRole("button", { name: "Weekdays" }).click();
+ await createDialog.getByRole("button", { name: "Schedule" }).click();
+ // Saving waits on the scheduler service, which is slow on a cold stack.
+ await expect(createDialog).toBeHidden({ timeout: 30_000 });
+
+ const created = await onlySchedule(page, graphId);
+ expect(created.cron).toBe("0 9 * * 1,2,3,4,5");
+ expectWeekdayAt(created, 9, 0);
+ await openSchedule(page, "Weekday report");
+ await expect(nextRunText(page)).toContainText("09:00");
+
+ await page.getByRole("button", { name: "Edit schedule" }).first().click();
+ const editDialog = page.getByRole("dialog", { name: "Edit Schedule" });
+ await editDialog.locator("#schedule-name").fill("Evening report");
+ await editDialog.locator("#schedule-time").fill("18:30");
+ await editDialog.getByRole("button", { name: "Save" }).click();
+ await expect(editDialog).toBeHidden({ timeout: 30_000 });
+
+ await page.reload();
+ await openSchedule(page, "Evening report");
+ await expect(nextRunText(page)).toContainText("18:30");
+ const edited = await onlySchedule(page, graphId);
+ expect(edited.id).toBe(created.id);
+ expect(edited.cron).toBe("30 18 * * 1,2,3,4,5");
+ expectWeekdayAt(edited, 18, 30);
+
+ await page.getByRole("button", { name: "Delete schedule" }).first().click();
+ await page.getByRole("button", { name: "Delete Schedule" }).click();
+ await expect.poll(() => listSchedules(page, graphId)).toEqual([]);
+ await page.reload();
+ await expect(page.getByText("Evening report")).toHaveCount(0);
+ const runs = await page.request.get(
+ `/api/proxy/api/graphs/${graphId}/executions`,
+ );
+ expect(await runs.json()).toMatchObject({ executions: [] });
+ });
+});
+
+function nextRunText(page: Page) {
+ return page.getByText("Next run", { exact: true }).locator("xpath=..");
+}
+
+async function openSchedule(page: Page, name: string) {
+ await page.getByRole("tab", { name: /^Scheduled/ }).click();
+ await page.getByText(name, { exact: true }).first().click();
+ await expect(page.getByText("Next run", { exact: true })).toBeVisible();
+}
+
+async function selectOption(
+ page: Page,
+ trigger: ReturnType<Page["locator"]>,
+ option: string,
+) {
+ await trigger.click();
+ await page.getByRole("option", { name: option, exact: true }).click();
+}
+
+async function listSchedules(page: Page, graphId: string) {
+ const response = await page.request.get(
+ `/api/proxy/api/graphs/${graphId}/schedules`,
+ );
+ expect(response.ok(), `listing schedules: ${response.status()}`).toBe(true);
+ return (await response.json()) as Schedule[];
+}
+
+async function onlySchedule(page: Page, graphId: string) {
+ const schedules = await listSchedules(page, graphId);
+ expect(schedules).toHaveLength(1);
+ return schedules[0];
+}
+
+// The scheduler must evaluate the cron in the user's timezone: the next run
+// is a Monday-to-Friday date at exactly the wall-clock time they picked.
+function expectWeekdayAt(schedule: Schedule, hour: number, minute: number) {
+ const parts = Object.fromEntries(
+ new Intl.DateTimeFormat("en-US", {
+ timeZone: TIMEZONE,
+ weekday: "short",
+ hour: "2-digit",
+ minute: "2-digit",
+ hourCycle: "h23",
+ })
+ .formatToParts(new Date(schedule.next_run_time))
+ .map((p) => [p.type, p.value]),
+ );
+ expect(["Mon", "Tue", "Wed", "Thu", "Fri"]).toContain(parts.weekday);
+ expect([Number(parts.hour), Number(parts.minute)]).toEqual([hour, minute]);
+}
+
+// Onboarding steps that dismiss the first-visit cards covering the Library.
+const COMPLETED_ONBOARDING_STEPS = [
+ "ONBOARDING_COMPLETE",
+ "AGENT_NEW_RUN",
+ "CAPABILITY_CARDS",
+ "AGENTS_TAB_INTRO",
+ "MARKETPLACE_TAB_INTRO",
+ "BUILD_TAB_INTRO",
+ "WORKFLOWS_MOVED",
+];
+
+// A brand-new user by default. Previews paywall fresh users, so there
+// PLAYWRIGHT_JOURNEY_EMAIL and PLAYWRIGHT_JOURNEY_PASSWORD sign in as an
+// existing subscribed account instead.
+async function signUpJourneyUser(page: Page) {
+ const email = process.env.PLAYWRIGHT_JOURNEY_EMAIL;
+ const password = process.env.PLAYWRIGHT_JOURNEY_PASSWORD;
+ if (email && password) {
+ const signIn = await page.request.post("/api/auth/sign-in/email", {
+ headers: { Origin: appOrigin() },
+ data: { email, password },
+ });
+ expect(signIn.ok(), `sign-in failed: ${signIn.status()}`).toBe(true);
+ } else {
+ const id = `${Date.now()}-${randomBytes(3).toString("hex")}`;
+ const signUp = await page.request.post("/api/auth/sign-up/email", {
+ headers: { Origin: appOrigin() },
+ data: {
+ email: `journey-${id}@${journeyEmailDomain()}`,
+ password: `Journey-${randomBytes(12).toString("hex")}`,
+ name: `Journey ${id}`,
+ },
+ });
+ expect(signUp.ok(), `sign-up failed: ${signUp.status()}`).toBe(true);
+ }
+ for (const step of COMPLETED_ONBOARDING_STEPS) {
+ const onboarding = await page.request.post(
+ "/api/proxy/api/onboarding/step",
+ { params: { step } },
+ );
+ expect(onboarding.ok(), `onboarding step ${step} failed`).toBe(true);
+ }
+ const timezone = await page.request.post(
+ "/api/proxy/api/auth/user/timezone",
+ { data: { timezone: TIMEZONE } },
+ );
+ expect(timezone.ok(), "setting the user's timezone failed").toBe(true);
+}
+
+async function createAgent(page: Page, name: string): Promise<string> {
+ const response = await page.request.post("/api/proxy/api/graphs", {
+ data: {
+ source: "upload",
+ graph: {
+ name,
+ description: "Stores a value, for the schedules journey",
+ is_active: true,
+ nodes: [
+ {
+ id: "store",
+ block_id: STORE_VALUE_BLOCK_ID,
+ input_default: { input: "scheduled" },
+ metadata: { position: { x: 0, y: 0 } },
+ input_links: [],
+ output_links: [],
+ },
+ ],
+ links: [],
+ },
+ },
+ });
+ expect(response.ok(), `creating the agent failed: ${response.status()}`).toBe(
+ true,
+ );
+ return (await response.json()).id;
+}
+
+function appOrigin() {
+ return new URL(process.env.PLAYWRIGHT_BASE_URL ?? "http://localhost:3000")
+ .origin;
+}
+
+// Previews only accept sign-ups from allowlisted domains; @previews.agpt.co
+// keeps password sign-up and needs no inbox.
+function journeyEmailDomain() {
+ if (process.env.PLAYWRIGHT_JOURNEY_EMAIL_DOMAIN) {
+ return process.env.PLAYWRIGHT_JOURNEY_EMAIL_DOMAIN;
+ }
+ const { hostname } = new URL(appOrigin());
+ return ["localhost", "127.0.0.1", "[::1]"].includes(hostname)
+ ? "example.com"
+ : "previews.agpt.co";
+}