Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(email): preserve absolute invitation scheduling times (#1177)

Genera860704b0ef8
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a531d9660..d80a8e5c3 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -224,9 +224,15 @@ importers:
src/shared:
dependencies:
+ '@philflow/tsdav-utils':
+ specifier: 0.7.0
+ version: 0.7.0
drizzle-orm:
specifier: ^0.45.4
+ ical.js:
+ specifier: 2.2.1
+ version: 2.2.1
mdast-util-find-and-replace:
specifier: ^3.0.3
version: 3.0.3
@@ -2850,6 +2856,9 @@ packages:
'@paulirish/[email protected]':
resolution: {integrity: sha512-PUl/vlfo08Oj804VI5nDPeSk9vyslnBlVzDDwFt8SUVxY8+KdGMkra/vrXjEEHe8gb7+RqVTfOIlGw0nyrEelA==}
+ '@philflow/[email protected]':
+ resolution: {integrity: sha512-reKM1zCykID+HOv1duqbuTqKpfuX7bQoYtYtkYQJ67IVmeHMHY1ASNrIpLjFMiZoD/ncmjUXMxG/vYWM+ZeWdw==}
+
resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==}
engines: {node: '>=14'}
@@ -6716,6 +6725,9 @@ packages:
resolution: {integrity: sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==}
engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-yK/UlPbEs316igb/tjRgbFA8ZV75rCsBJp/hWOatpyaPNlgw0dGDmU+FoicOcwX4xXkeXOkYiOmCqNPFpNPkQg==}
+
resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==}
engines: {node: '>=0.10.0'}
@@ -12301,6 +12313,10 @@ snapshots:
legacy-javascript: 0.0.4
third-party-web: 0.30.0
+ '@philflow/[email protected]':
+ dependencies:
+ ical.js: 2.2.1
+
optional: true
@@ -16377,6 +16393,8 @@ snapshots:
dependencies:
safer-buffer: 2.1.2
+
dependencies:
safer-buffer: 2.1.2
diff --git a/src/email-worker/src/__mocks__/cf.ts b/src/email-worker/src/__mocks__/cf.ts
index 39e44ab9f..fabd17cc2 100644
--- a/src/email-worker/src/__mocks__/cf.ts
+++ b/src/email-worker/src/__mocks__/cf.ts
@@ -105,7 +105,13 @@ export interface MockMessageOpts {
extraHeaders?: Record<string, string>
}
-export const CALENDAR_CONTENT = "BEGIN:VCALENDAR\nVERSION:2.0\nBEGIN:VEVENT\nSUMMARY:日程🙂\nEND:VEVENT\nEND:VCALENDAR\n"
+export const CALENDAR_CONTENT = [
+ "BEGIN:VCALENDAR", "VERSION:2.0", "BEGIN:VTIMEZONE", "TZID:Office", "BEGIN:STANDARD",
+ "DTSTART:20000101T000000", "TZOFFSETFROM:+0100", "TZOFFSETTO:+0100", "END:STANDARD", "END:VTIMEZONE",
+ "BEGIN:VEVENT", "SUMMARY:日程🙂", "DTSTART;TZID=Office:20261101T100000", "DTEND;TZID=Office:20261101T110000",
+ "LOCATION:https://meet.google.com/abc-defg-hij", "ATTENDEE;CN=Guest:mailto:[email protected]",
+ "END:VEVENT", "END:VCALENDAR", "",
+].join("\n")
export const CALENDAR_MESSAGE = {
body: CALENDAR_CONTENT.replace(/\n/g, "\r\n"),
extraHeaders: {
diff --git a/src/email-worker/src/imap-poller-do.test.ts b/src/email-worker/src/imap-poller-do.test.ts
index 0804410bd..a9e3c10c4 100644
--- a/src/email-worker/src/imap-poller-do.test.ts
+++ b/src/email-worker/src/imap-poller-do.test.ts
@@ -214,6 +214,11 @@ describe("alarm — normal UID-based flow", () => {
expect(notify1.subject).toBe("Hi")
expect(notify1.isWhitelisted).toBe(true)
expect(notify1.messageId).toBe("<msg1>")
+ expect(notify1.meetingInfo).toEqual({
+ title: "日程🙂", meetingUrl: "https://meet.google.com/abc-defg-hij",
+ startTime: "2026-11-01T09:00:00.000Z", endTime: "2026-11-01T10:00:00.000Z",
+ attendees: [{ name: "Guest", email: "[email protected]" }],
+ })
expect(JSON.parse(notify1.attachments)).toEqual([
{ key: "inline:0", filename: "invite.ics", contentType: "text/calendar", size: new TextEncoder().encode(CALENDAR_CONTENT).byteLength },
])
diff --git a/src/email-worker/test-runtime/worker.runtime.test.ts b/src/email-worker/test-runtime/worker.runtime.test.ts
index 8862ae26b..1081c25b1 100644
--- a/src/email-worker/test-runtime/worker.runtime.test.ts
+++ b/src/email-worker/test-runtime/worker.runtime.test.ts
@@ -3,6 +3,37 @@
import { runInDurableObject } from "cloudflare:test"
import { env, exports } from "cloudflare:workers"
import { describe, expect, it } from "vitest"
+import { createDb, EmailNotifyRequestSchema, parseIcs, queries } from "@alook/shared"
+
+const ANCIENT_MONTHLY_ZONE = `BEGIN:VTIMEZONE
+TZID:Ancient/Monthly
+BEGIN:DAYLIGHT
+DTSTART:10000101T000000
+TZOFFSETFROM:+0000
+TZOFFSETTO:+0100
+RRULE:FREQ=MONTHLY;BYMONTHDAY=1
+END:DAYLIGHT
+BEGIN:STANDARD
+DTSTART:10000115T000000
+TZOFFSETFROM:+0100
+TZOFFSETTO:+0000
+RRULE:FREQ=MONTHLY;BYMONTHDAY=15
+END:STANDARD
+END:VTIMEZONE`
+
+const FINITE_ONE_DAY_ZONE = `BEGIN:VTIMEZONE
+TZID:Finite/OneDay
+BEGIN:DAYLIGHT
+DTSTART:20260601T000000
+TZOFFSETFROM:+0000
+TZOFFSETTO:+0100
+END:DAYLIGHT
+BEGIN:STANDARD
+DTSTART:20260602T000000
+TZOFFSETFROM:+0100
+TZOFFSETTO:+0000
+END:STANDARD
+END:VTIMEZONE`
const runtimeEnv = env as unknown as {
DB: D1Database
@@ -15,6 +46,50 @@ const worker = (exports as unknown as {
}).default
describe("email-worker workerd runtime", () => {
+ it.each([
+ { name: "overlap", start: "20071104T013000", embedded: true, expected: "2007-11-04T05:30:00.000Z", before: "2007-11-04T05:29:59.999Z", status: "scheduled" },
+ { name: "gap", start: "20070311T023000", embedded: true, expected: "2007-03-11T07:30:00.000Z", before: "2007-03-11T07:29:59.999Z", status: "scheduled" },
+ { name: "exhausted ancient monthly recurrence", start: "20260610T100000", embedded: true, zoneOverride: ANCIENT_MONTHLY_ZONE, tzid: "Ancient/Monthly", expected: null, before: "2026-06-10T08:59:59.999Z", status: "pending" },
+ { name: "unresolved bare IANA", start: "20071104T013000", embedded: false, expected: null, before: "2007-11-04T05:29:59.999Z", status: "pending" },
+ { name: "unsupported finite one-day observances", start: "20260601T120000", embedded: true, zoneOverride: FINITE_ONE_DAY_ZONE, tzid: "Finite/OneDay", expected: null, before: "2026-06-01T10:59:59.999Z", status: "pending" },
+ ])("persists qualified invitation time in real D1: $name", async ({ start, embedded, zoneOverride, tzid = "America/New_York", expected, before, status }) => {
+ const zone = ["BEGIN:VTIMEZONE", "TZID:America/New_York", "BEGIN:DAYLIGHT",
+ "DTSTART:20070311T020000", "TZOFFSETFROM:-0500", "TZOFFSETTO:-0400", "RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU", "END:DAYLIGHT",
+ "BEGIN:STANDARD", "DTSTART:20061105T020000", "TZOFFSETFROM:-0400", "TZOFFSETTO:-0500", "RRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU", "END:STANDARD", "END:VTIMEZONE"].join("\n")
+ const invitation = ["BEGIN:VCALENDAR", "VERSION:2.0", embedded ? zoneOverride ?? zone : "", "BEGIN:VEVENT",
+ `DTSTART;TZID=${tzid}:${start}`, "SUMMARY:Runtime invitation",
+ "LOCATION:https://meet.google.com/abc-defg-hij", "END:VEVENT", "END:VCALENDAR"].filter(Boolean).join("\n")
+ const workspaceId = `ics-${crypto.randomUUID()}`
+ const now = "2026-11-04T00:00:00.000Z"
+ try {
+ await runtimeEnv.DB.prepare("INSERT INTO workspace (id, name, slug, created_at, updated_at) VALUES (?, 'ICS', ?, ?, ?)")
+ .bind(workspaceId, workspaceId, now, now).run()
+ const db = createDb(runtimeEnv.DB)
+ const agent = await queries.agent.createAgent(db, { workspaceId, name: "ICS agent" })
+ const notification = EmailNotifyRequestSchema.parse({
+ agentId: agent.id, workspaceId, r2Key: "runtime/unsubmitted-email",
+ from: "[email protected]", subject: "Runtime invitation", isWhitelisted: true,
+ meetingInfo: parseIcs(invitation),
+ })
+ const info = notification.meetingInfo
+ expect(info).toBeDefined()
+ if (!info) throw new Error("invitation metadata missing")
+ expect(info.startTime).toBe(expected)
+ const meeting = await queries.meetingSession.createMeetingSession(db, {
+ agentId: agent.id, workspaceId, meetingUrl: info.meetingUrl, title: info.title,
+ status, scheduledAt: info.startTime, isWhitelisted: true,
+ })
+ expect(meeting.status).toBe(status)
+ expect(meeting.scheduledAt).toBe(expected)
+ expect((await queries.meetingSession.getMeetingSession(db, meeting.id, workspaceId))?.scheduledAt).toBe(expected)
+ expect(await queries.meetingSession.listScheduledMeetings(db, workspaceId, before)).toEqual([])
+ expect((await queries.meetingSession.listScheduledMeetings(db, workspaceId, expected ?? now)).map(row => row.id))
+ .toEqual(expected === null ? [] : [meeting.id])
+ } finally {
+ await runtimeEnv.DB.prepare("DELETE FROM workspace WHERE id = ?").bind(workspaceId).run()
+ }
+ })
+
it("loads production migrations and serves the production entrypoint", async () => {
const schema = await runtimeEnv.DB.prepare(
"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",
diff --git a/src/shared/package.json b/src/shared/package.json
index 98fa06899..8397092a0 100644
--- a/src/shared/package.json
+++ b/src/shared/package.json
@@ -27,7 +27,9 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
+ "@philflow/tsdav-utils": "0.7.0",
"drizzle-orm": "^0.45.4",
+ "ical.js": "2.2.1",
"nanoid": "^5.1.16",
"zod": "^4.6",
"unified": "^11.0.5",
diff --git a/src/shared/src/lib/ics-parser.test.ts b/src/shared/src/lib/ics-parser.test.ts
index 85301a41f..8efdfabce 100644
--- a/src/shared/src/lib/ics-parser.test.ts
+++ b/src/shared/src/lib/ics-parser.test.ts
@@ -45,6 +45,82 @@ LOCATION:https://meet.google.com/xyz-wxyz-abc
END:VEVENT
END:VCALENDAR`
+
+const NEW_YORK_ZONE = `BEGIN:VTIMEZONE
+TZID:America/New_York
+BEGIN:DAYLIGHT
+DTSTART:20070311T020000
+TZOFFSETFROM:-0500
+TZOFFSETTO:-0400
+RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU
+END:DAYLIGHT
+BEGIN:STANDARD
+DTSTART:20061105T020000
+TZOFFSETFROM:-0400
+TZOFFSETTO:-0500
+RRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU
+END:STANDARD
+END:VTIMEZONE`
+
+const ANCIENT_MONTHLY_ZONE = `BEGIN:VTIMEZONE
+TZID:Ancient/Monthly
+BEGIN:DAYLIGHT
+DTSTART:10000101T000000
+TZOFFSETFROM:+0000
+TZOFFSETTO:+0100
+RRULE:FREQ=MONTHLY;BYMONTHDAY=1
+END:DAYLIGHT
+BEGIN:STANDARD
+DTSTART:10000115T000000
+TZOFFSETFROM:+0100
+TZOFFSETTO:+0000
+RRULE:FREQ=MONTHLY;BYMONTHDAY=15
+END:STANDARD
+END:VTIMEZONE`
+
+const FINITE_ONE_DAY_ICS = `BEGIN:VCALENDAR
+VERSION:2.0
+BEGIN:VTIMEZONE
+TZID:Finite/OneDay
+BEGIN:DAYLIGHT
+DTSTART:20260601T000000
+TZOFFSETFROM:+0000
+TZOFFSETTO:+0100
+END:DAYLIGHT
+BEGIN:STANDARD
+DTSTART:20260602T000000
+TZOFFSETFROM:+0100
+TZOFFSETTO:+0000
+END:STANDARD
+END:VTIMEZONE
+BEGIN:VEVENT
+DTSTART;TZID=Finite/OneDay:20260601T120000
+SUMMARY:Finite interval qualification
+END:VEVENT
+END:VCALENDAR
+`
+
+const RFC_TIME_VECTORS = [
+ ["summer", "20260428T100000", "2026-04-28T14:00:00.000Z"],
+ ["winter", "20260128T100000", "2026-01-28T15:00:00.000Z"],
+ ["RFC overlap first occurrence", "20071104T013000", "2007-11-04T05:30:00.000Z"],
+ ["RFC gap pre-transition offset", "20070311T023000", "2007-03-11T07:30:00.000Z"],
+ ["before spring transition", "20070311T013000", "2007-03-11T06:30:00.000Z"],
+ ["after spring transition", "20070311T033000", "2007-03-11T07:30:00.000Z"],
+ ["before autumn transition", "20071104T003000", "2007-11-04T04:30:00.000Z"],
+ ["after autumn transition", "20071104T023000", "2007-11-04T07:30:00.000Z"],
+] as const
+
+function timeInvitation(start: string, zone = "", end = ""): string {
+ return ["BEGIN:VCALENDAR", "VERSION:2.0", zone, "BEGIN:VEVENT", start, end,
+ "SUMMARY:Qualification", "END:VEVENT", "END:VCALENDAR"].filter(Boolean).join("\n")
+}
+
+function fixedZone(offset: string): string {
+ return ["BEGIN:VTIMEZONE", "TZID:Office", "BEGIN:STANDARD", "DTSTART:20000101T000000",
+ `TZOFFSETFROM:${offset}`, `TZOFFSETTO:${offset}`, "END:STANDARD", "END:VTIMEZONE"].join("\n")
+}
+
describe("ics-parser", () => {
describe("parseIcs", () => {
it("parses standard Google Calendar ICS with Google Meet link", () => {
@@ -52,15 +128,15 @@ describe("ics-parser", () => {
expect(result.title).toBe("Weekly Standup")
expect(result.meetingUrl).toBe("https://meet.google.com/abc-defg-hij")
- expect(result.startTime).toBe("2026-04-28T14:00:00Z")
- expect(result.endTime).toBe("2026-04-28T15:00:00Z")
+ expect(result.startTime).toBe("2026-04-28T14:00:00.000Z")
+ expect(result.endTime).toBe("2026-04-28T15:00:00.000Z")
})
it("parses ICS with Zoom link in description", () => {
const result = parseIcs(ZOOM_ICS)
expect(result.title).toBe("Design Review")
- expect(result.meetingUrl).toContain("zoom.us/j/1234567890")
+ expect(result.meetingUrl).toBe("https://us02web.zoom.us/j/1234567890?pwd=abc")
})
it("extracts multiple attendees with names and emails", () => {
@@ -76,8 +152,8 @@ describe("ics-parser", () => {
expect(result.title).toBe("Coffee Chat")
expect(result.meetingUrl).toBeNull()
- expect(result.startTime).toBe("2026-04-30T09:00:00Z")
- expect(result.endTime).toBe("2026-04-30T09:30:00Z")
+ expect(result.startTime).toBe("2026-04-30T09:00:00.000Z")
+ expect(result.endTime).toBe("2026-04-30T09:30:00.000Z")
})
it("handles multi-line folded ICS fields (RFC 5545 unfold)", () => {
@@ -101,11 +177,62 @@ describe("ics-parser", () => {
expect(result.meetingUrl).toBe("https://meet.google.com/abc-defg-hij")
})
- it("extracts DTSTART/DTEND with timezone (non-UTC)", () => {
- const result = parseIcs(LOCAL_TIME_ICS)
+ it.each([
+ ...RFC_TIME_VECTORS.map(([name, input, expected]) => ({
+ name, ics: timeInvitation(`DTSTART;TZID=America/New_York:${input}`, NEW_YORK_ZONE),
+ start: expected, end: null,
+ })),
+ { name: "exhausted ancient monthly recurrence", ics: timeInvitation("DTSTART;TZID=Ancient/Monthly:20260610T100000", ANCIENT_MONTHLY_ZONE), start: null, end: null },
+ { name: "modern monthly rule with UTC UNTIL", ics: timeInvitation("DTSTART;TZID=Ancient/Monthly:20260610T100000", ANCIENT_MONTHLY_ZONE.replaceAll("1000", "2020").replaceAll("BYMONTHDAY=1\n", "BYMONTHDAY=1;UNTIL=20301231T230000Z\n").replaceAll("BYMONTHDAY=15\n", "BYMONTHDAY=15;UNTIL=20301231T230000Z\n")), start: "2026-06-10T09:00:00.000Z", end: null },
+ { name: "original UTC UNTIL still limits conversion", ics: timeInvitation("DTSTART;TZID=Ancient/Monthly:20260610T100000", ANCIENT_MONTHLY_ZONE.replaceAll("1000", "2020").replaceAll("BYMONTHDAY=1\n", "BYMONTHDAY=1;UNTIL=20251231T230000Z\n").replaceAll("BYMONTHDAY=15\n", "BYMONTHDAY=15;UNTIL=20251231T230000Z\n")), start: "2026-06-10T10:00:00.000Z", end: null },
+ { name: "original COUNT still limits conversion", ics: timeInvitation("DTSTART;TZID=Ancient/Monthly:20260610T100000", ANCIENT_MONTHLY_ZONE.replaceAll("1000", "2020").replaceAll("BYMONTHDAY=1\n", "BYMONTHDAY=1;COUNT=2\n").replaceAll("BYMONTHDAY=15\n", "BYMONTHDAY=15;COUNT=2\n")), start: "2026-06-10T10:00:00.000Z", end: null },
+ { name: "all observances must finish", ics: timeInvitation("DTSTART;TZID=America/New_York:20260428T100000", NEW_YORK_ZONE.replace("END:VTIMEZONE", `${ANCIENT_MONTHLY_ZONE.split("\n").slice(2, -1).join("\n")}\nEND:VTIMEZONE`)), start: null, end: null },
+ { name: "complete lookahead before conversion", ics: timeInvitation("DTSTART;TZID=Office:20260610T100000", fixedZone("+0100").replace("DTSTART:20000101T000000", "DTSTART:20210101T000000").replace("END:STANDARD", `RRULE:FREQ=MONTHLY;BYMONTHDAY=${Array.from({ length: 28 }, (_, i) => i + 1).join(",")};BYHOUR=0,12\nEND:STANDARD`)), start: null, end: null },
+ { name: "finite local RDATE values", ics: timeInvitation("DTSTART;TZID=Ancient/Monthly:20260610T100000", ANCIENT_MONTHLY_ZONE.replaceAll("1000", "2020").replace("RRULE:FREQ=MONTHLY;BYMONTHDAY=1", "RDATE:20260601T000000,20260701T000000").replace("RRULE:FREQ=MONTHLY;BYMONTHDAY=15", "RDATE:20260615T000000,20260715T000000")), start: "2026-06-10T09:00:00.000Z", end: null },
+ { name: "UTC RDATE is not a local observance", ics: timeInvitation("DTSTART;TZID=Office:20260428T100000", fixedZone("+0100").replace("END:STANDARD", "RDATE:20260401T000000Z\nEND:STANDARD")), start: null, end: null },
+ { name: "original bare IANA timezone", ics: LOCAL_TIME_ICS, start: null, end: null },
+ { name: "original invitation with embedded definition", ics: LOCAL_TIME_ICS.replace("VERSION:2.0", `VERSION:2.0\n${NEW_YORK_ZONE}`), start: "2026-04-28T14:00:00.000Z", end: "2026-04-28T15:00:00.000Z" },
+ { name: "unknown TZID", ics: timeInvitation("DTSTART;TZID=Unknown/Zone:20260428T100000", NEW_YORK_ZONE), start: null, end: null },
+ { name: "floating", ics: timeInvitation("DTSTART:20260428T100000"), start: null, end: null },
+ { name: "date only", ics: timeInvitation("DTSTART;VALUE=DATE:20260428"), start: null, end: null },
+ { name: "invalid calendar date", ics: timeInvitation("DTSTART:20260230T100000Z"), start: null, end: null },
+ { name: "invalid hour", ics: timeInvitation("DTSTART:20260428T250000Z"), start: null, end: null },
+ { name: "missing timezone offsets", ics: timeInvitation("DTSTART;TZID=Office:20260428T100000", "BEGIN:VTIMEZONE\nTZID:Office\nBEGIN:STANDARD\nDTSTART:20000101T000000\nEND:STANDARD\nEND:VTIMEZONE"), start: null, end: null },
+ { name: "unsupported second offset", ics: timeInvitation("DTSTART;TZID=Office:20260428T100000", fixedZone("+010030")), start: null, end: null },
+ { name: "duplicate timezone definitions", ics: timeInvitation("DTSTART;TZID=Office:20260428T100000", `${fixedZone("+0100")}\n${fixedZone("+0200")}`), start: null, end: null },
+ { name: "unsupported observance recurrence", ics: timeInvitation("DTSTART;TZID=Office:20260428T100000", fixedZone("+0100").replace("END:STANDARD", "RRULE:FREQ=DAILY\nEND:STANDARD")), start: null, end: null },
+ { name: "known start with unknown end", ics: timeInvitation("DTSTART:20260428T140000Z", "", "DTEND:20260428T150000"), start: "2026-04-28T14:00:00.000Z", end: null },
+ { name: "unknown start with known end", ics: timeInvitation("DTSTART:20260428T140000", "", "DTEND:20260428T150000Z"), start: null, end: "2026-04-28T15:00:00.000Z" },
+ { name: "finite one-day observances are unsupported", ics: FINITE_ONE_DAY_ICS, start: null, end: null },
+ { name: "well-separated finite observances", ics: FINITE_ONE_DAY_ICS.replace("DTSTART:20260602T000000", "DTSTART:20260609T000000"), start: "2026-06-01T11:00:00.000Z", end: null },
+ { name: "close RDATE observances are unsupported", ics: timeInvitation("DTSTART;TZID=Ancient/Monthly:20260601T120000", ANCIENT_MONTHLY_ZONE.replaceAll("1000", "2020").replace("RRULE:FREQ=MONTHLY;BYMONTHDAY=1", "RDATE:20260601T000000").replace("RRULE:FREQ=MONTHLY;BYMONTHDAY=15", "RDATE:20260602T000000")), start: null, end: null },
+ { name: "close recurring observances are unsupported", ics: timeInvitation("DTSTART;TZID=Ancient/Monthly:20260601T120000", ANCIENT_MONTHLY_ZONE.replaceAll("1000", "2020").replace("RRULE:FREQ=MONTHLY;BYMONTHDAY=15", "RRULE:FREQ=MONTHLY;BYMONTHDAY=2")), start: null, end: null },
+ { name: "coincident observance walls are unsupported", ics: FINITE_ONE_DAY_ICS.replace("DTSTART:20260602T000000", "DTSTART:20260601T000000").replace("20260601T120000", "20260601T003000"), start: null, end: null },
+ { name: "close observances across the first century are unsupported", ics: FINITE_ONE_DAY_ICS.replaceAll("20260601", "00991231").replace("20260602", "01000101"), start: null, end: null },
+ ])("resolves only absolute invitation times: $name", ({ ics, start, end }) => {
+ const result = parseIcs(ics)
+ expect(result.startTime).toBe(start)
+ expect(result.endTime).toBe(end)
+ })
+
+ it("isolates same-named timezone definitions between invitations", () => {
+ for (const [offset, expected] of [
+ ["+0100", "2026-04-28T09:00:00.000Z"],
+ ["+0200", "2026-04-28T08:00:00.000Z"],
+ ["+0100", "2026-04-28T09:00:00.000Z"],
+ ] as const) {
+ expect(parseIcs(timeInvitation("DTSTART;TZID=Office:20260428T100000", fixedZone(offset))).startTime).toBe(expected)
+ }
+ })
- expect(result.startTime).toBe("2026-04-28T10:00:00")
- expect(result.endTime).toBe("2026-04-28T11:00:00")
+ it("keeps all meeting fields inside the first VEVENT", () => {
+ const second = ["BEGIN:VEVENT", "SUMMARY:Second meeting", "DTSTART:20260428T140000Z",
+ "LOCATION:https://meet.google.com/abc-defg-hij", "ATTENDEE;CN=Other:mailto:[email protected]", "END:VEVENT"].join("\n")
+ const first = NO_MEETING_URL_ICS.replace("END:VCALENDAR", `${second}\nEND:VCALENDAR`)
+ expect(parseIcs(first)).toEqual({
+ title: "Coffee Chat", meetingUrl: null,
+ startTime: "2026-04-30T09:00:00.000Z", endTime: "2026-04-30T09:30:00.000Z", attendees: [],
+ })
})
it("handles quoted CN names in attendees", () => {
diff --git a/src/shared/src/lib/ics-parser.ts b/src/shared/src/lib/ics-parser.ts
index e5ea6f3d4..26fd79283 100644
--- a/src/shared/src/lib/ics-parser.ts
+++ b/src/shared/src/lib/ics-parser.ts
@@ -1,3 +1,8 @@
+import ICAL from "ical.js"
+import { resolveZone } from "@philflow/tsdav-utils"
+import { z } from "zod"
+import { MeetingInfoSchema } from "../schemas"
+
export interface MeetingInfo {
title: string
meetingUrl: string | null
@@ -9,36 +14,98 @@ export interface MeetingInfo {
const MEET_URL_RE = /https:\/\/meet\.google\.com\/[a-z]{3}-[a-z]{4}-[a-z]{3}/gi
const ZOOM_URL_RE = /https:\/\/[\w.-]*zoom\.us\/j\/\d+[^\s<>"]*/gi
const TEAMS_URL_RE = /https:\/\/teams\.microsoft\.com\/l\/meetup-join\/[^\s<>"]*/gi
-
-function unfold(ics: string): string {
- return ics.replace(/\r?\n[ \t]/g, "")
-}
-
-function extractProperty(lines: string[], prop: string): string | null {
- for (const line of lines) {
- const upper = line.toUpperCase()
- if (upper.startsWith(prop.toUpperCase() + ":") || upper.startsWith(prop.toUpperCase() + ";")) {
- const colonIdx = line.indexOf(":")
- if (colonIdx === -1) continue
- return line.slice(colonIdx + 1).trim()
+const IcsDateTimeSchema = z.iso.datetime({ local: true })
+const IcsOffsetSchema = z.string().regex(/^[+-](?:[01]\d|2[0-3]):[0-5]\d$/)
+ .refine(value => value !== "-00:00")
+
+function hasSupportedObservances(zone: ICAL.Component, targetYear: number): boolean {
+ // The pinned converter looks ahead 3660 days from its UTC probes (within
+ // three days of this wall time). January of targetYear + 12 covers all of it.
+ const throughYear = targetYear + 12
+ if (throughYear > 9999) return false
+ let remainingOnsets = 4096
+ const onsetTimes: number[] = []
+ const observances = [
+ ...zone.getAllSubcomponents("standard"),
+ ...zone.getAllSubcomponents("daylight"),
+ ]
+ const complete = observances.length > 0 && observances.every(observance => {
+ const start = observance.getFirstProperty("dtstart")
+ const value: unknown = start?.toJSON()[3]
+ if (start?.type !== "date-time" || start.getParameter("tzid") !== undefined || typeof value !== "string"
+ || value.endsWith("Z") || !IcsDateTimeSchema.safeParse(value).success
+ || ["dtstart", "tzoffsetfrom", "tzoffsetto"].some(name => observance.getAllProperties(name).length !== 1)
+ || !["tzoffsetfrom", "tzoffsetto"].every(name =>
+ IcsOffsetSchema.safeParse(observance.getFirstProperty(name)?.toJSON()[3]).success)
+ || --remainingOnsets < 0) return false
+
+ const onsets = new Set<number>()
+ const addOnset = (date: string) => {
+ if (date.endsWith("Z") || !IcsDateTimeSchema.safeParse(date).success) return false
+ const coordinate = Date.parse(`${date}Z`)
+ if (!Number.isFinite(coordinate)) return false
+ onsets.add(coordinate)
+ return true
}
- }
- return null
+ if (!addOnset(value)) return false
+
+ for (const property of observance.getAllProperties("rdate")) {
+ if (property.type !== "date-time" || property.getParameter("tzid") !== undefined) return false
+ for (const date of property.toJSON().slice(3)) {
+ if (typeof date !== "string" || date.endsWith("Z")
+ || !IcsDateTimeSchema.safeParse(date).success || --remainingOnsets < 0) return false
+ if (!addOnset(date)) return false
+ }
+ }
+ for (const property of observance.getAllProperties("rrule")) {
+ const rule = (property.getFirstValue() as ICAL.Recur).clone()
+ if (!["YEARLY", "MONTHLY"].includes(rule.freq)
+ || !Number.isInteger(rule.interval) || rule.interval < 1) return false
+ // A superset avoids undercounting when the converter adjusts UTC UNTIL.
+ // Only this admission clone changes; conversion receives the original.
+ rule.until = null
+ rule.count = null
+ const iterator = rule.iterator(start.getFirstValue() as ICAL.Time)
+ for (;;) {
+ if (--remainingOnsets < 0) return false
+ const next = iterator.next()
+ if (!next) break
+ if (!addOnset(next.toString())) return false
+ if (next.year >= throughYear) break
+ }
+ }
+ onsetTimes.push(...onsets)
+ return true
+ })
+ if (!complete) return false
+ // Offsets below 24 hours make seven wall-clock days exceed five UTC days.
+ // This bounds adjacent transitions away from the converter's ±2-day probes.
+ onsetTimes.sort((a, b) => a - b)
+ return onsetTimes.every((time, index) => index === 0 || time - onsetTimes[index - 1]! >= 7 * 24 * 60 * 60 * 1000)
}
-function parseIcsDate(value: string): string | null {
- if (!value) return null
-
- const match = value.match(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})/)
- if (!match) return null
+function parseIcsDate(event: ICAL.Component, calendar: ICAL.Component, name: string): string | null {
+ try {
+ const property = event.getFirstProperty(name)
+ const value: unknown = property?.toJSON()[3]
+ if (property?.type !== "date-time" || typeof value !== "string"
+ || !IcsDateTimeSchema.safeParse(value).success) return null
- const [, y, m, d, hh, mm, ss] = match
- const isUtc = value.endsWith("Z")
-
- if (isUtc) {
- return `${y}-${m}-${d}T${hh}:${mm}:${ss}Z`
+ const tzid = property.getParameter("tzid")
+ if (value.endsWith("Z")) {
+ return tzid === undefined ? MeetingInfoSchema.shape.startTime.parse(value) : null
+ }
+ if (typeof tzid !== "string" || !tzid) return null
+ const zones = calendar.getAllSubcomponents("vtimezone")
+ .filter(zone => zone.getFirstPropertyValue("tzid") === tzid)
+ const zone = zones[0]
+ if (zones.length !== 1 || !zone || !hasSupportedObservances(zone, Number(value.slice(0, 4)))) return null
+ const converter = resolveZone(tzid, zone)
+ if (converter?.source !== "vtimezone") return null
+ return MeetingInfoSchema.shape.startTime.parse(converter.toInstant(value).toISOString())
+ } catch {
+ return null
}
- return `${y}-${m}-${d}T${hh}:${mm}:${ss}`
}
function extractMeetingUrl(text: string): string | null {
@@ -54,50 +121,38 @@ function extractMeetingUrl(text: string): string | null {
return null
}
-function extractAttendees(lines: string[]): { name: string; email: string }[] {
+function extractAttendees(event: ICAL.Component): { name: string; email: string }[] {
const attendees: { name: string; email: string }[] = []
const seen = new Set<string>()
-
- for (const line of lines) {
- if (!line.toUpperCase().startsWith("ATTENDEE")) continue
-
- let email = ""
- const mailtoMatch = line.match(/mailto:([^\s;>"]+)/i)
- if (mailtoMatch) {
- email = mailtoMatch[1].toLowerCase()
- }
- if (!email || seen.has(email)) continue
+ for (const property of event.getAllProperties("attendee")) {
+ const value = property.getFirstValue()
+ const match = typeof value === "string" ? value.match(/^mailto:([^\s;>"]+)$/i) : null
+ if (!match) continue
+ const email = match[1].toLowerCase()
+ if (seen.has(email)) continue
seen.add(email)
-
- let name = ""
- const cnMatch = line.match(/CN=([^;:]+)/i)
- if (cnMatch) {
- name = cnMatch[1].replace(/^["']|["']$/g, "").trim()
- }
-
- attendees.push({ name: name || email, email })
+ const cn = property.getParameter("cn")
+ attendees.push({ name: typeof cn === "string" && cn.trim() ? cn.trim() : email, email })
}
-
return attendees
}
export function parseIcs(icsText: string): MeetingInfo {
- const unfolded = unfold(icsText)
- const lines = unfolded.split(/\r?\n/)
-
- const title = extractProperty(lines, "SUMMARY") ?? ""
- const dtStart = extractProperty(lines, "DTSTART")
- const dtEnd = extractProperty(lines, "DTEND")
- const location = extractProperty(lines, "LOCATION") ?? ""
- const description = extractProperty(lines, "DESCRIPTION") ?? ""
-
- const fullText = [location, description, title].join(" ")
- const meetingUrl = extractMeetingUrl(fullText)
-
- const startTime = dtStart ? parseIcsDate(dtStart) : null
- const endTime = dtEnd ? parseIcsDate(dtEnd) : null
-
- const attendees = extractAttendees(lines)
-
- return { title, meetingUrl, startTime, endTime, attendees }
+ const result: MeetingInfo = { title: "", meetingUrl: null, startTime: null, endTime: null, attendees: [] }
+ try {
+ const calendar = new ICAL.Component(ICAL.parse(icsText))
+ const event = calendar.name === "vevent" ? calendar : calendar.getFirstSubcomponent("vevent")
+ if (!event) return result
+ const title = event.getFirstPropertyValue("summary")
+ result.title = typeof title === "string" ? title : ""
+ const fullText = [event.getFirstPropertyValue("location"), event.getFirstPropertyValue("description"), result.title]
+ .filter((value): value is string => typeof value === "string").join(" ")
+ result.meetingUrl = extractMeetingUrl(fullText)
+ result.startTime = parseIcsDate(event, calendar, "dtstart")
+ result.endTime = parseIcsDate(event, calendar, "dtend")
+ result.attendees = extractAttendees(event)
+ } catch {
+ return result
+ }
+ return result
}
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index ee947dd2e..b3091cd32 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -580,11 +580,15 @@ export type UpdateEmailStatusRequest = z.infer<
typeof UpdateEmailStatusRequestSchema
>;
+const MeetingTimeSchema = z.iso.datetime()
+ .transform(value => new Date(value).toISOString())
+ .nullable();
+
export const MeetingInfoSchema = z.object({
title: z.string(),
meetingUrl: z.string(),
- startTime: z.string().nullable(),
- endTime: z.string().nullable(),
+ startTime: MeetingTimeSchema,
+ endTime: MeetingTimeSchema,
attendees: z.array(z.object({ name: z.string(), email: z.string() })),
});
diff --git a/src/web/src/app/api/email/notify/route.test.ts b/src/web/src/app/api/email/notify/route.test.ts
index 789574e26..49be6f288 100644
--- a/src/web/src/app/api/email/notify/route.test.ts
+++ b/src/web/src/app/api/email/notify/route.test.ts
@@ -1,5 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest"
import { NextRequest } from "next/server"
+import { parseIcs } from "@alook/shared"
const mocks = vi.hoisted(() => ({
agent: vi.fn(), email: vi.fn(), meeting: vi.fn(), broadcast: vi.fn(), invalidate: vi.fn(),
@@ -23,6 +24,36 @@ vi.mock("@/lib/cache", async importOriginal => ({
}))
import { POST } from "./route"
+const ANCIENT_MONTHLY_ZONE = `BEGIN:VTIMEZONE
+TZID:Ancient/Monthly
+BEGIN:DAYLIGHT
+DTSTART:10000101T000000
+TZOFFSETFROM:+0000
+TZOFFSETTO:+0100
+RRULE:FREQ=MONTHLY;BYMONTHDAY=1
+END:DAYLIGHT
+BEGIN:STANDARD
+DTSTART:10000115T000000
+TZOFFSETFROM:+0100
+TZOFFSETTO:+0000
+RRULE:FREQ=MONTHLY;BYMONTHDAY=15
+END:STANDARD
+END:VTIMEZONE`
+
+const FINITE_ONE_DAY_ZONE = `BEGIN:VTIMEZONE
+TZID:Finite/OneDay
+BEGIN:DAYLIGHT
+DTSTART:20260601T000000
+TZOFFSETFROM:+0000
+TZOFFSETTO:+0100
+END:DAYLIGHT
+BEGIN:STANDARD
+DTSTART:20260602T000000
+TZOFFSETFROM:+0100
+TZOFFSETTO:+0000
+END:STANDARD
+END:VTIMEZONE`
+
const body = {
agentId: "a1", workspaceId: "ws1", r2Key: "emails/fixture/raw",
from: "[email protected]", to: "[email protected]", subject: "Stored message",
@@ -53,23 +84,46 @@ describe("inbound email after legacy execution removal", () => {
expect(mocks.invalidate).toHaveBeenCalledTimes(2)
})
- it.each([true, false])("retains meeting records for whitelisted=%s mail", async isWhitelisted => {
- const response = await POST(request({ ...body, isWhitelisted, meetingInfo: {
- title: "Planning", meetingUrl: "https://meet.example.test/room", startTime: "2026-11-01T10:00:00Z",
- endTime: null, attendees: [{ name: "Guest", email: "[email protected]" }],
- } }))
+ it.each([
+ { isWhitelisted: true, start: "DTSTART:20261101T100000Z", scheduledAt: "2026-11-01T10:00:00.000Z", status: "scheduled" },
+ { isWhitelisted: false, start: "DTSTART:20261101T100000Z", scheduledAt: "2026-11-01T10:00:00.000Z", status: "pending" },
+ { isWhitelisted: true, start: "DTSTART;TZID=Ancient/Monthly:20260610T100000", zone: ANCIENT_MONTHLY_ZONE, scheduledAt: null, status: "pending" },
+ { isWhitelisted: true, start: "", scheduledAt: null, status: "pending" },
+ { isWhitelisted: false, start: "", scheduledAt: null, status: "pending" },
+ { isWhitelisted: true, start: "DTSTART;TZID=Finite/OneDay:20260601T120000", zone: FINITE_ONE_DAY_ZONE, scheduledAt: null, status: "pending" },
+ ])("retains meeting records for whitelisted=$isWhitelisted and start=$start", async ({ isWhitelisted, start, zone = "", scheduledAt, status }) => {
+ const meetingInfo = parseIcs([
+ "BEGIN:VCALENDAR", "VERSION:2.0", zone, "BEGIN:VEVENT", start, "SUMMARY:Planning",
+ "LOCATION:https://meet.google.com/abc-defg-hij",
+ "ATTENDEE;CN=Guest:mailto:[email protected]", "END:VEVENT", "END:VCALENDAR",
+ ].filter(Boolean).join("\r\n"))
+ const response = await POST(request({ ...body, isWhitelisted, meetingInfo }))
expect(response.status).toBe(200)
+ expect(mocks.email).toHaveBeenCalledWith({}, expect.objectContaining({ r2Key: body.r2Key, subject: body.subject }))
expect(mocks.meeting).toHaveBeenCalledWith({}, expect.objectContaining({
agentId: "a1", workspaceId: "ws1", title: "Planning", participants: ["[email protected]"],
- status: isWhitelisted ? "scheduled" : "pending", isWhitelisted,
+ status, isWhitelisted, scheduledAt,
}))
expect(mocks.task).not.toHaveBeenCalled()
})
- it("rejects invalid notification input before any data write", async () => {
- const response = await POST(request({ agentId: "a1" }))
+ it.each([
+ { name: "missing notification fields", payload: { agentId: "a1" } },
+ ...[
+ { startTime: "2026-11-01T10:00:00", endTime: null },
+ { startTime: "2026-02-30T10:00:00Z", endTime: null },
+ { startTime: "2026-11-01T10:00:00+01:00", endTime: null },
+ { startTime: null, endTime: "2026-11-01T11:00:00" },
+ ].map(times => ({ name: JSON.stringify(times), payload: { ...body, meetingInfo: {
+ title: "Planning", meetingUrl: "https://meet.google.com/abc-defg-hij", attendees: [], ...times,
+ } } })),
+ ])("rejects invalid notification $name before any data write", async ({ payload }) => {
+ const response = await POST(request(payload))
expect(response.status).toBe(400)
+ expect(mocks.agent).not.toHaveBeenCalled()
expect(mocks.email).not.toHaveBeenCalled()
+ expect(mocks.meeting).not.toHaveBeenCalled()
+ expect(mocks.conversation).not.toHaveBeenCalled()
expect(mocks.task).not.toHaveBeenCalled()
})
diff --git a/src/web/src/app/api/email/notify/route.ts b/src/web/src/app/api/email/notify/route.ts
index bbfc86798..c35f29c72 100644
--- a/src/web/src/app/api/email/notify/route.ts
+++ b/src/web/src/app/api/email/notify/route.ts
@@ -37,7 +37,7 @@ export const POST = withEnv(async (req: NextRequest, ctx) => {
workspaceId: body.workspaceId,
title: mi.title || body.subject,
meetingUrl: mi.meetingUrl,
- status: body.isWhitelisted ? MeetingStatus.SCHEDULED : MeetingStatus.PENDING,
+ status: body.isWhitelisted && mi.startTime !== null ? MeetingStatus.SCHEDULED : MeetingStatus.PENDING,
fromEmail: body.from,
isWhitelisted: body.isWhitelisted,
participants: mi.attendees.map(a => a.email),