Skip to content

Build and run agents you can see, understand and trust.

fix(schedule): respect selected start times when creating schedules (#3610)

golemonf70bdcc483fb
diff --git a/examples/web_ui/frontend/src/api/types.ts b/examples/web_ui/frontend/src/api/types.ts
index eca9f3d35..d145171d3 100644
--- a/examples/web_ui/frontend/src/api/types.ts
+++ b/examples/web_ui/frontend/src/api/types.ts
@@ -783,6 +783,7 @@ export interface CreateScheduleRequest {
description?: string;
cron_expression: string;
timezone?: string;
+ started_at?: string | null;
ended_at?: string | null;
agent_id: string;
chat_model_config: ChatModelConfig;
diff --git a/examples/web_ui/frontend/src/pages/schedule/create-schedule-dialog.tsx b/examples/web_ui/frontend/src/pages/schedule/create-schedule-dialog.tsx
index 0d8bf107c..3aad826ab 100644
--- a/examples/web_ui/frontend/src/pages/schedule/create-schedule-dialog.tsx
+++ b/examples/web_ui/frontend/src/pages/schedule/create-schedule-dialog.tsx
@@ -32,7 +32,7 @@ import { Textarea } from '@/components/ui/textarea';
import { useAgents } from '@/hooks/useAgents';
import { useSchedules } from '@/hooks/useSchedules';
import { useTranslation } from '@/i18n/useI18n';
-import { getScheduleEndAt } from '@/pages/schedule/schedule-utils';
+import { getScheduleEndAt, getScheduleStartAt } from '@/pages/schedule/schedule-utils';
interface Props {
open: boolean;
@@ -152,7 +152,6 @@ export function CreateScheduleDialog({ open, onOpenChange, onCreated }: Props) {
const d = new Date(form.date!);
const [h, m] = form.time.split(':').map(Number);
- d.setHours(h, m, 0, 0);
if (form.freq === 'once') {
cronExpression = `${m} ${h} ${d.getDate()} ${d.getMonth() + 1} *`;
@@ -165,6 +164,7 @@ export function CreateScheduleDialog({ open, onOpenChange, onCreated }: Props) {
description: form.description.trim(),
cron_expression: cronExpression,
timezone: form.timezone,
+ started_at: getScheduleStartAt(form.date, form.time, form.timezone),
ended_at:
form.freq === 'once'
? undefined
diff --git a/examples/web_ui/frontend/src/pages/schedule/schedule-utils.ts b/examples/web_ui/frontend/src/pages/schedule/schedule-utils.ts
index 16bf33f53..7bc835f79 100644
--- a/examples/web_ui/frontend/src/pages/schedule/schedule-utils.ts
+++ b/examples/web_ui/frontend/src/pages/schedule/schedule-utils.ts
@@ -1,6 +1,35 @@
import { CronDate } from 'cron-parser';
import { format } from 'date-fns';
+/** Convert picker date/time in the task's zone, rejecting gaps and choosing the first fold. */
+export function getScheduleStartAt(date: Date, time: string, timezone: string): string {
+ if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(time)) {
+ throw new Error('Invalid start time. Please enter a time in HH:mm format.');
+ }
+ const local = `${format(date, 'yyyy-MM-dd')}T${time}:00.000`;
+ const parsed = new CronDate(local, timezone);
+ const wallTime = Date.parse(`${local}Z`);
+ // Sample both sides of a transition, including non-hour offset changes.
+ // Date objects prevent CronDate from treating timestamp zero as missing.
+ const day = 24 * 60 * 60 * 1000;
+ const offsets = new Set(
+ [-day, 0, day].map((delta) =>
+ new CronDate(new Date(parsed.getTime() + delta), timezone).getUTCOffset(),
+ ),
+ );
+ const candidates = [...offsets]
+ .map((offset) => new CronDate(new Date(wallTime - offset * 60 * 1000), timezone))
+ .filter(
+ (candidate) => candidate.getTime() + candidate.getUTCOffset() * 60 * 1000 === wallTime,
+ );
+ if (!candidates.length) {
+ throw new Error(
+ 'The selected start time does not exist in the task time zone. Please choose another time.',
+ );
+ }
+ return new Date(Math.min(...candidates.map((candidate) => candidate.getTime()))).toISOString();
+}
+
/** Convert a picker date to the inclusive end of that day in the task's timezone. */
export function getScheduleEndAt(date: Date | undefined, timezone: string): string | undefined {
if (!date) return undefined;
diff --git a/src/agentscope/app/_router/_schedule.py b/src/agentscope/app/_router/_schedule.py
index f704d6d7b..0acf858eb 100644
--- a/src/agentscope/app/_router/_schedule.py
+++ b/src/agentscope/app/_router/_schedule.py
@@ -118,9 +118,9 @@ async def create_schedule(
permission_mode=body.permission_mode,
chat_model_config=body.chat_model_config,
source=ScheduleSource.USER,
- # Aware on purpose: the trigger reads a naive start time in
- # the schedule's own timezone, not the server's.
- started_at=datetime.now().astimezone(),
+ # Keep the fallback aware so it denotes an absolute instant
+ # even when the task's timezone differs from the server's.
+ started_at=body.started_at or datetime.now().astimezone(),
ended_at=body.ended_at,
),
)
diff --git a/src/agentscope/app/_router/_schema/_schedule.py b/src/agentscope/app/_router/_schema/_schedule.py
index b24301466..ea07a96ee 100644
--- a/src/agentscope/app/_router/_schema/_schedule.py
+++ b/src/agentscope/app/_router/_schema/_schedule.py
@@ -27,6 +27,13 @@ class CreateScheduleRequest(BaseModel):
"'Asia/Shanghai'.",
)
+ started_at: AwareDatetime | None = Field(
+ default=None,
+ description="Inclusive start time of the schedule. Omit or set to "
+ "null to use the creation time. Must include a UTC offset, e.g. "
+ "'2026-11-01T20:26:00+08:00'.",
+ )
+
ended_at: AwareDatetime | None = Field(
default=None,
description="Inclusive end time of the schedule. Omit or set to null "
diff --git a/tests/schedule_router_test.py b/tests/schedule_router_test.py
index 751bff9e8..cafb164d3 100644
--- a/tests/schedule_router_test.py
+++ b/tests/schedule_router_test.py
@@ -156,10 +156,11 @@ class ScheduleHttpEndTimeTest(TestCase):
)
self.client = self.enterContext(TestClient(app))
- def test_end_time_round_trips_through_create_and_list(self) -> None:
- """An offset-bearing end time survives JSON input and list output."""
+ def test_start_and_end_round_trip_through_create_and_list(self) -> None:
+ """Both absolute boundaries survive persistence and list output."""
payload = {
**_request("59 23 * * *", "Asia/Shanghai").model_dump(mode="json"),
+ "started_at": "2099-12-01T15:59:00Z",
"ended_at": "2099-12-31T23:59:59.999+08:00",
}
created = self.client.post("/schedule/", json=payload)
@@ -174,7 +175,7 @@ class ScheduleHttpEndTimeTest(TestCase):
"agent_id": "agent-1",
"data": {
**{k: v for k, v in payload.items() if k != "agent_id"},
- "started_at": record.data.started_at,
+ "started_at": datetime.fromisoformat(payload["started_at"]),
"ended_at": datetime.fromisoformat(payload["ended_at"]),
"permission_mode": PermissionMode(payload["permission_mode"]),
"source": "USER",
@@ -259,6 +260,190 @@ class ScheduleHttpEndTimeTest(TestCase):
self.assertListEqual(self.storage.upserted, [])
self.assertListEqual(self.scheduler.notified, [])
+ def test_ambiguous_start_keeps_first_occurrence_for_every_frequency(
+ self,
+ ) -> None:
+ """A UTC start at the first DST fold stays eligible after storage."""
+ for cron in (
+ "30 1 * * *",
+ "30 1 * * 0",
+ "30 1 1 * *",
+ "30 1 1 11 *",
+ ):
+ with self.subTest(cron=cron):
+ self.storage.upserted.clear()
+ self.scheduler.notified.clear()
+ response = self.client.post(
+ "/schedule/",
+ json={
+ **_request(cron, "America/New_York").model_dump(
+ mode="json",
+ ),
+ "started_at": "2026-11-01T05:30:00Z",
+ },
+ )
+ self.assertEqual(response.status_code, 201, response.text)
+ restored = ScheduleRecord.model_validate_json(
+ self.storage.upserted[0].model_dump_json(),
+ )
+ trigger = SchedulerManager.validate_schedule(restored)
+ first = trigger.get_next_fire_time(
+ None,
+ datetime.fromisoformat("2026-10-30T00:00:00Z"),
+ )
+ self.assertIsNotNone(first)
+ self.assertEqual(
+ (first.isoformat(), first.fold),
+ ("2026-11-01T01:30:00-04:00", 0),
+ )
+
+ def test_omitted_and_null_start_use_creation_time(self) -> None:
+ """Both compatible request forms save an aware creation instant."""
+ cases: list[dict[str, None]] = [{}, {"started_at": None}]
+ for extra in cases:
+ with self.subTest(extra=extra):
+ self.storage.upserted.clear()
+ self.scheduler.notified.clear()
+ payload = {
+ **_request("0 * * * *").model_dump(
+ mode="json",
+ exclude={"started_at"},
+ ),
+ **extra,
+ }
+ before = datetime.now().astimezone()
+ response = self.client.post("/schedule/", json=payload)
+ after = datetime.now().astimezone()
+ self.assertEqual(response.status_code, 201, response.text)
+ record = self.storage.upserted[0]
+ self.assertEqual(
+ response.json(),
+ {"schedule_id": record.id},
+ )
+ self.assertEqual(self.scheduler.notified, [record.id])
+ self.assertIsNotNone(record.data.started_at.utcoffset())
+ self.assertLessEqual(before, record.data.started_at)
+ self.assertLessEqual(record.data.started_at, after)
+
+ def test_invalid_start_time_has_no_write_side_effects(self) -> None:
+ """Malformed/naive starts and invalid windows fail before mutation."""
+ cases = (
+ ("not-a-date", None, "datetime_from_date_parsing"),
+ ("2026-11-01T20:26:00", None, "timezone_aware"),
+ ("2026-02-30T20:26:00Z", None, "datetime_from_date_parsing"),
+ ("2026-11-01T25:26:00Z", None, "datetime_from_date_parsing"),
+ (
+ "2026-11-01T20:26:00+08:00",
+ "2026-11-01T12:26:00Z",
+ None,
+ ),
+ (
+ "2026-11-01T20:26:00+08:00",
+ "2026-11-01T12:25:59Z",
+ None,
+ ),
+ )
+ for start, end, error_type in cases:
+ with self.subTest(start=start, end=end):
+ response = self.client.post(
+ "/schedule/",
+ json={
+ **_request("26 20 * * *").model_dump(mode="json"),
+ "started_at": start,
+ "ended_at": end,
+ },
+ )
+ self.assertEqual(response.status_code, 422, response.text)
+ detail = response.json()["detail"]
+ if error_type:
+ # Parser descriptions differ by the invalid component.
+ self.assertEqual(
+ [
+ (item["type"], item["loc"], item["input"])
+ for item in detail
+ ],
+ [(error_type, ["body", "started_at"], start)],
+ )
+ else:
+ self.assertEqual(
+ response.json(),
+ {"detail": "ended_at must be later than started_at"},
+ )
+ self.assertEqual(
+ (self.storage.upserted, self.scheduler.notified),
+ ([], []),
+ )
+
+
+class ScheduleStartBoundaryTest(TestCase):
+ """Cron frequency rules and absolute activation boundaries."""
+
+ def test_start_time_frequency_boundaries(self) -> None:
+ """All frequencies retain their rules and inclusive start/end times."""
+ cases = (
+ ("daily", "26 20 * * *", "20:26", ("2026-11-01", "2026-11-02")),
+ ("midnight", "15 0 * * *", "00:15", ("2030-01-01", "2030-01-02")),
+ ("weekly", "26 20 * * 0", "20:26", ("2026-11-01", "2026-11-08")),
+ ("monthly", "26 20 1 * *", "20:26", ("2026-11-01", "2026-12-01")),
+ (
+ "month-end",
+ "15 0 31 * *",
+ "00:15",
+ ("2030-01-31", "2030-03-31"),
+ ),
+ ("once", "26 20 1 11 *", "20:26", ("2030-11-01",)),
+ ("once-leap-day", "26 20 29 2 *", "20:26", ("2032-02-29",)),
+ )
+ for frequency, cron, time, dates in cases:
+ expected_fires = [
+ datetime.fromisoformat(f"{day}T{time}:00+08:00")
+ for day in dates
+ ]
+ first = expected_fires[0]
+ utc_start = first.astimezone(ZoneInfo("UTC")).isoformat()
+ starts = (
+ first.isoformat(),
+ utc_start.replace("+00:00", "Z"),
+ )
+ for start in starts:
+ for bounded in (True, False):
+ with self.subTest(
+ frequency=frequency,
+ start=start,
+ bounded=bounded,
+ ):
+ end = expected_fires[-1] if bounded else None
+ if end is not None and end == first:
+ end += timedelta(days=1)
+ record = _record()
+ record.data.cron_expression = cron
+ record.data.timezone = "Asia/Shanghai"
+ record.data.started_at = datetime.fromisoformat(start)
+ record.data.ended_at = end
+ trigger = SchedulerManager.validate_schedule(record)
+ self.assertEqual(
+ [
+ trigger.get_next_fire_time(None, reference)
+ for reference in (
+ first - timedelta(days=2000),
+ first - timedelta(microseconds=1),
+ first,
+ )
+ ],
+ [first] * 3,
+ )
+ actual_fires = []
+ fire = first
+ for _ in expected_fires:
+ actual_fires.append(fire)
+ fire = trigger.get_next_fire_time(
+ fire,
+ fire + timedelta(seconds=1),
+ )
+ self.assertEqual(actual_fires, expected_fires)
+ if bounded:
+ self.assertIsNone(fire)
+
class ScheduleWeekdayTest(TestCase):
"""Standard cron weekdays are translated for APScheduler."""