Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(autopilots): redesign the autopilot schedule editor (#5457)
YYClaw465546b83baa
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 31ea83b329..23cc386dcf 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -112,6 +112,7 @@ import type {CreateAutopilotTriggerRequest,UpdateAutopilotTriggerRequest,ListAutopilotsResponse,+ CronPreviewResponse,GetAutopilotResponse,AutopilotCollaboratorsResponse,ListAutopilotRunsResponse,@@ -202,6 +203,8 @@ import {EMPTY_LIST_AUTOPILOTS_RESPONSE,AutopilotRunSchema,FALLBACK_AUTOPILOT_RUN,+ CronPreviewResponseSchema,+ UNREADABLE_CRON_PREVIEW_RESPONSE,ListIssuesResponseSchema,CreateIssueResponseSchema,ListWebhookDeliveriesResponseSchema,@@ -2524,6 +2527,19 @@ export class ApiClient {await this.fetch(`/api/autopilots/${autopilotId}/triggers/${triggerId}`, { method: "DELETE" });}+ async cronPreview(params: { expr: string; tz: string }): Promise<CronPreviewResponse> {+ const search = new URLSearchParams();+ search.set("expr", params.expr);+ search.set("tz", params.tz);+ const raw = await this.fetch<unknown>(`/api/autopilots/cron-preview?${search}`);+ return parseWithFallback(+ raw,+ CronPreviewResponseSchema,+ UNREADABLE_CRON_PREVIEW_RESPONSE,+ { endpoint: "GET /api/autopilots/cron-preview" },+ );+ }+async rotateAutopilotTriggerWebhookToken(autopilotId: string,triggerId: string,diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.tsindex 79e96a9f05..a14466a7e3 100644--- a/packages/core/api/schema.test.ts+++ b/packages/core/api/schema.test.ts@@ -485,6 +485,55 @@ describe("ApiClient schema fallback", () => {expect(resp.reused_skill_ids).toEqual([]);});});++ describe("cronPreview", () => {+ it("returns the parsed next runs", async () => {+ stubFetchJson({+ next_runs: ["2026-07-14T01:00:00Z", "2026-07-14T03:00:00Z"],+ });+ const client = new ApiClient("https://api.example.test");+ const res = await client.cronPreview({+ expr: "0 9-21/2 * * *",+ tz: "Asia/Shanghai",+ });+ expect(res).toEqual({+ next_runs: ["2026-07-14T01:00:00Z", "2026-07-14T03:00:00Z"],+ });+ });++ it("URL-encodes the expression and timezone", async () => {+ stubFetchJson({ next_runs: [] });+ const client = new ApiClient("https://api.example.test");+ await client.cronPreview({ expr: "0 9-21/2 * * 2-4", tz: "Asia/Shanghai" });+ const url = String(vi.mocked(fetch).mock.calls[0]?.[0]);+ expect(url).toContain("/api/autopilots/cron-preview?");+ expect(url).toContain("expr=0+9-21%2F2+*+*+2-4");+ expect(url).toContain("tz=Asia%2FShanghai");+ });++ it("returns an empty list verbatim when the expression never fires", async () => {+ stubFetchJson({ next_runs: [] });+ const client = new ApiClient("https://api.example.test");+ const res = await client.cronPreview({ expr: "0 0 30 2 *", tz: "UTC" });+ expect(res).toEqual({ next_runs: [] });+ });++ it("falls back to null when the response is malformed", async () => {+ // null, not [] — the caller must be able to tell "unreadable response"+ // apart from "this expression never fires".+ stubFetchJson({ next_runs: "not-an-array" });+ const client = new ApiClient("https://api.example.test");+ const res = await client.cronPreview({ expr: "0 9 * * *", tz: "UTC" });+ expect(res).toEqual({ next_runs: null });+ });++ it("falls back to null when the field is missing entirely", async () => {+ stubFetchJson({ runs: ["2026-07-14T01:00:00Z"] });+ const client = new ApiClient("https://api.example.test");+ const res = await client.cronPreview({ expr: "0 9 * * *", tz: "UTC" });+ expect(res).toEqual({ next_runs: null });+ });+ });});// Direct tests for the helper, decoupled from any specific endpoint —diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex f190c7c48d..2b60a35542 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -17,6 +17,7 @@ import type {CreateAgentFromTemplateResponse,CreateBillingCheckoutSessionResponse,CreateBillingPortalSessionResponse,+ CronPreviewResponse,GroupedIssuesResponse,InboxItem,InboxWorkspaceUnread,@@ -1230,6 +1231,18 @@ export const FALLBACK_AUTOPILOT_RUN: AutopilotRun = {created_at: "",};+// Cron preview: the server is the authority on the next occurrences. No+// `.default([])` here — a missing or reshaped field must fail validation so it+// degrades to the `next_runs: null` fallback ("preview unreadable") instead of+// masquerading as a valid empty list ("this expression never fires").+export const CronPreviewResponseSchema = z.object({+ next_runs: z.array(z.string()),+}).loose();++export const UNREADABLE_CRON_PREVIEW_RESPONSE: CronPreviewResponse = {+ next_runs: null,+};+export const EMPTY_WEBHOOK_DELIVERY: WebhookDelivery = {id: "",workspace_id: "",diff --git a/packages/core/autopilots/index.ts b/packages/core/autopilots/index.tsindex 5be9f1a3ce..a48259a41c 100644--- a/packages/core/autopilots/index.ts+++ b/packages/core/autopilots/index.ts@@ -5,6 +5,7 @@ export {autopilotRunsOptions,autopilotDeliveriesOptions,autopilotDeliveryOptions,+ cronPreviewOptions,} from "./queries";export {useCreateAutopilot,diff --git a/packages/core/autopilots/queries.ts b/packages/core/autopilots/queries.tsindex 65ead3cff6..c3fb139dd4 100644--- a/packages/core/autopilots/queries.ts+++ b/packages/core/autopilots/queries.ts@@ -14,6 +14,8 @@ export const autopilotKeys = {[...autopilotKeys.all(wsId), "deliveries", id] as const,delivery: (wsId: string, autopilotId: string, deliveryId: string) =>[...autopilotKeys.all(wsId), "deliveries", autopilotId, deliveryId] as const,+ cronPreview: (wsId: string, expr: string, tz: string) =>+ [...autopilotKeys.all(wsId), "cron-preview", expr, tz] as const,};export function autopilotListOptions(wsId: string) {@@ -87,3 +89,22 @@ export function autopilotDeliveryOptions(enabled: options?.enabled ?? true,});}++// cronPreviewOptions backs the schedule editor's next-run preview. The server+// owns cron/timezone evaluation, so the editor never approximates it locally.+export function cronPreviewOptions(+ wsId: string,+ expr: string,+ tz: string,+ options?: { enabled?: boolean },+) {+ return queryOptions({+ queryKey: autopilotKeys.cronPreview(wsId, expr, tz),+ queryFn: () => api.cronPreview({ expr, tz }),+ enabled: options?.enabled ?? true,+ staleTime: 30_000,+ // A 400 (invalid expression/timezone) is a stable answer for this input,+ // not a transient failure — retrying would only delay the inline error.+ retry: false,+ });+}diff --git a/packages/core/types/autopilot.ts b/packages/core/types/autopilot.tsindex 5b768e4899..e6e1fdc588 100644--- a/packages/core/types/autopilot.ts+++ b/packages/core/types/autopilot.ts@@ -184,6 +184,14 @@ export interface UpdateAutopilotTriggerRequest {event_filters?: WebhookEventFilter[] | null;}+export interface CronPreviewResponse {+ // Next occurrences as RFC3339 UTC timestamps, ascending. An empty array+ // means the expression never fires; `null` is the client-side sentinel for+ // "the response could not be read" (schema drift), which callers must not+ // present as "never fires".+ next_runs: string[] | null;+}+export interface ListAutopilotsResponse {autopilots: Autopilot[];total: number;diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex a005696b26..7516c0f714 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -165,6 +165,7 @@ export type {CreateAutopilotTriggerRequest,UpdateAutopilotTriggerRequest,ListAutopilotsResponse,+ CronPreviewResponse,GetAutopilotResponse,ListAutopilotRunsResponse,WebhookDelivery,diff --git a/packages/ui/components/ui/input-group.tsx b/packages/ui/components/ui/input-group.tsxindex 190cd7541e..8432d1b824 100644--- a/packages/ui/components/ui/input-group.tsx+++ b/packages/ui/components/ui/input-group.tsx@@ -6,7 +6,9 @@ import { cva, type VariantProps } from "class-variance-authority"import { cn } from "@multica/ui/lib/utils"import { Button } from "@multica/ui/components/ui/button"import { Input } from "@multica/ui/components/ui/input"+import { SelectTrigger } from "@multica/ui/components/ui/select"import { Textarea } from "@multica/ui/components/ui/textarea"+import { TimeInput } from "@multica/ui/components/ui/time-input"function InputGroup({ className, ...props }: React.ComponentProps<"div">) {return (@@ -54,6 +56,15 @@ function InputGroupAddon({data-slot="input-group-addon"data-align={align}className={cn(inputGroupAddonVariants({ align }), className)}+ onMouseDown={(e) => {+ if ((e.target as HTMLElement).closest("button")) {+ return+ }+ // The addon acts as part of the input, so a click on it must not move+ // focus: the blur would land before the click below could focus back,+ // and the input's blur handlers (commit, close) would already have run.+ e.preventDefault()+ }}onClick={(e) => {if ((e.target as HTMLElement).closest("button")) {return@@ -132,6 +143,50 @@ function InputGroupInput({)}+/** A Select that shares the group's box instead of bringing its own.+ *+ * The group lights its border from `[data-slot=input-group-control]:focus-visible`,+ * and a trigger that kept its own slot would leave the box dark while the select+ * it contains is the very thing focused — so the trigger takes that slot. Its+ * border, ring and background are the group's now; what it keeps is its own+ * content width, so the control ends where its longest option does. */+function InputGroupSelectTrigger({+ className,+ ...props+}: React.ComponentProps<typeof SelectTrigger>) {+ return (+ <SelectTrigger+ data-slot="input-group-control"+ className={cn(+ "h-full rounded-none border-0 bg-transparent shadow-none focus-visible:border-transparent focus-visible:ring-0 dark:bg-transparent dark:hover:bg-transparent",+ className+ )}+ {...props}+ />+ )+}++/** A TimeInput that shares the group's box instead of bringing its own.+ *+ * The slot goes on the segments rather than on the field: the group lights its+ * border from the control that has focus, and what has focus here is an hour or+ * a minute, never their wrapper. */+function InputGroupTimeInput({+ className,+ ...props+}: React.ComponentProps<typeof TimeInput>) {+ return (+ <TimeInput+ segmentSlot="input-group-control"+ className={cn(+ "h-full min-w-0 flex-1 justify-center rounded-none border-0 bg-transparent focus-within:border-transparent focus-within:ring-0 dark:bg-transparent",+ className+ )}+ {...props}+ />+ )+}+function InputGroupTextarea({className,...props@@ -154,5 +209,7 @@ export {InputGroupButton,InputGroupText,InputGroupInput,+ InputGroupSelectTrigger,InputGroupTextarea,+ InputGroupTimeInput,}diff --git a/packages/ui/components/ui/time-input.tsx b/packages/ui/components/ui/time-input.tsxindex 411afabf37..b0fccf0178 100644--- a/packages/ui/components/ui/time-input.tsx+++ b/packages/ui/components/ui/time-input.tsx@@ -8,14 +8,16 @@ import { cn } from "@multica/ui/lib/utils";// Adapted from openstatusHQ/time-picker (MIT).// Segmented HH:MM input with keyboard arrow increment / digit typing.-type Segment = "hours" | "minutes";+function pad2(n: number): string {+ return n.toString().padStart(2, "0");+}function getValidNumber(raw: string,{ max, min = 0, loop = false }: { max: number; min?: number; loop?: boolean },): string {let n = parseInt(raw, 10);- if (isNaN(n)) return "00";+ if (isNaN(n)) return pad2(min);if (!loop) {if (n > max) n = max;if (n < min) n = min;@@ -23,109 +25,130 @@ function getValidNumber(if (n > max) n = min;if (n < min) n = max;}- return n.toString().padStart(2, "0");+ return pad2(n);}-function arrowValue(current: string, step: number, seg: Segment): string {- const max = seg === "hours" ? 23 : 59;+function arrowValue(current: string, step: number, min: number, max: number): string {const n = parseInt(current, 10);- if (isNaN(n)) return "00";- return getValidNumber(String(n + step), { max, min: 0, loop: true });+ if (isNaN(n)) return pad2(min);+ return getValidNumber(String(n + step), { max, min, loop: true });}-function splitTime(value: string): { hh: string; mm: string } {+function splitTime(value: string, hourMin: number): { hh: string; mm: string } {const [rawH, rawM] = (value || "").split(":");- const hh = getValidNumber(rawH ?? "0", { max: 23 });+ const hh = getValidNumber(rawH ?? "0", { max: 23, min: hourMin });const mm = getValidNumber(rawM ?? "0", { max: 59 });return { hh, mm };}interface SegmentInputProps {- seg: Segment;value: string;+ /** The segment's own range. Arrow keys wrap inside it, and typed digits are+ * clamped to it, so a segment whose range is narrowed by its neighbour — a+ * window's end hour, which can never precede its start — can neither be+ * arrowed nor typed out of bounds. */+ min: number;+ max: number;+ /** What Backspace clears the segment to. Defaults to `min` — the neutral value+ * for a segment whose range starts at the field's own floor. A window's end+ * hour is not such a segment: its `min` is wherever the start currently sits,+ * so clearing it to `min` would collapse the window onto the start instead of+ * opening it to the end of the day. */+ clearTo?: number;onValueChange: (next: string) => void;onLeftFocus?: () => void;onRightFocus?: () => void;disabled?: boolean;ariaLabel: string;+ /** `data-slot` for the segment itself. The segments are what a container's+ * focus styling has to see: they, not the wrapper, are what gets focused. */+ slot?: string;+ autoFocus?: boolean;}-const SegmentInput = React.forwardRef<HTMLInputElement, SegmentInputProps>(- function SegmentInput(- { seg, value, onValueChange, onLeftFocus, onRightFocus, disabled, ariaLabel },- ref,- ) {- // Two-digit typing window: first digit pads with leading 0; second digit within- // 2s replaces the leading 0, clamped to segment max. After 2s, reset.- const [pendingSecond, setPendingSecond] = React.useState(false);-- React.useEffect(() => {- if (!pendingSecond) return;- const t = setTimeout(() => setPendingSecond(false), 2000);- return () => clearTimeout(t);- }, [pendingSecond]);-- const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {- if (e.key === "Tab") return;- if (e.key === "ArrowRight") {- e.preventDefault();+const SegmentInput = React.forwardRef<HTMLInputElement, SegmentInputProps>(function SegmentInput(+ { value, min, max, clearTo, onValueChange, onLeftFocus, onRightFocus, disabled, ariaLabel, slot, autoFocus },+ ref,+) {+ // Two-digit typing window: the first digit pads with a leading 0; a second+ // digit within 2s completes the pair. The first digit is remembered here+ // rather than read back from `value`, so an owner that clamps the value+ // between the two keystrokes cannot corrupt the number being typed.+ const [pendingFirst, setPendingFirst] = React.useState<string | null>(null);++ React.useEffect(() => {+ if (pendingFirst === null) return;+ const t = setTimeout(() => setPendingFirst(null), 2000);+ return () => clearTimeout(t);+ }, [pendingFirst]);++ const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {+ if (e.key === "Tab") return;+ if (e.key === "ArrowRight") {+ e.preventDefault();+ onRightFocus?.();+ return;+ }+ if (e.key === "ArrowLeft") {+ e.preventDefault();+ onLeftFocus?.();+ return;+ }+ if (e.key === "ArrowUp" || e.key === "ArrowDown") {+ e.preventDefault();+ const step = e.key === "ArrowUp" ? 1 : -1;+ onValueChange(arrowValue(value, step, min, max));+ setPendingFirst(null);+ return;+ }+ if (e.key >= "0" && e.key <= "9") {+ e.preventDefault();+ if (pendingFirst !== null) {+ onValueChange(getValidNumber(pendingFirst + e.key, { max, min }));+ setPendingFirst(null);onRightFocus?.();- return;- }- if (e.key === "ArrowLeft") {- e.preventDefault();- onLeftFocus?.();- return;- }- if (e.key === "ArrowUp" || e.key === "ArrowDown") {- e.preventDefault();- const step = e.key === "ArrowUp" ? 1 : -1;- onValueChange(arrowValue(value, step, seg));- setPendingSecond(false);- return;- }- if (e.key >= "0" && e.key <= "9") {- e.preventDefault();- const next = pendingSecond- ? getValidNumber(value.slice(1) + e.key, {- max: seg === "hours" ? 23 : 59,- })- : "0" + e.key;- onValueChange(next);- if (pendingSecond) {- setPendingSecond(false);- onRightFocus?.();- } else {- setPendingSecond(true);- }- return;- }- if (e.key === "Backspace" || e.key === "Delete") {- e.preventDefault();- onValueChange("00");- setPendingSecond(false);+ } else {+ // The first digit is clamped for display but remembered raw: in a+ // segment starting at 09, a typed "1" must still show something legal+ // while staying the tens digit of the 15 the user is halfway through.+ onValueChange(getValidNumber("0" + e.key, { max, min }));+ setPendingFirst(e.key);}- };-- return (- <input- ref={ref}- type="text"- inputMode="numeric"- maxLength={2}- value={value}- disabled={disabled}- aria-label={ariaLabel}- onChange={() => {- // Fully controlled by keydown; ignore native onChange.- }}- onKeyDown={handleKeyDown}- onFocus={(e) => e.currentTarget.select()}- className="w-7 bg-transparent text-center text-sm tabular-nums outline-none caret-transparent focus:text-foreground"- />- );- },-);+ return;+ }+ if (e.key === "Backspace" || e.key === "Delete") {+ e.preventDefault();+ onValueChange(pad2(clearTo ?? min));+ setPendingFirst(null);+ }+ };++ return (+ <input+ ref={ref}+ data-slot={slot}+ // Caller-gated: only set when the user just switched into this control,+ // never on first mount (see TimeInput's autoFocus doc).+ autoFocus={autoFocus}+ type="text"+ inputMode="numeric"+ maxLength={2}+ value={value}+ disabled={disabled}+ aria-label={ariaLabel}+ onChange={() => {+ // Fully controlled by keydown; ignore native onChange.+ }}+ onKeyDown={handleKeyDown}+ onFocus={(e) => e.currentTarget.select()}+ // The two-digit window belongs to one visit to this segment. Left open, a+ // "1" typed here and a "5" typed after a detour through another control+ // would pair up into 15.+ onBlur={() => setPendingFirst(null)}+ className="w-7 bg-transparent text-center text-sm tabular-nums outline-none caret-transparent focus:text-foreground disabled:opacity-50"+ />+ );+});export interface TimeInputProps {value: string;@@ -133,8 +156,27 @@ export interface TimeInputProps {disabled?: boolean;className?: string;showIcon?: boolean;- /** Render only the minute segment with an "At :" prefix. Used for hourly schedules. */- minuteOnly?: boolean;+ /** Render only the hour segment. Used where the minute has no meaning, such as+ * the bounds of an hour-granular window. */+ hourOnly?: boolean;+ /** Earliest hour this field may hold. The hour segment wraps and clamps within+ * [hourMin, 23] instead of [0, 23] — a window's end, which cannot precede its+ * start, arrows round to 23 rather than sticking at the start hour. */+ hourMin?: number;+ /** What Backspace clears the hour to, when that is not `hourMin` (see+ * SegmentInput's clearTo). */+ hourClearTo?: number;+ /** Accessible names for the two segments. This package holds no translations,+ * so callers that render several time fields side by side — a window's start+ * and end, say — pass localized names that tell them apart. */+ hourLabel?: string;+ minuteLabel?: string;+ /** `data-slot` for the hour and minute segments, for a container that styles+ * itself from what is focused inside it (see InputGroupTimeInput). */+ segmentSlot?: string;+ /** Focus the hour segment on mount. Callers gate this so it only fires when the+ * user just revealed this field, never on the first render of a form. */+ autoFocus?: boolean;}export function TimeInput({@@ -143,22 +185,27 @@ export function TimeInput({disabled,className,showIcon = true,- minuteOnly = false,+ hourOnly = false,+ hourMin = 0,+ hourClearTo,+ hourLabel = "Hour",+ minuteLabel = "Minute",+ segmentSlot,+ autoFocus,}: TimeInputProps) {- const { hh, mm } = splitTime(value);+ const { hh, mm } = splitTime(value, hourMin);const hourRef = React.useRef<HTMLInputElement>(null);const minuteRef = React.useRef<HTMLInputElement>(null);const setHour = (next: string) => onChange(`${next}:${mm}`);- const setMinute = (next: string) =>- onChange(`${minuteOnly ? "00" : hh}:${next}`);+ const setMinute = (next: string) => onChange(`${hh}:${next}`);return (<divdata-slot="time-input"onClick={(e) => {if (e.target === e.currentTarget) {- (minuteOnly ? minuteRef : hourRef).current?.focus();+ hourRef.current?.focus();}}}className={cn(@@ -169,48 +216,50 @@ export function TimeInput({className,)}>- {minuteOnly ? (- <>- {showIcon && (- <Clock className="pointer-events-none size-3.5 shrink-0 text-muted-foreground" />- )}- <span className="pointer-events-none select-none text-muted-foreground">- at :- </span>- <SegmentInput- ref={minuteRef}- seg="minutes"- value={mm}- onValueChange={setMinute}- disabled={disabled}- ariaLabel="Minute"- />- </>- ) : (+ {showIcon && (+ <Clock className="pointer-events-none size-3.5 shrink-0 text-muted-foreground" />+ )}+ <SegmentInput+ ref={hourRef}+ min={hourMin}+ max={23}+ clearTo={hourClearTo}+ value={hh}+ onValueChange={setHour}+ // Nowhere to advance to when the minute is off: focusing a disabled+ // input is a no-op, and the keypress that asked for it is already+ // swallowed, so the caret would appear stuck.+ onRightFocus={hourOnly ? undefined : () => minuteRef.current?.focus()}+ disabled={disabled}+ ariaLabel={hourLabel}+ slot={segmentSlot}+ autoFocus={autoFocus}+ />+ {/* hourOnly drops the minute segment and its colon entirely, rather than+ keeping an inert one for stable geometry: where the bounds are whole+ hours, a greyed-out :00 is only wasted width. The field narrows on the+ unit switch that sets this — the honest signal that minute-granular+ bounds are gone. */}+ {!hourOnly && (<>- {showIcon && (- <Clock className="pointer-events-none size-3.5 shrink-0 text-muted-foreground" />- )}- <SegmentInput- ref={hourRef}- seg="hours"- value={hh}- onValueChange={setHour}- onRightFocus={() => minuteRef.current?.focus()}- disabled={disabled}- ariaLabel="Hour"- />- <span className="pointer-events-none select-none text-muted-foreground">+ {/* -translate-y-[1.5px]: the digits are cap-height figures whose+ optical centre sits above the colon's two dots, so `items-center` —+ which lines up the boxes, not the ink — leaves the colon reading+ low. Nudge it up to the digits' centre. Transform, not margin, so+ it shifts nothing else. */}+ <span className="pointer-events-none -translate-y-[1.5px] select-none text-muted-foreground">:</span><SegmentInputref={minuteRef}- seg="minutes"+ min={0}+ max={59}value={mm}onValueChange={setMinute}onLeftFocus={() => hourRef.current?.focus()}disabled={disabled}- ariaLabel="Minute"+ ariaLabel={minuteLabel}+ slot={segmentSlot}/></>)}diff --git a/packages/views/autopilots/components/autopilot-detail-page.tsx b/packages/views/autopilots/components/autopilot-detail-page.tsxindex ce06b12b57..cf7ba0593d 100644--- a/packages/views/autopilots/components/autopilot-detail-page.tsx+++ b/packages/views/autopilots/components/autopilot-detail-page.tsx@@ -46,12 +46,14 @@ import {AlertDialogHeader,AlertDialogTitle,} from "@multica/ui/components/ui/alert-dialog";-import {- TriggerConfigSection,- getDefaultTriggerConfig,- toCronExpression,-} from "./trigger-config";-import type { TriggerConfig } from "./trigger-config";+import { ScheduleEditor } from "./schedule-editor/schedule-editor";+import { getDefaultScheduleConfig, type ScheduleConfig } from "./schedule-editor/model";+import { browserTimezone } from "../../common/timezone-select";+import { cronFields, parseCron, toCron } from "./schedule-editor/cron-mapping";+import { useDescribeSchedule } from "./schedule-editor/describe";+import { formatInTimeZone } from "../../common/format-in-time-zone";+import { SegmentedToggle } from "../../common/segmented-toggle";+import { useScheduleSubmitGate } from "./schedule-editor/validate";import type {AutopilotExecutionMode,AutopilotRun,@@ -68,15 +70,10 @@ import { WebhookDeliveriesSection } from "./webhook-deliveries-section";import { ProjectIcon } from "../../projects/components/project-icon";import { useT } from "../../i18n";-function formatDate(date: string): string {- return new Date(date).toLocaleString(undefined, {- month: "short",- day: "numeric",- hour: "2-digit",- minute: "2-digit",- });-}-+// A run that already happened is an instant in the reader's day, so it reads in+// the reader's zone (no timeZone passed). A run that is still to come belongs to+// the schedule that will fire it — see the trigger row, which passes the+// trigger's own timezone.type RunStatus = "issue_created" | "running" | "skipped" | "completed" | "failed";const RUN_VISUAL: Record<RunStatus, { color: string; icon: typeof CheckCircle2; spin?: boolean }> = {@@ -109,7 +106,7 @@ function WebhookPayloadSlot({ autopilotId, runId }: { autopilotId: string; runId}function RunRow({ run, agentId, agentName }: { run: AutopilotRun; agentId: string; agentName: string }) {- const { t } = useT("autopilots");+ const { t, i18n } = useT("autopilots");const wsPaths = useWorkspacePaths();const status = (RUN_VISUAL[run.status as RunStatus] ? (run.status as RunStatus) : "issue_created");const visual = RUN_VISUAL[status];@@ -155,7 +152,7 @@ function RunRow({ run, agentId, agentName }: { run: AutopilotRun; agentId: strin) : null}</span><span className="w-32 shrink-0 text-right text-xs text-muted-foreground tabular-nums">- {formatDate(run.triggered_at || run.created_at)}+ {formatInTimeZone(run.triggered_at || run.created_at, undefined, i18n.language)}</span>{syntheticTask && !run.issue_id && (<TranscriptButton@@ -219,7 +216,7 @@ function SkippedRunsGroup({agentId: string;agentName: string;}) {- const { t } = useT("autopilots");+ const { t, i18n } = useT("autopilots");const [open, setOpen] = useState(false);const latestRun = runs[0];const ToggleIcon = open ? ChevronDown : ChevronRight;@@ -242,7 +239,7 @@ function SkippedRunsGroup({</span>{latestRun && (<span className="w-32 shrink-0 text-right text-xs text-muted-foreground tabular-nums">- {formatDate(latestRun.triggered_at || latestRun.created_at)}+ {formatInTimeZone(latestRun.triggered_at || latestRun.created_at, undefined, i18n.language)}</span>)}</button>@@ -258,7 +255,8 @@ function SkippedRunsGroup({}function TriggerRow({ trigger, autopilotId, canWrite }: { trigger: AutopilotTrigger; autopilotId: string; canWrite: boolean }) {- const { t } = useT("autopilots");+ const { t, i18n } = useT("autopilots");+ const describeSchedule = useDescribeSchedule();const deleteTrigger = useDeleteAutopilotTrigger();const rotateToken = useRotateAutopilotTriggerWebhookToken();const [confirmOpen, setConfirmOpen] = useState(false);@@ -323,6 +321,12 @@ function TriggerRow({ trigger, autopilotId, canWrite }: { trigger: AutopilotTrigconst Icon = isWebhook ? Webhook : isApi ? Zap : Clock;const showWebhookUrlRow = isWebhook && webhookUrl;+ // null when the expression is beyond the structured model — those rows keep+ // showing the raw cron on its own.+ const scheduleConfig = trigger.cron_expression+ ? parseCron(trigger.cron_expression, trigger.timezone ?? "UTC")+ : null;+ const scheduleDescription = scheduleConfig ? describeSchedule(scheduleConfig) : null;// Delete control extracted so a webhook trigger can render it inline// with Copy / Rotate on the URL action row (where the other action@@ -363,14 +367,31 @@ function TriggerRow({ trigger, autopilotId, canWrite }: { trigger: AutopilotTrig)}</div>{trigger.cron_expression && (- <div className="text-xs text-muted-foreground mt-0.5">- {trigger.cron_expression}- {trigger.timezone && ` (${trigger.timezone})`}+ // The plain-language line leads; the raw expression drops to a+ // secondary line so the two never run together as one blob.+ <div className="mt-0.5 space-y-0.5">+ <div className="text-xs text-muted-foreground">+ {scheduleDescription ?? trigger.cron_expression}+ {trigger.timezone && ` (${trigger.timezone})`}+ </div>+ {scheduleDescription !== null && scheduleConfig !== null && (+ // Fields only: the zone already reads out in the sentence above,+ // where a person can use it — same rule as the editor's readback.+ <div className="font-mono text-[11px] text-muted-foreground/60">+ {cronFields(scheduleConfig)}+ </div>+ )}</div>)}{trigger.next_run_at && (<div className="text-xs text-muted-foreground">- {t(($) => $.trigger_row.next_label, { date: formatDate(trigger.next_run_at) })}+ {t(($) => $.trigger_row.next_label, {+ date: formatInTimeZone(+ trigger.next_run_at,+ trigger.timezone ?? undefined,+ i18n.language,+ ),+ })}</div>)}{showWebhookUrlRow && (@@ -462,18 +483,27 @@ function AddTriggerDialog({autopilotId: string;}) {const { t } = useT("autopilots");+ const wsId = useWorkspaceId();const createTrigger = useCreateAutopilotTrigger();const [kind, setKind] = useState<"schedule" | "webhook">("schedule");- const [config, setConfig] = useState<TriggerConfig>(getDefaultTriggerConfig);+ const [config, setConfig] = useState<ScheduleConfig>(() =>+ getDefaultScheduleConfig(browserTimezone()),+ );const [label, setLabel] = useState("");const [submitting, setSubmitting] = useState(false);+ const scheduleGate = useScheduleSubmitGate(wsId);+ const canSubmit = !submitting && (kind !== "schedule" || scheduleGate.scheduleValid);const handleSubmit = async () => {- if (submitting) return;+ if (!canSubmit) return;setSubmitting(true);try {if (kind === "schedule") {- const cronExpr = toCronExpression(config);+ if (!(await scheduleGate.ensureAccepted(config))) {+ setSubmitting(false);+ return;+ }+ const cronExpr = toCron(config);if (!cronExpr.trim()) {setSubmitting(false);return;@@ -496,7 +526,7 @@ function AddTriggerDialog({}onOpenChange(false);setKind("schedule");- setConfig(getDefaultTriggerConfig());+ setConfig(getDefaultScheduleConfig(browserTimezone()));setLabel("");} catch (err) {toast.error(@@ -513,43 +543,53 @@ function AddTriggerDialog({<Dialog open={open} onOpenChange={onOpenChange}><DialogContent className="max-w-sm"><DialogTitle>{t(($) => $.add_trigger_dialog.title)}</DialogTitle>- <div className="space-y-4 pt-2">+ {/* DialogContent is a grid, so without min-w-0 this item's min-width is+ its content's — and the cron readback is one unbreakable line that+ would push the track past the dialog instead of truncating. */}+ <div className="min-w-0 space-y-4 pt-2"><div><label className="text-xs font-medium text-muted-foreground">{t(($) => $.add_trigger_dialog.type_label)}</label>- <div className="mt-1 grid grid-cols-2 gap-1 rounded-md bg-muted p-1">- <button- type="button"- onClick={() => setKind("schedule")}- className={cn(- "flex items-center justify-center gap-1.5 rounded px-3 py-1.5 text-sm transition-colors",- kind === "schedule"- ? "bg-background text-foreground shadow-sm"- : "text-muted-foreground hover:text-foreground",- )}- >- <Clock className="h-3.5 w-3.5" />- {t(($) => $.add_trigger_dialog.type_schedule)}- </button>- <button- type="button"- onClick={() => setKind("webhook")}- className={cn(- "flex items-center justify-center gap-1.5 rounded px-3 py-1.5 text-sm transition-colors",- kind === "webhook"- ? "bg-background text-foreground shadow-sm"- : "text-muted-foreground hover:text-foreground",- )}- >- <Webhook className="h-3.5 w-3.5" />- {t(($) => $.add_trigger_dialog.type_webhook)}- </button>+ <div className="mt-1">+ <SegmentedToggle+ value={kind}+ onChange={setKind}+ buttonClassName="px-3 py-1.5 text-sm"+ options={[+ [+ "schedule",+ <span key="schedule" className="flex items-center justify-center gap-1.5">+ <Clock className="h-3.5 w-3.5" />+ {t(($) => $.add_trigger_dialog.type_schedule)}+ </span>,+ ],+ [+ "webhook",+ <span key="webhook" className="flex items-center justify-center gap-1.5">+ <Webhook className="h-3.5 w-3.5" />+ {t(($) => $.add_trigger_dialog.type_webhook)}+ </span>,+ ],+ ]}+ /></div></div>{kind === "schedule" ? (- <TriggerConfigSection config={config} onChange={setConfig} />+ <ScheduleEditor+ value={config}+ onChange={(next) => {+ scheduleGate.clearRejection();+ setConfig(next);+ }}+ wsId={wsId}+ onValidityChange={scheduleGate.onValidityChange}+ // Same reason as the autopilot dialog: the submit path reads the+ // schedule, validates it over the network, then writes what it+ // read — an edit landing inside that window would be discarded.+ disabled={submitting}+ />) : (<p className="rounded-md bg-muted/50 px-3 py-2 text-xs text-muted-foreground">{t(($) => $.add_trigger_dialog.webhook_help)}@@ -569,7 +609,7 @@ function AddTriggerDialog({/></div><div className="flex justify-end pt-1">- <Button size="sm" onClick={handleSubmit} disabled={submitting}>+ <Button size="sm" onClick={handleSubmit} disabled={!canSubmit}>{submitting? t(($) => $.add_trigger_dialog.submitting): t(($) => $.add_trigger_dialog.submit)}@@ -965,11 +1005,15 @@ export function AutopilotDetailPage({ autopilotId }: { autopilotId: string }) {</div></div>- <AddTriggerDialog- open={triggerDialogOpen}- onOpenChange={setTriggerDialogOpen}- autopilotId={autopilotId}- />+ {/* Mounted only while open, like the edit dialog: otherwise a rejected+ cron leaves scheduleValid=false behind for the next open. */}+ {triggerDialogOpen && (+ <AddTriggerDialog+ open={triggerDialogOpen}+ onOpenChange={setTriggerDialogOpen}+ autopilotId={autopilotId}+ />+ )}{editDialogOpen && (<AutopilotDialogmode="edit"diff --git a/packages/views/autopilots/components/autopilot-dialog.tsx b/packages/views/autopilots/components/autopilot-dialog.tsxindex c89e5c13f9..4acb2a2563 100644--- a/packages/views/autopilots/components/autopilot-dialog.tsx+++ b/packages/views/autopilots/components/autopilot-dialog.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useMemo, useRef, useState } from "react";+import { useMemo, useRef, useState } from "react";import { useQuery } from "@tanstack/react-query";import { toast } from "sonner";import {@@ -37,15 +37,6 @@ import {PopoverDescription,} from "@multica/ui/components/ui/popover";import { Button } from "@multica/ui/components/ui/button";-import {- Select,- SelectTrigger,- SelectValue,- SelectContent,- SelectItem,-} from "@multica/ui/components/ui/select";-import { TimeInput } from "@multica/ui/components/ui/time-input";-import { TimezonePicker } from "./pickers/timezone-picker";import { useCurrentWorkspace } from "@multica/core/paths";import { useWorkspaceId } from "@multica/core/hooks";import { agentListOptions, squadListOptions } from "@multica/core/workspace/queries";@@ -66,19 +57,17 @@ import type {} from "@multica/core/types";import { TitleEditor, ContentEditor } from "../../editor";import { ActorAvatar } from "../../common/actor-avatar";+import { SegmentedToggle } from "../../common/segmented-toggle";import { ProjectPicker } from "../../projects/components/project-picker";import { ProjectIcon } from "../../projects/components/project-icon";import { AgentPicker, type AssigneeSelection } from "./pickers/agent-picker";import { SubscriberMultiSelect } from "./subscriber-multi-select";import { AutopilotAccessManager } from "./autopilot-access-manager";-import {- getDefaultTriggerConfig,- getLocalTimezone,- parseCronExpression,- toCronExpression,- type TriggerConfig,- type TriggerFrequency,-} from "./trigger-config";+import { ScheduleEditor } from "./schedule-editor/schedule-editor";+import { getDefaultScheduleConfig, type ScheduleConfig } from "./schedule-editor/model";+import { browserTimezone } from "../../common/timezone-select";+import { parseCron, toCron } from "./schedule-editor/cron-mapping";+import { useScheduleSubmitGate } from "./schedule-editor/validate";import { WebhookEventFilterSection } from "./webhook-event-filter-section";import { useT } from "../../i18n";import { formatSchedulePartialFailureToast } from "./autopilot-dialog-toast";@@ -104,7 +93,7 @@ export type AutopilotDialogProps =open: boolean;onOpenChange: (v: boolean) => void;initial?: Partial<AutopilotInitial>;- initialTriggerConfig?: Partial<TriggerConfig>;+ initialSchedule?: Pick<ScheduleConfig, "time" | "days">;}| {mode: "edit";@@ -121,45 +110,6 @@ export type AutopilotDialogProps =// Static schema-level data (not user-visible)// ----------------------------------------------------------------------------const FREQUENCY_KEYS: TriggerFrequency[] = [- "hourly",- "daily",- "weekdays",- "weekly",- "custom",-];--const DAY_KEYS = [- "sunday",- "monday",- "tuesday",- "wednesday",- "thursday",- "friday",- "saturday",-] as const;--const TIMEZONE_OPTIONS = [- "UTC",- "America/New_York",- "America/Chicago",- "America/Denver",- "America/Los_Angeles",- "America/Sao_Paulo",- "Europe/London",- "Europe/Paris",- "Europe/Berlin",- "Europe/Moscow",- "Asia/Dubai",- "Asia/Kolkata",- "Asia/Singapore",- "Asia/Shanghai",- "Asia/Tokyo",- "Asia/Seoul",- "Australia/Sydney",- "Pacific/Auckland",-];-const OUTPUT_MODE_KEYS: AutopilotExecutionMode[] = ["create_issue", "run_only"];const OUTPUT_MODE_ICONS: Record<AutopilotExecutionMode, typeof FilePlus2> = {@@ -167,83 +117,6 @@ const OUTPUT_MODE_ICONS: Record<AutopilotExecutionMode, typeof FilePlus2> = {run_only: Play,};-// ----------------------------------------------------------------------------// Next-run computation (local approximation — server stores the authoritative value)-// -----------------------------------------------------------------------------function computeNextRun(cfg: TriggerConfig, now: Date): Date | null {- const [hStr, mStr] = cfg.time.split(":");- const hour = parseInt(hStr ?? "9", 10);- const minute = parseInt(mStr ?? "0", 10);- const next = new Date(now);-- switch (cfg.frequency) {- case "hourly": {- next.setMinutes(minute, 0, 0);- if (next <= now) next.setHours(next.getHours() + 1);- return next;- }- case "daily": {- next.setHours(hour, minute, 0, 0);- if (next <= now) next.setDate(next.getDate() + 1);- return next;- }- case "weekdays": {- next.setHours(hour, minute, 0, 0);- for (let i = 0; i < 8; i++) {- const dow = next.getDay();- if (next > now && dow >= 1 && dow <= 5) return next;- next.setDate(next.getDate() + 1);- next.setHours(hour, minute, 0, 0);- }- return null;- }- case "weekly": {- if (cfg.daysOfWeek.length === 0) return null;- next.setHours(hour, minute, 0, 0);- for (let i = 0; i < 8; i++) {- if (next > now && cfg.daysOfWeek.includes(next.getDay())) return next;- next.setDate(next.getDate() + 1);- next.setHours(hour, minute, 0, 0);- }- return null;- }- case "custom":- return null;- }-}--function useFormatCountdown(): (target: Date, now: Date) => string {- const { t } = useT("autopilots");- return (target, now) => {- const diff = Math.max(0, target.getTime() - now.getTime());- const seconds = Math.floor(diff / 1000);- const days = Math.floor(seconds / 86400);- const hours = Math.floor((seconds % 86400) / 3600);- const minutes = Math.floor((seconds % 3600) / 60);- if (days > 0) return t(($) => $.trigger_config.countdown.days_hours, { days, hours });- if (hours > 0) return t(($) => $.trigger_config.countdown.hours_minutes, { hours, minutes });- if (minutes > 0) return t(($) => $.trigger_config.countdown.minutes, { minutes });- return t(($) => $.trigger_config.countdown.less_than_minute);- };-}--function formatNextRunAbsolute(date: Date, timezone: string): string {- try {- return new Intl.DateTimeFormat("en-US", {- timeZone: timezone,- weekday: "short",- month: "short",- day: "numeric",- hour: "numeric",- minute: "2-digit",- hour12: true,- }).format(date);- } catch {- return date.toLocaleString();- }-}-// ---------------------------------------------------------------------------// Webhook event-filter dirty detection// ---------------------------------------------------------------------------@@ -258,19 +131,6 @@ function serializeEventFilters(filters: WebhookEventFilter[]): string {);}-// ----------------------------------------------------------------------------// Live "now" ticker for countdown-// -----------------------------------------------------------------------------function useNowTicker(intervalMs = 30_000): Date {- const [now, setNow] = useState(() => new Date());- useEffect(() => {- const t = setInterval(() => setNow(new Date()), intervalMs);- return () => clearInterval(t);- }, [intervalMs]);- return now;-}-// ---------------------------------------------------------------------------// AutopilotDialog// ---------------------------------------------------------------------------@@ -304,18 +164,19 @@ export function AutopilotDialog(props: AutopilotDialogProps) {initial.subscriber_user_ids ?? [],);- const initialCfg: TriggerConfig = (() => {+ const initialCfg: ScheduleConfig = (() => {if (isCreate) {- const tpl = props.initialTriggerConfig;- return tpl ? { ...getDefaultTriggerConfig(), ...tpl } : getDefaultTriggerConfig();+ const tpl = props.initialSchedule;+ const fallback = getDefaultScheduleConfig(browserTimezone());+ return tpl ? { ...fallback, ...tpl } : fallback;}const first = props.triggers[0];if (first?.cron_expression) {- return parseCronExpression(first.cron_expression, first.timezone ?? "UTC");+ return parseCron(first.cron_expression, first.timezone ?? "UTC");}- return getDefaultTriggerConfig();+ return getDefaultScheduleConfig(browserTimezone());})();- const [triggerConfig, setTriggerConfig] = useState<TriggerConfig>(initialCfg);+ const [schedule, setSchedule] = useState<ScheduleConfig>(initialCfg);// Trigger kind selector. Only meaningful in create mode — edit mode does// not support converting between kinds inline (PLAN.md calls that@@ -335,12 +196,12 @@ export function AutopilotDialog(props: AutopilotDialogProps) {!isCreate && props.triggers[0]?.event_filters ? props.triggers[0].event_filters : [];const [eventFilters, setEventFilters] = useState<WebhookEventFilter[]>(initialEventFilters);- const initialCronRef = useRef(toCronExpression(initialCfg));+ const initialCronRef = useRef(toCron(initialCfg));const initialTimezoneRef = useRef(initialCfg.timezone);const initialEventFiltersRef = useRef(serializeEventFilters(initialEventFilters));const scheduleDirty =- toCronExpression(triggerConfig) !== initialCronRef.current ||- triggerConfig.timezone !== initialTimezoneRef.current;+ toCron(schedule) !== initialCronRef.current ||+ schedule.timezone !== initialTimezoneRef.current;const eventFiltersDirty =serializeEventFilters(eventFilters) !== initialEventFiltersRef.current;@@ -382,13 +243,29 @@ export function AutopilotDialog(props: AutopilotDialogProps) {// and click into it to grab the URL" friction.const [createdWebhookTrigger, setCreatedWebhookTrigger] = useState<AutopilotTrigger | null>(null);+ const scheduleGate = useScheduleSubmitGate(wsId);++ // The schedule only gates submit when this save would actually write it. A+ // locked schedule (2+ triggers) or one the user never touched is not sent, so+ // a preview 400 on the stored expression — an expression the server accepted+ // once and may now reject, e.g. a timezone its tzdata dropped — must not veto+ // edits to the title, prompt or assignee.+ const scheduleWillBeWritten =+ triggerKind === "schedule" && !schedulePillDisabled && (isCreate || scheduleDirty);const canSubmit =- title.trim().length > 0 && assigneeId.length > 0 && !submitting;+ title.trim().length > 0 &&+ assigneeId.length > 0 &&+ !submitting &&+ (!scheduleWillBeWritten || scheduleGate.scheduleValid);const handleSubmit = async () => {if (!canSubmit) return;setSubmitting(true);try {+ if (scheduleWillBeWritten && !(await scheduleGate.ensureAccepted(schedule))) {+ setSubmitting(false);+ return;+ }if (isCreate) {const autopilot = await createAutopilot.mutateAsync({title: title.trim(),@@ -416,8 +293,8 @@ export function AutopilotDialog(props: AutopilotDialogProps) {await createTrigger.mutateAsync({autopilotId: autopilot.id,kind: "schedule",- cron_expression: toCronExpression(triggerConfig),- timezone: triggerConfig.timezone,+ cron_expression: toCron(schedule),+ timezone: schedule.timezone,});}} catch (err) {@@ -460,22 +337,22 @@ export function AutopilotDialog(props: AutopilotDialogProps) {// Skip the schedule sync when the autopilot's first trigger is a// webhook — there's no cron to update there, and the schedule// panel isn't even rendered for webhook autopilots.- if (triggerKind === "schedule" && scheduleDirty && !schedulePillDisabled) {+ if (scheduleWillBeWritten) {const snapshottedTriggerId = firstTriggerIdRef.current;try {if (snapshottedTriggerId) {await updateTrigger.mutateAsync({autopilotId: props.autopilotId,triggerId: snapshottedTriggerId,- cron_expression: toCronExpression(triggerConfig),- timezone: triggerConfig.timezone,+ cron_expression: toCron(schedule),+ timezone: schedule.timezone,});} else {await createTrigger.mutateAsync({autopilotId: props.autopilotId,kind: "schedule",- cron_expression: toCronExpression(triggerConfig),- timezone: triggerConfig.timezone,+ cron_expression: toCron(schedule),+ timezone: schedule.timezone,});}} catch (err) {@@ -675,7 +552,7 @@ export function AutopilotDialog(props: AutopilotDialogProps) {</div>{/* Right: Configuration */}- <aside className="w-full lg:w-[340px] shrink-0 overflow-visible lg:overflow-y-auto px-5 py-5 space-y-5 bg-muted/30">+ <aside className="w-full lg:w-[380px] shrink-0 overflow-visible lg:overflow-y-auto px-5 py-5 space-y-5 bg-muted/30"><AgentSectionselectedType={assigneeType}selectedId={assigneeId}@@ -706,16 +583,28 @@ export function AutopilotDialog(props: AutopilotDialogProps) {)}{triggerKind === "schedule" ? (- <ScheduleSection- config={triggerConfig}- onChange={setTriggerConfig}- disabled={schedulePillDisabled}- disabledReason={- schedulePillDisabled- ? t(($) => $.dialog.schedule_disabled_reason)- : undefined- }- />+ <div>+ <SectionLabel>{t(($) => $.dialog.section_schedule)}</SectionLabel>+ <ScheduleEditor+ value={schedule}+ onChange={(next) => {+ scheduleGate.clearRejection();+ setSchedule(next);+ }}+ wsId={wsId}+ onValidityChange={scheduleGate.onValidityChange}+ // Locked while the save is in flight: the submit path validates+ // over the network and then writes the schedule it read before+ // that round trip, so an edit made in between would be dropped+ // on the floor with a success toast over it.+ disabled={schedulePillDisabled || submitting}+ disabledReason={+ schedulePillDisabled+ ? t(($) => $.dialog.schedule_disabled_reason)+ : undefined+ }+ />+ </div>) : (<WebhookSectionisCreate={isCreate}@@ -948,145 +837,6 @@ function SubscribersSection({);}-function ScheduleSection({- config,- onChange,- disabled,- disabledReason,-}: {- config: TriggerConfig;- onChange: (c: TriggerConfig) => void;- disabled?: boolean;- disabledReason?: string;-}) {- const { t } = useT("autopilots");- const formatCountdown = useFormatCountdown();- const now = useNowTicker();- const next = useMemo(() => computeNextRun(config, now), [config, now]);- const frequencyItems = FREQUENCY_KEYS.map((value) => ({- value,- label: t(($) => $.dialog.frequency_long[value]),- }));- const dayItems = DAY_KEYS.map((dayKey, value) => ({- value: String(value),- label: t(($) => $.dialog.days[dayKey]),- }));- const timezones = useMemo(() => {- const local = getLocalTimezone();- if (TIMEZONE_OPTIONS.includes(local)) return TIMEZONE_OPTIONS;- return [local, ...TIMEZONE_OPTIONS];- }, []);-- const selectedDay = config.daysOfWeek[0] ?? 1;-- return (- <div>- <SectionLabel>{t(($) => $.dialog.section_schedule)}</SectionLabel>- <div- className={cn(- "space-y-2",- disabled && "opacity-60 pointer-events-none",- )}- >- {/* Row 1: Frequency + (Day when weekly) */}- <div className="grid grid-cols-2 gap-2">- <Select- items={frequencyItems}- value={config.frequency}- onValueChange={(v) =>- v && onChange({ ...config, frequency: v as TriggerFrequency })- }- >- <SelectTrigger className="w-full">- <SelectValue />- </SelectTrigger>- <SelectContent>- {frequencyItems.map((item) => (- <SelectItem key={item.value} value={item.value}>- {item.label}- </SelectItem>- ))}- </SelectContent>- </Select>- {config.frequency === "weekly" ? (- <Select- items={dayItems}- value={String(selectedDay)}- onValueChange={(v) =>- v && onChange({ ...config, daysOfWeek: [parseInt(v, 10)] })- }- >- <SelectTrigger className="w-full">- <SelectValue />- </SelectTrigger>- <SelectContent>- {dayItems.map((item) => (- <SelectItem key={item.value} value={item.value}>- {item.label}- </SelectItem>- ))}- </SelectContent>- </Select>- ) : (- <div />- )}- </div>-- {/* Row 2: Time + Timezone (hidden for hourly / custom) */}- {config.frequency === "custom" ? (- <input- type="text"- value={config.cronExpression}- onChange={(e) =>- onChange({ ...config, cronExpression: e.target.value })- }- placeholder="0 9 * * 1-5"- className="w-full rounded-lg border border-input bg-transparent px-2.5 py-1 h-8 text-sm font-mono outline-none transition-colors focus:border-ring focus:ring-3 focus:ring-ring/50 dark:bg-input/30"- />- ) : config.frequency === "hourly" ? (- <TimeInput- minuteOnly- value={config.time}- onChange={(v) => onChange({ ...config, time: v })}- />- ) : (- <div className="grid grid-cols-2 gap-2">- <TimeInput- value={config.time}- onChange={(v) => onChange({ ...config, time: v })}- />- <TimezonePicker- value={config.timezone}- onChange={(tz) => onChange({ ...config, timezone: tz })}- options={timezones}- />- </div>- )}-- {/* Next run preview */}- {next && (- <div className="flex items-center gap-1.5 text-xs text-muted-foreground pt-1">- <Clock className="size-3 shrink-0" />- <span className="truncate">- {t(($) => $.dialog.next_run_label)}{" "}- <span className="text-foreground">- {formatNextRunAbsolute(next, config.timezone)}- </span>- </span>- <span className="ml-auto rounded-sm bg-muted px-1.5 py-0.5 text-[10px] font-medium text-foreground shrink-0">- {formatCountdown(next, now)}- </span>- </div>- )}- </div>- {disabled && disabledReason && (- <p className="mt-2 text-[11px] text-muted-foreground">- {disabledReason}- </p>- )}- </div>- );-}// ---------------------------------------------------------------------------// Trigger kind segmented control + webhook help section@@ -1103,52 +853,31 @@ function TriggerKindSection({return (<div><SectionLabel>{t(($) => $.dialog.section_trigger_kind)}</SectionLabel>- <div className="grid grid-cols-2 gap-1 rounded-md bg-muted p-1">- <TriggerKindButton- active={kind === "schedule"}- onClick={() => onChange("schedule")}- icon={<Clock className="h-3.5 w-3.5" />}- label={t(($) => $.dialog.trigger_kind_schedule)}- />- <TriggerKindButton- active={kind === "webhook"}- onClick={() => onChange("webhook")}- icon={<Webhook className="h-3.5 w-3.5" />}- label={t(($) => $.dialog.trigger_kind_webhook)}- />- </div>+ <SegmentedToggle+ value={kind}+ onChange={onChange}+ buttonClassName="px-3 py-1.5 text-sm"+ options={[+ [+ "schedule",+ <span key="schedule" className="flex items-center justify-center gap-1.5">+ <Clock className="h-3.5 w-3.5" />+ {t(($) => $.dialog.trigger_kind_schedule)}+ </span>,+ ],+ [+ "webhook",+ <span key="webhook" className="flex items-center justify-center gap-1.5">+ <Webhook className="h-3.5 w-3.5" />+ {t(($) => $.dialog.trigger_kind_webhook)}+ </span>,+ ],+ ]}+ /></div>);}-function TriggerKindButton({- active,- onClick,- icon,- label,-}: {- active: boolean;- onClick: () => void;- icon: React.ReactNode;- label: string;-}) {- return (- <button- type="button"- onClick={onClick}- className={cn(- "flex items-center justify-center gap-1.5 rounded px-3 py-1.5 text-sm transition-colors",- active- ? "bg-background text-foreground shadow-sm"- : "text-muted-foreground hover:text-foreground",- )}- >- {icon}- <span>{label}</span>- </button>- );-}-function WebhookSection({isCreate,eventFilters,diff --git a/packages/views/autopilots/components/autopilots-page.tsx b/packages/views/autopilots/components/autopilots-page.tsxindex 2862b7fdfc..8ecef18867 100644--- a/packages/views/autopilots/components/autopilots-page.tsx+++ b/packages/views/autopilots/components/autopilots-page.tsx@@ -46,6 +46,7 @@ import {import { Skeleton } from "@multica/ui/components/ui/skeleton";import { useRowLink } from "../../navigation";import { ActorAvatar } from "../../common/actor-avatar";+import { formatInTimeZone } from "../../common/format-in-time-zone";import {CollectionPageHeader,CollectionPageHeaderAction,@@ -57,7 +58,7 @@ import {AutopilotBatchToolbar,AutopilotRowActions,} from "./autopilot-list-actions";-import type { TriggerFrequency } from "./trigger-config";+import type { ScheduleConfig } from "./schedule-editor/model";import { useT, useTimeAgo } from "../../i18n";// Column template — single source of truth for header, rows, and skeletons.@@ -135,10 +136,12 @@ interface AutopilotTemplate {id: TemplateId;prompt: string;icon: typeof Zap;- frequency: TriggerFrequency;- time: string;+ schedule: Pick<ScheduleConfig, "time" | "days">;}+const WEEKDAYS: ScheduleConfig["days"] = { kind: "weekly", daysOfWeek: [1, 2, 3, 4, 5] };+const MONDAY: ScheduleConfig["days"] = { kind: "weekly", daysOfWeek: [1] };+const TEMPLATES: AutopilotTemplate[] = [{id: "daily_news",@@ -148,8 +151,7 @@ const TEMPLATES: AutopilotTemplate[] = [4. Compile everything into a single digest post5. Post the digest as a comment on this issue and @mention all workspace members`,icon: Newspaper,- frequency: "daily",- time: "09:00",+ schedule: { time: { kind: "at", time: "09:00" }, days: { kind: "every" } },},{id: "pr_review",@@ -159,8 +161,7 @@ const TEMPLATES: AutopilotTemplate[] = [4. Post a comment on this issue listing all stale PRs with links5. @mention the team to remind them to review`,icon: GitPullRequest,- frequency: "weekdays",- time: "10:00",+ schedule: { time: { kind: "at", time: "10:00" }, days: WEEKDAYS },},{id: "bug_triage",@@ -170,8 +171,7 @@ const TEMPLATES: AutopilotTemplate[] = [4. Set the priority field on the issue accordingly5. Add a comment explaining your assessment and suggested next steps`,icon: Bug,- frequency: "weekdays",- time: "09:00",+ schedule: { time: { kind: "at", time: "09:00" }, days: WEEKDAYS },},{id: "weekly_progress",@@ -182,8 +182,7 @@ const TEMPLATES: AutopilotTemplate[] = [5. Write a structured weekly report with sections: Completed, In Progress, Blocked, Metrics6. Post the report as a comment on this issue`,icon: BarChart3,- frequency: "weekly",- time: "17:00",+ schedule: { time: { kind: "at", time: "17:00" }, days: MONDAY },},{id: "dependency_audit",@@ -193,8 +192,7 @@ const TEMPLATES: AutopilotTemplate[] = [4. For each finding, note the severity, affected package, and recommended fix5. Post a summary report as a comment with actionable items`,icon: Shield,- frequency: "weekly",- time: "08:00",+ schedule: { time: { kind: "at", time: "08:00" }, days: MONDAY },},{id: "documentation_check",@@ -204,8 +202,7 @@ const TEMPLATES: AutopilotTemplate[] = [4. Create a list of documentation gaps with file paths and suggested content5. Post the findings as a comment on this issue`,icon: FileSearch,- frequency: "weekly",- time: "14:00",+ schedule: { time: { kind: "at", time: "14:00" }, days: MONDAY },},];@@ -372,17 +369,13 @@ function LastRunCell({ autopilot }: { autopilot: Autopilot }) {}function NextRunCell({ autopilot }: { autopilot: Autopilot }) {+ const { i18n } = useT("autopilots");const next = autopilot.next_run_at;return (<ListGridCell className="hidden @2xl:flex">{next ? (<span className="whitespace-nowrap text-xs tabular-nums text-muted-foreground">- {new Date(next).toLocaleString(undefined, {- month: "short",- day: "numeric",- hour: "2-digit",- minute: "2-digit",- })}+ {formatInTimeZone(next, undefined, i18n.language)}</span>) : (<span className="text-xs text-muted-foreground/40">—</span>@@ -978,14 +971,7 @@ export function AutopilotsPage() {}: undefined}- initialTriggerConfig={- selectedTemplate- ? {- frequency: selectedTemplate.frequency,- time: selectedTemplate.time,- }- : undefined- }+ initialSchedule={selectedTemplate ? selectedTemplate.schedule : undefined}/>)}</div>diff --git a/packages/views/autopilots/components/pickers/timezone-picker.tsx b/packages/views/autopilots/components/pickers/timezone-picker.tsxindex 4272c25c46..28829a642b 100644--- a/packages/views/autopilots/components/pickers/timezone-picker.tsx+++ b/packages/views/autopilots/components/pickers/timezone-picker.tsx@@ -15,9 +15,28 @@ export interface TimezonePickerProps {options: string[];disabled?: boolean;className?: string;+ /** The trigger only shows the selected zone, so on its own it announces as+ * "Shanghai" — a value with no field. Callers name the field. */+ ariaLabel?: string;}+// Each lookup builds an Intl.DateTimeFormat — several hundred of them for the+// full IANA list, on every keystroke in the filter. Cached, but not forever: an+// offset moves at a DST boundary, and a desktop window lives for weeks, so an+// entry cached in March must not still say "London GMT+0" in April.+const OFFSET_TTL_MS = 10 * 60_000;+const offsetCache = new Map<string, { offset: string; at: number }>();+function offsetFor(tz: string): string {+ const now = Date.now();+ const cached = offsetCache.get(tz);+ if (cached !== undefined && now - cached.at < OFFSET_TTL_MS) return cached.offset;+ const offset = computeOffset(tz);+ offsetCache.set(tz, { offset, at: now });+ return offset;+}++function computeOffset(tz: string): string {try {const parts = new Intl.DateTimeFormat("en-US", {timeZone: tz,@@ -40,13 +59,14 @@ export function TimezonePicker({options,disabled,className,+ ariaLabel,}: TimezonePickerProps) {const { t } = useT("autopilots");const [open, setOpen] = useState(false);const [filter, setFilter] = useState("");const selectedCity = cityLabel(value);- const selectedOffset = useMemo(() => offsetFor(value), [value]);+ const selectedOffset = offsetFor(value);const query = filter.trim().toLowerCase();const filteredOptions = useMemo(() => {@@ -73,6 +93,15 @@ export function TimezonePicker({<buttontype="button"disabled={disabled}+ // The trigger's own text is the value, so a bare field name would+ // replace it. The name carries the whole visible line instead — the+ // offset is what tells two same-named zones apart, which is why it is+ // on screen in the first place.+ aria-label={+ ariaLabel === undefined+ ? undefined+ : `${ariaLabel}: ${[selectedCity, selectedOffset].filter(Boolean).join(" ")}`+ }className={cn("flex h-8 w-full items-center gap-1.5 rounded-lg border border-input bg-transparent px-2.5 text-sm transition-colors outline-none","hover:bg-accent/30",@@ -96,7 +125,11 @@ export function TimezonePicker({</>}>- {filteredOptions.length === 0 ? (+ {/* Built only while the popover is open: each row's offset lookup can cold-+ build an Intl.DateTimeFormat, and evaluating the full IANA list here on+ every render would pay that burst on dialog open (and again on each+ cache expiry) for a list the user may never look at. */}+ {!open ? null : filteredOptions.length === 0 ? (<PickerEmpty />) : (filteredOptions.map((tz) => {diff --git a/packages/views/autopilots/components/schedule-editor/cron-grammar.test.ts b/packages/views/autopilots/components/schedule-editor/cron-grammar.test.tsnew file mode 100644index 0000000000..0134f8e374--- /dev/null+++ b/packages/views/autopilots/components/schedule-editor/cron-grammar.test.ts@@ -0,0 +1,816 @@+import { describe, it, expect, vi } from "vitest";+import { cronFields, parseCron, toCron } from "./cron-mapping";++// The suite sweeps a corpus of tens of thousands of expressions per test, some+// round-tripping every one; that is well within a second locally but crosses+// the default 5s cap on a loaded CI runner. Give the whole-corpus sweeps room.+vi.setConfig({ testTimeout: 30_000 });++// Hand-written example lists are how corners get missed: they only ever cover+// the shapes someone thought of. This suite covers the grammar by construction+// instead — it enumerates every token form of every field, and judges the result+// against an independent reference implementation of robfig/cron v3's parser+// rather than against expected strings someone typed out.+//+// The reference is the oracle. If the editor and the reference disagree about+// what an expression means, the editor is wrong — that is the whole point.++// ---------------------------------------------------------------------------+// Reference implementation of robfig/cron v3 (5-field), from its source.+// ---------------------------------------------------------------------------++interface Bounds {+ min: number;+ max: number;+ names?: Record<string, number>;+}++const MONTH_NAMES = {+ jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6,+ jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12,+};+const DOW_NAMES = { sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6 };++const MINUTE: Bounds = { min: 0, max: 59 };+const HOUR: Bounds = { min: 0, max: 23 };+const DOM: Bounds = { min: 1, max: 31 };+const MONTH: Bounds = { min: 1, max: 12, names: MONTH_NAMES };+const DOW: Bounds = { min: 0, max: 6, names: DOW_NAMES };++/** One parsed field: the values it selects, and whether it was written as a+ * wildcard. robfig keeps that bit because dom/dow switch between AND and OR+ * depending on it. */+interface Field {+ values: Set<number>;+ star: boolean;+}++class CronSyntaxError extends Error {}++function parseIntOrName(token: string, b: Bounds): number {+ const named = b.names?.[token.toLowerCase()];+ if (named !== undefined) return named;+ // robfig numbers go through strconv.Atoi, which takes leading zeros and a+ // plus sign: "009", "+9" and "MON-05" are all legal. (Overflow past int is an+ // Atoi error; here it parses to a huge number and fails the bounds check —+ // same rejection, different wording.)+ if (!/^\+?\d+$/.test(token)) throw new CronSyntaxError(`bad token ${token}`);+ return parseInt(token, 10);+}++/** robfig getRange: `<range>` or `<range>/<step>`, where `<range>` is `*`, `?`,+ * `N`, or `N-M`. A bare `N` with a step means `N-max/step`. */+function getRange(expr: string, b: Bounds): Field {+ const parts = expr.split("/");+ if (parts.length > 2) throw new CronSyntaxError(`too many slashes in ${expr}`);+ const rangeStr = parts[0]!;+ if (rangeStr === "") throw new CronSyntaxError(`empty range in ${expr}`);++ let step = 1;+ if (parts.length === 2) {+ const stepStr = parts[1]!;+ // Steps are Atoi numbers too: "*/+5" is a step of 5 to the backend.+ if (!/^\+?\d+$/.test(stepStr)) throw new CronSyntaxError(`bad step ${stepStr}`);+ step = parseInt(stepStr, 10);+ if (step === 0) throw new CronSyntaxError("step of zero");+ }++ // The wildcard test is on the range's LOW END, not on the whole range+ // (parser.go:261), and the branch it takes never looks at what followed the+ // "-" — not to parse it, not even to count the hyphens. So "*-19", "?-5" and+ // "*-19-25" are all the full span, exactly as "*" is. Writing this as an+ // equality on the whole range instead is what a reference implementation gets+ // wrong by being tidier than the thing it stands in for: it then calls those+ // expressions syntax errors, and the suite below dutifully checks the editor+ // against a grammar the server does not have.+ const ends = rangeStr.split("-");+ const star = ends[0] === "*" || ends[0] === "?";+ let low: number;+ let high: number;+ if (star) {+ low = b.min;+ high = b.max;+ } else {+ if (ends.length > 2) throw new CronSyntaxError(`too many dashes in ${expr}`);+ low = parseIntOrName(ends[0]!, b);+ if (ends.length === 2) {+ high = parseIntOrName(ends[1]!, b);+ } else {+ // "N/step" means "N-max/step"; a bare "N" is just N.+ high = parts.length === 2 ? b.max : low;+ }+ }+ if (low < b.min || high > b.max) throw new CronSyntaxError(`${expr} out of bounds`);+ if (low > high) throw new CronSyntaxError(`${expr} runs backwards`);++ const values = new Set<number>();+ for (let v = low; v <= high; v += step) values.add(v);+ // A step wider than 1 CLEARS the star bit (parser.go:297-298, `if step > 1 {+ // extra = 0 }`). It is not a detail: the bit is what makes dom/dow AND rather+ // than OR, so in "0 9 */2 * 1" neither field is a wildcard and the schedule+ // fires on every even day-of-month OR every Monday — not on their intersection.+ return { values, star: star && step === 1 };+}++function parseField(expr: string, b: Bounds): Field {+ const values = new Set<number>();+ let star = false;+ // robfig splits lists with strings.FieldsFunc (parser.go:238), which DROPS+ // empty elements — so "0,30," and "1,,5" are accepted, and a field of nothing+ // but commas parses to a field that selects no value and therefore never+ // fires. A plain split() would call all of these syntax errors and make this+ // reference stricter than the parser it is standing in for.+ for (const part of expr.split(",").filter((p) => p.length > 0)) {+ const f = getRange(part, b);+ for (const v of f.values) values.add(v);+ if (f.star) star = true;+ }+ return { values, star };+}++interface Spec {+ minute: Field;+ hour: Field;+ dom: Field;+ month: Field;+ dow: Field;+ /** The `TZ=` / `CRON_TZ=` prefix's zone, null when the expression has none.+ * An empty name is spelled "UTC", which is what LoadLocation("") loads. */+ tz: string | null;+ /** Whether LoadLocation would accept that zone. The FIELDS of an expression+ * with a bad zone still parse — the server rejects the expression, but at+ * the timezone, and the editor's extraction relies on the difference. */+ tzValid: boolean;+ /** The expression with the prefix stripped, trimmed: the five fields as the+ * parser reads them, and as the editor's `raw` holds them. */+ body: string;+}++/** LoadLocation's verdict on every zone name the corpus uses. The oracle+ * cannot load real timezones, and it must not ask the browser — Intl and Go+ * disagree (Go loads "Local", Intl throws on it) — so the corpus keeps to+ * names whose verdict is pinned here. */+const TZ_VERDICTS: Record<string, boolean> = {+ UTC: true,+ "Asia/Tokyo": true,+ "Asia/Shanghai": true,+ Local: true,+ "Bogus/Zone": false,+ "A=B": false,+ "UTC\t": false,+};++/** robfig's prefix read (parser.go Parse), exactly: case-sensitive, on the+ * untrimmed text, name up to the FIRST LITERAL SPACE. No space at all is the+ * v3.0.1 panic (parser.go:99), which the server's guard turns into a plain+ * rejection — either way the expression is refused, so the oracle rejects. */+function referencePrefix(expr: string): { tz: string; tzValid: boolean; rest: string } | "reject" | null {+ if (!expr.startsWith("TZ=") && !expr.startsWith("CRON_TZ=")) return null;+ const space = expr.indexOf(" ");+ if (space === -1) return "reject";+ const name = expr.slice(expr.indexOf("=") + 1, space);+ const tzValid = TZ_VERDICTS[name === "" ? "UTC" : name];+ if (tzValid === undefined) throw new Error(`corpus uses unpinned timezone ${JSON.stringify(name)}`);+ return { tz: name === "" ? "UTC" : name, tzValid, rest: expr.slice(space).trim() };+}++/** Returns null when robfig would reject the expression's structure. A parsed+ * Spec with tzValid=false is still a server rejection — of the zone, not of+ * the fields; callers that mean "does the server accept this" must check both. */+function reference(expr: string): Spec | null {+ const prefix = referencePrefix(expr);+ if (prefix === "reject") return null;+ const body = prefix === null ? expr : prefix.rest;+ const parts = body.trim().split(/\s+/).filter((p) => p.length > 0);+ if (parts.length !== 5) return null;+ try {+ return {+ minute: parseField(parts[0]!, MINUTE),+ hour: parseField(parts[1]!, HOUR),+ dom: parseField(parts[2]!, DOM),+ month: parseField(parts[3]!, MONTH),+ dow: parseField(parts[4]!, DOW),+ tz: prefix === null ? null : prefix.tz,+ tzValid: prefix === null ? true : prefix.tzValid,+ body: body.trim(),+ };+ } catch (err) {+ if (err instanceof CronSyntaxError) return null;+ throw err;+ }+}++/** Does the server accept this expression as a whole — fields AND zone? */+function serverAccepts(spec: Spec | null): spec is Spec {+ return spec !== null && spec.tzValid;+}++/** Where the EDITOR's extraction applies. Syntactic — it also fires over a+ * body the server rejects ("TZ=UTC not a cron" echoes as the pair+ * ("not a cron", UTC), which the server rejects just the same) — plus one+ * gate the syntax cannot see: the zone must be one the browser could have+ * offered in the picker, since config.timezone is a picker value and a+ * formatter argument. "Local" is legal to LoadLocation (the SERVER host's+ * zone) but no browser zone at all, so it stays buried in the verbatim text,+ * where it keeps meaning what it meant. Not where robfig's read would panic+ * (no space) or would leave a second prefix as a field — there the editor+ * must keep the text verbatim too, and this returns null. */+function extractedForEcho(expr: string): { tz: string; rest: string } | null {+ const p = referencePrefix(expr);+ if (p === null || p === "reject") return null;+ if (p.rest.length === 0) return null;+ if (p.rest.startsWith("TZ=") || p.rest.startsWith("CRON_TZ=")) return null;+ const canonical = canonicalPickerZone(p.tz);+ if (canonical === null) return null;+ return { tz: canonical, rest: p.rest };+}++/** The browser's verdict on a zone name — the same Intl probe the editor runs,+ * since the editor's contract IS "what the picker can hold": the canonical+ * spelling the picker's list uses, or null when the browser cannot hold it. */+function canonicalPickerZone(tz: string): string | null {+ try {+ return new Intl.DateTimeFormat(undefined, { timeZone: tz }).resolvedOptions().timeZone;+ } catch {+ return null;+ }+}++/** robfig dayMatches: dom and dow are ANDed while either is a wildcard, and+ * ORed once both are restricted. Two specs are day-equivalent iff they agree on+ * every (day-of-month, day-of-week) pair. */+function dayMatches(spec: Spec, dom: number, dow: number): boolean {+ const domHit = spec.dom.values.has(dom);+ const dowHit = spec.dow.values.has(dow);+ return spec.dom.star || spec.dow.star ? domHit && dowHit : domHit || dowHit;+}++function sameSet(a: Set<number>, b: Set<number>): boolean {+ return a.size === b.size && [...a].every((v) => b.has(v));+}++/** Do two expressions fire at exactly the same instants? Compared over the whole+ * domain — every minute, hour, month, and every (dom, dow) pair — so this is an+ * exact equivalence, not a sampled one. */+function sameSchedule(a: Spec, b: Spec): boolean {+ if (!sameSet(a.minute.values, b.minute.values)) return false;+ if (!sameSet(a.hour.values, b.hour.values)) return false;+ if (!sameSet(a.month.values, b.month.values)) return false;+ for (let dom = 1; dom <= 31; dom++) {+ for (let dow = 0; dow <= 6; dow++) {+ if (dayMatches(a, dom, dow) !== dayMatches(b, dom, dow)) return false;+ }+ }+ return true;+}++// ---------------------------------------------------------------------------+// The corpus: every token form of every field.+// ---------------------------------------------------------------------------++// Each list walks one field through the whole closed grammar — wildcard,+// question mark, bare values at both bounds and past them, names, ranges+// (normal, degenerate, reversed, out of bounds), steps (on a wildcard, on a+// range, anchored to a value, of one, of zero, wider than the field), lists,+// Atoi's lexical variance (leading zeros, plus signs, overflow), and syntax+// that is simply malformed.+//+// Every field also carries the wildcard-low-end forms ("*-19", "?-5", "*-19/2"),+// which robfig reads as the full span with the upper end unread. They are the+// corner the reference above used to get wrong, so they belong in every list: a+// grammar quirk that lives in getRange lives in all five fields at once.+const MINUTE_TOKENS = [+ "*", "?", "0", "5", "30", "59", "60", "-5",+ "*/1", "*/5", "*/59", "*/60", "*/0", "?/5",+ "0/5", "15/5", "59/5",+ "0-30", "0-30/10", "30-0", "0-59",+ "0,30", "0,15,30,45", "0-10,30", "0-30/10,45",+ // robfig drops empty list elements, so these are legal, not typos.+ "0,30,", ",0,30", "1,,5", ",", "0,", ",0", "30,",+ // A list with a step-1 wildcard part means "*"; one whose extra part does not+ // parse is the syntax error the server calls it, wildcard or no wildcard.+ "0,*", "*,*/2", "?,15", "0,*-30", "*,60", "*,abc",+ // Atoi numbers: leading zeros and plus signs are legal, overflow is not.+ "09", "009", "00", "+30", "030-045", "00/05", "*/05", "*/+5",+ "99999999999999999999", "+",+ // The upper end of a wildcard range is unread — nonsense there is not an error.+ "*-30", "?-30", "*-30/10", "?-30/10", "*-99", "*-abc", "*-10-20", "9-?",+ "5-5", "", "*/", "0//5", "0--30", "abc",+];++const HOUR_TOKENS = [+ "*", "?", "0", "9", "23", "24", "-1",+ "*/1", "*/2", "*/23", "*/24", "*/0",+ "0/2", "9/2", "23/2", "9/1", "?/2",+ "*-19", "?-19", "*-19/2", "?-19/2", "*-19/23", "9-19/23",+ "9-21", "9-21/2", "9-21/1", "21-9", "0-23", "0-23/1", "9-9",+ // A window one hour wide, stepped: the editor writes this itself when a+ // dragged start meets its end. Past the model's interval bound ("/24") it has+ // no window form left and must collapse to the hour it selects.+ "9-9/3", "9-9/24", "9-11/5", "9-21/23", "9-21/30",+ "9,12,15", "9-12,18", "0-23/6", "9,12,", "9,,12", "9,", ",9", "0,",+ "9,*", "*,*/2",+ "09", "021", "+9", "09-021/02",+ "", "*/", "9//2", "abc",+];++const DOM_TOKENS = [+ "*", "?", "1", "15", "31", "0", "32",+ "*/2", "?/2", "1/2", "1-15", "1-15/2", "15-1",+ "*-15", "?-15", "*-15/2", "?/40",+ "1,15", "1-7,15", "1,15,", "1,,15", "15,", ",15", "1,*", "*,32", "L", "15W",+ "015", "01", "+15",+ "", "abc",+];++const MONTH_TOKENS = [+ "*", "?", "1", "6", "12", "0", "13",+ "JAN", "jan", "DEC", "FOO",+ "*/2", "?/2", "1-6", "1-6/2", "1,6", "6-1", "1,6,", "1,,6", "6,", ",6",+ "1,*", "JAN,*", "FOO,*",+ "*-6", "?-6", "*-6/2", "JAN-JUN/2",+ "06", "012", "+6",+ "", "abc",+];++const DOW_TOKENS = [+ "*", "?", "0", "1", "6", "7", "-1",+ "SUN", "sun", "SAT", "MON", "FOO",+ "*/2", "*/7", "?/2", "1/2", "MON/2", "0/3",+ "*-5", "?-5", "*-5/2", "?-5/2", "SUN-SAT/2",+ // A step wider than the week. robfig has no upper bound on a step, so these are+ // legal and degenerate: they select the range's first day and nothing else+ // ("*/100" is Sunday, "1-5/60" and "MON-FRI/60" are Monday). Day-of-week was the+ // last field whose parser drew its own step bound and refused them.+ "*/100", "1-5/60", "MON-FRI/60",+ "1-5", "MON-FRI", "mon-fri", "sun-sat", "0-6", "5-1", "1-5/2", "1-1",+ "1,3,5", "MON,WED", "5,1,5", "1,3-5", "0-2,4",+ // Empty list elements are dropped by the backend, so these are Mon–Fri and+ // {Mon, Fri} — and dow is the one field whose echo domain is "anything+ // enumerable", so they have to come back as chips, not as advanced-only.+ "1-5,", ",1,5", "1,,5", ",", "1,", ",1", "5,",+ "1,*", "MON,*", "*/2,*/3", "*,7",+ "001", "01", "+1", "+0", "MON-05", "0-06/02",+ "1#2", "5L",+ "", "abc",+];++// The model is two dimensions — a time and a set of days — so crossing the cron+// FIELDS pairwise is not enough: it leaves the two dimensions themselves+// uncrossed. A first cut of this suite did exactly that (minute x hour over a+// wildcard day, dom x dow over a fixed time) and a mutant that dropped the+// day-of-month whenever the time was an interval survived every invariant. Each+// full field-cross below is therefore replayed against every branch of the other+// dimension.++/** One expression per branch of the day logic: unrestricted, each weekly shape,+ * each day-of-month boundary, and the dom+dow pair cron ORs. */+const DAY_BRANCHES = ["* * *", "* * 1-5", "* * 0", "* * 6", "1 * *", "15 * *", "31 * *", "15 * 1"];++/** One expression per branch of the time logic: fixed, hourly and N-hourly (with+ * and without a window and a minute offset), and the minute-step forms. */+const TIME_BRANCHES = [+ "0 9", "30 14", "0 *", "15 *", "0 */2", "30 */3",+ "0 9-21", "30 9-21", "0 9-21/2", "* *", "*/10 *", "*/10 9-18", "*/15 9",+];++/** Every expression the corpus produces. */+function corpus(): string[] {+ const out = new Set<string>();++ // minute x hour, fully crossed — the model carries a single step dimension, so+ // whether a minute step may sit beside an hour step is settled here — and the+ // whole cross replayed against every shape the day dimension can take.+ for (const m of MINUTE_TOKENS) {+ for (const h of HOUR_TOKENS) {+ for (const days of DAY_BRANCHES) out.add(`${m} ${h} ${days}`);+ }+ }++ // dom x dow, fully crossed — cron ORs these two once both are restricted,+ // which the orthogonal model cannot express — against every shape of time.+ for (const dom of DOM_TOKENS) {+ for (const dow of DOW_TOKENS) {+ for (const time of TIME_BRANCHES) out.add(`${time} ${dom} * ${dow}`);+ }+ }++ // month, on its own axis: it does not interact with anything, but it still has+ // to survive both dimensions.+ for (const mo of MONTH_TOKENS) {+ for (const time of TIME_BRANCHES) out.add(`${time} * ${mo} *`);+ out.add(`0 9 15 ${mo} *`);+ out.add(`0 9 * ${mo} 1-5`);+ }++ // Structural shapes, which are about the expression rather than any one field.+ for (const e of [+ "", " ", "0 9 * *", "0 9 * * * *", "0 0 9 * * *",+ "@daily", "@hourly", "@every 1h", "@reboot",+ "not a cron", "0 9 * * 1 # comment",+ " 0 9 * * * ",+ ]) {+ out.add(e);+ }++ // The TZ= / CRON_TZ= prefix, which robfig reads BEFORE the fields and whose+ // zone then overrides the schedule's timezone column. Prefix shapes crossed+ // with bodies of every disposition: structurable, advanced-only, and invalid.+ const TZ_PREFIXES = [+ "TZ=UTC", "CRON_TZ=Asia/Tokyo", "TZ=Local", "TZ=",+ "TZ=Bogus/Zone", "TZ=A=B", "tz=UTC", "TZ=UTC\t",+ ];+ const TZ_BODIES = [+ "0 9 * * *", "30 */3 * * 1-5", "0 9 1,15 * *", "?/2 ?/2 * * ?/2",+ "not a cron", "0 9 * *", "", "@daily",+ ];+ for (const p of TZ_PREFIXES) {+ for (const b of TZ_BODIES) out.add(`${p} ${b}`);+ }+ // And the shapes that are about the prefix itself: no schedule after it (the+ // robfig v3.0.1 panic the server guards), trailing space only, a second+ // prefix behind the first (robfig strips ONE and reads the next as a field),+ // and a leading space (not a prefix to robfig at all).+ for (const e of [+ "TZ=UTC", "CRON_TZ=Asia/Tokyo", "TZ=", "TZ=UTC ", "TZ=UTC ",+ "TZ=UTC TZ=UTC 0 9 * * *", "TZ=UTC CRON_TZ=Asia/Tokyo 0 9 * * *",+ " TZ=UTC 0 9 * * *",+ ]) {+ out.add(e);+ }++ return [...out];+}++const CORPUS = corpus();++// Why the editor refuses an expression the backend would have accepted. These+// are the ONLY legitimate reasons: every valid expression that lands in+// advanced-only must be explained by one of them, or it is a corner of the+// grammar the model could have handled and quietly does not. The closure test at+// the bottom enforces exactly that, which is what keeps this list honest — a+// reason nobody can state is a gap, not a decision.+const EXCLUSIONS: Array<{ why: string; holds: (spec: Spec, fields: string[]) => boolean }> = [+ {+ // Commas around nothing (","). robfig drops the empty elements and is left+ // with a field selecting no value at all — legal, and the schedule simply+ // never fires. The model has no empty set to hold that (the chips keep at+ // least one day), so it stays advanced, where the raw text survives and the+ // server preview says "no upcoming runs" — which is the honest answer.+ why: "a field that selects no value at all, so the schedule never fires",+ holds: (s) => [s.minute, s.hour, s.dom, s.month, s.dow].some((f) => f.values.size === 0),+ },+ {+ why: "minute is a list, a range, or a step anchored off zero — the model has no minute-offset slot",+ holds: (_s, f) => {+ const m = f[0]!.replace(/^\?(?=\/|$)/, "*");+ if (m === "*") return false;+ if (/^\d{1,2}$/.test(m)) return false;+ return !/^(\*|0)\/\d{1,2}$/.test(m);+ },+ },+ {+ // A bare hour with a step ("9/2") is NOT excluded: robfig reads it as 9-23/2,+ // which is a window the model holds — so only a genuine LIST is left here.+ why: "hour is a list",+ holds: (_s, f) => {+ const h = f[1]!.replace(/^\?(?=\/|$)/, "*");+ return !(+ h === "*" ||+ /^\d{1,2}$/.test(h) ||+ /^\d{1,2}-\d{1,2}(\/\d{1,2})?$/.test(h) ||+ /^\*\/\d{1,2}$/.test(h) ||+ /^\d{1,2}\/\d{1,2}$/.test(h)+ );+ },+ },+ {+ why: "a minute step and an hour step at once — the model's interval has one step dimension",+ holds: (_s, f) => {+ const m = f[0]!.replace(/^\?(?=\/|$)/, "*");+ const minuteStepped = m === "*" || /^(\*|0)\/\d{1,2}$/.test(m);+ const hourStep = /\/(\d{1,2})$/.exec(f[1]!);+ return minuteStepped && hourStep !== null && parseInt(hourStep[1]!, 10) !== 1;+ },+ },+ {+ why: "day-of-month is anything but a single day",+ holds: (_s, f) => !(f[2] === "*" || /^\d{1,2}$/.test(f[2]!)),+ },+ {+ why: "a pinned day-of-month beside a restricted day-of-week — cron ORs them, the model can only intersect",+ holds: (_s, f) => f[2] !== "*" && f[4] !== "*",+ },+ { why: "month is pinned", holds: (_s, f) => f[3] !== "*" },+ {+ // "TZ=Local 0 9 * * *": legal to LoadLocation — it means the SERVER host's+ // zone — but no browser zone, so the picker has no entry to show for it.+ // Extraction would put a name in a control that cannot hold it; verbatim+ // advanced keeps the schedule running exactly as written instead.+ why: "an embedded timezone the picker cannot offer",+ holds: (s) => s.tz !== null && canonicalPickerZone(s.tz) === null,+ },+];++// Four reasons used to sit at the end of that list — or would have needed a+// place on it — and no longer do, because the editor stopped needing them:+//+// "?" in any field — the backend reads it as a wildcard, and so does the editor+// now (normalizeField rewrites it to "*", which is what it means).+//+// A wildcard with an upper end ("*-19", "?-5") — the backend decides a range is+// the full span from its low end alone and never reads the rest, so these mean+// "*" too, and normalizeRange rewrites them to it. The editor echoes them into+// its controls and saves them back in the canonical form. This one was invisible+// until the reference stopped being tidier than robfig: while the oracle called+// them syntax errors, the closure check below had nothing to explain.+//+// A step wider than its own field ("*/65" on minutes, "*/24" on hours) — legal,+// degenerate, and selecting only the range's first value, so it means a fixed+// value, which the model has always had a slot for. The editor collapses it to+// that value rather than greying itself out over a schedule it understands.+//+// A list with a step-1 wildcard among its parts ("0,*", "1,*", "JAN,*") — robfig+// ORs a list's parts together, and the wildcard part spans the whole field with+// its star bit set, so the field means "*" outright, the AND-or-OR choice+// between dom and dow included. collapseWildcardList rewrites it to "*" — but+// only once every part is seen to parse, because "*,abc" and "*,60" are syntax+// errors to the server and must stay ones to the editor. This family never had+// an entry above: it was the gap a review found, in the corpus and the model at+// once, which is what the guard on wildcard-list forms up in the corpus test+// now keeps found.+//+// A `TZ=` / `CRON_TZ=` prefix naming a zone the picker could offer — the+// backend reads the zone off the front of the expression and lets it override+// the timezone column, so the editor extracts it into the timezone field+// (extractTimezonePrefix), where the picker shows it and the column becomes+// the one source of truth. The shapes it deliberately leaves verbatim — no+// space after the prefix (the robfig v3.0.1 panic), a second prefix behind+// the first — are server rejections, not model limits, so they need no entry+// above either; a zone the picker cannot hold ("TZ=Local") is the one prefix+// shape that IS a model limit, and has its entry in the list.+//+// All were refusals to normalize, not limits of the model — the difference this+// list exists to keep honest. What is left above is the model's actual shape: it+// holds one day rule, one time rule and one step, and every reason there names a+// schedule that needs more than that.++/** The fields an exclusion reasons about, written as what they MEAN rather than+ * as the punctuation they happen to carry — and the meaning comes from the+ * reference parser, not from the editor, so a clause can never explain away a+ * gap by agreeing with the code that made it.+ *+ * A field the reference reads as a wildcard is spelled "*", whatever it was+ * written as ("?", "*", "*\/1"). A field it reads as a single value is spelled+ * as that value, whatever it was written as ("09", "9-9", "*\/65" → "0"). The+ * rest keeps its text, with empty list elements dropped and numbers canonicalized+ * the way strings.FieldsFunc and strconv.Atoi drop and canonicalize them.+ *+ * Reading the raw text instead is how a stray comma sneaks past: "0," is the+ * single value 0, but to a clause that matches "anything which is not a plain+ * number" it reads as a list, and the closure check then explains away a real+ * gap with a reason that was never true. That is exactly how a fix normalizing+ * only day-of-week survived this suite — and "009" reading as "not a plain+ * number" is the same trap with digits instead of commas. */+function meaningfulFields(expr: string, spec: Spec): string[] {+ const fields = [spec.minute, spec.hour, spec.dom, spec.month, spec.dow];+ return expr+ .trim()+ .split(/\s+/)+ .map((field, i) => {+ const parsed = fields[i]!;+ if (parsed.star) return "*";+ if (parsed.values.size === 1) return String([...parsed.values][0]);+ return field+ .split(",")+ .filter((part) => part.length > 0)+ .map((part) =>+ part.replace(/\+?\d+/g, (num) => {+ const n = Number(num);+ return Number.isSafeInteger(n) ? String(n) : num;+ }),+ )+ .join(",");+ });+}++describe("cron grammar — the editor against a reference robfig parser", () => {+ it("covers every token form of every field", () => {+ // A guard on the corpus itself: if a future edit guts these lists, the+ // invariants below would still pass, vacuously.+ expect(CORPUS.length).toBeGreaterThan(10_000);+ expect(CORPUS.filter((e) => reference(e) !== null).length).toBeGreaterThan(3000);+ expect(CORPUS.filter((e) => reference(e) === null).length).toBeGreaterThan(3000);+ // Both dimensions must actually be crossed — the omission that let a mutant+ // dropping the day-of-month for interval times slip through.+ expect(CORPUS).toContain("0 */2 15 * *");+ expect(CORPUS).toContain("*/10 9-18 15 * *");+ expect(CORPUS).toContain("0 9-21/2 * * 1-5");+ // Atoi's lexical variance must be present in every field.+ expect(CORPUS).toContain("009 9 * * *");+ expect(CORPUS).toContain("0 9 * * +1");+ // As must the wildcard-low-end forms, in every field — the quirk the+ // reference above used to be tidier than.+ expect(CORPUS).toContain("*-30 9 * * *");+ expect(CORPUS).toContain("0 *-19 * * *");+ expect(CORPUS).toContain("0 9 *-15 * *");+ expect(CORPUS).toContain("0 9 * *-6 *");+ expect(CORPUS).toContain("0 9 * * ?-5");+ // Lists carrying a wildcard part, in every field — the family that once+ // slipped past the closure test below by not being in the corpus at all.+ expect(CORPUS).toContain("0,* 9 * * *");+ expect(CORPUS).toContain("0 9,* * * *");+ expect(CORPUS).toContain("0 9 1,* * *");+ expect(CORPUS).toContain("0 9 * 1,* *");+ expect(CORPUS).toContain("0 9 * * 1,*");+ expect(CORPUS).toContain("*,abc 9 * * *");+ // And the timezone prefix, in its accepted, misspelled and panic shapes.+ expect(CORPUS).toContain("TZ=UTC 0 9 * * *");+ expect(CORPUS).toContain("CRON_TZ=Asia/Tokyo 30 */3 * * 1-5");+ expect(CORPUS).toContain("TZ=Bogus/Zone 0 9 * * *");+ expect(CORPUS).toContain("TZ=UTC");+ expect(CORPUS).toContain("tz=UTC 0 9 * * *");+ });++ it("reads the timezone prefix the way the server does", () => {+ // The oracle's prefix claims, pinned the way the wildcard low end is below:+ // the zone is read up to the first literal space and overrides the timezone+ // column; a prefix with no space after it is refused (robfig v3.0.1 panics+ // there — parser.go:99 — and the server's guard turns it into a rejection);+ // the detection is case-sensitive and untrimmed; a second prefix is a field.+ expect(reference("TZ=UTC 0 9 * * *")).toMatchObject({ tz: "UTC", tzValid: true });+ expect(reference("CRON_TZ=Asia/Tokyo 0 9 * * *")).toMatchObject({ tz: "Asia/Tokyo" });+ expect(reference("TZ= 0 9 * * *")).toMatchObject({ tz: "UTC", tzValid: true });+ expect(reference("TZ=Bogus/Zone 0 9 * * *")).toMatchObject({ tzValid: false });+ expect(reference("TZ=UTC")).toBeNull();+ expect(reference("CRON_TZ=Asia/Tokyo")).toBeNull();+ expect(reference("TZ=")).toBeNull();+ expect(reference("tz=UTC 0 9 * * *")).toBeNull();+ expect(reference(" TZ=UTC 0 9 * * *")).toBeNull();+ expect(reference("TZ=UTC TZ=UTC 0 9 * * *")).toBeNull();+ });++ it("reads a wildcard's low end the way the server does", () => {+ // The oracle's own claim, pinned: robfig takes "*-19" for the full span and+ // never reads what came after the "-". If this ever stops being true of the+ // server, this is the test that says so — and the corpus below is judged+ // against a grammar that has drifted.+ expect(reference("0 *-19 * * *")?.hour.values.size).toBe(24);+ expect(reference("0 ?-19 * * *")?.hour.star).toBe(true);+ expect(reference("0 *-19-25 * * *")?.hour.values.size).toBe(24);+ expect([...(reference("0 *-19/2 * * *")?.hour.values ?? [])]).toEqual([+ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22,+ ]);+ // Only the LOW end: a "?" anywhere else is the syntax error it always was.+ expect(reference("0 9-? * * *")).toBeNull();+ });++ it("never throws, whatever it is handed", () => {+ for (const expr of CORPUS) {+ expect(() => parseCron(expr, "UTC"), expr).not.toThrow();+ }+ });++ it("never structures an expression whose fields the server cannot parse", () => {+ // The inverse is the dangerous one: a schedule the editor shows in its+ // controls, lets the user save, and the backend then refuses — or worse,+ // silently reinterprets.+ const wronglyAccepted = CORPUS.filter(+ (e) => reference(e) === null && parseCron(e, "UTC").raw === null,+ );+ expect(wronglyAccepted).toEqual([]);+ });++ it("keeps an embedded zone in the config, so the server still judges the pair", () => {+ // What extraction must never do is drop or replace the zone: that would+ // turn a rejected expression into an accepted schedule in a different+ // timezone. A zone the picker cannot hold ("TZ=Bogus/Zone", "TZ=Local")+ // is not extracted at all — the expression stays verbatim in `raw`, and+ // toCron passes a self-prefixed raw through untouched, so the zone still+ // reaches the server exactly as written.+ // A sentinel that matches no embedded zone, so extraction and mere+ // pass-through of the parameter cannot be mistaken for one another. Both+ // directions are pinned: everywhere the syntactic rule extracts, the config+ // carries that zone — and everywhere it must not (no space after the+ // prefix, a second prefix), the parameter comes through untouched.+ const wrongTz = CORPUS.filter((e) => {+ const p = extractedForEcho(e);+ return parseCron(e, "Test/Sentinel").timezone !== (p?.tz ?? "Test/Sentinel");+ });+ expect(wrongTz).toEqual([]);+ });++ it("never structures a config the model's own domain cannot hold", () => {+ // Semantic equivalence cannot see this class of bug: a config with an+ // hour interval of 24 serializes back to the same "*/24" it came from and+ // fires at the same instants — but model.ts bounds intervals (hours 1-23,+ // minutes 1-59) and the interval select renders nothing past them, so the+ // user gets a control showing an impossible value. Every structured field+ // is checked against the domain the model declares, not against cron.+ const validTime = (t: string) => /^([01]\d|2[0-3]):[0-5]\d$/.test(t);+ const outOfDomain: Array<{ expr: string; why: string }> = [];+ for (const expr of CORPUS) {+ const c = parseCron(expr, "UTC");+ if (c.raw !== null) continue;+ const bad = (why: string) => outOfDomain.push({ expr, why });+ const { time, days } = c;+ if (time.kind === "at") {+ if (!validTime(time.time)) bad("at-time malformed");+ } else {+ const maxInterval = time.unit === "hours" ? 23 : 59;+ if (!Number.isInteger(time.interval) || time.interval < 1 || time.interval > maxInterval) {+ bad(`interval ${time.interval} outside 1-${maxInterval}`);+ }+ if (!Number.isInteger(time.minute) || time.minute < 0 || time.minute > 59) {+ bad(`minute ${time.minute} outside 0-59`);+ }+ if (time.window !== null && (!validTime(time.window.from) || !validTime(time.window.to))) {+ bad("window malformed");+ }+ }+ if (days.kind === "weekly") {+ const chips = days.daysOfWeek;+ if (chips.length === 0) bad("weekly with no days");+ if (chips.some((d) => !Number.isInteger(d) || d < 0 || d > 6)) bad("day outside 0-6");+ const canonical = [...new Set(chips)].toSorted((a, b) => a - b);+ if (JSON.stringify(canonical) !== JSON.stringify(chips)) bad("days not deduped ascending");+ } else if (days.kind === "monthly") {+ if (!Number.isInteger(days.dayOfMonth) || days.dayOfMonth < 1 || days.dayOfMonth > 31) {+ bad(`dayOfMonth ${days.dayOfMonth} outside 1-31`);+ }+ }+ }+ expect(outOfDomain).toEqual([]);+ });++ it("preserves the schedule's meaning through every structurable round-trip", () => {+ // The heart of it: for everything the editor claims it can represent, the+ // PAIR it hands back — the cron AND the timezone, since an embedded zone+ // moves between them — must fire at exactly the same instants as the+ // expression it was given. Set equality over the whole domain, not a spot+ // check; the zone compared by name, since the fields are zone-relative.+ const drifted: Array<{ expr: string; became: string; tz: string }> = [];+ for (const expr of CORPUS) {+ const config = parseCron(expr, "UTC");+ if (config.raw !== null) continue;+ const before = reference(expr);+ const after = reference(toCron(config));+ if (+ before === null ||+ after === null ||+ !sameSchedule(before, after) ||+ config.timezone !== (before.tz ?? "UTC")+ ) {+ drifted.push({ expr, became: toCron(config), tz: config.timezone });+ }+ }+ expect(drifted).toEqual([]);+ });++ it("hands back an unrepresentable expression as it was written, minus only an extracted prefix", () => {+ // The prefix moves into the timezone field; everything else survives+ // verbatim. `raw` for a prefixed expression is the fields alone — saving+ // the pair (raw, timezone) is the same schedule the prefix spelled.+ const mangled = CORPUS.filter((e) => {+ const c = parseCron(e, "Test/Sentinel");+ if (c.raw === null) return false;+ const p = extractedForEcho(e);+ const expectedRaw = p === null ? e : p.rest;+ return c.raw !== expectedRaw || cronFields(c) !== expectedRaw;+ });+ expect(mangled).toEqual([]);+ });++ it("is idempotent: a second pass changes nothing", () => {+ // The second pass gets the pair the first one produced — the timezone is+ // part of the round-trip now that a prefix extracts into it.+ const unstable = CORPUS.filter((expr) => {+ const once = parseCron(expr, "UTC");+ const twice = parseCron(toCron(once), once.timezone);+ return JSON.stringify(twice) !== JSON.stringify(once);+ });+ expect(unstable).toEqual([]);+ });++ it("sends a valid expression to advanced-only for a documented reason, never by accident", () => {+ // An expression the backend accepts, that the editor nonetheless refuses to+ // show in its controls, and that none of the reasons in EXCLUSIONS explains,+ // is a corner of the grammar the model could have handled and quietly does+ // not — the user gets greyed-out controls and a raw-cron box for a schedule+ // that runs perfectly well. Enumerating the difference is what turns "did we+ // remember that shape?" from a question about someone's care into a+ // mechanical diff.+ const unexplained: string[] = [];+ for (const expr of CORPUS) {+ const spec = reference(expr);+ if (!serverAccepts(spec)) continue;+ if (parseCron(expr, "UTC").raw === null) continue;+ // The fields an exclusion reasons about are the BODY's — an extracted+ // prefix is not a field, and would shift all five off by one.+ if (!EXCLUSIONS.some((x) => x.holds(spec, meaningfulFields(spec.body, spec)))) {+ unexplained.push(expr);+ }+ }+ expect(unexplained).toEqual([]);+ });+});diff --git a/packages/views/autopilots/components/schedule-editor/cron-mapping.test.ts b/packages/views/autopilots/components/schedule-editor/cron-mapping.test.tsnew file mode 100644index 0000000000..a1c431f1de--- /dev/null+++ b/packages/views/autopilots/components/schedule-editor/cron-mapping.test.ts@@ -0,0 +1,895 @@+import { describe, it, expect } from "vitest";+import { cronFields, parseCron, toCron } from "./cron-mapping";+import type { ScheduleConfig } from "./model";+import { getDefaultScheduleConfig } from "./model";++// The backend accepts robfig/cron v3 5-field expressions (minute, hour, dom,+// month, dow — no seconds, no @descriptors, no L/W/#). The structured model+// echoes the subset its controls can express; everything else must come back as+// advanced-only with the original string preserved verbatim in `raw`.+//+// These cases pin the canonical FORM the editor writes back. The exhaustive+// check that the form still MEANS the same thing lives in cron-grammar.test.ts,+// which enumerates the grammar against a reference parser rather than against+// examples anyone had to think of.++const TZ = "Asia/Shanghai";++function structured(expr: string): ScheduleConfig {+ const parsed = parseCron(expr, TZ);+ expect(parsed.raw, `expected ${JSON.stringify(expr)} to be structurable`).toBeNull();+ return parsed;+}++describe("parseCron — structurable expressions", () => {+ it("parses a fixed daily time", () => {+ const p = structured("0 9 * * *");+ expect(p.time).toEqual({ kind: "at", time: "09:00" });+ expect(p.days).toEqual({ kind: "every" });+ expect(p.timezone).toBe(TZ);+ });++ it("parses zero-padded fields", () => {+ expect(structured("05 09 * * *").time).toEqual({ kind: "at", time: "09:05" });+ });++ it("parses the weekday preset shape", () => {+ const p = structured("30 18 * * 1-5");+ expect(p.time).toEqual({ kind: "at", time: "18:30" });+ expect(p.days).toEqual({ kind: "weekly", daysOfWeek: [1, 2, 3, 4, 5] });+ });++ it("tolerates surrounding and repeated whitespace", () => {+ expect(structured(" 0 9 * * * ").time).toEqual({ kind: "at", time: "09:00" });+ });++ // The backend drops empty list elements, so a stray comma leaves an ordinary+ // single value behind in EVERY field — not just day-of-week. Greying the editor+ // out on these would refuse a schedule the server runs perfectly happily.+ it.each([+ ["minute", "0, 9 * * *"],+ ["leading comma in minute", ",0 9 * * *"],+ ["hour", "0 9, * * *"],+ ["leading comma in hour", "0 ,9 * * *"],+ ])("reads through a stray comma in the %s field", (_label, expr) => {+ expect(structured(expr).time).toEqual({ kind: "at", time: "09:00" });+ });++ it("reads through a stray comma in the day-of-month field", () => {+ expect(structured("0 9 15, * *").days).toEqual({ kind: "monthly", dayOfMonth: 15 });+ });++ // "?" is a wildcard to the backend, in every field. Reading it as anything+ // else — or as nothing at all — greys the controls out over a schedule that is+ // simply "every day".+ it.each([+ ["minute", "? 10 * * *"],+ ["hour", "0 ? * * *"],+ ["day-of-month", "0 9 ? * 1-5"],+ ["day-of-week", "0 9 15 * ?"],+ ])("takes a question mark in the %s field as a wildcard", (_label, expr) => {+ expect(structured(expr).raw).toBeNull();+ });+ it("reads a question mark as the wildcard it is", () => {+ const p = structured("? 10 * * *");+ expect(p.time).toEqual({+ kind: "every",+ unit: "minutes",+ interval: 1,+ minute: 0,+ window: { from: "10:00", to: "10:59" },+ });+ expect(cronFields(p)).toBe("* 10 * * *");+ });++ // robfig decides a range is the field's full span from its LOW end alone and+ // never reads what followed the "-" (parser.go:261). So these are wildcards to+ // the parser that will run the schedule — every one of them is accepted, and+ // fires exactly as "*" does. The editor reads them the same way and saves them+ // back canonically; greying its controls out over them would be refusing an+ // expression that means "every hour".+ it.each([+ ["an upper end on a star", "0 *-19 * * *", "0 * * * *"],+ ["an upper end on a question mark", "0 ?-19 * * *", "0 * * * *"],+ ["a stepped wildcard range", "0 *-19/2 * * *", "0 */2 * * *"],+ ["the same in the minute field", "*-30/10 9 * * *", "*/10 9 * * *"],+ ["nonsense past the dash, which is never read", "0 *-abc * * *", "0 * * * *"],+ ["more dashes than a range may have", "0 *-10-20 * * *", "0 * * * *"],+ ["day-of-week", "0 9 * * ?-5", "0 9 * * *"],+ ["day-of-month", "0 9 *-15 * *", "0 9 * * *"],+ ])("reads a wildcard's unread upper end the way the server does: %s", (_label, expr, canonical) => {+ const p = structured(expr);+ expect(cronFields(p)).toBe(canonical);+ });++ // Only the low end. A "?" anywhere else is the syntax error it has always been,+ // and normalizing it would structure an expression the server rejects.+ it("leaves a question mark that is not a range's low end alone", () => {+ expect(parseCron("0 9-? * * *", TZ).raw).toBe("0 9-? * * *");+ });++ // robfig ORs a list's parts together, and a step-1 wildcard part spans the+ // whole field with its star bit set — so a list carrying one IS "*", in every+ // field, the AND-or-OR choice between dom and dow included. The parsers+ // enumerate lists only where the model can hold them (day-of-week), so without+ // the collapse a "0,*" minute greys the editor out over "every minute".+ it.each([+ ["minute", "0,* 9 * * *", "* 9 * * *"],+ ["minute, beside a stepped wildcard", "*,*/2 9 * * *", "* 9 * * *"],+ ["minute, spelled with a question mark", "?,15 9 * * *", "* 9 * * *"],+ ["minute, with an unread upper end", "0,*-30 9 * * *", "* 9 * * *"],+ ["hour", "0 9,* * * *", "0 * * * *"],+ ["day-of-month", "0 9 1,* * *", "0 9 * * *"],+ ["month", "0 9 * 1,* *", "0 9 * * *"],+ ["month, with the wildcard beside a name", "0 9 * JAN,* *", "0 9 * * *"],+ ["day-of-week", "0 9 * * 1,*", "0 9 * * *"],+ ])("collapses a list carrying a wildcard in the %s field", (_label, expr, canonical) => {+ expect(cronFields(structured(expr))).toBe(canonical);+ });++ // But only when every part parses: "*,abc" and "*,60" are syntax errors to+ // the server, and a collapse that read just the wildcard part would structure+ // an expression the server rejects.+ it.each([["*,abc 9 * * *"], ["*,60 9 * * *"], ["0 9 *,32 * *"], ["0 9 * FOO,* *"]])(+ "leaves a wildcard list with an unparseable part alone: %s",+ (expr) => {+ expect(parseCron(expr, TZ).raw).toBe(expr);+ },+ );++ // A range that selects one value IS that value, however it was written: a step+ // wider than its range never gets past the range's first value, and "5-5" is 5.+ // The server runs all of these; refusing them means telling the user the+ // controls cannot show a schedule they can show perfectly well.+ it.each([+ ["step wider than the minute field", "*/65 * * * *", "0 * * * *"],+ ["step wider than the hour field", "0 */24 * * *", "0 0 * * *"],+ ["step wider than its hour range", "0 10-20/30 * * *", "0 10 * * *"],+ ["step wider than the dom field", "0 9 */40 * *", "0 9 1 * *"],+ ["range of one value", "5-5 9 * * *", "5 9 * * *"],+ ["three-digit step", "*/100 * * * *", "0 * * * *"],+ ])("collapses a degenerate %s", (_label, expr, canonical) => {+ const p = structured(expr);+ expect(p.raw).toBeNull();+ expect(cronFields(p)).toBe(canonical);+ });++ // A step wider than the window it steps over never reaches the window's second+ // hour, so this fires at 09:00 alone. The hour is a range slot, though, so the+ // window the user set survives the round-trip instead of being flattened to a+ // fixed 09:00 — and the interval, 23, is inside what the control can hold.+ it("keeps an hour window whose step outruns it", () => {+ const p = structured("0 9-19/23 * * *");+ expect(p.time).toEqual({+ kind: "every",+ unit: "hours",+ interval: 23,+ minute: 0,+ window: { from: "09:00", to: "19:00" },+ });+ expect(cronFields(p)).toBe("0 9-19/23 * * *");+ });++ // The expression from the bug: minute */65 is 0, so this is the 14th of the+ // month, on the hour, between 10:00 and 20:59 — every control can hold it.+ it("structures a degenerate step across all three dimensions", () => {+ const p = structured("*/65 10-20 14 * *");+ expect(p.days).toEqual({ kind: "monthly", dayOfMonth: 14 });+ expect(p.time).toEqual({+ kind: "every",+ unit: "hours",+ interval: 1,+ minute: 0,+ window: { from: "10:00", to: "20:00" },+ });+ expect(cronFields(p)).toBe("0 10-20 14 * *");+ });++ it.each([+ ["0 * * * *", 1, 0],+ ["15 * * * *", 1, 15],+ ["0 */2 * * *", 2, 0],+ ["15 */3 * * *", 3, 15],+ ])("parses hourly-interval %s", (expr, interval, minute) => {+ expect(structured(expr).time).toEqual({+ kind: "every",+ unit: "hours",+ interval,+ minute,+ window: null,+ });+ });++ // An hour range that covers every hour of the day is all day. The model spells+ // all day exactly one way — window: null — so the two spellings of it cannot+ // come back as two different schedules.+ it.each([+ ["0 0-23 * * *", "hours", 1, 0],+ ["0 0-23/3 * * *", "hours", 3, 0],+ ["15 0-23/2 * * *", "hours", 2, 15],+ ["*/30 0-23 * * *", "minutes", 30, 0],+ ["*/30 0-23/1 * * *", "minutes", 30, 0],+ ])("reads an hour range that spans the day as all day: %s", (expr, unit, interval, minute) => {+ expect(structured(expr).time).toEqual({+ kind: "every",+ unit,+ interval,+ minute,+ window: null,+ });+ });++ it.each([+ ["0 9-21 * * *", 1, "09:00", "21:00", 0],+ ["30 9-21 * * *", 1, "09:30", "21:30", 30],+ ["0 9-21/2 * * *", 2, "09:00", "21:00", 0],+ ])("parses hour window %s", (expr, interval, from, to, minute) => {+ expect(structured(expr).time).toEqual({+ kind: "every",+ unit: "hours",+ interval,+ minute,+ window: { from, to },+ });+ });++ // A bare value carrying a step runs to the field's max. robfig reads "9/2" as+ // 9-23/2, which is exactly the window the editor writes back out — so it has to+ // reach the controls, not grey them out.+ it.each([+ ["0 9/2 * * *", 2, "09:00", "23:00", 0, "0 9-23/2 * * *"],+ ["30 9/1 * * *", 1, "09:30", "23:30", 30, "30 9-23 * * *"],+ // "0/2" is "0-23/2" — every hour of the day, which is all day, not a window+ // that happens to span it.+ ["0 0/2 * * *", 2, null, null, 0, "0 */2 * * *"],+ // "?" is the wildcard wherever a range may start, a step above it included.+ ["0 ?/2 * * *", 2, null, null, 0, "0 */2 * * *"],+ ])("reads a bare hour with a step as running to the field max: %s", (expr, interval, from, to, minute, back) => {+ const p = structured(expr);+ expect(p.time).toEqual({+ kind: "every",+ unit: "hours",+ interval,+ minute,+ window: from === null ? null : { from, to },+ });+ expect(cronFields(p)).toBe(back);+ });++ // The editor writes "9-9/3" itself, whenever a dragged window start meets its+ // end at interval 3. Collapsing it to a fixed time would fire at the same+ // instant and lose the interval, the unit and the window on reload.+ it.each([+ ["0 9-9 * * *", 1, "09:00", "09:00"],+ ["0 9-9/3 * * *", 3, "09:00", "09:00"],+ ["0 9-11/5 * * *", 5, "09:00", "11:00"],+ ["0 9-21/23 * * *", 23, "09:00", "21:00"],+ ])("keeps a degenerate hour window as a window: %s", (expr, interval, from, to) => {+ expect(structured(expr).time).toEqual({+ kind: "every",+ unit: "hours",+ interval,+ minute: 0,+ window: { from, to },+ });+ });++ // The minute-step branch reads the same degenerate hour range as the single+ // hour it selects — a one-hour window, not a second step dimension. Keeping the+ // stepped range for the hours branch (above) must not cost this one its window.+ it.each([+ ["*/5 9-9/3 * * *", 5, "09:00", "09:59"],+ ["*/10 9-21/23 * * *", 10, "09:00", "09:59"],+ ["*/10 9-9 * * *", 10, "09:00", "09:59"],+ ])("reads a degenerate stepped hour beside a minute step as a single-hour window: %s", (expr, interval, from, to) => {+ expect(structured(expr).time).toEqual({+ kind: "every",+ unit: "minutes",+ interval,+ minute: 0,+ window: { from, to },+ });+ });++ // A step past what the model's interval can carry has no window form left, so+ // it still collapses to the single value it selects.+ it.each([+ ["0 9-9/24 * * *", "09:00"],+ ["0 9-21/30 * * *", "09:00"],+ ["0 */24 * * *", "00:00"],+ ])("collapses an hour step past the model's bound to the value it selects: %s", (expr, time) => {+ expect(structured(expr).time).toEqual({ kind: "at", time });+ });++ // robfig puts no ceiling on a step. A step wider than the field it steps over+ // selects that field's first value and nothing else — which is a day set, and+ // the chips hold day sets. Day-of-week was the last parser still drawing its own+ // step bound (1-59) and greying the editor out over these.+ it.each([+ ["0 9 * * */100", [0]],+ ["0 9 * * 1-5/60", [1]],+ ["0 9 * * MON-FRI/60", [1]],+ ["0 9 * * */7", [0]],+ ])("reads a day-of-week step wider than the week: %s", (expr, daysOfWeek) => {+ expect(structured(expr).days).toEqual({ kind: "weekly", daysOfWeek });+ });++ // Every dimension at once: a stepped interval, a window, and a day set.+ it("parses a compound expression across all three dimensions", () => {+ const p = structured("0 9-21/2 * * 2-4");+ expect(p.time).toEqual({+ kind: "every",+ unit: "hours",+ interval: 2,+ minute: 0,+ window: { from: "09:00", to: "21:00" },+ });+ expect(p.days).toEqual({ kind: "weekly", daysOfWeek: [2, 3, 4] });+ });++ it.each([+ ["* * * * *", 1, null],+ ["*/10 * * * *", 10, null],+ ["0/5 * * * *", 5, null],+ ["*/10 9-18 * * *", 10, { from: "09:00", to: "18:59" }],+ ["* 9 * * *", 1, { from: "09:00", to: "09:59" }],+ ["*/15 9 * * *", 15, { from: "09:00", to: "09:59" }],+ ])("parses minute-interval %s", (expr, interval, window) => {+ expect(structured(expr).time).toEqual({+ kind: "every",+ unit: "minutes",+ interval,+ minute: 0,+ window,+ });+ });++ it.each([+ ["30 10 15 * *", { kind: "at", time: "10:30" }, 15],+ ["0 9 1 * *", { kind: "at", time: "09:00" }, 1],+ ["0 9 31 * *", { kind: "at", time: "09:00" }, 31],+ [+ "*/10 * 15 * *",+ { kind: "every", unit: "minutes", interval: 10, minute: 0, window: null },+ 15,+ ],+ ])("parses monthly %s", (expr, time, dayOfMonth) => {+ const p = structured(expr);+ expect(p.time).toEqual(time);+ expect(p.days).toEqual({ kind: "monthly", dayOfMonth });+ });++ it.each([+ ["0 9 * * 0", [0]],+ ["0 9 * * 6", [6]],+ ["0 9 * * 1,3,5", [1, 3, 5]],+ ["0 9 * * 5,1,5", [1, 5]],+ ["0 9 * * 0-6", [0, 1, 2, 3, 4, 5, 6]],+ ["0 9 * * MON", [1]],+ // The two ends of the name map: an off-by-one there moves the schedule by a+ // day, and every other named case sits in its interior.+ ["0 9 * * SUN", [0]],+ ["0 9 * * SAT", [6]],+ ["0 9 * * mon-fri", [1, 2, 3, 4, 5]],+ ["0 9 * * MON,WED", [1, 3]],+ ["0 9 * * */2", [0, 2, 4, 6]],+ ["0 9 * * 1-5/2", [1, 3, 5]],+ ["0 9 * * 1/2", [1, 3, 5]],+ ["0 9 * * MON/2", [1, 3, 5]],+ // A step wider than the week still enumerates — to the range's first day.+ ["0 9 * * */7", [0]],+ ["0 9 * * 1,3-5", [1, 3, 4, 5]],+ // The backend drops empty list elements, so a stray comma is Mon–Fri to it,+ // not a syntax error. Refusing it here would grey out the controls on a+ // schedule the server runs perfectly happily.+ ["0 9 * * 1-5,", [1, 2, 3, 4, 5]],+ ["0 9 * * 1,,5", [1, 5]],+ ["0 9 * * ,1,5", [1, 5]],+ ])("expands dow %s to chips %j", (expr, days) => {+ expect(structured(expr).days).toEqual({ kind: "weekly", daysOfWeek: days });+ });+});++describe("parseCron — advanced-only fallback", () => {+ it.each([+ // minute field+ ["minute range", "0-30 9 * * *"],+ ["minute list", "0,30 9 * * *"],+ ["minute anchored step", "15/5 * * * *"],+ ["minute out of range", "60 9 * * *"],+ ["negative minute", "-5 9 * * *"],+ ["overflowing minute", "99999999999999999999 9 * * *"],+ // hour field+ ["hour list", "0 9,12,15 * * *"],+ ["hour out of range", "0 24 * * *"],+ ["hour wraparound range", "0 21-9 * * *"],+ ["minute step with hour step", "*/10 */2 * * *"],+ // A wildcard minute is a step of 1 — still a minute-dimension step, so a+ // real hour step alongside it exceeds the single-step model all the same.+ ["every minute with hour step", "* */2 * * *"],+ ["minute step with stepped window", "*/10 9-18/2 * * *"],+ // Both wildcards, so both are read — and then there are two steps, which is+ // one more than the model's interval carries. A real limit, not a refusal to+ // normalize: the day-of-week "?/2" beside them is structured fine on its own.+ ["question-mark steps in both time fields", "?/2 ?/2 * * ?/2"],+ // dom / month+ ["dom list", "0 9 1,15 * *"],+ ["dom range", "0 9 1-15 * *"],+ ["dom step", "0 9 */2 * *"],+ ["dom zero", "0 9 0 * *"],+ ["dom out of range", "0 9 32 * *"],+ ["dom plus dow (cron OR semantics)", "0 9 15 * 1"],+ ["pinned month", "0 9 * 6 *"],+ ["month name", "0 9 * JAN *"],+ // dow+ ["dow out of range", "0 9 * * 7"],+ ["dow wraparound range", "0 9 * * 5-1"],+ // structure & unsupported grammar+ ["four fields", "0 9 * *"],+ ["six fields (seconds cron)", "0 0 9 * * *"],+ ["free text", "not a cron"],+ ["empty string", ""],+ ["whitespace only", " "],+ ["@daily descriptor", "@daily"],+ ["@every descriptor", "@every 1h"],+ ["L in dom", "0 9 L * *"],+ ["L in dow", "0 9 * * 5L"],+ ["hash nth-weekday", "0 9 * * 1#2"],+ ["W nearest-weekday", "0 9 15W * *"],+ ])("%s → raw preserved verbatim", (_label, expr) => {+ const p = parseCron(expr, TZ);+ expect(p.raw).toBe(expr);+ expect(p.timezone).toBe(TZ);+ });+});++describe("cronFields — the five-field serialization", () => {+ const base = getDefaultScheduleConfig(TZ);++ it.each<[string, ScheduleConfig, string]>([+ [+ "fixed daily time",+ { ...base, time: { kind: "at", time: "09:00" }, days: { kind: "every" } },+ "0 9 * * *",+ ],+ [+ "weekday range collapses",+ {+ ...base,+ time: { kind: "at", time: "18:30" },+ days: { kind: "weekly", daysOfWeek: [1, 2, 3, 4, 5] },+ },+ "30 18 * * 1-5",+ ],+ [+ "non-consecutive days stay a list",+ {+ ...base,+ time: { kind: "at", time: "09:00" },+ days: { kind: "weekly", daysOfWeek: [1, 3, 5] },+ },+ "0 9 * * 1,3,5",+ ],+ [+ "mixed runs and singletons",+ {+ ...base,+ time: { kind: "at", time: "09:00" },+ days: { kind: "weekly", daysOfWeek: [0, 1, 2, 4] },+ },+ "0 9 * * 0-2,4",+ ],+ [+ "flagship compound",+ {+ ...base,+ time: {+ kind: "every",+ unit: "hours",+ interval: 2,+ minute: 0,+ window: { from: "09:00", to: "21:00" },+ },+ days: { kind: "weekly", daysOfWeek: [2, 3, 4] },+ },+ "0 9-21/2 * * 2-4",+ ],+ [+ "hourly with minute offset",+ {+ ...base,+ time: { kind: "every", unit: "hours", interval: 1, minute: 15, window: null },+ days: { kind: "every" },+ },+ "15 * * * *",+ ],+ [+ "every N hours all day",+ {+ ...base,+ time: { kind: "every", unit: "hours", interval: 3, minute: 0, window: null },+ days: { kind: "every" },+ },+ "0 */3 * * *",+ ],+ [+ "hour window without step",+ {+ ...base,+ time: {+ kind: "every",+ unit: "hours",+ interval: 1,+ minute: 30,+ window: { from: "09:30", to: "21:30" },+ },+ days: { kind: "every" },+ },+ "30 9-21 * * *",+ ],+ [+ "minute interval with window",+ {+ ...base,+ time: {+ kind: "every",+ unit: "minutes",+ interval: 10,+ minute: 0,+ window: { from: "09:00", to: "18:59" },+ },+ days: { kind: "every" },+ },+ "*/10 9-18 * * *",+ ],+ [+ "minute interval single hour",+ {+ ...base,+ time: {+ kind: "every",+ unit: "minutes",+ interval: 15,+ minute: 0,+ window: { from: "09:00", to: "09:59" },+ },+ days: { kind: "every" },+ },+ "*/15 9 * * *",+ ],+ [+ "every minute",+ {+ ...base,+ time: { kind: "every", unit: "minutes", interval: 1, minute: 0, window: null },+ days: { kind: "every" },+ },+ "* * * * *",+ ],+ [+ "monthly fixed time",+ {+ ...base,+ time: { kind: "at", time: "10:30" },+ days: { kind: "monthly", dayOfMonth: 15 },+ },+ "30 10 15 * *",+ ],+ // The day dimension has to survive an interval time pattern. Every other+ // `every` case above pins days to "every day", where the day-of-month field+ // is legitimately `*` — so only these pin it down.+ [+ "hourly interval on a day of the month",+ {+ ...base,+ time: { kind: "every", unit: "hours", interval: 2, minute: 0, window: null },+ days: { kind: "monthly", dayOfMonth: 15 },+ },+ "0 */2 15 * *",+ ],+ [+ "windowed hourly interval on a day of the month",+ {+ ...base,+ time: {+ kind: "every",+ unit: "hours",+ interval: 2,+ minute: 30,+ window: { from: "09:30", to: "21:30" },+ },+ days: { kind: "monthly", dayOfMonth: 15 },+ },+ "30 9-21/2 15 * *",+ ],+ [+ "windowed minute interval on a day of the month",+ {+ ...base,+ time: {+ kind: "every",+ unit: "minutes",+ interval: 10,+ minute: 0,+ window: { from: "09:00", to: "18:59" },+ },+ days: { kind: "monthly", dayOfMonth: 1 },+ },+ "*/10 9-18 1 * *",+ ],+ [+ "the whole week selected stays an explicit range",+ {+ ...base,+ time: { kind: "at", time: "09:00" },+ days: { kind: "weekly", daysOfWeek: [0, 1, 2, 3, 4, 5, 6] },+ },+ "0 9 * * 0-6",+ ],+ ])("%s", (_label, cfg, expected) => {+ expect(cronFields(cfg)).toBe(expected);+ });++ it("returns raw verbatim in advanced mode", () => {+ expect(cronFields({ ...base, raw: "0 9 1,15 * *" })).toBe("0 9 1,15 * *");+ });++ it("serialises weekly with no days to Monday as a safety fallback", () => {+ expect(+ cronFields({+ ...base,+ time: { kind: "at", time: "09:00" },+ days: { kind: "weekly", daysOfWeek: [] },+ }),+ ).toBe("0 9 * * 1");+ });+});++describe("bidirectional invariants", () => {+ const base = getDefaultScheduleConfig(TZ);+ const CANONICAL = [+ "0 9 * * *",+ "30 18 * * 1-5",+ "15 * * * *",+ "0 */2 * * *",+ "30 9-21 * * *",+ "0 9-21/2 * * 2-4",+ "*/10 9-18 * * 1-5",+ "*/15 9 * * *",+ "30 10 15 * *",+ "* * * * *",+ "0 9 * * 1,3,5",+ "0 9 * * 0-2,4",+ // The day dimension crossed with an interval one — the pairing the toCron+ // table above pins, held to the round-trip standard too.+ "0 */2 15 * *",+ "30 9-21/2 15 * *",+ "*/10 9-18 1 * *",+ // Every weekday selected: a set, not a wildcard, and it must come back as one.+ "0 9 * * 0-6",+ // A window one hour wide. The editor produces it whenever a dragged start+ // meets the end, so parseCron has to take it back — at any interval, not+ // only at 1, or the step and the unit are gone on the way back.+ "0 9-9 * * *",+ "0 9-9/3 * * *",+ "59 23 * * *",+ ];++ it.each(CANONICAL)("canonical form %s survives a verbatim round-trip", (expr) => {+ expect(cronFields(parseCron(expr, TZ))).toBe(expr);+ });++ const NORMALIZING: Array<[string, string]> = [+ ["05 09 * * *", "5 9 * * *"],+ ["0/5 * * * *", "*/5 * * * *"],+ // A step of 1 selects every hour: it is the plain field spelled out, not a+ // second step dimension, so it stays structurable.+ ["*/10 */1 * * *", "*/10 * * * *"],+ // An hour range that spans the day is all day: the model holds that one way,+ // and the reset control cannot be lit on a window there is nothing to reset.+ ["*/10 0-23/1 * * *", "*/10 * * * *"],+ ["*/10 0-23 * * *", "*/10 * * * *"],+ ["0 0-23 * * *", "0 * * * *"],+ ["0 0-23/3 * * *", "0 */3 * * *"],+ ["15 0-23/2 * * 1-5", "15 */2 * * 1-5"],+ // A step of 1 inside a window keeps the window: dropping it would run the+ // schedule around the clock instead of inside 09:00–18:59.+ ["*/10 9-18/1 * * *", "*/10 9-18 * * *"],+ // The hours-unit twin of the same rule: the /1 is spelled-out syntax, the+ // window survives it.+ ["0 9-21/1 * * *", "0 9-21 * * *"],+ ["0 9 * * 5,1,5", "0 9 * * 1,5"],+ ["0 9 * * MON-FRI", "0 9 * * 1-5"],+ // Names at both ends of the map, spanning the whole week.+ ["0 9 * * sun-sat", "0 9 * * 0-6"],+ // A stray comma normalizes away rather than dragging the schedule into the+ // raw-cron box — in every field, not just day-of-week.+ ["0 9 * * 1-5,", "0 9 * * 1-5"],+ ["0 9 * * 1,,5", "0 9 * * 1,5"],+ ["0, 9 * * *", "0 9 * * *"],+ ["0 9, * * *", "0 9 * * *"],+ ["0 9 15, * *", "0 9 15 * *"],+ [",0 ,9 * * *", "0 9 * * *"],+ // The backend reads numbers with strconv.Atoi: leading zeros and plus+ // signs are the same value to it, in any field and any position.+ ["009 09 * * *", "9 9 * * *"],+ ["+30 14 * * *", "30 14 * * *"],+ ["00/05 9-18 * * *", "*/5 9-18 * * *"],+ ["0 09-021/02 * * *", "0 9-21/2 * * *"],+ ["0 9 015 * *", "0 9 15 * *"],+ ["0 9 * * 001", "0 9 * * 1"],+ ["0 9 * * MON-05", "0 9 * * 1-5"],+ // {0,2,4,6} has no consecutive run, so run-collapse keeps it a list.+ ["0 9 * * */2", "0 9 * * 0,2,4,6"],+ // A bare hour with a step is the range it stands for, written out.+ ["0 9/2 * * *", "0 9-23/2 * * *"],+ ["0 ?/2 * * *", "0 */2 * * *"],+ // A step past the model's interval bound has no window form left.+ ["0 9-9/24 * * *", "0 9 * * *"],+ ];++ it.each(NORMALIZING)("%s re-serialises to the semantically equal %s", (expr, normalized) => {+ expect(cronFields(parseCron(expr, TZ))).toBe(normalized);+ });++ it.each([...CANONICAL, ...NORMALIZING.map(([e]) => e)])(+ "parse ∘ toCron ∘ parse is idempotent for %s",+ (expr) => {+ const once = parseCron(expr, TZ);+ const twice = parseCron(toCron(once), TZ);+ expect(twice).toEqual(once);+ },+ );++ it("advanced expressions round-trip verbatim", () => {+ const p = parseCron("0 9 1,15 * *", TZ);+ expect(p.raw).toBe("0 9 1,15 * *");+ expect(cronFields(p)).toBe("0 9 1,15 * *");+ expect(parseCron(toCron(p), TZ)).toEqual(p);+ });++ // The other direction, and the one the grammar suite cannot see: it enumerates+ // cron STRINGS, so a config the editor can build, save, and fail to read back+ // is invisible to it. Every case here is a config the controls actually+ // produce — a dragged window collapsed onto a single hour is the one that was+ // coming back as a fixed time, interval and unit and window silently dropped.+ const EDITOR_CONFIGS: Array<[string, ScheduleConfig]> = [+ [+ "a window dragged shut at interval 3",+ { ...base, time: { kind: "every", unit: "hours", interval: 3, minute: 0, window: { from: "09:00", to: "09:00" } } },+ ],+ [+ // clampWindow keeps both ends on the firing minute, so this is the shape+ // the controls hand over — not a hand-written one.+ "the same window with a firing minute",+ { ...base, time: { kind: "every", unit: "hours", interval: 2, minute: 30, window: { from: "22:30", to: "22:30" } } },+ ],+ [+ "a minute-step window one hour wide",+ { ...base, time: { kind: "every", unit: "minutes", interval: 10, minute: 0, window: { from: "09:00", to: "09:59" } } },+ ],+ [+ // The widest window the controls can now hand over: one hour short of the+ // day, because a window that spans the day IS all day and the editor+ // commits it as such.+ "a window that stops one hour short of the day",+ { ...base, time: { kind: "every", unit: "hours", interval: 1, minute: 0, window: { from: "00:00", to: "22:00" } } },+ ],+ [+ "an all-day interval carrying a firing minute",+ { ...base, time: { kind: "every", unit: "hours", interval: 3, minute: 15, window: null } },+ ],+ ];++ it.each(EDITOR_CONFIGS)("a config the editor can build survives cron and comes back: %s", (_label, config) => {+ expect(parseCron(toCron(config), TZ)).toEqual(config);+ });+});++describe("toCron — the wire expression", () => {+ const base = getDefaultScheduleConfig(TZ);++ it("carries the timezone as a TZ= prefix on every serialization", () => {+ expect(toCron({ ...base, time: { kind: "at", time: "09:00" } })).toBe(+ "TZ=Asia/Shanghai 0 9 * * *",+ );+ expect(toCron({ ...base, raw: "0 9 1,15 * *" })).toBe("TZ=Asia/Shanghai 0 9 1,15 * *");+ });++ it("round-trips through parseCron with no timezone fallback needed", () => {+ const config = { ...base, time: { kind: "at", time: "09:00" } } as const;+ // "Test/Sentinel" would only surface if the fallback were consulted: the+ // wire form must carry the zone itself.+ expect(parseCron(toCron(config), "Test/Sentinel")).toEqual(config);+ });++ it("never stacks a second prefix on a raw that carries its own", () => {+ // A self-prefixed raw is a typed expression awaiting the server's verdict.+ // robfig strips ONE prefix and reads what follows as fields, so prefixing+ // it again would quietly change what the server judges.+ for (const raw of ["TZ=Local 0 9 * * *", "CRON_TZ=Bogus/Zone 0 9 * * *", "TZ=UTC"]) {+ expect(toCron({ ...base, raw })).toBe(raw);+ }+ });++ it("degrades to the bare fields when the zone could not ride in a prefix", () => {+ // robfig ends the zone name at the first space, so a spaced (or empty)+ // name cannot be embedded; the timezone column still covers these.+ expect(toCron({ ...base, timezone: "" })).toBe("0 9 * * *");+ expect(toCron({ ...base, timezone: "Bad Zone" })).toBe("0 9 * * *");+ });+});++describe("parseCron — timezone prefix extraction", () => {+ // robfig reads a `TZ=` / `CRON_TZ=` prefix off the expression and lets it+ // OVERRIDE the schedule's timezone column, so the editor extracts it into+ // the config's timezone — the picker shows the zone that actually governs+ // the schedule, and toCron writes it back as the prefix of the wire form:+ // the expression IS the pair (timezone, fields) in both directions.+ it("extracts TZ= into the timezone and structures the rest", () => {+ const p = parseCron("TZ=Asia/Tokyo 0 9 * * *", TZ);+ expect(p.raw).toBeNull();+ expect(p.timezone).toBe("Asia/Tokyo");+ expect(p.time).toEqual({ kind: "at", time: "09:00" });+ expect(toCron(p)).toBe("TZ=Asia/Tokyo 0 9 * * *");+ });++ it("extracts CRON_TZ= the same way, and re-serialises it as TZ=", () => {+ const p = parseCron("CRON_TZ=America/New_York 30 */3 * * 1-5", TZ);+ expect(p.raw).toBeNull();+ expect(p.timezone).toBe("America/New_York");+ expect(toCron(p)).toBe("TZ=America/New_York 30 */3 * * 1-5");+ });++ it("reads an empty zone as the UTC it loads as", () => {+ // LoadLocation("") is UTC server-side; the picker needs the name, not the+ // spelling.+ expect(parseCron("TZ= 0 9 * * *", TZ).timezone).toBe("UTC");+ });++ it("canonicalizes the zone's spelling to the one the picker's list uses", () => {+ // Intl reads names case-insensitively, so "asia/shanghai" is a real zone —+ // but seating that spelling in the config would show a duplicate beside+ // the list's own "Asia/Shanghai". The canonical name is also the only+ // spelling the server's LoadLocation loads on every platform; lowercase+ // works there only by the grace of a case-insensitive filesystem.+ expect(parseCron("TZ=asia/shanghai 0 9 * * *", "UTC").timezone).toBe("Asia/Shanghai");+ expect(parseCron("CRON_TZ=UTC 0 9 * * *", "Asia/Tokyo").timezone).toBe("UTC");+ });++ it("extracts over an advanced-only body too, stripping the prefix from raw", () => {+ // The zone must not stay buried in `raw`, where it would silently overrule+ // the picker: the pair (raw, timezone) is the schedule either way.+ const p = parseCron("TZ=Asia/Tokyo ?/2 ?/2 * * ?/2", TZ);+ expect(p.raw).toBe("?/2 ?/2 * * ?/2");+ expect(p.timezone).toBe("Asia/Tokyo");+ });++ it.each([+ // The picker cannot hold these zones — "Local" is legal server-side (the+ // SERVER host's zone) but no browser zone; the others fail LoadLocation+ // too. Extraction would put a name in a control that cannot offer it, so+ // the whole expression stays verbatim and keeps meaning what it meant.+ ["a zone only the server knows", "TZ=Local 0 9 * * *"],+ ["a zone nobody knows", "TZ=Bogus/Zone 0 9 * * *"],+ ["a tab-ridden zone", "TZ=UTC\t 0 9 * * *"],+ // robfig v3.0.1 panics on a prefix with no space after it (parser.go:99);+ // the server guards that into a rejection. Verbatim advanced is the only+ // honest echo.+ ["prefix without a schedule", "TZ=UTC"],+ ["CRON_TZ prefix without a schedule", "CRON_TZ=Asia/Tokyo"],+ ["bare TZ=", "TZ="],+ ["prefix with only trailing space", "TZ=UTC "],+ // robfig strips ONE prefix and reads the second as a field — a rejection+ // extraction would quietly turn into an accepted schedule.+ ["a second prefix behind the first", "TZ=UTC TZ=UTC 0 9 * * *"],+ ["a CRON_TZ prefix behind a TZ one", "TZ=UTC CRON_TZ=Asia/Tokyo 0 9 * * *"],+ // Not prefixes to robfig at all: detection is case-sensitive and untrimmed.+ ["lowercase tz=", "tz=UTC 0 9 * * *"],+ ["leading space before the prefix", " TZ=UTC 0 9 * * *"],+ ])("%s stays verbatim in advanced mode", (_label, expr) => {+ const p = parseCron(expr, TZ);+ expect(p.raw).toBe(expr);+ expect(p.timezone).toBe(TZ);+ });+});diff --git a/packages/views/autopilots/components/schedule-editor/cron-mapping.ts b/packages/views/autopilots/components/schedule-editor/cron-mapping.tsnew file mode 100644index 0000000000..d04c54b45c--- /dev/null+++ b/packages/views/autopilots/components/schedule-editor/cron-mapping.ts@@ -0,0 +1,551 @@+import type { DayPattern, ScheduleConfig, TimePattern } from "./model";+import { consecutiveRuns, getDefaultScheduleConfig, pad2, timeParts } from "./model";++// The backend parser (robfig/cron v3, 5-field) accepts a closed grammar per+// field: `*`, `?`, integers, month/day names, `-` ranges, `/` steps and `,`+// lists. The structured editor round-trips only the subset below; everything+// else stays verbatim in `raw` (advanced-only mode).++const DOW_NAMES: Record<string, number> = {+ SUN: 0,+ MON: 1,+ TUE: 2,+ WED: 3,+ THU: 4,+ FRI: 5,+ SAT: 6,+};++const MONTH_NAMES: Record<string, number> = {+ JAN: 1,+ FEB: 2,+ MAR: 3,+ APR: 4,+ MAY: 5,+ JUN: 6,+ JUL: 7,+ AUG: 8,+ SEP: 9,+ OCT: 10,+ NOV: 11,+ DEC: 12,+};++interface FieldBounds {+ min: number;+ max: number;+ names?: Record<string, number>;+}++const MINUTE: FieldBounds = { min: 0, max: 59 };+const HOUR: FieldBounds = { min: 0, max: 23 };+const DOM: FieldBounds = { min: 1, max: 31 };+const MONTH: FieldBounds = { min: 1, max: 12, names: MONTH_NAMES };+const DOW: FieldBounds = { min: 0, max: 6, names: DOW_NAMES };++/** One part of a field, as robfig's getRange reads it. */+interface RangePart {+ lo: number;+ hi: number;+ step: number;+ /** The range was written as a wildcard ("*", or the "?" normalizeField rewrites+ * to one) rather than spelled out. Not robfig's star BIT, which it clears for+ * any step above 1: that bit decides whether dom and dow are ANDed or ORed, and+ * parseCron settles that question on the field text before it gets here — it+ * structures a pinned day-of-month only when day-of-week is written "*". What+ * this flag carries is the text, because that is what the model echoes: an hour+ * written "*" is "all day", and one written "0-23" is a window that happens to+ * span it. */+ wildcard: boolean;+ /** A step was written, whatever its value. "*" and "*\/1" select the same+ * values but are not the same text, and the collapse rules turn on which. */+ stepped: boolean;+ /** The range was written with both ends ("9-21"), not as a bare value. */+ explicitRange: boolean;+}++function fieldValue(s: string, bounds: FieldBounds): number | null {+ const named = bounds.names?.[s.toUpperCase()];+ if (named !== undefined) return named;+ if (!/^\d+$/.test(s)) return null;+ const n = Number(s);+ // Numbers past the safe-integer range overflow the backend's Atoi and are a+ // syntax error to it; out-of-bounds ones are one to its bounds check.+ if (!Number.isSafeInteger(n) || n < bounds.min || n > bounds.max) return null;+ return n;+}++/**+ * `<range>` or `<range>/<step>`, where `<range>` is `*`, a value, or `lo-hi` —+ * the whole of robfig's per-part grammar, in one place. Fields differ only in+ * the bounds and names they pass in, never in what the grammar means: a bare+ * value carrying a step runs to the field's max ("9/2" on hours is 9-23/2).+ *+ * The step is deliberately unbounded here, as it is in robfig: a step wider than+ * the range it steps over is legal and simply selects that range's first value+ * ("*\/100" on days is Sunday). Callers whose model slot cannot hold a step that+ * wide reject it themselves — they know what they can hold; the grammar does not.+ */+function parseRangePart(part: string, bounds: FieldBounds): RangePart | null {+ const [rangeStr, stepStr, ...rest] = part.split("/");+ if (rest.length > 0 || !rangeStr) return null;++ let step = 1;+ if (stepStr !== undefined) {+ if (!/^\d+$/.test(stepStr)) return null;+ step = Number(stepStr);+ if (!Number.isSafeInteger(step) || step < 1) return null;+ }+ const stepped = stepStr !== undefined;++ // normalizeField has already rewritten every wildcard range to "*".+ if (rangeStr === "*") {+ return {+ lo: bounds.min,+ hi: bounds.max,+ step,+ wildcard: true,+ stepped,+ explicitRange: false,+ };+ }++ const [loStr, hiStr, ...restRange] = rangeStr.split("-");+ if (restRange.length > 0 || !loStr) return null;+ const lo = fieldValue(loStr, bounds);+ if (lo === null) return null;++ let hi: number;+ if (hiStr === undefined) {+ // A bare value runs to the field's max when it carries a step ("9/2" is+ // 9-23/2), and is just itself when it does not.+ hi = stepped ? bounds.max : lo;+ } else {+ const hiVal = fieldValue(hiStr, bounds);+ if (hiVal === null) return null;+ hi = hiVal;+ }+ if (hi < lo) return null;++ return { lo, hi, step, wildcard: false, stepped, explicitRange: hiStr !== undefined };+}++/** The whole field as one pinned value — "9", and nothing that merely selects a+ * single value by other means ("9-9", "*\/100"), which the collapse rewrites to+ * this shape first when the model has a slot for it. */+function plainValue(field: string, bounds: FieldBounds): number | null {+ const r = parseRangePart(field, bounds);+ if (r === null || r.wildcard || r.stepped || r.explicitRange) return null;+ return r.lo;+}++/** Expand a dow field into a sorted, deduped day set, or null when it falls+ * outside the echoable grammar. Digits, names, ranges, steps and lists are+ * all enumerable — dow is structurable whenever robfig would accept it, a step+ * wider than the week ("*\/100" → Sunday) included. */+function expandDow(field: string): number[] | null {+ const days = new Set<number>();+ // `field` arrives normalized (see normalizeField), so an empty part here is a+ // genuinely malformed expression, not a stray comma.+ for (const part of field.split(",")) {+ const r = parseRangePart(part, DOW);+ if (r === null) return null;+ for (let d = r.lo; d <= r.hi; d += r.step) days.add(d);+ }+ if (days.size === 0) return null;+ return Array.from(days).toSorted((a, b) => a - b);+}++/** Serialize a day set as maximal consecutive runs: [1,2,3,4,5] → "1-5",+ * [0,1,2,4] → "0-2,4", [0,2,4,6] → "0,2,4,6". Any pair is worth a range here —+ * "0-1" is shorter than "0,1". */+function dowFieldFromDays(days: number[]): string {+ return consecutiveRuns(days)+ .map(([lo, hi]) => (hi > lo ? `${lo}-${hi}` : `${lo}`))+ .join(",");+}++/** The hour as an interval and an optional window. The model's interval is an+ * hour count, so a step it cannot hold has no every-N-hours form — a degenerate+ * one is already a fixed value by then, rewritten by collapseDegenerateRange. */+function parseHourPattern(+ field: string,+): { interval: number; range: { lo: number; hi: number } | null } | null {+ const r = parseRangePart(field, HOUR);+ if (r === null || r.step > HOUR.max) return null;+ // "*" and "0-23" select the same hours, and the model holds all day exactly one+ // way — as the absence of a window. The editor's window is always on screen now,+ // so there is no toggle state left for the two spellings to differ in: a window+ // that spans the day would only leave the reset control lit on a schedule that+ // is already all day, and hand the same schedule two structured forms.+ const spansDay = r.wildcard || (r.lo === HOUR.min && r.hi === HOUR.max);+ return { interval: r.step, range: spansDay ? null : { lo: r.lo, hi: r.hi } };+}++/** `*` → 1, `*\/N` and `0/N` → N. Anchored steps ("15/5") would need a minute+ * offset the model does not carry, so they stay advanced-only. */+function parseMinuteInterval(field: string): number | null {+ const r = parseRangePart(field, MINUTE);+ if (r === null || r.explicitRange || r.step > MINUTE.max) return null;+ // The step must run from the top of the hour: "*/5" and "0/5" are the same set,+ // "15/5" is one the model has no offset slot for. A bare "0" is a fixed minute,+ // not an interval — but parseTimeFields reads that before it ever gets here.+ if (r.lo !== MINUTE.min) return null;+ if (!r.stepped && !r.wildcard) return null;+ return r.step;+}++function parseTimeFields(minuteField: string, hourField: string): TimePattern | null {+ const plainMinute = plainValue(minuteField, MINUTE);++ // Fixed minute: either a fixed time, or an every-N-hours pattern.+ if (plainMinute !== null) {+ const plainHour = plainValue(hourField, HOUR);+ if (plainHour !== null) {+ return { kind: "at", time: `${pad2(plainHour)}:${pad2(plainMinute)}` };+ }+ const hour = parseHourPattern(hourField);+ if (hour === null) return null;+ return {+ kind: "every",+ unit: "hours",+ interval: hour.interval,+ minute: plainMinute,+ window:+ hour.range === null+ ? null+ : {+ from: `${pad2(hour.range.lo)}:${pad2(plainMinute)}`,+ to: `${pad2(hour.range.hi)}:${pad2(plainMinute)}`,+ },+ };+ }++ // Wildcard/stepped minute: an every-N-minutes pattern with an hour-granular+ // window. The model carries a single step, so a real hour step cannot be+ // combined with a minute step — but a step of 1 selects every hour, which is+ // just the unstepped field written out ("*/1" ≡ "*").+ const interval = parseMinuteInterval(minuteField);+ if (interval === null) return null;+ let window: { from: string; to: string } | null;+ const hour = parseHourPattern(hourField);+ if (hour === null) return null;+ if (hour.range === null) {+ // An all-day hour field — "*/N", or the "0-23/N" that means the same — is a+ // second step dimension once its step is real; the model has one step.+ if (hour.interval !== 1) return null;+ window = null;+ } else {+ const { lo, hi } = hour.range;+ // A step wider than the range it steps over never gets past that range's+ // first hour, so it selects that hour alone — a one-hour window, not a+ // second step. "9-9/3" and "9-21/23" both mean 09:00–09:59 here.+ const selectsOneHour = hour.interval > hi - lo;+ if (!selectsOneHour && hour.interval !== 1) return null;+ window = { from: `${pad2(lo)}:00`, to: `${pad2(selectsOneHour ? lo : hi)}:59` };+ }+ return { kind: "every", unit: "minutes", interval, minute: 0, window };+}++/** The backend accepts three kinds of lexical variance the parsers below do not:+ * it splits list fields with strings.FieldsFunc, which DROPS empty elements+ * ("1-5," is Mon–Fri to it, ",9" is hour 9, "1,,5" is {Mon, Fri}), it parses+ * every number with strconv.Atoi, which takes leading zeros and a plus sign+ * ("009", "+9" and "00/05" are 9, 9 and 0/5 to it), and it decides a range is a+ * wildcard on its LOW END ALONE — see normalizeRange. Every field is normalized+ * here, once, before any of the parsers below see it: a parser left to remember+ * this rule itself would, when it forgets, grey out the whole editor on a+ * schedule the server runs perfectly happily. */+function normalizeField(field: string): string {+ return field+ .split(",")+ .filter((part) => part.length > 0)+ .map(normalizeRange)+ .map((part) =>+ part.replace(/\+?\d+/g, (num) => {+ // Numbers past the safe-integer range overflow Atoi and are a syntax+ // error server-side; left alone, the parsers reject them the same way.+ const n = Number(num);+ return Number.isSafeInteger(n) ? String(n) : num;+ }),+ )+ .join(",");+}++/** robfig tests a range's LOW END for "*" or "?" (parser.go:261) and, when it+ * matches, takes the whole range as the field's full span — never looking at+ * what followed the "-". So "?" is "*", and so are "*-19", "?-5" and even+ * "*-19-25": the upper end is not merely unchecked, it is unread. A step+ * survives ("?/2" is "*\/2", "*-19/2" is "*\/2" — the low end sets the span, the+ * step still walks it), and only the low end is rewritten here, so "9-?" stays+ * the syntax error it is to the server.+ *+ * Odd, and load-bearing: these are wildcards to the parser that will run the+ * schedule, so an editor that called them unrepresentable would grey out its+ * controls over an expression that means "every hour". */+function normalizeRange(part: string): string {+ const slash = part.indexOf("/");+ const range = slash === -1 ? part : part.slice(0, slash);+ const step = slash === -1 ? "" : part.slice(slash);+ const low = range.split("-")[0];+ return low === "*" || low === "?" ? `*${step}` : part;+}++/** A step wider than the range it steps over never gets past that range's first+ * value, so it means a fixed value: "*\/65" on minutes is 0, "*\/24" on hours is+ * 0, "10-20/30" is 10, "*\/40" on day-of-month is the 1st. The server runs all of+ * these happily, and a fixed value is something the model has always had a slot+ * for. Rewriting them as that value is what lets the controls take them; without+ * it the editor greys itself out over a schedule it fully understands, and tells+ * the user — untruthfully — that the controls cannot represent it.+ *+ * `rangeSlot` marks a field the model holds as a range rather than as a value:+ * hour, and only hour. Such a field is never collapsed while the parser can still+ * read it exactly — neither a stepless "9-9" (the one-hour window the editor+ * writes when a dragged window start meets its end) nor a stepped "9-9/3" (the+ * same window at interval 3) may come back as a fixed time, or the every/unit/+ * window controls the user set are silently discarded on reload. Only a step past+ * what the model's interval can hold (> max) still collapses there, since+ * parseHourPattern would refuse it and the expression would grey the editor out+ * instead. Minute and day-of-month hold a value and not a range, so they collapse+ * in every form, "5-5" included.+ *+ * Safe on day-of-month, where the star bit decides whether dom and dow are ORed+ * or ANDed: robfig clears that bit for any step above 1 (parser.go:297), so+ * "*\/40" is already a restricted field, and "1" is another — the collapse cannot+ * flip "the 1st, or any Monday" into "the 1st, if it is a Monday". Month is left+ * alone: any pinned month is beyond the model regardless. */+function collapseDegenerateRange(+ field: string,+ bounds: FieldBounds,+ rangeSlot: boolean,+): string {+ return field+ .split(",")+ .map((part) => {+ const r = parseRangePart(part, bounds);+ // Not the grammar's shape at all: leave it be, and let the field's own+ // parser refuse it and send the expression to advanced-only.+ if (r === null) return part;+ // A range-slot field keeps every range its parser can still read exactly:+ // stepless ("9-9"), and stepped within the model's interval ("9-9/3").+ if (rangeSlot && !r.stepped) return part;+ if (rangeSlot && r.explicitRange && r.step <= bounds.max) return part;+ return r.step > r.hi - r.lo ? String(r.lo) : part;+ })+ .join(",");+}++/** A list with a step-1 wildcard element among its parts selects every value+ * the field has, star bit included: robfig ORs a list's parts together, the+ * wildcard part already spans the field, and a step of 1 is what keeps its+ * star bit set (parser.go:297) — so "1,*" IS "*", right down to the AND-or-OR+ * choice that bit drives between dom and dow. The parsers below read lists+ * only where the model enumerates them (day-of-week), so without this rewrite+ * a "0,*" minute greys the whole editor out over a schedule that means+ * "every minute".+ *+ * Collapsed only when EVERY part parses: "*,abc" and "*,60" are syntax errors+ * to the server, and a collapse that read just the wildcard part would+ * structure an expression the server rejects. A list whose wildcard parts all+ * carry real steps ("*\/2,*\/3") spans nothing by itself and is left for the+ * field's own parser to judge. */+function collapseWildcardList(field: string, bounds: FieldBounds): string {+ const parts = field.split(",");+ if (parts.length < 2) return field;+ const ranges = parts.map((part) => parseRangePart(part, bounds));+ if (ranges.some((r) => r === null)) return field;+ return ranges.some((r) => r!.wildcard && r!.step === 1) ? "*" : field;+}++/** The two prefixes robfig's Parse reads a timezone from. */+export function hasTimezonePrefix(s: string): boolean {+ return s.startsWith("TZ=") || s.startsWith("CRON_TZ=");+}++/** robfig's Parse reads an optional `TZ=` / `CRON_TZ=` prefix off the+ * expression before the fields — case-sensitively, on the untrimmed text, up+ * to the FIRST LITERAL SPACE (parser.go, `strings.Index(spec, " ")`) — and the+ * embedded zone then overrides the schedule's own timezone column: both go+ * through the same LoadLocation, so `CRON_TZ=Asia/Tokyo 0 9 * * *` with the+ * column at UTC fires at 09:00 Tokyo. A prefixed expression IS the pair+ * (timezone, fields), and extracting it into the editor's timezone field is+ * exact — it is what keeps the timezone picker truthful over an expression+ * that would otherwise silently overrule it.+ *+ * Null when there is nothing robfig would read as a prefix, and for the shapes+ * it would read but the editor must not touch:+ * - no space at all ("TZ=UTC"): robfig v3.0.1 panics on it (parser.go:99), so+ * it stays verbatim in advanced, where the server (guarded) calls it invalid;+ * - a second prefix right behind the first: robfig strips ONE prefix and reads+ * the second as a field, so extraction would quietly turn a rejected+ * expression into an accepted one;+ * - a zone the picker could not have offered (isPickerZone). config.timezone+ * is a picker value and a formatter argument, so only names the browser can+ * hold there are extracted. "TZ=Local 0 9 * * *" — legal server-side, where+ * it means the SERVER host's zone — stays verbatim in advanced and keeps+ * running exactly as written; so does a zone the server would reject, whose+ * honest echo is the raw text under the server's own error. */+export function extractTimezonePrefix(expr: string): { timezone: string; rest: string } | null {+ if (!hasTimezonePrefix(expr)) return null;+ const space = expr.indexOf(" ");+ if (space === -1) return null;+ const name = expr.slice(expr.indexOf("=") + 1, space);+ const rest = expr.slice(space).trim();+ if (rest.length === 0) return null;+ if (hasTimezonePrefix(rest)) return null;+ // An empty name loads as UTC server-side (LoadLocation("")); say so.+ const timezone = canonicalPickerZone(name === "" ? "UTC" : name);+ if (timezone === null) return null;+ return { timezone, rest };+}++/** The zone as the picker's list spells it, or null when the browser cannot+ * hold it at all — as the picker's value or as an Intl formatter argument.+ * Intl reads zone names case-insensitively, so "asia/shanghai" is a real zone+ * to it; putting THAT spelling in the config would seat a duplicate next to+ * the list's own "Asia/Shanghai" entry. resolvedOptions canonicalizes the+ * name, which is also the spelling the server's LoadLocation is guaranteed to+ * load — lowercase only ever worked there by the grace of a case-insensitive+ * filesystem. Where the browser and the server genuinely part ways ("Local",+ * tab-ridden garbage), the browser is the authority here, because+ * config.timezone is a browser-side value. */+function canonicalPickerZone(tz: string): string | null {+ try {+ return new Intl.DateTimeFormat(undefined, { timeZone: tz }).resolvedOptions().timeZone;+ } catch {+ return null;+ }+}++export function parseCron(expr: string, timezone: string): ScheduleConfig {+ // The prefix is extracted whether or not the rest is structurable: the zone+ // rides in `timezone` either way, and `raw` keeps only the fields. This is+ // the inverse of toCron, which puts the prefix back on the way out — and it+ // also hydrates legacy rows saved before expressions carried one, for which+ // the caller passes the timezone column as the fallback.+ const prefix = extractTimezonePrefix(expr);+ const tz = prefix === null ? timezone : prefix.timezone;+ const body = prefix === null ? expr : prefix.rest;+ const advanced: ScheduleConfig = {+ ...getDefaultScheduleConfig(tz),+ raw: body,+ };+ const parts = body.trim().split(/\s+/);+ if (parts.length !== 5) return advanced;+ const [rawMinute, rawHour, rawDom, rawMonth, rawDow] = parts.map(normalizeField) as [+ string,+ string,+ string,+ string,+ string,+ ];+ const minuteField = collapseDegenerateRange(collapseWildcardList(rawMinute, MINUTE), MINUTE, false);+ const hourField = collapseDegenerateRange(collapseWildcardList(rawHour, HOUR), HOUR, true);+ const domField = collapseDegenerateRange(collapseWildcardList(rawDom, DOM), DOM, false);+ const monthField = collapseWildcardList(rawMonth, MONTH);+ const dowField = collapseWildcardList(rawDow, DOW);++ if (monthField !== "*") return advanced;++ let days: DayPattern;+ if (domField === "*") {+ if (dowField === "*") {+ days = { kind: "every" };+ } else {+ const daysOfWeek = expandDow(dowField);+ if (daysOfWeek === null) return advanced;+ days = { kind: "weekly", daysOfWeek };+ }+ } else {+ // A pinned day-of-month is only structurable when dow is unrestricted:+ // cron treats dom+dow as OR, which the model cannot express.+ if (dowField !== "*") return advanced;+ const dayOfMonth = plainValue(domField, DOM);+ if (dayOfMonth === null) return advanced;+ days = { kind: "monthly", dayOfMonth };+ }++ const time = parseTimeFields(minuteField, hourField);+ if (time === null) return advanced;++ return { time, days, timezone: tz, raw: null };+}++/** The wire expression: the timezone rides IN the cron string, as a `TZ=`+ * prefix, on every save and every preview. robfig reads an embedded zone+ * before the schedule's own timezone column, so a bare expression next to the+ * column is two sources of truth with a silent override rule between them —+ * prefixing unconditionally leaves exactly one. The column is still written,+ * as a mirror: display surfaces and the preview endpoint's invalid_timezone+ * classification read it, and it always agrees with the prefix.+ *+ * The one shape that is NOT prefixed is an advanced `raw` that already starts+ * with a prefix of its own: that is a typed expression awaiting the server's+ * verdict (see applyDraft), and stacking a second prefix on it would make+ * robfig read the first as the zone and the second as a field. It goes out+ * verbatim — the embedded zone wins server-side, which is what the text says. */+export function toCron(config: ScheduleConfig): string {+ const fields = cronFields(config);+ if (hasTimezonePrefix(fields)) return fields;+ // Leading/trailing whitespace would not survive the prefix — robfig (and+ // parseCron) trim the text after the zone, so prefixing would silently edit+ // the very characters that make such an expression the rejection it is —+ // and an empty expression has nothing to put one on.+ if (fields === "" || fields !== fields.trim()) return fields;+ // A zone name with a space in it would end at that space to robfig and hand+ // the remainder to the field parser. IANA names never contain one (the picker+ // could not have offered it), so this only guards a corrupt config — which+ // degrades to the bare expression the timezone column already covers.+ if (config.timezone === "" || config.timezone.includes(" ")) return fields;+ return `TZ=${config.timezone} ${fields}`;+}++/** The schedule's five fields alone — the editable text of the cron box, whose+ * `TZ=` prefix is a fixed group-input segment drawn from config.timezone, not+ * characters in the field. Advanced expressions round-trip verbatim here. */+export function cronFields(config: ScheduleConfig): string {+ if (config.raw !== null) return config.raw;++ let dom = "*";+ let dow = "*";+ if (config.days.kind === "monthly") {+ dom = String(config.days.dayOfMonth);+ } else if (config.days.kind === "weekly") {+ // The editor keeps at least one day selected; serialize defensively to+ // Monday rather than emit an empty field.+ dow = config.days.daysOfWeek.length > 0 ? dowFieldFromDays(config.days.daysOfWeek) : "1";+ }++ const { time } = config;+ let minuteField: string;+ let hourField: string;+ if (time.kind === "at") {+ const at = timeParts(time.time);+ minuteField = String(at.minute);+ hourField = String(at.hour);+ } else if (time.unit === "hours") {+ if (time.window === null) {+ minuteField = String(time.minute);+ hourField = time.interval === 1 ? "*" : `*/${time.interval}`;+ } else {+ const from = timeParts(time.window.from);+ const to = timeParts(time.window.to);+ minuteField = String(from.minute);+ hourField =+ time.interval === 1+ ? `${from.hour}-${to.hour}`+ : `${from.hour}-${to.hour}/${time.interval}`;+ }+ } else {+ minuteField = time.interval === 1 ? "*" : `*/${time.interval}`;+ if (time.window === null) {+ hourField = "*";+ } else {+ const from = timeParts(time.window.from);+ const to = timeParts(time.window.to);+ hourField = from.hour === to.hour ? String(from.hour) : `${from.hour}-${to.hour}`;+ }+ }+ return `${minuteField} ${hourField} ${dom} * ${dow}`;+}diff --git a/packages/views/autopilots/components/schedule-editor/describe.test.ts b/packages/views/autopilots/components/schedule-editor/describe.test.tsnew file mode 100644index 0000000000..e501979263--- /dev/null+++ b/packages/views/autopilots/components/schedule-editor/describe.test.ts@@ -0,0 +1,69 @@+import { describe, expect, it } from "vitest";+import type { TFunction } from "i18next";+import { createI18n } from "@multica/core/i18n/react";+import enAutopilots from "../../../locales/en/autopilots.json";+import zhAutopilots from "../../../locales/zh-Hans/autopilots.json";+import { describeSchedule } from "./describe";+import { parseCron } from "./cron-mapping";+import { getDefaultScheduleConfig } from "./model";++// The description is the editor's plain-language readback of the structured+// model. Advanced-only expressions have no structured model to describe, so+// they render as the raw cron plus the server preview instead.++const TZ = "UTC";++function fixedT(+ locale: "en" | "zh-Hans",+ resources: Record<string, unknown>,+): TFunction<"autopilots"> {+ const i18n = createI18n(locale, { [locale]: { autopilots: resources } });+ return i18n.getFixedT(locale, "autopilots") as TFunction<"autopilots">;+}++describe("describeSchedule (en)", () => {+ const t = fixedT("en", enAutopilots);+ const describeExpr = (expr: string) => describeSchedule(t, parseCron(expr, TZ));++ // Clause order mirrors the editor's fields, top to bottom: time (with its+ // window, which belongs to the same dimension), then days.+ it.each([+ ["0 9 * * *", "At 09:00 · Every day"],+ ["30 18 * * 1-5", "At 18:30 · Mon–Fri"],+ ["0 9 * * 1,3,5", "At 09:00 · Mon, Wed, Fri"],+ ["15 * * * *", "Every hour at :15 · Every day"],+ ["0 */2 * * *", "Every 2 hours at :00 · Every day"],+ ["0 9-21/2 * * 2-4", "Every 2 hours · 09:00–21:00 · Tue–Thu"],+ ["30 9-21 * * *", "Every hour · 09:30–21:30 · Every day"],+ ["*/10 9-18 * * 1-5", "Every 10 minutes · 09:00–18:59 · Mon–Fri"],+ ["* * * * *", "Every minute · Every day"],+ ["30 10 15 * *", "At 10:30 · Day 15 of the month"],+ ])("%s → %s", (expr, expected) => {+ expect(describeExpr(expr)).toBe(expected);+ });++ it("returns null for advanced-only configs", () => {+ expect(describeExpr("0 9 1,15 * *")).toBeNull();+ expect(describeSchedule(t, { ...getDefaultScheduleConfig(TZ), raw: "@daily" })).toBeNull();+ });++ it("leaves no unresolved interpolation placeholders", () => {+ for (const expr of ["0 9-21/2 * * 2-4", "15 * * * *", "30 10 15 * *"]) {+ expect(describeExpr(expr)).not.toContain("{{");+ }+ });+});++describe("describeSchedule (zh-Hans)", () => {+ const t = fixedT("zh-Hans", zhAutopilots);+ const describeExpr = (expr: string) => describeSchedule(t, parseCron(expr, TZ));++ it.each([+ ["0 9 * * *", "09:00 · 每天"],+ ["0 9-21/2 * * 2-4", "每 2 小时 · 09:00–21:00 · 周二至周四"],+ ["0 9 * * 1,3,5", "09:00 · 周一、周三、周五"],+ ["30 10 15 * *", "10:30 · 每月 15 日"],+ ])("%s → %s", (expr, expected) => {+ expect(describeExpr(expr)).toBe(expected);+ });+});diff --git a/packages/views/autopilots/components/schedule-editor/describe.ts b/packages/views/autopilots/components/schedule-editor/describe.tsnew file mode 100644index 0000000000..e6898714c8--- /dev/null+++ b/packages/views/autopilots/components/schedule-editor/describe.ts@@ -0,0 +1,98 @@+import { useCallback } from "react";+import { useT } from "../../../i18n";+import type { ScheduleConfig } from "./model";+import { consecutiveRuns, DAY_KEYS, pad2 } from "./model";++type AutopilotsT = ReturnType<typeof useT<"autopilots">>["t"];++/** Collapse runs of 3+ consecutive days into a range ("Mon–Fri"), list the rest.+ * A run of two stays a list: "Mon–Tue" is no shorter to read than "Mon, Tue". */+function formatDayList(t: AutopilotsT, days: number[]): string {+ const name = (d: number) => t(($) => $.schedule_editor.describe.days_long[DAY_KEYS[d]!]);+ const parts: string[] = [];+ for (const [lo, hi] of consecutiveRuns(days)) {+ if (hi - lo >= 2) {+ parts.push(+ t(($) => $.schedule_editor.describe.days_range, { from: name(lo), to: name(hi) }),+ );+ } else {+ for (let d = lo; d <= hi; d++) parts.push(name(d));+ }+ }+ return parts.join(t(($) => $.schedule_editor.describe.days_join));+}++/** Plain-language readback of a structured schedule. Returns null in+ * advanced-only mode, where there is no structured model to describe. */+export function describeSchedule(t: AutopilotsT, config: ScheduleConfig): string | null {+ if (config.raw !== null) return null;++ // Clause order follows the editor's own fields, top to bottom: time (step and+ // its window are one dimension, so they stay adjacent), then days.+ const clauses: string[] = [];+ const { time } = config;+ if (time.kind === "at") {+ clauses.push(t(($) => $.schedule_editor.describe.time_at, { time: time.time }));+ } else if (time.unit === "hours") {+ if (time.window === null) {+ const minute = pad2(time.minute);+ clauses.push(+ time.interval === 1+ ? t(($) => $.schedule_editor.describe.time_every_hour, { minute })+ : t(($) => $.schedule_editor.describe.time_every_hours, {+ interval: time.interval,+ minute,+ }),+ );+ } else {+ clauses.push(+ time.interval === 1+ ? t(($) => $.schedule_editor.describe.time_every_hour_window)+ : t(($) => $.schedule_editor.describe.time_every_hours_window, {+ interval: time.interval,+ }),+ );+ clauses.push(+ t(($) => $.schedule_editor.describe.window, {+ from: time.window.from,+ to: time.window.to,+ }),+ );+ }+ } else {+ clauses.push(+ time.interval === 1+ ? t(($) => $.schedule_editor.describe.time_every_minute)+ : t(($) => $.schedule_editor.describe.time_every_minutes, { interval: time.interval }),+ );+ if (time.window !== null) {+ clauses.push(+ t(($) => $.schedule_editor.describe.window, {+ from: time.window.from,+ to: time.window.to,+ }),+ );+ }+ }++ switch (config.days.kind) {+ case "every":+ clauses.push(t(($) => $.schedule_editor.describe.days_every));+ break;+ case "weekly":+ clauses.push(formatDayList(t, config.days.daysOfWeek));+ break;+ case "monthly":+ clauses.push(+ t(($) => $.schedule_editor.describe.days_monthly, { day: config.days.dayOfMonth }),+ );+ break;+ }++ return clauses.join(" · ");+}++export function useDescribeSchedule(): (config: ScheduleConfig) => string | null {+ const { t } = useT("autopilots");+ return useCallback((config: ScheduleConfig) => describeSchedule(t, config), [t]);+}diff --git a/packages/views/autopilots/components/schedule-editor/model.ts b/packages/views/autopilots/components/schedule-editor/model.tsnew file mode 100644index 0000000000..44280d8594--- /dev/null+++ b/packages/views/autopilots/components/schedule-editor/model.ts@@ -0,0 +1,73 @@+export type TimePattern =+ | { kind: "at"; time: string } // "HH:MM"+ | {+ kind: "every";+ interval: number; // hours: 1-23, minutes: 1-59+ unit: "minutes" | "hours";+ // null = all day. For "hours" the window's from-minute is the firing+ // minute and `to` carries the same minute; for "minutes" the window is+ // hour-granular (from :00 to :59).+ window: { from: string; to: string } | null;+ // Firing minute for "hours" patterns ("every N hours at :M"), kept in+ // sync with window.from's minute when a window is set. Carried but+ // unused for "minutes" patterns (toCron ignores it there) so toggling+ // the unit back and forth does not discard the user's minute.+ minute: number;+ };++export type DayPattern =+ | { kind: "every" }+ | { kind: "weekly"; daysOfWeek: number[] } // 0=Sun … 6=Sat, non-empty, deduped, ascending+ | { kind: "monthly"; dayOfMonth: number }; // 1-31++export interface ScheduleConfig {+ time: TimePattern;+ days: DayPattern;+ timezone: string; // IANA+ // Non-null when the expression exceeds the structured model: the editor is+ // in advanced-only mode and this exact string round-trips verbatim.+ raw: string | null;+}++// Timezone lists live in views/common/timezone-select (browserTimezone /+// timezoneOptions) — the caller passes the resolved zone in so this module+// stays free of platform lookups.+export function getDefaultScheduleConfig(timezone: string): ScheduleConfig {+ return {+ time: { kind: "at", time: "09:00" },+ days: { kind: "every" },+ timezone,+ raw: null,+ };+}++// Position is the cron day-of-week number, so this order is load-bearing: it+// indexes the locale's day names AND is what `daysOfWeek` holds.+export const DAY_KEYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"] as const;++/** The maximal runs of consecutive days in an ascending set: [1,2,3,4,5] → one+ * run 1–5, [0,1,2,4] → 0–2 and 4–4. What counts as a run worth collapsing is the+ * caller's to decide — cron collapses any pair ("0-1"), the readback wants three+ * before it says "Mon–Wed" — but where the runs ARE is one question with one+ * answer, and both callers used to scan for them separately. */+export function consecutiveRuns(days: number[]): Array<[number, number]> {+ const sorted = Array.from(new Set(days)).toSorted((a, b) => a - b);+ const runs: Array<[number, number]> = [];+ let i = 0;+ while (i < sorted.length) {+ let j = i;+ while (j + 1 < sorted.length && sorted[j + 1] === sorted[j]! + 1) j++;+ runs.push([sorted[i]!, sorted[j]!]);+ i = j + 1;+ }+ return runs;+}++export function pad2(n: number): string {+ return String(n).padStart(2, "0");+}++export function timeParts(time: string): { hour: number; minute: number } {+ const [h, m] = time.split(":");+ return { hour: parseInt(h ?? "0", 10), minute: parseInt(m ?? "0", 10) };+}diff --git a/packages/views/autopilots/components/schedule-editor/schedule-editor.test.tsx b/packages/views/autopilots/components/schedule-editor/schedule-editor.test.tsxnew file mode 100644index 0000000000..a3cea6ea55--- /dev/null+++ b/packages/views/autopilots/components/schedule-editor/schedule-editor.test.tsx@@ -0,0 +1,1396 @@+import { useState } from "react";+import { describe, it, expect, vi } from "vitest";+import { screen, waitFor, fireEvent } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { ApiError } from "@multica/core/api";+import type { SupportedLocale } from "@multica/core/i18n";+import { renderWithI18n } from "../../../test/i18n";+import { ScheduleEditor } from "./schedule-editor";+import type { ScheduleConfig } from "./model";+import { getDefaultScheduleConfig } from "./model";+import { cronFields, parseCron, toCron } from "./cron-mapping";++// The heaviest interaction cases drive several async userEvent steps through+// Base UI dropdowns; fast locally, but a loaded CI runner can push a single one+// past the default 5s cap. Raise the ceiling without slowing the fast cases.+vi.setConfig({ testTimeout: 15_000 });++// The preview is server-owned; the editor must never approximate it. The mock+// stands in for the cron-preview endpoint: it 400s on anything that isn't a+// 5-field expression (mirroring the robfig parser's contract) and can be told+// to fail at the transport level, which must NOT read as "your cron is wrong".+const previewFailure = {+ transport: false,+ unreadable: false,+ badTimezone: false,+ // A 400 whose code the editor does not know. The endpoint only ever sends+ // invalid_cron and invalid_timezone today, but a rejection it cannot classify+ // must still reach the user with the server's own words attached.+ unknownCode: false,+ // Every run already in the past, so the editor's "the list has expired,+ // refresh it" effect fires. Two schedules sharing a next-run instant is the+ // norm, not a coincidence — anything firing at tomorrow 09:00 does.+ expired: false,+};+// Every expression the editor actually asked the server about, in order. The+// expired-preview refresh is an *extra* fetch on top of the first one, so its+// absence for a given expression is visible as a missing entry here.+const previewCalls: string[] = [];++vi.mock("@multica/core/autopilots/queries", () => ({+ cronPreviewOptions: (+ wsId: string,+ expr: string,+ tz: string,+ options?: { enabled?: boolean },+ ) => ({+ queryKey: [+ "autopilots",+ wsId,+ "cron-preview",+ expr,+ tz,+ previewFailure.transport,+ previewFailure.unreadable,+ previewFailure.badTimezone,+ previewFailure.unknownCode,+ previewFailure.expired,+ ],+ queryFn: async () => {+ previewCalls.push(expr);+ if (previewFailure.expired) {+ // A shared instant, deliberately: the guard must tell the two+ // expressions apart, and it cannot do that from the timestamp alone.+ return { next_runs: ["2020-01-01T00:00:00Z"] };+ }+ if (previewFailure.transport) {+ throw new ApiError("API error: 500 Internal Server Error", 500, "Internal Server Error");+ }+ if (previewFailure.badTimezone) {+ throw new ApiError(`invalid timezone "${tz}"`, 400, "Bad Request", {+ error: `invalid timezone "${tz}"`,+ code: "invalid_timezone",+ });+ }+ if (previewFailure.unknownCode) {+ throw new ApiError("schedule rejected by policy", 400, "Bad Request", {+ error: "schedule rejected by policy",+ code: "some_future_code",+ });+ }+ // The server reads a TZ=/CRON_TZ= prefix off the expression itself+ // (case-sensitively, up to the first literal space) and validates the+ // embedded zone before the fields — the guarded no-space shape and an+ // unknown zone are both invalid_cron, since they are part of the string.+ let fields = expr;+ if (fields.startsWith("TZ=") || fields.startsWith("CRON_TZ=")) {+ const space = fields.indexOf(" ");+ const zone = space === -1 ? null : fields.slice(fields.indexOf("=") + 1, space);+ // "asia/shanghai" mirrors a dev server on a case-insensitive filesystem,+ // where LoadLocation takes the lowercase spelling too.+ if (zone === null || !["UTC", "Asia/Tokyo", "Asia/Shanghai", "asia/shanghai", "Local", ""].includes(zone)) {+ throw new ApiError(`parse cron: provided bad location ${zone ?? expr}`, 400, "Bad Request", {+ error: "parse cron: provided bad location",+ code: "invalid_cron",+ });+ }+ fields = fields.slice(space).trim();+ }+ if (fields.trim().split(/\s+/).length !== 5) {+ throw new ApiError("parse cron: expected exactly 5 fields", 400, "Bad Request", {+ error: "parse cron: expected exactly 5 fields",+ code: "invalid_cron",+ });+ }+ // A response the schema could not read degrades to null — distinct from+ // an empty list, which means "this expression never fires".+ if (previewFailure.unreadable) return { next_runs: null };+ if (fields === "0 0 30 2 *") return { next_runs: [] };+ return {+ next_runs: ["2126-07-14T01:00:00Z", "2126-07-14T03:00:00Z", "2126-07-14T05:00:00Z"],+ };+ },+ enabled: options?.enabled ?? true,+ retry: false,+ }),+}));++vi.mock("../pickers/timezone-picker", () => ({+ TimezonePicker: ({ value, onChange }: { value: string; onChange: (tz: string) => void }) => (+ <select data-testid="timezone-picker" value={value} onChange={(e) => onChange(e.target.value)}>+ <option value="UTC">UTC</option>+ <option value="Asia/Shanghai">Asia/Shanghai</option>+ </select>+ ),+}));++function Harness({+ initial,+ onChange,+ disabled,+}: {+ initial: ScheduleConfig;+ onChange?: () => void;+ disabled?: boolean;+}) {+ const [value, setValue] = useState(initial);+ const [valid, setValid] = useState(true);+ return (+ <>+ <ScheduleEditor+ value={value}+ onChange={(next) => {+ onChange?.();+ setValue(next);+ }}+ wsId="ws-test"+ disabled={disabled}+ onValidityChange={setValid}+ />+ <output data-testid="cron-out">{cronFields(value)}</output>+ <output data-testid="wire-out">{toCron(value)}</output>+ <output data-testid="raw-out">{String(value.raw)}</output>+ <output data-testid="tz-out">{value.timezone}</output>+ <output data-testid="valid-out">{String(valid)}</output>+ </>+ );+}++function renderEditor(+ initial: ScheduleConfig,+ opts?: { onChange?: () => void; disabled?: boolean; locale?: SupportedLocale },+) {+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return renderWithI18n(+ <QueryClientProvider client={qc}>+ <Harness initial={initial} onChange={opts?.onChange} disabled={opts?.disabled} />+ </QueryClientProvider>,+ opts?.locale === undefined ? undefined : { locale: opts.locale },+ );+}++const cron = (expr: string) => parseCron(expr, "UTC");+const cronOut = () => screen.getByTestId("cron-out").textContent;+const wireOut = () => screen.getByTestId("wire-out").textContent;++// The cron expression is read-only until clicked, but already an input in+// advanced-only mode, so only click it open when the field isn't mounted yet.+async function openCronInput(): Promise<HTMLElement> {+ if (screen.queryByRole("textbox", { name: "Cron" }) === null) {+ const user = userEvent.setup();+ await user.click(screen.getByRole("button", { name: /click to edit/ }));+ }+ return screen.getByRole("textbox", { name: "Cron" });+}++async function editCronText(expr: string) {+ const input = await openCronInput();+ fireEvent.change(input, { target: { value: expr } });+ fireEvent.blur(input);+}++describe("ScheduleEditor", () => {+ it("renders the three form blocks and the cron readback", () => {+ renderEditor(cron("0 9-21 * * *"));+ expect(screen.getByText("Time")).toBeInTheDocument();+ expect(screen.getByText("Days")).toBeInTheDocument();+ expect(screen.getByText("Timezone")).toBeInTheDocument();+ // The cron expression lives in the result panel below the form, shown as a+ // click-to-edit readback rather than a labelled field.+ expect(screen.getByRole("button", { name: /click to edit/ })).toBeInTheDocument();+ });++ it("never fires onChange on mount (untouched save sends no update)", async () => {+ const onChange = vi.fn();+ renderEditor(cron("0 9-21 * * *"), { onChange });+ await waitFor(() => expect(screen.getByText("Next runs")).toBeInTheDocument());+ expect(onChange).not.toHaveBeenCalled();+ expect(cronOut()).toBe("0 9-21 * * *");+ });++ it("echoes a compound expression into structured controls", () => {+ renderEditor(cron("0 9-21/2 * * 2-4"));+ expect(screen.getByTestId("raw-out").textContent).toBe("null");+ expect(screen.getByRole("button", { name: "Tuesday", pressed: true })).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Thursday", pressed: true })).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Monday", pressed: false })).toBeInTheDocument();+ expect(screen.getByText(/Every 2 hours · 09:00–21:00 · Tue–Thu/)).toBeInTheDocument();+ });++ it("toggles weekly day chips without collapsing the selection", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 9 * * 2-4"));+ await user.click(screen.getByRole("button", { name: "Friday" }));+ expect(cronOut()).toBe("0 9 * * 2-5");+ await user.click(screen.getByRole("button", { name: "Tuesday" }));+ expect(cronOut()).toBe("0 9 * * 3-5");+ });++ it("keeps a compound time pattern intact while the days are edited", async () => {+ const user = userEvent.setup();+ // Every other day-editing test starts from 09:00 — the default time — so a+ // setDays that reset the time dimension would pass them all unnoticed. This+ // one starts where the time is nothing like the default.+ renderEditor(cron("30 9-21/3 * * 2-4"));+ await user.click(screen.getByRole("button", { name: "Friday" }));+ expect(cronOut()).toBe("30 9-21/3 * * 2-5");+ await user.click(screen.getByRole("button", { name: "Tuesday" }));+ expect(cronOut()).toBe("30 9-21/3 * * 3-5");++ // …and the same for a switch of day *kind*, not just a chip toggle.+ await user.click(screen.getByLabelText("Day pattern"));+ await user.click(await screen.findByRole("option", { name: "Day of month" }));+ expect(cronOut()).toBe("30 9-21/3 1 * *");+ await user.click(screen.getByLabelText("Day pattern"));+ await user.click(await screen.findByRole("option", { name: "Every day" }));+ expect(cronOut()).toBe("30 9-21/3 * * *");+ });++ it("edits interval, window and day chips in sequence on one schedule", async () => {+ const user = userEvent.setup();+ // The three dimensions are written by two handlers that each overwrite the+ // whole config (`{...value, time | days, raw: null}`). Editing them one at a+ // time from a trivial baseline never shows one clobbering another.+ renderEditor(cron("0 9-21/2 * * 2-4"));++ fireEvent.change(screen.getByRole("spinbutton"), { target: { value: "3" } });+ expect(cronOut()).toBe("0 9-21/3 * * 2-4");++ await user.click(screen.getByLabelText("Window end hour"));+ await user.keyboard("18");+ expect(cronOut()).toBe("0 9-18/3 * * 2-4");++ await user.click(screen.getByRole("button", { name: "Monday" }));+ expect(cronOut()).toBe("0 9-18/3 * * 1-4");++ await user.click(screen.getByLabelText("Window start hour"));+ await user.keyboard("10");+ expect(cronOut()).toBe("0 10-18/3 * * 1-4");+ });++ it("keeps at least one weekly day selected", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 9 * * 1"));+ await user.click(screen.getByRole("button", { name: "Monday" }));+ expect(cronOut()).toBe("0 9 * * 1");+ });++ // Stepping off a bound wraps; stepping from OUTSIDE the range lands on the+ // bound that was overshot. Clamping before stepping instead of after made the+ // bounds themselves unreachable from a mistyped number.+ it.each([+ ["0", "ArrowUp", "0 9 1 * *"],+ ["0", "ArrowDown", "0 9 1 * *"],+ ["40", "ArrowDown", "0 9 31 * *"],+ ["40", "ArrowUp", "0 9 31 * *"],+ ])("steps a mistyped day-of-month %s back onto the bound it overshot", (typed, key, expected) => {+ renderEditor(cron("0 9 15 * *"));+ const box = screen.getByRole("spinbutton");+ fireEvent.change(box, { target: { value: typed } });+ fireEvent.keyDown(box, { key });+ expect(cronOut()).toBe(expected);+ });++ it.each([+ ["31", "ArrowUp", "0 9 1 * *"],+ ["1", "ArrowDown", "0 9 31 * *"],+ ])("still wraps the day-of-month at %s", (typed, key, expected) => {+ renderEditor(cron("0 9 15 * *"));+ const box = screen.getByRole("spinbutton");+ fireEvent.change(box, { target: { value: typed } });+ fireEvent.keyDown(box, { key });+ expect(cronOut()).toBe(expected);+ });++ it("edits the interval step outside of raw cron", () => {+ renderEditor(cron("0 */2 * * *"));+ fireEvent.change(screen.getByRole("spinbutton"), { target: { value: "3" } });+ expect(cronOut()).toBe("0 */3 * * *");+ });++ it("hydrates structured controls from cron text", async () => {+ renderEditor(cron("0 9 * * *"));+ await editCronText("0 9-21/2 * * 2-4");+ expect(cronOut()).toBe("0 9-21/2 * * 2-4");+ expect(screen.getByTestId("raw-out").textContent).toBe("null");+ expect(screen.getByRole("button", { name: "Tuesday", pressed: true })).toBeInTheDocument();+ });++ it("enters advanced-only mode for unrepresentable expressions and recovers", async () => {+ renderEditor(cron("0 9 1,15 * *"));+ // The notice waits for the server to take the expression — until then all the+ // editor knows is that it cannot parse it, which is also true of a typo.+ await waitFor(() =>+ expect(screen.getByText(/visual editor can't represent/)).toBeInTheDocument(),+ );+ expect(screen.getByTestId("raw-out").textContent).toBe("0 9 1,15 * *");++ await editCronText("0 9 * * *");+ expect(screen.getByTestId("raw-out").textContent).toBe("null");+ expect(screen.queryByText(/visual editor can't represent/)).not.toBeInTheDocument();+ });++ it("takes a degenerate expression into the controls instead of greying them out", async () => {+ // "*/65" steps past the minute field on its first stride, so it selects+ // minute 0 — the 14th of the month, on the hour, from 10:00 to 20:59. Every+ // control can hold that, and the editor used to claim otherwise while the+ // preview below it listed the hourly runs.+ renderEditor(cron("*/65 10-20 14 * *"));+ expect(screen.getByTestId("raw-out").textContent).toBe("null");+ expect(screen.getByTestId("cron-out").textContent).toBe("0 10-20 14 * *");+ expect(screen.queryByText(/visual editor can't represent/)).not.toBeInTheDocument();+ // Live controls, carrying the schedule — not a greyed-out shell over a raw+ // cron box.+ expect(screen.getByLabelText("Day of month")).toHaveValue(14);+ });++ it("changes the timezone of a structured schedule without touching the expression", async () => {+ renderEditor(cron("0 9-21/2 * * 2-4"));+ // The zone has to change on a *settled* preview, or "not settled yet" and+ // "re-querying for the new zone" are the same state and prove nothing.+ const line = await waitFor(() => {+ const el = screen.getByText("Next runs").closest("div");+ expect(el).toHaveAttribute("aria-busy", "false");+ return el;+ });++ fireEvent.change(screen.getByTestId("timezone-picker"), {+ target: { value: "Asia/Shanghai" },+ });+ expect(screen.getByTestId("tz-out").textContent).toBe("Asia/Shanghai");+ // The timezone is orthogonal to the expression: it is the one control that+ // must move the schedule without rewriting a single cron field.+ expect(cronOut()).toBe("0 9-21/2 * * 2-4");+ expect(screen.getByTestId("raw-out").textContent).toBe("null");+ // The preview is the server's answer for a cron AND a zone, so a new zone+ // must re-ask: 09:00 in Shanghai is not 09:00 in UTC. A preview keyed on the+ // expression alone would still read settled here, having never noticed.+ expect(line).toHaveAttribute("aria-busy", "true");+ await waitFor(() => expect(line).toHaveAttribute("aria-busy", "false"));+ });++ it("keeps the timezone editable in advanced-only mode and preserves raw", () => {+ renderEditor(cron("0 9 1,15 * *"));+ fireEvent.change(screen.getByTestId("timezone-picker"), {+ target: { value: "Asia/Shanghai" },+ });+ expect(screen.getByTestId("tz-out").textContent).toBe("Asia/Shanghai");+ expect(screen.getByTestId("raw-out").textContent).toBe("0 9 1,15 * *");+ });++ it("shows server-driven next runs", async () => {+ renderEditor(getDefaultScheduleConfig("UTC"));+ await waitFor(() => expect(screen.getByText("Next runs")).toBeInTheDocument());+ });++ it("shows the server error inline for an invalid expression", async () => {+ renderEditor(cron("0 9 * * *"));+ await editCronText("@daily");+ await waitFor(() => expect(screen.getByText(/expected exactly 5 fields/)).toBeInTheDocument());+ });++ it("does not accept an emptied cron expression", async () => {+ renderEditor(cron("0 9 * * 1-5"));+ await editCronText(" ");+ // Snaps back to the model instead of writing "" into raw and letting the+ // dialog submit an empty cron_expression.+ expect(screen.getByTestId("cron-out").textContent).toBe("0 9 * * 1-5");+ expect(screen.getByTestId("raw-out").textContent).toBe("null");+ });++ it("does not reinterpret the cron text while the user is still typing", async () => {+ renderEditor(cron("0 9 * * *"));+ const input = await openCronInput();+ fireEvent.change(input, { target: { value: "0 9 * *" } });+ // Half-typed text must not flip the editor into advanced-only mode; the+ // model only changes on blur/Enter.+ expect(screen.getByTestId("raw-out").textContent).toBe("null");+ expect(screen.getByRole("button", { name: "At a time" })).toBeEnabled();+ });++ it("validates the cron text on blur, not on every keystroke", async () => {+ renderEditor(cron("0 9 * * *"));+ const input = await openCronInput();+ fireEvent.change(input, { target: { value: "0 9 * *" } });+ // The half-typed expression would be rejected by the server, but it is not+ // the user's answer yet — nothing is sent and nothing is flagged.+ await waitFor(() => expect(screen.getByText("Next runs")).toBeInTheDocument());+ expect(screen.queryByText(/isn't valid/)).not.toBeInTheDocument();++ fireEvent.blur(input);+ await waitFor(() => expect(screen.getByText(/isn't valid/)).toBeInTheDocument());+ });++ it("commits the cron text on Enter", async () => {+ renderEditor(cron("0 9 * * *"));+ const input = await openCronInput();+ fireEvent.change(input, { target: { value: "0 9-21/2 * * 2-4" } });+ fireEvent.keyDown(input, { key: "Enter" });+ expect(screen.getByTestId("cron-out").textContent).toBe("0 9-21/2 * * 2-4");+ });++ it("disables the structured controls in advanced-only mode, not just greys them", () => {+ renderEditor(cron("0 9 1,15 * *"));+ // pointer-events-none alone would still let a keyboard user activate these+ // and silently overwrite the hand-written expression.+ expect(screen.getByRole("button", { name: "At a time" })).toBeDisabled();+ expect(screen.getByRole("button", { name: "At an interval" })).toBeDisabled();+ expect(screen.getByLabelText("Hour")).toBeDisabled();+ });++ it("disables every schedule control when the editor is locked", async () => {+ renderEditor(cron("0 9 * * 1-5"), { disabled: true });+ expect(screen.getByRole("button", { name: "At a time" })).toBeDisabled();+ expect(screen.getByRole("button", { name: "Monday" })).toBeDisabled();+ // Locked: the cron row cannot even be opened for editing.+ expect(screen.getByRole("button", { name: /click to edit/ })).toBeDisabled();+ expect(screen.queryByRole("textbox", { name: "Cron" })).not.toBeInTheDocument();+ });++ it("still shows next runs when the editor is locked", async () => {+ renderEditor(cron("0 9 * * 1-5"), { disabled: true });+ await waitFor(() => expect(screen.getByText("Next runs")).toBeInTheDocument());+ });++ it("keeps the hour when switching between fixed time and interval", async () => {+ const user = userEvent.setup();+ renderEditor(cron("30 14 * * *"));+ await user.click(screen.getByRole("button", { name: "At an interval" }));+ await user.click(screen.getByRole("button", { name: "At a time" }));+ // The interval model has nowhere to keep an hour; losing it would silently+ // rewrite 14:30 as 09:30.+ expect(screen.getByTestId("cron-out").textContent).toBe("30 14 * * *");+ });++ it("keeps the minute across a fixed time → minute-step window → fixed time trip", async () => {+ const user = userEvent.setup();+ renderEditor(cron("30 14 * * *"));+ await user.click(screen.getByRole("button", { name: "At an interval" }));+ await user.click(screen.getByLabelText("Interval unit"));+ await user.click(await screen.findByRole("option", { name: "minutes" }));+ await user.click(screen.getByLabelText("Window start hour"));+ await user.keyboard("14");+ await user.click(screen.getByRole("button", { name: "At a time" }));+ // A minute-step window is hour-granular, so its bounds read :00 — but the+ // model still holds the 30 the user typed. Reading the anchor back off the+ // window would silently fire the schedule half an hour early.+ expect(screen.getByTestId("cron-out").textContent).toBe("30 14 * * *");+ });++ it("focuses the interval when the time switches to an interval", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 9 * * *"));+ await user.click(screen.getByRole("button", { name: "At an interval" }));+ // The switch reveals a fresh field; the caret lands in it so the step can be+ // typed without a second click.+ expect(screen.getByLabelText("Interval")).toHaveFocus();+ });++ it("focuses the hour when the time switches back to a fixed time", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 */2 * * *"));+ await user.click(screen.getByRole("button", { name: "At a time" }));+ expect(screen.getByLabelText("Hour")).toHaveFocus();+ });++ it("focuses the step when the interval unit switches", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 */2 * * *"));+ await user.click(screen.getByLabelText("Interval unit"));+ await user.click(await screen.findByRole("option", { name: "minutes" }));+ // The step stays mounted across the unit switch, so this is an imperative+ // focus, not autoFocus — the caret returns to the number to retype it.+ expect(screen.getByLabelText("Interval")).toHaveFocus();+ });++ it("focuses the day box when the day pattern switches to monthly", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 9 * * *"));+ await user.click(screen.getByLabelText("Day pattern"));+ await user.click(await screen.findByRole("option", { name: "Day of month" }));+ expect(screen.getByLabelText("Day of month")).toHaveFocus();+ });++ it("does not steal focus on first render, even when a field is already shown", async () => {+ // The gate is a user switch, not the field's presence: a schedule that opens+ // already monthly must not pull focus (and the panel's scroll) on mount.+ renderEditor(cron("0 9 14 * *"));+ expect(screen.getByLabelText("Day of month")).not.toHaveFocus();+ });++ it("names every control, so none is announced as a bare box", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 9 * * *"));+ expect(screen.getByLabelText("Hour")).toBeInTheDocument();+ expect(screen.getByLabelText("Minute")).toBeInTheDocument();+ expect(screen.getByLabelText("Day pattern")).toBeInTheDocument();++ await user.click(screen.getByRole("button", { name: "At an interval" }));+ expect(screen.getByLabelText("Interval")).toBeInTheDocument();+ expect(screen.getByLabelText("Interval unit")).toBeInTheDocument();+ // The window is on screen from the moment the interval is, all-day included.+ expect(screen.getByLabelText("Window start hour")).toBeInTheDocument();+ expect(screen.getByLabelText("Window end hour")).toBeInTheDocument();++ await user.click(screen.getByLabelText("Day pattern"));+ await user.click(await screen.findByRole("option", { name: "Day of month" }));+ expect(screen.getByLabelText("Day of month")).toBeInTheDocument();+ });++ it("labels every select trigger with its option's text, not its raw value", async () => {+ renderEditor(cron("*/15 9-21 * * *"));+ // Base UI falls back to the raw value, which would read as "every" and+ // "minutes" — the enum members, not the labels the user picked.+ const triggers = screen.getAllByRole("combobox").map((el) => el.textContent ?? "");+ expect(triggers.some((text) => text.startsWith("Every day"))).toBe(true);+ expect(triggers.some((text) => text.startsWith("minutes"))).toBe(true);+ });++ it("edits both ends of a minute-step window in place, with no minute segment", async () => {+ const user = userEvent.setup();+ renderEditor(cron("*/15 9-21 * * *"));+ const startHour = screen.getByLabelText("Window start hour");+ const endHour = screen.getByLabelText("Window end hour");+ // A minute-step window is hour-granular: the bounds carry no minute, so the+ // minute segment is not rendered at all — not shown greyed-out.+ expect(screen.queryByLabelText("Window start minute")).toBeNull();+ expect(screen.queryByLabelText("Window end minute")).toBeNull();+ await user.click(startHour!);+ await user.keyboard("10");+ expect(cronOut()).toBe("*/15 10-21 * * *");+ await user.click(endHour!);+ await user.keyboard("18");+ expect(cronOut()).toBe("*/15 10-18 * * *");+ });++ it("restores the interval and its window after a round trip through fixed time", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 9-21/3 * * 1-5"));+ await user.click(screen.getByRole("button", { name: "At a time" }));+ await user.click(screen.getByRole("button", { name: "At an interval" }));+ // Step, unit and window are as much user input as the hour is; rebuilding+ // the pattern from defaults would silently turn "every 3h, 9-21" into+ // "every hour, all day".+ expect(screen.getByTestId("cron-out").textContent).toBe("0 9-21/3 * * 1-5");+ });++ it("reports a transport failure as an unavailable preview, not an invalid cron", async () => {+ previewFailure.transport = true;+ try {+ renderEditor(cron("0 9 * * *"));+ await waitFor(() => expect(screen.getByText(/Next runs unavailable/)).toBeInTheDocument());+ expect(screen.queryByText(/500 Internal Server Error/)).not.toBeInTheDocument();+ } finally {+ previewFailure.transport = false;+ }+ });++ it("says so when a valid expression has no upcoming runs", async () => {+ renderEditor(cron("0 0 30 2 *"));+ await waitFor(() => expect(screen.getByText(/no upcoming runs/)).toBeInTheDocument());+ });++ it("does not call an unreadable response 'no upcoming runs'", async () => {+ previewFailure.unreadable = true;+ try {+ renderEditor(cron("0 9 * * *"));+ await waitFor(() => expect(screen.getByText(/Next runs unavailable/)).toBeInTheDocument());+ // A drifted response must never be presented as "your daily 09:00+ // schedule will never run".+ expect(screen.queryByText(/no upcoming runs/)).not.toBeInTheDocument();+ } finally {+ previewFailure.unreadable = false;+ }+ });++ it("reports validity so the dialog can block an invalid cron", async () => {+ renderEditor(cron("0 9 * * *"));+ await waitFor(() => expect(screen.getByTestId("valid-out").textContent).toBe("true"));+ await editCronText("@daily");+ await waitFor(() => expect(screen.getByTestId("valid-out").textContent).toBe("false"));+ expect(screen.getByText("This cron expression isn't valid.")).toBeInTheDocument();+ // A rejected expression has no runs: the section goes entirely, rather than+ // leaving a heading and a divider framing nothing under the error.+ expect(screen.queryByText("Next runs")).not.toBeInTheDocument();+ });++ it("keeps a transport failure from marking the expression invalid", async () => {+ previewFailure.transport = true;+ try {+ renderEditor(cron("0 9 * * *"));+ await waitFor(() => expect(screen.getByText(/Next runs unavailable/)).toBeInTheDocument());+ expect(screen.getByTestId("valid-out").textContent).toBe("true");+ } finally {+ previewFailure.transport = false;+ }+ });++ it("types the window end two digits at a time without clamping mid-keystroke", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 9-21 * * *"));+ const endHour = screen.getByLabelText("Window end hour");+ await user.click(endHour!);+ // The intermediate "01" is below the start hour. Clamping it there would+ // leave TimeInput building the second digit from a value it never showed.+ await user.keyboard("12");+ expect(cronOut()).toBe("0 9-12 * * *");+ });++ it("never lets the window end fall below its start, not even mid-edit", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 9-21 * * *"));+ const endHour = screen.getByLabelText("Window end hour");+ await user.click(endHour!);+ await user.keyboard("08");+ // A window that ends before it starts has no cron form. The two ends+ // constrain each other while typing, so it is never displayed or submitted —+ // no error at save time.+ expect(endHour).toHaveValue("09");+ expect(cronOut()).toBe("0 9-9 * * *");+ });++ it("draws the interval and its unit in one box, lit by whichever holds focus", async () => {+ renderEditor(cron("0 */3 * * *"));+ const step = screen.getByLabelText("Interval");+ const unit = screen.getByLabelText("Interval unit");+ // "Every 3 hours" is one setting: the step and the unit share a box, rather+ // than sitting in two that happen to be next to each other.+ const box = step.closest("[data-slot=input-group]");+ expect(box).not.toBeNull();+ expect(box).toContainElement(unit);+ // The box lights its border from the control inside it that has focus, and it+ // knows them by this slot. A trigger that kept its own would leave the box+ // dark while the select it holds is the very thing focused.+ expect(step).toHaveAttribute("data-slot", "input-group-control");+ expect(unit).toHaveAttribute("data-slot", "input-group-control");+ });++ it("draws the window's two ends in one box", async () => {+ renderEditor(cron("0 9-21/3 * * *"));+ const start = screen.getByLabelText("Window start hour");+ // A window is one value with two ends, so it reads as one control rather than+ // two fields that happen to sit next to each other.+ const box = start.closest("[data-slot=input-group]");+ expect(box).not.toBeNull();+ expect(box).toContainElement(screen.getByLabelText("Window end hour"));+ // The segments, not their wrapper, are what the box lights its border from:+ // they are what gets focused.+ expect(start).toHaveAttribute("data-slot", "input-group-control");+ });++ // The window is a dimension of the schedule, not a mode of the editor: it is on+ // screen for every interval, and narrowing it is one edit — not a mode switch+ // followed by one.+ it("shows the day's bounds for an all-day interval, at either unit", async () => {+ const user = userEvent.setup();+ renderEditor(cron("15 */3 * * *"));+ // The hours unit carries the firing minute at both ends.+ expect(screen.getByLabelText("Window start hour")).toHaveValue("00");+ expect(screen.getByLabelText("Window start minute")).toHaveValue("15");+ expect(screen.getByLabelText("Window end hour")).toHaveValue("23");+ expect(screen.getByLabelText("Window end minute")).toHaveValue("15");++ await user.click(screen.getByLabelText("Interval unit"));+ await user.click(await screen.findByRole("option", { name: "minutes" }));+ // A minute-step window is hour-granular: the bounds are the whole hours.+ expect(screen.getByLabelText("Window start hour")).toHaveValue("00");+ expect(screen.getByLabelText("Window end hour")).toHaveValue("23");+ });++ it("narrows an all-day interval by editing the bound, with nothing to click first", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 */3 * * *"));+ await user.click(screen.getByLabelText("Window start hour"));+ await user.keyboard("09");+ // One edit, no mode switch.+ expect(cronOut()).toBe("0 9-23/3 * * *");+ });++ it("takes a window widened back to the whole day as all day again", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 9-21/3 * * *"));+ await user.click(screen.getByLabelText("Window start hour"));+ await user.keyboard("00");+ await user.click(screen.getByLabelText("Window end hour"));+ await user.keyboard("23");+ // A window that spans the day IS all day: the schedule has one form, and+ // "0-23/3" is not a second one.+ expect(cronOut()).toBe("0 */3 * * *");+ });++ it("clears the window end to the end of the day, not onto its start", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 9-15 * * *"));+ await user.click(screen.getByLabelText("Window end hour"));+ await user.keyboard("{Backspace}");+ // The end's floor is wherever the start sits, but that is not its neutral+ // value: clearing it opens the window to the end of the day.+ expect(cronOut()).toBe("0 9-23 * * *");+ });++ it("clears the window start to midnight", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 9-23 * * *"));+ await user.click(screen.getByLabelText("Window start hour"));+ await user.keyboard("{Backspace}");+ // Both bounds cleared is the whole day — which is all day, not a 00-23 window.+ expect(cronOut()).toBe("0 * * * *");+ });++ it("raises the window end when the start is moved past it", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 9-12 * * *"));+ const startHour = screen.getByLabelText("Window start hour");+ await user.click(startHour!);+ await user.keyboard("18");+ expect(cronOut()).toBe("0 18-18 * * *");+ });++ it("moves the shared firing minute when the window end's minute is edited", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 9-21 * * *"));+ const endMinute = screen.getByLabelText("Window end minute");+ await user.click(endMinute!);+ await user.keyboard("30");+ // cron keeps one minute for both ends of the range, so the start moves too.+ expect(cronOut()).toBe("30 9-21 * * *");+ });++ it("keeps the firing minute across an interval unit round-trip", async () => {+ const user = userEvent.setup();+ renderEditor(cron("30 */2 * * *"));+ await user.click(screen.getAllByRole("combobox")[0]!);+ await user.click(await screen.findByRole("option", { name: "minutes" }));+ await user.click(screen.getAllByRole("combobox")[0]!);+ await user.click(await screen.findByRole("option", { name: "hours" }));+ expect(cronOut()).toBe("30 */2 * * *");+ });++ it("keeps the firing minute across a unit round-trip with a time window", async () => {+ const user = userEvent.setup();+ renderEditor(cron("30 9-21/2 * * *"));+ await user.click(screen.getAllByRole("combobox")[0]!);+ await user.click(await screen.findByRole("option", { name: "minutes" }));+ await user.click(screen.getAllByRole("combobox")[0]!);+ await user.click(await screen.findByRole("option", { name: "hours" }));+ // The window carries the firing minute in cron, so the unit toggle must not+ // strand it: `minute`, not the window text, is the source of truth.+ expect(cronOut()).toBe("30 9-21/2 * * *");+ });++ it("keeps the firing minute when the window is widened back to the whole day", async () => {+ const user = userEvent.setup();+ renderEditor(cron("30 9-21/2 * * *"));+ await user.click(screen.getByLabelText("Window start hour"));+ await user.keyboard("00");+ await user.click(screen.getByLabelText("Window end hour"));+ await user.keyboard("23");+ // The minute is the schedule's, not the window's: dropping it when the window+ // goes would move the runs to the top of the hour behind the user's back.+ expect(cronOut()).toBe("30 */2 * * *");+ });++ it("keeps both typed digits when the window start's minute is edited", async () => {+ const user = userEvent.setup();+ renderEditor(cron("1 9-21/2 * * *"));+ const startMinute = screen.getByLabelText("Window start minute");+ await user.click(startMinute!);+ // The second keystroke must build on the first one, not on the minute the+ // model held before it — a stale minute would snap "12" back to "01".+ await user.keyboard("12");+ expect(cronOut()).toBe("12 9-21/2 * * *");+ });++ it("never leaves a cleared number box sitting over a stale model value", async () => {+ const user = userEvent.setup();+ renderEditor(cron("*/15 * * * *"));+ const interval = screen.getByRole("spinbutton");+ await user.clear(interval);+ // While the box is empty the model keeps the last valid value, but the box+ // must not stay empty over it once the user leaves the field.+ expect(cronOut()).toBe("*/15 * * * *");+ fireEvent.blur(interval);+ expect(interval).toHaveValue(15);+ });++ it("clamps an out-of-range number into the field's bounds on blur", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 */6 * * *"));+ const interval = screen.getByRole("spinbutton");+ await user.clear(interval);+ await user.type(interval, "24");+ // The digits arrive one at a time, so the box passes through "2" — a value+ // the user never chose. Leaving the field must land on the bound they were+ // reaching for, not on the first digit they happened to type.+ fireEvent.blur(interval);+ expect(interval).toHaveValue(23);+ expect(cronOut()).toBe("0 */23 * * *");+ });++ it("gives the weekday selection back after a trip through another day kind", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 9 * * 2,4,6"));+ await user.click(screen.getByLabelText("Day pattern"));+ await user.click(await screen.findByRole("option", { name: "Every day" }));+ expect(cronOut()).toBe("0 9 * * *");+ await user.click(screen.getByLabelText("Day pattern"));+ await user.click(await screen.findByRole("option", { name: "Days of week" }));+ // Rebuilt from defaults, a glance at another kind would save the autopilot+ // to Monday — a day the user never picked.+ expect(cronOut()).toBe("0 9 * * 2,4,6");+ });++ it("warns that short months are skipped for days 29-31, and only there", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 9 15 * *"));+ expect(screen.queryByText(/are skipped/)).not.toBeInTheDocument();+ const day = screen.getByLabelText("Day of month");+ await user.clear(day);+ await user.type(day, "31");+ expect(screen.getByText("Months without day 31 are skipped.")).toBeInTheDocument();+ });++ it("gives the day of month back after a trip through another day kind", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 9 25 * *"));+ await user.click(screen.getByLabelText("Day pattern"));+ await user.click(await screen.findByRole("option", { name: "Every day" }));+ await user.click(screen.getByLabelText("Day pattern"));+ await user.click(await screen.findByRole("option", { name: "Day of month" }));+ expect(cronOut()).toBe("0 9 25 * *");+ });++ it("gives the window end back when the start stops overrunning it", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 9-15/2 * * *"));+ const startHour = screen.getByLabelText("Window start hour");+ await user.click(startHour);+ await user.keyboard("22");+ // A window cannot run backwards, so the end is dragged along…+ expect(cronOut()).toBe("0 22-22/2 * * *");+ await user.click(startHour);+ await user.keyboard("09");+ // …but it is the user's 15:00, not a value the drag invented: keeping 22+ // here would nearly double how often the autopilot runs.+ expect(cronOut()).toBe("0 9-15/2 * * *");+ });++ it("takes a window typed into the cron box as the end to hold, not the old one", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 9-15/2 * * *"));+ await editCronText("0 8-20/2 * * *");+ const startHour = screen.getByLabelText("Window start hour");+ await user.click(startHour);+ await user.keyboard("09");+ // The end the user just typed into the cron box is the current intent; an+ // anchor left over from before it would quietly cut the window back to 15:00.+ expect(cronOut()).toBe("0 9-20/2 * * *");+ });++ it.each(["22", "15"])(+ "keeps the window when a fixed time at or past its end is carried back (%s:00)",+ async (typed) => {+ const user = userEvent.setup();+ renderEditor(cron("0 9-15/3 * * *"));+ await user.click(screen.getByRole("button", { name: "At a time" }));+ await user.click(screen.getByLabelText("Hour"));+ await user.keyboard(typed);+ await user.click(screen.getByRole("button", { name: "At an interval" }));+ // Rebasing onto the end hour itself collapses the window just as surely as+ // rebasing past it: 15:00–15:00 is not a window.+ expect(cronOut()).toBe("0 9-15/3 * * *");+ },+ );++ it("keeps the window when a fixed time later than its end is carried back", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 9-15/3 * * *"));+ await user.click(screen.getByRole("button", { name: "At a time" }));+ const hour = screen.getByLabelText("Hour");+ await user.click(hour);+ await user.keyboard("22");+ await user.click(screen.getByRole("button", { name: "At an interval" }));+ // Rebasing the window onto 22:00 would drag its end up and hand back the+ // single hour 22:00–22:00 — the window the anchor exists to preserve.+ expect(cronOut()).toBe("0 9-15/3 * * *");+ });++ it("holds the dragged-open window's anchor across an interval unit switch", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 9-15/2 * * *"));+ await user.click(screen.getByLabelText("Window start hour"));+ await user.keyboard("22");+ expect(cronOut()).toBe("0 22-22/2 * * *");+ // A unit switch rewrites the end from 22:00 to 22:59 without the user asking+ // for anything — it must not be read as "22 is what I want".+ await user.click(screen.getByLabelText("Interval unit"));+ await user.click(await screen.findByRole("option", { name: "minutes" }));+ await user.click(screen.getByLabelText("Interval unit"));+ await user.click(await screen.findByRole("option", { name: "hours" }));+ await user.click(screen.getByLabelText("Window start hour"));+ await user.keyboard("09");+ expect(cronOut()).toBe("0 9-15/2 * * *");+ });++ it("takes an end typed right after a drag as the new end", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 9-15/2 * * *"));+ await user.click(screen.getByLabelText("Window start hour"));+ await user.keyboard("22");+ // The drag already produced 22; typing 22 into the end field means the user+ // wants it — the start must not hand back the old 15 afterwards.+ await user.click(screen.getByLabelText("Window end hour"));+ await user.keyboard("22");+ await user.click(screen.getByLabelText("Window start hour"));+ await user.keyboard("09");+ expect(cronOut()).toBe("0 9-22/2 * * *");+ });++ it("gives the step back after a trip through the other interval unit", async () => {+ const user = userEvent.setup();+ renderEditor(cron("*/45 * * * *"));+ await user.click(screen.getByLabelText("Interval unit"));+ await user.click(await screen.findByRole("option", { name: "hours" }));+ // 45 hours has no meaning, so the step is clamped on the way there…+ expect(cronOut()).toBe("0 */23 * * *");+ await user.click(screen.getByLabelText("Interval unit"));+ await user.click(await screen.findByRole("option", { name: "minutes" }));+ // …but keeping the 23 on the way back would double how often it runs.+ expect(cronOut()).toBe("*/45 * * * *");+ });++ it("keeps the structured schedule under an expression it cannot represent", async () => {+ renderEditor(cron("0 17 * * 1"));+ await editCronText("0 9 1,15 * *");+ expect(screen.getByTestId("raw-out").textContent).toBe("0 9 1,15 * *");+ // The greyed controls must still show the schedule the user had, not the+ // 09:00/every-day defaults parseCron falls back to — that schedule is what+ // they return to the moment the expression is structurable again.+ expect(screen.getByRole("button", { name: "Monday", pressed: true })).toBeInTheDocument();+ expect(screen.getByLabelText("Hour")).toHaveValue("17");+ });++ it("closes the cron field when a blur brings the expression back into the model", async () => {+ renderEditor(cron("0 9 1,15 * *"));+ const input = screen.getByRole("textbox", { name: "Cron" });+ fireEvent.change(input, { target: { value: "0 9 * * *" } });+ fireEvent.blur(input);+ // The field is only open because the expression was advanced-only; once it+ // isn't, the panel goes back to its readback.+ expect(screen.getByRole("button", { name: /click to edit/ })).toBeInTheDocument();+ });++ it("keeps the cron field open and focused when Enter leaves advanced-only mode", async () => {+ renderEditor(cron("0 9 1,15 * *"));+ const input = screen.getByRole("textbox", { name: "Cron" });+ input.focus();+ fireEvent.change(input, { target: { value: "0 9 15 * *" } });+ fireEvent.keyDown(input, { key: "Enter" });+ // The expression is structurable again, so the field would collapse back to+ // its readback — under the hands of the keyboard user still typing in it.+ expect(screen.getByTestId("raw-out").textContent).toBe("null");+ expect(screen.getByRole("textbox", { name: "Cron" })).toHaveFocus();+ });++ it("marks the previous expression's next runs as pending instead of removing the row", async () => {+ renderEditor(cron("0 9 * * *"));+ const line = await waitFor(() => screen.getByText("Next runs").closest("div"));+ expect(line).not.toBeNull();++ await editCronText("0 18 * * *");+ // The description updates instantly while the preview is still the cached+ // 09:00 answer. The row stays mounted so it does not blink out on every+ // edit, but it must not read as this schedule's answer until it catches up.+ expect(screen.getByText(/At 18:00/)).toBeInTheDocument();+ expect(screen.getByText("Next runs").closest("div")).toBe(line);+ expect(line).toHaveAttribute("aria-busy", "true");++ // Once the preview catches up, the same element carries the new text.+ await waitFor(() => expect(line).toHaveAttribute("aria-busy", "false"));+ expect(screen.getByText("Next runs").closest("div")).toBe(line);+ });++ it("refreshes an expired preview per expression, not per run instant", async () => {+ previewFailure.expired = true;+ previewCalls.length = 0;+ try {+ renderEditor(cron("0 9 * * *"));+ // The first run has already passed, so the cached list is stale and the+ // editor asks again — once, then it stops: a client clock ahead of the+ // server must not turn this into a refetch on every tick.+ await waitFor(() =>+ expect(previewCalls.filter((e) => e === "TZ=UTC 0 9 * * *")).toHaveLength(2),+ );++ await editCronText("0 9 * * 1-5");+ // A different schedule that happens to share that same passed instant. A+ // guard keyed on the instant alone would count the refresh it did for the+ // previous expression as having covered this one, and leave it showing a+ // run in the past for as long as the dialog stays open.+ await waitFor(() =>+ expect(previewCalls.filter((e) => e === "TZ=UTC 0 9 * * 1-5")).toHaveLength(2),+ );+ // Still exactly one refresh each — the guard holds within an expression.+ expect(previewCalls.filter((e) => e === "TZ=UTC 0 9 * * *")).toHaveLength(2);+ } finally {+ previewFailure.expired = false;+ previewCalls.length = 0;+ }+ });++ it("blames the timezone, not the cron, when the server rejects the zone", async () => {+ previewFailure.badTimezone = true;+ try {+ renderEditor(cron("0 9 * * *"));+ await waitFor(() =>+ expect(screen.getByText(/timezone isn't recognized/)).toBeInTheDocument(),+ );+ expect(screen.queryByText("This cron expression isn't valid.")).not.toBeInTheDocument();+ } finally {+ previewFailure.badTimezone = false;+ }+ });++ // The model cannot tell an expression that is beyond the controls from one that+ // is plain wrong — both land in `raw`. Only the server can, so every notice+ // below is about what the server said, not about what the model could parse.++ it("does not call an unverified expression too advanced for the controls", async () => {+ previewFailure.transport = true;+ try {+ renderEditor(cron("0 9 1,15 * *"));+ await waitFor(() =>+ expect(screen.getByText(/server couldn't be reached/)).toBeInTheDocument(),+ );+ // The claim it must not make: with the preview endpoint down, "the server+ // takes this, the controls just can't show it" is an answer nobody gave.+ expect(screen.queryByText(/visual editor can't represent/)).not.toBeInTheDocument();+ // Saving stays open all the same — the write path validates the cron of its+ // own accord, so a preview outage must not block a schedule the server would+ // have taken.+ expect(screen.getByTestId("valid-out").textContent).toBe("true");+ } finally {+ previewFailure.transport = false;+ }+ });++ it("does not call an unreadable preview too advanced for the controls", async () => {+ previewFailure.unreadable = true;+ try {+ renderEditor(cron("0 9 1,15 * *"));+ await waitFor(() =>+ expect(screen.getByText(/server couldn't be reached/)).toBeInTheDocument(),+ );+ expect(screen.queryByText(/visual editor can't represent/)).not.toBeInTheDocument();+ } finally {+ previewFailure.unreadable = false;+ }+ });++ it("says the expression is still being checked before the server has answered", async () => {+ renderEditor(cron("0 9 1,15 * *"));+ // The round trip is a whole debounce and a request away, and an invalid cron+ // is indistinguishable from an unrepresentable one until it lands.+ expect(screen.getByText(/Checking this expression/)).toBeInTheDocument();+ await waitFor(() =>+ expect(screen.getByText(/visual editor can't represent/)).toBeInTheDocument(),+ );+ expect(screen.queryByText(/Checking this expression/)).not.toBeInTheDocument();+ });++ it("calls an accepted expression advanced even when it has no upcoming runs", async () => {+ // 29 Feb is both beyond the controls (a month is pinned) and firing nowhere in+ // the preview window. An empty list is still an answer: the server took it.+ renderEditor(cron("0 0 30 2 *"));+ await waitFor(() =>+ expect(screen.getByText(/visual editor can't represent/)).toBeInTheDocument(),+ );+ expect(screen.getByText(/no upcoming runs/)).toBeInTheDocument();+ });++ it("shows the rejection, not the advanced notice, for an invalid expression", async () => {+ renderEditor(cron("0 9 * * *"));+ await editCronText("@daily");+ await waitFor(() => expect(screen.getByText(/expected exactly 5 fields/)).toBeInTheDocument());+ expect(screen.queryByText(/visual editor can't represent/)).not.toBeInTheDocument();+ expect(screen.queryByText(/Checking this expression/)).not.toBeInTheDocument();+ });++ it("blames the timezone in advanced-only mode too", async () => {+ previewFailure.badTimezone = true;+ try {+ renderEditor(cron("0 9 1,15 * *"));+ await waitFor(() =>+ expect(screen.getByText(/timezone isn't recognized/)).toBeInTheDocument(),+ );+ expect(screen.queryByText(/visual editor can't represent/)).not.toBeInTheDocument();+ } finally {+ previewFailure.badTimezone = false;+ }+ });++ it("surfaces a rejection whose code it does not know, with the server's reason", async () => {+ previewFailure.unknownCode = true;+ try {+ renderEditor(cron("0 9 * * *"));+ // An unclassifiable 400 is still a refusal: it blocks the save and carries+ // the server's own words, rather than being swallowed as an outage.+ await waitFor(() => expect(screen.getByText(/rejected by policy/)).toBeInTheDocument());+ expect(screen.getByTestId("valid-out").textContent).toBe("false");+ expect(screen.getByText("This cron expression isn't valid.")).toBeInTheDocument();+ } finally {+ previewFailure.unknownCode = false;+ }+ });++ // Every numeric field in the panel is a wheel, not a slider: stepping off one+ // end of its range comes out at the other. A field that stopped dead at its+ // bound would leave a keyboard user pressing a key that does nothing, and make+ // 23:00 → 00:00 a mouse-only move.+ describe("keyboard stepping wraps within each field's range", () => {+ it("wraps the fixed time's hour and minute", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 23 * * *"));+ await user.click(screen.getByLabelText("Hour"));+ await user.keyboard("{ArrowUp}");+ expect(cronOut()).toBe("0 0 * * *");+ await user.keyboard("{ArrowDown}");+ expect(cronOut()).toBe("0 23 * * *");++ await user.click(screen.getByLabelText("Minute"));+ await user.keyboard("{ArrowDown}");+ expect(cronOut()).toBe("59 23 * * *");+ await user.keyboard("{ArrowUp}");+ expect(cronOut()).toBe("0 23 * * *");+ });++ it("wraps the firing minute an all-day interval carries in its window start", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 */2 * * *"));+ await user.click(screen.getByLabelText("Window start minute"));+ await user.keyboard("{ArrowDown}");+ // Still all day — only the minute moved, so the schedule keeps its "*/2".+ expect(cronOut()).toBe("59 */2 * * *");+ });++ it("wraps the interval step within the unit's range", async () => {+ const user = userEvent.setup();+ // The step starts at 1, which is its minimum — not 0, so its wrap-around+ // lands on the unit's max rather than on some shared 0.+ renderEditor(cron("0 * * * *"));+ await user.click(screen.getByLabelText("Interval"));+ await user.keyboard("{ArrowDown}");+ expect(cronOut()).toBe("0 */23 * * *");+ await user.keyboard("{ArrowUp}");+ expect(cronOut()).toBe("0 * * * *");++ // Minutes carry a different ceiling, and the wrap must follow it.+ await user.click(screen.getByLabelText("Interval unit"));+ await user.click(await screen.findByRole("option", { name: "minutes" }));+ await user.click(screen.getByLabelText("Interval"));+ await user.keyboard("{ArrowDown}");+ expect(cronOut()).toBe("*/59 * * * *");+ });++ it("wraps the day of month", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 9 31 * *"));+ const day = screen.getByLabelText("Day of month");+ await user.click(day);+ await user.keyboard("{ArrowUp}");+ expect(cronOut()).toBe("0 9 1 * *");+ await user.keyboard("{ArrowDown}");+ expect(cronOut()).toBe("0 9 31 * *");+ });++ it("wraps the window end within the range its start leaves it", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 9-15/2 * * *"));+ const end = screen.getByLabelText("Window end hour");+ await user.click(end);+ // Pull the end down onto the start, so the next step is off the bottom of+ // its range. (Typed, not parsed: "9-9/2" reads back as a fixed 9:00.)+ await user.keyboard("09");+ expect(cronOut()).toBe("0 9-9/2 * * *");+ // A completed pair hands focus on to the minute; the hour is where the+ // stepping is being tested.+ await user.click(end);+ // The end can never precede the start, so its range is 9–23: stepping+ // below 9 comes out at 23, not at 8 (which has no cron form) and not stuck+ // on 9 (which is the same key doing nothing).+ await user.keyboard("{ArrowDown}");+ expect(cronOut()).toBe("0 9-23/2 * * *");+ await user.keyboard("{ArrowUp}");+ expect(cronOut()).toBe("0 9-9/2 * * *");+ });++ it("keeps an out-of-range end unreachable by typing, too", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 9-15/2 * * *"));+ await user.click(screen.getByLabelText("Window end hour"));+ // 08 is before the start: the field holds it at the start hour rather than+ // wrapping a half-typed number round to 23.+ await user.keyboard("08");+ expect(cronOut()).toBe("0 9-9/2 * * *");+ });++ it("still types a two-digit end whose first digit alone is out of range", async () => {+ const user = userEvent.setup();+ renderEditor(cron("0 9-15/2 * * *"));+ await user.click(screen.getByLabelText("Window end hour"));+ // The "1" of 18 is below the 9 the field starts at. Clamping it for display+ // must not overwrite the digit being typed — the pair still has to land as 18.+ await user.keyboard("18");+ expect(cronOut()).toBe("0 9-18/2 * * *");+ });+ });++ describe("timezone prefix extraction", () => {+ // Extraction rewrites two controls the user is looking at — the zone lands+ // in the picker, the cron box loses the prefix — so a TYPED prefix waits+ // for the server: the text commits verbatim first, and only the preview's+ // 200 for that exact text promotes it to the extracted pair.+ it("moves a typed CRON_TZ= prefix into the picker once the server accepts it", async () => {+ renderEditor(cron("0 9 * * *"));+ await editCronText("CRON_TZ=Asia/Tokyo 30 9 * * 1-5");+ // Before the verdict: verbatim, both controls untouched.+ expect(screen.getByTestId("raw-out").textContent).toBe("CRON_TZ=Asia/Tokyo 30 9 * * 1-5");+ expect(screen.getByTestId("tz-out").textContent).toBe("UTC");+ // The 200 lands both rewrites at once.+ await waitFor(() =>+ expect(screen.getByTestId("tz-out").textContent).toBe("Asia/Tokyo"),+ );+ expect(screen.getByTestId("raw-out").textContent).toBe("null");+ expect(cronOut()).toBe("30 9 * * 1-5");+ });++ it("promotes into advanced-only when the rest is beyond the model", async () => {+ renderEditor(cron("0 9 * * *"));+ await editCronText("TZ=Asia/Tokyo ?/2 ?/2 * * ?/2");+ await waitFor(() =>+ expect(screen.getByTestId("tz-out").textContent).toBe("Asia/Tokyo"),+ );+ expect(screen.getByTestId("raw-out").textContent).toBe("?/2 ?/2 * * ?/2");+ });++ it("never promotes an expression the server rejected", async () => {+ renderEditor(cron("0 9 * * *"));+ await editCronText("TZ=Europe/Berlin 0 9 * * *");+ // The mock's server knows no Berlin; the browser does. The text must+ // stay exactly as typed, under the server's own error — the picker never+ // shows a zone the server refused.+ await waitFor(() =>+ expect(screen.getByText("This cron expression isn't valid.")).toBeInTheDocument(),+ );+ expect(screen.getByTestId("raw-out").textContent).toBe("TZ=Europe/Berlin 0 9 * * *");+ expect(screen.getByTestId("tz-out").textContent).toBe("UTC");+ });++ it("leaves a zone the picker cannot offer buried in the text, even accepted", async () => {+ renderEditor(cron("0 9 * * *"));+ await editCronText("TZ=Local 0 9 * * *");+ // "Local" is legal server-side (the SERVER host's zone) — the preview+ // 200s — but no browser zone: there is nothing the picker could show for+ // it, so the expression stays verbatim and keeps meaning what it meant.+ await waitFor(() => expect(screen.getByText("Next runs")).toBeInTheDocument());+ expect(screen.getByTestId("raw-out").textContent).toBe("TZ=Local 0 9 * * *");+ expect(screen.getByTestId("tz-out").textContent).toBe("UTC");+ });++ it("leaves a prefix with no schedule after it verbatim, timezone untouched", async () => {+ renderEditor(cron("0 9 * * *"));+ await editCronText("TZ=Asia/Tokyo");+ // robfig v3.0.1 panics on this shape and the (guarded) server rejects it;+ // rewriting any of it would put words in the user's mouth mid-typo.+ await waitFor(() =>+ expect(screen.getByText("This cron expression isn't valid.")).toBeInTheDocument(),+ );+ expect(screen.getByTestId("raw-out").textContent).toBe("TZ=Asia/Tokyo");+ expect(screen.getByTestId("tz-out").textContent).toBe("UTC");+ });++ it("promotes a lowercase zone under its canonical spelling", async () => {+ renderEditor(cron("0 9 * * *"));+ await editCronText("TZ=asia/shanghai 0 9 * * *");+ // The mock's server takes the lowercase spelling (a case-insensitive+ // filesystem does), but the picker's list knows only "Asia/Shanghai" —+ // seating "asia/shanghai" would show the same zone twice.+ await waitFor(() =>+ expect(screen.getByTestId("tz-out").textContent).toBe("Asia/Shanghai"),+ );+ expect(screen.getByTestId("raw-out").textContent).toBe("null");+ expect(cronOut()).toBe("0 9 * * *");+ });++ it("extracts immediately on hydration — a stored expression already passed the server", () => {+ renderEditor(cron("CRON_TZ=Asia/Tokyo 30 9 * * 1-5"));+ expect(screen.getByTestId("raw-out").textContent).toBe("null");+ expect(screen.getByTestId("tz-out").textContent).toBe("Asia/Tokyo");+ expect(cronOut()).toBe("30 9 * * 1-5");+ });+ });++ describe("timezone prefix as the wire form", () => {+ // The expression that leaves the editor — for the preview and for saving —+ // always carries the timezone as a TZ= prefix, so the cron string and the+ // timezone column can never disagree about which zone governs the schedule.+ it("serialises the picker's zone into the expression it validates and saves", async () => {+ renderEditor(cron("0 9 * * *"));+ expect(wireOut()).toBe("TZ=UTC 0 9 * * *");+ previewCalls.length = 0;+ fireEvent.change(screen.getByTestId("timezone-picker"), {+ target: { value: "Asia/Shanghai" },+ });+ // The prefix follows the picker; the fields do not move.+ expect(wireOut()).toBe("TZ=Asia/Shanghai 0 9 * * *");+ expect(cronOut()).toBe("0 9 * * *");+ // And the preview judges the prefixed pair, not the bare fields.+ await waitFor(() =>+ expect(previewCalls).toContain("TZ=Asia/Shanghai 0 9 * * *"),+ );+ });++ it("draws the prefix as a fixed segment, outside the editable text", async () => {+ renderEditor(cron("0 9 * * *"));+ const input = await openCronInput();+ // The zone is not characters in the field — it cannot be half-deleted+ // into the no-space shape robfig panics on.+ expect((input as HTMLInputElement).value).toBe("0 9 * * *");+ expect(screen.getByText("TZ=UTC")).toBeInTheDocument();+ });++ it("keeps focus in the field when the fixed segment is clicked", async () => {+ renderEditor(cron("0 9 * * *"));+ await openCronInput();+ // The browser moves focus on mousedown, before the addon's click-to-focus+ // can run — and blurring the input is what closes the field. The segment+ // must swallow the mousedown (fireEvent returns false when the default+ // was prevented) so focus never leaves.+ expect(fireEvent.mouseDown(screen.getByText("TZ=UTC"))).toBe(false);+ });++ it("yields the fixed segment while a typed prefix awaits the verdict", async () => {+ renderEditor(cron("0 9 * * *"));+ await editCronText("TZ=Local 0 9 * * *");+ // The committed text carries its own prefix; drawing the picker's next+ // to it would read as an expression carrying both. It also must not be+ // stacked onto the wire form — robfig strips ONE prefix and would read+ // the second as a field.+ await waitFor(() => expect(screen.getByText("Next runs")).toBeInTheDocument());+ expect(wireOut()).toBe("TZ=Local 0 9 * * *");+ const input = await openCronInput();+ expect((input as HTMLInputElement).value).toBe("TZ=Local 0 9 * * *");+ expect(screen.queryByText("TZ=UTC")).not.toBeInTheDocument();+ });++ it("re-serialises a promoted CRON_TZ= under the canonical TZ= segment", async () => {+ renderEditor(cron("0 9 * * *"));+ await editCronText("CRON_TZ=Asia/Tokyo 30 9 * * 1-5");+ await waitFor(() =>+ expect(screen.getByTestId("tz-out").textContent).toBe("Asia/Tokyo"),+ );+ expect(wireOut()).toBe("TZ=Asia/Tokyo 30 9 * * 1-5");+ });+ });+});diff --git a/packages/views/autopilots/components/schedule-editor/schedule-editor.tsx b/packages/views/autopilots/components/schedule-editor/schedule-editor.tsxnew file mode 100644index 0000000000..fd9e11dc0d--- /dev/null+++ b/packages/views/autopilots/components/schedule-editor/schedule-editor.tsx@@ -0,0 +1,1204 @@+"use client";++import {+ useEffect,+ useId,+ useMemo,+ useRef,+ useState,+ type ComponentProps,+ type ComponentType,+ type ReactNode,+} from "react";+import { useQuery } from "@tanstack/react-query";+import { Clock, Pencil } from "lucide-react";+import { cn } from "@multica/ui/lib/utils";+import { Input } from "@multica/ui/components/ui/input";+import {+ InputGroup,+ InputGroupAddon,+ InputGroupInput,+ InputGroupSelectTrigger,+ InputGroupText,+ InputGroupTimeInput,+} from "@multica/ui/components/ui/input-group";+import {+ Select,+ SelectTrigger,+ SelectValue,+ SelectContent,+ SelectItem,+} from "@multica/ui/components/ui/select";+import { TimeInput } from "@multica/ui/components/ui/time-input";+import { cronPreviewOptions } from "@multica/core/autopilots/queries";+import { ApiError } from "@multica/core/api";+import { timezoneOptions } from "../../../common/timezone-select";+import { useDebouncedValue } from "../../../common/use-debounced-value";+import { SegmentedToggle } from "../../../common/segmented-toggle";+import { formatInTimeZone } from "../../../common/format-in-time-zone";+import { TimezonePicker } from "../pickers/timezone-picker";+import { useT } from "../../../i18n";+import type { DayPattern, ScheduleConfig, TimePattern } from "./model";+import { DAY_KEYS, pad2, timeParts } from "./model";+import {+ cronFields,+ extractTimezonePrefix,+ hasTimezonePrefix,+ parseCron,+ toCron,+} from "./cron-mapping";+import { classifyScheduleRejection } from "./validate";+import { useDescribeSchedule } from "./describe";++export interface ScheduleEditorProps {+ value: ScheduleConfig;+ onChange: (value: ScheduleConfig) => void;+ wsId: string;+ disabled?: boolean;+ disabledReason?: string;+ /** Fires when the server accepts or rejects the current expression, so the+ * owning dialog can keep its submit button in step with the inline error. */+ onValidityChange?: (valid: boolean) => void;+}++const PREVIEW_DEBOUNCE_MS = 300;++type EveryPattern = Extract<TimePattern, { kind: "every" }>;+type ScheduleWindow = { from: string; to: string };++function useNowTicker(intervalMs = 30_000): Date {+ const [now, setNow] = useState(() => new Date());+ useEffect(() => {+ const id = setInterval(() => setNow(new Date()), intervalMs);+ return () => clearInterval(id);+ }, [intervalMs]);+ return now;+}++function useFormatCountdown() {+ const { t } = useT("autopilots");+ return (target: Date, now: Date): string => {+ const diffMs = target.getTime() - now.getTime();+ if (diffMs < 60_000) return t(($) => $.schedule_editor.countdown.less_than_minute);+ const minutes = Math.floor(diffMs / 60_000);+ const hours = Math.floor(minutes / 60);+ const days = Math.floor(hours / 24);+ if (days > 0)+ return t(($) => $.schedule_editor.countdown.days_hours, {+ days,+ hours: hours % 24,+ minutes: minutes % 60,+ });+ if (hours > 0)+ return t(($) => $.schedule_editor.countdown.hours_minutes, {+ hours,+ minutes: minutes % 60,+ });+ return t(($) => $.schedule_editor.countdown.minutes, { minutes });+ };+}++// The window is a dimension of the schedule, not a mode of the editor: all day is+// the window that spans the day, and the model spells that one way — `window:+// null`. Every window the editor commits goes through here, so the two never drift+// into two representations of the same schedule.+//+// The bounds are read as hours. A minute-step window is hour-granular (its ends+// read :00 and :59), and an hours-step window carries the firing minute at both+// ends — neither minute has a say in whether the window spans the day.+function isFullDay(window: ScheduleWindow): boolean {+ return timeParts(window.from).hour === 0 && timeParts(window.to).hour === 23;+}++/** The window as the controls show it. All day has no window of its own, and the+ * fields still have to render something: the bounds it stands for. */+function displayWindow(time: EveryPattern): ScheduleWindow {+ if (time.window !== null) return time.window;+ return time.unit === "hours"+ ? { from: `00:${pad2(time.minute)}`, to: `23:${pad2(time.minute)}` }+ : { from: "00:00", to: "23:59" };+}++// An "every N hours, all day" pattern has nowhere to keep an hour, so the last+// hour:minute the user actually expressed is carried outside the model. Without+// it, at 14:30 → interval → at silently comes back as 09:30.+//+// The hour comes from the window, the minute from `minute` — never from the+// window's own text. A minute-step window is hour-granular, so its bounds read+// :00; taking the minute from there would drop the 30 of a 14:30 the user typed+// before switching, which the model still holds.+//+// All day has no hour to give: the 00:00 its fields show is the absence of a+// bound, not a time the user picked, and carrying it over would rewrite their+// 14:30 to 00:30 on the way back to a fixed time.+function timeAnchorOf(time: TimePattern): string | null {+ if (time.kind === "at") return time.time;+ if (time.window === null) return null;+ return `${pad2(timeParts(time.window.from).hour)}:${pad2(time.minute)}`;+}++function defaultAtTime(prev: TimePattern, anchor: string): string {+ return (+ timeAnchorOf(prev) ??+ `${pad2(timeParts(anchor).hour)}:${pad2(prev.kind === "every" ? prev.minute : 0)}`+ );+}++// Switching to a fixed time can only carry one HH:MM, so the step, the unit and+// the window would be gone on the way back — "every 3h, 9:00–21:00" would return+// as "every hour, all day". They are remembered outside the model and restored,+// rebased on whatever time the user is now switching away from.+function defaultEveryTime(prev: TimePattern, anchor: EveryPattern | null): EveryPattern {+ if (prev.kind === "every") return prev;+ const { hour, minute } = timeParts(prev.time);+ const base: EveryPattern = anchor ?? {+ kind: "every",+ interval: 1,+ unit: "hours",+ window: null,+ minute,+ };+ const time: EveryPattern = { ...base, minute };+ if (time.window === null) return time;+ // The window restarts at the time the user is switching away from — but only+ // where that still leaves a window. Rebasing "09:00–15:00" onto a 22:00 fixed+ // time would drag the end up to 22 and hand back the single hour 22:00–22:00,+ // destroying the very window this anchor exists to keep.+ // Strictly earlier: a start rebased onto the end hour itself leaves the single+ // hour 15:00–15:00, which is the same collapse by another name.+ const rebased =+ hour < timeParts(time.window.to).hour+ ? { from: `${pad2(hour)}:${pad2(minute)}`, to: time.window.to }+ : time.window;+ // Rebasing a window that ends at 23 onto a midnight fixed time spans the whole+ // day, and a window that spans the day is not one — the model holds that as all+ // day, and nothing else may hand back a second form of it.+ const window = clampWindow(rebased, time.unit, minute);+ return { ...time, window: isFullDay(window) ? null : window };+}++// Keep windows canonical: `minute` — not the window's own current text — is the+// single source of truth for the firing minute, so a hours → minutes → hours+// unit round-trip restores it instead of leaving the zeroed value behind. Minute+// intervals are hour-granular, and `to` is never earlier than `from`.+function clampWindow(+ window: ScheduleWindow,+ unit: EveryPattern["unit"],+ minute: number,+): ScheduleWindow {+ const from = timeParts(window.from);+ const to = timeParts(window.to);+ const edgeMinute = unit === "hours" ? minute : 0;+ const endMinute = unit === "hours" ? minute : 59;+ const endHour = Math.max(to.hour, from.hour);+ return {+ from: `${pad2(from.hour)}:${pad2(edgeMinute)}`,+ to: `${pad2(endHour)}:${pad2(endMinute)}`,+ };+}++function toggleDay(days: number[], day: number): number[] {+ if (days.includes(day)) {+ if (days.length === 1) return days;+ return days.filter((d) => d !== day);+ }+ return [...days, day].toSorted((a, b) => a - b);+}++/** One dimension of the schedule. A fieldset, not a styled div: a greyed-out+ * control that keyboard users can still reach would silently overwrite the+ * stored expression. */+function ScheduleField({+ label,+ disabled,+ children,+}: {+ label: string;+ disabled: boolean;+ children: ReactNode;+}) {+ return (+ // No `m-0` here: it ties with the parent's space-y on specificity and wins on+ // source order, zeroing the gap between the blocks. Preflight already resets+ // the fieldset's margin.+ //+ // Label above its controls, each block full width: the panel is a narrow+ // sidebar column, and a label column would take a quarter of it from the+ // controls that have to hold a whole time range.+ // 6px label→control, against the 8px between a block's own controls and the+ // 20px between blocks, so the label reads as the heading of what follows it.+ <fieldset+ disabled={disabled}+ className={cn("flex min-w-0 flex-col gap-1.5 border-0 p-0", disabled && "opacity-60")}+ >+ <p className="text-xs font-medium text-muted-foreground">{label}</p>+ {/* flex gap, not space-y: Base UI's Select appends a hidden fixed-position+ form input after the trigger, which space-y counts as the last child —+ handing its 8px to the visible control and inflating the block. */}+ <div className="flex min-w-0 flex-col gap-2">{children}</div>+ </fieldset>+ );+}++/** Number field whose DOM text and model value cannot drift apart: clearing it+ * is allowed while typing, and blur reconciles the box with the model —+ * clamping an out-of-range number into the field's bounds, and snapping back to+ * the committed value when the box holds no number at all. Without the clamp,+ * typing "24" into a 1–23 field would commit the 2 of the first keystroke and+ * then reject the pair, leaving "every 2 hours" — a schedule the user never+ * chose — behind. */+function NumberField({+ value,+ min,+ max,+ onCommit,+ className,+ ariaLabel,+ autoFocus,+ // The box this field is drawn in. Standing alone it brings its own; inside an+ // InputGroup the group owns the border, the ring and the focus slot, and+ // InputGroupInput is the same field with all three given up.+ component: Field = Input,+}: {+ value: number;+ min: number;+ max: number;+ onCommit: (value: number) => void;+ className?: string;+ ariaLabel: string;+ autoFocus?: boolean;+ component?: ComponentType<ComponentProps<"input">>;+}) {+ const [text, setText] = useState(String(value));+ const lastValueRef = useRef(value);+ if (lastValueRef.current !== value) {+ lastValueRef.current = value;+ setText(String(value));+ }+ return (+ <Field+ type="number"+ aria-label={ariaLabel}+ // Caller-gated: set only when the user just revealed this field, never on+ // first mount.+ autoFocus={autoFocus}+ min={min}+ max={max}+ value={text}+ onChange={(e) => {+ setText(e.target.value);+ const n = parseInt(e.target.value, 10);+ if (!Number.isNaN(n) && n >= min && n <= max) onCommit(n);+ }}+ // The native stepper stops dead at the bounds; every other field in this+ // panel wraps, so these do too. Stepping off 31 gives day 1 back, not+ // another press that does nothing.+ onKeyDown={(e) => {+ if (e.key !== "ArrowUp" && e.key !== "ArrowDown") return;+ e.preventDefault();+ const typed = parseInt(text, 10);+ // An out-of-range box is not somewhere to step FROM — stepping is what+ // brings it back in, and it lands on the bound it overshot. Clamping+ // first and then stepping would step off that bound instead, so the+ // bound itself could never be reached: in a 1-31 field, an arrow on a+ // typed "0" gave 2, and one on "40" gave 30.+ const stepped =+ Number.isNaN(typed) || typed >= min && typed <= max+ ? (Number.isNaN(typed) ? value : typed) + (e.key === "ArrowUp" ? 1 : -1)+ : Math.min(max, Math.max(min, typed));+ const wrapped = stepped > max ? min : stepped < min ? max : stepped;+ setText(String(wrapped));+ if (wrapped !== lastValueRef.current) onCommit(wrapped);+ }}+ onBlur={() => {+ const n = parseInt(text, 10);+ if (Number.isNaN(n)) {+ setText(String(lastValueRef.current));+ return;+ }+ const clamped = Math.min(max, Math.max(min, n));+ setText(String(clamped));+ if (clamped !== lastValueRef.current) onCommit(clamped);+ }}+ className={className}+ />+ );+}++// The two window fields sit tight against each other so the interval box beside+// them keeps the width. Trimmed from the field's default padding and digit gap:+// the group's own border already frames them, and there is nothing between the+// two ends but the "~", so the roomier standalone spacing is width the row can't+// spare here.+const WINDOW_FIELD_COMPACT = "gap-0.5 px-1";++export function ScheduleEditor({+ value,+ onChange,+ wsId,+ disabled,+ disabledReason,+ onValidityChange,+}: ScheduleEditorProps) {+ const { t, i18n } = useT("autopilots");+ const describe = useDescribeSchedule();+ const formatCountdown = useFormatCountdown();+ const now = useNowTicker();+ const advanced = value.raw !== null;+ const locked = disabled === true;++ // The cron text mirrors the structured model except while the user is+ // typing in the cron input, where the draft wins until it is applied.+ // Applying only on blur/Enter (never on a typing pause) keeps a half-typed+ // expression from flipping the editor into advanced-only mode mid-edit.+ const [cronDraft, setCronDraft] = useState<string | null>(null);+ // Two views of the committed expression. The wire form (toCron) carries the+ // timezone as a `TZ=` prefix and is what validation and saving see; the box+ // holds only the five fields, because its prefix is a fixed group segment+ // drawn from the picker, not characters the user can edit or delete.+ const committedCron = toCron(value);+ const fieldsText = cronFields(value);+ const cronText = cronDraft ?? fieldsText;+ // A typed `TZ=` prefix lives in the text itself until the server has ruled+ // on it (see applyDraft), and while it does the fixed segment yields — two+ // prefixes on screen would read as an expression that carries both.+ const ownPrefix = hasTimezonePrefix(cronText);+ const [cronEditing, setCronEditing] = useState(false);+ const cronInputRef = useRef<HTMLInputElement | null>(null);+ // Autofocus leaves the caret at the end, scrolling a long expression's head+ // out of view the moment it opens; the edit starts where the readback left off.+ useEffect(() => {+ if (!cronEditing) return;+ const input = cronInputRef.current;+ if (input === null) return;+ input.setSelectionRange(0, 0);+ input.scrollLeft = 0;+ }, [cronEditing]);+ const cronErrorId = useId();+ // Advanced-only expressions cannot be edited anywhere else, so their field is+ // always open.+ const cronOpen = advanced || cronEditing;++ const timeAnchorRef = useRef(timeAnchorOf(value.time) ?? "09:00");+ const currentAnchor = timeAnchorOf(value.time);+ if (currentAnchor !== null) timeAnchorRef.current = currentAnchor;++ const everyAnchorRef = useRef<EveryPattern | null>(null);+ if (value.time.kind === "every") everyAnchorRef.current = value.time;++ // Hours cap the step at 23, minutes at 59, so switching units clamps — and a+ // step of 45 minutes would come back from a glance at "hours" as 23. Each+ // unit remembers its own last step.+ const intervalAnchorRef = useRef<Record<EveryPattern["unit"], number | null>>({+ hours: null,+ minutes: null,+ });+ if (value.time.kind === "every") {+ intervalAnchorRef.current[value.time.unit] = value.time.interval;+ }++ // The day kinds cannot hold each other's value either: "every day" has no day+ // set, weekly has no day number. A glance at another kind and back would+ // otherwise return Tue/Thu/Sat as Monday, and day 25 as day 1.+ const daysOfWeekAnchorRef = useRef<number[]>([1]);+ const dayOfMonthAnchorRef = useRef(1);+ if (value.days.kind === "weekly") daysOfWeekAnchorRef.current = value.days.daysOfWeek;+ if (value.days.kind === "monthly") dayOfMonthAnchorRef.current = value.days.dayOfMonth;++ // Focus the field a mode switch just revealed, so the user can type straight+ // away: the time toggle swaps in a fresh control, and picking "Day of month"+ // brings up the day box. The flag is set at the switch, read by the mounting+ // control's autoFocus, and cleared after the commit — so it fires only on a+ // user switch, never on the dialog's first render (which would steal focus and+ // scroll the panel on open). A passive effect resets it, well after autoFocus+ // has run during the commit.+ const focusTimeFieldRef = useRef(false);+ const focusDayFieldRef = useRef(false);+ useEffect(() => {+ focusTimeFieldRef.current = false;+ focusDayFieldRef.current = false;+ });++ // A typed expression carrying a `TZ=` prefix, awaiting the server's verdict+ // before it is promoted to its extracted form (see applyDraft). Compared+ // against committedCron before every use, so a later edit retires it without+ // needing to be cleared.+ const pendingTzPromotionRef = useRef<string | null>(null);++ /** Commit the cron box's text. Returns whether the editor is in advanced-only+ * mode afterwards — the caller cannot read that off `advanced`, which still+ * holds the value from the render being left. */+ const applyDraft = (draft: string): boolean => {+ const next = draft.trim();+ setCronDraft(null);+ // An empty expression is not a schedule: snap back to the model rather+ // than writing "" into `raw` and letting the dialog submit it.+ if (next.length === 0 || next === cronFields(value)) return advanced;+ // A typed `TZ=` prefix is NOT extracted here. Extraction rewrites two+ // controls at once — the zone lands in the picker, the text loses the+ // prefix — and only the server can say the zone is real, so both rewrites+ // wait for its verdict: the expression is committed verbatim (advanced),+ // and the effect below promotes it to the extracted pair when the preview+ // for this exact text comes back accepted. Until then the picker never+ // shows a zone the server might reject, and the box never loses a+ // character the user could still be fixing. (Hydration is different:+ // parseCron extracts immediately there, because a STORED expression+ // already passed the server's validation when it was saved.)+ if (extractTimezonePrefix(next) !== null) {+ pendingTzPromotionRef.current = next;+ onChange({ ...value, raw: next });+ return true;+ }+ pendingTzPromotionRef.current = null;+ const parsed = parseCron(next, value.timezone);+ // An expression beyond the model keeps the structured schedule underneath+ // it. parseCron has no previous config to work from and hands back the+ // 09:00 defaults with the text in `raw`; letting those defaults land would+ // show the greyed-out controls a schedule the user never had, and lose+ // theirs the moment they simplify the expression again.+ onChange(parsed.raw === null ? parsed : { ...value, raw: next });+ return parsed.raw !== null;+ };++ const setTime = (time: TimePattern) => {+ setCronDraft(null);+ onChange({ ...value, time, raw: null });+ };+ const setDays = (days: DayPattern) => {+ setCronDraft(null);+ onChange({ ...value, days, raw: null });+ };+ // Timezone is orthogonal to the expression, so it stays editable — and+ // `raw` stays untouched — in advanced-only mode.+ const setTimezone = (timezone: string) => onChange({ ...value, timezone });++ // The preview stays on even when the editor is locked: it is read-only+ // information the user still needs (the old editor showed it too). It follows+ // the committed expression, not the draft — validation happens once the cron+ // field is left, never on every keystroke.+ const previewExpr = useDebouncedValue(committedCron, PREVIEW_DEBOUNCE_MS);+ const preview = useQuery(+ cronPreviewOptions(wsId, previewExpr, value.timezone, {+ enabled: previewExpr.trim().length > 0,+ }),+ );+ const { refetch } = preview;+ // `null` means the response could not be read (schema drift) — distinct from+ // an empty list, which means the expression genuinely never fires.+ const nextRuns = preview.data?.next_runs ?? null;++ // Only a 400 means "this input is invalid" — a transport or server failure+ // must not be painted as the user's cron being wrong. The server tags which+ // input it rejected, because the cron and the timezone are fixed in+ // different controls.+ const previewIsCurrent = previewExpr === committedCron;+ const liveRejection =+ previewIsCurrent && preview.error instanceof ApiError && preview.error.status === 400+ ? preview.error+ : null;++ // Promote a pending `TZ=` expression once the server has accepted it — and+ // only the exact text the verdict is about. The preview judged the verbatim+ // prefixed expression (the server reads the embedded zone itself), so a 200+ // covers both rewrites the promotion makes: the zone moves into the picker+ // and the prefix comes off the cron box. On a rejection nothing happens: the+ // text stays as typed, under the server's own error.+ const promoted = pendingTzPromotionRef.current;+ useEffect(() => {+ if (promoted === null || promoted !== committedCron) return;+ if (!previewIsCurrent || !preview.isSuccess) return;+ pendingTzPromotionRef.current = null;+ onChange(parseCron(promoted, value.timezone));+ }, [promoted, committedCron, previewIsCurrent, preview.isSuccess, value.timezone, onChange]);+ // The server's last verdict outlives the request that produced it, but only+ // for the exact input it judged — the expression AND the timezone, since the+ // server rejects either. While that input is re-queried (a retry, a refetch+ // after an outage) the query holds neither error nor data, and without this a+ // rejection would blink out and Save would go live for a cron the server has+ // already refused — which the pre-write check cannot catch either, since it+ // passes a schedule through when the network is what failed. Only a readable+ // answer changes the verdict; a transport failure says nothing about the cron,+ // and a change to either input retires it by no longer matching the key.+ //+ // Two keys live in this component, one debounce apart. `committedKey` is the+ // input the user has settled on; `queriedKey` (below) is what the query — and+ // so its `refetch` and the data in hand — actually belongs to. Anything+ // reasoning about the user's input takes the committed one; anything reasoning+ // about the request takes the queried one.+ const committedKey = `${committedCron} ${value.timezone}`;+ const verdictRef = useRef<{+ key: string;+ rejection: ApiError | null;+ accepted: boolean;+ } | null>(null);+ if (previewIsCurrent) {+ if (liveRejection !== null) {+ verdictRef.current = { key: committedKey, rejection: liveRejection, accepted: false };+ } else if (preview.isSuccess) {+ // `accepted` licenses the advanced notice: "the server accepts this+ // expression", not "has not rejected it". An unreadable 200 (schema+ // drift) accepts nothing.+ verdictRef.current = { key: committedKey, rejection: null, accepted: nextRuns !== null };+ }+ }+ const verdict = verdictRef.current?.key === committedKey ? verdictRef.current : null;+ const rejection = liveRejection ?? verdict?.rejection ?? null;+ const scheduleRejection = rejection !== null ? classifyScheduleRejection(rejection) : null;+ const cronErrorDetail = scheduleRejection?.detail ?? null;+ const previewUnavailable =+ previewIsCurrent &&+ ((preview.error !== null && cronErrorDetail === null) ||+ (preview.isSuccess && nextRuns === null));++ // The preview arrives one round trip after every edit. Unmounting the line+ // while it is in flight makes it blink out and back on each keystroke, so the+ // last answer stays on screen and its text is replaced in place. It is dimmed+ // and marked busy until it belongs to the current expression, so a stale list+ // is never presented as this schedule's answer.+ const previewIsSettled = previewIsCurrent && preview.isSuccess && nextRuns !== null;+ const serverAccepted = verdict?.accepted === true;+ const shownPreviewRef = useRef<{ runs: string[]; timezone: string } | null>(null);+ if (+ previewIsSettled &&+ (shownPreviewRef.current?.runs !== nextRuns ||+ shownPreviewRef.current.timezone !== value.timezone)+ ) {+ shownPreviewRef.current = { runs: nextRuns, timezone: value.timezone };+ }+ const shownPreview = shownPreviewRef.current;+ // Formatted once per preview, not per render: every keystroke in the cron box+ // and every 30s countdown tick re-renders the editor, while these Intl formats+ // only change when the preview or locale does. Each run renders in full —+ // "Jul 13, 3:00 PM", "7月13日 15:00" — because a bare time under a dated line+ // would read as a footnote to it.+ const shownRuns = useMemo(() => {+ if (shownPreview === null) return [];+ return shownPreview.runs.map((iso) => ({+ iso,+ label: formatInTimeZone(iso, shownPreview.timezone, i18n.language),+ at: Date.parse(iso),+ }));+ }, [shownPreview, i18n.language]);+ const previewIsPending = !previewIsSettled;+ // Busy/dimming only makes sense over the list: the unavailable message never+ // settles, and dimming it forever would read as a permanent loading state.+ const previewShowsList =+ cronErrorDetail === null &&+ !previewUnavailable &&+ shownPreview !== null &&+ shownPreview.runs.length > 0;++ // A malformed timestamp must degrade to "no countdown", never to NaN, so every+ // value is checked before it becomes a Date (see the list below).+ const firstRunMs = nextRuns?.[0] !== undefined ? Date.parse(nextRuns[0]) : Number.NaN;++ // The preview is cached, so once its first entry is in the past the whole+ // list is stale — refresh it. The guard names the input AND the run it was+ // fired for: without the run, a client clock ahead of the server would refetch+ // on every tick; without the input, two schedules sharing a next-run instant+ // (any two that fire at tomorrow 09:00 do) would take one's refresh as+ // covering the other, and nothing else would rescue it — the preview is fresh+ // for 30s and refetchOnWindowFocus is off repo-wide. The input is the+ // *debounced* expression, not the committed one: the query, `refetch` and+ // `firstRunMs` all belong to that, and naming the committed one would mark the+ // new expression as refreshed while the data in hand is still the previous+ // expression's, swallowing the refresh it is owed once its preview arrives.+ const queriedKey = `${previewExpr} ${value.timezone}`;+ const refetchedForRef = useRef<string | null>(null);+ useEffect(() => {+ if (Number.isNaN(firstRunMs) || firstRunMs > now.getTime()) return;+ const fetchedFor = `${queriedKey} ${firstRunMs}`;+ if (refetchedForRef.current === fetchedFor) return;+ refetchedForRef.current = fetchedFor;+ void refetch();+ }, [firstRunMs, now, refetch, queriedKey]);++ // The dialog owns the submit button, so it needs to know the expression the+ // server rejected — otherwise Save persists a cron that can never run. The+ // expression and the timezone are deps of their own: a dialog that optimistically+ // cleared its own submit-time rejection needs the verdict restated even when the+ // rejection text is the one it already had (a cached 400 for the query this+ // edit lands on arrives with no null in between).+ useEffect(() => {+ onValidityChange?.(cronErrorDetail === null);+ }, [cronErrorDetail, committedCron, value.timezone, onValidityChange]);++ const timezones = useMemo(() => timezoneOptions(value.timezone), [value.timezone]);++ const description = describe(value);++ const dayKindLabel = (kind: DayPattern["kind"]): string => {+ if (kind === "every") return t(($) => $.schedule_editor.days_every);+ if (kind === "weekly") return t(($) => $.schedule_editor.days_weekly);+ return t(($) => $.schedule_editor.days_monthly);+ };+ const dayKindItems = (["every", "weekly", "monthly"] as const).map((kind) => ({+ value: kind,+ label: dayKindLabel(kind),+ }));++ return (+ // 20px between blocks, against 8px inside one (label→control, control→its+ // own extra rows): a block must read as further from its neighbour than from+ // its own parts, or the whole panel collapses into one wall of controls.+ <div className="space-y-5">+ <ScheduleField label={t(($) => $.schedule_editor.time_label)} disabled={locked || advanced}>+ <SegmentedToggle+ value={value.time.kind}+ options={[+ ["at", t(($) => $.schedule_editor.time_at)],+ ["every", t(($) => $.schedule_editor.time_every)],+ ]}+ onChange={(kind) => {+ focusTimeFieldRef.current = true;+ setTime(+ kind === "at"+ ? {+ kind: "at",+ time: defaultAtTime(value.time, timeAnchorRef.current),+ }+ : defaultEveryTime(value.time, everyAnchorRef.current),+ );+ }}+ />+ {value.time.kind === "at" ? (+ <TimeInput+ value={value.time.time}+ hourLabel={t(($) => $.schedule_editor.a11y.fixed_hour)}+ minuteLabel={t(($) => $.schedule_editor.a11y.fixed_minute)}+ onChange={(v) => setTime({ kind: "at", time: v })}+ autoFocus={focusTimeFieldRef.current}+ />+ ) : (+ <EveryTimeControls+ time={value.time}+ intervalAnchor={intervalAnchorRef.current}+ onSet={setTime}+ autoFocus={focusTimeFieldRef.current}+ />+ )}+ </ScheduleField>++ <ScheduleField label={t(($) => $.schedule_editor.days_label)} disabled={locked || advanced}>+ {/* A 7:4 grid, the same template as the interval row above, so the two+ rows line up as one two-column grid at the minutes unit. Grid tracks+ size by the template alone — unlike flex, which let each box's own+ padding and w-fit/w-full skew the split and knocked the columns out of+ line. When there is no day-of-month box the select spans both tracks,+ so every/weekly still fill the width. */}+ <div className="grid grid-cols-[7fr_4fr] items-center gap-2">+ <Select+ items={dayKindItems}+ value={value.days.kind}+ onValueChange={(v) => {+ if (!v || v === value.days.kind) return;+ if (v === "every") setDays({ kind: "every" });+ else if (v === "weekly")+ setDays({ kind: "weekly", daysOfWeek: daysOfWeekAnchorRef.current });+ else {+ // Only monthly reveals a field to type into; the day box takes the+ // caret so the day can be set without a second click.+ focusDayFieldRef.current = true;+ setDays({ kind: "monthly", dayOfMonth: dayOfMonthAnchorRef.current });+ }+ }}+ >+ <SelectTrigger+ aria-label={t(($) => $.schedule_editor.a11y.day_pattern)}+ className={cn("w-full min-w-0", value.days.kind !== "monthly" && "col-span-2")}+ >+ <SelectValue>{dayKindLabel(value.days.kind)}</SelectValue>+ </SelectTrigger>+ <SelectContent>+ {dayKindItems.map((item) => (+ <SelectItem key={item.value} value={item.value}>+ {item.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ {value.days.kind === "monthly" && (+ <NumberField+ value={value.days.dayOfMonth}+ min={1}+ max={31}+ ariaLabel={t(($) => $.schedule_editor.a11y.day_of_month)}+ onCommit={(n) => setDays({ kind: "monthly", dayOfMonth: n })}+ className="h-8 min-w-0"+ autoFocus={focusDayFieldRef.current}+ />+ )}+ </div>+ {value.days.kind === "weekly" && (+ <div className="flex w-full gap-0.5">+ {DAY_KEYS.map((dayKey, i) => {+ const days = value.days;+ const selected = days.kind === "weekly" && days.daysOfWeek.includes(i);+ return (+ <button+ key={dayKey}+ type="button"+ aria-pressed={selected}+ // The chip's own text is an abbreviation; the name is not.+ aria-label={t(($) => $.schedule_editor.a11y.days_full[dayKey])}+ onClick={() => {+ if (days.kind !== "weekly") return;+ setDays({+ kind: "weekly",+ daysOfWeek: toggleDay(days.daysOfWeek, i),+ });+ }}+ // flex-1 + min-w-0: the seven chips split the row evenly, so+ // both states share one box model and label width can't+ // change a chip's size.+ className={cn(+ "inline-flex h-6.5 min-w-0 flex-1 items-center justify-center rounded-md",+ "text-[11px] font-medium leading-none transition-colors",+ selected+ ? "bg-foreground text-background"+ : "bg-muted text-muted-foreground hover:text-foreground",+ )}+ >+ {t(($) => $.schedule_editor.days_short[dayKey])}+ </button>+ );+ })}+ </div>+ )}+ {value.days.kind === "monthly" && value.days.dayOfMonth >= 29 && (+ <p className="text-xs text-muted-foreground">+ {t(($) => $.schedule_editor.monthly_short_month_hint, {+ day: value.days.dayOfMonth,+ })}+ </p>+ )}+ </ScheduleField>++ <ScheduleField label={t(($) => $.schedule_editor.timezone_label)} disabled={locked}>+ {/* The fieldset already disables the trigger; disabled:opacity-100 keeps+ the control from dimming a second time on top of it. */}+ <TimezonePicker+ value={value.timezone}+ onChange={setTimezone}+ options={timezones}+ ariaLabel={t(($) => $.schedule_editor.a11y.timezone)}+ className="disabled:opacity-100"+ />+ </ScheduleField>++ {/* The cron text, the plain-language readback and the server preview are+ all derived views of the same expression, so they share one panel: the+ result of the fields above, not more fields alongside them. The cron+ line inside it doubles as the advanced editing entry — clicking it+ swaps the text for an input, and the form dims while raw mode holds. */}+ <div className="rounded-md bg-muted/40 p-2.5 text-xs text-muted-foreground">+ <div className="space-y-2">+ {/* The plain-language sentence leads: it is the line a person reads,+ so it takes the panel's entry and the foreground color, and the+ expression drops to a technical echo below it. */}+ {description !== null && (+ <p className="flex items-start gap-1.5 text-foreground">+ <Clock className="mt-0.5 h-3 w-3 shrink-0" />+ <span>{description}</span>+ </p>+ )}+ {cronOpen ? (+ // The `TZ=` segment is part of the expression but not of the editable+ // text: it renders as a fixed addon drawn from the timezone picker, so+ // the zone cannot be half-deleted into a prefix robfig would panic on,+ // and the fields flow to the server exactly as typed.+ <InputGroup className="bg-background dark:bg-input/30">+ {!ownPrefix && (+ // Its own row above the fields, mirroring the closed readback:+ // a long zone name and long fields truncate independently+ // instead of splitting one line between them.+ <InputGroupAddon align="block-start" className="font-mono text-xs">+ {/* eslint-disable-next-line i18next/no-literal-string -- cron syntax, not copy */}+ <span className="min-w-0 truncate">TZ={value.timezone}</span>+ </InputGroupAddon>+ )}+ <InputGroupInput+ ref={cronInputRef}+ type="text"+ // Only when the user opened the field. An advanced-only expression+ // has it open from the first render, and autofocusing there would+ // pull focus (and the dialog's scroll) to the bottom of the panel+ // on open, past the title the user came to edit.+ autoFocus={cronEditing}+ aria-label={t(($) => $.schedule_editor.cron_toggle)}+ value={cronText}+ disabled={locked}+ onChange={(e) => setCronDraft(e.target.value)}+ onBlur={() => {+ // The mode after the draft lands, not the one being left: an+ // expression simplified back into the model must close the field,+ // and `advanced` still reads true in this render.+ const stillAdvanced = cronDraft !== null ? applyDraft(cronDraft) : advanced;+ // Advanced-only expressions have no structured view to fall back+ // to, so the field stays open.+ if (!stillAdvanced) setCronEditing(false);+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter" && cronDraft !== null) {+ e.preventDefault();+ // Applying can end advanced-only mode, which would collapse the+ // field back to its readback and drop focus to the body under+ // the user's hands. The field stays open until they leave it.+ setCronEditing(true);+ applyDraft(cronDraft);+ }+ }}+ aria-invalid={cronErrorDetail !== null}+ aria-describedby={cronErrorDetail !== null ? cronErrorId : undefined}+ className="font-mono text-sm"+ />+ </InputGroup>+ ) : (+ // The expression is edited where it is shown — clicking it swaps the+ // text for the field, instead of opening a second copy underneath.+ <button+ type="button"+ disabled={locked}+ onClick={() => setCronEditing(true)}+ // The pencil is decoration; this is the name a screen reader hears.+ aria-label={t(($) => $.schedule_editor.cron_click_to_edit)}+ className="flex w-full items-center gap-1.5 text-left hover:text-foreground disabled:pointer-events-none disabled:opacity-60"+ >+ {/* Closed, the readback shows only the editable text — the zone+ is already on screen in the picker above, and a self-prefixed+ advanced expression carries its zone in the text itself. The+ full wire form appears when the field opens, as the fixed+ segment above the fields. */}+ <span className="min-w-0 truncate font-mono">{cronText}</span>+ <Pencil aria-hidden className="h-3 w-3 shrink-0 opacity-60" />+ </button>+ )}+ {/* One note under the expression, never a stack of them: a rejection is+ what the user must act on, the advanced notice explains why the+ controls are off, and the syntax hint is the fallback. */}+ {cronErrorDetail !== null ? (+ // The rejection names the field it belongs to (aria-describedby) and+ // announces itself: without it, the only feedback a screen-reader+ // user gets for a bad expression is a Save button that went quiet.+ <div id={cronErrorId} role="alert" className="space-y-0.5">+ <p className="text-destructive">+ {scheduleRejection?.code === "invalid_timezone"+ ? t(($) => $.schedule_editor.timezone_invalid)+ : t(($) => $.schedule_editor.cron_invalid)}+ </p>+ {/* The parser's own words, verbatim — untranslated, but it is the+ only text that says which field is wrong. */}+ <p className="font-mono text-[11px] text-destructive/70">{cronErrorDetail}</p>+ </div>+ ) : advanced ? (+ // Three different things are being said here, and only the first is+ // a statement about the expression: the server took it and the+ // controls cannot show it; we could not ask; we have not asked yet.+ <p>+ {serverAccepted+ ? t(($) => $.schedule_editor.advanced_hint)+ : previewUnavailable+ ? t(($) => $.schedule_editor.advanced_unverified)+ : t(($) => $.schedule_editor.advanced_checking)}+ </p>+ ) : cronOpen ? (+ <p>{t(($) => $.schedule_editor.cron_hint)}</p>+ ) : null}+ </div>++ {/* A rejected expression has nothing to preview: the whole section goes,+ heading and divider with it, rather than leaving an empty frame under+ the error. The error already fills the space it vacates.++ Otherwise the height is reserved: the preview is a round trip behind+ every edit, and a section that collapsed and reappeared would reflow+ the dialog. Same elements across fetches: React swaps the text nodes+ instead of tearing the section down, so a re-render of the same+ schedule never flashes — it just dims and reports busy until the+ answer is current. */}+ {cronErrorDetail === null && (+ <div+ aria-busy={previewShowsList ? previewIsPending : undefined}+ className={cn(+ "mt-2.5 min-h-14 border-t border-border/60 pt-2.5 transition-opacity",+ previewShowsList && previewIsPending && "opacity-50",+ )}+ >+ <p className="mb-1.5 font-medium text-foreground">+ {t(($) => $.schedule_editor.next_runs_label)}+ </p>+ {previewUnavailable ? (+ <p>{t(($) => $.schedule_editor.preview_unavailable)}</p>+ ) : shownPreview !== null && shownPreview.runs.length > 0 ? (+ // A grid, not per-row flex: the localized dates are not fixed-width,+ // so only a shared column can line the countdowns up with each+ // other. max-content sizes that column to the widest date.+ <ul className="grid grid-cols-[max-content_max-content] gap-x-5 gap-y-1">+ {shownRuns.map(({ iso, label, at }) => (+ // contents: the row's two cells belong to the grid above,+ // not to a box of their own.+ <li key={iso} className="contents">+ {/* Dark date, dim countdown: the icon column is gone — the+ grid already lines the rows up, and the describe line's+ clock stays the panel's only icon. */}+ <span className="text-foreground tabular-nums">{label}</span>+ {/* Each run carries its own countdown, next to the time+ it counts down to. */}+ <span className="whitespace-nowrap tabular-nums opacity-70">+ {Number.isNaN(at)+ ? ""+ : t(($) => $.schedule_editor.next_in, {+ countdown: formatCountdown(new Date(at), now),+ })}+ </span>+ </li>+ ))}+ </ul>+ ) : previewIsSettled ? (+ // An empty list from a readable response: valid syntax, never fires.+ <p>{t(($) => $.schedule_editor.no_upcoming_runs)}</p>+ ) : null}+ </div>+ )}+ </div>+ {disabled === true && disabledReason !== undefined && (+ <p className="mt-2 text-[11px] text-muted-foreground">{disabledReason}</p>+ )}+ </div>+ );+}++function EveryTimeControls({+ time,+ intervalAnchor,+ onSet,+ autoFocus,+}: {+ time: EveryPattern;+ intervalAnchor: Record<EveryPattern["unit"], number | null>;+ onSet: (time: TimePattern) => void;+ autoFocus?: boolean;+}) {+ const { t } = useT("autopilots");+ const maxInterval = time.unit === "hours" ? 23 : 59;+ const unitItems = (["hours", "minutes"] as const).map((unit) => ({+ value: unit,+ label:+ unit === "hours"+ ? t(($) => $.schedule_editor.unit_hours)+ : t(($) => $.schedule_editor.unit_minutes),+ }));+ // The bounds on screen. `time.window` is what the schedule holds — null while it+ // runs all day — and these are what the two fields show either way, so the user+ // narrows the window by editing the day's bounds rather than by first announcing+ // that they want a window at all.+ const window = displayWindow(time);++ // Focus the step field when the unit changes, so the user can retype it for the+ // new unit without reaching back. The field stays mounted across a unit switch,+ // so autoFocus (mount only) cannot do this — focus it once the switch has+ // re-rendered. Queried off the group rather than threaded through+ // NumberField/Input as a ref: those shared components do not forward one, and+ // the step is the group's only number input.+ const groupRef = useRef<HTMLDivElement>(null);+ const focusStepOnUnitChangeRef = useRef(false);+ useEffect(() => {+ if (!focusStepOnUnitChangeRef.current) return;+ focusStepOnUnitChangeRef.current = false;+ const step = groupRef.current?.querySelector<HTMLInputElement>('input[type="number"]');+ step?.focus();+ step?.select();+ }, [time.unit]);++ // The end the user actually asked for. A window cannot run backwards, so a+ // start pushed past the end drags the end along with it — but the end must+ // come back when the start does, or "09:00–15:00", briefly mis-typed as a+ // 22:00 start, is saved as "09:00–22:00" and the autopilot runs twice as often+ // as it was set to.+ const endAnchorRef = useRef<number | null>(null);+ // The end hour this control itself produced by dragging the start. Every other+ // end — typed into the end field or the cron box, hydrated from the server,+ // widened back out by hand — is the user's new intent and re-seeds the+ // anchor; only a drag leaves it standing, because a drag is what the anchor+ // exists to undo.+ //+ // Hours, not the "HH:MM" text: a unit switch rewrites 22:00 to 22:59 without+ // the user touching anything, and taking that for new intent would hand the+ // dragged-open window back as if they had asked for it.+ const draggedEndRef = useRef<number | null>(null);+ if (timeParts(window.to).hour !== draggedEndRef.current) {+ endAnchorRef.current = timeParts(window.to).hour;+ }+ const anchoredEnd = (from: string, to: string): string => {+ const end = Math.max(endAnchorRef.current ?? timeParts(to).hour, timeParts(from).hour);+ return `${pad2(end)}:${pad2(timeParts(to).minute)}`;+ };++ // Every edit of the two fields lands here, and a window that spans the day is+ // committed as the absence of one, so a schedule that runs around the clock has+ // a single form no matter which way the user arrived at it.+ const setWindow = (next: ScheduleWindow, minute: number) => {+ const clamped = clampWindow(next, time.unit, minute);+ onSet({ ...time, minute, window: isFullDay(clamped) ? null : clamped });+ };++ return (+ // Frequency and window on one line: "every N hours" is how often, "from~to"+ // is the daily span it runs within — two settings, two boxes, side by side.+ // A 7:4 grid, the same template as the day row below, so the two rows read as+ // one two-column grid at the minutes unit. The window's min-w-fit lets its+ // track grow past the 4-share to its content, so the wider HH:MM ~ HH:MM at+ // the hours unit fits (the interval track yields) instead of clipping — that+ // unit then steps out of the alignment, which is only asked of minutes.+ <div ref={groupRef} className="grid min-w-0 grid-cols-[7fr_4fr] items-center gap-2">+ {/* "Every 3 hours" is one setting, so it reads as one control: the prefix,+ the step and the unit share a single box. The step takes the room the+ other two leave — the prefix is as wide as its translation, the unit as+ wide as its longest option — so the field never has to be sized against+ text it cannot see. */}+ <InputGroup className="min-w-0">+ {/* pl-2.5, not the addon's default pl-2: this row sits directly above the+ day select, and the two read as one column only if their first+ character starts at the same x. A Select trigger pads to 2.5. */}+ <InputGroupAddon className="pl-2.5">+ {t(($) => $.schedule_editor.every_prefix)}+ </InputGroupAddon>+ <NumberField+ component={InputGroupInput}+ autoFocus={autoFocus}+ value={time.interval}+ min={1}+ max={maxInterval}+ ariaLabel={t(($) => $.schedule_editor.a11y.interval)}+ onCommit={(n) => onSet({ ...time, interval: n })}+ // The spinner would sit between the number and the unit, reading as a+ // control over the word beside it. The arrow keys still step, and still+ // wrap, which the spinner never did.+ // min-w floor so the flex-1 field can never be squeezed to nothing and+ // clip its digits when the row is tight; wide enough for the two-digit+ // max at either unit.+ className="min-w-[2.5ch] px-0 text-center [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"+ />+ <Select+ items={unitItems}+ value={time.unit}+ onValueChange={(v) => {+ if (!v || v === time.unit) return;+ const unit = v as EveryPattern["unit"];+ const max = unit === "hours" ? 23 : 59;+ focusStepOnUnitChangeRef.current = true;+ onSet({+ ...time,+ unit,+ // The step this unit was last set to, if it ever was: clamping 45+ // minutes down to 23 hours is unavoidable, keeping the 23 on the+ // way back is not.+ interval: intervalAnchor[unit] ?? Math.min(time.interval, max),+ // `minute` is carried through untouched: zeroing it here would+ // silently drop the firing minute on a hours → minutes → hours+ // round-trip. toCron ignores it for minute patterns anyway.+ window: time.window === null ? null : clampWindow(time.window, unit, time.minute),+ });+ }}+ >+ <InputGroupSelectTrigger+ aria-label={t(($) => $.schedule_editor.a11y.interval_unit)}+ className="pr-2.5"+ >+ <SelectValue>+ {unitItems.find((item) => item.value === time.unit)?.label}+ </SelectValue>+ </InputGroupSelectTrigger>+ {/* min-w-[7rem]: below the component's 144px default, which the two+ short options don't need — but not so far that "minutes" and its+ check mark (the item's pr-8) lose room. */}+ <SelectContent className="min-w-[7rem]">+ {unitItems.map((item) => (+ <SelectItem key={item.value} value={item.value}>+ {item.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </InputGroup>+ {/* The window, always on screen. One clock leads the whole box (an addon,+ like the interval row's "Every"), not one per field: a single icon marks+ this as a time control without the width two would cost between the ends.++ A minute-step window is hour-granular — cron puts the step in the minute+ field, so the bounds carry no minute of their own. Both ends are the same+ in-place field either way; the minute segment is simply not offered where+ it would mean nothing. */}+ {/* Sits in the grid's 4-share second column, under the day row's number.+ min-w-fit lets that track grow past the share to the box's content: at+ the minutes unit the hour-only window fits the share and stays aligned;+ at hours the wider HH:MM ~ HH:MM pushes the track out and the interval+ yields, rather than the window clipping (its segments never shrink).+ has-disabled off: the group dims itself when anything inside it is+ disabled, and the minute segments are, by design, under a minute step —+ which does not make the row unavailable. A locked or advanced schedule+ still greys out, from the fieldset around the whole block. */}+ <InputGroup className="min-w-fit has-disabled:bg-transparent has-disabled:opacity-100 dark:has-disabled:bg-input/30">+ {/* Leads the box, not focusable: the fields after it take the focus and+ the group's border. pr-0 lets the start field's own padding set the+ icon-to-digit gap, so it matches the gap between the two ends. */}+ <InputGroupAddon className="pl-2 pr-0">+ <Clock className="size-3.5 text-muted-foreground" />+ </InputGroupAddon>+ <InputGroupTimeInput+ className={WINDOW_FIELD_COMPACT}+ showIcon={false}+ hourOnly={time.unit === "minutes"}+ hourLabel={t(($) => $.schedule_editor.a11y.window_start_hour)}+ minuteLabel={t(($) => $.schedule_editor.a11y.window_start_minute)}+ value={window.from}+ onChange={(v) => {+ // The window's two ends share one firing minute — cron has no+ // second minute to put there — so editing either end's minute+ // moves both. setWindow must get the minute just typed, not+ // time.minute: mid-two-digit-entry the model still holds the+ // first digit's value, which would overwrite the second one.+ const minute = time.unit === "hours" ? timeParts(v).minute : time.minute;+ const to = anchoredEnd(v, window.to);+ // Marks this end as the drag's doing, so the next render keeps the+ // anchor instead of taking the dragged value for a new intent.+ // anchoredEnd already keeps the hour at or above the start's, so+ // setWindow's clamp will not move it again.+ draggedEndRef.current = timeParts(to).hour;+ setWindow({ from: v, to }, minute);+ }}+ />+ <InputGroupText className="shrink-0">~</InputGroupText>+ {/* The window's end. The two ends constrain each other as they are edited+ — hourMin keeps the end from falling below the start — so a reversed+ window, which has no cron form, cannot even be displayed, let alone+ submitted. The bound is the field's own range rather than a clamp+ applied to whatever it emits: the arrow keys wrap inside it (stepping+ below the start hour lands on 23, not on a key that does nothing).++ Clearing it opens the window to the end of the day (hourClearTo)+ rather than collapsing it onto the start: backspace on the end of a+ window is how a keyboard user says "run until the day is out". */}+ <InputGroupTimeInput+ className={WINDOW_FIELD_COMPACT}+ showIcon={false}+ value={window.to}+ hourMin={timeParts(window.from).hour}+ hourClearTo={23}+ hourOnly={time.unit === "minutes"}+ hourLabel={t(($) => $.schedule_editor.a11y.window_end_hour)}+ minuteLabel={t(($) => $.schedule_editor.a11y.window_end_minute)}+ onChange={(v) => {+ const minute = time.unit === "hours" ? timeParts(v).minute : time.minute;+ // Typed, not dragged — the end the start has to give back. Set here+ // rather than left to the re-seeding rule, which cannot see intent+ // in an end that happens to equal the one a drag just produced.+ endAnchorRef.current = timeParts(v).hour;+ draggedEndRef.current = timeParts(v).hour;+ setWindow({ from: window.from, to: v }, minute);+ }}+ />+ </InputGroup>+ </div>+ );+}diff --git a/packages/views/autopilots/components/schedule-editor/validate.test.ts b/packages/views/autopilots/components/schedule-editor/validate.test.tsnew file mode 100644index 0000000000..a032414240--- /dev/null+++ b/packages/views/autopilots/components/schedule-editor/validate.test.ts@@ -0,0 +1,80 @@+import { describe, it, expect, vi } from "vitest";+import { QueryClient } from "@tanstack/react-query";+import { ApiError } from "@multica/core/api";+import { findScheduleRejection } from "./validate";+import { parseCron } from "./cron-mapping";++// The submit paths call this right before writing: the editor's inline error+// only covers previews that have settled, so a cron typed and saved in one+// motion would otherwise slip through. Only a 400 may block the save — an+// unreachable preview endpoint must not keep anyone from saving a schedule the+// server would have accepted.++const behavior: { mode: "ok" | "invalid_cron" | "invalid_timezone" | "transport" | "no_code" } = {+ mode: "ok",+};++vi.mock("@multica/core/autopilots/queries", () => ({+ cronPreviewOptions: (wsId: string, expr: string, tz: string) => ({+ queryKey: ["autopilots", wsId, "cron-preview", expr, tz, behavior.mode],+ queryFn: async () => {+ if (behavior.mode === "transport") {+ throw new ApiError("API error: 502 Bad Gateway", 502, "Bad Gateway");+ }+ if (behavior.mode === "invalid_cron") {+ throw new ApiError("parse cron: expected exactly 5 fields", 400, "Bad Request", {+ error: "parse cron: expected exactly 5 fields",+ code: "invalid_cron",+ });+ }+ if (behavior.mode === "invalid_timezone") {+ throw new ApiError(`invalid timezone "${tz}"`, 400, "Bad Request", {+ error: `invalid timezone "${tz}"`,+ code: "invalid_timezone",+ });+ }+ if (behavior.mode === "no_code") {+ throw new ApiError("bad request", 400, "Bad Request", "bad request");+ }+ return { next_runs: ["2126-07-14T01:00:00Z"] };+ },+ retry: false,+ }),+}));++function run() {+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return findScheduleRejection(qc, "ws-test", parseCron("0 9 * * *", "UTC"));+}++describe("findScheduleRejection", () => {+ it("returns null when the server accepts the schedule", async () => {+ behavior.mode = "ok";+ await expect(run()).resolves.toBeNull();+ });++ it("returns the cron rejection with the parser's own words", async () => {+ behavior.mode = "invalid_cron";+ await expect(run()).resolves.toEqual({+ code: "invalid_cron",+ detail: "parse cron: expected exactly 5 fields",+ });+ });++ it("blames the timezone when the server rejects the zone", async () => {+ behavior.mode = "invalid_timezone";+ const rejection = await run();+ expect(rejection?.code).toBe("invalid_timezone");+ });++ it("falls back to invalid_cron when a 400 carries no readable code", async () => {+ behavior.mode = "no_code";+ const rejection = await run();+ expect(rejection?.code).toBe("invalid_cron");+ });++ it("does not block the save on a transport or server failure", async () => {+ behavior.mode = "transport";+ await expect(run()).resolves.toBeNull();+ });+});diff --git a/packages/views/autopilots/components/schedule-editor/validate.ts b/packages/views/autopilots/components/schedule-editor/validate.tsnew file mode 100644index 0000000000..05b167f36b--- /dev/null+++ b/packages/views/autopilots/components/schedule-editor/validate.ts@@ -0,0 +1,112 @@+import { useState } from "react";+import { useQueryClient, type QueryClient } from "@tanstack/react-query";+import { toast } from "sonner";+import { ApiError } from "@multica/core/api";+import { cronPreviewOptions } from "@multica/core/autopilots/queries";+import { useT } from "../../../i18n";+import type { ScheduleConfig } from "./model";+import { toCron } from "./cron-mapping";++/** The server's rejection, split the way the editor is: which input is at fault+ * (the cron box or the timezone picker), and the parser's own words. */+export interface ScheduleRejection {+ code: "invalid_cron" | "invalid_timezone";+ detail: string;+}++/** Read the server's classification off a preview 400. Anything but an explicit+ * invalid_timezone tag is the cron's fault. */+export function classifyScheduleRejection(err: ApiError): ScheduleRejection {+ const body = typeof err.body === "object" && err.body !== null ? err.body : {};+ const code = (body as { code?: unknown }).code;+ return {+ code: code === "invalid_timezone" ? "invalid_timezone" : "invalid_cron",+ detail: err.message,+ };+}++/**+ * Ask the server whether it accepts this schedule, and return its rejection+ * (or null when it accepts).+ *+ * The editor's inline error only covers expressions whose preview has already+ * settled: typing an invalid cron and clicking Save immediately commits the+ * draft on blur while the preview request is still in flight, so the submit+ * gate would still be open. Creating the autopilot in that state persists it+ * and then fails to create its trigger, leaving an autopilot that can never+ * run — so submit paths validate once more before writing.+ *+ * Transport failures resolve to null: an unreachable preview endpoint must not+ * block saving a schedule the server would have accepted.+ */+export async function findScheduleRejection(+ queryClient: QueryClient,+ wsId: string,+ config: ScheduleConfig,+): Promise<ScheduleRejection | null> {+ try {+ await queryClient.fetchQuery(cronPreviewOptions(wsId, toCron(config), config.timezone));+ return null;+ } catch (err) {+ if (!(err instanceof ApiError) || err.status !== 400) return null;+ return classifyScheduleRejection(err);+ }+}++/** Announce a rejection the way both submit paths must: the headline names the+ * control at fault, because the cron and the timezone are fixed in different+ * ones, and the parser's own words go underneath — untranslated, but the only+ * text that says what is actually wrong. */+export function toastScheduleRejection(+ t: ReturnType<typeof useT<"autopilots">>["t"],+ rejection: ScheduleRejection,+): void {+ toast.error(+ rejection.code === "invalid_timezone"+ ? t(($) => $.schedule_editor.timezone_invalid)+ : t(($) => $.schedule_editor.cron_invalid),+ { description: rejection.detail },+ );+}++/**+ * The submit gate every form that writes a schedule needs, in one place: a+ * schedule the server has rejected must not be submittable, or the form+ * persists an autopilot whose trigger then 400s and never runs.+ *+ * - `scheduleValid` gates the submit button, fed by the editor's+ * `onValidityChange` and by `ensureAccepted`.+ * - `clearRejection` belongs in the schedule's `onChange`: a submit-time+ * rejection is the gate's, not the editor's — the editor's own preview may+ * never query that expression if the user edits again before the debounce+ * fires, and then nothing would re-enable Save. Any edit lifts it; the+ * editor's inline error re-disables Save if the new expression is bad too.+ * - `ensureAccepted` runs the pre-write check (see findScheduleRejection) and+ * toasts the rejection itself; the caller only unwinds its own submit state.+ *+ * Mount the owning form only while it is open: the gate's state lives with it,+ * and a form kept mounted closed would carry a stale rejection into its next+ * opening.+ */+export function useScheduleSubmitGate(wsId: string): {+ scheduleValid: boolean;+ clearRejection: () => void;+ onValidityChange: (valid: boolean) => void;+ ensureAccepted: (config: ScheduleConfig) => Promise<boolean>;+} {+ const { t } = useT("autopilots");+ const queryClient = useQueryClient();+ const [scheduleValid, setScheduleValid] = useState(true);+ return {+ scheduleValid,+ clearRejection: () => setScheduleValid(true),+ onValidityChange: setScheduleValid,+ ensureAccepted: async (config: ScheduleConfig): Promise<boolean> => {+ const rejection = await findScheduleRejection(queryClient, wsId, config);+ if (rejection === null) return true;+ setScheduleValid(false);+ toastScheduleRejection(t, rejection);+ return false;+ },+ };+}diff --git a/packages/views/autopilots/components/trigger-config.test.ts b/packages/views/autopilots/components/trigger-config.test.tsdeleted file mode 100644index c094d42075..0000000000--- a/packages/views/autopilots/components/trigger-config.test.ts+++ /dev/null@@ -1,250 +0,0 @@-import { describe, it, expect } from "vitest";-import {- parseCronExpression,- toCronExpression,- getDefaultTriggerConfig,- type TriggerConfig,-} from "./trigger-config";--// The backend accepts standard 5-field cron (robfig/cron v3: minute, hour,-// dom, month, dow — no seconds, no @descriptors). Each field may be `*`, a-// plain number, a range `a-b`, a step `*/n` | `a/n` | `a-b/n`, a list, or a-// name (JAN/MON). The form only models four exact shapes:-//-// hourly M * * * *-// daily M H * * *-// weekdays M H * * 1-5-// weekly M H * * d[,d...] (plain days 0-6)-//-// where M/H/d are plain in-range integers. Every other expression must parse-// as `custom` with the original string preserved in cronExpression.--describe("parseCronExpression", () => {- describe("preset recognition", () => {- it("recognises hourly at minute 0", () => {- const parsed = parseCronExpression("0 * * * *", "UTC");- expect(parsed.frequency).toBe("hourly");- expect(parsed.time).toBe("00:00");- });-- it("recognises hourly at minute 30", () => {- const parsed = parseCronExpression("30 * * * *", "UTC");- expect(parsed.frequency).toBe("hourly");- expect(parsed.time).toBe("00:30");- });-- it("recognises hourly with a zero-padded minute", () => {- const parsed = parseCronExpression("05 * * * *", "UTC");- expect(parsed.frequency).toBe("hourly");- expect(parsed.time).toBe("00:05");- });-- it("recognises daily at midnight", () => {- const parsed = parseCronExpression("0 0 * * *", "UTC");- expect(parsed.frequency).toBe("daily");- expect(parsed.time).toBe("00:00");- });-- it("recognises daily at the last minute of the day", () => {- const parsed = parseCronExpression("59 23 * * *", "UTC");- expect(parsed.frequency).toBe("daily");- expect(parsed.time).toBe("23:59");- });-- it("recognises daily with zero-padded fields", () => {- const parsed = parseCronExpression("05 09 * * *", "UTC");- expect(parsed.frequency).toBe("daily");- expect(parsed.time).toBe("09:05");- });-- it("recognises the weekdays pattern", () => {- const parsed = parseCronExpression("30 18 * * 1-5", "UTC");- expect(parsed.frequency).toBe("weekdays");- expect(parsed.time).toBe("18:30");- expect(parsed.daysOfWeek).toEqual([1, 2, 3, 4, 5]);- });-- it("recognises weekly on a single day", () => {- const parsed = parseCronExpression("0 9 * * 0", "UTC");- expect(parsed.frequency).toBe("weekly");- expect(parsed.daysOfWeek).toEqual([0]);- });-- it("recognises weekly on Saturday (upper bound)", () => {- const parsed = parseCronExpression("0 9 * * 6", "UTC");- expect(parsed.frequency).toBe("weekly");- expect(parsed.daysOfWeek).toEqual([6]);- });-- it("recognises weekly with multiple days", () => {- const parsed = parseCronExpression("0 9 * * 1,3,5", "UTC");- expect(parsed.frequency).toBe("weekly");- expect(parsed.daysOfWeek).toEqual([1, 3, 5]);- expect(parsed.time).toBe("09:00");- });-- it("normalises unsorted, duplicated weekly days", () => {- const parsed = parseCronExpression("0 9 * * 5,1,5", "UTC");- expect(parsed.frequency).toBe("weekly");- expect(parsed.daysOfWeek).toEqual([1, 5]);- });-- it("tolerates surrounding and repeated whitespace", () => {- const parsed = parseCronExpression(" 0 9 * * * ", "UTC");- expect(parsed.frequency).toBe("daily");- expect(parsed.time).toBe("09:00");- });-- it("tolerates tab separators", () => {- const parsed = parseCronExpression("0\t9\t*\t*\t*", "UTC");- expect(parsed.frequency).toBe("daily");- });- });-- describe("custom fallback — minute field", () => {- it.each([- ["range", "0-30 9 * * *"],- ["list", "0,30 9 * * *"],- ["step over wildcard", "*/15 9 * * *"],- ["step from anchor", "0/5 9 * * *"],- ["step over range", "0-30/5 9 * * *"],- ["wildcard (every minute of the hour)", "* 9 * * *"],- ["wildcard everywhere (every minute)", "* * * * *"],- ["out of range", "60 9 * * *"],- ["out of range with wildcard hour", "60 * * * *"],- ["negative", "-5 9 * * *"],- ])("falls back to custom for minute %s", (_label, cron) => {- const parsed = parseCronExpression(cron, "UTC");- expect(parsed.frequency).toBe("custom");- expect(parsed.cronExpression).toBe(cron);- });- });-- describe("custom fallback — hour field", () => {- it.each([- ["range", "0 9-21 * * *"],- ["list", "0 9,12,15 * * *"],- ["step over wildcard", "0 */2 * * *"],- ["step from anchor", "0 9/2 * * *"],- ["step over range", "0 9-17/2 * * *"],- ["out of range", "0 24 * * *"],- ["range with weekday dow", "0 9-21 * * 1-5"],- ["range with listed dow", "0 9-21 * * 1,3"],- ])("falls back to custom for hour %s", (_label, cron) => {- const parsed = parseCronExpression(cron, "UTC");- expect(parsed.frequency).toBe("custom");- expect(parsed.cronExpression).toBe(cron);- });- });-- describe("custom fallback — day-of-month and month fields", () => {- it.each([- ["specific day of month", "0 9 1 * *"],- ["day-of-month range", "0 9 1-15 * *"],- ["day-of-month step", "0 9 */2 * *"],- ["question mark day of month", "0 9 ? * *"],- ["specific month", "0 9 * 6 *"],- ["month range", "0 9 * 1-6 *"],- ["month name", "0 9 * JAN *"],- ["fully pinned date", "15 3 15 6 2"],- ])("falls back to custom for %s", (_label, cron) => {- const parsed = parseCronExpression(cron, "UTC");- expect(parsed.frequency).toBe("custom");- expect(parsed.cronExpression).toBe(cron);- });- });-- describe("custom fallback — day-of-week field", () => {- it.each([- ["range other than 1-5", "0 9 * * 2-4"],- ["full-week range", "0 9 * * 0-6"],- ["day name", "0 9 * * MON"],- ["day name list", "0 9 * * MON,WED"],- ["step", "0 9 * * */2"],- ["step over range", "0 9 * * 1-5/2"],- ["mixed list and range", "0 9 * * 1,3-5"],- ["out-of-range day 7", "0 9 * * 7"],- ["question mark", "0 9 * * ?"],- ["hourly minute with weekday dow", "0 * * * 1-5"],- ["hourly minute with single dow", "30 * * * 1"],- ])("falls back to custom for dow %s", (_label, cron) => {- const parsed = parseCronExpression(cron, "UTC");- expect(parsed.frequency).toBe("custom");- expect(parsed.cronExpression).toBe(cron);- });- });-- describe("custom fallback — malformed structure", () => {- it.each([- ["too few fields", "0 9 * *"],- ["too many fields (seconds cron)", "0 0 9 * * *"],- ["free text", "not a cron"],- ["empty string", ""],- ["whitespace only", " "],- ["@daily descriptor", "@daily"],- ["@every descriptor", "@every 1h"],- ])("falls back to custom for %s", (_label, cron) => {- const parsed = parseCronExpression(cron, "UTC");- expect(parsed.frequency).toBe("custom");- expect(parsed.cronExpression).toBe(cron);- });- });-- describe("invariants", () => {- it("preserves the raw expression on preset matches too", () => {- expect(parseCronExpression("30 18 * * 1-5", "UTC").cronExpression).toBe(- "30 18 * * 1-5",- );- });-- it("preserves provided timezone", () => {- expect(parseCronExpression("0 9 * * *", "Asia/Shanghai").timezone).toBe(- "Asia/Shanghai",- );- expect(parseCronExpression("0 9-21 * * *", "Asia/Shanghai").timezone).toBe(- "Asia/Shanghai",- );- });- });-- describe("round-trips through toCronExpression", () => {- const presets: Array<[string, Partial<TriggerConfig>]> = [- ["hourly", { frequency: "hourly", time: "00:15" }],- ["daily", { frequency: "daily", time: "09:30" }],- ["weekdays", { frequency: "weekdays", time: "08:00" }],- ["weekly", { frequency: "weekly", time: "14:45", daysOfWeek: [0, 2, 6] }],- ];-- it.each(presets)("round-trips %s", (_label, overrides) => {- const cfg = { ...getDefaultTriggerConfig(), ...overrides };- const parsed = parseCronExpression(toCronExpression(cfg), "UTC");- expect(parsed.frequency).toBe(cfg.frequency);- expect(parsed.time).toBe(cfg.time);- if (cfg.frequency === "weekly") {- expect(parsed.daysOfWeek).toEqual(cfg.daysOfWeek);- }- });-- it("serialises weekly with no days selected to Monday as a safety fallback", () => {- const cfg = {- ...getDefaultTriggerConfig(),- frequency: "weekly" as const,- time: "09:00",- daysOfWeek: [],- };- expect(toCronExpression(cfg)).toBe("0 9 * * 1");- });-- it("round-trips a custom expression verbatim", () => {- const cfg = {- ...getDefaultTriggerConfig(),- frequency: "custom" as const,- cronExpression: "0 9-21 * * *",- };- const parsed = parseCronExpression(toCronExpression(cfg), "UTC");- expect(parsed.frequency).toBe("custom");- expect(parsed.cronExpression).toBe("0 9-21 * * *");- expect(toCronExpression(parsed)).toBe("0 9-21 * * *");- });- });-});diff --git a/packages/views/autopilots/components/trigger-config.tsx b/packages/views/autopilots/components/trigger-config.tsxdeleted file mode 100644index 3e1603fa1b..0000000000--- a/packages/views/autopilots/components/trigger-config.tsx+++ /dev/null@@ -1,423 +0,0 @@-"use client";--import { useMemo } from "react";-import { cn } from "@multica/ui/lib/utils";-import {- Select,- SelectTrigger,- SelectValue,- SelectContent,- SelectItem,-} from "@multica/ui/components/ui/select";-import { useT } from "../../i18n";--export type TriggerFrequency = "hourly" | "daily" | "weekdays" | "weekly" | "custom";--export interface TriggerConfig {- frequency: TriggerFrequency;- time: string; // HH:MM- daysOfWeek: number[]; // 0=Sun … 6=Sat — used when frequency === "weekly"- cronExpression: string; // only used when frequency === "custom"- timezone: string; // IANA-}--// ----------------------------------------------------------------------------// Constants — schema-level (not user-visible)-// -----------------------------------------------------------------------------const FREQUENCY_KEYS: TriggerFrequency[] = [- "hourly",- "daily",- "weekdays",- "weekly",- "custom",-];--const DAY_SHORT_KEYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"] as const;--const COMMON_TIMEZONES = [- "UTC",- "America/New_York",- "America/Chicago",- "America/Denver",- "America/Los_Angeles",- "America/Sao_Paulo",- "Europe/London",- "Europe/Paris",- "Europe/Berlin",- "Europe/Moscow",- "Asia/Dubai",- "Asia/Kolkata",- "Asia/Singapore",- "Asia/Shanghai",- "Asia/Tokyo",- "Asia/Seoul",- "Australia/Sydney",- "Pacific/Auckland",-];--// ----------------------------------------------------------------------------// Helpers-// -----------------------------------------------------------------------------export function getLocalTimezone(): string {- try {- return Intl.DateTimeFormat().resolvedOptions().timeZone;- } catch {- return "UTC";- }-}--function getTimezoneOffset(tz: string): string {- if (tz === "UTC") return "UTC";- try {- const parts = new Intl.DateTimeFormat("en-US", {- timeZone: tz,- timeZoneName: "shortOffset",- }).formatToParts(new Date());- return parts.find((p) => p.type === "timeZoneName")?.value ?? tz;- } catch {- return tz;- }-}--function getTimezoneLabel(tz: string): string {- if (tz === "UTC") return "UTC";- const city = tz.split("/").pop()?.replace(/_/g, " ") ?? tz;- return `${city} (${getTimezoneOffset(tz)})`;-}--function formatTime12h(time: string): string {- const [h, m] = time.split(":");- const hour = parseInt(h ?? "9", 10);- const min = parseInt(m ?? "0", 10);- const ampm = hour >= 12 ? "PM" : "AM";- return `${hour % 12 || 12}:${min.toString().padStart(2, "0")} ${ampm}`;-}--// ----------------------------------------------------------------------------// Public helpers-// -----------------------------------------------------------------------------export function getDefaultTriggerConfig(): TriggerConfig {- return {- frequency: "daily",- time: "09:00",- daysOfWeek: [1],- cronExpression: "0 9 * * 1-5",- timezone: getLocalTimezone(),- };-}--function sortedDays(days: number[]): number[] {- return Array.from(new Set(days)).toSorted((a, b) => a - b);-}--export function toCronExpression(cfg: TriggerConfig): string {- const [h, m] = cfg.time.split(":");- const hour = parseInt(h ?? "9", 10);- const min = parseInt(m ?? "0", 10);- switch (cfg.frequency) {- case "hourly":- return `${min} * * * *`;- case "daily":- return `${min} ${hour} * * *`;- case "weekdays":- return `${min} ${hour} * * 1-5`;- case "weekly": {- const days = sortedDays(cfg.daysOfWeek);- const dow = days.length > 0 ? days.join(",") : "1";- return `${min} ${hour} * * ${dow}`;- }- case "custom":- return cfg.cronExpression;- }-}--// Strict field matcher: cron fields also allow ranges, lists, and steps-// ("9-21", "0,30", "*/5") that parseInt would silently truncate to their-// first number, so only bare 1-2 digit integers count as a preset match.-function parsePlainInt(s: string, max: number): number | null {- if (!/^\d{1,2}$/.test(s)) return null;- const n = parseInt(s, 10);- return n > max ? null : n;-}--export function parseCronExpression(cron: string, timezone: string): TriggerConfig {- const base: TriggerConfig = {- ...getDefaultTriggerConfig(),- timezone,- cronExpression: cron,- };- const parts = cron.trim().split(/\s+/);- if (parts.length !== 5) return { ...base, frequency: "custom" };- const minStr = parts[0] ?? "";- const hourStr = parts[1] ?? "";- const dom = parts[2] ?? "";- const mon = parts[3] ?? "";- const dow = parts[4] ?? "";- if (dom !== "*" || mon !== "*") return { ...base, frequency: "custom" };- const min = parsePlainInt(minStr, 59);- if (min === null) return { ...base, frequency: "custom" };-- if (hourStr === "*") {- if (dow !== "*") return { ...base, frequency: "custom" };- const time = `00:${String(min).padStart(2, "0")}`;- return { ...base, frequency: "hourly", time };- }- const hour = parsePlainInt(hourStr, 23);- if (hour === null) return { ...base, frequency: "custom" };- const time = `${String(hour).padStart(2, "0")}:${String(min).padStart(2, "0")}`;-- if (dow === "*") return { ...base, frequency: "daily", time };- if (dow === "1-5") return { ...base, frequency: "weekdays", time, daysOfWeek: [1, 2, 3, 4, 5] };- if (/^[0-6](,[0-6])*$/.test(dow)) {- const days = sortedDays(dow.split(",").map((n) => parseInt(n, 10)));- return { ...base, frequency: "weekly", time, daysOfWeek: days };- }- return { ...base, frequency: "custom" };-}--// ----------------------------------------------------------------------------// Hooks (i18n-aware)-// -----------------------------------------------------------------------------// Hook returning a function that produces the compact "Hourly · :15 / Daily 09:00"-// summary. Was a pure module-level function before i18n; converted to a hook so-// the strings can flow through useT.-export function useSummarizeTrigger(): (cfg: TriggerConfig) => string {- const { t } = useT("autopilots");- return (cfg) => {- switch (cfg.frequency) {- case "hourly": {- const min = cfg.time.split(":")[1] ?? "00";- return t(($) => $.trigger_config.summary.hourly, { min });- }- case "daily":- return t(($) => $.trigger_config.summary.daily, { time: cfg.time });- case "weekdays":- return t(($) => $.trigger_config.summary.weekdays, { time: cfg.time });- case "weekly":- return t(($) => $.trigger_config.summary.weekly, {- days: formatDayList(cfg.daysOfWeek, t),- time: cfg.time,- });- case "custom":- return t(($) => $.trigger_config.summary.custom);- }- };-}--// Hook returning a function that produces the longer "Runs daily at 9:00 AM PDT"-// description. Same rationale as useSummarizeTrigger.-export function useDescribeTrigger(): (cfg: TriggerConfig) => string {- const { t } = useT("autopilots");- return (cfg) => {- const offset = getTimezoneOffset(cfg.timezone);- switch (cfg.frequency) {- case "hourly": {- const min = parseInt(cfg.time.split(":")[1] ?? "0", 10).toString().padStart(2, "0");- return t(($) => $.trigger_config.describe.hourly, { min });- }- case "daily":- return t(($) => $.trigger_config.describe.daily, {- time: formatTime12h(cfg.time),- offset,- });- case "weekdays":- return t(($) => $.trigger_config.describe.weekdays, {- time: formatTime12h(cfg.time),- offset,- });- case "weekly":- return t(($) => $.trigger_config.describe.weekly, {- days: formatDayList(cfg.daysOfWeek, t),- time: formatTime12h(cfg.time),- offset,- });- case "custom":- return t(($) => $.trigger_config.describe.custom, {- cron: cfg.cronExpression,- });- }- };-}--// Helper that resolves day-short labels through t() — extracted so the two-// hooks above can share the join logic without each grabbing its own t.-type AutopilotsT = ReturnType<typeof useT<"autopilots">>["t"];-function formatDayList(days: number[], t: AutopilotsT): string {- const sorted = sortedDays(days);- if (sorted.length === 0) return t(($) => $.trigger_config.summary.no_days);- return sorted- .map((d) => t(($) => $.trigger_config.days_short[DAY_SHORT_KEYS[d]!]))- .join(", ");-}--// ----------------------------------------------------------------------------// Component-// -----------------------------------------------------------------------------export function TriggerConfigSection({- config,- onChange,-}: {- config: TriggerConfig;- onChange: (config: TriggerConfig) => void;-}) {- const { t } = useT("autopilots");- const describeTrigger = useDescribeTrigger();- const timezones = useMemo(() => {- const local = getLocalTimezone();- const set = new Set(COMMON_TIMEZONES);- return set.has(local) ? COMMON_TIMEZONES : [local, ...COMMON_TIMEZONES];- }, []);-- return (- <div className="space-y-3">- {/* Frequency tabs */}- <div className="flex flex-wrap gap-1">- {FREQUENCY_KEYS.map((freq) => (- <button- key={freq}- type="button"- className={cn(- "rounded-md px-3 py-1.5 text-xs font-medium transition-colors",- config.frequency === freq- ? "bg-foreground text-background"- : "bg-muted text-muted-foreground hover:text-foreground",- )}- onClick={() => onChange({ ...config, frequency: freq })}- >- {t(($) => $.trigger_config.frequencies[freq])}- </button>- ))}- </div>-- {config.frequency === "custom" ? (- /* Custom cron input */- <div>- <label className="text-xs text-muted-foreground">- {t(($) => $.trigger_config.cron_label)}- </label>- <input- type="text"- value={config.cronExpression}- onChange={(e) => onChange({ ...config, cronExpression: e.target.value })}- placeholder="0 9 * * 1-5"- className="mt-1 w-full rounded-md border bg-background px-3 py-2 text-sm font-mono outline-none focus:ring-1 focus:ring-ring"- />- <p className="text-xs text-muted-foreground mt-1">- {t(($) => $.trigger_config.cron_hint)}- </p>- </div>- ) : (- <>- {/* Time + Timezone row */}- <div className="flex gap-3">- {config.frequency === "hourly" ? (- <div className="w-24">- <label className="text-xs text-muted-foreground">- {t(($) => $.trigger_config.minute_label)}- </label>- <input- type="number"- min={0}- max={59}- value={parseInt(config.time.split(":")[1] ?? "0", 10)}- onChange={(e) => {- const min = Math.max(0, Math.min(59, parseInt(e.target.value) || 0));- onChange({ ...config, time: `00:${min.toString().padStart(2, "0")}` });- }}- className="mt-1 w-full rounded-md border bg-background px-3 py-2 text-sm font-mono outline-none focus:ring-1 focus:ring-ring"- />- </div>- ) : (- <>- <div className="w-28">- <label className="text-xs text-muted-foreground">- {t(($) => $.trigger_config.time_label)}- </label>- <input- type="time"- value={config.time}- onChange={(e) => onChange({ ...config, time: e.target.value || config.time })}- className="mt-1 w-full rounded-md border bg-background px-3 py-2 text-sm font-mono outline-none focus:ring-1 focus:ring-ring"- />- </div>- <div className="flex-1 min-w-0">- <label className="text-xs text-muted-foreground">- {t(($) => $.trigger_config.timezone_label)}- </label>- <Select- items={timezones.map((value) => ({- value,- label: getTimezoneLabel(value),- }))}- value={config.timezone}- onValueChange={(v) => v && onChange({ ...config, timezone: v })}- >- <SelectTrigger className="mt-1 w-full">- <SelectValue>- {() => getTimezoneLabel(config.timezone)}- </SelectValue>- </SelectTrigger>- <SelectContent>- {timezones.map((tz) => (- <SelectItem key={tz} value={tz}>- {getTimezoneLabel(tz)}- </SelectItem>- ))}- </SelectContent>- </Select>- </div>- </>- )}- </div>-- {/* Day-of-week multi-selector for weekly */}- {config.frequency === "weekly" && (- <div>- <label className="text-xs text-muted-foreground">- {t(($) => $.trigger_config.days_label)}- </label>- <div className="flex gap-1 mt-1">- {DAY_SHORT_KEYS.map((dayKey, i) => {- const selected = config.daysOfWeek.includes(i);- return (- <button- key={dayKey}- type="button"- aria-pressed={selected}- className={cn(- "rounded-md px-2.5 py-1 text-xs font-medium transition-colors",- selected- ? "bg-foreground text-background"- : "bg-muted text-muted-foreground hover:text-foreground",- )}- onClick={() => {- const next = selected- ? config.daysOfWeek.filter((d) => d !== i)- : [...config.daysOfWeek, i];- // Keep at least one day selected so the cron stays valid.- onChange({- ...config,- daysOfWeek: next.length > 0 ? next : config.daysOfWeek,- });- }}- >- {t(($) => $.trigger_config.days_short[dayKey])}- </button>- );- })}- </div>- </div>- )}- </>- )}-- {/* Human-readable preview */}- <p className="text-xs text-muted-foreground">{describeTrigger(config)}</p>- </div>- );-}diff --git a/packages/views/common/format-in-time-zone.test.ts b/packages/views/common/format-in-time-zone.test.tsnew file mode 100644index 0000000000..69b7cfca33--- /dev/null+++ b/packages/views/common/format-in-time-zone.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from "vitest";+import { formatInTimeZone } from "./format-in-time-zone";++// An autopilot's next run is printed on the schedule's clock, not the reader's:+// a trigger that says "18:00 (America/Los_Angeles)" must not contradict itself by+// showing its next run as 09:00 to a reader in UTC+8. A run that already happened+// is an instant in the reader's day, and passes no zone.+describe("formatInTimeZone", () => {+ // 2026-07-14T01:00:00Z is 18:00 of the 13th in Los Angeles (PDT, UTC-7).+ const iso = "2026-07-14T01:00:00Z";++ it("renders the instant in the given timezone", () => {+ const out = formatInTimeZone(iso, "America/Los_Angeles", "en-US");+ expect(out).toContain("13");+ expect(out).toMatch(/6:00\s?PM|18:00/);+ });++ it("renders the same instant differently in another timezone", () => {+ const out = formatInTimeZone(iso, "Asia/Shanghai", "en-US");+ expect(out).toContain("14");+ expect(out).toMatch(/9:00\s?AM|09:00/);+ });++ it("falls back to local time for a zone this runtime does not know", () => {+ // Wrong by an offset, but still a time of day — which a raw ISO string is not.+ expect(formatInTimeZone(iso, "Not/AZone", "en-US")).not.toBe("");+ expect(formatInTimeZone(iso, "Not/AZone", "en-US")).not.toBe(iso);+ });++ it("keeps the reader's locale when it falls back over a bad zone", () => {+ // The zone is what failed, not the language: dropping to the runtime's default+ // locale here would hand a zh-Hans reader an English date.+ expect(formatInTimeZone(iso, "Not/AZone", "zh-CN")).toMatch(/月/);+ });++ it("hands back an unreadable timestamp instead of throwing", () => {+ // Intl throws on an invalid Date. A drifted backend timestamp must degrade to+ // text, not take the whole detail page down with it.+ expect(formatInTimeZone("not-a-date", "UTC", "en-US")).toBe("not-a-date");+ });+});diff --git a/packages/views/common/format-in-time-zone.ts b/packages/views/common/format-in-time-zone.tsnew file mode 100644index 0000000000..65b0984ed8--- /dev/null+++ b/packages/views/common/format-in-time-zone.ts@@ -0,0 +1,31 @@+/** Render an instant on the schedule's clock, not the reader's: an autopilot+ * that says "18:00 (America/Los_Angeles)" must not print its next run as 09:00+ * to a reader in UTC+8. The wording — month name, 12- or 24-hour dial — is the+ * reader's locale.+ *+ * Two things can go wrong, and neither may take a page down:+ * - a zone this browser's ICU data does not carry (an autopilot saved from a+ * newer build, opened in an older packaged desktop one) → local time: wrong by+ * an offset, but still a time of day, which a raw ISO string is not;+ * - a timestamp that is not a date at all (backend drift) → the string itself.+ * Intl throws on an invalid Date, so this is checked before formatting, not+ * caught after: a catch would only run the same throwing call again. */+export function formatInTimeZone(+ iso: string,+ timeZone: string | undefined,+ locale: string,+): string {+ const at = new Date(iso);+ if (Number.isNaN(at.getTime())) return iso;+ const options: Intl.DateTimeFormatOptions = {+ month: "short",+ day: "numeric",+ hour: "2-digit",+ minute: "2-digit",+ };+ try {+ return new Intl.DateTimeFormat(locale, { ...options, timeZone }).format(at);+ } catch {+ return new Intl.DateTimeFormat(locale, options).format(at);+ }+}diff --git a/packages/views/common/segmented-toggle.tsx b/packages/views/common/segmented-toggle.tsxnew file mode 100644index 0000000000..ab1dd68d32--- /dev/null+++ b/packages/views/common/segmented-toggle.tsx@@ -0,0 +1,45 @@+"use client";++import type { ReactNode } from "react";+import { cn } from "@multica/ui/lib/utils";++/** A pill-button group for picking between mutually exclusive modes: the active+ * option lifts to the background, the rest stay muted. One control for every+ * either/or, so switching mode always looks and works the same wherever it+ * appears. */+export function SegmentedToggle<T extends string>({+ value,+ options,+ onChange,+ buttonClassName,+}: {+ value: T;+ options: ReadonlyArray<readonly [T, ReactNode]>;+ onChange: (value: T) => void;+ /** Overrides the compact default sizing (text-xs px-2 py-1). */+ buttonClassName?: string;+}) {+ return (+ <div className="grid auto-cols-fr grid-flow-col gap-1 rounded-md bg-muted p-1">+ {options.map(([key, label]) => (+ <button+ key={key}+ type="button"+ aria-pressed={value === key}+ onClick={() => {+ if (key !== value) onChange(key);+ }}+ className={cn(+ "rounded-sm font-medium transition-colors",+ buttonClassName ?? "px-2 py-1 text-xs",+ value === key+ ? "bg-background text-foreground shadow-sm"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ {label}+ </button>+ ))}+ </div>+ );+}diff --git a/packages/views/common/use-debounced-value.ts b/packages/views/common/use-debounced-value.tsnew file mode 100644index 0000000000..93656bf88f--- /dev/null+++ b/packages/views/common/use-debounced-value.ts@@ -0,0 +1,13 @@+"use client";++import { useEffect, useState } from "react";++/** The value as it stood once it stopped changing for `delayMs`. */+export function useDebouncedValue<T>(value: T, delayMs: number): T {+ const [debounced, setDebounced] = useState(value);+ useEffect(() => {+ const id = setTimeout(() => setDebounced(value), delayMs);+ return () => clearTimeout(id);+ }, [value, delayMs]);+ return debounced;+}diff --git a/packages/views/editor/extensions/code-block-view.tsx b/packages/views/editor/extensions/code-block-view.tsxindex f64e479ab3..fd766bc3e9 100644--- a/packages/views/editor/extensions/code-block-view.tsx+++ b/packages/views/editor/extensions/code-block-view.tsx@@ -1,11 +1,12 @@"use client";-import { useEffect, useState } from "react";+import { useState } from "react";import { NodeViewWrapper, NodeViewContent } from "@tiptap/react";import type { NodeViewProps } from "@tiptap/react";import { Code as CodeIcon, Copy, Check, Eye } from "lucide-react";import { cn } from "@multica/ui/lib/utils";import { copyText } from "@multica/ui/lib/clipboard";+import { useDebouncedValue } from "../../common/use-debounced-value";import { useT } from "../../i18n";import { MermaidDiagram } from "../mermaid-diagram";import { CodeBlockIframe } from "../code-block-iframe";@@ -21,15 +22,6 @@ const PREVIEW_DEBOUNCE_MS = 200;const HTML_PREVIEW_HEIGHT = "h-[480px]";-function useDebouncedValue<T>(value: T, delayMs: number): T {- const [debounced, setDebounced] = useState(value);- useEffect(() => {- const id = setTimeout(() => setDebounced(value), delayMs);- return () => clearTimeout(id);- }, [value, delayMs]);- return debounced;-}-function CodeBlockView({ node }: NodeViewProps) {const { t } = useT("editor");const [copied, setCopied] = useState(false);diff --git a/packages/views/locales/en/autopilots.json b/packages/views/locales/en/autopilots.jsonindex e0943124ba..c17e2ef91c 100644--- a/packages/views/locales/en/autopilots.json+++ b/packages/views/locales/en/autopilots.json@@ -303,7 +303,6 @@"event_filter_actions_placeholder": "completed, failed","event_filter_hint": "Only process webhooks matching these events. Leave empty to accept all.","schedule_disabled_reason": "This autopilot has multiple schedules — edit them in the detail page.",- "next_run_label": "Next run:","output_modes": {"create_issue": {"label": "Create issue",@@ -313,32 +312,20 @@"label": "Run only","description": "Silent run, no issue created"}- },- "frequency_long": {- "hourly": "Every hour",- "daily": "Every day",- "weekdays": "Every weekday",- "weekly": "Every week",- "custom": "Custom cron"- },- "days": {- "sunday": "Sunday",- "monday": "Monday",- "tuesday": "Tuesday",- "wednesday": "Wednesday",- "thursday": "Thursday",- "friday": "Friday",- "saturday": "Saturday"}},- "trigger_config": {- "frequencies": {- "hourly": "Hourly",- "daily": "Daily",- "weekdays": "Weekdays",- "weekly": "Days",- "custom": "Custom"- },+ "schedule_editor": {+ "time_label": "Time",+ "time_at": "At a time",+ "time_every": "At an interval",+ "every_prefix": "Every",+ "unit_hours": "hours",+ "unit_minutes": "minutes",+ "days_label": "Days",+ "days_every": "Every day",+ "days_weekly": "Days of week",+ "days_monthly": "Day of month",+ "monthly_short_month_hint": "Months without day {{day}} are skipped.","days_short": {"sun": "Sun","mon": "Mon",@@ -348,32 +335,69 @@"fri": "Fri","sat": "Sat"},- "cron_label": "Cron Expression",- "cron_hint": "Standard 5-field cron (min hour dom month dow)",- "minute_label": "Minute",- "time_label": "Time","timezone_label": "Timezone",- "days_label": "Days",- "summary": {- "hourly": "Hourly · :{{min}}",- "daily": "Daily {{time}}",- "weekdays": "Weekdays {{time}}",- "weekly": "{{days}} {{time}}",- "custom": "Custom cron",- "no_days": "—"- },+ "cron_toggle": "Cron",+ "cron_click_to_edit": "click to edit",+ "cron_hint": "Standard 5-field cron (min hour dom month dow)",+ "cron_invalid": "This cron expression isn't valid.",+ "timezone_invalid": "This timezone isn't recognized by the server.",+ "advanced_hint": "This expression uses features the visual editor can't represent. Edit the cron text directly, or simplify it to re-enable the controls.",+ "advanced_unverified": "The server couldn't be reached to check this expression, so the controls stay off. Make sure the cron text is right before saving.",+ "advanced_checking": "Checking this expression with the server. The controls stay off until it answers.",+ "next_runs_label": "Next runs",+ "next_in": "in {{countdown}}",+ "preview_unavailable": "Next runs unavailable right now.",+ "no_upcoming_runs": "This expression has no upcoming runs.","describe": {- "hourly": "Runs every hour at :{{min}}",- "daily": "Runs daily at {{time}} {{offset}}",- "weekdays": "Runs weekdays at {{time}} {{offset}}",- "weekly": "Runs every {{days}} at {{time}} {{offset}}",- "custom": "Custom schedule: {{cron}}"+ "days_every": "Every day",+ "days_monthly": "Day {{day}} of the month",+ "days_long": {+ "sun": "Sun",+ "mon": "Mon",+ "tue": "Tue",+ "wed": "Wed",+ "thu": "Thu",+ "fri": "Fri",+ "sat": "Sat"+ },+ "days_range": "{{from}}–{{to}}",+ "days_join": ", ",+ "time_at": "At {{time}}",+ "time_every_hour": "Every hour at :{{minute}}",+ "time_every_hours": "Every {{interval}} hours at :{{minute}}",+ "time_every_hour_window": "Every hour",+ "time_every_hours_window": "Every {{interval}} hours",+ "time_every_minute": "Every minute",+ "time_every_minutes": "Every {{interval}} minutes",+ "window": "{{from}}–{{to}}"},"countdown": {- "days_hours": "{{days}}d {{hours}}h",+ "days_hours": "{{days}}d {{hours}}h {{minutes}}m","hours_minutes": "{{hours}}h {{minutes}}m","minutes": "{{minutes}}m","less_than_minute": "<1m"+ },+ "a11y": {+ "fixed_hour": "Hour",+ "fixed_minute": "Minute",+ "interval": "Interval",+ "interval_unit": "Interval unit",+ "window_start_hour": "Window start hour",+ "window_start_minute": "Window start minute",+ "window_end_hour": "Window end hour",+ "window_end_minute": "Window end minute",+ "day_pattern": "Day pattern",+ "day_of_month": "Day of month",+ "timezone": "Timezone",+ "days_full": {+ "sun": "Sunday",+ "mon": "Monday",+ "tue": "Tuesday",+ "wed": "Wednesday",+ "thu": "Thursday",+ "fri": "Friday",+ "sat": "Saturday"+ }}},"agent_picker": {diff --git a/packages/views/locales/ja/autopilots.json b/packages/views/locales/ja/autopilots.jsonindex 94c0af89bc..91a2a61a10 100644--- a/packages/views/locales/ja/autopilots.json+++ b/packages/views/locales/ja/autopilots.json@@ -303,7 +303,6 @@"event_filter_actions_placeholder": "completed, failed","event_filter_hint": "これらのイベントに一致する Webhook のみを処理します。空にするとすべて許可します。","schedule_disabled_reason": "このオートパイロットには複数のスケジュールがあります。詳細ページで編集してください。",- "next_run_label": "次回実行:","output_modes": {"create_issue": {"label": "イシューを作成",@@ -313,32 +312,20 @@"label": "実行のみ","description": "イシューを作成せず、静かに実行します"}- },- "frequency_long": {- "hourly": "毎時",- "daily": "毎日",- "weekdays": "平日ごと",- "weekly": "毎週",- "custom": "カスタム cron"- },- "days": {- "sunday": "日曜日",- "monday": "月曜日",- "tuesday": "火曜日",- "wednesday": "水曜日",- "thursday": "木曜日",- "friday": "金曜日",- "saturday": "土曜日"}},- "trigger_config": {- "frequencies": {- "hourly": "毎時",- "daily": "毎日",- "weekdays": "平日",- "weekly": "曜日",- "custom": "カスタム"- },+ "schedule_editor": {+ "time_label": "時刻",+ "time_at": "時刻指定",+ "time_every": "間隔指定",+ "every_prefix": "毎",+ "unit_hours": "時間",+ "unit_minutes": "分",+ "days_label": "日",+ "days_every": "毎日",+ "days_weekly": "曜日指定",+ "days_monthly": "日付指定",+ "monthly_short_month_hint": "{{day}} 日が存在しない月はスキップされます。","days_short": {"sun": "日","mon": "月",@@ -348,32 +335,69 @@"fri": "金","sat": "土"},- "cron_label": "Cron 式",- "cron_hint": "標準の 5 フィールド cron(分 時 日 月 曜日)",- "minute_label": "分",- "time_label": "時刻","timezone_label": "タイムゾーン",- "days_label": "曜日",- "summary": {- "hourly": "毎時 · :{{min}}",- "daily": "毎日 {{time}}",- "weekdays": "平日 {{time}}",- "weekly": "{{days}} {{time}}",- "custom": "カスタム cron",- "no_days": "—"- },+ "cron_toggle": "Cron",+ "cron_click_to_edit": "クリックして編集",+ "cron_hint": "標準 5 フィールド cron(分 時 日 月 曜日)",+ "cron_invalid": "この cron 式は無効です。",+ "timezone_invalid": "このタイムゾーンはサーバーで認識できません。",+ "advanced_hint": "この式にはビジュアルエディタで表現できない機能が含まれています。cron テキストを直接編集するか、式を簡略化してください。",+ "advanced_unverified": "サーバーに接続できず、この式を検証できませんでした。コントロールは無効のままです。保存する前に cron テキストを確認してください。",+ "advanced_checking": "この式をサーバーで検証しています。結果が返るまでコントロールは無効のままです。",+ "next_runs_label": "次回以降の実行",+ "next_in": "{{countdown}}後",+ "preview_unavailable": "次回実行時刻を取得できません。",+ "no_upcoming_runs": "この式に該当する今後の実行はありません。","describe": {- "hourly": "毎時 :{{min}} に実行",- "daily": "毎日 {{time}} {{offset}} に実行",- "weekdays": "平日 {{time}} {{offset}} に実行",- "weekly": "毎週 {{days}} {{time}} {{offset}} に実行",- "custom": "カスタムスケジュール: {{cron}}"+ "days_every": "毎日",+ "days_monthly": "毎月 {{day}} 日",+ "days_long": {+ "sun": "日曜",+ "mon": "月曜",+ "tue": "火曜",+ "wed": "水曜",+ "thu": "木曜",+ "fri": "金曜",+ "sat": "土曜"+ },+ "days_range": "{{from}}〜{{to}}",+ "days_join": "、",+ "time_at": "{{time}}",+ "time_every_hour": "毎時 {{minute}} 分",+ "time_every_hours": "{{interval}} 時間ごと(毎時 {{minute}} 分)",+ "time_every_hour_window": "毎時",+ "time_every_hours_window": "{{interval}} 時間ごと",+ "time_every_minute": "毎分",+ "time_every_minutes": "{{interval}} 分ごと",+ "window": "{{from}}–{{to}}"},"countdown": {- "days_hours": "{{days}} 日 {{hours}} 時間",- "hours_minutes": "{{hours}} 時間 {{minutes}} 分",- "minutes": "{{minutes}} 分",- "less_than_minute": "1 分未満"+ "days_hours": "{{days}}日 {{hours}}時間 {{minutes}}分",+ "hours_minutes": "{{hours}}時間 {{minutes}}分",+ "minutes": "{{minutes}}分",+ "less_than_minute": "1分未満"+ },+ "a11y": {+ "fixed_hour": "時",+ "fixed_minute": "分",+ "interval": "間隔",+ "interval_unit": "間隔の単位",+ "window_start_hour": "時間帯の開始(時)",+ "window_start_minute": "時間帯の開始(分)",+ "window_end_hour": "時間帯の終了(時)",+ "window_end_minute": "時間帯の終了(分)",+ "day_pattern": "日付の指定方法",+ "day_of_month": "毎月の日",+ "timezone": "タイムゾーン",+ "days_full": {+ "sun": "日曜日",+ "mon": "月曜日",+ "tue": "火曜日",+ "wed": "水曜日",+ "thu": "木曜日",+ "fri": "金曜日",+ "sat": "土曜日"+ }}},"agent_picker": {diff --git a/packages/views/locales/ko/autopilots.json b/packages/views/locales/ko/autopilots.jsonindex 736037dab1..58b337bdb3 100644--- a/packages/views/locales/ko/autopilots.json+++ b/packages/views/locales/ko/autopilots.json@@ -303,7 +303,6 @@"event_filter_actions_placeholder": "completed, failed","event_filter_hint": "이 이벤트와 일치하는 Webhook만 처리합니다. 비워 두면 모두 허용합니다.","schedule_disabled_reason": "이 오토파일럿에는 여러 일정이 있습니다. 상세 페이지에서 수정하세요.",- "next_run_label": "다음 실행:","output_modes": {"create_issue": {"label": "이슈 생성",@@ -313,32 +312,20 @@"label": "실행만","description": "이슈를 만들지 않고 조용히 실행합니다"}- },- "frequency_long": {- "hourly": "매시간",- "daily": "매일",- "weekdays": "평일마다",- "weekly": "매주",- "custom": "사용자 지정 cron"- },- "days": {- "sunday": "일요일",- "monday": "월요일",- "tuesday": "화요일",- "wednesday": "수요일",- "thursday": "목요일",- "friday": "금요일",- "saturday": "토요일"}},- "trigger_config": {- "frequencies": {- "hourly": "매시간",- "daily": "매일",- "weekdays": "평일",- "weekly": "요일",- "custom": "사용자 지정"- },+ "schedule_editor": {+ "time_label": "시간",+ "time_at": "시각 지정",+ "time_every": "간격 지정",+ "every_prefix": "매",+ "unit_hours": "시간",+ "unit_minutes": "분",+ "days_label": "요일/날짜",+ "days_every": "매일",+ "days_weekly": "요일 지정",+ "days_monthly": "날짜 지정",+ "monthly_short_month_hint": "{{day}}일이 없는 달은 건너뜁니다.","days_short": {"sun": "일","mon": "월",@@ -348,32 +335,69 @@"fri": "금","sat": "토"},- "cron_label": "Cron 표현식",- "cron_hint": "표준 5필드 cron(분 시 일 월 요일)",- "minute_label": "분",- "time_label": "시간","timezone_label": "시간대",- "days_label": "요일",- "summary": {- "hourly": "매시간 · :{{min}}",- "daily": "매일 {{time}}",- "weekdays": "평일 {{time}}",- "weekly": "{{days}} {{time}}",- "custom": "사용자 지정 cron",- "no_days": "—"- },+ "cron_toggle": "Cron",+ "cron_click_to_edit": "클릭하여 편집",+ "cron_hint": "표준 5필드 cron (분 시 일 월 요일)",+ "cron_invalid": "이 cron 표현식은 유효하지 않습니다.",+ "timezone_invalid": "서버가 이 시간대를 인식하지 못합니다.",+ "advanced_hint": "이 표현식에는 시각적 편집기에서 표현할 수 없는 기능이 포함되어 있습니다. cron 텍스트를 직접 편집하거나 표현식을 단순화하세요.",+ "advanced_unverified": "서버에 연결할 수 없어 이 표현식을 검증하지 못했습니다. 컨트롤은 비활성 상태로 유지됩니다. 저장하기 전에 cron 텍스트를 확인하세요.",+ "advanced_checking": "이 표현식을 서버에서 검증하는 중입니다. 결과가 올 때까지 컨트롤은 비활성 상태입니다.",+ "next_runs_label": "다음 실행",+ "next_in": "{{countdown}} 후",+ "preview_unavailable": "다음 실행 시각을 가져올 수 없습니다.",+ "no_upcoming_runs": "이 표현식에는 예정된 실행이 없습니다.","describe": {- "hourly": "매시간 :{{min}}에 실행",- "daily": "매일 {{time}} {{offset}}에 실행",- "weekdays": "평일 {{time}} {{offset}}에 실행",- "weekly": "매주 {{days}} {{time}} {{offset}}에 실행",- "custom": "사용자 지정 일정: {{cron}}"+ "days_every": "매일",+ "days_monthly": "매월 {{day}}일",+ "days_long": {+ "sun": "일요일",+ "mon": "월요일",+ "tue": "화요일",+ "wed": "수요일",+ "thu": "목요일",+ "fri": "금요일",+ "sat": "토요일"+ },+ "days_range": "{{from}}~{{to}}",+ "days_join": ", ",+ "time_at": "{{time}}",+ "time_every_hour": "매시 {{minute}}분",+ "time_every_hours": "{{interval}}시간마다 (매시 {{minute}}분)",+ "time_every_hour_window": "매시간",+ "time_every_hours_window": "{{interval}}시간마다",+ "time_every_minute": "매분",+ "time_every_minutes": "{{interval}}분마다",+ "window": "{{from}}–{{to}}"},"countdown": {- "days_hours": "{{days}}일 {{hours}}시간",+ "days_hours": "{{days}}일 {{hours}}시간 {{minutes}}분","hours_minutes": "{{hours}}시간 {{minutes}}분","minutes": "{{minutes}}분","less_than_minute": "1분 미만"+ },+ "a11y": {+ "fixed_hour": "시",+ "fixed_minute": "분",+ "interval": "간격",+ "interval_unit": "간격 단위",+ "window_start_hour": "시간대 시작 시",+ "window_start_minute": "시간대 시작 분",+ "window_end_hour": "시간대 종료 시",+ "window_end_minute": "시간대 종료 분",+ "day_pattern": "날짜 방식",+ "day_of_month": "매월 며칠",+ "timezone": "시간대",+ "days_full": {+ "sun": "일요일",+ "mon": "월요일",+ "tue": "화요일",+ "wed": "수요일",+ "thu": "목요일",+ "fri": "금요일",+ "sat": "토요일"+ }}},"agent_picker": {diff --git a/packages/views/locales/zh-Hans/autopilots.json b/packages/views/locales/zh-Hans/autopilots.jsonindex f5be556639..d2a3441dea 100644--- a/packages/views/locales/zh-Hans/autopilots.json+++ b/packages/views/locales/zh-Hans/autopilots.json@@ -303,7 +303,6 @@"event_filter_actions_placeholder": "completed, failed","event_filter_hint": "只处理匹配这些事件的 webhook。留空则接受所有事件。","schedule_disabled_reason": "该自动化有多个时间表——请到详情页编辑。",- "next_run_label": "下次运行:","output_modes": {"create_issue": {"label": "创建 issue",@@ -313,32 +312,20 @@"label": "仅运行","description": "静默运行,不创建 issue"}- },- "frequency_long": {- "hourly": "每小时",- "daily": "每天",- "weekdays": "每个工作日",- "weekly": "每周",- "custom": "自定义 cron"- },- "days": {- "sunday": "周日",- "monday": "周一",- "tuesday": "周二",- "wednesday": "周三",- "thursday": "周四",- "friday": "周五",- "saturday": "周六"}},- "trigger_config": {- "frequencies": {- "hourly": "每小时",- "daily": "每天",- "weekdays": "工作日",- "weekly": "按天",- "custom": "自定义"- },+ "schedule_editor": {+ "time_label": "时间",+ "time_at": "定点",+ "time_every": "按间隔",+ "every_prefix": "每",+ "unit_hours": "小时",+ "unit_minutes": "分钟",+ "days_label": "日子",+ "days_every": "每天",+ "days_weekly": "按星期",+ "days_monthly": "按日期",+ "monthly_short_month_hint": "没有 {{day}} 日的月份将跳过。","days_short": {"sun": "日","mon": "一",@@ -348,32 +335,69 @@"fri": "五","sat": "六"},- "cron_label": "Cron 表达式",- "cron_hint": "标准 5 字段 cron(分 时 日 月 星期)",- "minute_label": "分钟",- "time_label": "时间","timezone_label": "时区",- "days_label": "星期",- "summary": {- "hourly": "每小时 · :{{min}}",- "daily": "每天 {{time}}",- "weekdays": "工作日 {{time}}",- "weekly": "{{days}} {{time}}",- "custom": "自定义 cron",- "no_days": "—"- },+ "cron_toggle": "Cron",+ "cron_click_to_edit": "点击编辑",+ "cron_hint": "标准 5 字段 cron(分 时 日 月 星期)",+ "cron_invalid": "该 cron 表达式无效。",+ "timezone_invalid": "服务端无法识别该时区。",+ "advanced_hint": "该表达式包含可视化编辑器暂不支持的特性。可直接编辑 cron 文本,或简化表达式以恢复可视化编辑。",+ "advanced_unverified": "暂时无法连接服务器校验该表达式,可视化控件保持停用。保存前请确认 cron 文本无误。",+ "advanced_checking": "正在向服务器校验该表达式,结果返回前可视化控件保持停用。",+ "next_runs_label": "接下来",+ "next_in": "{{countdown}}后",+ "preview_unavailable": "暂时无法获取下次运行时间。",+ "no_upcoming_runs": "该表达式没有即将到来的运行。","describe": {- "hourly": "每小时整点过 {{min}} 分运行",- "daily": "每天 {{time}} {{offset}} 运行",- "weekdays": "每个工作日 {{time}} {{offset}} 运行",- "weekly": "每 {{days}} 的 {{time}} {{offset}} 运行",- "custom": "自定义时间表:{{cron}}"+ "days_every": "每天",+ "days_monthly": "每月 {{day}} 日",+ "days_long": {+ "sun": "周日",+ "mon": "周一",+ "tue": "周二",+ "wed": "周三",+ "thu": "周四",+ "fri": "周五",+ "sat": "周六"+ },+ "days_range": "{{from}}至{{to}}",+ "days_join": "、",+ "time_at": "{{time}}",+ "time_every_hour": "每小时的第 {{minute}} 分",+ "time_every_hours": "每 {{interval}} 小时的第 {{minute}} 分",+ "time_every_hour_window": "每小时",+ "time_every_hours_window": "每 {{interval}} 小时",+ "time_every_minute": "每分钟",+ "time_every_minutes": "每 {{interval}} 分钟",+ "window": "{{from}}–{{to}}"},"countdown": {- "days_hours": "{{days}} 天 {{hours}} 小时",+ "days_hours": "{{days}} 天 {{hours}} 小时 {{minutes}} 分","hours_minutes": "{{hours}} 小时 {{minutes}} 分","minutes": "{{minutes}} 分","less_than_minute": "不到 1 分"+ },+ "a11y": {+ "fixed_hour": "小时",+ "fixed_minute": "分钟",+ "interval": "间隔",+ "interval_unit": "间隔单位",+ "window_start_hour": "时间窗口起始小时",+ "window_start_minute": "时间窗口起始分钟",+ "window_end_hour": "时间窗口结束小时",+ "window_end_minute": "时间窗口结束分钟",+ "day_pattern": "日期方式",+ "day_of_month": "每月几号",+ "timezone": "时区",+ "days_full": {+ "sun": "周日",+ "mon": "周一",+ "tue": "周二",+ "wed": "周三",+ "thu": "周四",+ "fri": "周五",+ "sat": "周六"+ }}},"agent_picker": {diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 6cb4d95e6c..9b5790484b 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1138,6 +1138,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Route("/api/autopilots", func(r chi.Router) {r.Get("/", h.ListAutopilots)r.Post("/", h.CreateAutopilot)+ r.Get("/cron-preview", h.CronPreview)r.Route("/{id}", func(r chi.Router) {r.Get("/", h.GetAutopilot)r.Patch("/", h.UpdateAutopilot)diff --git a/server/internal/handler/autopilot_cron_preview.go b/server/internal/handler/autopilot_cron_preview.gonew file mode 100644index 0000000000..97def6305c--- /dev/null+++ b/server/internal/handler/autopilot_cron_preview.go@@ -0,0 +1,55 @@+package handler++import (+ "net/http"+ "time"++ "github.com/multica-ai/multica/server/internal/service"+)++// Rejection codes let the editor say which input is at fault: a timezone the+// server's tzdata does not know is not the user's cron being wrong, and the two+// are fixed in different controls.+const (+ cronPreviewInvalidCron = "invalid_cron"+ cronPreviewInvalidTimezone = "invalid_timezone"+)++func writeCronPreviewError(w http.ResponseWriter, code, msg string) {+ writeJSON(w, http.StatusBadRequest, map[string]any{"error": msg, "code": code})+}++// CronPreview computes the next occurrences of a candidate cron expression+// so schedule editors can show an authoritative preview before saving.+// Compute-only: workspace membership is enforced by the router group and no+// other resource is touched.+func (h *Handler) CronPreview(w http.ResponseWriter, r *http.Request) {+ expr := r.URL.Query().Get("expr")+ if expr == "" {+ writeCronPreviewError(w, cronPreviewInvalidCron, "expr is required")+ return+ }+ tz := r.URL.Query().Get("tz")+ if tz == "" {+ tz = "UTC"+ }+ if err := service.ValidateTimezone(tz); err != nil {+ writeCronPreviewError(w, cronPreviewInvalidTimezone, err.Error())+ return+ }++ const previewCount = 3+ // A syntactically valid expression that never fires comes back as a short (or+ // empty) slice, not an error: the editor tells "never runs" from "your cron is+ // wrong" by the status code.+ occurrences, err := service.NextOccurrencesAfterUTC(expr, tz, time.Now().UTC(), previewCount)+ if err != nil {+ writeCronPreviewError(w, cronPreviewInvalidCron, err.Error())+ return+ }+ nextRuns := make([]string, 0, len(occurrences))+ for _, at := range occurrences {+ nextRuns = append(nextRuns, at.Format(time.RFC3339))+ }+ writeJSON(w, http.StatusOK, map[string]any{"next_runs": nextRuns})+}diff --git a/server/internal/handler/autopilot_cron_preview_test.go b/server/internal/handler/autopilot_cron_preview_test.gonew file mode 100644index 0000000000..e41e164619--- /dev/null+++ b/server/internal/handler/autopilot_cron_preview_test.go@@ -0,0 +1,189 @@+package handler++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "net/url"+ "testing"+ "time"+)++func cronPreviewRequest(expr, tz string) *http.Request {+ q := url.Values{}+ q.Set("expr", expr)+ if tz != "" {+ q.Set("tz", tz)+ }+ return newRequest("GET", "/api/autopilots/cron-preview?"+q.Encode(), nil)+}++func decodeCronPreview(t *testing.T, w *httptest.ResponseRecorder) []string {+ t.Helper()+ var body struct {+ NextRuns []string `json:"next_runs"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {+ t.Fatalf("failed to decode body: %v", err)+ }+ return body.NextRuns+}++func TestCronPreview_ValidExpression(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ w := httptest.NewRecorder()+ testHandler.CronPreview(w, cronPreviewRequest("0 9 * * *", "UTC"))+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ runs := decodeCronPreview(t, w)+ if len(runs) != 3 {+ t.Fatalf("expected 3 next_runs, got %d: %v", len(runs), runs)+ }+ var prev time.Time+ for i, s := range runs {+ ts, err := time.Parse(time.RFC3339, s)+ if err != nil {+ t.Fatalf("next_runs[%d] = %q is not RFC3339: %v", i, s, err)+ }+ if ts.UTC().Hour() != 9 || ts.Minute() != 0 {+ t.Fatalf("next_runs[%d] = %q, want 09:00 UTC", i, s)+ }+ if i > 0 && !ts.After(prev) {+ t.Fatalf("next_runs not strictly ascending: %v", runs)+ }+ prev = ts+ }+}++func TestCronPreview_CompoundExpression(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ w := httptest.NewRecorder()+ testHandler.CronPreview(w, cronPreviewRequest("0 9-21/2 * * 2-4", "Asia/Shanghai"))+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ loc, err := time.LoadLocation("Asia/Shanghai")+ if err != nil {+ t.Fatalf("failed to load location: %v", err)+ }+ for i, s := range decodeCronPreview(t, w) {+ ts, err := time.Parse(time.RFC3339, s)+ if err != nil {+ t.Fatalf("next_runs[%d] not RFC3339: %v", i, err)+ }+ local := ts.In(loc)+ if wd := local.Weekday(); wd < time.Tuesday || wd > time.Thursday {+ t.Fatalf("next_runs[%d] = %s falls on %s, want Tue-Thu", i, s, wd)+ }+ if h := local.Hour(); h < 9 || h > 21 || (h-9)%2 != 0 {+ t.Fatalf("next_runs[%d] = %s local hour %d, want 9-21 step 2", i, s, h)+ }+ }+}++func TestCronPreview_TimezoneApplied(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ w := httptest.NewRecorder()+ testHandler.CronPreview(w, cronPreviewRequest("0 9 * * *", "Asia/Shanghai"))+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ runs := decodeCronPreview(t, w)+ if len(runs) == 0 {+ t.Fatal("expected next_runs, got none")+ }+ ts, err := time.Parse(time.RFC3339, runs[0])+ if err != nil {+ t.Fatalf("not RFC3339: %v", err)+ }+ // 09:00 Asia/Shanghai (UTC+8, no DST) is 01:00 UTC.+ if ts.UTC().Hour() != 1 {+ t.Fatalf("expected 01:00 UTC for 09:00 Asia/Shanghai, got %s", runs[0])+ }+}++func TestCronPreview_DefaultsToUTC(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ w := httptest.NewRecorder()+ testHandler.CronPreview(w, cronPreviewRequest("30 18 * * *", ""))+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ runs := decodeCronPreview(t, w)+ if len(runs) == 0 {+ t.Fatal("expected next_runs, got none")+ }+ ts, err := time.Parse(time.RFC3339, runs[0])+ if err != nil {+ t.Fatalf("not RFC3339: %v", err)+ }+ if ts.UTC().Hour() != 18 || ts.Minute() != 30 {+ t.Fatalf("expected 18:30 UTC, got %s", runs[0])+ }+}++// A syntactically valid expression that never fires answers 200 with an empty+// list, not 400: the editor tells "never runs" from "your cron is wrong" by the+// status, and a 400 here would also block the trigger from being saved at all.+func TestCronPreview_NeverFiringExpression(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ w := httptest.NewRecorder()+ testHandler.CronPreview(w, cronPreviewRequest("0 0 30 2 *", "UTC"))+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if runs := decodeCronPreview(t, w); len(runs) != 0 {+ t.Fatalf("expected no next_runs, got %v", runs)+ }+}++func TestCronPreview_BadRequests(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ cases := []struct {+ name string+ expr string+ tz string+ code string+ }{+ {"invalid expression", "not a cron", "UTC", cronPreviewInvalidCron},+ {"six fields", "0 0 9 * * *", "UTC", cronPreviewInvalidCron},+ {"descriptor", "@daily", "UTC", cronPreviewInvalidCron},+ {"L token", "0 9 L * *", "UTC", cronPreviewInvalidCron},+ {"missing expr", "", "UTC", cronPreviewInvalidCron},+ // A timezone the server does not know is a distinct fault from a bad+ // expression — the editor fixes them in different controls.+ {"invalid timezone", "0 9 * * *", "Not/AZone", cronPreviewInvalidTimezone},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ w := httptest.NewRecorder()+ testHandler.CronPreview(w, cronPreviewRequest(tc.expr, tc.tz))+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())+ }+ var body struct {+ Error string `json:"error"`+ Code string `json:"code"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || body.Error == "" {+ t.Fatalf("expected {\"error\": ...} body, got %s", w.Body.String())+ }+ if body.Code != tc.code {+ t.Fatalf("expected code %q, got %q", tc.code, body.Code)+ }+ })+ }+}diff --git a/server/internal/service/builtin_skills/multica-autopilots/references/autopilots-source-map.md b/server/internal/service/builtin_skills/multica-autopilots/references/autopilots-source-map.mdindex e33fa08d09..8600c27686 100644--- a/server/internal/service/builtin_skills/multica-autopilots/references/autopilots-source-map.md+++ b/server/internal/service/builtin_skills/multica-autopilots/references/autopilots-source-map.md@@ -9,5 +9,6 @@- `server/cmd/server/router.go` exposes authenticated `/api/autopilots` routes and unauthenticated webhook ingress `/api/webhooks/autopilots/{token}`.- `server/internal/handler/autopilot_webhook.go` durably stores public webhook deliveries, synchronously admits an idempotent run for the compatible `200 accepted|skipped` + `run_id` response, and wakes the worker.- `server/internal/handler/webhook_delivery_worker.go` claims queued deliveries with expiring database leases, applies per-trigger dispatch pacing, and resumes admitted runs using `autopilot_run.webhook_delivery_id` so recovery cannot duplicate a run/task.+- `GET /api/autopilots/cron-preview?expr=&tz=` (`server/internal/handler/autopilot_cron_preview.go`) returns `{next_runs}` — the next 3 occurrences as RFC3339 UTC — or 400 with the parser/timezone error. Compute-only (no autopilot is touched), gated by workspace membership; schedule editors use it instead of approximating the next run client-side.- Write/execute authorization lives in `autopilotWriteByOwnership` / `memberCanWriteAutopilot` / `requireAutopilotWrite` (`server/internal/handler/autopilot.go`): editing, deleting, triggering, replaying deliveries, and managing triggers/webhook secrets require the autopilot's creator, a workspace owner/admin, or an explicit collaborator. Reads (list/get/runs/deliveries) stay open to any workspace member, but `GetAutopilot` redacts `webhook_token`/`webhook_path`/`webhook_url` for callers who lack write access, since the token alone can trigger the autopilot. Creating a new autopilot is still open to any member (they become its creator). This is the autopilot-level View/Write layer; it is independent of, and ANDed with, the private-assignee-agent gate enforced at dispatch time in `shouldSkipDispatch`.- Explicit write grants ("collaborators") are stored in the `autopilot_collaborator` table (migration 128, members-only, no FK — deleted alongside the autopilot in the delete transaction). Endpoints: `POST /api/autopilots/{id}/collaborators` (body `{user_id}`) and `DELETE /api/autopilots/{id}/collaborators/{userId}`, both gated by the NARROWER `requireAutopilotAccessManagement` (creator or workspace owner/admin only — a granted collaborator keeps write/execute but cannot re-grant or revoke peers, preventing privilege escalation), both returning the updated `{collaborators}` list. `GetAutopilot` embeds the `collaborators` array and stamps two per-caller booleans: `can_write` (gates edit/run/trigger controls) and the narrower `can_manage_access` (gates the "Manage access" entry). The web/desktop "Manage access" UI lives in `packages/views/autopilots/components/manage-access-dialog.tsx`.diff --git a/server/internal/service/cron.go b/server/internal/service/cron.goindex 86744688d6..06dc33f339 100644--- a/server/internal/service/cron.go+++ b/server/internal/service/cron.go@@ -2,6 +2,7 @@ package serviceimport ("fmt"+ "strings""time""github.com/robfig/cron/v3"@@ -30,6 +31,33 @@ func NextOccurrenceAfterUTC(cronExpr, timezone string, after time.Time) (time.Tireturn sched.Next(after.In(loc)).UTC(), nil}+// NextOccurrencesAfterUTC parses cronExpr in `timezone` once and returns the+// next `count` activations strictly after `after`, ascending, in UTC. It stops+// early — returning a shorter slice — when the expression has no further+// occurrence within robfig's five-year search horizon (e.g. "0 0 30 2 *"), which+// robfig reports as the zero time.+//+// Unlike calling NextOccurrenceAfterUTC in a loop, the expression is parsed and+// the location loaded exactly once. The schedule editor's preview endpoint asks+// for this on every debounced keystroke, so the difference is not academic.+func NextOccurrencesAfterUTC(cronExpr, timezone string, after time.Time, count int) ([]time.Time, error) {+ sched, loc, err := parseCronSchedule(cronExpr, timezone)+ if err != nil {+ return nil, err+ }+ out := make([]time.Time, 0, count)+ cursor := after.In(loc)+ for i := 0; i < count; i++ {+ next := sched.Next(cursor)+ if next.IsZero() {+ break+ }+ out = append(out, next.UTC())+ cursor = next+ }+ return out, nil+}+// NextOccurrencesUTC parses cronExpr in `timezone` and returns every// activation in the half-open interval `(after, until]`, in canonical// UTC order (ascending). Used by the Autopilot schedule dispatch job to@@ -90,6 +118,14 @@ func ValidateTimezone(timezone string) error {}func parseCronSchedule(cronExpr, timezone string) (cron.Schedule, *time.Location, error) {+ // robfig v3.0.1 reads an optional "TZ="/"CRON_TZ=" prefix up to the first+ // space and panics (parser.go:99, slice[:-1]) when that space is missing.+ // The preview endpoint feeds raw user text here, so reject the shape the+ // parser cannot survive instead of turning a typo into a 500.+ if (strings.HasPrefix(cronExpr, "TZ=") || strings.HasPrefix(cronExpr, "CRON_TZ=")) &&+ !strings.Contains(cronExpr, " ") {+ return nil, nil, fmt.Errorf("parse cron: missing schedule after timezone prefix %q", cronExpr)+ }sched, err := cronParser.Parse(cronExpr)if err != nil {return nil, nil, fmt.Errorf("parse cron: %w", err)diff --git a/server/internal/service/cron_test.go b/server/internal/service/cron_test.goindex 8247db464b..11354983aa 100644--- a/server/internal/service/cron_test.go+++ b/server/internal/service/cron_test.go@@ -160,3 +160,54 @@ func TestNextOccurrenceAdvancesPastFiredSlot(t *testing.T) {t.Fatalf("next occurrence %s must be strictly after the fired slot %s", got, fired)}}++// TestParseCronScheduleTimezonePrefix pins the parser's handling of robfig's+// "TZ=" / "CRON_TZ=" expression prefix — the grammar contract the schedule+// editor's extraction (cron-mapping.ts) is written against.+func TestParseCronScheduleTimezonePrefix(t *testing.T) {+ t.Run("prefix without a schedule errors instead of panicking", func(t *testing.T) {+ // robfig v3.0.1 slices up to the first space and panics when there is+ // none (parser.go:99). The guard must turn that into a parse error.+ for _, expr := range []string{"TZ=UTC", "CRON_TZ=Asia/Tokyo", "TZ="} {+ if _, _, err := parseCronSchedule(expr, "UTC"); err == nil {+ t.Fatalf("expected error for %q", expr)+ }+ }+ })+ t.Run("embedded timezone overrides the timezone argument", func(t *testing.T) {+ after := time.Date(2026, 7, 14, 0, 0, 0, 0, time.UTC)+ got, err := NextOccurrenceAfterUTC("CRON_TZ=Asia/Tokyo 0 9 * * *", "UTC", after)+ if err != nil {+ t.Fatal(err)+ }+ // 09:00 in Tokyo, not 09:00 UTC. `after` is exactly 09:00 Tokyo and+ // Next is strictly after, so the answer is the following day's slot.+ want := time.Date(2026, 7, 15, 0, 0, 0, 0, time.UTC)+ if !got.Equal(want) {+ t.Fatalf("got %s, want %s", got.Format(time.RFC3339), want.Format(time.RFC3339))+ }+ })+ t.Run("prefix and column are equivalent spellings", func(t *testing.T) {+ after := time.Date(2026, 7, 14, 0, 0, 0, 0, time.UTC)+ embedded, err := NextOccurrenceAfterUTC("CRON_TZ=Asia/Tokyo 0 9 * * *", "UTC", after)+ if err != nil {+ t.Fatal(err)+ }+ column, err := NextOccurrenceAfterUTC("0 9 * * *", "Asia/Tokyo", after)+ if err != nil {+ t.Fatal(err)+ }+ if !embedded.Equal(column) {+ t.Fatalf("embedded %s != column %s", embedded, column)+ }+ })+ t.Run("prefix detection is exact", func(t *testing.T) {+ // Lowercase and leading-space forms are NOT prefixes to robfig: the+ // token lands in the fields and the expression is a field-count error.+ for _, expr := range []string{"tz=UTC 0 9 * * *", " TZ=UTC 0 9 * * *"} {+ if _, _, err := parseCronSchedule(expr, "UTC"); err == nil {+ t.Fatalf("expected error for %q", expr)+ }+ }+ })+}