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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: harden recurrence scheduling paths
[._.]/ Adam Eivy7b1bcf0f6de6
diff --git a/client/src/components/cos/tabs/workflow/ScheduleEditor.jsx b/client/src/components/cos/tabs/workflow/ScheduleEditor.jsxindex 126b1a38e8..26ba15e04e 100644--- a/client/src/components/cos/tabs/workflow/ScheduleEditor.jsx+++ b/client/src/components/cos/tabs/workflow/ScheduleEditor.jsx@@ -83,7 +83,8 @@ export default function ScheduleEditor({ node, allNodes, timezone, onClose, onSaconst validateCron = (value) => String(value || '').trim().split(/\s+/).length === 5;const handleSave = async () => {- if (form.mode === 'cron' && !form.cronSchedule && !validateCron(form.cronExpression)) {+ const hasValidJobRecurrence = node.kind === 'job' && form.cronSchedule;+ if (form.mode === 'cron' && !hasValidJobRecurrence && !validateCron(form.cronExpression)) {toast.error('Cron schedules need five fields');return;}@@ -103,7 +104,7 @@ export default function ScheduleEditor({ node, allNodes, timezone, onClose, onSaconst payload = {enabled: form.enabled,type: form.mode,- cronExpression: form.mode === 'cron' ? form.cronExpression.trim() : null,+ cronExpression: form.mode === 'cron' ? String(form.cronExpression || '').trim() || null : null,runAfter: form.runAfter};if (form.mode === 'custom') payload.intervalMs = intervalHours * 3_600_000;@@ -116,7 +117,7 @@ export default function ScheduleEditor({ node, allNodes, timezone, onClose, onSaconst payload = {enabled: form.enabled,weekdaysOnly: form.weekdaysOnly,- cronExpression: form.mode === 'cron' ? (buildCronFromRecurrence(form.cronSchedule) || form.cronExpression.trim() || null) : null,+ cronExpression: form.mode === 'cron' ? (buildCronFromRecurrence(form.cronSchedule) || String(form.cronExpression || '').trim() || null) : null,cronSchedule: form.mode === 'cron' ? form.cronSchedule : null,scheduledTime: form.mode === 'interval' ? (form.scheduledTime || null) : null};@@ -191,15 +192,19 @@ export default function ScheduleEditor({ node, allNodes, timezone, onClose, onSa<div className="space-y-2"><span className="block text-xs text-gray-400">Run on</span><CronSchedulePicker- value={form.cronSchedule || form.cronExpression}- valueShape="recurrence"- timezone={timezone}- onChange={rule => {- set('cronSchedule', rule);- set('cronExpression', buildCronFromRecurrence(rule) || null);+ value={node.kind === 'job' ? (form.cronSchedule || form.cronExpression) : form.cronExpression}+ valueShape={node.kind === 'job' ? 'recurrence' : 'cron'}+ timezone={node.kind === 'job' ? timezone : undefined}+ onChange={value => {+ if (node.kind === 'job') {+ set('cronSchedule', value);+ set('cronExpression', buildCronFromRecurrence(value) || null);+ } else {+ set('cronExpression', value);+ }}}/>- <p className="text-[11px] text-gray-600">No days selected runs every day.</p>+ {node.kind === 'job' && <p className="text-[11px] text-gray-600">No days selected runs every day.</p>}</div>)}diff --git a/server/lib/recurrenceValidation.js b/server/lib/recurrenceValidation.jsindex cfc5658ca5..35e6eff065 100644--- a/server/lib/recurrenceValidation.js+++ b/server/lib/recurrenceValidation.js@@ -55,6 +55,9 @@ export const recurrenceRuleSchema = z.object({if (!value.time) {ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['time'], message: 'recurrence requires time' });}+ if (value.interval > 1 && !value.anchorDate) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['anchorDate'], message: 'multi-period recurrence requires anchorDate' });+ }if (value.frequency === 'weekly' && value.interval > 52) {ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['interval'], message: 'weekly recurrence supports at most 52 weeks' });}diff --git a/server/lib/recurrenceValidation.test.js b/server/lib/recurrenceValidation.test.jsindex baf60bb887..0a493b8c95 100644--- a/server/lib/recurrenceValidation.test.js+++ b/server/lib/recurrenceValidation.test.js@@ -19,6 +19,12 @@ describe('recurrenceRuleSchema', () => {expect(recurrenceRuleSchema.safeParse({ frequency: 'weekly', time: '02:00' }).success).toBe(false);});+ it('requires an anchor for multi-period calendar recurrences', () => {+ expect(recurrenceRuleSchema.safeParse({+ frequency: 'monthly-date', interval: 2, dayOfMonth: 1, time: '02:00',+ }).success).toBe(false);+ });+it('requires a raw expression for custom recurrence', () => {expect(recurrenceRuleSchema.safeParse({ frequency: 'custom' }).success).toBe(false);});diff --git a/server/services/eventScheduler.js b/server/services/eventScheduler.jsindex 498e36799b..67136712b6 100644--- a/server/services/eventScheduler.js+++ b/server/services/eventScheduler.js@@ -165,7 +165,6 @@ function parseCronToPrevRun(cronExpr, from = new Date(), timezone = 'UTC') {return walkCron(cronExpr, from, timezone, { stepMs: -60 * 1000 })}-const RECURRENCE_MINUTE = 60 * 1000const RECURRENCE_DAY = 24 * 60 * 60 * 1000function localDaySerial(parts) {@@ -186,36 +185,126 @@ 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+function localDateFromSerial(serial) {+ const date = new Date(serial * RECURRENCE_DAY)+ return {+ year: date.getUTCFullYear(),+ month: date.getUTCMonth() + 1,+ day: date.getUTCDate(),+ dayOfWeek: date.getUTCDay(),+ serial,+ }+}++function monthSerial(year, month) {+ return year * 12 + month - 1+}- const serial = localDaySerial(parts)- if (serial < anchor.serial) return false+function localMonthFromSerial(serial) {+ const year = Math.floor(serial / 12)+ return { year, month: serial - year * 12 + 1 }+}++/**+ * Resolve a local calendar date/time to its UTC instant. A short correction+ * loop handles ordinary timezone offsets and DST transitions without walking+ * every minute between `from` and the next sparse occurrence.+ */+function localDateTimeToUtc(date, time, timezone) {+ const [hour, minute] = time.split(':').map(Number)+ const targetMs = Date.UTC(date.year, date.month - 1, date.day, hour, minute)+ let candidate = new Date(targetMs)++ for (let attempt = 0; attempt < 4; attempt += 1) {+ const actual = getLocalParts(candidate, timezone)+ const actualMs = Date.UTC(actual.year, actual.month - 1, actual.day, actual.hour, actual.minute)+ const deltaMs = targetMs - actualMs+ if (deltaMs === 0) return candidate+ candidate = new Date(candidate.getTime() + deltaMs)+ }++ // A local time skipped by a DST spring-forward has no exact UTC instant.+ return null+}++function weekdayOfMonth(year, month, weekday, ordinal) {+ const lastDay = daysInMonth(year, month)+ if (ordinal === 'last') {+ const lastWeekday = new Date(Date.UTC(year, month - 1, lastDay)).getUTCDay()+ return lastDay - ((lastWeekday - weekday + 7) % 7)+ }++ const ordinalNumber = { first: 1, second: 2, third: 3, fourth: 4 }[ordinal]+ if (!ordinalNumber) return null+ const firstWeekday = new Date(Date.UTC(year, month - 1, 1)).getUTCDay()+ const day = 1 + ((weekday - firstWeekday + 7) % 7) + (ordinalNumber - 1) * 7+ return day <= lastDay ? day : null+}++function findNextRecurrenceCandidate(rule, anchor, from, timezone, maxDate) {+ const reference = getLocalParts(from, timezone)+ const referenceSerial = localDaySerial(reference)+ const maxLocalParts = getLocalParts(new Date(maxDate.getTime() - 1), timezone)+ const maxSerial = localDaySerial(maxLocalParts)+ const isUsable = date => {+ if (!date || date.serial < anchor.serial || date.serial < referenceSerial || date.serial > maxSerial) return null+ const candidate = localDateTimeToUtc(date, rule.time, timezone)+ return candidate && candidate > from && candidate < maxDate ? candidate : null+ }if (rule.frequency === 'daily') {- const days = Math.floor(serial - anchor.serial)- return days % rule.interval === 0 && (!rule.weekdays.length || rule.weekdays.includes(parts.dayOfWeek))+ const firstSerial = Math.max(anchor.serial, referenceSerial)+ const firstIndex = Math.max(0, Math.ceil((firstSerial - anchor.serial) / rule.interval))+ for (let index = firstIndex; ; index += 1) {+ const serial = anchor.serial + index * rule.interval+ if (serial > maxSerial) return null+ const date = localDateFromSerial(serial)+ if (rule.weekdays.length && !rule.weekdays.includes(date.dayOfWeek)) continue+ const candidate = isUsable(date)+ if (candidate) return candidate+ }}if (rule.frequency === 'weekly') {- const currentWeek = serial - parts.dayOfWeekconst 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 referenceWeek = referenceSerial - reference.dayOfWeek+ const firstWeek = Math.max(anchorWeek, referenceWeek)+ const firstIndex = Math.max(0, Math.ceil((firstWeek - anchorWeek) / (7 * rule.interval)))+ const weekdays = [...rule.weekdays].sort((a, b) => a - b)+ for (let index = firstIndex; ; index += 1) {+ const weekStart = anchorWeek + index * rule.interval * 7+ if (weekStart > maxSerial) return null+ for (const weekday of weekdays) {+ const date = localDateFromSerial(weekStart + weekday)+ const candidate = isUsable(date)+ if (candidate) return candidate+ }+ }}- 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)+ const anchorMonth = monthSerial(anchor.year, anchor.month)+ const referenceMonth = monthSerial(reference.year, reference.month)+ const firstMonth = Math.max(anchorMonth, referenceMonth)+ const firstIndex = Math.max(0, Math.ceil((firstMonth - anchorMonth) / rule.interval))+ const maxMonth = monthSerial(maxLocalParts.year, maxLocalParts.month)++ for (let index = firstIndex; ; index += 1) {+ const currentMonth = anchorMonth + index * rule.interval+ if (currentMonth > maxMonth) return null+ const { year, month } = localMonthFromSerial(currentMonth)+ const day = rule.frequency === 'monthly-date'+ ? (rule.dayOfMonth <= daysInMonth(year, month) ? rule.dayOfMonth : null)+ : weekdayOfMonth(year, month, rule.weekday, rule.ordinal)+ if (!day) continue+ const candidate = isUsable({+ year,+ month,+ day,+ dayOfWeek: new Date(Date.UTC(year, month - 1, day)).getUTCDay(),+ serial: Date.UTC(year, month - 1, day) / RECURRENCE_DAY,+ })+ if (candidate) return candidate}- return false}/**@@ -239,20 +328,10 @@ function parseRecurrenceToNextRun(rule, from = new Date(), timezone = 'UTC', untserial: 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+ return findNextRecurrenceCandidate(normalized, anchor, from, timezone, maxDate)}/**diff --git a/server/services/eventScheduler.test.js b/server/services/eventScheduler.test.jsindex 37c1107546..37765db2ba 100644--- a/server/services/eventScheduler.test.js+++ b/server/services/eventScheduler.test.js@@ -174,6 +174,13 @@ describe('parseRecurrenceToNextRun', () => {expect(next.toISOString()).toBe('2024-01-25T19:00:00.000Z');});+ it('jumps directly to sparse annual occurrences', () => {+ const next = parseRecurrenceToNextRun({+ frequency: 'monthly-date', interval: 12, dayOfMonth: 1, time: '00:00', anchorDate: '2024-01-01',+ }, new Date('2024-01-02T00:00:00.000Z'));+ expect(next.toISOString()).toBe('2025-01-01T00: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);