Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: share friendly cron recurrence scheduling

[._.]/ Adam Eivy9c203a33ba1f
diff --git a/client/src/components/CronInput.jsx b/client/src/components/CronInput.jsx
index c3ce8ce366..c628b1fbc0 100644
--- a/client/src/components/CronInput.jsx
+++ b/client/src/components/CronInput.jsx
@@ -1,6 +1,6 @@
import { useState } from 'react';
-import { CRON_PRESETS, DEFAULT_CRON, describeCron, parseSimpleCron } from '../utils/cronHelpers';
-import WeekdayTimePicker from './WeekdayTimePicker';
+import { DEFAULT_CRON } from '../utils/cronHelpers';
+import CronSchedulePicker from './CronSchedulePicker';
/**
* Inline cron expression editor with a day-of-week + time-of-day picker.
@@ -13,10 +13,6 @@ import WeekdayTimePicker from './WeekdayTimePicker';
*/
export default function CronInput({ value, onSave, onCancel, className = '' }) {
const [expr, setExpr] = useState(value || DEFAULT_CRON);
- const [showAdvanced, setShowAdvanced] = useState(false);
-
- const parsed = parseSimpleCron(expr);
- const isDaily = parsed && parsed.days.length === 0;
const handleSave = () => {
const trimmed = expr.trim();
@@ -27,7 +23,14 @@ export default function CronInput({ value, onSave, onCancel, className = '' }) {
return (
<div className={`flex flex-col gap-2 ${className}`}>
<div className="flex flex-wrap items-center gap-1.5">
- <WeekdayTimePicker value={expr} onChange={setExpr} />
+ <CronSchedulePicker
+ value={expr}
+ onChange={setExpr}
+ onCronKeyDown={event => {
+ if (event.key === 'Enter') handleSave();
+ if (event.key === 'Escape') onCancel?.();
+ }}
+ />
<button
type="button"
onClick={handleSave}
@@ -47,46 +50,6 @@ export default function CronInput({ value, onSave, onCancel, className = '' }) {
)}
</div>
- <div className="flex flex-wrap items-center gap-2">
- <span className="text-xs text-gray-500">
- {isDaily ? 'Every day ' : ''}{expr && describeCron(expr)}
- </span>
- <button
- type="button"
- onClick={() => setShowAdvanced(v => !v)}
- className="text-xs text-gray-500 hover:text-gray-300 underline decoration-dotted"
- >
- {showAdvanced ? 'Hide advanced' : 'Advanced'}
- </button>
- </div>
-
- {showAdvanced && (
- <div className="flex flex-wrap items-center gap-1">
- <input
- type="text"
- value={expr}
- onChange={e => setExpr(e.target.value)}
- onKeyDown={e => {
- if (e.key === 'Enter') handleSave();
- if (e.key === 'Escape') onCancel?.();
- }}
- className="w-28 sm:w-32 px-2 py-1 bg-port-bg border border-port-border rounded text-xs text-white font-mono focus:border-port-accent focus:outline-hidden"
- placeholder="0 7 * * *"
- aria-label="Cron expression"
- />
- <select
- value=""
- onChange={e => { if (e.target.value) setExpr(e.target.value); }}
- className="px-1 py-1 bg-port-bg border border-port-border rounded text-gray-400 text-xs"
- aria-label="Cron presets"
- >
- <option value="">Presets</option>
- {CRON_PRESETS.map(p => (
- <option key={p.value} value={p.value}>{p.label}</option>
- ))}
- </select>
- </div>
- )}
</div>
);
}
diff --git a/client/src/components/CronSchedulePicker.jsx b/client/src/components/CronSchedulePicker.jsx
new file mode 100644
index 0000000000..50ca444e54
--- /dev/null
+++ b/client/src/components/CronSchedulePicker.jsx
@@ -0,0 +1,414 @@
+import { useId, useState } from 'react';
+import {
+ CRON_PRESETS,
+ DEFAULT_CRON,
+ DEFAULT_TIME,
+ WEEKDAYS,
+ RECURRENCE_FREQUENCIES,
+ RECURRENCE_ORDINALS,
+ buildCronFromRecurrence,
+ describeRecurrence,
+ parseCronToRecurrence,
+} from '../utils/cronHelpers';
+
+const WEEKDAY_SET = WEEKDAYS.filter(day => day.value >= 1 && day.value <= 5).map(day => day.value);
+
+const localDateKey = (date = new Date()) => {
+ const year = date.getFullYear();
+ const month = String(date.getMonth() + 1).padStart(2, '0');
+ const day = String(date.getDate()).padStart(2, '0');
+ return `${year}-${month}-${day}`;
+};
+
+function nextWeekdayDate(days) {
+ const selected = Array.isArray(days) && days.length ? days : [1];
+ const date = new Date();
+ const today = date.getDay();
+ const delta = Math.min(...selected.map(day => (day - today + 7) % 7));
+ date.setDate(date.getDate() + delta);
+ return localDateKey(date);
+}
+
+function withAnchor(rule) {
+ if (rule.frequency === 'weekly' && Number(rule.interval) > 1 && !rule.anchorDate) {
+ return { ...rule, anchorDate: nextWeekdayDate(rule.weekdays) };
+ }
+ if (rule.frequency.startsWith('monthly') && Number(rule.interval) > 1 && !rule.anchorDate) {
+ return { ...rule, anchorDate: localDateKey() };
+ }
+ if (rule.frequency === 'daily' && Number(rule.interval) > 1 && !rule.anchorDate) {
+ return { ...rule, anchorDate: localDateKey() };
+ }
+ return rule;
+}
+
+function normalizeRule(value) {
+ const parsed = typeof value === 'string' ? parseCronToRecurrence(value) : value;
+ if (parsed?.frequency) {
+ return {
+ interval: 1,
+ time: DEFAULT_TIME,
+ ...parsed,
+ weekdays: Array.isArray(parsed.weekdays) ? parsed.weekdays : [],
+ };
+ }
+ return { frequency: 'daily', interval: 1, weekdays: [], time: DEFAULT_TIME };
+}
+
+function commissionToRule(schedule) {
+ if (!schedule) return normalizeRule(null);
+ if (schedule.kind === 'RECURRENCE') return normalizeRule(schedule.recurrence);
+ if (schedule.kind === 'CUSTOM') return { frequency: 'custom', cron: schedule.cron || '' };
+ if (schedule.kind === 'WEEKLY') {
+ return {
+ frequency: 'weekly', interval: 1, weekdays: Number.isInteger(schedule.weekday) ? [schedule.weekday] : [1],
+ time: schedule.atLocalTime || DEFAULT_TIME,
+ };
+ }
+ return {
+ frequency: 'daily', interval: 1,
+ weekdays: schedule.weekdaysOnly ? WEEKDAY_SET : [],
+ time: schedule.atLocalTime || DEFAULT_TIME,
+ };
+}
+
+function ruleToCommission(rule, previous) {
+ const preserved = previous?.timezone ? { timezone: previous.timezone } : {};
+ if (rule.frequency === 'custom') return { ...preserved, kind: 'CUSTOM', cron: String(rule.cron || '').trim() };
+
+ const days = [...new Set(rule.weekdays || [])].sort((a, b) => a - b);
+ if (rule.frequency === 'daily' && Number(rule.interval) === 1 && (days.length === 0 || days.join(',') === WEEKDAY_SET.join(','))) {
+ return { ...preserved, kind: 'DAILY', atLocalTime: rule.time || DEFAULT_TIME, weekdaysOnly: days.length > 0 };
+ }
+ if (rule.frequency === 'weekly' && Number(rule.interval) === 1 && days.length === 1) {
+ return { ...preserved, kind: 'WEEKLY', weekday: days[0], atLocalTime: rule.time || DEFAULT_TIME };
+ }
+ if (rule.frequency === 'weekly' && days.length === 1) {
+ return { ...preserved, kind: 'RECURRENCE', recurrence: withAnchor({ ...rule, weekdays: days }) };
+ }
+ return {
+ ...preserved,
+ kind: 'RECURRENCE',
+ recurrence: withAnchor({ ...rule, weekdays: days }),
+ };
+}
+
+function DayButtons({ days, onChange }) {
+ const selected = new Set(days || []);
+ const toggle = (day) => {
+ const next = selected.has(day) ? [...selected].filter(value => value !== day) : [...selected, day];
+ onChange(next.sort((a, b) => a - b));
+ };
+ return (
+ <div className="flex flex-wrap items-center gap-1" role="group" aria-label="Days of week">
+ {WEEKDAYS.map(day => (
+ <button
+ key={day.value}
+ type="button"
+ onClick={() => toggle(day.value)}
+ aria-pressed={selected.has(day.value)}
+ aria-label={day.label}
+ title={day.label}
+ className={`min-h-9 min-w-9 rounded text-xs font-medium transition-colors ${
+ selected.has(day.value)
+ ? 'bg-port-accent text-white'
+ : 'border border-port-border bg-port-bg text-gray-400 hover:border-port-accent'
+ }`}
+ >
+ {day.short}
+ </button>
+ ))}
+ </div>
+ );
+}
+
+function TimeInput({ value, onChange, label = 'Time of day' }) {
+ const id = useId();
+ return (
+ <label htmlFor={id} className="flex items-center gap-2 text-xs text-gray-400">
+ <span>{label}</span>
+ <input
+ id={id}
+ type="time"
+ value={value || ''}
+ onChange={event => onChange(event.target.value)}
+ className="rounded border border-port-border bg-port-bg px-2 py-1.5 text-xs text-white focus:border-port-accent focus:outline-hidden"
+ />
+ </label>
+ );
+}
+
+function CronExpressionPicker({ value, onChange, className, showAdvanced, showSummary, cronAriaLabel, onCronKeyDown }) {
+ const expr = typeof value === 'string' ? value : '';
+ const parsed = parseCronToRecurrence(expr);
+ const simple = parsed?.frequency === 'daily' || parsed?.frequency === 'weekly';
+ const days = simple && parsed.frequency === 'weekly' ? parsed.weekdays : [];
+ const time = simple ? parsed.time : '';
+ const [advanced, setAdvanced] = useState(showAdvanced);
+
+ const apply = (nextDays, nextTime) => {
+ const built = buildCronFromRecurrence({
+ frequency: nextDays.length ? 'weekly' : 'daily', interval: 1, weekdays: nextDays, time: nextTime,
+ });
+ if (built) onChange(built);
+ };
+
+ return (
+ <div className={`space-y-2 ${className || ''}`}>
+ <div className="flex flex-wrap items-center gap-3">
+ <DayButtons
+ days={days}
+ onChange={nextDays => apply(nextDays, time || DEFAULT_TIME)}
+ />
+ <TimeInput value={time} onChange={nextTime => apply(days, nextTime)} />
+ </div>
+ {showSummary && expr && <p className="text-xs text-gray-500">{parsed?.frequency === 'custom' ? expr : describeRecurrence(parsed)}</p>}
+ {showAdvanced && (
+ <>
+ <button
+ type="button"
+ onClick={() => setAdvanced(current => !current)}
+ className="text-xs text-gray-500 underline decoration-dotted hover:text-gray-300"
+ >
+ {advanced ? 'Hide advanced' : 'Advanced cron'}
+ </button>
+ {advanced && (
+ <div className="flex flex-wrap items-center gap-2">
+ <input
+ type="text"
+ value={expr}
+ onChange={event => onChange(event.target.value)}
+ onKeyDown={event => {
+ if (event.key === 'Escape') event.currentTarget.blur();
+ onCronKeyDown?.(event);
+ }}
+ className="min-w-[12rem] flex-1 rounded border border-port-border bg-port-bg px-3 py-2 font-mono text-sm text-white"
+ placeholder="0 7 * * *"
+ aria-label={cronAriaLabel}
+ />
+ <select
+ value=""
+ onChange={event => { if (event.target.value) onChange(event.target.value); }}
+ className="rounded border border-port-border bg-port-bg px-2 py-2 text-xs text-gray-400"
+ aria-label="Cron presets"
+ >
+ <option value="">Presets</option>
+ {CRON_PRESETS.map(preset => <option key={preset.value} value={preset.value}>{preset.label}</option>)}
+ </select>
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ );
+}
+
+function RecurrenceRulePicker({ value, onChange, className, showAdvanced = true }) {
+ const [advanced, setAdvanced] = useState(showAdvanced);
+ const customCronId = useId();
+ const anchorDateId = useId();
+ const rule = normalizeRule(value);
+ const update = (patch) => onChange(withAnchor({ ...rule, ...patch }));
+ const setFrequency = (frequency) => {
+ const defaults = {
+ daily: { frequency, interval: 1, weekdays: [], time: rule.time || DEFAULT_TIME },
+ weekly: { frequency, interval: 1, weekdays: rule.weekdays?.length ? rule.weekdays : [1], time: rule.time || DEFAULT_TIME },
+ 'monthly-date': { frequency, interval: 1, dayOfMonth: 1, time: rule.time || DEFAULT_TIME },
+ 'monthly-weekday': { frequency, interval: 1, ordinal: 'first', weekday: 1, time: rule.time || DEFAULT_TIME },
+ custom: { frequency, cron: buildCronFromRecurrence(rule) || DEFAULT_CRON },
+ };
+ onChange(withAnchor(defaults[frequency]));
+ };
+
+ return (
+ <div className={`space-y-3 ${className || ''}`}>
+ <label className="block text-xs text-gray-400">
+ Recurrence pattern
+ <select
+ value={rule.frequency}
+ onChange={event => setFrequency(event.target.value)}
+ className="mt-1.5 w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white"
+ aria-label="Recurrence pattern"
+ >
+ {RECURRENCE_FREQUENCIES.map(option => <option key={option.value} value={option.value}>{option.label}</option>)}
+ </select>
+ </label>
+
+ {rule.frequency === 'custom' ? (
+ <>
+ <label className="block text-xs text-gray-400" htmlFor={customCronId}>
+ Cron expression
+ <input
+ id={customCronId}
+ value={rule.cron || ''}
+ onChange={event => update({ cron: event.target.value })}
+ className="mt-1.5 w-full rounded border border-port-border bg-port-bg px-3 py-2 font-mono text-sm text-white"
+ placeholder="0 7 * * *"
+ />
+ </label>
+ <select
+ value=""
+ onChange={event => { if (event.target.value) update({ cron: event.target.value }); }}
+ className="w-full rounded border border-port-border bg-port-bg px-3 py-2 text-xs text-gray-400"
+ aria-label="Cron presets"
+ >
+ <option value="">Presets</option>
+ {CRON_PRESETS.map(preset => <option key={preset.value} value={preset.value}>{preset.label}</option>)}
+ </select>
+ </>
+ ) : (
+ <>
+ {rule.frequency === 'daily' && (
+ <>
+ <label className="flex flex-wrap items-center gap-2 text-xs text-gray-400">
+ Every
+ <input
+ type="number"
+ min="1"
+ max="365"
+ value={rule.interval || 1}
+ onChange={event => update({ interval: Number(event.target.value) || 1 })}
+ className="w-20 rounded border border-port-border bg-port-bg px-2 py-1.5 text-sm text-white"
+ aria-label="Repeat every number of days"
+ />
+ day(s)
+ </label>
+ <div className="space-y-1">
+ <span className="block text-xs text-gray-500">Optional weekday restriction (leave empty for every day)</span>
+ <DayButtons days={rule.weekdays} onChange={weekdays => update({ weekdays })} />
+ </div>
+ </>
+ )}
+ {rule.frequency === 'weekly' && (
+ <>
+ <label className="flex flex-wrap items-center gap-2 text-xs text-gray-400">
+ Every
+ <input
+ type="number"
+ min="1"
+ max="52"
+ value={rule.interval || 1}
+ onChange={event => update({ interval: Number(event.target.value) || 1 })}
+ className="w-20 rounded border border-port-border bg-port-bg px-2 py-1.5 text-sm text-white"
+ aria-label="Repeat every number of weeks"
+ />
+ week(s) on
+ </label>
+ <DayButtons
+ days={rule.weekdays}
+ onChange={weekdays => update({ weekdays: weekdays.length ? weekdays : [1] })}
+ />
+ </>
+ )}
+ {rule.frequency === 'monthly-date' && (
+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
+ <label className="block text-xs text-gray-400">
+ Day of month
+ <input
+ type="number"
+ min="1"
+ max="31"
+ value={rule.dayOfMonth || 1}
+ onChange={event => update({ dayOfMonth: Number(event.target.value) || 1 })}
+ className="mt-1.5 w-full rounded border border-port-border bg-port-bg px-2 py-1.5 text-sm text-white"
+ />
+ </label>
+ <label className="block text-xs text-gray-400">
+ Every N months
+ <input
+ type="number"
+ min="1"
+ max="12"
+ value={rule.interval || 1}
+ onChange={event => update({ interval: Number(event.target.value) || 1 })}
+ className="mt-1.5 w-full rounded border border-port-border bg-port-bg px-2 py-1.5 text-sm text-white"
+ />
+ </label>
+ </div>
+ )}
+ {rule.frequency === 'monthly-weekday' && (
+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-3">
+ <label className="block text-xs text-gray-400">
+ Which
+ <select value={rule.ordinal || 'first'} onChange={event => update({ ordinal: event.target.value })} className="mt-1.5 w-full rounded border border-port-border bg-port-bg px-2 py-1.5 text-sm text-white">
+ {RECURRENCE_ORDINALS.map(option => <option key={option.value} value={option.value}>{option.label}</option>)}
+ </select>
+ </label>
+ <label className="block text-xs text-gray-400">
+ Weekday
+ <select value={rule.weekday ?? 1} onChange={event => update({ weekday: Number(event.target.value) })} className="mt-1.5 w-full rounded border border-port-border bg-port-bg px-2 py-1.5 text-sm text-white">
+ {WEEKDAYS.map(day => <option key={day.value} value={day.value}>{day.label}</option>)}
+ </select>
+ </label>
+ <label className="block text-xs text-gray-400">
+ Every N months
+ <input
+ type="number"
+ min="1"
+ max="12"
+ value={rule.interval || 1}
+ onChange={event => update({ interval: Number(event.target.value) || 1 })}
+ className="mt-1.5 w-full rounded border border-port-border bg-port-bg px-2 py-1.5 text-sm text-white"
+ />
+ </label>
+ </div>
+ )}
+ <TimeInput value={rule.time} onChange={time => update({ time })} label="Time" />
+ {Number(rule.interval) > 1 && (
+ <label className="block text-xs text-gray-400" htmlFor={anchorDateId}>
+ Starting date
+ <input
+ id={anchorDateId}
+ type="date"
+ value={rule.anchorDate || ''}
+ onChange={event => update({ anchorDate: event.target.value })}
+ className="mt-1.5 rounded border border-port-border bg-port-bg px-2 py-1.5 text-sm text-white"
+ />
+ </label>
+ )}
+ </>
+ )}
+
+ <p className="text-xs text-gray-500">{describeRecurrence(rule)}</p>
+ {showAdvanced && rule.frequency !== 'custom' && (
+ <>
+ <button type="button" onClick={() => setAdvanced(current => !current)} className="text-xs text-gray-500 underline decoration-dotted hover:text-gray-300">
+ {advanced ? 'Hide cron preview' : 'Show cron preview'}
+ </button>
+ {advanced && (
+ <>
+ <p className="text-[11px] text-gray-600">Compatibility preview; anchored intervals run from the calendar rule.</p>
+ <p className="rounded border border-port-border/60 bg-port-bg/60 px-2 py-1.5 font-mono text-xs text-gray-500">{buildCronFromRecurrence(rule) || 'No equivalent cron preview'}</p>
+ </>
+ )}
+ </>
+ )}
+ </div>
+ );
+}
+
+function CommissionSchedulePicker({ value, onChange, className }) {
+ const rule = commissionToRule(value);
+ return (
+ <RecurrenceRulePicker
+ value={rule}
+ onChange={nextRule => onChange(ruleToCommission(nextRule, value))}
+ className={className}
+ showAdvanced
+ />
+ );
+}
+
+/**
+ * Shared friendly cron/recurrence editor.
+ *
+ * `valueShape="cron"` reads/writes a legacy five-field string. `recurrence`
+ * reads/writes the richer calendar rule used by scheduled jobs. `commission`
+ * adapts that same editor to the commission's backwards-compatible schedule
+ * descriptor, including DAILY/WEEKLY/CUSTOM records.
+ */
+export default function CronSchedulePicker({ value, onChange, className = '', valueShape = 'cron', showAdvanced = true, showSummary = true, cronAriaLabel = 'Cron expression', onCronKeyDown }) {
+ if (valueShape === 'commission') return <CommissionSchedulePicker value={value} onChange={onChange} className={className} />;
+ if (valueShape === 'recurrence') return <RecurrenceRulePicker value={value} onChange={onChange} className={className} showAdvanced={showAdvanced} />;
+ return <CronExpressionPicker value={value} onChange={onChange} className={className} showAdvanced={showAdvanced} showSummary={showSummary} cronAriaLabel={cronAriaLabel} onCronKeyDown={onCronKeyDown} />;
+}
diff --git a/client/src/components/CronSchedulePicker.test.jsx b/client/src/components/CronSchedulePicker.test.jsx
new file mode 100644
index 0000000000..86f16f8fa4
--- /dev/null
+++ b/client/src/components/CronSchedulePicker.test.jsx
@@ -0,0 +1,55 @@
+import { describe, it, expect, vi } from 'vitest';
+import { fireEvent, render, screen } from '@testing-library/react';
+import CronSchedulePicker from './CronSchedulePicker.jsx';
+
+describe('CronSchedulePicker', () => {
+ it('edits an arbitrary weekly interval without losing the weekday', () => {
+ const onChange = vi.fn();
+ render(
+ <CronSchedulePicker
+ value={{ frequency: 'weekly', interval: 2, weekdays: [1], time: '02:00', anchorDate: '2026-08-31' }}
+ valueShape="recurrence"
+ onChange={onChange}
+ />,
+ );
+
+ expect(screen.getByText('Every 2 weeks on Mon at 02:00')).toBeInTheDocument();
+ fireEvent.click(screen.getByTitle('Tue'));
+
+ expect(onChange).toHaveBeenLastCalledWith(expect.objectContaining({
+ frequency: 'weekly', interval: 2, weekdays: [1, 2], anchorDate: '2026-08-31',
+ }));
+ });
+
+ it('keeps weekly recurrence valid when the last weekday is clicked', () => {
+ const onChange = vi.fn();
+ render(
+ <CronSchedulePicker
+ value={{ frequency: 'weekly', interval: 1, weekdays: [1], time: '02:00' }}
+ valueShape="recurrence"
+ onChange={onChange}
+ />,
+ );
+
+ fireEvent.click(screen.getByTitle('Mon'));
+ expect(onChange).toHaveBeenLastCalledWith(expect.objectContaining({ weekdays: [1] }));
+ });
+
+ it('adapts legacy commission schedules and promotes them to rich recurrence', () => {
+ const onChange = vi.fn();
+ render(
+ <CronSchedulePicker
+ value={{ kind: 'WEEKLY', weekday: 1, atLocalTime: '02:00' }}
+ valueShape="commission"
+ onChange={onChange}
+ />,
+ );
+
+ fireEvent.change(screen.getByLabelText('Repeat every number of weeks'), { target: { value: '2' } });
+
+ expect(onChange).toHaveBeenLastCalledWith(expect.objectContaining({
+ kind: 'RECURRENCE',
+ recurrence: expect.objectContaining({ frequency: 'weekly', interval: 2, weekdays: [1] }),
+ }));
+ });
+});
diff --git a/client/src/components/WeekdayTimePicker.jsx b/client/src/components/WeekdayTimePicker.jsx
index ecc81da130..7e76d52938 100644
--- a/client/src/components/WeekdayTimePicker.jsx
+++ b/client/src/components/WeekdayTimePicker.jsx
@@ -1,4 +1,4 @@
-import { WEEKDAYS, DEFAULT_TIME, parseSimpleCron, buildWeeklyCron } from '../utils/cronHelpers';
+import CronSchedulePicker from './CronSchedulePicker';
/**
* Day-of-week + time-of-day picker that reads/writes a cron expression.
@@ -10,55 +10,13 @@ import { WEEKDAYS, DEFAULT_TIME, parseSimpleCron, buildWeeklyCron } from '../uti
* and the first interaction converts it into a simple day+time cron.
*/
export default function WeekdayTimePicker({ value, onChange, className = '' }) {
- const parsed = parseSimpleCron(value);
- const days = parsed?.days ?? [];
- const time = parsed?.time ?? '';
-
- const apply = (nextDays, nextTime) => {
- const built = buildWeeklyCron(nextDays, nextTime);
- if (built) onChange(built);
- };
-
- const toggleDay = (day) => {
- const nextDays = days.includes(day) ? days.filter(d => d !== day) : [...days, day];
- apply(nextDays, time || DEFAULT_TIME);
- };
-
- const handleTimeChange = (nextTime) => apply(days, nextTime);
-
return (
- <div className={`flex flex-wrap items-center gap-1.5 ${className}`}>
- <div className="flex items-center gap-0.5" role="group" aria-label="Days of week">
- {WEEKDAYS.map(wd => {
- const active = !!parsed && days.includes(wd.value);
- return (
- <button
- key={wd.value}
- type="button"
- onClick={() => toggleDay(wd.value)}
- aria-pressed={active}
- aria-label={wd.label}
- title={wd.label}
- className={`w-6 h-6 rounded text-xs font-medium ${
- active
- ? 'bg-port-accent text-white'
- : 'bg-port-bg border border-port-border text-gray-400 hover:border-port-accent'
- }`}
- >
- {wd.short}
- </button>
- );
- })}
- </div>
- <label className="flex items-center gap-1 text-xs text-gray-400">
- <span className="sr-only">Time of day</span>
- <input
- type="time"
- value={time}
- onChange={e => handleTimeChange(e.target.value)}
- className="px-2 py-1 bg-port-bg border border-port-border rounded text-xs text-white focus:border-port-accent focus:outline-hidden"
- />
- </label>
- </div>
+ <CronSchedulePicker
+ value={value}
+ onChange={onChange}
+ className={className}
+ showAdvanced={false}
+ showSummary={false}
+ />
);
}
diff --git a/client/src/components/agents/tabs/SchedulesTab.jsx b/client/src/components/agents/tabs/SchedulesTab.jsx
index f5fa39db76..29d9718bf6 100644
--- a/client/src/components/agents/tabs/SchedulesTab.jsx
+++ b/client/src/components/agents/tabs/SchedulesTab.jsx
@@ -4,6 +4,7 @@ import BrailleSpinner from '../../BrailleSpinner';
import { FormField } from '../../ui/FormField';
import { ACTION_TYPES, SCHEDULE_TYPES, CRON_PRESETS, INTERVAL_PRESETS } from '../constants';
import { formatDateTime } from '../../../utils/formatters';
+import CronSchedulePicker from '../../CronSchedulePicker';
export default function SchedulesTab({ agentId }) {
const [schedules, setSchedules] = useState([]);
@@ -204,18 +205,11 @@ export default function SchedulesTab({ agentId }) {
</FormField>
{formData.schedule.type === 'cron' && (
- <FormField label="Cron Expression" className="mb-4">
- <select
+ <FormField label="Cron schedule" className="mb-4">
+ <CronSchedulePicker
value={formData.schedule.cron}
- onChange={(e) => setFormData({ ...formData, schedule: { ...formData.schedule, cron: e.target.value } })}
- className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white"
- >
- {CRON_PRESETS.map(preset => (
- <option key={preset.value} value={preset.value}>
- {preset.label}
- </option>
- ))}
- </select>
+ onChange={cron => setFormData({ ...formData, schedule: { ...formData.schedule, cron } })}
+ />
</FormField>
)}
diff --git a/client/src/components/apps/tabs/CustomTasksSection.jsx b/client/src/components/apps/tabs/CustomTasksSection.jsx
index b1811300b0..ba93c18c0c 100644
--- a/client/src/components/apps/tabs/CustomTasksSection.jsx
+++ b/client/src/components/apps/tabs/CustomTasksSection.jsx
@@ -7,8 +7,8 @@ import FormField from '../../ui/FormField';
import { useConfirmDelete } from '../../../hooks/useConfirmDelete';
import * as api from '../../../services/api';
import { timeAgo } from '../../../utils/formatters';
-import { CRON_PRESETS, DEFAULT_CRON, describeCron } from '../../../utils/cronHelpers';
-import WeekdayTimePicker from '../../WeekdayTimePicker';
+import { DEFAULT_CRON, describeCron, describeRecurrence, parseCronToRecurrence, buildCronFromRecurrence } from '../../../utils/cronHelpers';
+import CronSchedulePicker from '../../CronSchedulePicker';
import { AGENT_OPTIONS, agentOptionButtonClass } from '../../cos/constants';
const INTERVAL_OPTIONS = [
@@ -43,6 +43,7 @@ function emptyForm() {
interval: 'weekly',
scheduledTime: '',
cronExpression: '',
+ cronSchedule: null,
priority: 'MEDIUM',
autonomyLevel: 'manager',
taskMetadata: { useWorktree: true, openPR: true, simplify: true }
@@ -54,10 +55,11 @@ function formFromJob(job) {
name: job.name || '',
description: job.description || '',
promptTemplate: job.promptTemplate || '',
- scheduleMode: job.cronExpression ? 'cron' : 'interval',
+ scheduleMode: job.cronExpression || job.cronSchedule ? 'cron' : 'interval',
interval: job.interval || 'weekly',
scheduledTime: job.scheduledTime || '',
cronExpression: job.cronExpression || '',
+ cronSchedule: job.cronSchedule || (job.cronExpression ? parseCronToRecurrence(job.cronExpression) : null),
priority: job.priority || 'MEDIUM',
autonomyLevel: job.autonomyLevel || 'manager',
taskMetadata: { useWorktree: false, openPR: false, simplify: false, ...(job.taskMetadata || {}) }
@@ -77,10 +79,12 @@ function toPayload(form, appId) {
taskMetadata: form.taskMetadata
};
if (form.scheduleMode === 'cron') {
- payload.cronExpression = form.cronExpression?.trim() || null;
+ payload.cronExpression = buildCronFromRecurrence(form.cronSchedule) || form.cronExpression?.trim() || null;
+ payload.cronSchedule = form.cronSchedule || null;
payload.scheduledTime = null;
} else {
payload.cronExpression = null;
+ payload.cronSchedule = null;
payload.interval = form.interval;
payload.scheduledTime = form.scheduledTime || null;
}
@@ -88,6 +92,7 @@ function toPayload(form, appId) {
}
function scheduleSummary(job) {
+ if (job.cronSchedule) return describeRecurrence(job.cronSchedule);
if (job.cronExpression) return describeCron(job.cronExpression);
const label = INTERVAL_OPTIONS.find(i => i.value === job.interval)?.label || job.interval;
return job.scheduledTime ? `${label} at ${job.scheduledTime}` : label;
@@ -99,7 +104,7 @@ function TaskForm({ form, setForm, onSave, onCancel, saveLabel }) {
// (07:00 daily) so an untouched picker is actually saveable — otherwise the
// form shows a schedule while cronExpression stays empty and Save is blocked.
const setScheduleMode = (mode) =>
- setForm(f => ({ ...f, scheduleMode: mode, cronExpression: mode === 'cron' && !f.cronExpression ? DEFAULT_CRON : f.cronExpression }));
+ setForm(f => ({ ...f, scheduleMode: mode, cronExpression: mode === 'cron' && !f.cronExpression && !f.cronSchedule ? DEFAULT_CRON : f.cronExpression }));
// Toggle a git-workflow flag while preserving the system-wide invariant that
// openPR implies useWorktree (matches toggleAppMetadataOverride used elsewhere):
// turning openPR on forces useWorktree on; turning useWorktree off forces openPR off.
@@ -159,28 +164,15 @@ function TaskForm({ form, setForm, onSave, onCancel, saveLabel }) {
</div>
{form.scheduleMode === 'cron' ? (
<div className="space-y-2">
- <WeekdayTimePicker value={form.cronExpression || DEFAULT_CRON} onChange={value => update('cronExpression', value)} />
- <div className="flex gap-2 items-center flex-wrap">
- <input
- type="text"
- value={form.cronExpression || ''}
- onChange={e => update('cronExpression', e.target.value)}
- className="flex-1 min-w-[10rem] px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm font-mono"
- placeholder="0 7 * * *"
- aria-label="Cron expression"
- title="Cron expression: minute hour dayOfMonth month dayOfWeek"
- />
- <select
- value=""
- onChange={e => { if (e.target.value) update('cronExpression', e.target.value); }}
- className="px-2 py-2 bg-port-bg border border-port-border rounded-lg text-gray-400 text-xs"
- aria-label="Cron presets"
- >
- <option value="">Presets</option>
- {CRON_PRESETS.map(p => <option key={p.value} value={p.value}>{p.label}</option>)}
- </select>
- </div>
- {form.cronExpression && <span className="text-xs text-gray-500">{describeCron(form.cronExpression)}</span>}
+ <CronSchedulePicker
+ value={form.cronSchedule || form.cronExpression || DEFAULT_CRON}
+ valueShape="recurrence"
+ onChange={rule => {
+ update('cronSchedule', rule);
+ const cron = buildCronFromRecurrence(rule);
+ update('cronExpression', cron || null);
+ }}
+ />
</div>
) : (
<div className="flex gap-3">
@@ -275,8 +267,8 @@ export default function CustomTasksSection({ appId, appName }) {
const validate = (form) => {
if (!form.name.trim()) { toast.error('Name is required'); return false; }
if (!form.promptTemplate.trim()) { toast.error('Prompt is required'); return false; }
- if (form.scheduleMode === 'cron' && (!form.cronExpression?.trim() || form.cronExpression.trim().split(/\s+/).length !== 5)) {
- toast.error('A valid 5-field cron expression is required'); return false;
+ if (form.scheduleMode === 'cron' && !form.cronSchedule && (!form.cronExpression?.trim() || form.cronExpression.trim().split(/\s+/).length !== 5)) {
+ toast.error('A valid recurrence or 5-field cron expression is required'); return false;
}
return true;
};
diff --git a/client/src/components/cos/tabs/JobsTab.jsx b/client/src/components/cos/tabs/JobsTab.jsx
index 56492d77b1..5c4934981c 100644
--- a/client/src/components/cos/tabs/JobsTab.jsx
+++ b/client/src/components/cos/tabs/JobsTab.jsx
@@ -3,8 +3,8 @@ import { Plus, RefreshCw, Play, Trash2, ChevronDown, ChevronUp, Clock, ToggleLef
import toast from '../../ui/Toast';
import * as api from '../../../services/api';
import { timeAgo, timeUntil, formatDateTime, formatDateNumeric } from '../../../utils/formatters';
-import { CRON_PRESETS, DEFAULT_CRON, describeCron, JOB_INTERVAL_OPTIONS as INTERVAL_OPTIONS } from '../../../utils/cronHelpers';
-import WeekdayTimePicker from '../../WeekdayTimePicker';
+import { DEFAULT_CRON, describeCron, describeRecurrence, parseCronToRecurrence, buildCronFromRecurrence, JOB_INTERVAL_OPTIONS as INTERVAL_OPTIONS } from '../../../utils/cronHelpers';
+import CronSchedulePicker from '../../CronSchedulePicker';
import { effectiveModelFor, effortAwareModelOptions } from '../../../utils/providers';
import ProviderModelSelector from '../../ProviderModelSelector';
import EffortSelect from '../EffortSelect';
@@ -58,6 +58,7 @@ const INITIAL_JOB = {
interval: 'daily',
scheduledTime: '',
cronExpression: '',
+ cronSchedule: null,
priority: 'MEDIUM',
autonomyLevel: 'manager',
promptTemplate: '',
@@ -174,10 +175,13 @@ function normalizeJobPayload(formData) {
// is unambiguous across create and update.
if (!payload.appId) payload.appId = null;
if (payload.scheduleMode === 'cron') {
- payload.cronExpression = payload.cronExpression?.trim() || null;
+ const derivedCron = buildCronFromRecurrence(payload.cronSchedule);
+ payload.cronExpression = derivedCron || payload.cronExpression?.trim() || null;
+ payload.cronSchedule = payload.cronSchedule || null;
payload.scheduledTime = null;
} else {
payload.cronExpression = null;
+ payload.cronSchedule = null;
}
delete payload.scheduleMode;
return payload;
@@ -196,7 +200,7 @@ function ScheduleFields({ data, onChange }) {
onChange('scheduleMode', opt.value);
// Seed the expression with the picker's displayed default (07:00
// daily) so an untouched Cron picker is actually saveable.
- if (opt.value === 'cron' && !data.cronExpression) onChange('cronExpression', DEFAULT_CRON);
+ if (opt.value === 'cron' && !data.cronExpression && !data.cronSchedule) onChange('cronExpression', DEFAULT_CRON);
}}
className={`px-2 py-1 text-xs rounded transition-colors ${
data.scheduleMode === opt.value
@@ -210,32 +214,15 @@ function ScheduleFields({ data, onChange }) {
</div>
{data.scheduleMode === 'cron' ? (
<div className="space-y-2">
- <WeekdayTimePicker value={data.cronExpression || DEFAULT_CRON} onChange={value => onChange('cronExpression', value)} />
- <div className="flex gap-2 items-center">
- <input
- type="text"
- value={data.cronExpression || ''}
- onChange={e => onChange('cronExpression', e.target.value)}
- className="flex-1 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm font-mono"
- placeholder="0 7 * * *"
- title="Cron expression: minute hour dayOfMonth month dayOfWeek"
- aria-label="Cron expression: minute hour dayOfMonth month dayOfWeek"
- />
- <select
- value=""
- onChange={e => { if (e.target.value) onChange('cronExpression', e.target.value); }}
- className="px-2 py-2 bg-port-bg border border-port-border rounded-lg text-gray-400 text-xs"
- aria-label="Cron presets"
- >
- <option value="">Presets</option>
- {CRON_PRESETS.map(p => (
- <option key={p.value} value={p.value}>{p.label}</option>
- ))}
- </select>
- </div>
- {data.cronExpression && (
- <span className="text-xs text-gray-500">{describeCron(data.cronExpression)}</span>
- )}
+ <CronSchedulePicker
+ value={data.cronSchedule || data.cronExpression || DEFAULT_CRON}
+ valueShape="recurrence"
+ onChange={rule => {
+ onChange('cronSchedule', rule);
+ const cron = buildCronFromRecurrence(rule);
+ onChange('cronExpression', cron || null);
+ }}
+ />
</div>
) : (
<div className="flex gap-3">
@@ -264,6 +251,7 @@ function ScheduleFields({ data, onChange }) {
function formatNextDue(job) {
// Cron jobs: show human-readable schedule (server computes exact next fire time)
+ if (job.cronSchedule) return describeRecurrence(job.cronSchedule);
if (job.cronExpression) return describeCron(job.cronExpression);
const { lastRun, intervalMs, scheduledTime } = job;
@@ -299,10 +287,11 @@ function JobCard({ job, apps, providers, onToggle, onTrigger, onDelete, onUpdate
name: job.name,
description: job.description,
type: job.type || 'agent',
- scheduleMode: job.cronExpression ? 'cron' : 'interval',
+ scheduleMode: job.cronExpression || job.cronSchedule ? 'cron' : 'interval',
interval: job.interval,
scheduledTime: job.scheduledTime || '',
cronExpression: job.cronExpression || '',
+ cronSchedule: job.cronSchedule || (job.cronExpression ? parseCronToRecurrence(job.cronExpression) : null),
priority: job.priority,
autonomyLevel: job.autonomyLevel,
promptTemplate: job.promptTemplate || '',
@@ -382,7 +371,9 @@ function JobCard({ job, apps, providers, onToggle, onTrigger, onDelete, onUpdate
<div className="flex items-center gap-3 text-xs text-gray-500 mt-1">
<span className="flex items-center gap-1">
<Clock size={10} />
- {job.cronExpression
+ {job.cronSchedule
+ ? <span title={job.cronExpression || undefined}>{describeRecurrence(job.cronSchedule)}</span>
+ : job.cronExpression
? <span title={job.cronExpression}>{describeCron(job.cronExpression)}</span>
: <>
{INTERVAL_OPTIONS.find(i => i.value === job.interval)?.label || job.interval}
@@ -678,8 +669,8 @@ export default function JobsTab() {
toast.error('Prompt template is required for AI jobs');
return;
}
- if (newJob.scheduleMode === 'cron' && (!newJob.cronExpression?.trim() || newJob.cronExpression.trim().split(/\s+/).length !== 5)) {
- toast.error('A valid 5-field cron expression is required for cron scheduling');
+ if (newJob.scheduleMode === 'cron' && !newJob.cronSchedule && (!newJob.cronExpression?.trim() || newJob.cronExpression.trim().split(/\s+/).length !== 5)) {
+ toast.error('A valid recurrence or 5-field cron expression is required for cron scheduling');
return;
}
diff --git a/client/src/components/cos/tabs/workflow/ScheduleEditor.jsx b/client/src/components/cos/tabs/workflow/ScheduleEditor.jsx
index 4b238b619c..78afb02753 100644
--- a/client/src/components/cos/tabs/workflow/ScheduleEditor.jsx
+++ b/client/src/components/cos/tabs/workflow/ScheduleEditor.jsx
@@ -2,8 +2,8 @@ import { useEffect, useMemo, useState } from 'react';
import { Bot, GitBranch, Loader2, Plus, Save, X } from 'lucide-react';
import toast from '../../../ui/Toast';
import * as api from '../../../../services/api';
-import { describeCron, parseSimpleCron, buildWeeklyCron, DEFAULT_CRON } from '../../../../utils/cronHelpers';
-import WeekdayTimePicker from '../../../WeekdayTimePicker';
+import { DEFAULT_CRON } from '../../../../utils/cronHelpers';
+import CronSchedulePicker from '../../../CronSchedulePicker';
const TASK_MODES = [
['cron', 'Pinned time (cron)'],
@@ -187,16 +187,9 @@ export default function ScheduleEditor({ node, allNodes, timezone, onClose, onSa
{form.mode === 'cron' && (
<div className="space-y-2">
- <div>
- <span className="block text-xs text-gray-400">Run on</span>
- <WeekdayTimePicker value={form.cronExpression || DEFAULT_CRON} onChange={value => set('cronExpression', value)} className="mt-1.5" />
- <p className="mt-1 text-[11px] text-gray-600">No days selected runs every day.</p>
- </div>
- <label className="block text-xs text-gray-400">
- Advanced cron
- <input value={form.cronExpression} onChange={event => set('cronExpression', event.target.value)} placeholder="0 9 * * *" className="mt-1.5 w-full rounded border border-port-border bg-port-bg px-3 py-2 font-mono text-sm text-white" />
- </label>
- {validateCron(form.cronExpression) && <p className="text-xs text-gray-500">{describeCron(form.cronExpression)}</p>}
+ <span className="block text-xs text-gray-400">Run on</span>
+ <CronSchedulePicker value={form.cronExpression} onChange={value => set('cronExpression', value)} />
+ <p className="text-[11px] text-gray-600">No days selected runs every day.</p>
</div>
)}
@@ -205,14 +198,7 @@ export default function ScheduleEditor({ node, allNodes, timezone, onClose, onSa
<p className="text-xs text-gray-400">
Drains work back-to-back. Once parked, this is its reset/recheck time — leave blank to keep the default interval-based recheck cadence.
</p>
- <input
- type="time"
- value={parseSimpleCron(form.recheckCron)?.time ?? ''}
- aria-label="Perpetual recheck time"
- onChange={event => set('recheckCron', buildWeeklyCron(parseSimpleCron(form.recheckCron)?.days ?? [], event.target.value))}
- className="w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white"
- />
- <input value={form.recheckCron} onChange={event => set('recheckCron', event.target.value)} placeholder="0 9 * * *" className="w-full rounded border border-port-border bg-port-bg px-3 py-2 font-mono text-xs text-gray-300" aria-label="Perpetual recheck cron" />
+ <CronSchedulePicker value={form.recheckCron} onChange={value => set('recheckCron', value)} />
</div>
)}
diff --git a/client/src/components/creative-commission/CommissionConfigForm.jsx b/client/src/components/creative-commission/CommissionConfigForm.jsx
index 3388cad84b..41754c02f3 100644
--- a/client/src/components/creative-commission/CommissionConfigForm.jsx
+++ b/client/src/components/creative-commission/CommissionConfigForm.jsx
@@ -16,8 +16,9 @@ import ProviderModelSelector from '../ProviderModelSelector';
import { isProcessProvider } from '../../utils/providers';
import { getProviders, getSettings, listImageModels, listVideoModels, listMusicEngines } from '../../services/api';
import { deriveAvailableBackends } from '../../lib/imageGenBackends';
+import CronSchedulePicker from '../CronSchedulePicker';
import {
- WEEKDAYS, inputCls, labelCls, describeSchedule,
+ inputCls, labelCls,
ABILITY_OPTIONS, GENERATION_FIELDS_BY_ABILITY, mergeGenerationForAbility,
backendFieldsForAbility, RENDER_BACKEND_AUTO,
COMMISSION_NAME_MAX, COMMISSION_INTENT_MAX, COMMISSION_STYLE_SPEC_MAX, COMMISSION_BRIEF_TAG_MAX,
@@ -131,70 +132,11 @@ export default function CommissionConfigForm({ form, patchForm, saving, onSave,
{/* Schedule */}
<section className="space-y-3 border-t border-port-border pt-4">
<h3 className="text-sm font-semibold text-gray-200">Schedule</h3>
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
- <div>
- <label className={labelCls} htmlFor="commission-kind">Cadence</label>
- <select
- id="commission-kind"
- className={inputCls}
- value={form.schedule.kind}
- onChange={(e) => patchForm(['schedule', 'kind'], e.target.value)}
- >
- <option value="DAILY">Daily</option>
- <option value="WEEKLY">Weekly</option>
- <option value="CUSTOM">Custom (cron)</option>
- </select>
- </div>
- {form.schedule.kind !== 'CUSTOM' && (
- <div>
- <label className={labelCls} htmlFor="commission-time">Time (24h, local)</label>
- <input
- id="commission-time"
- type="time"
- className={inputCls}
- value={form.schedule.atLocalTime}
- onChange={(e) => patchForm(['schedule', 'atLocalTime'], e.target.value)}
- />
- </div>
- )}
- {form.schedule.kind === 'WEEKLY' && (
- <div>
- <label className={labelCls} htmlFor="commission-weekday">Day of week</label>
- <select
- id="commission-weekday"
- className={inputCls}
- value={form.schedule.weekday}
- onChange={(e) => patchForm(['schedule', 'weekday'], Number(e.target.value))}
- >
- {WEEKDAYS.map((d, i) => <option key={i} value={i}>{d}</option>)}
- </select>
- </div>
- )}
- {form.schedule.kind === 'CUSTOM' && (
- <div>
- <label className={labelCls} htmlFor="commission-cron">Cron (5-field)</label>
- <input
- id="commission-cron"
- className={inputCls}
- value={form.schedule.cron}
- maxLength={120}
- onChange={(e) => patchForm(['schedule', 'cron'], e.target.value)}
- placeholder="0 2 * * *"
- />
- </div>
- )}
- </div>
- {form.schedule.kind === 'DAILY' && (
- <label className="flex items-center gap-2 text-sm text-gray-300">
- <input
- type="checkbox"
- checked={form.schedule.weekdaysOnly}
- onChange={(e) => patchForm(['schedule', 'weekdaysOnly'], e.target.checked)}
- />
- Weekdays only (Mon–Fri)
- </label>
- )}
- <p className="text-xs text-gray-500">{describeSchedule(form.schedule)}</p>
+ <CronSchedulePicker
+ value={form.schedule}
+ valueShape="commission"
+ onChange={schedule => patchForm(['schedule'], schedule)}
+ />
</section>
{/* Generation — fields adapt to the selected output type (#2769) */}
diff --git a/client/src/components/creative-commission/commissionForm.js b/client/src/components/creative-commission/commissionForm.js
index b378164fc1..40f68460b7 100644
--- a/client/src/components/creative-commission/commissionForm.js
+++ b/client/src/components/creative-commission/commissionForm.js
@@ -7,6 +7,8 @@
* Kept side-effect-free so both surfaces map record ↔ form identically.
*/
+import { describeRecurrence } from '../../utils/cronHelpers.js';
+
// Client mirror of the server's brief field caps
// (server/lib/creativeCommissionValidation.js). The intent is roomy on purpose:
// it reaches the planning LLM verbatim, so it holds a whole instruction set —
@@ -194,6 +196,7 @@ export function describeSchedule(schedule) {
if (!schedule) return 'No schedule';
const { kind, atLocalTime, weekday, weekdaysOnly, cron } = schedule;
if (kind === 'CUSTOM') return `Custom · ${cron || '—'}`;
+ if (kind === 'RECURRENCE') return describeRecurrence(schedule.recurrence) || 'Custom recurrence';
if (kind === 'WEEKLY') return `Weekly · ${WEEKDAYS[weekday] ?? '—'} at ${atLocalTime || '—'}`;
if (kind === 'DAILY') return `Daily${weekdaysOnly ? ' (weekdays)' : ''} at ${atLocalTime || '—'}`;
return kind || 'No schedule';
@@ -233,6 +236,8 @@ export function toForm(c) {
weekday: Number.isInteger(c.schedule?.weekday) ? c.schedule.weekday : 0,
weekdaysOnly: c.schedule?.weekdaysOnly === true,
cron: c.schedule?.cron || '',
+ recurrence: c.schedule?.recurrence || null,
+ timezone: c.schedule?.timezone || null,
},
// Per-ability generation (#2769): only the selected type's fields, filled
// from the record or the type's defaults.
@@ -263,8 +268,11 @@ export const blankForm = () => toForm({});
// Build the API payload from form state, dropping fields the schedule kind doesn't use.
export function toPayload(form) {
const s = { kind: form.schedule.kind };
+ if (form.schedule.timezone) s.timezone = form.schedule.timezone;
if (form.schedule.kind === 'CUSTOM') {
s.cron = form.schedule.cron.trim();
+ } else if (form.schedule.kind === 'RECURRENCE') {
+ s.recurrence = form.schedule.recurrence;
} else {
s.atLocalTime = form.schedule.atLocalTime;
if (form.schedule.kind === 'WEEKLY') s.weekday = Number(form.schedule.weekday);
diff --git a/client/src/components/creative-commission/commissionForm.test.js b/client/src/components/creative-commission/commissionForm.test.js
index 8fcc9242d9..b77b2cc6cd 100644
--- a/client/src/components/creative-commission/commissionForm.test.js
+++ b/client/src/components/creative-commission/commissionForm.test.js
@@ -52,6 +52,12 @@ describe('commissionForm helpers', () => {
expect(p.schedule).toEqual({ kind: 'CUSTOM', cron: '0 2 * * *' });
});
+ it('round-trips rich recurrence and an explicit timezone', () => {
+ const recurrence = { frequency: 'monthly-weekday', interval: 1, ordinal: 'first', weekday: 4, time: '19:00' };
+ const form = toForm({ schedule: { kind: 'RECURRENCE', recurrence, timezone: 'UTC' } });
+ expect(toPayload(form).schedule).toEqual({ kind: 'RECURRENCE', recurrence, timezone: 'UTC' });
+ });
+
it('nulls a provider-less model so a stored pin never dangles', () => {
const form = { ...blankForm(), assignment: { providerId: '', model: 'gpt-x' } };
expect(toPayload(form).assignment).toEqual({ providerId: null, model: null });
diff --git a/client/src/components/privacy/PrivacyBrokersTab.jsx b/client/src/components/privacy/PrivacyBrokersTab.jsx
index ebaf496c04..5e23fdb604 100644
--- a/client/src/components/privacy/PrivacyBrokersTab.jsx
+++ b/client/src/components/privacy/PrivacyBrokersTab.jsx
@@ -18,6 +18,7 @@ import {
ACTION_TONES, manualCaseActions, labelFor,
} from './constants';
import { isHttpUrl } from '../../utils/urlNormalize';
+import CronSchedulePicker from '../CronSchedulePicker';
// Digest action icon by descriptor `icon` token (positive resolution vs dismiss).
const ACTION_ICONS = { check: CheckCircle2, x: XCircle };
@@ -244,16 +245,9 @@ export default function PrivacyBrokersTab({ subjectId }) {
)}
</label>
- <div className="flex flex-wrap items-center gap-2">
- <label htmlFor="privacy-recheck-cron" className="text-[11px] uppercase tracking-wide text-gray-500">Cron</label>
- <input
- id="privacy-recheck-cron"
- type="text"
- value={cronDraft}
- onChange={(e) => setCronDraft(e.target.value)}
- placeholder="0 4 * * 0"
- className="px-2 py-1 text-sm rounded bg-port-bg border border-port-border text-gray-200 font-mono w-36"
- />
+ <div className="space-y-2">
+ <span className="text-[11px] uppercase tracking-wide text-gray-500">Recheck cadence</span>
+ <CronSchedulePicker value={cronDraft} onChange={setCronDraft} />
<button
onClick={saveCron}
disabled={!cronDirty || scheduleSaving}
diff --git a/client/src/components/settings/BackupTab.jsx b/client/src/components/settings/BackupTab.jsx
index ae596ff9c9..be620b833e 100644
--- a/client/src/components/settings/BackupTab.jsx
+++ b/client/src/components/settings/BackupTab.jsx
@@ -8,6 +8,7 @@ import useAsyncAction from '../../hooks/useAsyncAction';
import Modal from '../ui/Modal';
import { getSettings, updateSettings, getBackupStatus, triggerBackup, getBackupSnapshots, restoreDatabase } from '../../services/api';
import { formatBytes } from '../../utils/formatters';
+import CronSchedulePicker from '../CronSchedulePicker';
// Set equality — rsync --exclude flags are order-independent, so reordering
// is NOT a dirty state; only membership changes (added/removed entries) are.
@@ -38,7 +39,6 @@ const shadowsDefault = (customPath, defaultPath) => {
export function BackupTab() {
const destPathId = useId();
- const cronId = useId();
const additionalExcludeId = useId();
const defaultExcludesPanelId = useId();
const [loading, setLoading] = useState(true);
@@ -304,16 +304,9 @@ export function BackupTab() {
</div>
<div className="space-y-1">
- <label htmlFor={cronId} className="block text-sm text-gray-400">Schedule (cron)</label>
- <input
- id={cronId}
- type="text"
- value={cronExpression}
- onChange={e => setCronExpression(e.target.value)}
- className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"
- placeholder="0 2 * * *"
- />
- <p className="text-xs text-gray-500">Default: 2:00 AM daily</p>
+ <span className="block text-sm text-gray-400">Schedule</span>
+ <CronSchedulePicker value={cronExpression} onChange={setCronExpression} cronAriaLabel="Schedule (cron)" />
+ <p className="text-xs text-gray-500">Default: 2:00 AM daily. Times use the configured timezone.</p>
</div>
{defaultExcludeRows.length > 0 && (
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index 6ab371f4c5..f8233964e4 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -23,7 +23,7 @@ grep -i "what you want to do" client/src/utils/README.md
| Module | Purpose |
|---|---|
| `formatters` | Date/time/duration/byte/word formatters (`clamp`, `formatBytes`, `formatDownloadGb` (decimal-GB model download size, "~29 GB"), `formatCompactCount`, `timeAgo`, `formatAgeDays` (age in whole DAYS — "412 days ago" — where `timeAgo` would collapse to "1y ago"; model-download lists), `localDateKey` (browser-local `YYYY-MM-DD`), `shiftISODate` (DST-safe calendar-day shifts), `formatTimecode`, `formatDurationMs`, `formatDateShort`, `formatContextTokens` (suffix-less context length, "4K"), `throughputLabel` (a measured model's speed as one label — tok/s where the runtime reported token counts, `~` prefixed when frame-counted, else chars/s; never both), `parseTimeoutMs`, `formatCooldown`, `recommendedRamGb`, `nameFromImageFilename`, `formatUsd` — one USD renderer (`signed` puts the minus outside the `$`; `trimWhole` drops `.00` on a typed round price) — `formatWeight` / `formatPercent` — round unit-converted floats (`170.35000000000002` → `170.4 lbs`) so raw binary precision never reaches a tile — `middleTruncate` — clip a long string from the MIDDLE so its distinguishing tail survives, where CSS `line-clamp`/`text-overflow` always eats the end — …) plus timeout-input bounds and `getAppName`. Do not re-define formatters inside components. **Never write `new Date(x).toLocaleDateString()` inline** — pick the helper for the shape you want: `formatDateNumeric` ("3/5/2026", compact cells), `formatDateShort` ("Mar 5, 2026"), `formatDate` ("March 5, 2026"), `formatDateFull` ("Saturday, March 5, 2026"), `formatWeekdayDate` ("Monday, Mar 5", `{ weekday, year }`), `formatMonthDay` ("Mar 5"), `formatMonthYear` ("March 2026"), `formatWeekdayShort` ("Mon"), `formatWeekdayTime` ("Mon, 7:00 AM"), `formatTimeOfDay` ("1:30 PM"), `formatTimeOfDaySeconds` ("1:30:45 PM", log/queue rows), `formatClockTime` ("02:30:45 PM"; `{ seconds, hour12, timeZone }`), `formatDateTime`. Date display helpers anchor a bare `YYYY-MM-DD` at LOCAL midnight (a naive `new Date('2026-03-05')` is UTC midnight and renders as the previous day west of Greenwich) and take a fallback instead of rendering the literal "Invalid Date". |
-| `cronHelpers` | Cron preset list, `isCronExpression` detection, `describeCron` human-readable rendering, and `JOB_INTERVAL_OPTIONS` — the interval-mode cadences for autonomous jobs, mirroring the server's `INTERVAL_OPTIONS`. Import it rather than re-declaring the list in a scheduling component. |
+| `cronHelpers` | Cron preset list, friendly cron parsing/building, anchored recurrence parsing/building/description, `isCronExpression` detection, `describeCron` human-readable rendering, and `JOB_INTERVAL_OPTIONS` — the interval-mode cadences for autonomous jobs, mirroring the server's `INTERVAL_OPTIONS`. Import it rather than re-declaring the list in a scheduling component. |
| `markdownText` | `markdownToPlainText(md)` — flatten markdown source to one plain-text string for a clamped preview: strips heading/list/blockquote/fence markers, unwraps emphasis, inline code and links, images → `[alt]`, collapses blank-line runs. Use whenever a card previews arbitrary agent-authored markdown — `line-clamp-N` does not clamp a subtree of block elements, and foreign `##` headings would otherwise join the page's heading outline. Underscore emphasis is word-boundary gated and `__…__` needs interior whitespace, so stack frames and user-agent strings (`10_15_7`, `__init__`) are never silently rewritten. `dropsMarkupWhenFlattened(md)` — did the flatten lose actual markup, as opposed to only normalizing whitespace? Gates a "Show more" disclosure so a short-but-lossy body stays reachable without putting a toggle on every body that merely lost a trailing newline. |
| `timeWindow` | Time-of-day window math (`isInTimeWindow`, `timeStringToMinutes`) and morning-layout auto-switch helpers (`pickActiveLayoutId`, `recordManualLayoutPick`). |
| `timezone` | Timezone day-key helpers (`dayKeyInTimezone`, `todayKeyInTimezone`) — browser mirror of the server's `todayInTimezone`, so date-scoped POST surfaces derive "today" in the user's configured timezone and agree with the server (#2681). |
diff --git a/client/src/utils/cronHelpers.js b/client/src/utils/cronHelpers.js
index 628c5bacef..ea1bea6b12 100644
--- a/client/src/utils/cronHelpers.js
+++ b/client/src/utils/cronHelpers.js
@@ -86,6 +86,142 @@ export function buildWeeklyCron(days, time) {
return `${minute} ${hr} * * ${dow}`;
}
+export const RECURRENCE_FREQUENCIES = [
+ { value: 'daily', label: 'Every day' },
+ { value: 'weekly', label: 'Weekly' },
+ { value: 'monthly-date', label: 'Day of the month' },
+ { value: 'monthly-weekday', label: 'Nth weekday of the month' },
+ { value: 'custom', label: 'Custom cron' },
+];
+
+export const RECURRENCE_ORDINALS = [
+ { value: 'first', label: 'First' },
+ { value: 'second', label: 'Second' },
+ { value: 'third', label: 'Third' },
+ { value: 'fourth', label: 'Fourth' },
+ { value: 'last', label: 'Last' },
+];
+
+const MONTHLY_DAY_RANGES = {
+ first: '1-7',
+ second: '8-14',
+ third: '15-21',
+ fourth: '22-28',
+};
+
+const ORDINAL_LABELS = Object.fromEntries(RECURRENCE_ORDINALS.map(({ value, label }) => [value, label]));
+
+const validTime = (time) => {
+ const match = String(time || '').match(/^([01]\d|2[0-3]):([0-5]\d)$/);
+ return match ? `${match[1]}:${match[2]}` : null;
+};
+
+const sortedUniqueDays = (days) => [...new Set((Array.isArray(days) ? days : []).map(Number))]
+ .filter(day => Number.isInteger(day) && day >= 0 && day <= 6)
+ .sort((a, b) => a - b);
+
+/**
+ * Parse the part of cron that the recurrence editor can round-trip. More
+ * expressive/legacy strings return a custom rule so the advanced editor never
+ * replaces a value merely because its friendly controls cannot model it.
+ */
+export function parseCronToRecurrence(expr) {
+ if (!expr) return null;
+ const parts = String(expr).trim().split(/\s+/);
+ if (parts.length !== 5) return { frequency: 'custom', cron: String(expr).trim() };
+ const [minute, hour, dom, mon, dow] = parts;
+ const time = validTime(`${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`);
+ if (!time || mon !== '*') return { frequency: 'custom', cron: String(expr).trim() };
+
+ if (dom === '*') {
+ const days = parseDowField(dow);
+ if (!days) return { frequency: 'custom', cron: String(expr).trim() };
+ return days.length === 0
+ ? { frequency: 'daily', interval: 1, weekdays: [], time }
+ : { frequency: 'weekly', interval: 1, weekdays: days, time };
+ }
+
+ if (dow === '*' && /^\d{1,2}$/.test(dom)) {
+ const dayOfMonth = Number(dom);
+ if (dayOfMonth >= 1 && dayOfMonth <= 31) {
+ return { frequency: 'monthly-date', interval: 1, dayOfMonth, time };
+ }
+ }
+
+ const ordinal = Object.entries(MONTHLY_DAY_RANGES).find(([, range]) => range === dom)?.[0];
+ if (ordinal && /^\d$/.test(dow) && Number(dow) <= 7) {
+ return { frequency: 'monthly-weekday', interval: 1, ordinal, weekday: Number(dow) % 7, time };
+ }
+
+ return { frequency: 'custom', cron: String(expr).trim() };
+}
+
+/** Build a compatibility cron string from a recurrence rule. */
+export function buildCronFromRecurrence(rule) {
+ if (!rule || typeof rule !== 'object') return '';
+ if (rule.frequency === 'custom') return String(rule.cron || '').trim();
+ const time = validTime(rule.time);
+ if (!time) return '';
+ const [hour, minute] = time.split(':').map(Number);
+ const prefix = `${minute} ${hour}`;
+ const interval = Math.max(1, Number(rule.interval) || 1);
+
+ if (rule.frequency === 'daily') {
+ const days = sortedUniqueDays(rule.weekdays);
+ // A stepped day-of-month field combined with a weekday is not an exact
+ // representation of an anchored daily interval. Keep the preview honest.
+ if (days.length && interval > 1) return '';
+ return `${prefix} ${interval > 1 ? `*/${interval}` : '*'} * ${days.length ? days.join(',') : '*'}`;
+ }
+ if (rule.frequency === 'weekly') {
+ const days = sortedUniqueDays(rule.weekdays);
+ return `${prefix} * * ${days.length ? days.join(',') : '*'}`;
+ }
+ if (rule.frequency === 'monthly-date') {
+ const day = Number(rule.dayOfMonth);
+ return Number.isInteger(day) && day >= 1 && day <= 31 ? `${prefix} ${day} * *` : '';
+ }
+ if (rule.frequency === 'monthly-weekday') {
+ const range = MONTHLY_DAY_RANGES[rule.ordinal];
+ const weekday = Number(rule.weekday);
+ if (!range || !Number.isInteger(weekday) || weekday < 0 || weekday > 6) return '';
+ // `last` is intentionally left to the recurrence scheduler; there is no
+ // portable five-field cron spelling for the last weekday of a month.
+ return range ? `${prefix} ${range} * ${weekday}` : '';
+ }
+ return '';
+}
+
+/** Human-readable rendering for a rule emitted by CronSchedulePicker. */
+export function describeRecurrence(rule) {
+ if (!rule) return '';
+ if (rule.frequency === 'custom') return rule.cron || '';
+ const time = validTime(rule.time) || '—';
+ const interval = Math.max(1, Number(rule.interval) || 1);
+ if (rule.frequency === 'daily') {
+ const weekdaysOnly = sortedUniqueDays(rule.weekdays).join(',') === '1,2,3,4,5';
+ if (weekdaysOnly) return `Weekdays at ${time}`;
+ const days = sortedUniqueDays(rule.weekdays).map(day => WEEKDAYS[day]?.label || day).join(', ');
+ const cadence = interval === 1 ? 'Daily' : `Every ${interval} days`;
+ return `${cadence}${days ? ` on ${days}` : ''} at ${time}`;
+ }
+ if (rule.frequency === 'weekly') {
+ const days = sortedUniqueDays(rule.weekdays).map(day => WEEKDAYS[day]?.label || day).join(', ');
+ const cadence = interval === 1 ? 'Weekly' : `Every ${interval} weeks`;
+ return `${cadence}${days ? ` on ${days}` : ''} at ${time}`;
+ }
+ if (rule.frequency === 'monthly-date') {
+ const cadence = interval === 1 ? 'every month' : `every ${interval} months`;
+ return `Day ${rule.dayOfMonth || '—'} of ${cadence} at ${time}`;
+ }
+ if (rule.frequency === 'monthly-weekday') {
+ const weekday = WEEKDAYS[Number(rule.weekday)]?.label || 'weekday';
+ const cadence = interval === 1 ? 'every month' : `every ${interval} months`;
+ return `${ORDINAL_LABELS[rule.ordinal] || 'Nth'} ${weekday} of ${cadence} at ${time}`;
+ }
+ return '';
+}
+
export function describeCron(expr) {
if (!expr) return '';
const parts = expr.trim().split(/\s+/);
diff --git a/client/src/utils/cronHelpers.test.js b/client/src/utils/cronHelpers.test.js
index f277a731be..c76cac6b51 100644
--- a/client/src/utils/cronHelpers.test.js
+++ b/client/src/utils/cronHelpers.test.js
@@ -1,5 +1,8 @@
import { describe, it, expect } from 'vitest';
-import { parseSimpleCron, buildWeeklyCron, describeCron, WEEKDAYS } from './cronHelpers.js';
+import {
+ parseSimpleCron, buildWeeklyCron, describeCron, WEEKDAYS,
+ parseCronToRecurrence, buildCronFromRecurrence, describeRecurrence,
+} from './cronHelpers.js';
describe('parseSimpleCron', () => {
it('parses a daily cron as every-day (no days)', () => {
@@ -84,4 +87,28 @@ describe('WEEKDAYS', () => {
expect(WEEKDAYS[0].label).toBe('Sun');
});
});
+
+describe('calendar recurrence helpers', () => {
+ it('builds and describes an anchored every-two-weeks rule', () => {
+ const rule = {
+ frequency: 'weekly', interval: 2, weekdays: [1], time: '02:00', anchorDate: '2026-08-31',
+ };
+ expect(buildCronFromRecurrence(rule)).toBe('0 2 * * 1');
+ expect(describeRecurrence(rule)).toBe('Every 2 weeks on Mon at 02:00');
+ });
+
+ it('parses a first-Thursday cron into the monthly weekday shape', () => {
+ const rule = parseCronToRecurrence('0 19 1-7 * 4');
+ expect(rule).toEqual({
+ frequency: 'monthly-weekday', interval: 1, ordinal: 'first', weekday: 4, time: '19:00',
+ });
+ expect(buildCronFromRecurrence(rule)).toBe('0 19 1-7 * 4');
+ });
+
+ it('keeps last-weekday recurrence in the rich shape', () => {
+ const rule = { frequency: 'monthly-weekday', interval: 1, ordinal: 'last', weekday: 4, time: '19:00' };
+ expect(buildCronFromRecurrence(rule)).toBe('');
+ expect(describeRecurrence(rule)).toBe('Last Thu of every month at 19:00');
+ });
+});
// @vitest-environment node
diff --git a/server/lib/README.md b/server/lib/README.md
index 947fc07f35..9ebfffddb3 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -39,6 +39,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `quotaBurnValidation.js` | Zod schemas for the Quota Burn routes (partial config PUT, manual-run body, `run once` re-arm body). |
| `quotaReset.js` | `parseHumanReset` turns a provider CLI's human reset string into ISO 8601 (call it from the adapter); `normalizeResetAt`/`hoursUntilReset` compute time remaining without treating unknown values as imminent resets; `parseObservedReset` pulls the reset a provider stated in its own refusal text, and `isObservedBlockActive` is the shared "is that refusal still holding?" predicate every observed-refusal ledger uses. |
| `quotaWindows.js` | Classifies a quota window by PERIOD (`windowPeriodHours`); `classifyWindows` splits one card's windows into the weekly allowance that expires unused and the 5-hour one that refuses first, in one pass. `windowLabelOf` names a window. Pure. |
+| `recurrenceValidation.js` | Shared Zod shape and vocabulary for anchored calendar recurrences that cannot be represented faithfully by five-field cron. |
| `appleHealthValidation.js` | Apple Health import payloads. |
| `brainValidation.js` | Brain/memory route schemas (search, ingest, edit). |
| `catalogValidation.js` | Creative ingredients catalog route schemas (scraps, ingredients, links, relations, tags, revisions, sync envelope). |
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index 9838867f43..865267db95 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -17,6 +17,7 @@ import { CURSOR_COMMAND } from './cursor.js';
import { isValidSlashdoCommand } from './slashdoInvocation.js';
import { PR_COMPLETION_VALUES } from './prDisposition.js';
import { AGENT_RUN_EVENT_KINDS, RUN_EVENT_READ_LIMITS } from './agentRunEvents.js';
+import { recurrenceRuleSchema } from './recurrenceValidation.js';
// =============================================================================
// COS TASK SCHEMAS
@@ -1438,6 +1439,10 @@ export const createCosJobSchema = z.object({
// distinguish "clear this field" from an omitted field it should preserve.
scheduledTime: z.string().nullable().optional(),
cronExpression: z.string().nullable().optional(),
+ // Optional calendar rule for schedules that need an anchored interval (for
+ // example every two weeks). cronExpression remains the compatibility preview
+ // and the raw/custom path.
+ cronSchedule: recurrenceRuleSchema.nullable().optional(),
enabled: z.boolean().optional(),
priority: z.string().optional(),
autonomyLevel: z.enum(['standby', 'assistant', 'manager', 'yolo']).optional(),
diff --git a/server/lib/creativeCommissionValidation.js b/server/lib/creativeCommissionValidation.js
index c572a7d0bb..308a3327aa 100644
--- a/server/lib/creativeCommissionValidation.js
+++ b/server/lib/creativeCommissionValidation.js
@@ -2,6 +2,7 @@ import { z } from 'zod';
import { QUEUEABLE_IMAGE_MODES } from '../services/imageGen/modes.js';
import { VIDEO_GEN_MODES } from '../services/videoGen/modes.js';
import { RENDER_TARGET_BACKEND_AUTO } from './renderTargets.js';
+import { recurrenceRuleSchema } from './recurrenceValidation.js';
// =============================================================================
// CREATIVE COMMISSION SCHEMAS (Autonomous Creation Engine — #2657, Phase 1)
@@ -29,8 +30,9 @@ import { RENDER_TARGET_BACKEND_AUTO } from './renderTargets.js';
export const CREATIVE_COMMISSION_ABILITIES = Object.freeze(['video', 'image', 'music', 'music-video', 'series']);
// Schedule cadence kinds. DAILY/WEEKLY are composed into a cron by the service;
-// CUSTOM carries a raw 5-field cron the service validates via isValidCron.
-export const CREATIVE_COMMISSION_SCHEDULE_KINDS = Object.freeze(['DAILY', 'WEEKLY', 'CUSTOM']);
+// CUSTOM carries a raw 5-field cron; RECURRENCE carries the richer calendar rule
+// used for anchored intervals such as every two weeks or the last Thursday.
+export const CREATIVE_COMMISSION_SCHEDULE_KINDS = Object.freeze(['DAILY', 'WEEKLY', 'CUSTOM', 'RECURRENCE']);
export const CREATIVE_COMMISSION_QUALITIES = Object.freeze(['draft', 'standard', 'high']);
export const CREATIVE_COMMISSION_ASPECT_RATIOS = Object.freeze(['16:9', '9:16', '1:1']);
@@ -226,6 +228,7 @@ export const creativeCommissionScheduleSchema = z.object({
// CUSTOM only: a raw 5-field cron. Loosely bounded here; isValidCron is the
// authority (service layer).
cron: z.string().trim().max(120).optional(),
+ recurrence: recurrenceRuleSchema.optional(),
// IANA tz; null/absent falls back to the user's configured timezone at fire.
timezone: z.string().max(64).nullable().optional(),
}).superRefine((val, ctx) => {
@@ -239,6 +242,9 @@ export const creativeCommissionScheduleSchema = z.object({
if (val.kind === 'CUSTOM' && !val.cron) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['cron'], message: 'CUSTOM schedule requires a cron expression' });
}
+ if (val.kind === 'RECURRENCE' && !val.recurrence) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['recurrence'], message: 'RECURRENCE schedule requires a recurrence rule' });
+ }
// Reject an invalid IANA timezone at the request boundary — eventScheduler
// passes it to Intl.DateTimeFormat, which throws RangeError on a bad zone; a
// bad value persisted here would wedge the whole scheduler sync at register
diff --git a/server/lib/index.js b/server/lib/index.js
index 80fccc7bdb..3cf8a3c3e2 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -157,6 +157,7 @@ export * from './auditCatalog.js';
export * from './quotaBurnValidation.js';
export * from './quotaReset.js';
export * from './quotaWindows.js';
+export * from './recurrenceValidation.js';
export * from './opencodeConfig.js';
export * from './localProviderRuntime.js';
export * from './mtplxModels.js';
diff --git a/server/lib/recurrenceValidation.js b/server/lib/recurrenceValidation.js
new file mode 100644
index 0000000000..cfc5658ca5
--- /dev/null
+++ b/server/lib/recurrenceValidation.js
@@ -0,0 +1,74 @@
+import { z } from 'zod';
+
+// Calendar recurrence is deliberately separate from five-field cron. Cron is
+// still the wire format for existing schedules, but it cannot express an
+// anchored every-N-weeks rule without either drifting at month boundaries or
+// firing on the wrong weeks.
+export const RECURRENCE_FREQUENCIES = Object.freeze([
+ 'daily',
+ 'weekly',
+ 'monthly-date',
+ 'monthly-weekday',
+ 'custom',
+]);
+
+export const RECURRENCE_ORDINALS = Object.freeze(['first', 'second', 'third', 'fourth', 'last']);
+
+const HHMM_RE = /^([01]\d|2[0-3]):[0-5]\d$/;
+const DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
+
+function isValidCalendarDate(value) {
+ const match = value.match(DATE_RE);
+ if (!match) return false;
+ const year = Number(match[1]);
+ const month = Number(match[2]);
+ const day = Number(match[3]);
+ const date = new Date(Date.UTC(year, month - 1, day));
+ return date.getUTCFullYear() === year
+ && date.getUTCMonth() + 1 === month
+ && date.getUTCDate() === day;
+}
+
+export const recurrenceRuleSchema = z.object({
+ frequency: z.enum(RECURRENCE_FREQUENCIES),
+ // For daily this is days; weekly, weeks; monthly, months.
+ interval: z.number().int().min(1).max(365).optional().default(1),
+ time: z.string().regex(HHMM_RE, 'must be HH:MM (24h)').optional(),
+ weekdays: z.array(z.number().int().min(0).max(6)).max(7).optional().default([]),
+ weekday: z.number().int().min(0).max(6).optional(),
+ dayOfMonth: z.number().int().min(1).max(31).optional(),
+ ordinal: z.enum(RECURRENCE_ORDINALS).optional(),
+ // The anchor is local-calendar data, not an instant. It makes every-N-weeks
+ // and every-N-months stable across restarts and timezone/DST changes.
+ anchorDate: z.string()
+ .regex(DATE_RE, 'must be YYYY-MM-DD')
+ .refine(isValidCalendarDate, 'must be a valid calendar date')
+ .optional(),
+ // Only used when frequency is custom. The scheduler validates the expression
+ // with its own parser after this shape check.
+ cron: z.string().trim().max(120).optional(),
+}).superRefine((value, ctx) => {
+ if (value.frequency === 'custom') {
+ if (!value.cron) ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['cron'], message: 'custom recurrence requires cron' });
+ return;
+ }
+ if (!value.time) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['time'], message: 'recurrence requires time' });
+ }
+ if (value.frequency === 'weekly' && value.interval > 52) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['interval'], message: 'weekly recurrence supports at most 52 weeks' });
+ }
+ if ((value.frequency === 'monthly-date' || value.frequency === 'monthly-weekday') && value.interval > 12) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['interval'], message: 'monthly recurrence supports at most 12 months' });
+ }
+ if (value.frequency === 'weekly' && value.weekdays.length === 0) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['weekdays'], message: 'weekly recurrence requires a weekday' });
+ }
+ if (value.frequency === 'monthly-date' && value.dayOfMonth == null) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['dayOfMonth'], message: 'monthly-date recurrence requires dayOfMonth' });
+ }
+ if (value.frequency === 'monthly-weekday') {
+ if (!value.ordinal) ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['ordinal'], message: 'monthly-weekday recurrence requires ordinal' });
+ if (value.weekday == null) ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['weekday'], message: 'monthly-weekday recurrence requires weekday' });
+ }
+});
diff --git a/server/lib/recurrenceValidation.test.js b/server/lib/recurrenceValidation.test.js
new file mode 100644
index 0000000000..baf60bb887
--- /dev/null
+++ b/server/lib/recurrenceValidation.test.js
@@ -0,0 +1,36 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+import { recurrenceRuleSchema } from './recurrenceValidation.js';
+
+describe('recurrenceRuleSchema', () => {
+ it('accepts an anchored every-two-weeks rule', () => {
+ expect(recurrenceRuleSchema.safeParse({
+ frequency: 'weekly', interval: 2, weekdays: [1], time: '02:00', anchorDate: '2026-08-31',
+ }).success).toBe(true);
+ });
+
+ it('accepts an nth weekday rule', () => {
+ expect(recurrenceRuleSchema.safeParse({
+ frequency: 'monthly-weekday', ordinal: 'first', weekday: 4, time: '19:00',
+ }).success).toBe(true);
+ });
+
+ it('rejects a weekly rule without a selected weekday', () => {
+ expect(recurrenceRuleSchema.safeParse({ frequency: 'weekly', time: '02:00' }).success).toBe(false);
+ });
+
+ it('requires a raw expression for custom recurrence', () => {
+ expect(recurrenceRuleSchema.safeParse({ frequency: 'custom' }).success).toBe(false);
+ });
+
+ it('keeps interval limits aligned with the scheduler search horizon', () => {
+ expect(recurrenceRuleSchema.safeParse({ frequency: 'weekly', interval: 53, weekdays: [1], time: '02:00' }).success).toBe(false);
+ expect(recurrenceRuleSchema.safeParse({ frequency: 'monthly-date', interval: 13, dayOfMonth: 1, time: '02:00' }).success).toBe(false);
+ });
+
+ it('rejects an impossible anchor date instead of silently rebasing it', () => {
+ expect(recurrenceRuleSchema.safeParse({
+ frequency: 'weekly', interval: 2, weekdays: [1], time: '02:00', anchorDate: '2026-02-31',
+ }).success).toBe(false);
+ });
+});
diff --git a/server/routes/cosJobRoutes.js b/server/routes/cosJobRoutes.js
index 9c737ccc39..da19875a30 100644
--- a/server/routes/cosJobRoutes.js
+++ b/server/routes/cosJobRoutes.js
@@ -6,7 +6,7 @@ import { Router } from 'express';
import * as cos from '../services/cos.js';
import * as autonomousJobs from '../services/autonomousJobs.js';
import { checkJobGate, hasGate, getRegisteredGates } from '../services/jobGates.js';
-import { parseCronToNextRun } from '../services/eventScheduler.js';
+import { parseCronToNextRun, isValidRecurrence } from '../services/eventScheduler.js';
import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';
import { createCosJobSchema, updateCosJobSchema } from '../lib/validation.js';
@@ -30,6 +30,12 @@ function validateCronExpression(cronExpression) {
}
}
+function validateRecurrenceRule(rule) {
+ if (!isValidRecurrence(rule)) {
+ throw new ServerError('Invalid cron recurrence rule', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+}
+
// GET /api/cos/jobs - Get all autonomous jobs
router.get('/jobs', asyncHandler(async (req, res) => {
const jobs = await autonomousJobs.getAllJobs();
@@ -90,7 +96,7 @@ router.get('/jobs/:id', asyncHandler(async (req, res) => {
router.post('/jobs', asyncHandler(async (req, res) => {
const parsedJob = createCosJobSchema.safeParse(req.body);
if (!parsedJob.success) failValidation(parsedJob);
- const { name, description, category, type, interval, intervalMs, scheduledTime, cronExpression, enabled, priority, autonomyLevel, promptTemplate, command, triggerAction, appId, taskMetadata, providerId, model, effort } = parsedJob.data;
+ const { name, description, category, type, interval, intervalMs, scheduledTime, cronExpression, cronSchedule, enabled, priority, autonomyLevel, promptTemplate, command, triggerAction, appId, taskMetadata, providerId, model, effort } = parsedJob.data;
if (type === 'shell' && !command?.trim()) {
throw new ServerError('command is required for shell jobs', { status: 400, code: 'VALIDATION_ERROR' });
@@ -103,9 +109,10 @@ router.post('/jobs', asyncHandler(async (req, res) => {
if (cronExpression) {
validateCronExpression(cronExpression);
}
+ if (cronSchedule) validateRecurrenceRule(cronSchedule);
const job = await autonomousJobs.createJob({
- name, description, category, type, interval, intervalMs, scheduledTime, cronExpression,
+ name, description, category, type, interval, intervalMs, scheduledTime, cronExpression, cronSchedule,
enabled, priority, autonomyLevel, promptTemplate, command, triggerAction, appId, taskMetadata, providerId, model, effort
});
res.json({ success: true, job });
@@ -115,13 +122,14 @@ router.post('/jobs', asyncHandler(async (req, res) => {
router.put('/jobs/:id', asyncHandler(async (req, res) => {
const parsedJobUpdate = updateCosJobSchema.safeParse(req.body);
if (!parsedJobUpdate.success) failValidation(parsedJobUpdate);
- const { name, description, category, type, interval, intervalMs, scheduledTime, cronExpression,
+ const { name, description, category, type, interval, intervalMs, scheduledTime, cronExpression, cronSchedule,
enabled, priority, autonomyLevel, promptTemplate, command, triggerAction, weekdaysOnly, appId, taskMetadata, providerId, model, effort } = parsedJobUpdate.data;
if (cronExpression) {
validateCronExpression(cronExpression);
}
+ if (cronSchedule) validateRecurrenceRule(cronSchedule);
const job = await autonomousJobs.updateJob(req.params.id, {
- name, description, category, type, interval, intervalMs, scheduledTime, cronExpression,
+ name, description, category, type, interval, intervalMs, scheduledTime, cronExpression, cronSchedule,
enabled, priority, autonomyLevel, promptTemplate, command, triggerAction, weekdaysOnly, appId, taskMetadata, providerId, model, effort
});
if (!job) {
diff --git a/server/routes/cosJobRoutes.test.js b/server/routes/cosJobRoutes.test.js
index c67077e806..1c0717253f 100644
--- a/server/routes/cosJobRoutes.test.js
+++ b/server/routes/cosJobRoutes.test.js
@@ -33,7 +33,8 @@ vi.mock('../services/jobGates.js', () => ({
}));
vi.mock('../services/eventScheduler.js', () => ({
- parseCronToNextRun: vi.fn()
+ parseCronToNextRun: vi.fn(),
+ isValidRecurrence: vi.fn(() => true),
}));
import * as cos from '../services/cos.js';
@@ -199,6 +200,19 @@ describe('CoS Job Routes', () => {
expect(response.status).toBe(200);
});
+ it('accepts and forwards an anchored calendar recurrence', async () => {
+ parseCronToNextRun.mockReturnValue(new Date());
+ autonomousJobs.createJob.mockResolvedValue({ id: 'j1' });
+
+ const cronSchedule = { frequency: 'weekly', interval: 2, weekdays: [1], time: '02:00', anchorDate: '2026-08-31' };
+ const response = await request(app)
+ .post('/api/cos/jobs')
+ .send({ name: 'Biweekly Job', promptTemplate: 'test', cronExpression: '0 2 * * 1', cronSchedule });
+
+ expect(response.status).toBe(200);
+ expect(autonomousJobs.createJob).toHaveBeenCalledWith(expect.objectContaining({ cronSchedule }));
+ });
+
it('should return 400 for invalid cron expression format', async () => {
const response = await request(app)
.post('/api/cos/jobs')
diff --git a/server/routes/creativeCommissions.test.js b/server/routes/creativeCommissions.test.js
index 95c2da351d..da6907f89a 100644
--- a/server/routes/creativeCommissions.test.js
+++ b/server/routes/creativeCommissions.test.js
@@ -65,6 +65,18 @@ describe('POST /api/creative-commission', () => {
}));
});
+ it('accepts an anchored calendar recurrence schedule', async () => {
+ svc.createCommission.mockResolvedValue({ id: 'commission-2', name: 'Biweekly Surreal' });
+ const recurrence = { frequency: 'weekly', interval: 2, weekdays: [1], time: '02:00', anchorDate: '2026-08-31' };
+ const res = await request(buildApp()).post('/api/creative-commission').send({
+ ...validBody(), schedule: { kind: 'RECURRENCE', recurrence },
+ });
+ expect(res.status).toBe(201);
+ expect(svc.createCommission).toHaveBeenCalledWith(expect.objectContaining({
+ schedule: expect.objectContaining({ kind: 'RECURRENCE', recurrence }),
+ }));
+ });
+
it('rejects a body missing the brief with 400 (service not called)', async () => {
const res = await request(buildApp()).post('/api/creative-commission').send({ name: 'x', schedule: { kind: 'DAILY', atLocalTime: '02:00' } });
expect(res.status).toBe(400);
diff --git a/server/services/autonomousJobs/crud.js b/server/services/autonomousJobs/crud.js
index 57890bc3ab..e3890f4626 100644
--- a/server/services/autonomousJobs/crud.js
+++ b/server/services/autonomousJobs/crud.js
@@ -89,6 +89,7 @@ async function createJob(jobData) {
// do isolated work and open a PR like the built-in task types.
taskMetadata: jobData.taskMetadata || null,
cronExpression: jobData.cronExpression || null,
+ cronSchedule: jobData.cronSchedule || null,
type: jobType,
interval: jobData.interval || 'weekly',
intervalMs: resolveIntervalMs(jobData.interval || 'weekly', jobData.intervalMs),
@@ -150,7 +151,7 @@ async function updateJob(jobId, updates) {
const updatableFields = [
'name', 'description', 'category', 'type', 'interval', 'intervalMs',
- 'scheduledTime', 'cronExpression', 'weekdaysOnly', 'enabled', 'priority', 'autonomyLevel', 'promptTemplate',
+ 'scheduledTime', 'cronExpression', 'cronSchedule', 'weekdaysOnly', 'enabled', 'priority', 'autonomyLevel', 'promptTemplate',
'command', 'triggerAction', 'config', 'appId', 'taskMetadata', 'providerId', 'model', 'effort'
]
diff --git a/server/services/autonomousJobs/scheduler.js b/server/services/autonomousJobs/scheduler.js
index a714bec12f..a3f792a2a8 100644
--- a/server/services/autonomousJobs/scheduler.js
+++ b/server/services/autonomousJobs/scheduler.js
@@ -7,7 +7,7 @@
*/
import { getUserTimezone, getLocalParts, nextLocalTime } from '../../lib/timezone.js'
-import { parseCronToNextRun } from '../eventScheduler.js'
+import { parseCronToNextRun, parseRecurrenceToNextRun } from '../eventScheduler.js'
import { DAY } from './constants.js'
import { loadJobs } from './store.js'
@@ -40,9 +40,11 @@ async function getDueJobs() {
for (const job of enabledJobs) {
// Cron-mode jobs: compute next run from cron expression
- if (job.cronExpression) {
+ if (job.cronSchedule || job.cronExpression) {
const from = job.lastRun ? new Date(job.lastRun) : new Date(now)
- const next = parseCronToNextRun(job.cronExpression, from, timezone)
+ const next = job.cronSchedule
+ ? parseRecurrenceToNextRun(job.cronSchedule, from, timezone)
+ : parseCronToNextRun(job.cronExpression, from, timezone)
if (!next || next.getTime() > now) continue
due.push({
@@ -111,10 +113,12 @@ async function getNextDueJob() {
for (const job of enabledJobs) {
let nextDue
- if (job.cronExpression) {
+ if (job.cronSchedule || job.cronExpression) {
// Cron-mode: derive next due from cron expression
const from = job.lastRun ? new Date(job.lastRun) : new Date()
- const next = parseCronToNextRun(job.cronExpression, from, timezone)
+ const next = job.cronSchedule
+ ? parseRecurrenceToNextRun(job.cronSchedule, from, timezone)
+ : parseCronToNextRun(job.cronExpression, from, timezone)
if (!next) continue
nextDue = next.getTime()
} else {
diff --git a/server/services/cosJobScheduler.js b/server/services/cosJobScheduler.js
index bd8b25265b..3fe49effb2 100644
--- a/server/services/cosJobScheduler.js
+++ b/server/services/cosJobScheduler.js
@@ -21,7 +21,7 @@
* (job:spawned/job:spawn-failed → clearSpawningJob + re-register) back to these.
*/
-import { schedule as scheduleEvent, cancel as cancelEvent, parseCronToNextRun } from './eventScheduler.js';
+import { schedule as scheduleEvent, cancel as cancelEvent, parseCronToNextRun, parseRecurrenceToNextRun } from './eventScheduler.js';
import { getUserTimezone, getLocalParts, nextLocalTime } from '../lib/timezone.js';
import { formatDuration } from '../lib/fileUtils.js';
import { loadState, isDaemonRunning, canQueueImprovementTasks } from './cosState.js';
@@ -52,6 +52,14 @@ function computeNextJobFireTime(job, timezone) {
// which correctly computes lastRun + intervalMs without scheduling them every day.
// e.g. { interval: 'daily', scheduledTime: '04:30' } → '30 4 * * *'
let cronExpr = job.cronExpression;
+ if (job.cronSchedule) {
+ const from = job.lastRun ? new Date(job.lastRun) : new Date();
+ const next = parseRecurrenceToNextRun(job.cronSchedule, from, timezone);
+ if (!next) {
+ throw new Error(`Invalid calendar recurrence for autonomous job${job.id ? ` "${job.id}"` : ''}`);
+ }
+ return next.getTime();
+ }
const isDailyCronCandidate = job.interval === 'daily' || job.weekdaysOnly;
if (!cronExpr && job.scheduledTime && isDailyCronCandidate) {
const match = String(job.scheduledTime).match(/^([01]\d|2[0-3]):([0-5]\d)$/);
diff --git a/server/services/creativeCommissions/directive.js b/server/services/creativeCommissions/directive.js
index 3f74e44968..d73741610e 100644
--- a/server/services/creativeCommissions/directive.js
+++ b/server/services/creativeCommissions/directive.js
@@ -48,6 +48,52 @@ export const MAX_DIRECTIVE_GOAL_LEN = COMMISSION_INTENT_MAX
const clamp = (s, max) => (s.length > max ? `${s.slice(0, Math.max(0, max - 1))}…` : s);
const clampNote = (note) => clamp(note, MAX_DIGEST_NOTE_LEN);
+const MONTHLY_DAY_RANGES = Object.freeze({
+ first: '1-7',
+ second: '8-14',
+ third: '15-21',
+ fourth: '22-28',
+});
+
+/** Return the rich calendar rule carried by a commission, when present. */
+export function commissionToRecurrence(schedule) {
+ if (!schedule || typeof schedule !== 'object') return null;
+ if (schedule.kind === 'RECURRENCE') return schedule.recurrence || null;
+ return null;
+}
+
+function recurrenceToCron(rule) {
+ if (!rule || typeof rule !== 'object') return null;
+ if (rule.frequency === 'custom') return typeof rule.cron === 'string' && rule.cron.trim() ? rule.cron.trim() : null;
+ const match = typeof rule.time === 'string' ? rule.time.match(/^([01]\d|2[0-3]):([0-5]\d)$/) : null;
+ if (!match) return null;
+ const prefix = `${Number(match[2])} ${Number(match[1])}`;
+ const interval = Math.max(1, Number(rule.interval) || 1);
+ if (rule.frequency === 'daily') {
+ const weekdays = Array.isArray(rule.weekdays)
+ ? [...new Set(rule.weekdays)].filter(day => Number.isInteger(day) && day >= 0 && day <= 6).sort((a, b) => a - b)
+ : [];
+ if (weekdays.length && interval > 1) return null;
+ return `${prefix} ${interval > 1 ? `*/${interval}` : '*'} * ${weekdays.length ? weekdays.join(',') : '*'}`;
+ }
+ if (rule.frequency === 'weekly') {
+ const weekdays = Array.isArray(rule.weekdays) ? [...new Set(rule.weekdays)].sort((a, b) => a - b) : [];
+ return `${prefix} * * ${weekdays.length ? weekdays.join(',') : '*'}`;
+ }
+ if (rule.frequency === 'monthly-date') {
+ const day = Number(rule.dayOfMonth);
+ return Number.isInteger(day) && day >= 1 && day <= 31 ? `${prefix} ${day} * *` : null;
+ }
+ if (rule.frequency === 'monthly-weekday') {
+ const range = MONTHLY_DAY_RANGES[rule.ordinal];
+ const weekday = Number(rule.weekday);
+ return range && Number.isInteger(weekday) && weekday >= 0 && weekday <= 6
+ ? `${prefix} ${range} * ${weekday}`
+ : null;
+ }
+ return null;
+}
+
/**
* Compose a 5-field cron (`minute hour dayOfMonth month dayOfWeek`) from a
* commission schedule. Returns the raw string, or null when the schedule is
@@ -58,6 +104,8 @@ export function commissionToCron(schedule) {
if (!schedule || typeof schedule !== 'object') return null;
const { kind, atLocalTime, weekday, weekdaysOnly, cron } = schedule;
+ if (kind === 'RECURRENCE') return recurrenceToCron(schedule.recurrence);
+
if (kind === 'CUSTOM') {
return typeof cron === 'string' && cron.trim() ? cron.trim() : null;
}
diff --git a/server/services/creativeCommissions/directive.test.js b/server/services/creativeCommissions/directive.test.js
index d01ca4d1e8..a2f567aa1a 100644
--- a/server/services/creativeCommissions/directive.test.js
+++ b/server/services/creativeCommissions/directive.test.js
@@ -1,6 +1,6 @@
import { describe, it, expect } from 'vitest';
import {
- commissionToCron, renderFeedbackDigest, composeDirectiveGoal,
+ commissionToCron, commissionToRecurrence, renderFeedbackDigest, composeDirectiveGoal,
MAX_DIRECTIVE_GOAL_LEN, MAX_SYSTEM_PREFIX_LEN,
} from './directive.js';
import { CREATIVE_DIRECTOR_GOAL_MAX } from '../../lib/creativeDirectorValidation.js';
@@ -63,6 +63,20 @@ describe('commissionToCron', () => {
expect(commissionToCron({ kind: 'CUSTOM', cron: ' */15 * * * * ' })).toBe('*/15 * * * *');
});
+ it('keeps rich calendar recurrence separate from its compatibility cron', () => {
+ const recurrence = { frequency: 'weekly', interval: 2, weekdays: [1], time: '02:00', anchorDate: '2026-08-31' };
+ const schedule = { kind: 'RECURRENCE', recurrence };
+ expect(commissionToRecurrence(schedule)).toEqual(recurrence);
+ expect(commissionToCron(schedule)).toBe('0 2 * * 1');
+ });
+
+ it('keeps weekday restrictions in the daily compatibility preview', () => {
+ expect(commissionToCron({
+ kind: 'RECURRENCE',
+ recurrence: { frequency: 'daily', interval: 1, weekdays: [1, 3], time: '09:00' },
+ })).toBe('0 9 * * 1,3');
+ });
+
it('returns null when required fields are missing', () => {
expect(commissionToCron(null)).toBeNull();
expect(commissionToCron({ kind: 'DAILY' })).toBeNull();
diff --git a/server/services/creativeCommissions/scheduler.js b/server/services/creativeCommissions/scheduler.js
index e705cb7a13..7f9b522b11 100644
--- a/server/services/creativeCommissions/scheduler.js
+++ b/server/services/creativeCommissions/scheduler.js
@@ -22,14 +22,14 @@
* `syncCommissionSchedules` after a mutation), not on settings:updated.
*/
-import { schedule, cancel, isValidCron } from '../eventScheduler.js';
+import { schedule, cancel, isValidCron, isValidRecurrence } from '../eventScheduler.js';
import { getUserTimezone } from '../../lib/timezone.js';
import { getSettings, settingsEvents } from '../settings.js';
import { RENDER_TARGET } from '../../lib/renderTargets.js';
import { renderTargetDefaults } from '../imageGen/cloudProviderConfig.js';
import { resolveVideoMode, VIDEO_GEN_MODE } from '../videoGen/modes.js';
import { listCommissions, getCommission, recordCommissionRun, commissionEvents } from './store.js';
-import { commissionToCron } from './directive.js';
+import { commissionToCron, commissionToRecurrence } from './directive.js';
import { buildCommissionDirective, getAbilityAdapter } from './abilityAdapters.js';
import { buildMusicTasteRecipe } from './musicTasteRecipe.js';
import { surfaceCommissionRun } from './surface.js';
@@ -67,6 +67,12 @@ export function activeCommissions(commissions) {
const out = [];
for (const c of commissions || []) {
if (!c || c.enabled === false || !c.id) continue;
+ const recurrence = commissionToRecurrence(c.schedule);
+ if (recurrence) {
+ if (!isValidRecurrence(recurrence)) continue;
+ out.push({ id: c.id, recurrence, timezone: c.schedule?.timezone || null });
+ continue;
+ }
const cron = commissionToCron(c.schedule);
if (!cron || !isValidCron(cron)) continue;
out.push({ id: c.id, cron, timezone: c.schedule?.timezone || null });
@@ -77,7 +83,7 @@ export function activeCommissions(commissions) {
function signatureOf(active, fallbackTz) {
return JSON.stringify({
tz: fallbackTz || null,
- s: active.map((e) => [e.id, e.cron, e.timezone]),
+ s: active.map((e) => [e.id, e.cron || null, e.recurrence || null, e.timezone]),
});
}
@@ -88,8 +94,9 @@ function registerSchedule(entry, timezone) {
try {
schedule({
id: eventId(entry.id),
- type: 'cron',
+ type: entry.recurrence ? 'recurrence' : 'cron',
cron: entry.cron,
+ recurrence: entry.recurrence,
timezone: entry.timezone || timezone,
handler: () => runScheduledCommission(entry.id),
metadata: { source: 'creativeCommissionScheduler', commissionId: entry.id },
@@ -155,8 +162,9 @@ export async function runScheduledCommission(commissionId) {
const commission = await getCommission(commissionId).catch(() => null);
if (!commission || commission.enabled === false) return;
+ const recurrence = commissionToRecurrence(commission.schedule);
const cron = commissionToCron(commission.schedule);
- if (!cron || !isValidCron(cron)) return; // schedule became invalid since registration
+ if (recurrence ? !isValidRecurrence(recurrence) : (!cron || !isValidCron(cron))) return; // schedule became invalid since registration
await fireCommission(commission, 'schedule');
}
diff --git a/server/services/creativeCommissions/scheduler.test.js b/server/services/creativeCommissions/scheduler.test.js
index c706979216..aedf3afb4c 100644
--- a/server/services/creativeCommissions/scheduler.test.js
+++ b/server/services/creativeCommissions/scheduler.test.js
@@ -8,6 +8,7 @@ vi.mock('../eventScheduler.js', () => ({
schedule: (...a) => scheduleMock(...a),
cancel: (...a) => cancelMock(...a),
isValidCron: (expr) => typeof expr === 'string' && expr.trim().split(/\s+/).length === 5,
+ isValidRecurrence: (rule) => rule?.frequency === 'weekly' && Array.isArray(rule.weekdays) && rule.weekdays.length > 0,
}));
vi.mock('../../lib/timezone.js', () => ({ getUserTimezone: async () => 'UTC' }));
@@ -134,6 +135,13 @@ describe('activeCommissions', () => {
]);
expect(active.map((e) => e.id)).toEqual(['c']);
});
+
+ it('keeps rich recurrence for the event scheduler instead of flattening intervals', () => {
+ const recurrence = { frequency: 'weekly', interval: 2, weekdays: [1], time: '02:00', anchorDate: '2026-08-31' };
+ expect(activeCommissions([videoCommission({ schedule: { kind: 'RECURRENCE', recurrence } })])).toEqual([{
+ id: 'commission-1', recurrence, timezone: null,
+ }]);
+ });
});
describe('startCommissionScheduler (no cold-boot generation)', () => {
@@ -150,6 +158,15 @@ describe('startCommissionScheduler (no cold-boot generation)', () => {
expect(advanceMock).not.toHaveBeenCalled();
});
+ it('registers rich recurrence as a recurrence event', async () => {
+ const recurrence = { frequency: 'weekly', interval: 2, weekdays: [1], time: '02:00', anchorDate: '2026-08-31' };
+ listCommissionsMock.mockResolvedValue([videoCommission({ schedule: { kind: 'RECURRENCE', recurrence } })]);
+ await startCommissionScheduler();
+ expect(scheduleMock).toHaveBeenCalledWith(expect.objectContaining({
+ id: 'creative-commission-commission-1', type: 'recurrence', recurrence,
+ }));
+ });
+
it('cancels crons whose commission was removed on the next sync', async () => {
listCommissionsMock.mockResolvedValueOnce([videoCommission()]);
await syncCommissionSchedules();
diff --git a/server/services/creativeCommissions/store.js b/server/services/creativeCommissions/store.js
index d5691ec499..7b7a74e479 100644
--- a/server/services/creativeCommissions/store.js
+++ b/server/services/creativeCommissions/store.js
@@ -58,7 +58,7 @@ import { PATHS } from '../../lib/fileUtils.js';
import { createCollectionStore } from '../../lib/collectionStore.js';
import { createPgFileFacade, resolvePgBackend, isFileBackend } from '../../lib/pgFileFacade.js';
import { createRecordWriteQueue } from '../../lib/fileWriteQueue.js';
-import { isValidCron } from '../eventScheduler.js';
+import { isValidCron, isValidRecurrence } from '../eventScheduler.js';
import { compareNewerWins } from '../../lib/lwwTimestamp.js';
import {
contentHashForRecord,
@@ -264,6 +264,9 @@ export function sanitizeCommission(raw) {
weekday: Number.isInteger(schedule.weekday) ? schedule.weekday : null,
weekdaysOnly: schedule.weekdaysOnly === true,
cron: isStr(schedule.cron) ? schedule.cron : null,
+ recurrence: schedule.recurrence && typeof schedule.recurrence === 'object'
+ ? { ...schedule.recurrence, weekdays: Array.isArray(schedule.recurrence.weekdays) ? schedule.recurrence.weekdays : [] }
+ : null,
timezone: isStr(schedule.timezone) ? schedule.timezone : null,
},
// Per-ability generation (#2769): a known type's adapter fills its defaults
@@ -516,6 +519,13 @@ export function _resetCommissionStore() {
* schema — so validation.js stays a leaf free of the eventScheduler import.
*/
export function assertValidSchedule(schedule) {
+ const recurrence = schedule?.kind === 'RECURRENCE' ? schedule.recurrence : null;
+ if (recurrence) {
+ if (!isValidRecurrence(recurrence)) {
+ throw makeErr('Invalid schedule: could not derive a valid recurrence', ERR_VALIDATION);
+ }
+ return recurrence;
+ }
const cron = commissionToCron(schedule);
if (!cron || !isValidCron(cron)) {
throw makeErr('Invalid schedule: could not derive a valid cron expression', ERR_VALIDATION);
diff --git a/server/services/creativeCommissions/store.test.js b/server/services/creativeCommissions/store.test.js
index c5d76bc1e1..15baecb53e 100644
--- a/server/services/creativeCommissions/store.test.js
+++ b/server/services/creativeCommissions/store.test.js
@@ -204,6 +204,11 @@ describe('assertValidSchedule', () => {
try { assertValidSchedule({ kind: 'CUSTOM', cron: 'not a cron' }); }
catch (e) { expect(e.code).toBe(ERR_VALIDATION); }
});
+
+ it('accepts an anchored calendar recurrence', () => {
+ const recurrence = { frequency: 'weekly', interval: 2, weekdays: [1], time: '02:00', anchorDate: '2026-08-31' };
+ expect(assertValidSchedule({ kind: 'RECURRENCE', recurrence })).toEqual(recurrence);
+ });
});
describe('createCommission', () => {
diff --git a/server/services/eventScheduler.js b/server/services/eventScheduler.js
index 2915e354b2..498e36799b 100644
--- a/server/services/eventScheduler.js
+++ b/server/services/eventScheduler.js
@@ -7,6 +7,7 @@
import { cosEvents } from './cosEvents.js'
import { getLocalParts } from '../lib/timezone.js'
+import { recurrenceRuleSchema } from '../lib/recurrenceValidation.js'
// Maximum safe setTimeout value (2^31 - 1 ms, ~24.8 days)
const MAX_TIMEOUT = 2147483647
@@ -164,6 +165,96 @@ function parseCronToPrevRun(cronExpr, from = new Date(), timezone = 'UTC') {
return walkCron(cronExpr, from, timezone, { stepMs: -60 * 1000 })
}
+const RECURRENCE_MINUTE = 60 * 1000
+const RECURRENCE_DAY = 24 * 60 * 60 * 1000
+
+function localDaySerial(parts) {
+ return Date.UTC(parts.year, parts.month - 1, parts.day) / RECURRENCE_DAY
+}
+
+function parseAnchorDate(value) {
+ if (typeof value !== 'string') return null
+ const match = value.match(/^(\d{4})-(\d{2})-(\d{2})$/)
+ if (!match) return null
+ const year = Number(match[1]); const month = Number(match[2]); const day = Number(match[3])
+ const date = new Date(Date.UTC(year, month - 1, day))
+ if (date.getUTCFullYear() !== year || date.getUTCMonth() + 1 !== month || date.getUTCDate() !== day) return null
+ return { year, month, day, serial: date.getTime() / RECURRENCE_DAY, dayOfWeek: date.getUTCDay() }
+}
+
+function daysInMonth(year, month) {
+ return new Date(Date.UTC(year, month, 0)).getUTCDate()
+}
+
+function recurrenceMatches(parts, rule, anchor) {
+ const [hour, minute] = rule.time.split(':').map(Number)
+ if (parts.hour !== hour || parts.minute !== minute) return false
+
+ const serial = localDaySerial(parts)
+ if (serial < anchor.serial) return false
+
+ if (rule.frequency === 'daily') {
+ const days = Math.floor(serial - anchor.serial)
+ return days % rule.interval === 0 && (!rule.weekdays.length || rule.weekdays.includes(parts.dayOfWeek))
+ }
+
+ if (rule.frequency === 'weekly') {
+ const currentWeek = serial - parts.dayOfWeek
+ const anchorWeek = anchor.serial - anchor.dayOfWeek
+ const weeks = Math.floor((currentWeek - anchorWeek) / 7)
+ return weeks >= 0 && weeks % rule.interval === 0 && rule.weekdays.includes(parts.dayOfWeek)
+ }
+
+ const months = (parts.year - anchor.year) * 12 + parts.month - anchor.month
+ if (months < 0 || months % rule.interval !== 0) return false
+
+ if (rule.frequency === 'monthly-date') return parts.day === rule.dayOfMonth
+ if (rule.frequency === 'monthly-weekday') {
+ if (parts.dayOfWeek !== rule.weekday) return false
+ if (rule.ordinal === 'last') return parts.day + 7 > daysInMonth(parts.year, parts.month)
+ const ordinal = Math.floor((parts.day - 1) / 7) + 1
+ return ordinal === ({ first: 1, second: 2, third: 3, fourth: 4 }[rule.ordinal] || 0)
+ }
+ return false
+}
+
+/**
+ * Find the next local-calendar occurrence for an anchored recurrence rule.
+ * Unlike cron, the interval is measured from the persisted local anchor, so
+ * every two weeks remains every two weeks across month boundaries and DST.
+ */
+function parseRecurrenceToNextRun(rule, from = new Date(), timezone = 'UTC', until = null) {
+ const parsed = recurrenceRuleSchema.safeParse(rule)
+ if (!parsed.success) return null
+ const normalized = parsed.data
+ if (normalized.frequency === 'custom') return parseCronToNextRun(normalized.cron, from, timezone, until)
+
+ const reference = getLocalParts(from, timezone)
+ const parsedAnchor = parseAnchorDate(normalized.anchorDate)
+ if (normalized.anchorDate && !parsedAnchor) return null
+ const anchor = parsedAnchor || {
+ year: reference.year,
+ month: reference.month,
+ day: reference.day,
+ serial: localDaySerial(reference),
+ dayOfWeek: reference.dayOfWeek,
+ }
+ const cursor = new Date(from)
+ cursor.setSeconds(0, 0)
+ cursor.setMinutes(cursor.getMinutes() + 1)
+ const boundary = new Date(from)
+ boundary.setFullYear(boundary.getFullYear() + 2)
+ const maxDate = until instanceof Date && until < boundary ? until : boundary
+ let iterations = 0
+ while (cursor < maxDate) {
+ if (++iterations > MAX_CRON_ITERATIONS) return null
+ const parts = getLocalParts(cursor, timezone)
+ if (recurrenceMatches(parts, normalized, anchor)) return cursor
+ cursor.setTime(cursor.getTime() + RECURRENCE_MINUTE)
+ }
+ return null
+}
+
/**
* Check if a value matches a cron field expression
* @param {number} value - Current value
@@ -246,6 +337,7 @@ function createSafeTimer(callback, delayMs, eventId) {
* @param {string} config.id - Unique event identifier
* @param {string} config.type - Event type (cron, interval, once)
* @param {string} config.cron - Cron expression (for type: cron)
+ * @param {Object} config.recurrence - Anchored calendar rule (for type: recurrence)
* @param {number} config.intervalMs - Interval in ms (for type: interval)
* @param {number} config.delayMs - Delay in ms (for type: once)
* @param {Function} config.handler - Event handler function
@@ -253,7 +345,7 @@ function createSafeTimer(callback, delayMs, eventId) {
* @returns {Object} - Scheduled event
*/
function schedule(config) {
- const { id, type, cron, timezone, intervalMs, delayMs, handler, metadata = {} } = config
+ const { id, type, cron, recurrence, timezone, intervalMs, delayMs, handler, metadata = {} } = config
if (!id || !type || !handler) {
throw new Error('Event requires id, type, and handler')
@@ -268,6 +360,7 @@ function schedule(config) {
id,
type,
cron,
+ recurrence,
timezone: timezone || 'UTC',
intervalMs,
delayMs,
@@ -287,6 +380,11 @@ function schedule(config) {
event.nextRunAt = parseCronToNextRun(cron, new Date(), event.timezone)?.getTime() || null
break
+ case 'recurrence':
+ if (!recurrence) throw new Error('Recurrence type requires recurrence rule')
+ event.nextRunAt = parseRecurrenceToNextRun(recurrence, new Date(), event.timezone)?.getTime() || null
+ break
+
case 'interval':
if (!intervalMs) throw new Error('Interval type requires intervalMs')
event.nextRunAt = Date.now() + intervalMs
@@ -397,6 +495,11 @@ function updateNextRunTime(event) {
event.nextRunAt = nextDate?.getTime() || null
break
+ case 'recurrence':
+ const nextRecurrence = parseRecurrenceToNextRun(event.recurrence, new Date(), event.timezone || 'UTC')
+ event.nextRunAt = nextRecurrence?.getTime() || null
+ break
+
case 'interval':
event.nextRunAt = Date.now() + event.intervalMs
break
@@ -478,6 +581,8 @@ function getScheduledEvents() {
id: e.id,
type: e.type,
active: e.active,
+ cron: e.cron,
+ recurrence: e.recurrence,
nextRunAt: e.nextRunAt,
lastRunAt: e.lastRunAt,
runCount: e.runCount,
@@ -499,6 +604,7 @@ function getEvent(id) {
type: event.type,
active: event.active,
cron: event.cron,
+ recurrence: event.recurrence,
intervalMs: event.intervalMs,
nextRunAt: event.nextRunAt,
lastRunAt: event.lastRunAt,
@@ -597,6 +703,16 @@ function isValidCron(expr) {
}
}
+/** Non-throwing predicate for the richer calendar recurrence path. */
+function isValidRecurrence(rule) {
+ if (!recurrenceRuleSchema.safeParse(rule).success) return false
+ try {
+ return Boolean(parseRecurrenceToNextRun(rule))
+ } catch {
+ return false
+ }
+}
+
export {
schedule,
cancel,
@@ -610,6 +726,8 @@ export {
triggerNow,
parseCronToNextRun,
parseCronToPrevRun,
+ parseRecurrenceToNextRun,
isValidCron,
+ isValidRecurrence,
MAX_TIMEOUT
}
diff --git a/server/services/eventScheduler.test.js b/server/services/eventScheduler.test.js
index 0482b60302..37c1107546 100644
--- a/server/services/eventScheduler.test.js
+++ b/server/services/eventScheduler.test.js
@@ -12,7 +12,9 @@ import {
triggerNow,
parseCronToNextRun,
parseCronToPrevRun,
- isValidCron
+ isValidCron,
+ parseRecurrenceToNextRun,
+ isValidRecurrence,
} from './eventScheduler.js';
// eventScheduler.js's "UTC" branch (the default, and what every consumer below
@@ -146,6 +148,40 @@ describe('parseCronToNextRun', () => {
});
});
+// =============================================================================
+// calendar recurrence scheduling
+// =============================================================================
+
+describe('parseRecurrenceToNextRun', () => {
+ it('keeps every-two-weeks cadence anchored across a month boundary', () => {
+ const next = parseRecurrenceToNextRun({
+ frequency: 'weekly', interval: 2, weekdays: [1], time: '02:00', anchorDate: '2024-01-01',
+ }, new Date('2024-01-01T03:00:00.000Z'));
+ expect(next.toISOString()).toBe('2024-01-15T02:00:00.000Z');
+ });
+
+ it('finds the first Thursday of the month', () => {
+ const next = parseRecurrenceToNextRun({
+ frequency: 'monthly-weekday', ordinal: 'first', weekday: 4, time: '19:00',
+ }, FIXED_NOW);
+ expect(next.toISOString()).toBe('2024-01-04T19:00:00.000Z');
+ });
+
+ it('finds the last Thursday of the month', () => {
+ const next = parseRecurrenceToNextRun({
+ frequency: 'monthly-weekday', ordinal: 'last', weekday: 4, time: '19:00',
+ }, FIXED_NOW);
+ expect(next.toISOString()).toBe('2024-01-25T19:00:00.000Z');
+ });
+
+ it('validates both rich recurrence rules and custom cron rules', () => {
+ expect(isValidRecurrence({ frequency: 'weekly', interval: 2, weekdays: [1], time: '02:00', anchorDate: '2024-01-01' })).toBe(true);
+ expect(isValidRecurrence({ frequency: 'custom', cron: '*/15 * * * *' })).toBe(true);
+ expect(isValidRecurrence({ frequency: 'custom', cron: 'not a cron' })).toBe(false);
+ expect(isValidRecurrence({ frequency: 'weekly', weekdays: [], time: '02:00' })).toBe(false);
+ });
+});
+
// =============================================================================
// parseCronToPrevRun
// =============================================================================
@@ -264,6 +300,21 @@ describe('schedule() lifecycle with fake timers', () => {
expect(handler).toHaveBeenCalledTimes(1);
});
+ it('fires an anchored recurrence event and re-arms its next occurrence', async () => {
+ const handler = vi.fn();
+ schedule({
+ id: 'recurrence-1',
+ type: 'recurrence',
+ recurrence: { frequency: 'weekly', interval: 2, weekdays: [1], time: '00:05', anchorDate: '2024-01-01' },
+ handler,
+ });
+
+ expect(getEvent('recurrence-1').nextRunAt).toBe(new Date('2024-01-01T00:05:00.000Z').getTime());
+ await vi.advanceTimersByTimeAsync(5 * 60 * 1000);
+ expect(handler).toHaveBeenCalledTimes(1);
+ expect(getEvent('recurrence-1').nextRunAt).toBe(new Date('2024-01-15T00:05:00.000Z').getTime());
+ });
+
it('cancel() removes the event and its pending timer stops firing', async () => {
const handler = vi.fn();
schedule({ id: 'cancel-1', type: 'once', delayMs: 1000, handler });