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.
refactor(backend): move the schedule routes into their own feature module (#14473)
Reinier van der Leer35e8d9d80a37
diff --git a/autogpt_platform/backend/backend/api/features/schedules/__init__.py b/autogpt_platform/backend/backend/api/features/schedules/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/autogpt_platform/backend/backend/api/features/schedules/model.py b/autogpt_platform/backend/backend/api/features/schedules/model.pynew file mode 100644index 0000000000..b05c8bbf4f--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/schedules/model.py@@ -0,0 +1,21 @@+from typing import Any, Optional++import pydantic++from backend.data.model import CredentialsMetaInput+++class ScheduleCreationRequest(pydantic.BaseModel):+ graph_version: Optional[int] = None+ name: str+ cron: str+ inputs: dict[str, Any]+ credentials: dict[str, CredentialsMetaInput] = pydantic.Field(default_factory=dict)+ timezone: Optional[str] = pydantic.Field(+ default=None,+ description="User's timezone for scheduling (e.g., 'America/New_York'). If not provided, will use user's saved timezone or UTC.",+ )+ expert_id: Optional[str] = pydantic.Field(+ 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.",+ )diff --git a/autogpt_platform/backend/backend/api/features/schedules/routes.py b/autogpt_platform/backend/backend/api/features/schedules/routes.pynew file mode 100644index 0000000000..512f1d603e--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/schedules/routes.py@@ -0,0 +1,176 @@+from typing import Annotated, Any++from autogpt_libs.auth import get_request_context, get_user_id, requires_user+from autogpt_libs.auth.models import RequestContext+from fastapi import APIRouter, Body, HTTPException, Path, Security+from starlette.status import HTTP_404_NOT_FOUND++from backend.api.features.experts import experts_db+from backend.api.features.schedules.model import ScheduleCreationRequest+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.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+# 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)])+++ path="/graphs/{graph_id}/schedules",+ summary="Create execution schedule",+)+async def create_graph_execution_schedule(+ user_id: Annotated[str, Security(get_user_id)],+ ctx: Annotated[RequestContext, Security(get_request_context)],+ graph_id: str = Path(..., description="ID of the graph to schedule"),+ schedule_params: ScheduleCreationRequest = Body(),+) -> scheduler.GraphExecutionJobInfo:+ graph = await graph_db.get_graph(+ graph_id=graph_id,+ version=schedule_params.graph_version,+ user_id=user_id,+ )+ if not graph:+ raise HTTPException(+ status_code=404,+ detail=f"Graph #{graph_id} v{schedule_params.graph_version} not found.",+ )++ # Use timezone from request if provided, otherwise fetch from user profile+ if schedule_params.timezone:+ user_timezone = schedule_params.timezone+ else:+ user = await get_user_by_id(user_id)+ user_timezone = get_user_timezone_or_utc(user.timezone if user else None)++ # Expert attribution: explicit expert_id must be an active expert owned+ # by the caller; when omitted, a unique (user, graph) → expert match+ # keeps attribution for schedules created through the generic UI.+ expert_id = schedule_params.expert_id+ if expert_id is not None:+ expert = await experts_db.get_expert(+ user_id, expert_id, include_workflows=False+ )+ if expert is None or expert.is_archived:+ raise HTTPException(+ status_code=404, detail=f"Expert #{expert_id} not found."+ )+ else:+ expert_id = await experts_db.resolve_expert_for_graph(user_id, graph_id)++ result = await get_scheduler_client().add_execution_schedule(+ user_id=user_id,+ graph_id=graph_id,+ graph_version=graph.version,+ name=schedule_params.name,+ cron=schedule_params.cron,+ input_data=schedule_params.inputs,+ input_credentials=schedule_params.credentials,+ user_timezone=user_timezone,+ organization_id=ctx.org_id,+ team_id=ctx.team_id,+ expert_id=expert_id,+ )++ # Convert the next_run_time back to user timezone for display+ if result.next_run_time:+ result.next_run_time = convert_utc_time_to_user_timezone(+ result.next_run_time, user_timezone+ )++ await complete_onboarding_step(user_id, OnboardingStep.SCHEDULE_AGENT)++ return result+++ path="/graphs/{graph_id}/schedules",+ summary="List execution schedules for a graph",+)+async def list_graph_execution_schedules(+ user_id: Annotated[str, Security(get_user_id)],+ ctx: Annotated[RequestContext, Security(get_request_context)],+ graph_id: str = Path(),+) -> list[scheduler.GraphExecutionJobInfo]:+ team_ids = await get_user_team_ids(user_id, ctx.org_id) if ctx.org_id else []+ return await get_scheduler_client().get_graph_execution_schedules(+ user_id=user_id,+ graph_id=graph_id,+ organization_id=ctx.org_id,+ team_ids=team_ids,+ )+++ path="/schedules",+ summary="List execution schedules for a user",+)+async def list_all_graphs_execution_schedules(+ user_id: Annotated[str, Security(get_user_id)],+ ctx: Annotated[RequestContext, Security(get_request_context)],+) -> list[scheduler.GraphExecutionJobInfo]:+ team_ids = await get_user_team_ids(user_id, ctx.org_id) if ctx.org_id else []+ return await get_scheduler_client().get_graph_execution_schedules(+ user_id=user_id,+ organization_id=ctx.org_id,+ team_ids=team_ids,+ )+++# Keep above /schedules/{schedule_id}: a GET added there would otherwise match+# "followups" as an id, since FastAPI answers with the first route that fits.+ path="/schedules/followups",+ summary="List copilot follow-up schedules for a user",+ operation_id="listCopilotFollowupSchedules",+)+async def list_copilot_turn_schedules(+ user_id: Annotated[str, Security(get_user_id)],+) -> list[scheduler.CopilotTurnJobInfo]:+ """Return only copilot-turn schedules for the current user.++ Sibling of :func:`list_all_graphs_execution_schedules`; one route per kind+ keeps the generated frontend client typed to a single concrete return type+ instead of a discriminated union.+ """+ schedules = await get_scheduler_client().get_execution_schedules(+ user_id=user_id, kind="copilot_turn"+ )+ # Defensive isinstance filter mirrors ``get_graph_execution_schedules``+ # (executor.scheduler.Scheduler) — the scheduler is the source of truth+ # for the ``kind`` filter, but we narrow the polymorphic+ # ``list[GraphExecutionJobInfo | CopilotTurnJobInfo]`` to the typed+ # subset before returning so the generated frontend client gets a single+ # concrete schema. If a row ever slips through the discriminator (e.g.+ # legacy untyped row, scheduler-side bug), we drop it rather than fail+ # the response with a Pydantic validation error.+ return [s for s in schedules if isinstance(s, scheduler.CopilotTurnJobInfo)]+++ path="/schedules/{schedule_id}",+ summary="Delete execution schedule",+)+async def delete_graph_execution_schedule(+ user_id: Annotated[str, Security(get_user_id)],+ ctx: Annotated[RequestContext, Security(get_request_context)],+ schedule_id: str = Path(..., description="ID of the schedule to delete"),+) -> dict[str, Any]:+ try:+ await get_scheduler_client().delete_schedule(schedule_id, user_id=user_id)+ except NotFoundError:+ raise HTTPException(+ status_code=HTTP_404_NOT_FOUND,+ detail=f"Schedule #{schedule_id} not found",+ )+ return {"id": schedule_id}diff --git a/autogpt_platform/backend/backend/api/features/schedules/routes_test.py b/autogpt_platform/backend/backend/api/features/schedules/routes_test.pynew file mode 100644index 0000000000..9c92efcc36--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/schedules/routes_test.py@@ -0,0 +1,324 @@+"""Tests for the schedule routes."""++from unittest.mock import AsyncMock, Mock++import fastapi+import fastapi.testclient+import pytest+import pytest_mock+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++app = fastapi.FastAPI()+app.include_router(router)+client = fastapi.testclient.TestClient(app)++[email protected](autouse=True)+def setup_app_auth(mock_jwt_user, test_user_id):+ from autogpt_libs.auth.dependencies import get_request_context+ from autogpt_libs.auth.jwt_utils import get_jwt_payload+ from autogpt_libs.auth.models import RequestContext++ app.dependency_overrides[get_jwt_payload] = mock_jwt_user["get_jwt_payload"]++ # The real get_request_context queries Prisma to resolve the personal org,+ # which closes the test event loop between sync TestClient calls.+ async def _fake_request_context() -> RequestContext:+ return RequestContext(+ user_id=test_user_id,+ org_id="test-org",+ team_id=None,+ is_org_owner=True,+ is_org_admin=True,+ is_org_billing_manager=False,+ is_team_admin=True,+ is_team_billing_manager=False,+ seat_status="ACTIVE",+ )++ app.dependency_overrides[get_request_context] = _fake_request_context+ yield+ app.dependency_overrides.clear()+++EXPECTED_OPERATIONS = {+ ("post", "/api/graphs/{graph_id}/schedules"): "postV1Create execution schedule",+ ("get", "/api/graphs/{graph_id}/schedules"): (+ "getV1List execution schedules for a graph"+ ),+ ("get", "/api/schedules"): "getV1List execution schedules for a user",+ ("get", "/api/schedules/followups"): "listCopilotFollowupSchedules",+ ("delete", "/api/schedules/{schedule_id}"): "deleteV1Delete execution schedule",+}+++ "method,path,operation_id",+ [(m, p, oid) for (m, p), oid in EXPECTED_OPERATIONS.items()],+)+def test_schedule_operation_is_published(method: str, path: str, operation_id: str):+ """The mounted surface is contract: the generated frontend client is built from it."""+ operation = real_app.openapi()["paths"][path][method]+ assert operation["operationId"] == operation_id+ assert operation["tags"] == ["v1", "schedules"]+++def test_schedule_surface_has_no_other_operations():+ published = {+ (method, path)+ for path, operations in real_app.openapi()["paths"].items()+ for method, operation in operations.items()+ if "schedules" in operation["tags"] and "v1" in operation["tags"]+ }+ assert published == set(EXPECTED_OPERATIONS)++[email protected]("path", sorted({p for _, p in EXPECTED_OPERATIONS}))+def test_schedule_path_is_served_by_this_module(path: str):+ handlers = {+ route.endpoint.__module__+ for route in real_app.routes+ if isinstance(route, APIRoute) and route.path == path+ }+ assert handlers == {"backend.api.features.schedules.routes"}+++def test_followups_is_not_shadowed_by_the_schedule_id_route():+ """Only registration order keeps these apart; a GET on {schedule_id} would win."""+ paths = [+ route.path+ for route in real_app.routes+ if isinstance(route, APIRoute) and route.path.startswith("/api/schedules/")+ ]+ assert paths.index("/api/schedules/followups") < paths.index(+ "/api/schedules/{schedule_id}"+ )+++def test_list_copilot_turn_schedules_filters_to_copilot_kind(+ mocker: pytest_mock.MockFixture,+ test_user_id: str,+) -> None:+ """GET /schedules/followups returns only CopilotTurnJobInfo items for the user.++ The route delegates to ``Scheduler.get_execution_schedules(kind="copilot_turn")``;+ we mock the client to make sure (a) the kind filter is forwarded and+ (b) any non-copilot rows are dropped from the response.+ """+ from backend.executor.scheduler import CopilotTurnJobInfo, GraphExecutionJobInfo++ copilot_info = CopilotTurnJobInfo(+ id="sched-1",+ name="copilot followup",+ next_run_time="2026-05-22T10:00:00+00:00",+ timezone="UTC",+ user_id=test_user_id,+ session_id="sess-1",+ message="check status",+ cron="0 9 * * *",+ )+ graph_info = GraphExecutionJobInfo(+ id="sched-2",+ name="graph run",+ next_run_time="2026-05-22T11:00:00+00:00",+ timezone="UTC",+ user_id=test_user_id,+ graph_id="g-1",+ graph_version=1,+ cron="0 10 * * *",+ input_data={},+ )++ mock_client = Mock()+ mock_client.get_execution_schedules = AsyncMock(+ return_value=[copilot_info, graph_info]+ )+ mocker.patch(+ "backend.api.features.schedules.routes.get_scheduler_client",+ return_value=mock_client,+ )++ response = client.get("/schedules/followups")++ assert response.status_code == 200+ body = response.json()+ assert len(body) == 1+ assert body[0]["id"] == "sched-1"+ assert body[0]["kind"] == "copilot_turn"+ assert body[0]["session_id"] == "sess-1"++ mock_client.get_execution_schedules.assert_awaited_once_with(+ user_id=test_user_id, kind="copilot_turn"+ )+++def _job_info(**overrides) -> scheduler.GraphExecutionJobInfo:+ defaults = {+ "id": "sched-1",+ "name": "nightly",+ "next_run_time": "2026-01-01T03:00:00+00:00",+ "user_id": "user-1",+ "graph_id": "graph-1",+ "graph_version": 3,+ "cron": "0 3 * * *",+ "input_data": {},+ }+ defaults.update(overrides)+ return scheduler.GraphExecutionJobInfo(**defaults)+++def _patch_scheduler(mocker: pytest_mock.MockFixture, **methods) -> Mock:+ scheduler_client = Mock()+ for name, value in methods.items():+ setattr(scheduler_client, name, value)+ mocker.patch(+ "backend.api.features.schedules.routes.get_scheduler_client",+ return_value=scheduler_client,+ )+ return scheduler_client+++def test_list_graph_execution_schedules_scopes_to_the_graph(+ mocker: pytest_mock.MockFixture,+) -> None:+ sched = _patch_scheduler(+ mocker, get_graph_execution_schedules=AsyncMock(return_value=[_job_info()])+ )+ mocker.patch(+ "backend.api.features.schedules.routes.get_user_team_ids",+ AsyncMock(return_value=["team-9"]),+ )++ response = client.get("/graphs/graph-1/schedules")++ assert response.status_code == 200+ assert [s["id"] for s in response.json()] == ["sched-1"]+ assert sched.get_graph_execution_schedules.await_args.kwargs["graph_id"] == (+ "graph-1"+ )+++def test_list_all_schedules_does_not_scope_to_a_graph(+ mocker: pytest_mock.MockFixture,+) -> None:+ """The user-wide route shares a scheduler method with the per-graph one, so+ passing a graph_id here would silently narrow it."""+ sched = _patch_scheduler(+ mocker, get_graph_execution_schedules=AsyncMock(return_value=[])+ )+ mocker.patch(+ "backend.api.features.schedules.routes.get_user_team_ids",+ AsyncMock(return_value=[]),+ )++ response = client.get("/schedules")++ assert response.status_code == 200+ assert "graph_id" not in sched.get_graph_execution_schedules.await_args.kwargs+++def test_delete_schedule_returns_the_id(mocker: pytest_mock.MockFixture) -> None:+ sched = _patch_scheduler(mocker, delete_schedule=AsyncMock())++ response = client.delete("/schedules/sched-1")++ assert response.status_code == 200+ assert response.json() == {"id": "sched-1"}+ assert sched.delete_schedule.await_args.args[0] == "sched-1"+++def test_delete_schedule_maps_not_found_to_404(+ mocker: pytest_mock.MockFixture,+) -> None:+ _patch_scheduler(+ mocker, delete_schedule=AsyncMock(side_effect=NotFoundError("gone"))+ )++ response = client.delete("/schedules/missing")++ assert response.status_code == 404+++def test_create_schedule_returns_404_for_an_unknown_graph(+ mocker: pytest_mock.MockFixture,+) -> None:+ mocker.patch(+ "backend.api.features.schedules.routes.graph_db.get_graph",+ AsyncMock(return_value=None),+ )++ response = client.post(+ "/graphs/graph-1/schedules",+ json={"name": "nightly", "cron": "0 3 * * *", "inputs": {}},+ )++ assert response.status_code == 404+++def test_create_schedule_resolves_the_expert_when_none_is_given(+ mocker: pytest_mock.MockFixture,+) -> None:+ """Attribution for schedules made through the generic UI rests on this+ lookup; without it every such schedule loses its expert."""+ mocker.patch(+ "backend.api.features.schedules.routes.graph_db.get_graph",+ AsyncMock(return_value=Mock(version=3)),+ )+ mocker.patch(+ "backend.api.features.schedules.routes.experts_db.resolve_expert_for_graph",+ AsyncMock(return_value="expert-7"),+ )+ sched = _patch_scheduler(+ mocker, add_execution_schedule=AsyncMock(return_value=_job_info())+ )+ mocker.patch(+ "backend.api.features.schedules.routes.complete_onboarding_step", AsyncMock()+ )++ response = client.post(+ "/graphs/graph-1/schedules",+ json={+ "name": "nightly",+ "cron": "0 3 * * *",+ "inputs": {},+ "timezone": "Europe/Amsterdam",+ },+ )++ assert response.status_code == 200+ kwargs = sched.add_execution_schedule.await_args.kwargs+ assert kwargs["expert_id"] == "expert-7"+ assert kwargs["user_timezone"] == "Europe/Amsterdam"+++def test_create_schedule_rejects_an_archived_expert(+ mocker: pytest_mock.MockFixture,+) -> None:+ """An explicit expert_id must be live and the caller's; an archived one+ would otherwise attribute the schedule's spend to a retired expert."""+ mocker.patch(+ "backend.api.features.schedules.routes.graph_db.get_graph",+ AsyncMock(return_value=Mock(version=3)),+ )+ mocker.patch(+ "backend.api.features.schedules.routes.experts_db.get_expert",+ AsyncMock(return_value=Mock(is_archived=True)),+ )++ response = client.post(+ "/graphs/graph-1/schedules",+ json={+ "name": "nightly",+ "cron": "0 3 * * *",+ "inputs": {},+ "timezone": "UTC",+ "expert_id": "expert-7",+ },+ )++ assert response.status_code == 404diff --git a/autogpt_platform/backend/backend/api/features/skills/routes_test.py b/autogpt_platform/backend/backend/api/features/skills/routes_test.pyindex fe0286edc8..799d06e6c2 100644--- a/autogpt_platform/backend/backend/api/features/skills/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/skills/routes_test.py@@ -384,6 +384,8 @@ def test_expert_skill_routes_refuse_an_expert_the_caller_does_not_own(("upload", "store_user_skill"),("read", "read_user_skill_with_body"),("delete", "delete_user_skill"),+ ("upload_package", "store_user_skill"),+ ("download_package", "read_user_skill_package"),],)def test_expert_skill_routes_forward_an_owned_expert(diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.pyindex cdf9361d94..af717d2485 100644--- a/autogpt_platform/backend/backend/api/features/v1.py+++ b/autogpt_platform/backend/backend/api/features/v1.py@@ -49,7 +49,6 @@ from backend.api.features.executions.activity_gate import (hide_activity_summaries_if_disabled,hide_activity_summary_if_disabled,)-from backend.api.features.experts import experts_dbfrom backend.api.features.workspace.routes import create_file_download_responsefrom backend.api.model import (CreateGraph,@@ -123,7 +122,6 @@ from backend.data.subscription_trial_billing import (sync_trials_for_billing_event,)from backend.data.tally import extract_business_understanding-from backend.data.tenancy import get_user_team_idsfrom backend.data.understanding import (BusinessUnderstandingInput,upsert_business_understanding,@@ -139,7 +137,6 @@ from backend.data.user import (verify_preference_token,)from backend.data.workspace import get_workspace_file_by_id-from backend.executor import schedulerfrom backend.executor import utils as execution_utilsfrom backend.integrations.webhooks.graph_lifecycle_hooks import (before_graph_activate,@@ -153,7 +150,6 @@ from backend.notifications import lifecyclefrom backend.notifications.queue import queue_pass_workfrom backend.notifications.trial import notify_trial, on_trial_invoicefrom backend.util.cache import cached-from backend.util.clients import get_scheduler_clientfrom backend.util.cloud_storage import get_cloud_storage_handlerfrom backend.util.exceptions import (GraphValidationError,@@ -163,10 +159,7 @@ from backend.util.exceptions import (from backend.util.feature_flag import Flag, evaluate_feature_flagfrom backend.util.json import dumpsfrom backend.util.settings import Settings-from backend.util.timezone_utils import (- convert_utc_time_to_user_timezone,- get_user_timezone_or_utc,-)+from backend.util.timezone_utils import get_user_timezone_or_utcfrom backend.util.virus_scanner import scan_content_safefrom .library import db as library_db@@ -2560,183 +2553,3 @@ async def download_shared_file(raise HTTPException(status_code=404, detail="Not found")return await create_file_download_response(file)---########################################################-##################### Schedules ########################-########################################################---class ScheduleCreationRequest(pydantic.BaseModel):- graph_version: Optional[int] = None- name: str- cron: str- inputs: dict[str, Any]- credentials: dict[str, CredentialsMetaInput] = pydantic.Field(default_factory=dict)- timezone: Optional[str] = pydantic.Field(- default=None,- description="User's timezone for scheduling (e.g., 'America/New_York'). If not provided, will use user's saved timezone or UTC.",- )- expert_id: Optional[str] = pydantic.Field(- 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.",- )---@v1_router.post(- path="/graphs/{graph_id}/schedules",- summary="Create execution schedule",- tags=["schedules"],- dependencies=[Security(requires_user)],-)-async def create_graph_execution_schedule(- user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],- graph_id: str = Path(..., description="ID of the graph to schedule"),- schedule_params: ScheduleCreationRequest = Body(),-) -> scheduler.GraphExecutionJobInfo:- graph = await graph_db.get_graph(- graph_id=graph_id,- version=schedule_params.graph_version,- user_id=user_id,- )- if not graph:- raise HTTPException(- status_code=404,- detail=f"Graph #{graph_id} v{schedule_params.graph_version} not found.",- )-- # Use timezone from request if provided, otherwise fetch from user profile- if schedule_params.timezone:- user_timezone = schedule_params.timezone- else:- user = await get_user_by_id(user_id)- user_timezone = get_user_timezone_or_utc(user.timezone if user else None)-- # Expert attribution: explicit expert_id must be an active expert owned- # by the caller; when omitted, a unique (user, graph) → expert match- # keeps attribution for schedules created through the generic UI.- expert_id = schedule_params.expert_id- if expert_id is not None:- expert = await experts_db.get_expert(- user_id, expert_id, include_workflows=False- )- if expert is None or expert.is_archived:- raise HTTPException(- status_code=404, detail=f"Expert #{expert_id} not found."- )- else:- expert_id = await experts_db.resolve_expert_for_graph(user_id, graph_id)-- result = await get_scheduler_client().add_execution_schedule(- user_id=user_id,- graph_id=graph_id,- graph_version=graph.version,- name=schedule_params.name,- cron=schedule_params.cron,- input_data=schedule_params.inputs,- input_credentials=schedule_params.credentials,- user_timezone=user_timezone,- organization_id=ctx.org_id,- team_id=ctx.team_id,- expert_id=expert_id,- )-- # Convert the next_run_time back to user timezone for display- if result.next_run_time:- result.next_run_time = convert_utc_time_to_user_timezone(- result.next_run_time, user_timezone- )-- await complete_onboarding_step(user_id, OnboardingStep.SCHEDULE_AGENT)-- return result---@v1_router.get(- path="/graphs/{graph_id}/schedules",- summary="List execution schedules for a graph",- tags=["schedules"],- dependencies=[Security(requires_user)],-)-async def list_graph_execution_schedules(- user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],- graph_id: str = Path(),-) -> list[scheduler.GraphExecutionJobInfo]:- team_ids = await get_user_team_ids(user_id, ctx.org_id) if ctx.org_id else []- return await get_scheduler_client().get_graph_execution_schedules(- user_id=user_id,- graph_id=graph_id,- organization_id=ctx.org_id,- team_ids=team_ids,- )---@v1_router.get(- path="/schedules",- summary="List execution schedules for a user",- tags=["schedules"],- dependencies=[Security(requires_user)],-)-async def list_all_graphs_execution_schedules(- user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],-) -> list[scheduler.GraphExecutionJobInfo]:- team_ids = await get_user_team_ids(user_id, ctx.org_id) if ctx.org_id else []- return await get_scheduler_client().get_graph_execution_schedules(- user_id=user_id,- organization_id=ctx.org_id,- team_ids=team_ids,- )---@v1_router.get(- path="/schedules/followups",- summary="List copilot follow-up schedules for a user",- operation_id="listCopilotFollowupSchedules",- tags=["schedules"],- dependencies=[Security(requires_user)],-)-async def list_copilot_turn_schedules(- user_id: Annotated[str, Security(get_user_id)],-) -> list[scheduler.CopilotTurnJobInfo]:- """Return only copilot-turn schedules for the current user.-- Sibling of :func:`list_all_graphs_execution_schedules`; one route per kind- keeps the generated frontend client typed to a single concrete return type- instead of a discriminated union.- """- schedules = await get_scheduler_client().get_execution_schedules(- user_id=user_id, kind="copilot_turn"- )- # Defensive isinstance filter mirrors ``get_graph_execution_schedules``- # (executor.scheduler.Scheduler) — the scheduler is the source of truth- # for the ``kind`` filter, but we narrow the polymorphic- # ``list[GraphExecutionJobInfo | CopilotTurnJobInfo]`` to the typed- # subset before returning so the generated frontend client gets a single- # concrete schema. If a row ever slips through the discriminator (e.g.- # legacy untyped row, scheduler-side bug), we drop it rather than fail- # the response with a Pydantic validation error.- return [s for s in schedules if isinstance(s, scheduler.CopilotTurnJobInfo)]---@v1_router.delete(- path="/schedules/{schedule_id}",- summary="Delete execution schedule",- tags=["schedules"],- dependencies=[Security(requires_user)],-)-async def delete_graph_execution_schedule(- user_id: Annotated[str, Security(get_user_id)],- ctx: Annotated[RequestContext, Security(get_request_context)],- schedule_id: str = Path(..., description="ID of the schedule to delete"),-) -> dict[str, Any]:- try:- await get_scheduler_client().delete_schedule(schedule_id, user_id=user_id)- except NotFoundError:- raise HTTPException(- status_code=HTTP_404_NOT_FOUND,- detail=f"Schedule #{schedule_id} not found",- )- return {"id": schedule_id}diff --git a/autogpt_platform/backend/backend/api/features/v1_test.py b/autogpt_platform/backend/backend/api/features/v1_test.pyindex 92bde90c58..19bc62bd9e 100644--- a/autogpt_platform/backend/backend/api/features/v1_test.py+++ b/autogpt_platform/backend/backend/api/features/v1_test.py@@ -1339,60 +1339,3 @@ async def test_upload_file_gcs_not_configured_fallback(test_user_id: str):# Verify cloud storage methods were NOT calledmock_handler.store_file.assert_not_called()---def test_list_copilot_turn_schedules_filters_to_copilot_kind(- mocker: pytest_mock.MockFixture,- test_user_id: str,-) -> None:- """GET /schedules/followups returns only CopilotTurnJobInfo items for the user.-- The route delegates to ``Scheduler.get_execution_schedules(kind="copilot_turn")``;- we mock the client to make sure (a) the kind filter is forwarded and- (b) any non-copilot rows are dropped from the response.- """- from backend.executor.scheduler import CopilotTurnJobInfo, GraphExecutionJobInfo-- copilot_info = CopilotTurnJobInfo(- id="sched-1",- name="copilot followup",- next_run_time="2026-05-22T10:00:00+00:00",- timezone="UTC",- user_id=test_user_id,- session_id="sess-1",- message="check status",- cron="0 9 * * *",- )- graph_info = GraphExecutionJobInfo(- id="sched-2",- name="graph run",- next_run_time="2026-05-22T11:00:00+00:00",- timezone="UTC",- user_id=test_user_id,- graph_id="g-1",- graph_version=1,- cron="0 10 * * *",- input_data={},- )-- mock_client = Mock()- mock_client.get_execution_schedules = AsyncMock(- return_value=[copilot_info, graph_info]- )- mocker.patch(- "backend.api.features.v1.get_scheduler_client",- return_value=mock_client,- )-- response = client.get("/schedules/followups")-- assert response.status_code == 200- body = response.json()- assert len(body) == 1- assert body[0]["id"] == "sched-1"- assert body[0]["kind"] == "copilot_turn"- assert body[0]["session_id"] == "sess-1"-- mock_client.get_execution_schedules.assert_awaited_once_with(- user_id=test_user_id, kind="copilot_turn"- )diff --git a/autogpt_platform/backend/backend/api/rest_api.py b/autogpt_platform/backend/backend/api/rest_api.pyindex 7287dfc2e1..478fe7c5a6 100644--- a/autogpt_platform/backend/backend/api/rest_api.py+++ b/autogpt_platform/backend/backend/api/rest_api.py@@ -54,6 +54,7 @@ import backend.api.features.otto.routesimport backend.api.features.platform_linking.routesimport backend.api.features.postmark.postmarkimport backend.api.features.push.routes as push_routes+import backend.api.features.schedules.routes as schedules_routesimport backend.api.features.search.routes as search_routesimport backend.api.features.skills.routes as skills_routesimport backend.api.features.store.model@@ -397,6 +398,11 @@ app.include_router(tags=["v1", "skills"],prefix="/api/skills",)+app.include_router(+ schedules_routes.router,+ tags=["v1", "schedules"],+ prefix="/api",+)app.include_router(auth_email_routes.auth_email_router,prefix="/api/auth/email",diff --git a/autogpt_platform/backend/backend/copilot/tools/session_context.py b/autogpt_platform/backend/backend/copilot/tools/session_context.pyindex dc6b735a6e..810d1f29a8 100644--- a/autogpt_platform/backend/backend/copilot/tools/session_context.py+++ b/autogpt_platform/backend/backend/copilot/tools/session_context.py@@ -128,7 +128,7 @@ async def build_session_context(session_id: str, user_id: str) -> str:# The endpoint already narrows by ``kind`` server-side; the isinstance# filter is a belt-and-braces guard against a legacy untyped row that- # might slip through (matches ``v1.list_copilot_turn_schedules``).+ # might slip through (matches ``schedules.routes.list_copilot_turn_schedules``).jobs = [j for j in raw_jobs if isinstance(j, CopilotTurnJobInfo)]if not jobs: