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: keep a CoS schedule alive when a run throws after the handler (#5651)
Adam Eivycea73d7933f6
diff --git a/server/services/eventScheduler.js b/server/services/eventScheduler.jsindex 6032db7302..0d5e230a3a 100644--- a/server/services/eventScheduler.js+++ b/server/services/eventScheduler.js@@ -507,7 +507,7 @@ function scheduleNextRun(event) {if (delay < 0) {// Already past - run immediately for non-recurring, or calculate next for recurringif (event.type === 'once') {- runEvent(event)+ runEventFloating(event)return}// Calculate next occurrence@@ -516,32 +516,78 @@ function scheduleNextRun(event) {return}- const timer = createSafeTimer(() => runEvent(event), delay, event.id)+ const timer = createSafeTimer(() => runEventFloating(event), delay, event.id)activeTimers.set(event.id, timer)}/**- * Run an event+ * Start a run without awaiting it, from a timer or another fire-and-forget path.+ * runEvent already swallows handler failures; this catch exists so a defect in+ * runEvent's own bookkeeping surfaces as one log line instead of an unhandled+ * rejection that can take the process down.* @param {Object} event - Event object*/-async function runEvent(event) {- const startTime = Date.now()+function runEventFloating(event) {+ runEvent(event).catch(err => {+ console.error(`❌ Event ${event.id} run failed: ${err.message}`)+ })+}- event.lastRunAt = startTime- event.runCount+++/**+ * Stop an event and drop its pending timer handle.+ * @param {Object} event - Event object+ */+function deactivate(event) {+ event.active = false+ activeTimers.delete(event.id)+}- let success = true- let error = null+/**+ * Re-arm an event after a run.+ *+ * Runs from runEvent's `finally`, so a throw anywhere earlier in the run can+ * never leave a recurring schedule un-armed but still listed as active. A next+ * run time that cannot be computed (malformed cron, recurrence past its `until`)+ * deactivates the event with one error line rather than leaving the CoS Schedule+ * tab showing an armed schedule that will never fire again.+ *+ * @param {Object} event - Event object+ */+function rearm(event) {+ if (!event.active) return++ if (event.type === 'once') {+ deactivate(event)+ return+ }try {- await event.handler(event)+ updateNextRunTime(event)} catch (err) {- success = false- error = err.message- console.error(`⚠️ Event ${event.id} failed: ${err.message}`)+ console.error(`❌ Event ${event.id} could not compute its next run (${err.message}) - schedule stopped`)+ deactivate(event)+ return}- // Record in history (push + truncate is faster than unshift + pop for large arrays)+ if (!event.nextRunAt) {+ console.error(`❌ Event ${event.id} has no next run time - schedule stopped`)+ deactivate(event)+ return+ }++ scheduleNextRun(event)+}++/**+ * Append one run to the bounded history ring.+ * @param {Object} event - Event object+ * @param {Object} result - Run outcome+ * @param {number} result.startTime - Run start timestamp+ * @param {boolean} result.success - Whether the handler completed+ * @param {string|null} result.error - Handler failure message, if any+ */+function recordEventHistory(event, { startTime, success, error }) {+ // push + truncate is faster than unshift + pop for large arrayseventHistory.push({eventId: event.id,type: event.type,@@ -554,21 +600,38 @@ async function runEvent(event) {if (eventHistory.length > MAX_HISTORY) {eventHistory.splice(0, eventHistory.length - MAX_HISTORY)}+}- // Emit completion- cosEvents.emit('scheduler:ran', {- id: event.id,- success,- runCount: event.runCount- })+/**+ * Run an event+ * @param {Object} event - Event object+ */+async function runEvent(event) {+ const startTime = Date.now()- // Schedule next run for recurring events- if (event.active && event.type !== 'once') {- updateNextRunTime(event)- scheduleNextRun(event)- } else if (event.type === 'once') {- event.active = false- activeTimers.delete(event.id)+ event.lastRunAt = startTime+ event.runCount++++ let success = true+ let error = null++ try {+ await event.handler(event)+ } catch (err) {+ success = false+ error = err.message+ console.error(`⚠️ Event ${event.id} failed: ${err.message}`)+ } finally {+ recordEventHistory(event, { startTime, success, error })++ // A synchronous listener that throws must not cost the schedule its re-arm+ try {+ cosEvents.emit('scheduler:ran', { id: event.id, success, runCount: event.runCount })+ } catch (err) {+ console.error(`⚠️ Event ${event.id} scheduler:ran listener threw: ${err.message}`)+ }++ rearm(event)}}diff --git a/server/services/eventScheduler.test.js b/server/services/eventScheduler.test.jsindex 9566ed082b..4fe577da87 100644--- a/server/services/eventScheduler.test.js+++ b/server/services/eventScheduler.test.js@@ -16,6 +16,7 @@ import {parseRecurrenceToNextRun,isValidRecurrence,} from './eventScheduler.js';+import { cosEvents } from './cosEvents.js';// eventScheduler.js's "UTC" branch (the default, and what every consumer below// uses unless it passes an explicit IANA timezone) reads local Date methods@@ -405,6 +406,79 @@ describe('schedule() lifecycle with fake timers', () => {expect(entry.duration).toBeGreaterThanOrEqual(0);});+ it('re-arms a recurring event even when a scheduler:ran listener throws', async () => {+ // The re-arm used to sit after the emit, outside any try — one throwing+ // listener permanently stopped the schedule while the UI still showed it active.+ const handler = vi.fn();+ const listener = vi.fn(() => { throw new Error('listener boom'); });+ cosEvents.on('scheduler:ran', listener);+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});++ try {+ schedule({ id: 'listener-throw', type: 'interval', intervalMs: 5000, handler });++ await vi.advanceTimersByTimeAsync(5000);+ expect(handler).toHaveBeenCalledTimes(1);+ expect(listener).toHaveBeenCalledTimes(1);+ expect(getEvent('listener-throw').active).toBe(true);+ expect(getStats().activeTimers).toBe(1); // re-armed with a fresh handle++ await vi.advanceTimersByTimeAsync(5000);+ expect(handler).toHaveBeenCalledTimes(2); // schedule survived the throw+ } finally {+ cosEvents.off('scheduler:ran', listener);+ consoleError.mockRestore();+ }+ });++ it('stops a cron event whose expression became unparseable, with one error log', async () => {+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});++ try {+ // The handler receives the live event object — corrupt the cron mid-run the+ // same way a bad persisted value would surface on the next recompute.+ schedule({+ id: 'bad-cron',+ type: 'cron',+ cron: '* * * * *',+ handler: event => { event.cron = '* * *'; },+ });++ await vi.advanceTimersByTimeAsync(60 * 1000);++ expect(getEvent('bad-cron').active).toBe(false);+ expect(getStats().activeTimers).toBe(0);+ expect(consoleError).toHaveBeenCalledWith(+ expect.stringContaining('Event bad-cron could not compute its next run')+ );+ } finally {+ consoleError.mockRestore();+ }+ });++ it('stops a recurrence event that yields no next occurrence, with one error log', async () => {+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});++ try {+ schedule({+ id: 'no-next',+ type: 'recurrence',+ recurrence: { frequency: 'weekly', interval: 1, weekdays: [1], time: '00:05', anchorDate: '2024-01-01' },+ handler: event => { event.recurrence = { frequency: 'weekly', interval: 0 }; },+ });++ await vi.advanceTimersByTimeAsync(5 * 60 * 1000);++ expect(getEvent('no-next').active).toBe(false);+ expect(getStats().activeTimers).toBe(0);+ expect(consoleError).toHaveBeenCalledWith(+ expect.stringContaining('Event no-next has no next run time')+ );+ } finally {+ consoleError.mockRestore();+ }+ });+it('cancelAll() removes every scheduled event and reports the count removed', () => {schedule({ id: 'a', type: 'once', delayMs: 1000, handler: () => {} });schedule({ id: 'b', type: 'once', delayMs: 1000, handler: () => {} });