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(backend): use the timezone AutoPilot was given when scheduling an agent (#14434)
Reinier van der Leere92b55f1c094
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_agent.py b/autogpt_platform/backend/backend/copilot/tools/run_agent.pyindex bf8127aa5f..973bb48f8a 100644--- a/autogpt_platform/backend/backend/copilot/tools/run_agent.py+++ b/autogpt_platform/backend/backend/copilot/tools/run_agent.py@@ -28,6 +28,7 @@ from backend.util.exceptions import (from backend.util.timezone_utils import (convert_utc_time_to_user_timezone,get_user_timezone_or_utc,+ validate_timezone,)from .base import BaseTool@@ -117,7 +118,7 @@ class RunAgentInput(BaseModel):use_defaults: bool = Falseschedule_name: str = ""cron: str = ""- timezone: str = "UTC"+ timezone: str = ""wait_for_result: int = Field(default=0, ge=0, le=MAX_TOOL_WAIT_SECONDS)dry_run: bool = Field(default=False)save_as_preset: bool = False@@ -208,7 +209,7 @@ class RunAgentTool(BaseTool):},"timezone": {"type": "string",- "description": "IANA timezone (default: UTC).",+ "description": "IANA timezone for the cron expression. Omit to use the user's configured timezone.",},"wait_for_result": {"type": "integer",@@ -1166,14 +1167,31 @@ class RunAgentTool(BaseTool):session_id=session_id,)+ # Precedence mirrors POST /graphs/{graph_id}/schedules: an explicit+ # timezone wins over the user's stored preference, which wins over UTC.+ # Resolved before the library agent, so a rejected timezone persists nothing.+ if timezone:+ # Never silently downgrade to UTC here — the model has already told+ # the user which timezone it is scheduling in.+ if not validate_timezone(timezone):+ return ErrorResponse(+ message=(+ f"'{timezone}' is not a valid IANA timezone. Use a name "+ "like 'Europe/London', or omit it to use the user's "+ "configured timezone."+ ),+ error="invalid_timezone",+ session_id=session_id,+ )+ user_timezone = timezone+ else:+ user = await user_db().get_user_by_id(user_id)+ user_timezone = get_user_timezone_or_utc(user.timezone)+# Get or create library agentlibrary_agent = await get_or_create_library_agent(graph, user_id)emit_tool_display_name(library_agent.name)- # Get user timezone- user = await user_db().get_user_by_id(user_id)- user_timezone = get_user_timezone_or_utc(user.timezone if user else timezone)-# Create schedule — the scheduler re-validates credentials via# ``validate_and_construct_node_execution_input`` and will raise# ``GraphValidationError`` if any required credential is missingdiff --git a/autogpt_platform/backend/backend/copilot/tools/run_agent_test.py b/autogpt_platform/backend/backend/copilot/tools/run_agent_test.pyindex b3aeb8f9c3..20c7286120 100644--- a/autogpt_platform/backend/backend/copilot/tools/run_agent_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/run_agent_test.py@@ -5,6 +5,7 @@ import orjsonimport pytestfrom backend.data.execution import ExecutionStatus+from backend.data.model import USER_TIMEZONE_NOT_SETfrom backend.executor.scheduler import GraphExecutionJobInfofrom backend.executor.utils import is_credential_validation_error_messagefrom backend.util.exceptions import (@@ -21,6 +22,7 @@ from ._test_data import ()from .models import ErrorResponse, ExecutionStartedResponse, SetupRequirementsResponsefrom .run_agent import RunAgentInput, RunAgentTool+from .utils import get_or_create_library_agent# This is so the formatter doesn't remove the fixture importssetup_llm_test_data = setup_llm_test_data@@ -903,6 +905,126 @@ async def test_run_agent_schedule_structural_error_returns_error_response(assert result_data.get("type") != "setup_requirements"[email protected](loop_scope="session")+async def test_schedule_prefers_explicit_timezone_over_stored_preference(+ setup_test_data,+):+ """The QA repro: AutoPilot asks for a timezone, confirms it back to the+ user, and the schedule must be created in that one — not the profile's."""+ _, fake_scheduler, _ = await _schedule_with_timezone(+ setup_test_data,+ stored_timezone="Europe/Amsterdam",+ timezone="Europe/London",+ )++ kwargs = fake_scheduler.add_execution_schedule.await_args.kwargs+ assert kwargs["user_timezone"] == "Europe/London"++[email protected](loop_scope="session")+async def test_schedule_without_explicit_timezone_uses_stored_preference(+ setup_test_data,+):+ _, fake_scheduler, _ = await _schedule_with_timezone(+ setup_test_data, stored_timezone="Europe/Amsterdam"+ )++ kwargs = fake_scheduler.add_execution_schedule.await_args.kwargs+ assert kwargs["user_timezone"] == "Europe/Amsterdam"++[email protected](loop_scope="session")+async def test_schedule_falls_back_to_utc_when_user_has_no_timezone(+ setup_test_data,+):+ _, fake_scheduler, _ = await _schedule_with_timezone(+ setup_test_data, stored_timezone=USER_TIMEZONE_NOT_SET+ )++ kwargs = fake_scheduler.add_execution_schedule.await_args.kwargs+ assert kwargs["user_timezone"] == "UTC"++[email protected](loop_scope="session")+async def test_schedule_rejects_invalid_explicit_timezone(setup_test_data):+ """An unknown timezone is refused, never silently downgraded to UTC —+ the model has already told the user which timezone it is scheduling in."""+ response, fake_scheduler, library_agent_spy = await _schedule_with_timezone(+ setup_test_data,+ stored_timezone="Europe/Amsterdam",+ timezone="Mars/Olympus_Mons",+ )++ assert response is not None+ assert isinstance(response.output, str)+ result_data = orjson.loads(response.output)+ assert result_data.get("error") == "invalid_timezone"+ assert "Mars/Olympus_Mons" in result_data["message"]+ assert fake_scheduler.add_execution_schedule.await_count == 0+ # A rejected schedule must not have added the agent to the user's library.+ assert library_agent_spy.await_count == 0+++async def _schedule_with_timezone(+ setup_test_data, *, stored_timezone: str, **run_agent_kwargs+):+ """Schedule an agent and hand back (response, scheduler mock, library-agent spy)."""+ user = setup_test_data["user"]+ store_submission = setup_test_data["store_submission"]+ tool = RunAgentTool()++ fake_scheduler = AsyncMock()+ fake_scheduler.add_execution_schedule.return_value = GraphExecutionJobInfo(+ id=str(uuid.uuid4()),+ name="My Schedule",+ next_run_time="",+ timezone="UTC",+ user_id=user.id,+ graph_id=str(uuid.uuid4()),+ graph_version=1,+ cron="0 10 * * *",+ input_data={},+ )++ library_agent_spy = AsyncMock(wraps=get_or_create_library_agent)++ with (+ patch(+ "backend.copilot.tools.run_agent.get_scheduler_client",+ return_value=fake_scheduler,+ ),+ patch(+ "backend.copilot.tools.run_agent.user_db",+ _fake_user_db(stored_timezone),+ ),+ patch(+ "backend.copilot.tools.run_agent.get_or_create_library_agent",+ library_agent_spy,+ ),+ ):+ response = await tool.execute(+ user_id=user.id,+ session_id=str(uuid.uuid4()),+ tool_call_id=str(uuid.uuid4()),+ username_agent_slug=(f"{user.email.split('@')[0]}/{store_submission.slug}"),+ inputs={"test_input": "value"},+ schedule_name="My Schedule",+ cron="0 10 * * *",+ dry_run=False,+ session=make_session(user_id=user.id),+ **run_agent_kwargs,+ )+ return response, fake_scheduler, library_agent_spy+++def _fake_user_db(stored_timezone: str):+ """Stub ``user_db()`` so the stored timezone under test is exact,+ independent of whatever the shared fixture user happens to carry."""+ fake = MagicMock()+ fake.get_user_by_id = AsyncMock(return_value=MagicMock(timezone=stored_timezone))+ return MagicMock(return_value=fake)++@pytest.mark.asyncio(loop_scope="session")async def test_run_agent_execution_credential_race_returns_setup_card(setup_test_data,