"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(scheduled-research): add timezone-aware local schedules (#954)
Pham Van Ngoan516ae67ef7aa
diff --git a/README.md b/README.mdindex 624500419..59e979733 100644--- a/README.md+++ b/README.md@@ -1019,13 +1019,13 @@ The same Settings page includes an **IM Channels** panel for local operators. It### Scheduled research-Run a research prompt or backtest on a repeating schedule. The background executor is **off by default** — start the server with `VIBE_TRADING_ENABLE_SCHEDULER=1` to enable it:+Run a research prompt or backtest on a repeating schedule — from the **Scheduled** page in the web UI or over REST. The background executor is **off by default** — start the server with `VIBE_TRADING_ENABLE_SCHEDULER=1` to enable it:```bashVIBE_TRADING_ENABLE_SCHEDULER=1 vibe-trading serve --port 8899```-Then create jobs over REST. `schedule` is either a bare integer (interval in **milliseconds**) or a 5-field cron expression (`min hour dom mon dow`):+Then create jobs over REST. `schedule` is either a bare integer (interval in **milliseconds**) or a 5-field cron expression (`min hour dom mon dow`; each field takes `*`, `*/n`, numbers, comma lists, or low-high ranges like `1-5`). Cron runs on the wall clock of the job's optional `timezone` (an IANA key), so the cadence holds across DST transitions — a spring-forward gap time is skipped, and a fall-back ambiguous time runs once, at its first occurrence. Jobs without a `timezone` keep plain UTC semantics:```bash# every 6 hours (cron)@@ -1033,6 +1033,11 @@ curl -X POST http://localhost:8899/scheduled-runs \-H "Content-Type: application/json" \-d '{"prompt":"Scan CSI300 for momentum breakouts and backtest the top 5","schedule":"0 */6 * * *"}'+# weekdays at 23:30 Auckland wall time — DST-proof+curl -X POST http://localhost:8899/scheduled-runs \+ -H "Content-Type: application/json" \+ -d '{"prompt":"Pre-open scan of NZX names","schedule":"30 23 * * 1-5","timezone":"Pacific/Auckland"}'+# list / cancelcurl http://localhost:8899/scheduled-runscurl -X DELETE http://localhost:8899/scheduled-runs/<job_id>diff --git a/README_ar.md b/README_ar.mdindex 8b992c008..e697eb06c 100644--- a/README_ar.md+++ b/README_ar.md@@ -958,13 +958,13 @@ vibe-trading serve --port 8899### البحث المجدول (Scheduled research)-شغّل prompt بحثي أو backtest وفق جدول متكرر. المنفّذ الخلفي **معطّل افتراضياً** — شغّل الخادم بـ `VIBE_TRADING_ENABLE_SCHEDULER=1` لتفعيله:+شغّل prompt بحثي أو backtest وفق جدول متكرر — من صفحة **المجدولة** في واجهة الويب أو عبر REST. المنفّذ الخلفي **معطّل افتراضياً** — شغّل الخادم بـ `VIBE_TRADING_ENABLE_SCHEDULER=1` لتفعيله:```bashVIBE_TRADING_ENABLE_SCHEDULER=1 vibe-trading serve --port 8899```-ثم أنشئ المهام عبر REST. الحقل `schedule` إما عدد صحيح بسيط (الفاصل بـ**المللي ثانية**) أو تعبير cron من 5 حقول (`دقيقة ساعة يوم شهر يوم-الأسبوع`):+ثم أنشئ المهام عبر REST. الحقل `schedule` إما عدد صحيح بسيط (الفاصل بـ**المللي ثانية**) أو تعبير cron من 5 حقول (`دقيقة ساعة يوم شهر يوم-الأسبوع`؛ يقبل كل حقل `*` و`*/n` وأرقاماً وقوائم بفواصل ونطاقات مثل `1-5`). يُقيَّم cron وفق الساعة الحائطية لـ `timezone` الاختيارية للمهمة (مفتاح IANA)، فيبقى الإيقاع ثابتاً عبر تغييرات التوقيت الصيفي — يُتخطى الوقت غير الموجود في الربيع، ويُنفَّذ الوقت المكرر في الخريف مرة واحدة عند أول ظهور. المهام بدون `timezone` تحتفظ بدلالات UTC كما هي:```bash# كل 6 ساعات (cron)@@ -972,6 +972,11 @@ curl -X POST http://localhost:8899/scheduled-runs \-H "Content-Type: application/json" \-d '{"prompt":"Scan CSI300 for momentum breakouts and backtest the top 5","schedule":"0 */6 * * *"}'+# أيام العمل 23:30 بتوقيت أوكلاند المحلي — ثابت عبر التوقيت الصيفي+curl -X POST http://localhost:8899/scheduled-runs \+ -H "Content-Type: application/json" \+ -d '{"prompt":"Pre-open scan of NZX names","schedule":"30 23 * * 1-5","timezone":"Pacific/Auckland"}'+# السرد / الإلغاءcurl http://localhost:8899/scheduled-runscurl -X DELETE http://localhost:8899/scheduled-runs/<job_id>diff --git a/README_ja.md b/README_ja.mdindex df4d5e68b..5f9b8705b 100644--- a/README_ja.md+++ b/README_ja.md@@ -955,13 +955,13 @@ Settings reads は side-effect free です。`GET /settings/llm` と `GET /setti### Scheduled research(定期リサーチ)-リサーチ prompt や backtest を繰り返しスケジュールで実行します。バックグラウンド executor は**既定でオフ**です。`VIBE_TRADING_ENABLE_SCHEDULER=1` を付けて server を起動すると有効になります:+リサーチ prompt や backtest を繰り返しスケジュールで実行します。Web UI の**スケジュール**ページからも REST からも操作できます。バックグラウンド executor は**既定でオフ**です。`VIBE_TRADING_ENABLE_SCHEDULER=1` を付けて server を起動すると有効になります:```bashVIBE_TRADING_ENABLE_SCHEDULER=1 vibe-trading serve --port 8899```-その後、REST でジョブを作成します。`schedule` は単なる整数(interval は**ミリ秒**)か、5 フィールドの cron 式(`分 時 日 月 曜日`)です:+その後、REST でジョブを作成します。`schedule` は単なる整数(interval は**ミリ秒**)か、5 フィールドの cron 式(`分 時 日 月 曜日`。各フィールドは `*`、`*/n`、数値、カンマ区切りリスト、`1-5` のような範囲に対応)です。cron はジョブの任意の `timezone`(IANA キー)の壁時計で評価され、夏時間の切り替え後もリズムは変わりません——存在しない時刻(春の進み)はスキップされ、重複する時刻(秋の戻り)は最初の 1 回だけ実行されます。`timezone` のないジョブは従来どおり UTC で動作します:```bash# 6 時間ごと(cron)@@ -969,6 +969,11 @@ curl -X POST http://localhost:8899/scheduled-runs \-H "Content-Type: application/json" \-d '{"prompt":"Scan CSI300 for momentum breakouts and backtest the top 5","schedule":"0 */6 * * *"}'+# 平日 23:30(オークランドの壁時計、夏時間でもずれない)+curl -X POST http://localhost:8899/scheduled-runs \+ -H "Content-Type: application/json" \+ -d '{"prompt":"Pre-open scan of NZX names","schedule":"30 23 * * 1-5","timezone":"Pacific/Auckland"}'+# 一覧 / キャンセルcurl http://localhost:8899/scheduled-runscurl -X DELETE http://localhost:8899/scheduled-runs/<job_id>diff --git a/README_ko.md b/README_ko.mdindex 9a399c1a8..944df3c23 100644--- a/README_ko.md+++ b/README_ko.md@@ -958,13 +958,13 @@ Settings read는 side effect가 없습니다. `GET /settings/llm`과 `GET /setti### Scheduled research (예약 리서치)-리서치 prompt나 backtest를 반복 일정으로 실행합니다. 백그라운드 executor는 **기본적으로 꺼져 있습니다** — `VIBE_TRADING_ENABLE_SCHEDULER=1`로 server를 시작하면 활성화됩니다:+리서치 prompt나 backtest를 반복 일정으로 실행합니다 — Web UI의 **예약** 페이지에서도, REST로도 관리할 수 있습니다. 백그라운드 executor는 **기본적으로 꺼져 있습니다** — `VIBE_TRADING_ENABLE_SCHEDULER=1`로 server를 시작하면 활성화됩니다:```bashVIBE_TRADING_ENABLE_SCHEDULER=1 vibe-trading serve --port 8899```-그런 다음 REST로 작업을 생성합니다. `schedule`은 단순 정수(간격, 단위 **밀리초**)이거나 5필드 cron 표현식(`분 시 일 월 요일`)입니다:+그런 다음 REST로 작업을 생성합니다. `schedule`은 단순 정수(간격, 단위 **밀리초**)이거나 5필드 cron 표현식(`분 시 일 월 요일`; 각 필드는 `*`, `*/n`, 숫자, 쉼표 목록, `1-5` 같은 범위 지원)입니다. cron은 작업의 선택적 `timezone`(IANA 키)의 벽시계 기준으로 평가되어 서머타임 전환 후에도 주기가 유지됩니다 — 봄에 존재하지 않는 시각은 건너뛰고, 가을에 중복되는 시각은 첫 번째 발생 시 한 번만 실행됩니다. `timezone`이 없는 작업은 기존 UTC 의미를 유지합니다:```bash# 6시간마다 (cron)@@ -972,6 +972,11 @@ curl -X POST http://localhost:8899/scheduled-runs \-H "Content-Type: application/json" \-d '{"prompt":"Scan CSI300 for momentum breakouts and backtest the top 5","schedule":"0 */6 * * *"}'+# 평일 23:30 (오클랜드 현지 시각, 서머타임에도 안 밀림)+curl -X POST http://localhost:8899/scheduled-runs \+ -H "Content-Type: application/json" \+ -d '{"prompt":"Pre-open scan of NZX names","schedule":"30 23 * * 1-5","timezone":"Pacific/Auckland"}'+# 목록 / 취소curl http://localhost:8899/scheduled-runscurl -X DELETE http://localhost:8899/scheduled-runs/<job_id>diff --git a/README_zh.md b/README_zh.mdindex 73583775c..f0ec8e80d 100644--- a/README_zh.md+++ b/README_zh.md@@ -982,13 +982,13 @@ Settings 读取无副作用:`GET /settings/llm` 和 `GET /settings/data-source### 定时研究(Scheduled research)-让研究 prompt 或回测按固定周期重复运行。后台执行器**默认关闭**——启动服务时设置 `VIBE_TRADING_ENABLE_SCHEDULER=1` 才会开启:+让研究 prompt 或回测按固定周期重复运行——既可以在 Web UI 的**定时任务**页面操作,也可以走 REST。后台执行器**默认关闭**——启动服务时设置 `VIBE_TRADING_ENABLE_SCHEDULER=1` 才会开启:```bashVIBE_TRADING_ENABLE_SCHEDULER=1 vibe-trading serve --port 8899```-然后通过 REST 创建任务。`schedule` 可以是纯整数(间隔**毫秒**)或 5 段 cron 表达式(`分 时 日 月 周`):+然后通过 REST 创建任务。`schedule` 可以是纯整数(间隔**毫秒**)或 5 段 cron 表达式(`分 时 日 月 周`,每段支持 `*`、`*/n`、数字、逗号列表和 `1-5` 这样的范围)。cron 按任务可选的 `timezone`(IANA 时区名)的挂钟求值,夏令时切换后节奏保持不变——春季不存在的时间会被跳过,秋季重复的时间只在第一次出现时运行一次。不带 `timezone` 的任务保持原有 UTC 语义:```bash# 每 6 小时(cron)@@ -996,6 +996,11 @@ curl -X POST http://localhost:8899/scheduled-runs \-H "Content-Type: application/json" \-d '{"prompt":"Scan CSI300 for momentum breakouts and backtest the top 5","schedule":"0 */6 * * *"}'+# 工作日 23:30(奥克兰挂钟时间,夏令时不漂移)+curl -X POST http://localhost:8899/scheduled-runs \+ -H "Content-Type: application/json" \+ -d '{"prompt":"Pre-open scan of NZX names","schedule":"30 23 * * 1-5","timezone":"Pacific/Auckland"}'+# 列出 / 取消curl http://localhost:8899/scheduled-runscurl -X DELETE http://localhost:8899/scheduled-runs/<job_id>diff --git a/agent/.env.example b/agent/.env.exampleindex c5b2a16ff..5ee40304d 100644--- a/agent/.env.example+++ b/agent/.env.example@@ -210,7 +210,9 @@ TUSHARE_TOKEN=your-tushare-token# Opt-in background scheduler for saved research jobs (off by default).# When enabled, the API server runs a background poller that fires due-# interval/cron scheduled-research jobs through the session runtime.+# interval/cron scheduled-research jobs through the session runtime. Cron+# jobs may carry an IANA `timezone` (evaluated on that zone's wall clock,+# DST-aware); jobs without one evaluate in UTC.# VIBE_TRADING_ENABLE_SCHEDULER=1# A dispatch failure stays retryable until this many consecutive failures.# Retry timing is max(next scheduled time, exponential delay), capped below.diff --git a/agent/src/api/scheduled_routes.py b/agent/src/api/scheduled_routes.pyindex 39bb5ce4d..6d0532bc0 100644--- a/agent/src/api/scheduled_routes.py+++ b/agent/src/api/scheduled_routes.py@@ -125,6 +125,14 @@ class CreateScheduledRunRequest(BaseModel):config: Dict[str, Any] = Field(default_factory=dict, description="Optional backtest parameters")+ timezone: Optional[str] = Field(+ None,+ description=(+ "IANA timezone key the cron schedule is evaluated in "+ "(e.g. 'Pacific/Auckland'); null = UTC, the pre-existing "+ "semantics. Ignored by interval schedules."+ ),+ )class ScheduledRunResponse(BaseModel):@@ -141,6 +149,7 @@ class ScheduledRunResponse(BaseModel):last_error: Optional[str] = Nonefailure_kind: Optional[str] = Noneconfig: Dict[str, Any] = Field(default_factory=dict)+ timezone: Optional[str] = None# ---------------------------------------------------------------------------@@ -193,22 +202,40 @@ def register_scheduled_routes(JobStatus,ScheduledResearchJob,validate_schedule,+ validate_timezone,)+ from src.scheduled_research.executor import next_due+try:validate_schedule(request.schedule)+ validate_timezone(request.timezone)except ValueError as exc:raise HTTPException(status_code=422, detail=str(exc)) from excnow_ms = int(time.time() * 1000)+ next_run_at = request.next_run_at+ if next_run_at is None:+ next_run_at = now_ms+ if request.timezone is not None and not request.schedule.strip().isdigit():+ # A timezone-carrying cron job's contract is the authored wall+ # clock, so its first fire is the first authored occurrence —+ # not the creation moment. Interval jobs and timezone-less+ # jobs keep the pre-existing immediate-first-fire default.+ try:+ next_run_at = next_due(request.schedule, now_ms, request.timezone)+ except ValueError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from exc+job = ScheduledResearchJob(id=request.id or str(uuid.uuid4()),prompt=request.prompt,schedule=request.schedule,- next_run_at=request.next_run_at if request.next_run_at is not None else now_ms,+ next_run_at=next_run_at,status=JobStatus.PENDING,created_at=now_ms,config=request.config,+ timezone=request.timezone,)_get_scheduled_research_store().upsert(job)return ScheduledRunResponse(**job.to_dict())diff --git a/agent/src/scheduled_research/executor.py b/agent/src/scheduled_research/executor.pyindex 51b0bd4c3..b7ab06ea2 100644--- a/agent/src/scheduled_research/executor.py+++ b/agent/src/scheduled_research/executor.py@@ -11,11 +11,19 @@ from __future__ import annotationsimport asyncioimport loggingimport time-from datetime import datetime, timedelta, timezone+from datetime import date, datetime, timedelta, timezone, tzinfofrom typing import Awaitable, Callable+from zoneinfo import ZoneInfofrom src.config.accessor import get_env_config-from src.scheduled_research.models import JobStatus, ScheduledResearchJob, validate_schedule+from src.scheduled_research.models import (+ CRON_BOUNDS,+ JobStatus,+ ScheduledResearchJob,+ parse_cron_field,+ validate_schedule,+ validate_timezone,+)from src.scheduled_research.store import ScheduledResearchJobStorefrom src.tools.redaction import redact_internal_paths, redact_text@@ -31,9 +39,10 @@ DispatchCallback = Callable[[ScheduledResearchJob], Awaitable[None]]_TRUE_VALUES = {"1", "true", "yes", "on"}# Search by day, not by minute, so an impossible date (e.g. Feb 31) fails fast# instead of scanning years of minutes on the event loop. Four years covers any-# real recurrence, including a Feb-29 leap day.-_CRON_SEARCH_LIMIT_DAYS = 4 * 366 + 1-_CRON_BOUNDS = ((0, 59), (0, 23), (1, 31), (1, 12), (0, 6))+# real recurrence, including a Feb-29 leap day; the extra headroom absorbs a+# yearly occurrence landing in a DST spring-forward gap (skipped by policy)+# several years in a row before a real instant exists again.+_CRON_SEARCH_LIMIT_DAYS = 6 * 366 + 1def _now_ms() -> int:@@ -75,52 +84,64 @@ def _persisted_error(exc: Exception) -> str:return f"{safe[: _MAX_PERSISTED_ERROR_CHARS - 3]}..."-def next_due(schedule: str, after_ms: int) -> int:+def next_due(schedule: str, after_ms: int, tz: str | None = None) -> int:"""Return the first due epoch-ms strictly after ``after_ms``.Supports the scheduled-research schedule format: a bare positive integer- string for interval milliseconds, or a simplified 5-field cron expression- interpreted in UTC.+ string for interval milliseconds, or a simplified 5-field cron expression.+ Cron is evaluated on the wall clock of *tz* (an IANA timezone key) when+ one is given, in UTC otherwise — the semantics every job had before the+ field existed. Interval schedules ignore *tz* entirely."""validate_schedule(schedule)spec = schedule.strip()if spec.isdigit():+ # Before the timezone check: interval schedules must keep advancing+ # even when the stored key cannot resolve on this host.return after_ms + int(spec)- return _next_cron_due(spec, after_ms)+ validate_timezone(tz)+ return _next_cron_due(spec, after_ms, tz)-def _next_cron_due(schedule: str, after_ms: int) -> int:+def _next_cron_due(schedule: str, after_ms: int, tz: str | None = None) -> int:minutes, hours, doms, months, dows = (- _parse_cron_field(part, low, high) for part, (low, high) in zip(schedule.split(), _CRON_BOUNDS)+ parse_cron_field(part, low, high) for part, (low, high) in zip(schedule.split(), CRON_BOUNDS))- start = datetime.fromtimestamp(after_ms / 1000.0, timezone.utc) + timedelta(milliseconds=1)- # Round up to the next whole minute; cron has minute resolution.- if start.second or start.microsecond:- start = (start + timedelta(minutes=1)).replace(second=0, microsecond=0)-- day = start.replace(hour=0, minute=0, second=0, microsecond=0)+ zone = timezone.utc if tz is None else ZoneInfo(tz)+ # Walk candidates on the *local* calendar of ``zone`` so field matching —+ # the weekday in particular — follows the authoring wall clock. Ascending+ # wall order maps to ascending UTC order under a fixed fold policy, so+ # "strictly after" stays a plain epoch comparison.+ day = datetime.fromtimestamp(after_ms / 1000.0, zone).date()for offset in range(_CRON_SEARCH_LIMIT_DAYS):candidate_day = day + timedelta(days=offset)if not _day_matches(candidate_day, doms, months, dows):continuefor hour in sorted(hours) if hours is not None else range(24):for minute in sorted(minutes) if minutes is not None else range(60):- fire = candidate_day.replace(hour=hour, minute=minute)- if fire >= start:- return int(fire.timestamp() * 1000)+ fire_ms = _local_wall_time_to_epoch_ms(candidate_day, hour, minute, zone)+ if fire_ms is not None and fire_ms > after_ms:+ return fire_msraise ValueError(f"cron schedule has no matching time within search window: {schedule!r}")-def _parse_cron_field(part: str, low: int, high: int) -> set[int] | None:- if part == "*":- return None- if part.startswith("*/"):- step = int(part[2:])- return set(range(low, high + 1, step))- return {int(part)}+def _local_wall_time_to_epoch_ms(day: date, hour: int, minute: int, zone: tzinfo) -> int | None:+ """Resolve one local wall time to a UTC epoch-ms instant.++ DST policy (#953): a nonexistent wall time — the spring-forward gap —+ returns ``None`` so the occurrence is skipped; ``ZoneInfo`` would+ otherwise silently map it past the transition (PEP 495) and run it. An+ ambiguous wall time — the fall-back fold — resolves with ``fold=0``, the+ first occurrence, so it runs exactly once.+ """+ local = datetime(day.year, day.month, day.day, hour, minute, tzinfo=zone)+ as_utc = local.astimezone(timezone.utc)+ if as_utc.astimezone(zone).replace(tzinfo=None) != local.replace(tzinfo=None):+ return None # wall time does not exist in this zone (DST gap)+ return int(as_utc.timestamp() * 1000)-def _day_matches(dt: datetime, doms: set[int] | None, months: set[int] | None, dows: set[int] | None) -> bool:+def _day_matches(dt: date, doms: set[int] | None, months: set[int] | None, dows: set[int] | None) -> bool:if months is not None and dt.month not in months:return False@@ -255,7 +276,14 @@ class ScheduledResearchExecutor:key=lambda job: job.next_run_at,)for job in jobs:- await self._run_job(job, now)+ # One job's unexpected persistence/lifecycle error must not starve+ # every job sorted after it, tick after tick.+ try:+ await self._run_job(job, now)+ except asyncio.CancelledError:+ raise+ except Exception:+ logger.error("scheduled research job %s failed its run cycle", job.id, exc_info=True)def recover_stale_running(self) -> int:"""Reset jobs left ``RUNNING`` by a previous executor process.@@ -336,7 +364,7 @@ class ScheduledResearchExecutor:job.last_run_at = now_mstry:- scheduled_next_run = next_due(job.schedule, now_ms)+ scheduled_next_run = next_due(job.schedule, now_ms, job.timezone)except Exception as exc:logger.error("scheduled research schedule advancement failed for job %s", job.id, exc_info=True)job.status = JobStatus.FAILEDdiff --git a/agent/src/scheduled_research/models.py b/agent/src/scheduled_research/models.pyindex c1b105784..e25bb076d 100644--- a/agent/src/scheduled_research/models.py+++ b/agent/src/scheduled_research/models.py@@ -12,7 +12,8 @@ import reimport timefrom dataclasses import dataclass, fieldfrom enum import Enum-from typing import Any, Dict, Optional+from typing import Any, Dict, Optional, Set+from zoneinfo import ZoneInfo# ---------------------------------------------------------------------------# Schedule validation@@ -22,14 +23,71 @@ from typing import Any, Dict, Optional# * a bare positive integer (interval in milliseconds), e.g. "60000"# * a simplified cron expression with 5 fields, e.g. "0 */6 * * *"# Fields: minute hour day-of-month month day-of-week-# Each field may be: number, *, or */n+# Each field may be: *, */n, or a comma-separated list of numbers and+# low-high ranges (e.g. "1-5", "1,3,5", "1,3-5")_INTERVAL_MS_RE = re.compile(r"^[1-9][0-9]*$")-_CRON_FIELD_RE = re.compile(r"^(\*|\*/[1-9][0-9]*|[0-9]+)$")+_CRON_STEP_RE = re.compile(r"^\*/[1-9][0-9]*$")+_CRON_ATOM_RE = re.compile(r"^([0-9]+)(?:-([0-9]+))?$")_CRON_PARTS = 5# Inclusive (low, high) bounds per cron field: minute hour day-of-month month-# day-of-week. A bare number and a ``*/n`` step are both validated against the-# field's high bound so out-of-range values (e.g. minute ``99``) are rejected.-_CRON_BOUNDS = ((0, 59), (0, 23), (1, 31), (1, 12), (0, 6))+# day-of-week. Every number in a field — a bare value, a ``*/n`` step, or+# either end of a range — is validated against these bounds so out-of-range+# values (e.g. minute ``99``) are rejected. Day-of-week uses the cron+# convention Sunday == 0; ``7`` is not accepted as a Sunday alias.+CRON_BOUNDS = ((0, 59), (0, 23), (1, 31), (1, 12), (0, 6))+++def _validate_cron_field(part: str, low: int, high: int) -> None:+ """Raise ``ValueError`` when one cron field is malformed or out of range."""+ if part == "*":+ return+ if _CRON_STEP_RE.fullmatch(part):+ value = int(part[2:])+ if not low <= value <= high:+ raise ValueError(f"cron field {part!r} is out of range; expected {low}-{high}")+ return+ for atom in part.split(","):+ match = _CRON_ATOM_RE.fullmatch(atom)+ if match is None:+ raise ValueError(+ f"cron field {part!r} is not valid; each field must be *, */n, "+ f"or a comma-separated list of numbers and low-high ranges"+ )+ start = int(match.group(1))+ end = int(match.group(2)) if match.group(2) is not None else start+ if start > end:+ raise ValueError(f"cron range {atom!r} is reversed; expected low-high")+ if start < low or end > high:+ raise ValueError(f"cron field {atom!r} is out of range; expected {low}-{high}")+++def parse_cron_field(part: str, low: int, high: int) -> Optional[Set[int]]:+ """Expand one validated cron field into its matching values.++ Kept beside :func:`validate_schedule` so the accepted grammar and the+ executor's evaluation of it can never drift apart.++ Args:+ part: One whitespace-delimited cron field (already validated).+ low: Inclusive lower bound of the field.+ high: Inclusive upper bound of the field.++ Returns:+ The set of matching integer values, or ``None`` for the ``*`` wildcard.+ """+ if part == "*":+ return None+ if part.startswith("*/"):+ step = int(part[2:])+ return set(range(low, high + 1, step))+ values: Set[int] = set()+ for atom in part.split(","):+ start, _, end = atom.partition("-")+ if end:+ values.update(range(int(start), int(end) + 1))+ else:+ values.add(int(start))+ return valuesdef validate_schedule(schedule: str) -> None:@@ -46,19 +104,54 @@ def validate_schedule(schedule: str) -> None:raise ValueError("schedule must be a non-empty string")if _INTERVAL_MS_RE.fullmatch(schedule.strip()):+ # 15 digits ≈ 31,000 years in milliseconds — anything longer is not a+ # usable interval and would only feed int() conversion of huge strings.+ if len(schedule.strip()) > 15:+ raise ValueError("interval is too large; expected at most 15 digits of milliseconds")return # valid intervalparts = schedule.strip().split()if len(parts) != _CRON_PARTS:raise ValueError(f"schedule must be a positive integer (ms) or a 5-field cron string; got: {schedule!r}")- for part, (low, high) in zip(parts, _CRON_BOUNDS):- if not _CRON_FIELD_RE.fullmatch(part):- raise ValueError(f"cron field {part!r} is not valid; each field must be *, */n, or a number")- if part == "*":- continue- value = int(part[2:]) if part.startswith("*/") else int(part)- if not low <= value <= high:- raise ValueError(f"cron field {part!r} is out of range; expected {low}-{high}")+ for part, (low, high) in zip(parts, CRON_BOUNDS):+ _validate_cron_field(part, low, high)+++def validate_timezone_shape(tz: Optional[str]) -> None:+ """Raise ``ValueError`` when *tz* is not ``None`` or a non-empty string.++ This is the persistence-level check: it deliberately does NOT resolve the+ key, because resolvability depends on the host's timezone database. A+ store written where a key resolved must keep loading and persisting on a+ host where it does not; the executor surfaces the unresolvable key as a+ per-job schedule failure instead.+ """+ if tz is None:+ return+ if not isinstance(tz, str) or not tz.strip():+ raise ValueError("timezone must be a non-empty IANA timezone key or null")+++def validate_timezone(tz: Optional[str]) -> None:+ """Raise ``ValueError`` when *tz* is not a resolvable IANA timezone key.++ ``None`` is always valid and means legacy UTC semantics. Resolution goes+ through :class:`zoneinfo.ZoneInfo`, so whatever validates here is exactly+ what the executor can evaluate later.++ Args:+ tz: An IANA timezone key such as ``"Pacific/Auckland"``, or ``None``.++ Raises:+ ValueError: When *tz* is not ``None`` and cannot be resolved.+ """+ validate_timezone_shape(tz)+ if tz is None:+ return+ try:+ ZoneInfo(tz)+ except Exception as exc:+ raise ValueError(f"timezone {tz!r} is not a recognized IANA timezone key") from exc# ---------------------------------------------------------------------------@@ -101,6 +194,9 @@ class ScheduledResearchJob:failure_kind: ``"dispatch"`` for provider/session failures or``"schedule"`` when the schedule cannot be advanced.config: Opaque dict for future backtest parameters.+ timezone: IANA timezone key the cron schedule is evaluated in, or+ ``None`` for UTC (the semantics every job had before this field+ existed). Interval schedules ignore it."""id: str@@ -114,6 +210,7 @@ class ScheduledResearchJob:last_error: Optional[str] = Nonefailure_kind: Optional[str] = Noneconfig: Dict[str, Any] = field(default_factory=dict)+ timezone: Optional[str] = Nonedef to_dict(self) -> Dict[str, Any]:"""Serialize to a plain JSON-serializable dict.@@ -134,6 +231,7 @@ class ScheduledResearchJob:"last_error": self.last_error,"failure_kind": self.failure_kind,"config": self.config,+ "timezone": self.timezone,}@classmethod@@ -176,6 +274,15 @@ class ScheduledResearchJob:raise TypeError("'last_error' must be a string or null")if failure_kind is not None and failure_kind not in {"dispatch", "schedule"}:raise ValueError("'failure_kind' must be 'dispatch', 'schedule', or null")+ # Type-checked only: resolving the zone at load time would let one+ # unresolvable key quarantine the whole store file. Absent -> None+ # (UTC); a blank string normalizes to None too, so every loaded record+ # satisfies the shape check the store re-runs on lifecycle writes.+ tz = data.get("timezone")+ if tz is not None and not isinstance(tz, str):+ raise TypeError("'timezone' must be a string or null")+ if tz is not None and not tz.strip():+ tz = Nonestatus = JobStatus(data["status"])raw_config = data.get("config")config: Dict[str, Any] = raw_config if isinstance(raw_config, dict) else {}@@ -191,4 +298,5 @@ class ScheduledResearchJob:last_error=last_error,failure_kind=failure_kind,config=config,+ timezone=tz,)diff --git a/agent/src/scheduled_research/store.py b/agent/src/scheduled_research/store.pyindex 4b13a749c..b32960945 100644--- a/agent/src/scheduled_research/store.py+++ b/agent/src/scheduled_research/store.py@@ -19,7 +19,7 @@ from pathlib import Pathfrom typing import Dict, List, Optionalfrom src.config.paths import get_runtime_root-from src.scheduled_research.models import ScheduledResearchJob, validate_schedule+from src.scheduled_research.models import ScheduledResearchJob, validate_schedule, validate_timezone_shapelogger = logging.getLogger(__name__)@@ -73,7 +73,8 @@ class ScheduledResearchJobStore:Args:path: Explicit path. Defaults to- ``agent/data/scheduled_research_jobs.json``.+ ``<runtime root>/scheduled_research/scheduled_research_jobs.json``+ (see :func:`_default_store_path`)."""self.path: Path = path if path is not None else _default_store_path()@@ -137,16 +138,21 @@ class ScheduledResearchJobStore:def upsert(self, job: ScheduledResearchJob) -> None:"""Insert or replace a job by id.- Validates the schedule string before persisting.+ Validates the schedule string and the timezone's shape before+ persisting. The timezone key is deliberately not resolved here — see+ :func:`~src.scheduled_research.models.validate_timezone_shape` — so+ executor lifecycle writes keep working on a host whose timezone+ database lacks a key that validated where the job was created.Args:job: The job to store.Raises:- ValueError: When ``job.schedule`` is malformed.+ ValueError: When ``job.schedule`` or ``job.timezone`` is malformed.CorruptStoreError: When the existing store cannot be parsed."""validate_schedule(job.schedule)+ validate_timezone_shape(job.timezone)jobs = self.load()jobs[job.id] = jobself.save(jobs)diff --git a/agent/tests/test_scheduled_research_executor.py b/agent/tests/test_scheduled_research_executor.pyindex 33fc1d3b5..36df4fbf6 100644--- a/agent/tests/test_scheduled_research_executor.py+++ b/agent/tests/test_scheduled_research_executor.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport asynciofrom datetime import datetime, timezonefrom pathlib import Path+from zoneinfo import ZoneInfoimport pytestfrom src.scheduled_research.executor import (@@ -21,6 +22,12 @@ def _ms(year: int, month: int, day: int, hour: int, minute: int) -> int:return int(datetime(year, month, day, hour, minute, tzinfo=timezone.utc).timestamp() * 1000)+def _local_ms(tz: str, year: int, month: int, day: int, hour: int, minute: int, *, fold: int = 0) -> int:+ """Epoch-ms of a wall-clock time in an IANA zone (``fold=0`` = first occurrence)."""+ local = datetime(year, month, day, hour, minute, tzinfo=ZoneInfo(tz), fold=fold)+ return int(local.timestamp() * 1000)++def _store(tmp_path: Path) -> ScheduledResearchJobStore:return ScheduledResearchJobStore(path=tmp_path / "jobs.json")@@ -32,6 +39,7 @@ def _job(next_run_at: int = 0,status: JobStatus = JobStatus.PENDING,created_at: int = 0,+ timezone: str | None = None,) -> ScheduledResearchJob:return ScheduledResearchJob(id=job_id,@@ -40,6 +48,7 @@ def _job(next_run_at=next_run_at,status=status,created_at=created_at,+ timezone=timezone,)@@ -502,3 +511,189 @@ def test_disabled_executor_start_stop_are_noops(tmp_path: Path) -> None:assert scheduler_enabled_from_env("true") is Trueassert calls == []assert store.get("job-001").status == JobStatus.PENDING # type: ignore[union-attr]+++# ---------------------------------------------------------------------------+# Timezone-aware cron evaluation (#953)+# ---------------------------------------------------------------------------+++def test_tz_cron_weekday_survives_spring_forward_auckland() -> None:+ # NZ springs forward on Sun 2026-09-27 (02:00 NZST -> 03:00 NZDT). A+ # weekday-23:30 cadence authored in Auckland must fire Fri then Mon at+ # 23:30 local on both sides of the transition, even though the UTC offset+ # moves from +12 to +13.+ friday_fire = _local_ms("Pacific/Auckland", 2026, 9, 25, 23, 30)+ monday_fire = _local_ms("Pacific/Auckland", 2026, 9, 28, 23, 30)+ assert next_due("30 23 * * 1-5", friday_fire, "Pacific/Auckland") == monday_fire++ fired_local = datetime.fromtimestamp(monday_fire / 1000.0, ZoneInfo("Pacific/Auckland"))+ assert (fired_local.weekday(), fired_local.hour, fired_local.minute) == (0, 23, 30)+++def test_tz_cron_weekday_survives_fall_back_auckland() -> None:+ # NZ falls back on Sun 2026-04-05 (03:00 NZDT -> 02:00 NZST).+ friday_fire = _local_ms("Pacific/Auckland", 2026, 4, 3, 23, 30)+ monday_fire = _local_ms("Pacific/Auckland", 2026, 4, 6, 23, 30)+ assert next_due("30 23 * * 1-5", friday_fire, "Pacific/Auckland") == monday_fire+++def test_tz_cron_weekday_is_evaluated_in_authoring_zone() -> None:+ # Monday 00:30 in Auckland is still Sunday in UTC; the weekday field must+ # follow the authoring wall clock, not the UTC calendar.+ sunday_noon = _local_ms("Pacific/Auckland", 2026, 6, 14, 12, 0)+ monday_first = _local_ms("Pacific/Auckland", 2026, 6, 15, 0, 30)+ result = next_due("30 0 * * 1", sunday_noon, "Pacific/Auckland")+ assert result == monday_first+ assert datetime.fromtimestamp(result / 1000.0, timezone.utc).weekday() == 6 # Sunday in UTC+++def test_tz_cron_half_hour_offset_adelaide() -> None:+ # ACST is UTC+9:30, so a 09:00 local fire lands on a half-hour UTC boundary.+ after = _local_ms("Australia/Adelaide", 2026, 6, 10, 9, 0)+ next_fire = _local_ms("Australia/Adelaide", 2026, 6, 11, 9, 0)+ result = next_due("0 9 * * *", after, "Australia/Adelaide")+ assert result == next_fire+ assert result % 3_600_000 == 1_800_000++ # Across the Adelaide spring-forward (Sun 2026-10-04, +9:30 -> +10:30) the+ # local fire time is preserved while the UTC instant shifts by an hour.+ before_transition = _local_ms("Australia/Adelaide", 2026, 10, 3, 9, 0)+ after_transition = _local_ms("Australia/Adelaide", 2026, 10, 4, 9, 0)+ assert next_due("0 9 * * *", before_transition, "Australia/Adelaide") == after_transition+++def test_tz_cron_spring_forward_gap_skips_occurrence_new_york() -> None:+ # 02:30 does not exist on Sun 2026-03-08 in America/New_York (02:00 EST+ # jumps to 03:00 EDT). The occurrence is skipped, not shifted.+ saturday_fire = _local_ms("America/New_York", 2026, 3, 7, 2, 30)+ monday_fire = _local_ms("America/New_York", 2026, 3, 9, 2, 30)+ assert next_due("30 2 * * *", saturday_fire, "America/New_York") == monday_fire+++def test_tz_cron_fall_back_ambiguous_time_runs_once_at_first_occurrence_new_york() -> None:+ # 01:30 happens twice on Sun 2026-11-01 in America/New_York (EDT 05:30Z,+ # then EST 06:30Z after the clocks fall back). The job runs once, at the+ # first occurrence, and the second occurrence is not a separate firing.+ saturday_fire = _local_ms("America/New_York", 2026, 10, 31, 1, 30)+ first_occurrence = _local_ms("America/New_York", 2026, 11, 1, 1, 30, fold=0)+ assert first_occurrence == _ms(2026, 11, 1, 5, 30)+ assert next_due("30 1 * * *", saturday_fire, "America/New_York") == first_occurrence++ monday_fire = _local_ms("America/New_York", 2026, 11, 2, 1, 30)+ assert next_due("30 1 * * *", first_occurrence, "America/New_York") == monday_fire+ assert next_due("30 1 * * *", first_occurrence, "America/New_York") != _ms(2026, 11, 1, 6, 30)+++def test_tz_none_keeps_utc_semantics_for_extended_grammar() -> None:+ # 2026-07-31 is a Friday; the next weekday fire after Friday 11:30 UTC is+ # Monday 11:30 UTC. Without a timezone the new range grammar still+ # evaluates on the UTC wall clock exactly as before.+ assert next_due("30 11 * * 1-5", _ms(2026, 7, 31, 11, 30)) == _ms(2026, 8, 3, 11, 30)+++def test_tz_aware_next_due_defaults_match_legacy_signature() -> None:+ reference = _ms(2026, 6, 11, 0, 1)+ for schedule in ("0 */6 * * *", "0 0 13 * 5", "60000"):+ assert next_due(schedule, reference) == next_due(schedule, reference, None)+++def test_interval_schedule_ignores_timezone() -> None:+ assert next_due("60000", 5_000, "Pacific/Auckland") == 65_000+ # Even an unresolvable key: interval advancement must not depend on the+ # host's timezone database.+ assert next_due("60000", 5_000, "Not/AZone") == 65_000+++def test_unknown_timezone_raises_value_error() -> None:+ with pytest.raises(ValueError, match="not a recognized IANA timezone"):+ next_due("0 12 * * *", 0, "Not/AZone")+++def test_tz_cron_is_strictly_after_in_local_zone() -> None:+ exact_fire = _local_ms("Pacific/Auckland", 2026, 6, 15, 12, 0)+ next_day = _local_ms("Pacific/Auckland", 2026, 6, 16, 12, 0)+ assert next_due("0 12 * * *", exact_fire, "Pacific/Auckland") == next_day+++def test_executor_advances_tz_job_on_local_calendar(tmp_path: Path) -> None:+ store = _store(tmp_path)+ friday_fire = _local_ms("Pacific/Auckland", 2026, 9, 25, 23, 30)+ monday_fire = _local_ms("Pacific/Auckland", 2026, 9, 28, 23, 30)+ store.upsert(+ _job(+ schedule="30 23 * * 1-5",+ next_run_at=friday_fire,+ timezone="Pacific/Auckland",+ )+ )+ calls: list[str] = []++ async def dispatch(job: ScheduledResearchJob) -> None:+ calls.append(job.id)++ async def scenario() -> None:+ executor = ScheduledResearchExecutor(store, dispatch)+ await executor.tick(friday_fire)++ asyncio.run(scenario())++ saved = store.get("job-001")+ assert saved is not None+ assert calls == ["job-001"]+ assert saved.status == JobStatus.COMPLETED+ assert saved.timezone == "Pacific/Auckland"+ assert saved.next_run_at == monday_fire+++def test_executor_marks_job_failed_when_timezone_unresolvable(tmp_path: Path) -> None:+ store = _store(tmp_path)+ # The store checks only the timezone's shape, so a key another host's tz+ # database knew persists fine; this host surfaces it per-job at+ # advancement time instead of crashing lifecycle writes.+ store.upsert(_job(schedule="0 12 * * *", next_run_at=10, timezone="Not/AZone"))+ calls: list[str] = []++ async def dispatch(job: ScheduledResearchJob) -> None:+ calls.append(job.id)++ async def scenario() -> None:+ executor = ScheduledResearchExecutor(store, dispatch)+ await executor.tick(20)++ asyncio.run(scenario())++ saved = store.get("job-001")+ assert saved is not None+ assert calls == ["job-001"]+ assert saved.status == JobStatus.FAILED+ assert saved.failure_kind == "schedule"+ assert saved.last_error is not None+++def test_tick_continues_past_a_job_whose_lifecycle_write_raises(tmp_path: Path) -> None:+ class ExplodingUpsertStore(ScheduledResearchJobStore):+ def upsert(self, job: ScheduledResearchJob) -> None:+ if job.id == "bad":+ raise RuntimeError("disk full")+ super().upsert(job)++ store = ExplodingUpsertStore(path=tmp_path / "jobs.json")+ good_store = ScheduledResearchJobStore(path=tmp_path / "jobs.json")+ good_store.save({j.id: j for j in (_job("bad", next_run_at=10), _job("good", next_run_at=20))})+ calls: list[str] = []++ async def dispatch(job: ScheduledResearchJob) -> None:+ calls.append(job.id)++ async def scenario() -> None:+ executor = ScheduledResearchExecutor(store, dispatch)+ await executor.tick(100)++ asyncio.run(scenario())++ # "bad" exploded on its mark-RUNNING write; "good" must still have run.+ assert calls == ["good"]+ saved = good_store.get("good")+ assert saved is not None+ assert saved.status == JobStatus.COMPLETEDdiff --git a/agent/tests/test_scheduled_research_store.py b/agent/tests/test_scheduled_research_store.pyindex 3a82950b9..988e95cd8 100644--- a/agent/tests/test_scheduled_research_store.py+++ b/agent/tests/test_scheduled_research_store.py@@ -12,7 +12,12 @@ from pathlib import Pathimport pytest-from src.scheduled_research.models import JobStatus, ScheduledResearchJob, validate_schedule+from src.scheduled_research.models import (+ JobStatus,+ ScheduledResearchJob,+ validate_schedule,+ validate_timezone,+)from src.scheduled_research.store import CorruptStoreError, ScheduledResearchJobStore@@ -95,6 +100,63 @@ class TestValidateSchedule:def test_accepts_boundary_values(self) -> None:validate_schedule("59 23 31 12 6") # all field maxima+ def test_accepts_weekday_range(self) -> None:+ validate_schedule("30 23 * * 1-5")++ def test_rejects_oversized_interval(self) -> None:+ validate_schedule("9" * 15) # ~31,000 years is the accepted ceiling+ with pytest.raises(ValueError, match="interval is too large"):+ validate_schedule("9" * 16)++ def test_accepts_list_and_mixed_range(self) -> None:+ validate_schedule("0 9 * * 1,3,5")+ validate_schedule("0 9 * * 1,3-5")+ validate_schedule("0 9 1-15 * *")++ def test_rejects_reversed_range(self) -> None:+ with pytest.raises(ValueError, match="reversed"):+ validate_schedule("0 9 * * 5-1")++ def test_rejects_out_of_range_list_and_range_ends(self) -> None:+ with pytest.raises(ValueError):+ validate_schedule("0 9 * * 1-8") # dow high end > 6+ with pytest.raises(ValueError):+ validate_schedule("0 9 * * 1,9") # dow list member > 6++ def test_rejects_range_step_and_wildcard_in_list(self) -> None:+ with pytest.raises(ValueError):+ validate_schedule("0 9 * * 1-5/2") # range steps are not part of the grammar+ with pytest.raises(ValueError):+ validate_schedule("0 9 * * *,1") # wildcard cannot appear in a list++ def test_rejects_empty_list_atoms(self) -> None:+ with pytest.raises(ValueError):+ validate_schedule("0 9 * * 1,,3")+ with pytest.raises(ValueError):+ validate_schedule("0 9 * * 1-")+ with pytest.raises(ValueError):+ validate_schedule("0 9 * * -5")+++class TestValidateTimezone:+ def test_accepts_none(self) -> None:+ validate_timezone(None)++ def test_accepts_iana_keys(self) -> None:+ validate_timezone("UTC")+ validate_timezone("Pacific/Auckland")+ validate_timezone("Australia/Adelaide")++ def test_rejects_unknown_key(self) -> None:+ with pytest.raises(ValueError, match="not a recognized IANA timezone"):+ validate_timezone("Not/AZone")++ def test_rejects_empty_and_blank(self) -> None:+ with pytest.raises(ValueError):+ validate_timezone("")+ with pytest.raises(ValueError):+ validate_timezone(" ")+# ---------------------------------------------------------------------------# Store CRUD tests@@ -225,6 +287,59 @@ class TestScheduledResearchJobStore:assert fetched.prompt == job.promptassert fetched.schedule == "0 */4 * * *"+ def test_timezone_round_trips_through_store(self, tmp_path: Path) -> None:+ store = ScheduledResearchJobStore(path=tmp_path / "jobs.json")+ job = _make_job("tz-001", schedule="30 23 * * 1-5")+ job.timezone = "Pacific/Auckland"+ store.upsert(job)++ fetched = ScheduledResearchJobStore(path=tmp_path / "jobs.json").get("tz-001")+ assert fetched is not None+ assert fetched.timezone == "Pacific/Auckland"++ def test_legacy_record_without_timezone_loads_as_none(self, tmp_path: Path) -> None:+ store_path = tmp_path / "jobs.json"+ legacy = _make_job("legacy-tz").to_dict()+ legacy.pop("timezone")+ store_path.write_text(+ json.dumps({"schema_version": 1, "jobs": [legacy]}), encoding="utf-8"+ )++ fetched = ScheduledResearchJobStore(path=store_path).get("legacy-tz")+ assert fetched is not None+ assert fetched.timezone is None++ def test_upsert_accepts_unresolvable_timezone_shape(self, tmp_path: Path) -> None:+ # Resolvability depends on the host tz database; the store checks only+ # the shape so lifecycle writes never crash on foreign keys.+ store = ScheduledResearchJobStore(path=tmp_path / "jobs.json")+ job = _make_job("tz-shape", schedule="0 12 * * *")+ job.timezone = "Not/AZone"+ store.upsert(job)+ fetched = store.get("tz-shape")+ assert fetched is not None+ assert fetched.timezone == "Not/AZone"++ def test_upsert_rejects_blank_timezone(self, tmp_path: Path) -> None:+ store = ScheduledResearchJobStore(path=tmp_path / "jobs.json")+ job = _make_job("tz-blank")+ job.timezone = " "+ with pytest.raises(ValueError, match="timezone"):+ store.upsert(job)++ def test_from_dict_rejects_non_string_timezone(self) -> None:+ raw = _make_job("tz-type").to_dict()+ raw["timezone"] = 13+ with pytest.raises(TypeError, match="'timezone' must be a string or null"):+ ScheduledResearchJob.from_dict(raw)++ def test_from_dict_normalizes_blank_timezone_to_none(self) -> None:+ # A blank string must load as None so every loaded record satisfies+ # the shape check the store re-runs on executor lifecycle writes.+ raw = _make_job("tz-blank-load").to_dict()+ raw["timezone"] = " "+ assert ScheduledResearchJob.from_dict(raw).timezone is None+def test_retry_state_round_trips_and_legacy_jobs_get_defaults(self, tmp_path: Path) -> None:store_path = tmp_path / "jobs.json"store = ScheduledResearchJobStore(path=store_path)diff --git a/agent/tests/test_scheduled_routes.py b/agent/tests/test_scheduled_routes.pyindex 7ced39e4f..f73a0eec6 100644--- a/agent/tests/test_scheduled_routes.py+++ b/agent/tests/test_scheduled_routes.py@@ -194,3 +194,129 @@ def test_delete_rejects_unsafe_job_id(response = client.delete("/scheduled-runs/bad.id")assert response.status_code == 400+++def test_create_with_timezone_echoes_and_persists(+ client: TestClient, store: ScheduledResearchJobStore+):+ response = client.post(+ "/scheduled-runs",+ json={+ "id": "auckland-scan",+ "prompt": "pre-open scan of NZX names",+ "schedule": "30 23 * * 1-5",+ "timezone": "Pacific/Auckland",+ },+ )++ assert response.status_code == 201+ assert response.json()["timezone"] == "Pacific/Auckland"++ saved = store.get("auckland-scan")+ assert saved is not None+ assert saved.timezone == "Pacific/Auckland"+ assert saved.schedule == "30 23 * * 1-5"+++def test_create_without_timezone_defaults_to_null(+ client: TestClient, store: ScheduledResearchJobStore+):+ response = client.post(+ "/scheduled-runs",+ json={"id": "utc-scan", "prompt": "scan", "schedule": "0 9 * * *"},+ )++ assert response.status_code == 201+ body = response.json()+ assert "timezone" in body+ assert body["timezone"] is None+ saved = store.get("utc-scan")+ assert saved is not None+ assert saved.timezone is None+++def test_create_rejects_unknown_timezone(+ client: TestClient, store: ScheduledResearchJobStore+):+ response = client.post(+ "/scheduled-runs",+ json={+ "id": "bad-tz",+ "prompt": "scan",+ "schedule": "0 9 * * *",+ "timezone": "Not/AZone",+ },+ )++ assert response.status_code == 422+ assert "IANA timezone" in response.json()["detail"]+ assert store.get("bad-tz") is None+++def test_list_includes_timezone(client: TestClient, store: ScheduledResearchJobStore):+ _seed(store, id="tz-listed", schedule="0 9 * * 1-5", timezone="Australia/Adelaide")++ response = client.get("/scheduled-runs")++ assert response.status_code == 200+ rows = {row["id"]: row for row in response.json()}+ assert rows["tz-listed"]["timezone"] == "Australia/Adelaide"+++def test_create_tz_cron_defaults_next_run_to_first_authored_occurrence(+ client: TestClient, store: ScheduledResearchJobStore+):+ from src.scheduled_research.executor import next_due++ before = int(__import__("time").time() * 1000)+ response = client.post(+ "/scheduled-runs",+ json={+ "id": "first-occurrence",+ "prompt": "scan",+ "schedule": "30 23 * * 1-5",+ "timezone": "Pacific/Auckland",+ },+ )+ after = int(__import__("time").time() * 1000)++ assert response.status_code == 201+ next_run_at = response.json()["next_run_at"]+ # The first fire is the first authored wall-clock occurrence, which for a+ # 23:30 weekday cadence is strictly in the future — never "now".+ assert next_run_at > after+ assert next_due("30 23 * * 1-5", before, "Pacific/Auckland") <= next_run_at+ assert next_run_at <= next_due("30 23 * * 1-5", after, "Pacific/Auckland")+++def test_create_without_timezone_keeps_immediate_first_fire(+ client: TestClient, store: ScheduledResearchJobStore+):+ before = int(__import__("time").time() * 1000)+ response = client.post(+ "/scheduled-runs",+ json={"id": "legacy-default", "prompt": "scan", "schedule": "0 9 * * *"},+ )+ after = int(__import__("time").time() * 1000)++ assert response.status_code == 201+ assert before <= response.json()["next_run_at"] <= after+++def test_create_interval_with_timezone_keeps_immediate_first_fire(+ client: TestClient, store: ScheduledResearchJobStore+):+ before = int(__import__("time").time() * 1000)+ response = client.post(+ "/scheduled-runs",+ json={+ "id": "interval-tz",+ "prompt": "scan",+ "schedule": "60000",+ "timezone": "Pacific/Auckland",+ },+ )+ after = int(__import__("time").time() * 1000)++ assert response.status_code == 201+ assert before <= response.json()["next_run_at"] <= afterdiff --git a/frontend/src/components/layout/Layout.tsx b/frontend/src/components/layout/Layout.tsxindex bb2c8ccc1..65fa99901 100644--- a/frontend/src/components/layout/Layout.tsx+++ b/frontend/src/components/layout/Layout.tsx@@ -1,7 +1,7 @@import { useTranslation } from "react-i18next";import { useEffect, useRef, useState } from "react";import { Link, Outlet, useLocation, useSearchParams } from "react-router";-import { Activity, BarChart3, Bot, Check, ChevronDown, FileText, Languages, Moon, Sun, Plus, Trash2, Pencil, MessageSquare, ChevronsLeft, ChevronsRight, Settings, Layers, Loader2 } from "lucide-react";+import { Activity, BarChart3, Bot, CalendarClock, Check, ChevronDown, FileText, Languages, Moon, Sun, Plus, Trash2, Pencil, MessageSquare, ChevronsLeft, ChevronsRight, Settings, Layers, Loader2 } from "lucide-react";import { cn } from "@/lib/utils";import { useDarkMode } from "@/hooks/useDarkMode";import { api, type SessionItem } from "@/lib/api";@@ -22,6 +22,7 @@ export function Layout() {const NAV = [{ to: "/", icon: Bot, label: t('layout.agent') },{ to: "/runtime", icon: Activity, label: t('layout.runtime') },+ { to: "/scheduled", icon: CalendarClock, label: t('layout.scheduled') },{ to: "/reports", icon: FileText, label: t('layout.reports') },{ to: "/alpha-zoo", icon: Layers, label: t('layout.alphaZoo') },{ to: "/settings", icon: Settings, label: t('layout.settings') },diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.jsonindex 1f5d28fba..419c8e196 100644--- a/frontend/src/i18n/locales/ar.json+++ b/frontend/src/i18n/locales/ar.json@@ -6,6 +6,7 @@"home": "الرئيسية","agent": "الوكيل","runtime": "مراقبة التداول",+ "scheduled": "المجدولة","reports": "التقارير","alphaZoo": "مكتبة ألفا","settings": "الإعدادات",@@ -120,6 +121,44 @@"diagnosticNetworkUnreachable": "يتعذر الوصول إلى خدمة Longbridge. تحقق من اتصال الشبكة، ثم أعد المحاولة.","diagnosticBrokerError": "رفض الوسيط طلب التحقق المخصص للقراءة فقط. أعد المحاولة أو راجع سجلات الخادم."},+ "scheduled": {+ "title": "الأبحاث المجدولة",+ "subtitle": "تشغيل دوري وفق توقيتك المحلي — يبقى الإيقاع ثابتًا عبر تغييرات التوقيت الصيفي.",+ "promptLabel": "موجّه البحث",+ "promptPlaceholder": "مثال: مسح ما قبل الافتتاح: رتّب أحجام التداول غير المعتادة أمس ولخّص أخبار الليل",+ "modeLabel": "إيقاع التشغيل",+ "modeTime": "في وقت محدد يوميًا",+ "modeAdvanced": "متقدم (cron أو فاصل زمني)",+ "timeLabel": "الوقت المحلي",+ "daysLabel": "الأيام",+ "daysWeekdays": "أيام العمل (الاثنين–الجمعة)",+ "daysEveryDay": "كل يوم",+ "scheduleLabel": "تعبير الجدولة",+ "advancedHint": "تعبير cron من 5 حقول يُقيّم في المنطقة الزمنية المحددة (دقيقة ساعة يوم شهر يوم-أسبوع؛ تُدعم القوائم والنطاقات)، أو فاصل زمني بالمللي ثانية.",+ "timezoneLabel": "المنطقة الزمنية",+ "create": "إنشاء جدولة",+ "promptRequired": "أدخل موجّه البحث قبل إنشاء الجدولة.",+ "invalidTime": "أدخل وقتًا صالحًا بصيغة HH:MM.",+ "executorHint": "تُنفّذ المهام فقط عندما يعمل الخادم مع تفعيل VIBE_TRADING_ENABLE_SCHEDULER.",+ "listTitle": "المهام المجدولة",+ "loading": "جارٍ تحميل المهام المجدولة…",+ "retry": "إعادة المحاولة",+ "empty": "لا توجد مهام مجدولة بعد — أنشئ واحدة أعلاه.",+ "cadenceEvery": "كل {{interval}}",+ "cadenceDaily": "يوميًا في {{time}}",+ "cadenceWeekly": "{{days}} في {{time}}",+ "statusPending": "قيد الانتظار",+ "statusRunning": "قيد التشغيل",+ "statusCompleted": "مكتمل",+ "statusFailed": "فشل",+ "statusCancelled": "أُلغي",+ "nextRun": "التشغيل التالي: {{when}}",+ "lastError": "آخر خطأ: {{error}}",+ "delete": "حذف",+ "deleteAria": "حذف المهمة المجدولة: {{prompt}}",+ "confirmDelete": "تأكيد الحذف",+ "confirmDeleteAria": "تأكيد حذف المهمة المجدولة: {{prompt}}"+ },"reports": {"badge": "التقارير","title": "مكتبة تقارير الاختبار العكسي",diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex 5aae46481..727ea17a6 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -11,6 +11,7 @@"home": "Home","agent": "Agent","runtime": "Runtime",+ "scheduled": "Scheduled","reports": "Reports","alphaZoo": "Alpha Zoo","settings": "Settings",@@ -125,6 +126,44 @@"diagnosticNetworkUnreachable": "The Longbridge service is unreachable. Check network access and retry.","diagnosticBrokerError": "The broker rejected the read-only verification request. Retry or check backend logs."},+ "scheduled": {+ "title": "Scheduled Research",+ "subtitle": "Recurring research runs on your local wall clock — cadences hold across DST changes.",+ "promptLabel": "Research prompt",+ "promptPlaceholder": "e.g. Pre-open scan: rank yesterday's unusual volume and summarize overnight news",+ "modeLabel": "Cadence",+ "modeTime": "At a time of day",+ "modeAdvanced": "Advanced (cron or interval)",+ "timeLabel": "Local time",+ "daysLabel": "Days",+ "daysWeekdays": "Weekdays (Mon–Fri)",+ "daysEveryDay": "Every day",+ "scheduleLabel": "Schedule expression",+ "advancedHint": "A 5-field cron expression evaluated in the selected timezone (minute hour day month weekday; lists and ranges allowed), or a bare interval in milliseconds.",+ "timezoneLabel": "Timezone",+ "create": "Schedule run",+ "promptRequired": "Enter a research prompt before scheduling.",+ "invalidTime": "Enter a valid time as HH:MM.",+ "executorHint": "Runs execute only when the server is started with VIBE_TRADING_ENABLE_SCHEDULER enabled.",+ "listTitle": "Scheduled runs",+ "loading": "Loading scheduled runs…",+ "retry": "Retry",+ "empty": "No scheduled runs yet — create one above.",+ "cadenceEvery": "Every {{interval}}",+ "cadenceDaily": "Daily at {{time}}",+ "cadenceWeekly": "{{days}} at {{time}}",+ "statusPending": "Pending",+ "statusRunning": "Running",+ "statusCompleted": "Completed",+ "statusFailed": "Failed",+ "statusCancelled": "Cancelled",+ "nextRun": "Next run: {{when}}",+ "lastError": "Last error: {{error}}",+ "delete": "Delete",+ "deleteAria": "Delete scheduled run: {{prompt}}",+ "confirmDelete": "Confirm delete",+ "confirmDeleteAria": "Confirm deleting scheduled run: {{prompt}}"+ },"reports": {"badge": "Reports","title": "Backtest Report Library",diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.jsonindex f6d4b65b5..ba62b1695 100644--- a/frontend/src/i18n/locales/ja.json+++ b/frontend/src/i18n/locales/ja.json@@ -6,6 +6,7 @@"home": "ホーム","agent": "エージェント","runtime": "取引モニター",+ "scheduled": "スケジュール","reports": "レポート","alphaZoo": "アルファ・ライブラリ","settings": "設定",@@ -120,6 +121,44 @@"diagnosticNetworkUnreachable": "Longbridge サービスに接続できません。ネットワーク接続を確認して再試行してください。","diagnosticBrokerError": "ブローカーが読み取り専用の検証リクエストを拒否しました。再試行するか、バックエンドのログを確認してください。"},+ "scheduled": {+ "title": "スケジュールリサーチ",+ "subtitle": "ローカルの壁時計どおりに定期実行——夏時間の切り替え後もリズムは変わりません。",+ "promptLabel": "リサーチプロンプト",+ "promptPlaceholder": "例:寄り付き前スキャン:昨日の出来高異常をランク付けし、夜間ニュースを要約",+ "modeLabel": "実行サイクル",+ "modeTime": "毎日決まった時刻",+ "modeAdvanced": "詳細設定(cron または間隔)",+ "timeLabel": "ローカル時刻",+ "daysLabel": "曜日",+ "daysWeekdays": "平日(月〜金)",+ "daysEveryDay": "毎日",+ "scheduleLabel": "スケジュール式",+ "advancedHint": "選択したタイムゾーンで評価される 5 フィールドの cron 式(分 時 日 月 曜日;リストと範囲に対応)、またはミリ秒単位の間隔。",+ "timezoneLabel": "タイムゾーン",+ "create": "スケジュールを作成",+ "promptRequired": "スケジュール作成の前にリサーチプロンプトを入力してください。",+ "invalidTime": "有効な時刻を HH:MM 形式で入力してください。",+ "executorHint": "サーバーで VIBE_TRADING_ENABLE_SCHEDULER が有効な場合のみ実行されます。",+ "listTitle": "スケジュール一覧",+ "loading": "スケジュールを読み込み中…",+ "retry": "再試行",+ "empty": "スケジュールはまだありません——上のフォームから作成してください。",+ "cadenceEvery": "{{interval}} ごと",+ "cadenceDaily": "毎日 {{time}}",+ "cadenceWeekly": "{{days}} {{time}}",+ "statusPending": "待機中",+ "statusRunning": "実行中",+ "statusCompleted": "完了",+ "statusFailed": "失敗",+ "statusCancelled": "キャンセル済み",+ "nextRun": "次回実行:{{when}}",+ "lastError": "直近のエラー:{{error}}",+ "delete": "削除",+ "deleteAria": "スケジュールを削除:{{prompt}}",+ "confirmDelete": "削除を確認",+ "confirmDeleteAria": "スケジュールの削除を確認:{{prompt}}"+ },"reports": {"badge": "レポート","title": "バックテストレポートライブラリ",diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.jsonindex 8e84a97fe..69c69956c 100644--- a/frontend/src/i18n/locales/ko.json+++ b/frontend/src/i18n/locales/ko.json@@ -6,6 +6,7 @@"home": "홈","agent": "에이전트","runtime": "거래 모니터",+ "scheduled": "예약","reports": "리포트","alphaZoo": "알파 라이브러리","settings": "설정",@@ -120,6 +121,44 @@"diagnosticNetworkUnreachable": "Longbridge 서비스에 연결할 수 없습니다. 네트워크 연결을 확인하고 다시 시도하세요.","diagnosticBrokerError": "브로커가 읽기 전용 검증 요청을 거부했습니다. 다시 시도하거나 백엔드 로그를 확인하세요."},+ "scheduled": {+ "title": "예약 리서치",+ "subtitle": "현지 시계 기준으로 반복 실행——서머타임 전환 후에도 주기가 유지됩니다.",+ "promptLabel": "리서치 프롬프트",+ "promptPlaceholder": "예: 장 시작 전 스캔: 전일 이상 거래량 순위와 야간 뉴스 요약",+ "modeLabel": "실행 주기",+ "modeTime": "매일 지정 시각",+ "modeAdvanced": "고급(cron 또는 간격)",+ "timeLabel": "현지 시각",+ "daysLabel": "요일",+ "daysWeekdays": "평일(월–금)",+ "daysEveryDay": "매일",+ "scheduleLabel": "스케줄 표현식",+ "advancedHint": "선택한 시간대 기준으로 평가되는 5필드 cron 표현식(분 시 일 월 요일; 목록과 범위 지원) 또는 밀리초 단위 간격.",+ "timezoneLabel": "시간대",+ "create": "예약 생성",+ "promptRequired": "예약을 만들기 전에 리서치 프롬프트를 입력하세요.",+ "invalidTime": "유효한 시각을 HH:MM 형식으로 입력하세요.",+ "executorHint": "서버에서 VIBE_TRADING_ENABLE_SCHEDULER가 활성화된 경우에만 실행됩니다.",+ "listTitle": "예약 목록",+ "loading": "예약을 불러오는 중…",+ "retry": "다시 시도",+ "empty": "예약된 작업이 없습니다——위에서 만들어 보세요.",+ "cadenceEvery": "{{interval}}마다",+ "cadenceDaily": "매일 {{time}}",+ "cadenceWeekly": "{{days}} {{time}}",+ "statusPending": "대기 중",+ "statusRunning": "실행 중",+ "statusCompleted": "완료",+ "statusFailed": "실패",+ "statusCancelled": "취소됨",+ "nextRun": "다음 실행: {{when}}",+ "lastError": "최근 오류: {{error}}",+ "delete": "삭제",+ "deleteAria": "예약 삭제: {{prompt}}",+ "confirmDelete": "삭제 확인",+ "confirmDeleteAria": "예약 삭제 확인: {{prompt}}"+ },"reports": {"badge": "리포트","title": "백테스트 리포트 라이브러리",diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.jsonindex e2b4f648f..c00cdd251 100644--- a/frontend/src/i18n/locales/zh-CN.json+++ b/frontend/src/i18n/locales/zh-CN.json@@ -6,6 +6,7 @@"home": "首页","agent": "智能体","runtime": "交易监控",+ "scheduled": "定时任务","reports": "报告","alphaZoo": "Alpha 因子库","settings": "设置",@@ -120,6 +121,44 @@"diagnosticNetworkUnreachable": "无法连接 Longbridge 服务。请检查网络后重试。","diagnosticBrokerError": "券商拒绝了只读验证请求。请重试或检查后端日志。"},+ "scheduled": {+ "title": "定时研究",+ "subtitle": "按你的本地时间周期运行研究任务——夏令时切换后节奏保持不变。",+ "promptLabel": "研究提示词",+ "promptPlaceholder": "例如:盘前扫描:按昨日异常成交量排名并总结隔夜新闻",+ "modeLabel": "运行节奏",+ "modeTime": "每天定时",+ "modeAdvanced": "高级(cron 或间隔)",+ "timeLabel": "本地时间",+ "daysLabel": "运行日",+ "daysWeekdays": "工作日(周一至周五)",+ "daysEveryDay": "每天",+ "scheduleLabel": "调度表达式",+ "advancedHint": "在所选时区求值的 5 字段 cron 表达式(分 时 日 月 星期;支持列表和范围),或以毫秒为单位的间隔。",+ "timezoneLabel": "时区",+ "create": "创建定时任务",+ "promptRequired": "请先填写研究提示词再创建定时任务。",+ "invalidTime": "请输入有效时间(格式 HH:MM)。",+ "executorHint": "仅当服务端启用 VIBE_TRADING_ENABLE_SCHEDULER 时才会执行。",+ "listTitle": "定时任务",+ "loading": "正在加载定时任务…",+ "retry": "重试",+ "empty": "暂无定时任务——请在上方创建。",+ "cadenceEvery": "每 {{interval}}",+ "cadenceDaily": "每天 {{time}}",+ "cadenceWeekly": "{{days}} {{time}}",+ "statusPending": "待运行",+ "statusRunning": "运行中",+ "statusCompleted": "已完成",+ "statusFailed": "失败",+ "statusCancelled": "已取消",+ "nextRun": "下次运行:{{when}}",+ "lastError": "最近错误:{{error}}",+ "delete": "删除",+ "deleteAria": "删除定时任务:{{prompt}}",+ "confirmDelete": "确认删除",+ "confirmDeleteAria": "确认删除定时任务:{{prompt}}"+ },"reports": {"badge": "报告","title": "回测报告库",diff --git a/frontend/src/lib/__tests__/cadence.test.ts b/frontend/src/lib/__tests__/cadence.test.tsnew file mode 100644index 000000000..21f8edfdc--- /dev/null+++ b/frontend/src/lib/__tests__/cadence.test.ts@@ -0,0 +1,65 @@+import { describe, expect, it } from "vitest";+import {+ describeCadence,+ formatIntervalMs,+ formatWallTime,+ formatWeekdays,+} from "@/lib/cadence";++describe("describeCadence", () => {+ it("classifies interval-ms schedules", () => {+ expect(describeCadence("60000")).toEqual({ kind: "interval", ms: 60000 });+ });++ it("classifies a fixed daily time", () => {+ expect(describeCadence("0 9 * * *")).toEqual({ kind: "daily", hour: 9, minute: 0 });+ });++ it("classifies weekday ranges and lists in local terms", () => {+ expect(describeCadence("30 23 * * 1-5")).toEqual({+ kind: "weekly",+ weekdays: [1, 2, 3, 4, 5],+ hour: 23,+ minute: 30,+ });+ expect(describeCadence("0 9 * * 1,3-4")).toEqual({+ kind: "weekly",+ weekdays: [1, 3, 4],+ hour: 9,+ minute: 0,+ });+ });++ it("falls back to the raw expression for anything else", () => {+ expect(describeCadence("*/5 * * * *")).toEqual({ kind: "cron", expression: "*/5 * * * *" });+ expect(describeCadence("0 9 1 * *")).toEqual({ kind: "cron", expression: "0 9 1 * *" });+ expect(describeCadence("0 9 * * 5-1")).toEqual({ kind: "cron", expression: "0 9 * * 5-1" });+ });+});++describe("formatIntervalMs", () => {+ it("prefers the largest whole unit", () => {+ expect(formatIntervalMs(3_600_000)).toBe("1h");+ expect(formatIntervalMs(300_000)).toBe("5m");+ expect(formatIntervalMs(5_000)).toBe("5s");+ expect(formatIntervalMs(1_500)).toBe("1500ms");+ });+});++describe("formatWallTime", () => {+ it("zero-pads to HH:MM", () => {+ expect(formatWallTime(9, 5)).toBe("09:05");+ expect(formatWallTime(23, 30)).toBe("23:30");+ });+});++describe("formatWeekdays", () => {+ it("collapses a contiguous span", () => {+ expect(formatWeekdays([1, 2, 3, 4, 5], "en")).toBe("Mon–Fri");+ });++ it("lists non-contiguous days", () => {+ expect(formatWeekdays([1, 3, 5], "en")).toBe("Mon, Wed, Fri");+ expect(formatWeekdays([0, 6], "en")).toBe("Sun, Sat");+ });+});diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex dcd67a5de..8dd62c6a8 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -147,6 +147,13 @@ export const api = {// Codex-style LLM summary title from the first exchange; backend refuses to// overwrite a manual rename, so this is safe to fire-and-forget.autoTitleSession: (sid: string) => request<{ status: string; title: string }>(`/sessions/${sid}/title/auto`, { method: "POST" }),+ // Scheduled research: cadence + timezone are stored as authored (local+ // wall-clock cron + IANA key), so list rows render without any UTC math.+ listScheduledRuns: (signal?: AbortSignal) => request<ScheduledRun[]>("/scheduled-runs", { signal }),+ createScheduledRun: (body: CreateScheduledRunRequest) =>+ request<ScheduledRun>("/scheduled-runs", { method: "POST", body: JSON.stringify(body) }),+ deleteScheduledRun: (id: string) =>+ request<void>(`/scheduled-runs/${encodeURIComponent(id)}`, { method: "DELETE" }),sendMessage: (sid: string, content: string) => request<{ message_id: string; attempt_id: string }>(`/sessions/${sid}/messages`, { method: "POST", body: JSON.stringify({ content }) }),cancelSession: (sid: string) => request<{ status: string }>(`/sessions/${sid}/cancel`, { method: "POST" }),getSessionMessages: (sid: string) => request<MessageItem[]>(`/sessions/${sid}/messages`),@@ -288,6 +295,31 @@ export const api = {}),};+// --- Scheduled research types ---++export interface ScheduledRun {+ id: string;+ prompt: string;+ schedule: string;+ next_run_at: number;+ status: string;+ created_at: number;+ last_run_at: number | null;+ consecutive_failures: number;+ last_error: string | null;+ failure_kind: string | null;+ config: Record<string, unknown>;+ timezone: string | null;+}++export interface CreateScheduledRunRequest {+ id?: string;+ prompt: string;+ schedule: string;+ timezone?: string | null;+ config?: Record<string, unknown>;+}+// --- Swarm types ---export interface SwarmPreset {diff --git a/frontend/src/lib/cadence.ts b/frontend/src/lib/cadence.tsnew file mode 100644index 000000000..ba1076266--- /dev/null+++ b/frontend/src/lib/cadence.ts@@ -0,0 +1,82 @@+// Structured description of a scheduled-run cadence.+//+// The backend stores the schedule exactly as authored: an interval-ms string,+// or a 5-field cron expression evaluated on the wall clock of the job's IANA+// timezone (UTC when the job has none). Because the stored cron is already+// local time, describing it is a lossless read — no UTC conversion happens+// here, which is what keeps the description correct on both sides of a DST+// transition (#953).++export type CadenceDescription =+ | { kind: "interval"; ms: number }+ | { kind: "daily"; hour: number; minute: number }+ | { kind: "weekly"; weekdays: number[]; hour: number; minute: number }+ | { kind: "cron"; expression: string };++const INTERVAL_RE = /^[1-9][0-9]*$/;+const SIMPLE_VALUE_RE = /^[0-9]+$/;++function parseDowField(field: string): number[] | null {+ // Cron day-of-week convention: Sunday == 0. Accepts N, N-M, and comma+ // lists of both — the exact grammar the backend validates.+ const days = new Set<number>();+ for (const atom of field.split(",")) {+ const match = /^([0-9]+)(?:-([0-9]+))?$/.exec(atom);+ if (!match) return null;+ const start = Number(match[1]);+ const end = match[2] !== undefined ? Number(match[2]) : start;+ if (start > end || end > 6) return null;+ for (let d = start; d <= end; d++) days.add(d);+ }+ return Array.from(days).sort((a, b) => a - b);+}++export function describeCadence(schedule: string): CadenceDescription {+ const spec = schedule.trim();+ if (INTERVAL_RE.test(spec)) {+ return { kind: "interval", ms: Number(spec) };+ }+ const fields = spec.split(/\s+/);+ if (fields.length === 5) {+ const [minute, hour, dom, month, dow] = fields;+ const fixedTime = SIMPLE_VALUE_RE.test(minute) && SIMPLE_VALUE_RE.test(hour);+ if (fixedTime && dom === "*" && month === "*") {+ if (dow === "*") {+ return { kind: "daily", hour: Number(hour), minute: Number(minute) };+ }+ const weekdays = parseDowField(dow);+ if (weekdays) {+ return { kind: "weekly", weekdays, hour: Number(hour), minute: Number(minute) };+ }+ }+ }+ return { kind: "cron", expression: spec };+}++export function formatIntervalMs(ms: number): string {+ if (ms % 3_600_000 === 0) return `${ms / 3_600_000}h`;+ if (ms % 60_000 === 0) return `${ms / 60_000}m`;+ if (ms % 1_000 === 0) return `${ms / 1_000}s`;+ return `${ms}ms`;+}++export function formatWallTime(hour: number, minute: number): string {+ return `${String(hour).padStart(2, "0")}:${String(minute).padStart(2, "0")}`;+}++// 2021-08-01 was a Sunday, so day offsets map cron's Sunday==0 convention+// onto real dates for locale-aware weekday names.+const CRON_SUNDAY_UTC_MS = Date.UTC(2021, 7, 1);++export function formatWeekdays(weekdays: number[], locale: string): string {+ const names = new Intl.DateTimeFormat(locale, { weekday: "short", timeZone: "UTC" });+ const label = (d: number) => names.format(new Date(CRON_SUNDAY_UTC_MS + d * 86_400_000));+ // Collapse a contiguous span into "Mon–Fri"; anything else stays a list.+ const contiguous =+ weekdays.length > 2 &&+ weekdays.every((d, i) => i === 0 || d === weekdays[i - 1] + 1);+ if (contiguous) {+ return `${label(weekdays[0])}–${label(weekdays[weekdays.length - 1])}`;+ }+ return weekdays.map(label).join(", ");+}diff --git a/frontend/src/pages/Scheduled.tsx b/frontend/src/pages/Scheduled.tsxnew file mode 100644index 000000000..c5d1310b1--- /dev/null+++ b/frontend/src/pages/Scheduled.tsx@@ -0,0 +1,432 @@+import { useCallback, useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { CalendarClock, Loader2, Plus, Trash2 } from "lucide-react";+import { cn } from "@/lib/utils";+import { api, ApiError, type ScheduledRun } from "@/lib/api";+import {+ describeCadence,+ formatIntervalMs,+ formatWallTime,+ formatWeekdays,+} from "@/lib/cadence";++const fieldClass =+ "w-full rounded-md border bg-background px-3 py-2 text-sm outline-none transition focus:border-primary focus:ring-2 focus:ring-primary/20 disabled:cursor-not-allowed disabled:opacity-60";+const labelClass = "text-sm font-medium";+const hintClass = "text-xs text-muted-foreground";++const POLL_MS = 15_000;++type DaysChoice = "every" | "weekdays";+type ComposerMode = "time" | "advanced";++function browserTimezone(): string {+ try {+ return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";+ } catch {+ return "UTC";+ }+}++function timezoneOptions(): string[] {+ // Not yet in the project's TS lib target, hence the local type.+ const supported = (Intl as { supportedValuesOf?: (key: "timeZone") => string[] })+ .supportedValuesOf;+ const zones = typeof supported === "function" ? supported("timeZone") : [browserTimezone()];+ return zones.includes("UTC") ? zones : ["UTC", ...zones];+}++// Jobs created before timezone support have timezone=null and keep their+// original UTC semantics; render them as UTC without converting anything.+function displayZone(run: ScheduledRun): string {+ return run.timezone ?? "UTC";+}++function formatInZone(epochMs: number, zone: string, locale: string): string {+ const date = new Date(epochMs);+ if (Number.isNaN(date.getTime())) return "—";+ try {+ return new Intl.DateTimeFormat(locale, {+ timeZone: zone,+ dateStyle: "medium",+ timeStyle: "short",+ }).format(date);+ } catch {+ return date.toISOString();+ }+}++function StatusPill({ label, tone }: { label: string; tone: "success" | "danger" | "warning" | "neutral" }) {+ return (+ <span+ className={cn(+ "inline-flex items-center rounded px-2 py-0.5 text-xs font-medium",+ tone === "success" && "bg-success/10 text-success",+ tone === "danger" && "bg-danger/10 text-danger",+ tone === "warning" && "bg-warning/10 text-warning",+ tone === "neutral" && "bg-muted text-muted-foreground",+ )}+ >+ {label}+ </span>+ );+}++export function Scheduled() {+ const { t, i18n } = useTranslation();+ const locale = i18n.language;++ const [runs, setRuns] = useState<ScheduledRun[]>([]);+ const [loading, setLoading] = useState(true);+ const [listError, setListError] = useState<string | null>(null);+ const [pendingDelete, setPendingDelete] = useState<string | null>(null);++ const [prompt, setPrompt] = useState("");+ const [mode, setMode] = useState<ComposerMode>("time");+ const [time, setTime] = useState("09:00");+ const [days, setDays] = useState<DaysChoice>("weekdays");+ const [advanced, setAdvanced] = useState("");+ const [timezone, setTimezone] = useState(() => browserTimezone());+ const [saving, setSaving] = useState(false);+ const [composerError, setComposerError] = useState<string | null>(null);++ const zonesRef = useRef<string[] | null>(null);+ if (zonesRef.current === null) zonesRef.current = timezoneOptions();++ // Stale-response guard: each refresh aborts the previous request and only+ // the newest sequence number may write state, so a slow 15s poll can never+ // overwrite the list a create/delete just updated.+ const refreshSeq = useRef(0);+ const refreshController = useRef<AbortController | null>(null);++ const refresh = useCallback(async () => {+ refreshController.current?.abort();+ const controller = new AbortController();+ refreshController.current = controller;+ const seq = ++refreshSeq.current;+ try {+ const rows = await api.listScheduledRuns(controller.signal);+ if (seq !== refreshSeq.current) return;+ setRuns(rows);+ setListError(null);+ } catch (error) {+ if (seq !== refreshSeq.current || controller.signal.aborted) return;+ setListError(error instanceof ApiError ? error.message : String(error));+ } finally {+ if (seq === refreshSeq.current) setLoading(false);+ }+ }, []);++ useEffect(() => {+ void refresh();+ const timer = setInterval(() => void refresh(), POLL_MS);+ return () => {+ refreshSeq.current++; // invalidate any in-flight response+ refreshController.current?.abort();+ clearInterval(timer);+ };+ }, [refresh]);++ // Auto-disarm an armed delete after a few seconds (blur is unreliable on+ // Safari/iOS, where buttons do not take focus on click).+ useEffect(() => {+ if (pendingDelete === null) return;+ const timer = setTimeout(() => setPendingDelete(null), 5_000);+ return () => clearTimeout(timer);+ }, [pendingDelete]);++ function composedSchedule(): string | null {+ if (mode === "advanced") {+ const spec = advanced.trim();+ return spec ? spec : null;+ }+ const match = /^(\d{1,2}):(\d{2})$/.exec(time);+ if (!match) return null;+ return `${Number(match[2])} ${Number(match[1])} * * ${days === "every" ? "*" : "1-5"}`;+ }++ async function handleCreate(event: React.FormEvent) {+ event.preventDefault();+ setComposerError(null);+ if (!prompt.trim()) {+ setComposerError(t("scheduled.promptRequired"));+ return;+ }+ const schedule = composedSchedule();+ if (schedule === null) {+ setComposerError(t("scheduled.invalidTime"));+ return;+ }+ setSaving(true);+ try {+ await api.createScheduledRun({ prompt: prompt.trim(), schedule, timezone });+ setPrompt("");+ await refresh();+ } catch (error) {+ setComposerError(error instanceof ApiError ? error.message : String(error));+ } finally {+ setSaving(false);+ }+ }++ async function handleConfirmedDelete(id: string) {+ setPendingDelete(null);+ try {+ await api.deleteScheduledRun(id);+ await refresh();+ } catch (error) {+ setListError(error instanceof ApiError ? error.message : String(error));+ }+ }++ function cadenceLabel(run: ScheduledRun): string {+ const cadence = describeCadence(run.schedule);+ switch (cadence.kind) {+ case "interval":+ return t("scheduled.cadenceEvery", { interval: formatIntervalMs(cadence.ms) });+ case "daily":+ return t("scheduled.cadenceDaily", { time: formatWallTime(cadence.hour, cadence.minute) });+ case "weekly":+ return t("scheduled.cadenceWeekly", {+ days: formatWeekdays(cadence.weekdays, locale),+ time: formatWallTime(cadence.hour, cadence.minute),+ });+ default:+ return cadence.expression;+ }+ }++ function statusLabel(run: ScheduledRun): { label: string; tone: "success" | "danger" | "warning" | "neutral" } {+ switch (run.status) {+ case "completed":+ return { label: t("scheduled.statusCompleted"), tone: "success" };+ case "failed":+ return { label: t("scheduled.statusFailed"), tone: "danger" };+ case "running":+ return { label: t("scheduled.statusRunning"), tone: "warning" };+ case "cancelled":+ return { label: t("scheduled.statusCancelled"), tone: "neutral" };+ default:+ return { label: t("scheduled.statusPending"), tone: "neutral" };+ }+ }++ return (+ <div className="mx-auto max-w-4xl space-y-6 p-6">+ <header className="flex items-center gap-3">+ <CalendarClock className="h-6 w-6 text-primary" aria-hidden />+ <div>+ <h1 className="text-xl font-semibold">{t("scheduled.title")}</h1>+ <p className={hintClass}>{t("scheduled.subtitle")}</p>+ </div>+ </header>++ <form onSubmit={handleCreate} className="space-y-4 rounded-lg border bg-card p-4">+ <div className="space-y-1.5">+ <label htmlFor="scheduled-prompt" className={labelClass}>+ {t("scheduled.promptLabel")}+ </label>+ <textarea+ id="scheduled-prompt"+ required+ rows={2}+ value={prompt}+ onChange={(e) => setPrompt(e.target.value)}+ placeholder={t("scheduled.promptPlaceholder")}+ className={fieldClass}+ />+ </div>++ <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">+ <div className="space-y-1.5">+ <label htmlFor="scheduled-mode" className={labelClass}>+ {t("scheduled.modeLabel")}+ </label>+ <select+ id="scheduled-mode"+ value={mode}+ onChange={(e) => setMode(e.target.value as ComposerMode)}+ className={fieldClass}+ >+ <option value="time">{t("scheduled.modeTime")}</option>+ <option value="advanced">{t("scheduled.modeAdvanced")}</option>+ </select>+ </div>++ {mode === "time" ? (+ <>+ <div className="space-y-1.5">+ <label htmlFor="scheduled-time" className={labelClass}>+ {t("scheduled.timeLabel")}+ </label>+ <input+ id="scheduled-time"+ type="time"+ required+ value={time}+ onChange={(e) => setTime(e.target.value)}+ className={fieldClass}+ />+ </div>+ <div className="space-y-1.5">+ <label htmlFor="scheduled-days" className={labelClass}>+ {t("scheduled.daysLabel")}+ </label>+ <select+ id="scheduled-days"+ value={days}+ onChange={(e) => setDays(e.target.value as DaysChoice)}+ className={fieldClass}+ >+ <option value="weekdays">{t("scheduled.daysWeekdays")}</option>+ <option value="every">{t("scheduled.daysEveryDay")}</option>+ </select>+ </div>+ </>+ ) : (+ <div className="space-y-1.5 sm:col-span-2">+ <label htmlFor="scheduled-advanced" className={labelClass}>+ {t("scheduled.scheduleLabel")}+ </label>+ <input+ id="scheduled-advanced"+ required+ value={advanced}+ onChange={(e) => setAdvanced(e.target.value)}+ placeholder="30 23 * * 1-5"+ className={cn(fieldClass, "font-mono")}+ />+ <p className={hintClass}>{t("scheduled.advancedHint")}</p>+ </div>+ )}++ <div className="space-y-1.5">+ <label htmlFor="scheduled-timezone" className={labelClass}>+ {t("scheduled.timezoneLabel")}+ </label>+ <select+ id="scheduled-timezone"+ value={timezone}+ onChange={(e) => setTimezone(e.target.value)}+ className={fieldClass}+ >+ {zonesRef.current.map((zone) => (+ <option key={zone} value={zone}>+ {zone}+ </option>+ ))}+ </select>+ </div>+ </div>++ {composerError && (+ <p role="alert" className="text-sm text-danger">+ {composerError}+ </p>+ )}++ <div className="flex flex-wrap items-center gap-3">+ <button+ type="submit"+ disabled={saving}+ className="inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-60"+ >+ {saving ? <Loader2 className="h-4 w-4 animate-spin" aria-hidden /> : <Plus className="h-4 w-4" aria-hidden />}+ {t("scheduled.create")}+ </button>+ <p className={hintClass}>{t("scheduled.executorHint")}</p>+ </div>+ </form>++ <section aria-label={t("scheduled.listTitle")} className="rounded-lg border bg-card">+ {loading ? (+ <div className="flex items-center justify-center gap-2 p-8 text-sm text-muted-foreground">+ <Loader2 className="h-4 w-4 animate-spin" aria-hidden />+ {t("scheduled.loading")}+ </div>+ ) : listError && runs.length === 0 ? (+ <div className="space-y-2 p-6 text-sm">+ <p className="text-danger">{listError}</p>+ <button+ type="button"+ onClick={() => void refresh()}+ className="rounded-md border px-3 py-1.5 text-sm transition hover:bg-muted"+ >+ {t("scheduled.retry")}+ </button>+ </div>+ ) : runs.length === 0 ? (+ <p className="p-8 text-center text-sm text-muted-foreground">{t("scheduled.empty")}</p>+ ) : (+ <>+ {listError && (+ <p role="alert" className="border-b px-4 py-2 text-xs text-danger">+ {listError}+ </p>+ )}+ <ul className="divide-y">+ {runs.map((run) => {+ const status = statusLabel(run);+ const zone = displayZone(run);+ return (+ <li key={run.id} className="flex flex-wrap items-start gap-3 p-4">+ <div className="min-w-0 flex-1 space-y-1">+ <div className="flex flex-wrap items-center gap-2">+ <span className="font-medium">{cadenceLabel(run)}</span>+ <span className={hintClass}>{zone}</span>+ <StatusPill label={status.label} tone={status.tone} />+ </div>+ <p className="truncate text-sm text-muted-foreground">{run.prompt}</p>+ <p className={hintClass}>+ {t("scheduled.nextRun", {+ when: formatInZone(run.next_run_at, zone, locale),+ })}+ </p>+ {run.last_error && (+ <p className="break-words text-xs text-danger">+ {t("scheduled.lastError", { error: run.last_error })}+ </p>+ )}+ </div>+ {pendingDelete === run.id ? (+ <div className="flex items-center gap-1.5">+ {/* Cancel first so it inherits the Delete button's spot —+ an accidental double-click disarms instead of destroying. */}+ <button+ type="button"+ onClick={() => setPendingDelete(null)}+ className="rounded-md border px-2.5 py-1.5 text-xs text-muted-foreground transition hover:bg-muted"+ >+ {t("layout.cancel")}+ </button>+ <button+ type="button"+ onClick={() => void handleConfirmedDelete(run.id)}+ aria-label={t("scheduled.confirmDeleteAria", { prompt: run.prompt })}+ className="inline-flex items-center gap-1.5 rounded-md border border-danger bg-danger/10 px-2.5 py-1.5 text-xs text-danger transition"+ >+ <Trash2 className="h-3.5 w-3.5" aria-hidden />+ {t("scheduled.confirmDelete")}+ </button>+ </div>+ ) : (+ <button+ type="button"+ onClick={() => setPendingDelete(run.id)}+ aria-label={t("scheduled.deleteAria", { prompt: run.prompt })}+ className="inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1.5 text-xs text-muted-foreground transition hover:bg-muted"+ >+ <Trash2 className="h-3.5 w-3.5" aria-hidden />+ {t("scheduled.delete")}+ </button>+ )}+ </li>+ );+ })}+ </ul>+ </>+ )}+ </section>+ </div>+ );+}diff --git a/frontend/src/pages/__tests__/Scheduled.test.tsx b/frontend/src/pages/__tests__/Scheduled.test.tsxnew file mode 100644index 000000000..0c2d5eec9--- /dev/null+++ b/frontend/src/pages/__tests__/Scheduled.test.tsx@@ -0,0 +1,139 @@+import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { Scheduled } from "@/pages/Scheduled";+import { ApiError, api, type ScheduledRun } from "@/lib/api";++vi.mock("@/lib/api", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@/lib/api")>();+ return {+ ...actual,+ api: {+ ...actual.api,+ listScheduledRuns: vi.fn(),+ createScheduledRun: vi.fn(),+ deleteScheduledRun: vi.fn(),+ },+ };+});++const mocked = api as unknown as {+ listScheduledRuns: ReturnType<typeof vi.fn>;+ createScheduledRun: ReturnType<typeof vi.fn>;+ deleteScheduledRun: ReturnType<typeof vi.fn>;+};++function run(overrides: Partial<ScheduledRun> = {}): ScheduledRun {+ return {+ id: "auckland-scan",+ prompt: "pre-open scan of NZX names",+ schedule: "30 23 * * 1-5",+ next_run_at: 1_790_000_000_000,+ status: "pending",+ created_at: 1_780_000_000_000,+ last_run_at: null,+ consecutive_failures: 0,+ last_error: null,+ failure_kind: null,+ config: {},+ timezone: "Pacific/Auckland",+ ...overrides,+ };+}++beforeEach(() => {+ vi.clearAllMocks();+ mocked.listScheduledRuns.mockResolvedValue([]);+});++describe("Scheduled page", () => {+ it("renders the stored local cadence and timezone without UTC conversion", async () => {+ mocked.listScheduledRuns.mockResolvedValue([run()]);+ render(<Scheduled />);++ expect(await screen.findByText("Mon–Fri at 23:30")).toBeInTheDocument();+ const row = screen.getByRole("listitem");+ expect(within(row).getByText("Pacific/Auckland")).toBeInTheDocument();+ expect(within(row).getByText("pre-open scan of NZX names")).toBeInTheDocument();+ });++ it("shows legacy timezone-less jobs as UTC", async () => {+ mocked.listScheduledRuns.mockResolvedValue([run({ timezone: null, schedule: "0 9 * * *" })]);+ render(<Scheduled />);++ expect(await screen.findByText("Daily at 09:00")).toBeInTheDocument();+ expect(within(screen.getByRole("listitem")).getByText("UTC")).toBeInTheDocument();+ });++ it("creates a job from the wall-clock composer", async () => {+ mocked.createScheduledRun.mockResolvedValue(run());+ render(<Scheduled />);+ await screen.findByText(/No scheduled runs yet/);++ fireEvent.change(screen.getByLabelText("Research prompt"), {+ target: { value: "scan the pre-open movers" },+ });+ fireEvent.change(screen.getByLabelText("Local time"), { target: { value: "23:30" } });+ fireEvent.submit(screen.getByRole("button", { name: /Schedule run/ }));++ await waitFor(() =>+ expect(mocked.createScheduledRun).toHaveBeenCalledWith(+ expect.objectContaining({+ prompt: "scan the pre-open movers",+ schedule: "30 23 * * 1-5",+ timezone: expect.any(String),+ }),+ ),+ );+ });++ it("surfaces a validation error from the backend", async () => {+ mocked.createScheduledRun.mockRejectedValue(+ new ApiError("timezone 'Not/AZone' is not a recognized IANA timezone key", 422),+ );+ render(<Scheduled />);+ await screen.findByText(/No scheduled runs yet/);++ fireEvent.change(screen.getByLabelText("Research prompt"), {+ target: { value: "scan" },+ });+ fireEvent.submit(screen.getByRole("button", { name: /Schedule run/ }));++ expect(await screen.findByRole("alert")).toHaveTextContent(+ "not a recognized IANA timezone",+ );+ });++ it("deletes only after an explicit confirm click, and cancel disarms", async () => {+ mocked.listScheduledRuns.mockResolvedValue([run()]);+ mocked.deleteScheduledRun.mockResolvedValue(undefined);+ render(<Scheduled />);++ fireEvent.click(await screen.findByRole("button", { name: /Delete scheduled run/ }));+ expect(mocked.deleteScheduledRun).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));+ expect(screen.queryByRole("button", { name: /Confirm deleting/ })).not.toBeInTheDocument();+ expect(mocked.deleteScheduledRun).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole("button", { name: /Delete scheduled run/ }));+ fireEvent.click(screen.getByRole("button", { name: /Confirm deleting/ }));+ await waitFor(() =>+ expect(mocked.deleteScheduledRun).toHaveBeenCalledWith("auckland-scan"),+ );+ });++ it("blocks a whitespace-only prompt client-side", async () => {+ render(<Scheduled />);+ await screen.findByText(/No scheduled runs yet/);++ fireEvent.change(screen.getByLabelText("Research prompt"), {+ target: { value: " " },+ });+ fireEvent.submit(screen.getByRole("button", { name: /Schedule run/ }));++ expect(await screen.findByRole("alert")).toHaveTextContent(+ "Enter a research prompt",+ );+ expect(mocked.createScheduledRun).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/router.tsx b/frontend/src/router.tsxindex 9c58044a4..ca163ebab 100644--- a/frontend/src/router.tsx+++ b/frontend/src/router.tsx@@ -16,6 +16,9 @@ const Settings = lazy(() =>const Runtime = lazy(() =>import("@/pages/Runtime").then((m) => ({ default: m.Runtime })),);+const Scheduled = lazy(() =>+ import("@/pages/Scheduled").then((m) => ({ default: m.Scheduled })),+);const Reports = lazy(() =>import("@/pages/Reports").then((m) => ({ default: m.Reports })),);@@ -50,6 +53,7 @@ export const router = createBrowserRouter([{ path: "/about", element: wrap(Home) },{ path: "/agent", element: wrap(Agent) },{ path: "/runtime", element: wrap(Runtime) },+ { path: "/scheduled", element: wrap(Scheduled) },{ path: "/reports", element: wrap(Reports) },{ path: "/settings", element: wrap(Settings) },{ path: "/runs/:runId", element: wrap(RunDetail) },diff --git a/frontend/vite.config.ts b/frontend/vite.config.tsindex a3b45650a..b29420d76 100644--- a/frontend/vite.config.ts+++ b/frontend/vite.config.ts@@ -15,6 +15,7 @@ const PROXY_PATHS = ["/live","/upload","/shadow-reports",+ "/scheduled-runs",];export default defineConfig(({ mode }) => {