Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.
TypeScript
fix(calendar): fast-forward stale recurring events in a single step (#208)
cicada3b2910392c2f
diff --git a/server/src/__integration__/calendar-scheduler.test.ts b/server/src/__integration__/calendar-scheduler.test.tsnew file mode 100644index 0000000..12b8a3d--- /dev/null+++ b/server/src/__integration__/calendar-scheduler.test.ts@@ -0,0 +1,135 @@+import assert from 'node:assert/strict'+import { after, before, beforeEach, test } from 'node:test'+import { pool } from '../db/pool.js'+import { tickCalendar } from '../calendar.js'+import { ensureSchemaOnce, resetAllTables, teardownAll } from './_helpers.js'++before(async () => {+ await ensureSchemaOnce()+})++beforeEach(async () => {+ await resetAllTables()+})++after(async () => {+ await teardownAll()+})++const COMPANY_ID = 'co-calendar-test'+const USER_ID = 'u-calendar-test'++async function seedFixture() {+ await pool.query(+ `INSERT INTO companies (id, name, slug, owner_user_id) VALUES ($1, 'Calendar Co', $1, $2)`,+ [COMPANY_ID, USER_ID],+ )+ await pool.query(+ `INSERT INTO participants (id, company_id, kind, name, initial, avatar_bg, status)+ VALUES ($1, $2, 'human', 'Tester', 'T', '#abcdef', 'avail')`,+ [USER_ID, COMPANY_ID],+ )+}++test('[integration] calendar: fast-forwards stale recurring event in a single step to due slot', async () => {+ await seedFixture()+ const eventId = 'ev-stale-daily'+ // Event started 10 days ago at 10:00:00Z, recurs daily+ const startAt = new Date('2026-06-05T10:00:00.000Z')+ const now = new Date('2026-06-15T10:05:00.000Z') // 10 days later, 5 min past slot++ await pool.query(+ `INSERT INTO calendar_events (+ id, company_id, created_by, kind, title, start_at, recurrence, status+ ) VALUES ($1, $2, $3, 'personal', 'Daily Sync', $4, $5::jsonb, 'active')`,+ [eventId, COMPANY_ID, USER_ID, startAt, JSON.stringify({ freq: 'daily', interval: 1 })],+ )++ // Single tick must fast-forward directly to today (2026-06-15) instead of slow-crawling+ const res = await tickCalendar(now)+ assert.equal(res.scanned, 1)++ const { rows } = await pool.query<{ last_fired_at: Date; status: string }>(+ `SELECT last_fired_at, status FROM calendar_events WHERE id = $1`, [eventId],+ )+ assert.equal(rows[0]?.status, 'active')+ assert.equal(rows[0]?.last_fired_at?.toISOString(), '2026-06-15T10:00:00.000Z')+})++test('[integration] calendar: fast-forwards stale recurring event to future slot without firing', async () => {+ await seedFixture()+ const eventId = 'ev-stale-future'+ // Event started 10 days ago at 10:00:00Z, recurs daily+ const startAt = new Date('2026-06-05T10:00:00.000Z')+ const now = new Date('2026-06-15T15:00:00.000Z') // 5 hours past today's slot (> 1 hour)++ await pool.query(+ `INSERT INTO calendar_events (+ id, company_id, created_by, kind, title, start_at, recurrence, status+ ) VALUES ($1, $2, $3, 'personal', 'Daily Sync', $4, $5::jsonb, 'active')`,+ [eventId, COMPANY_ID, USER_ID, startAt, JSON.stringify({ freq: 'daily', interval: 1 })],+ )++ // Single tick must fast-forward last_fired_at to now without slow-crawling+ const res = await tickCalendar(now)+ assert.equal(res.scanned, 1)++ const { rows } = await pool.query<{ last_fired_at: Date; status: string }>(+ `SELECT last_fired_at, status FROM calendar_events WHERE id = $1`, [eventId],+ )+ assert.equal(rows[0]?.status, 'active')+ assert.equal(rows[0]?.last_fired_at?.toISOString(), '2026-06-15T15:00:00.000Z')++ // Next tick at 15:01: waits for tomorrow's slot without firing+ const resNext = await tickCalendar(new Date('2026-06-15T15:01:00.000Z'))+ assert.equal(resNext.scanned, 1)+ assert.equal(resNext.fired, 0)+})++test('[integration] calendar: expired one-shot event is marked done in a single step', async () => {+ await seedFixture()+ const eventId = 'ev-expired-oneshot'+ // One-shot event scheduled 3 hours ago (> 1 hour)+ const startAt = new Date('2026-06-15T07:00:00.000Z')+ const now = new Date('2026-06-15T10:00:00.000Z')++ await pool.query(+ `INSERT INTO calendar_events (+ id, company_id, created_by, kind, title, start_at, recurrence, status+ ) VALUES ($1, $2, $3, 'personal', 'One-Shot Meeting', $4, NULL, 'active')`,+ [eventId, COMPANY_ID, USER_ID, startAt],+ )++ const res = await tickCalendar(now)+ assert.equal(res.scanned, 1)+ assert.equal(res.fired, 0)++ const { rows } = await pool.query<{ last_fired_at: Date; status: string }>(+ `SELECT last_fired_at, status FROM calendar_events WHERE id = $1`, [eventId],+ )+ assert.equal(rows[0]?.status, 'done')+})++test('[integration] calendar: recurring event with past until date is marked done in a single step', async () => {+ await seedFixture()+ const eventId = 'ev-expired-until'+ // Recurring event whose until date passed 5 days ago+ const startAt = new Date('2026-06-01T10:00:00.000Z')+ const now = new Date('2026-06-15T10:00:00.000Z')++ await pool.query(+ `INSERT INTO calendar_events (+ id, company_id, created_by, kind, title, start_at, recurrence, status+ ) VALUES ($1, $2, $3, 'personal', 'Temporary Sync', $4, $5::jsonb, 'active')`,+ [eventId, COMPANY_ID, USER_ID, startAt, JSON.stringify({ freq: 'daily', interval: 1, until: '2026-06-05T10:00:00.000Z' })],+ )++ const res = await tickCalendar(now)+ assert.equal(res.scanned, 1)+ assert.equal(res.fired, 0)++ const { rows } = await pool.query<{ last_fired_at: Date; status: string }>(+ `SELECT last_fired_at, status FROM calendar_events WHERE id = $1`, [eventId],+ )+ assert.equal(rows[0]?.status, 'done')+})diff --git a/server/src/calendar.ts b/server/src/calendar.tsindex de323bd..44e0ce9 100644--- a/server/src/calendar.ts+++ b/server/src/calendar.ts@@ -385,7 +385,7 @@ async function sendReminder(event: CalendarEventRow, occurrence: Date, now: Datefunction sanitizeReminderSubject(event: CalendarEventRow, leadMinutes: number): string {// Strip control characters to stop header injection, keep subject short.- const title = event.title.replace(/[\r\n\t -]/g, ' ').slice(0, 160)+ const title = event.title.replace(/[\r\n\t\x00-\x1f]/g, ' ').slice(0, 160)if (leadMinutes <= 1) return `Starting now: ${title}`if (leadMinutes < 60) return `In ${leadMinutes} min: ${title}`const h = Math.round(leadMinutes / 60)@@ -453,7 +453,7 @@ export async function tickCalendar(now: Date = new Date()): Promise<{ scanned: nconst after = row.last_fired_at? new Date(row.last_fired_at.getTime() + 1): row.start_at- const slot = nextOccurrenceOnOrAfter(row.start_at, row.recurrence, after)+ let slot = nextOccurrenceOnOrAfter(row.start_at, row.recurrence, after)if (!slot) {await withOutboxTransaction(async (client) => {await client.query(`UPDATE calendar_events SET status='done', updated_at=NOW() WHERE id=$1`, [row.id])@@ -477,14 +477,48 @@ export async function tickCalendar(now: Date = new Date()): Promise<{ scanned: nif (slot.getTime() > now.getTime()) continue // not yetconst lag = now.getTime() - slot.getTime()if (lag > MAX_CATCHUP_MS) {- await withOutboxTransaction(async (client) => {- await client.query(- `UPDATE calendar_events SET last_fired_at = $2, updated_at = NOW() WHERE id = $1`,- [row.id, slot],- )- await enqueueCalendarChanged(client, row.company_id, 'event.updated', row.id)- })- continue+ if (!row.recurrence) {+ await withOutboxTransaction(async (client) => {+ await client.query(+ `UPDATE calendar_events SET last_fired_at = $2, status = 'done', updated_at = NOW() WHERE id = $1`,+ [row.id, slot],+ )+ await enqueueCalendarChanged(client, row.company_id, 'event.updated', row.id)+ })+ continue+ }++ // Stale recurring event: fast-forward past the backlog in a single step+ // instead of slow-crawling one slot per tick.+ const catchupFloor = new Date(now.getTime() - MAX_CATCHUP_MS)+ const nextSlot = nextOccurrenceOnOrAfter(row.start_at, row.recurrence, catchupFloor)+ if (!nextSlot) {+ await withOutboxTransaction(async (client) => {+ await client.query(+ `UPDATE calendar_events SET last_fired_at = $2, status = 'done', updated_at = NOW() WHERE id = $1`,+ [row.id, slot],+ )+ await enqueueCalendarChanged(client, row.company_id, 'event.updated', row.id)+ })+ continue+ }++ if (nextSlot.getTime() <= now.getTime()) {+ // There is an occurrence inside the catch-up window [now - MAX_CATCHUP_MS, now].+ // Jump directly to this slot so it can fire on this tick.+ slot = nextSlot+ } else {+ // No occurrences fell inside the catch-up window; the next occurrence is in the future.+ // Fast-forward last_fired_at to now so subsequent ticks await nextSlot without firing.+ await withOutboxTransaction(async (client) => {+ await client.query(+ `UPDATE calendar_events SET last_fired_at = $2, updated_at = NOW() WHERE id = $1`,+ [row.id, now],+ )+ await enqueueCalendarChanged(client, row.company_id, 'event.updated', row.id)+ })+ continue+ }}const result = await dispatchEvent(row, slot)if (result.status === 'dispatched' || result.status === 'skipped' || result.status === 'failed') {