Skip to content

🙌 OpenHands: AI-Driven Development

feat: allow editing a custom cron expression from the edit-automation modal (#16964)

Vasco Schiavo50144692e369
diff --git a/__tests__/components/automations/detail/edit-automation-modal.test.tsx b/__tests__/components/automations/detail/edit-automation-modal.test.tsx
index 4644960cb0..6dc89f4ded 100644
--- a/__tests__/components/automations/detail/edit-automation-modal.test.tsx
+++ b/__tests__/components/automations/detail/edit-automation-modal.test.tsx
@@ -96,6 +96,23 @@ const customAutomation: Automation = {
trigger: { type: "cron", schedule: "0 9,17 * * *" },
};
+// An automation whose stored schedule this form's validator rejects.
+const rejectedScheduleAutomation: Automation = {
+ ...dailyAutomation,
+ id: "auto-6",
+ name: "Legacy schedule",
+ trigger: { type: "cron", schedule: "0 0 30 2 *" },
+};
+
+// An event-triggered automation. `buildInitialState` marks these as custom
+// schedules too, so they guard the submit path against cron validation.
+const eventAutomation: Automation = {
+ ...dailyAutomation,
+ id: "auto-5",
+ name: "On PR opened",
+ trigger: { type: "event", source: "github", on: "pull_request.opened" },
+};
+
// A schedule automation pinned to a concrete LLM profile, used to exercise
// the profile picker (the base fixtures intentionally leave `model` unset).
const modeledAutomation: Automation = {
@@ -235,20 +252,19 @@ describe("EditAutomationModal", () => {
).toBeInTheDocument();
});
- it("renders custom-schedule hint and skips schedule mutation for non-preset cron", async () => {
+ it("renders the cron field and skips schedule mutation for non-preset cron", async () => {
// Arrange — schedule "0 9,17 * * *" is not a Daily/Weekdays/Weekly
- // preset; the modal must treat it as read-only for frequency but
- // still allow editing the prompt/name.
+ // preset; frequency stays read-only but the expression itself, and
+ // the prompt/name, remain editable.
vi.mocked(AutomationService.updateAutomation).mockResolvedValue(
customAutomation,
);
const user = userEvent.setup();
renderModal(customAutomation);
- // The hint surfaces so the user understands why frequency is
- // disabled; this is the user-visible signal that we're in
- // custom mode.
- expect(screen.getByTestId("custom-schedule-hint")).toBeInTheDocument();
+ // The cron field is the user-visible signal that we're in custom mode.
+ expect(screen.getByTestId("edit-automation-cron")).toBeInTheDocument();
+ expect(screen.getByTestId("edit-automation-frequency")).toBeDisabled();
// Act — change only the name and save.
const nameInput = screen.getByTestId("edit-automation-name");
@@ -267,6 +283,153 @@ describe("EditAutomationModal", () => {
expect(body).toMatchObject({ name: "Renamed" });
});
+ it("sends the edited cron expression for a custom schedule", async () => {
+ // Arrange
+ vi.mocked(AutomationService.updateAutomation).mockResolvedValue(
+ customAutomation,
+ );
+ const user = userEvent.setup();
+ renderModal(customAutomation);
+
+ // The field starts pre-filled with the automation's own expression.
+ const cronInput = screen.getByTestId("edit-automation-cron");
+ expect(cronInput).toHaveValue("0 9,17 * * *");
+
+ // Act
+ await user.clear(cronInput);
+ await user.type(cronInput, "*/5 * * * *");
+ await user.click(screen.getByTestId("edit-automation-save"));
+
+ // Assert
+ await waitFor(() => {
+ expect(AutomationService.updateAutomation).toHaveBeenCalledTimes(1);
+ });
+ const [, body] = vi.mocked(AutomationService.updateAutomation).mock
+ .calls[0];
+ expect(body).toMatchObject({
+ trigger: { type: "cron", schedule: "*/5 * * * *" },
+ });
+ });
+
+ it("blocks an invalid cron expression instead of sending it", async () => {
+ // Arrange
+ const user = userEvent.setup();
+ renderModal(customAutomation);
+
+ // Act — 60 is out of range for the minute field.
+ const cronInput = screen.getByTestId("edit-automation-cron");
+ await user.clear(cronInput);
+ await user.type(cronInput, "60 * * * *");
+ await user.click(screen.getByTestId("edit-automation-save"));
+
+ // Assert — the error surfaces and nothing reaches the API.
+ expect(
+ await screen.findByText("AUTOMATIONS$ERROR_CRON_INVALID"),
+ ).toBeInTheDocument();
+ expect(AutomationService.updateAutomation).not.toHaveBeenCalled();
+ });
+
+ it("saves an unrelated edit without revalidating an untouched schedule", async () => {
+ // Arrange — the stored expression is one this form would reject.
+ vi.mocked(AutomationService.updateAutomation).mockResolvedValue(
+ rejectedScheduleAutomation,
+ );
+ const user = userEvent.setup();
+ renderModal(rejectedScheduleAutomation);
+
+ // Act — change only the name.
+ const nameInput = screen.getByTestId("edit-automation-name");
+ await user.clear(nameInput);
+ await user.type(nameInput, "Renamed");
+ await user.click(screen.getByTestId("edit-automation-save"));
+
+ // Assert
+ await waitFor(() => {
+ expect(AutomationService.updateAutomation).toHaveBeenCalledTimes(1);
+ });
+ const [, body] = vi.mocked(AutomationService.updateAutomation).mock
+ .calls[0];
+ expect(body).not.toHaveProperty("trigger");
+ expect(body).toMatchObject({ name: "Renamed" });
+ expect(screen.queryByText("AUTOMATIONS$ERROR_CRON_INVALID")).toBeNull();
+ });
+
+ it("sends a named-day expression the automation service accepts", async () => {
+ // Arrange — croniter takes day names.
+ vi.mocked(AutomationService.updateAutomation).mockResolvedValue(
+ customAutomation,
+ );
+ const user = userEvent.setup();
+ renderModal(customAutomation);
+
+ // Act
+ const cronInput = screen.getByTestId("edit-automation-cron");
+ await user.clear(cronInput);
+ await user.type(cronInput, "0 0 * * SUN");
+ await user.click(screen.getByTestId("edit-automation-save"));
+
+ // Assert
+ await waitFor(() => {
+ expect(AutomationService.updateAutomation).toHaveBeenCalledTimes(1);
+ });
+ const [, body] = vi.mocked(AutomationService.updateAutomation).mock
+ .calls[0];
+ expect(body).toMatchObject({
+ trigger: { type: "cron", schedule: "0 0 * * SUN" },
+ });
+ });
+
+ it("blocks a schedule that can never fire instead of sending it", async () => {
+ // Arrange
+ const user = userEvent.setup();
+ renderModal(customAutomation);
+
+ // Act — February never has a 31st.
+ const cronInput = screen.getByTestId("edit-automation-cron");
+ await user.clear(cronInput);
+ await user.type(cronInput, "0 0 31 2 *");
+ await user.click(screen.getByTestId("edit-automation-save"));
+
+ // Assert
+ expect(
+ await screen.findByText("AUTOMATIONS$ERROR_CRON_UNREACHABLE"),
+ ).toBeInTheDocument();
+ expect(AutomationService.updateAutomation).not.toHaveBeenCalled();
+ });
+
+ it("disables the time input while the cron field owns the schedule", () => {
+ // Arrange / Act
+ renderModal(customAutomation);
+
+ // Assert — the field no longer accepts input that save would discard.
+ expect(screen.getByTestId("edit-automation-time")).toBeDisabled();
+ expect(screen.getByTestId("edit-automation-cron")).toBeEnabled();
+ });
+
+ it("saves an event-triggered automation without a cron trigger", async () => {
+ // Arrange — these have no schedule, so cron validation must not run.
+ vi.mocked(AutomationService.updateAutomation).mockResolvedValue(
+ eventAutomation,
+ );
+ const user = userEvent.setup();
+ renderModal(eventAutomation);
+
+ // Act
+ const nameInput = screen.getByTestId("edit-automation-name");
+ await user.clear(nameInput);
+ await user.type(nameInput, "Renamed");
+ await user.click(screen.getByTestId("edit-automation-save"));
+
+ // Assert
+ await waitFor(() => {
+ expect(AutomationService.updateAutomation).toHaveBeenCalledTimes(1);
+ });
+ const [, body] = vi.mocked(AutomationService.updateAutomation).mock
+ .calls[0];
+ expect(body).not.toHaveProperty("trigger");
+ expect(body).toMatchObject({ name: "Renamed" });
+ });
+
it("surfaces an error toast and keeps the modal open when the update fails", async () => {
// Arrange — backend rejects the PATCH.
vi.mocked(AutomationService.updateAutomation).mockRejectedValue(
diff --git a/__tests__/utils/automation-schedule.test.ts b/__tests__/utils/automation-schedule.test.ts
index c9e758fc56..3b8bcc22dc 100644
--- a/__tests__/utils/automation-schedule.test.ts
+++ b/__tests__/utils/automation-schedule.test.ts
@@ -1,6 +1,8 @@
import { describe, it, expect } from "vitest";
+import { I18nKey } from "#/i18n/declaration";
import {
buildCronSchedule,
+ validateCronSchedule,
parseCronSchedule,
parseTimeOfDay,
} from "#/utils/automation-schedule";
@@ -68,6 +70,89 @@ describe("automation-schedule", () => {
});
});
+ describe("validateCronSchedule", () => {
+ it("accepts, and trims, expressions the preset parser reports as custom", () => {
+ // Arrange — none of these map onto Daily/Weekdays/Weekly, so the
+ // edit modal relies on this check rather than parseCronSchedule.
+ const valid = ["*/10 * * * *", "0 9,17 * * *", "0 0 1-15 * 1-5"];
+
+ // Assert
+ expect(valid.map((c) => validateCronSchedule(c))).toEqual(
+ valid.map((schedule) => ({ schedule })),
+ );
+ expect(valid.every((c) => parseCronSchedule(c).kind === "custom")).toBe(
+ true,
+ );
+ expect(validateCronSchedule(" */10 * * * * ")).toEqual({
+ schedule: "*/10 * * * *",
+ });
+ });
+
+ it("accepts the expressions the automation service accepts", () => {
+ // Arrange — verified against croniter 6.2.2.
+ const serviceAccepts = [
+ "0 0 * * 7",
+ "0 0 * * SUN",
+ "0 0 * JAN *",
+ "0 0 * * MON-FRI",
+ "0 0 L * *",
+ "0 0 15W * *",
+ "0 0 * * 5#3",
+ "0 0 ? * MON",
+ "5-1 * * * *", // a reversed range wraps
+ "*/90 * * * *", // the step is unbounded
+ "* * * * * *", // seconds
+ "* * * * * * *", // seconds and year
+ "@daily",
+ "0 0 29 2 *", // leap years only, but it does fire
+ "0 0 31 1,2 *", // January has a 31st
+ ];
+
+ // Assert
+ expect(serviceAccepts.map((c) => validateCronSchedule(c))).toEqual(
+ serviceAccepts.map((schedule) => ({ schedule })),
+ );
+ });
+
+ it("rejects wrong field counts, out-of-range values and free text", () => {
+ // Arrange
+ const invalid = [
+ "* * * *",
+ "* * * * * * * *",
+ "60 * * * *",
+ "* * * * 9",
+ "every ten minutes please now",
+ "@bogus",
+ "",
+ ];
+
+ // Assert — one shared key, so the form shows the same guidance.
+ expect(invalid.map((c) => validateCronSchedule(c))).toEqual(
+ invalid.map(() => ({
+ errorKey: I18nKey.AUTOMATIONS$ERROR_CRON_INVALID,
+ })),
+ );
+ });
+
+ it("rejects a well-formed schedule that can never fire", () => {
+ // Arrange — croniter parses these, then finds no fire time.
+ const unreachable = [
+ "0 0 31 2 *",
+ "0 0 30 2 *",
+ "0 0 31 4 *",
+ "0 0 31 2,4 *",
+ "0 0 31 2 MON",
+ ];
+
+ // Assert — well-formed, not malformed, so a distinct key.
+ expect(unreachable.map((c) => validateCronSchedule(c))).toEqual(
+ unreachable.map(() => ({
+ errorKey: I18nKey.AUTOMATIONS$ERROR_CRON_UNREACHABLE,
+ })),
+ );
+ });
+ });
+
describe("parseTimeOfDay", () => {
it("parses HH:MM and rejects out-of-range or malformed values", () => {
// Act
diff --git a/src/components/features/automations/detail/edit-automation-modal.tsx b/src/components/features/automations/detail/edit-automation-modal.tsx
index db3e2bef62..f6f487796a 100644
--- a/src/components/features/automations/detail/edit-automation-modal.tsx
+++ b/src/components/features/automations/detail/edit-automation-modal.tsx
@@ -19,6 +19,8 @@ import {
formatTimeOfDay,
parseTimeOfDay,
formatEventOn,
+ validateCronSchedule,
+ CRON_EXPRESSION_EXAMPLE,
type SchedulePresetKind,
} from "#/utils/automation-schedule";
import {
@@ -152,12 +154,14 @@ export function EditAutomationModal({
const [form, setForm] = useState<FormState>(initial);
const [nameError, setNameError] = useState<string | null>(null);
const [timeoutError, setTimeoutError] = useState<string | null>(null);
+ const [scheduleError, setScheduleError] = useState<string | null>(null);
useEffect(() => {
if (isOpen) {
setForm(initial);
setNameError(null);
setTimeoutError(null);
+ setScheduleError(null);
}
}, [isOpen, initial]);
@@ -191,11 +195,6 @@ export function EditAutomationModal({
label: t(key),
}));
- const isTimeEditable =
- !form.isCustomSchedule ||
- parseTimeOfDay(form.timeOfDay) !== null ||
- form.timeOfDay === "";
-
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
@@ -235,7 +234,22 @@ export function EditAutomationModal({
body.timeout = timeoutResult.value;
}
- if (!form.isCustomSchedule && form.frequency !== "custom") {
+ if (automation.trigger.type !== "event" && form.isCustomSchedule) {
+ // An untouched schedule is the service's business, not the form's.
+ const trimmedSchedule = form.rawSchedule.trim();
+ if (trimmedSchedule !== (automation.trigger.schedule ?? "").trim()) {
+ const scheduleResult = validateCronSchedule(form.rawSchedule);
+ if ("errorKey" in scheduleResult) {
+ setScheduleError(t(scheduleResult.errorKey));
+ return;
+ }
+ body.trigger = {
+ ...automation.trigger,
+ schedule: scheduleResult.schedule,
+ };
+ }
+ setScheduleError(null);
+ } else if (!form.isCustomSchedule && form.frequency !== "custom") {
const parsedTime = parseTimeOfDay(form.timeOfDay);
if (parsedTime) {
const newSchedule = buildCronSchedule({
@@ -464,7 +478,7 @@ export function EditAutomationModal({
onChange={(e) =>
setForm((f) => ({ ...f, timeOfDay: e.target.value }))
}
- disabled={form.isCustomSchedule && !isTimeEditable}
+ disabled={form.isCustomSchedule}
className={cn(
formControlSettingsFieldClassName,
"disabled:bg-[var(--oh-surface-raised)]",
@@ -478,20 +492,18 @@ export function EditAutomationModal({
</label>
{form.isCustomSchedule && (
- <p
- className="text-xs text-muted"
- data-testid="custom-schedule-hint"
- >
- {t(I18nKey.AUTOMATIONS$CUSTOM_SCHEDULE_HINT)}
- {form.rawSchedule && (
- <>
- {" "}
- <code className="text-xs text-content">
- {form.rawSchedule}
- </code>
- </>
- )}
- </p>
+ <SettingsInput
+ testId="edit-automation-cron"
+ name="cron"
+ type="text"
+ label={t(I18nKey.AUTOMATIONS$CRON_EXPRESSION)}
+ value={form.rawSchedule}
+ onChange={(value) =>
+ setForm((f) => ({ ...f, rawSchedule: value }))
+ }
+ error={scheduleError ?? undefined}
+ placeholder={CRON_EXPRESSION_EXAMPLE}
+ />
)}
</>
) : null}
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index d1676d504c..09776b08a9 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -13565,22 +13565,56 @@
"uk": "Таймаут не може перевищувати {{max}} секунд",
"ca": "El temps d'espera no pot superar els {{max}} segons"
},
- "AUTOMATIONS$CUSTOM_SCHEDULE_HINT": {
- "en": "This automation uses a custom schedule. Frequency editing is disabled to avoid breaking it.",
- "ja": "このオートメーションはカスタムスケジュールを使用しています。誤って壊さないよう、頻度の編集は無効化されています。",
- "zh-CN": "此自动化使用自定义计划。已禁用频率编辑以避免破坏它。",
- "zh-TW": "此自動化使用自訂排程。已停用頻率編輯以避免破壞它。",
- "ko-KR": "이 자동화는 사용자 지정 일정을 사용합니다. 손상을 피하기 위해 빈도 편집이 비활성화되어 있습니다.",
- "no": "Denne automatiseringen bruker en tilpasset plan. Frekvensredigering er deaktivert for å unngå å ødelegge den.",
- "it": "Questa automazione utilizza una pianificazione personalizzata. La modifica della frequenza è disabilitata per evitare di romperla.",
- "pt": "Esta automação usa um cronograma personalizado. A edição da frequência está desativada para evitar quebrá-la.",
- "es": "Esta automatización usa un cronograma personalizado. La edición de frecuencia está desactivada para evitar romperla.",
- "ar": "تستخدم هذه الأتمتة جدولاً مخصصًا. تم تعطيل تعديل التكرار لتجنب كسرها.",
- "fr": "Cette automatisation utilise un calendrier personnalisé. L'édition de la fréquence est désactivée pour éviter de la casser.",
- "tr": "Bu otomasyon özel bir zamanlama kullanır. Bozmamak için sıklık düzenlemesi devre dışı bırakılmıştır.",
- "de": "Diese Automatisierung verwendet einen benutzerdefinierten Zeitplan. Die Häufigkeitsbearbeitung ist deaktiviert, um sie nicht zu beschädigen.",
- "uk": "Ця автоматизація використовує власний розклад. Редагування частоти вимкнено, щоб не пошкодити її.",
- "ca": "Aquesta automatització utilitza un calendari personalitzat. L'edició de la freqüència està desactivada per evitar trencar-la."
+ "AUTOMATIONS$CRON_EXPRESSION": {
+ "en": "Cron expression",
+ "ja": "Cron 式",
+ "zh-CN": "Cron 表达式",
+ "zh-TW": "Cron 運算式",
+ "ko-KR": "Cron 표현식",
+ "no": "Cron-uttrykk",
+ "it": "Espressione cron",
+ "pt": "Expressão cron",
+ "es": "Expresión cron",
+ "ar": "تعبير Cron",
+ "fr": "Expression cron",
+ "tr": "Cron ifadesi",
+ "de": "Cron-Ausdruck",
+ "uk": "Вираз cron",
+ "ca": "Expressió cron"
+ },
+ "AUTOMATIONS$ERROR_CRON_INVALID": {
+ "en": "Enter a valid cron expression",
+ "ja": "有効な cron 式を入力してください",
+ "zh-CN": "请输入有效的 cron 表达式",
+ "zh-TW": "請輸入有效的 cron 運算式",
+ "ko-KR": "유효한 cron 표현식을 입력하세요",
+ "no": "Skriv inn et gyldig cron-uttrykk",
+ "it": "Inserisci un'espressione cron valida",
+ "pt": "Introduza uma expressão cron válida",
+ "es": "Introduce una expresión cron válida",
+ "ar": "أدخل تعبير Cron صالحًا",
+ "fr": "Saisissez une expression cron valide",
+ "tr": "Geçerli bir cron ifadesi girin",
+ "de": "Geben Sie einen gültigen Cron-Ausdruck ein",
+ "uk": "Введіть коректний вираз cron",
+ "ca": "Introduïu una expressió cron vàlida"
+ },
+ "AUTOMATIONS$ERROR_CRON_UNREACHABLE": {
+ "en": "This cron expression will never run",
+ "ja": "この cron 式は実行されることがありません",
+ "zh-CN": "此 cron 表达式永远不会运行",
+ "zh-TW": "此 cron 運算式永遠不會執行",
+ "ko-KR": "이 cron 표현식은 절대 실행되지 않습니다",
+ "no": "Dette cron-uttrykket vil aldri kjøre",
+ "it": "Questa espressione cron non verrà mai eseguita",
+ "pt": "Esta expressão cron nunca será executada",
+ "es": "Esta expresión cron nunca se ejecutará",
+ "ar": "لن يتم تشغيل تعبير Cron هذا مطلقًا",
+ "fr": "Cette expression cron ne s'exécutera jamais",
+ "tr": "Bu cron ifadesi hiçbir zaman çalışmaz",
+ "de": "Dieser Cron-Ausdruck wird nie ausgeführt",
+ "uk": "Цей вираз cron ніколи не виконається",
+ "ca": "Aquesta expressió cron no s'executarà mai"
},
"AUTOMATIONS$EDIT_SUCCESS": {
"en": "Automation updated",
diff --git a/src/utils/automation-schedule.ts b/src/utils/automation-schedule.ts
index 240d20211a..4e0d12e1fe 100644
--- a/src/utils/automation-schedule.ts
+++ b/src/utils/automation-schedule.ts
@@ -1,3 +1,5 @@
+import { I18nKey } from "#/i18n/declaration";
+
export type SchedulePresetKind = "daily" | "weekdays" | "weekly";
export interface PresetSchedule {
@@ -111,3 +113,150 @@ export function formatEventOn(on: string | string[] | undefined): string {
if (Array.isArray(on)) return on.join(", ");
return on;
}
+
+/** Example expression shown when the cron field is empty. */
+export const CRON_EXPRESSION_EXAMPLE = "*/10 * * * *";
+
+// The service validates with croniter, so this must accept everything croniter
+// does: five fields, optionally plus seconds and then year, or an alias.
+const CRON_ALIASES = new Set([
+ "@yearly",
+ "@annually",
+ "@monthly",
+ "@weekly",
+ "@daily",
+ "@midnight",
+ "@hourly",
+]);
+
+const CRON_MIN_FIELDS = 5;
+const CRON_MAX_FIELDS = 7;
+
+// Seconds and year are appended after these, so the positions always hold.
+const CRON_FIELD_BOUNDS: readonly (readonly [number, number])[] = [
+ [0, 59], // minute
+ [0, 23], // hour
+ [1, 31], // day of month
+ [1, 12], // month
+ [0, 7], // day of week — croniter spells Sunday 0 and 7
+];
+
+const DAY_OF_MONTH_INDEX = 2;
+const MONTH_INDEX = 3;
+
+// Indexed from 1. February is 29: the 29th does fire, in leap years.
+const MAX_DAYS_IN_MONTH = [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
+
+const MONTH_NAMES = "JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC";
+const DAY_NAMES = "SUN|MON|TUE|WED|THU|FRI|SAT";
+
+// croniter does not bound the step: `*/90` is accepted.
+const NUMERIC_TERM = /^(\*|\d+(?:-\d+)?)(?:\/(\d+))?$/;
+
+/** Vocabulary beyond plain numbers, matched but not expanded. */
+const EXTRA_TERM_PATTERNS: readonly (RegExp | null)[] = [
+ null, // minute
+ null, // hour
+ /^(?:\?|L|\d+W)$/i, // `?`, `L`, `15W`
+ new RegExp(`^(?:${MONTH_NAMES})(?:-(?:${MONTH_NAMES}))?(?:/\\d+)?$`, "i"),
+ // `SUN`, `MON-FRI#2`, `5#3`, `?` — but no `L`, which croniter rejects here.
+ new RegExp(
+ `^(?:(?:${DAY_NAMES}|\\d+)(?:-(?:${DAY_NAMES}|\\d+))?(?:/\\d+)?(?:#\\d+)?|\\?)$`,
+ "i",
+ ),
+];
+
+type CronFieldParse =
+ | { kind: "invalid" }
+ /** Well-formed, but not expanded, so it constrains nothing. */
+ | { kind: "unmodelled" }
+ | { kind: "values"; values: number[] };
+
+function parseCronField(
+ field: string,
+ [min, max]: readonly [number, number],
+ extraPattern: RegExp | null,
+): CronFieldParse {
+ const values = new Set<number>();
+
+ for (const term of field.split(",")) {
+ const match = term.match(NUMERIC_TERM);
+ if (!match) {
+ if (extraPattern?.test(term)) return { kind: "unmodelled" };
+ return { kind: "invalid" };
+ }
+
+ const [, rangePart, stepPart] = match;
+ const step = stepPart === undefined ? 1 : Number(stepPart);
+ if (step < 1) return { kind: "invalid" };
+
+ if (rangePart === "*") {
+ for (let value = min; value <= max; value += step) values.add(value);
+ continue;
+ }
+
+ const [startPart, endPart] = rangePart.split("-");
+ const start = parseSingleInt(startPart, min, max);
+ if (start === null) return { kind: "invalid" };
+ if (endPart === undefined) {
+ values.add(start);
+ continue;
+ }
+ const end = parseSingleInt(endPart, min, max);
+ if (end === null) return { kind: "invalid" };
+ // croniter wraps a reversed range like `5-1`; that wrap is not modelled.
+ if (end < start) return { kind: "unmodelled" };
+ for (let value = start; value <= end; value += step) values.add(value);
+ }
+
+ return { kind: "values", values: [...values] };
+}
+
+export type CronScheduleValidation =
+ | { schedule: string }
+ | { errorKey: I18nKey };
+
+/**
+ * Validate a raw cron expression from the edit form — `parseCronSchedule` only
+ * classifies against the presets, reporting arbitrary text as `custom`.
+ *
+ * One-sided by design: rejects only what croniter certainly rejects, and defers
+ * on anything it does not model.
+ */
+export function validateCronSchedule(raw: string): CronScheduleValidation {
+ const schedule = raw.trim();
+ if (!schedule) return { errorKey: I18nKey.AUTOMATIONS$ERROR_CRON_INVALID };
+
+ if (schedule.startsWith("@")) {
+ return CRON_ALIASES.has(schedule.toLowerCase())
+ ? { schedule }
+ : { errorKey: I18nKey.AUTOMATIONS$ERROR_CRON_INVALID };
+ }
+
+ const fields = schedule.split(/\s+/);
+ if (fields.length < CRON_MIN_FIELDS || fields.length > CRON_MAX_FIELDS) {
+ return { errorKey: I18nKey.AUTOMATIONS$ERROR_CRON_INVALID };
+ }
+
+ const parsed = CRON_FIELD_BOUNDS.map((bounds, index) =>
+ parseCronField(fields[index], bounds, EXTRA_TERM_PATTERNS[index]),
+ );
+ if (parsed.some((field) => field.kind === "invalid")) {
+ return { errorKey: I18nKey.AUTOMATIONS$ERROR_CRON_INVALID };
+ }
+
+ // croniter parses `0 0 31 2 *` and then finds no fire time for it.
+ const days = parsed[DAY_OF_MONTH_INDEX];
+ const months = parsed[MONTH_INDEX];
+ if (
+ days.kind === "values" &&
+ months.kind === "values" &&
+ !months.values.some((month) =>
+ days.values.some((day) => day <= MAX_DAYS_IN_MONTH[month]),
+ )
+ ) {
+ return { errorKey: I18nKey.AUTOMATIONS$ERROR_CRON_UNREACHABLE };
+ }
+
+ return { schedule };
+}