Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(email): add calendar_only filter and Calendar tab (#2820)
Evan Hutnikfdd038942015
diff --git a/js/app/packages/app/component/app-sidebar/soup-filter-presets.ts b/js/app/packages/app/component/app-sidebar/soup-filter-presets.tsindex 0b05ea88af..c5bd81cfc7 100644--- a/js/app/packages/app/component/app-sidebar/soup-filter-presets.ts+++ b/js/app/packages/app/component/app-sidebar/soup-filter-presets.ts@@ -33,6 +33,15 @@ export const NOISE_QUERY_FILTERS = {emailView: 'inbox' as const,};+/** Query filters for the "Calendar" tab — returns only threads with an iCalendar attachment. */+export const CALENDAR_QUERY_FILTERS = {+ email_filters: {+ calendar_only: true as const,+ shared: SharedEmailFilter.exclude,+ },+ emailView: 'inbox' as const,+};+export type SoupFiltersPreset = {queryFilters: SoupBody;clientFilters: {@@ -142,6 +151,13 @@ export const VIEW_TAB_PRESETS: Record<ListView, ViewTabConfig> = {},clientFilters: { and: ['email', 'no-drafts'] },}),+ calendar: () => ({+ queryFilters: {+ ...QUERY_FILTERS.email,+ ...CALENDAR_QUERY_FILTERS,+ },+ clientFilters: { and: ['email', 'no-drafts'] },+ }),drafts: () => ({queryFilters: {...QUERY_FILTERS.email,diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view-tabs.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view-tabs.tsxindex ac57e0293d..f46cc959c2 100644--- a/js/app/packages/app/component/next-soup/soup-view/soup-view-tabs.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view-tabs.tsx@@ -43,6 +43,7 @@ export const VIEW_TAB_LISTS: Record<TabbedListView, TabItem[]> = {mail: [{ value: 'important', label: 'Signal' },{ value: 'noise', label: 'Noise' },+ { value: 'calendar', label: 'Calendar' },{ value: 'sent', label: 'Sent' },{ value: 'drafts', label: 'Drafts' },{ value: 'shared', label: 'Shared' },diff --git a/js/app/packages/service-clients/service-search/generated/models/emailFilters.ts b/js/app/packages/service-clients/service-search/generated/models/emailFilters.tsindex 6aaebc5d33..1559fa83b8 100644--- a/js/app/packages/service-clients/service-search/generated/models/emailFilters.ts+++ b/js/app/packages/service-clients/service-search/generated/models/emailFilters.ts@@ -4,6 +4,7 @@* search_service* OpenAPI spec version: 0.1.0*/+import type { EmailFiltersCalendarOnly } from './emailFiltersCalendarOnly';import type { EmailFiltersImportance } from './emailFiltersImportance';import type { NotificationFilters } from './notificationFilters';import type { SharedEmailFilter } from './sharedEmailFilter';@@ -14,6 +15,10 @@ import type { SharedEmailFilter } from './sharedEmailFilter';export interface EmailFilters {/** Email BCC addresses to filter by. Examples: ['[email protected]']. Empty if not filtering by BCC. */bcc?: string[];+ /** When `Some(true)`, only include threads that have at least one message+with an iCalendar attachment (`.ics` filename or `application/ics` mime+type). `Some(false)` and `None` apply no constraint. */+ calendar_only?: EmailFiltersCalendarOnly;/** Email CC addresses to filter by. Examples: ['[email protected]']. Empty if not filtering by CC. */cc?: string[];/** Email thread IDs to filter by. Examples: ['thread-uuid-1']. Empty to search all threads. */diff --git a/js/app/packages/service-clients/service-search/generated/models/emailFiltersCalendarOnly.ts b/js/app/packages/service-clients/service-search/generated/models/emailFiltersCalendarOnly.tsnew file mode 100644index 0000000000..239a6fe6fc--- /dev/null+++ b/js/app/packages/service-clients/service-search/generated/models/emailFiltersCalendarOnly.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * search_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * When `Some(true)`, only include threads that have at least one message+with an iCalendar attachment (`.ics` filename or `application/ics` mime+type). `Some(false)` and `None` apply no constraint.+ */+export type EmailFiltersCalendarOnly = boolean | null;diff --git a/js/app/packages/service-clients/service-search/generated/models/index.ts b/js/app/packages/service-clients/service-search/generated/models/index.tsindex 073b6eab0a..ea3d48a6f5 100644--- a/js/app/packages/service-clients/service-search/generated/models/index.ts+++ b/js/app/packages/service-clients/service-search/generated/models/index.ts@@ -82,6 +82,7 @@ export * from './documentSearchResultRawContent';export * from './documentSearchResultScore';export * from './documentSubType';export * from './emailFilters';+export * from './emailFiltersCalendarOnly';export * from './emailFiltersImportance';export * from './emailSearchParticipant';export * from './emailSearchParticipantName';diff --git a/js/app/packages/service-clients/service-search/openapi.json b/js/app/packages/service-clients/service-search/openapi.jsonindex e6f7d65297..36103a4f88 100644--- a/js/app/packages/service-clients/service-search/openapi.json+++ b/js/app/packages/service-clients/service-search/openapi.json@@ -928,6 +928,10 @@},"description": "Email BCC addresses to filter by. Examples: ['[email protected]']. Empty if not filtering by BCC."},+ "calendar_only": {+ "type": ["boolean", "null"],+ "description": "When `Some(true)`, only include threads that have at least one message\nwith an iCalendar attachment (`.ics` filename or `application/ics` mime\ntype). `Some(false)` and `None` apply no constraint."+ },"cc": {"type": "array","items": {diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/emailFilters.ts b/js/app/packages/service-clients/service-storage/generated/schemas/emailFilters.tsindex 91767a9100..70e1bf9d43 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/emailFilters.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/emailFilters.ts@@ -4,6 +4,7 @@* document_storage_service* OpenAPI spec version: 0.1.0*/+import type { EmailFiltersCalendarOnly } from './emailFiltersCalendarOnly';import type { EmailFiltersImportance } from './emailFiltersImportance';import type { NotificationFilters } from './notificationFilters';import type { SharedEmailFilter } from './sharedEmailFilter';@@ -14,6 +15,10 @@ import type { SharedEmailFilter } from './sharedEmailFilter';export interface EmailFilters {/** Email BCC addresses to filter by. Examples: ['[email protected]']. Empty if not filtering by BCC. */bcc?: string[];+ /** When `Some(true)`, only include threads that have at least one message+with an iCalendar attachment (`.ics` filename or `application/ics` mime+type). `Some(false)` and `None` apply no constraint. */+ calendar_only?: EmailFiltersCalendarOnly;/** Email CC addresses to filter by. Examples: ['[email protected]']. Empty if not filtering by CC. */cc?: string[];/** Email thread IDs to filter by. Examples: ['thread-uuid-1']. Empty to search all threads. */diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/emailFiltersCalendarOnly.ts b/js/app/packages/service-clients/service-storage/generated/schemas/emailFiltersCalendarOnly.tsnew file mode 100644index 0000000000..44ff8691c5--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/emailFiltersCalendarOnly.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * When `Some(true)`, only include threads that have at least one message+with an iCalendar attachment (`.ics` filename or `application/ics` mime+type). `Some(false)` and `None` apply no constraint.+ */+export type EmailFiltersCalendarOnly = boolean | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.tsindex e62b70524d..8c2eda9849 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts@@ -291,6 +291,7 @@ export * from './editPdfPlaceableCommentAnchorRequestWidthPct';export * from './editPdfPlaceableCommentAnchorRequestXPct';export * from './editPdfPlaceableCommentAnchorRequestYPct';export * from './emailFilters';+export * from './emailFiltersCalendarOnly';export * from './emailFiltersImportance';export * from './emptyResponse';export * from './entityFilterAst';diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex 6518db4fae..44b9a62526 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -5295,6 +5295,12 @@ export const postItemsSoupBody = zod.describe("Email BCC addresses to filter by. Examples: ['[email protected]']. Empty if not filtering by BCC."),+ calendar_only: zod+ .boolean()+ .nullish()+ .describe(+ 'When `Some(true)`, only include threads that have at least one message\nwith an iCalendar attachment (`.ics` filename or `application\/ics` mime\ntype). `Some(false)` and `None` apply no constraint.'+ ),cc: zod.array(zod.string()).optional()diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex cb97f21c1f..a7b758e97e 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -7865,6 +7865,10 @@},"description": "Email BCC addresses to filter by. Examples: ['[email protected]']. Empty if not filtering by BCC."},+ "calendar_only": {+ "type": ["boolean", "null"],+ "description": "When `Some(true)`, only include threads that have at least one message\nwith an iCalendar attachment (`.ics` filename or `application/ics` mime\ntype). `Some(false)` and `None` apply no constraint."+ },"cc": {"type": "array","items": {diff --git a/rust/cloud-storage/email/fixtures/email_dynamic_query_calendar.sql b/rust/cloud-storage/email/fixtures/email_dynamic_query_calendar.sqlnew file mode 100644index 0000000000..002c766c14--- /dev/null+++ b/rust/cloud-storage/email/fixtures/email_dynamic_query_calendar.sql@@ -0,0 +1,35 @@+-- Calendar attachments fixture for testing the calendar_only filter.+-- Layers on top of `email_dynamic_query` — adds iCalendar / non-iCalendar+-- attachments to a subset of the existing threads.+--+-- Expected matches for calendar_only=true:+-- Thread 1 — .ics filename+-- Thread 2 — .ics filename (sent)+-- Thread 4 — application/ics mime (non-.ics filename)+-- Thread 5 — thread has both a .pdf and an .ics attachment on the same message+-- Not matched (have no attachments or only non-calendar attachments):+-- Thread 3, 6, 7, 8, 9, 10, 11++INSERT INTO email_attachments (id, message_id, filename, mime_type, created_at)+VALUES+ -- Thread 1 (inbox, from john): .ics filename → match+ ('90000001-0000-0000-0000-000000000001', '30000001-0000-0000-0000-000000000001',+ 'invite.ics', 'text/calendar', NOW()),++ -- Thread 2 (sent): .ics filename → match+ ('90000002-0000-0000-0000-000000000002', '30000002-0000-0000-0000-000000000002',+ 'event.ics', 'text/calendar', NOW()),++ -- Thread 4 (starred, inbox_visible): application/ics mime with non-.ics filename → match via mime+ ('90000004-0000-0000-0000-000000000004', '30000004-0000-0000-0000-000000000004',+ 'calendar-invite', 'application/ics', NOW()),++ -- Thread 5 (important inbox, from john): a non-calendar PDF AND an .ics → match (at least one)+ ('90000005-0000-0000-0000-000000000005', '30000005-0000-0000-0000-000000000005',+ 'notes.pdf', 'application/pdf', NOW()),+ ('90000005-0000-0000-0000-000000000006', '30000005-0000-0000-0000-000000000005',+ 'team-meeting.ics', 'text/calendar', NOW()),++ -- Thread 7 (inbox with CC): only a non-calendar attachment → should NOT match+ ('90000007-0000-0000-0000-000000000007', '30000007-0000-0000-0000-000000000007',+ 'report.pdf', 'application/pdf', NOW());diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/filters.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/filters.rsindex 491aa6588e..29a097dbc9 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/filters.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/filters.rs@@ -8,9 +8,9 @@ pub(super) fn has_thread_literals(ast: &Expr<EmailLiteral>) -> bool {ast.collapse_frames(|frame| match frame {filter_ast::ExprFrame::And(a, b) | filter_ast::ExprFrame::Or(a, b) => a || b,filter_ast::ExprFrame::Not(a) => a,- filter_ast::ExprFrame::Literal(EmailLiteral::ThreadId(_) | EmailLiteral::ProjectId(_)) => {- true- }+ filter_ast::ExprFrame::Literal(+ EmailLiteral::ThreadId(_) | EmailLiteral::ProjectId(_) | EmailLiteral::CalendarOnly(_),+ ) => true,filter_ast::ExprFrame::Literal(EmailLiteral::Shared(_)) => false,filter_ast::ExprFrame::Literal(_) => false,})@@ -21,7 +21,10 @@ pub(super) fn has_message_literals(ast: &Expr<EmailLiteral>) -> bool {filter_ast::ExprFrame::And(a, b) | filter_ast::ExprFrame::Or(a, b) => a || b,filter_ast::ExprFrame::Not(a) => a,filter_ast::ExprFrame::Literal(- EmailLiteral::ThreadId(_) | EmailLiteral::ProjectId(_) | EmailLiteral::Shared(_),+ EmailLiteral::ThreadId(_)+ | EmailLiteral::ProjectId(_)+ | EmailLiteral::Shared(_)+ | EmailLiteral::CalendarOnly(_),) => false,filter_ast::ExprFrame::Literal(_) => true,})@@ -215,6 +218,7 @@ pub(super) fn build_message_email_filter(ast: &Expr<EmailLiteral>) -> SqlFragmenSqlFragment::raw("TRUE")}filter_ast::ExprFrame::Literal(EmailLiteral::Shared(_)) => SqlFragment::raw("TRUE"),+ filter_ast::ExprFrame::Literal(EmailLiteral::CalendarOnly(_)) => SqlFragment::raw("TRUE"),});fragment.with_and_prefix()@@ -239,6 +243,24 @@ pub(super) fn build_thread_email_filter(ast: &Expr<EmailLiteral>) -> SqlFragmentf}+ filter_ast::ExprFrame::Literal(EmailLiteral::CalendarOnly(true)) => SqlFragment::raw(+ r#"EXISTS (+ SELECT 1+ FROM email_messages m_cal+ JOIN email_attachments a_cal ON a_cal.message_id = m_cal.id+ WHERE m_cal.thread_id = t.id+ AND (+ a_cal.filename ILIKE '%.ics'+ OR a_cal.mime_type = 'text/calendar'+ OR a_cal.mime_type = 'application/ics'+ )+ )"#,+ ),++ filter_ast::ExprFrame::Literal(EmailLiteral::CalendarOnly(false)) => {+ SqlFragment::raw("TRUE")+ }+filter_ast::ExprFrame::Literal(EmailLiteral::Sender(_)| EmailLiteral::Cc(_)diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rsindex fabc7aefca..06765ece1a 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic/tests.rs@@ -582,3 +582,49 @@ fn test_sql_injection_thread_id_not_in_raw_sql() {assert!(result.has_bind_uuid(&id));assert!(result.has_no_raw_containing(&id.to_string()));}++#[test]+fn test_build_thread_email_filter_calendar_only_true_emits_ics_exists() {+ let expr = Expr::Literal(EmailLiteral::CalendarOnly(true));+ let result = build_thread_email_filter(&expr);+ let debug = result.to_debug_sql();++ assert!(debug.contains("EXISTS"));+ assert!(debug.contains("email_attachments"));+ assert!(debug.contains("m_cal.thread_id = t.id"));+ assert!(debug.contains("a_cal.filename ILIKE '%.ics'"));+ assert!(debug.contains("a_cal.mime_type = 'text/calendar'"));+ assert!(debug.contains("a_cal.mime_type = 'application/ics'"));+}++#[test]+fn test_build_thread_email_filter_calendar_only_false_maps_to_true() {+ let expr = Expr::Literal(EmailLiteral::CalendarOnly(false));+ let result = build_thread_email_filter(&expr);+ let debug = result.to_debug_sql();++ assert!(debug.contains("TRUE"));+ assert!(!debug.contains("email_attachments"));+}++#[test]+fn test_build_message_email_filter_maps_calendar_only_to_true() {+ let expr = Expr::Literal(EmailLiteral::CalendarOnly(true));+ let result = build_message_email_filter(&expr);+ let debug = result.to_debug_sql();++ assert!(debug.contains("TRUE"));+ assert!(!debug.contains("email_attachments"));+}++#[test]+fn test_has_thread_literals_true_when_calendar_only_present() {+ let expr = Expr::Literal(EmailLiteral::CalendarOnly(true));+ assert!(has_thread_literals(&expr));+}++#[test]+fn test_has_message_literals_false_when_only_calendar_only() {+ let expr = Expr::Literal(EmailLiteral::CalendarOnly(true));+ assert!(!has_message_literals(&expr));+}diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/dynamic_query.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/dynamic_query.rsindex f40df99040..0fb9ce54fd 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/test/dynamic_query.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test/dynamic_query.rs@@ -1418,6 +1418,200 @@ async fn test_shared_include_returns_own_and_shared_threads(Ok(())}+// ── calendar_only filter tests ──────────────────────────────────────+//+// The email_dynamic_query_calendar fixture attaches iCalendar and non-iCalendar+// attachments to threads 1, 2, 4, 5, 7. Threads 1/2/4/5 should match the+// calendar_only=true predicate; thread 7 and all unattached threads should not.++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query", "email_dynamic_query_calendar")+ )+)]+async fn test_dynamic_query_calendar_only_filter(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::All);+ let limit = 50;++ let filter = Arc::new(Expr::Literal(EmailLiteral::CalendarOnly(true)));+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);++ let results =+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;++ let result_ids: std::collections::HashSet<String> =+ results.iter().map(|r| r.id.to_string()).collect();++ assert!(+ result_ids.contains("20000001-0000-0000-0000-000000000001"),+ "Thread 1 (.ics filename) should match"+ );+ assert!(+ result_ids.contains("20000002-0000-0000-0000-000000000002"),+ "Thread 2 (.ics filename) should match"+ );+ assert!(+ result_ids.contains("20000004-0000-0000-0000-000000000004"),+ "Thread 4 (application/ics mime) should match"+ );+ assert!(+ result_ids.contains("20000005-0000-0000-0000-000000000005"),+ "Thread 5 (one of two attachments is .ics) should match"+ );++ assert!(+ !result_ids.contains("20000003-0000-0000-0000-000000000003"),+ "Thread 3 (no attachments) should not match"+ );+ assert!(+ !result_ids.contains("20000006-0000-0000-0000-000000000006"),+ "Thread 6 (no attachments) should not match"+ );+ assert!(+ !result_ids.contains("20000007-0000-0000-0000-000000000007"),+ "Thread 7 (only a non-calendar pdf attachment) should not match"+ );+ assert!(+ !result_ids.contains("20000008-0000-0000-0000-000000000008"),+ "Thread 8 (no attachments) should not match"+ );++ assert_eq!(+ results.len(),+ 4,+ "Expected exactly 4 matching threads (1, 2, 4, 5), got: {:?}",+ result_ids+ );++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query", "email_dynamic_query_calendar")+ )+)]+async fn test_dynamic_query_calendar_only_inbox_view(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);+ let limit = 50;++ let filter = Arc::new(Expr::Literal(EmailLiteral::CalendarOnly(true)));+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);++ let results =+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;++ let result_ids: std::collections::HashSet<String> =+ results.iter().map(|r| r.id.to_string()).collect();++ // Inbox view restricts to inbox_visible=true AND latest_inbound_message_ts IS NOT NULL.+ // Of the calendar-matching threads (1, 2, 4, 5), only 1, 4, 5 are inbox-visible with an+ // inbound ts. Thread 2 is sent (inbox_visible=false).+ assert!(result_ids.contains("20000001-0000-0000-0000-000000000001"));+ assert!(result_ids.contains("20000004-0000-0000-0000-000000000004"));+ assert!(result_ids.contains("20000005-0000-0000-0000-000000000005"));+ assert!(+ !result_ids.contains("20000002-0000-0000-0000-000000000002"),+ "Thread 2 is sent, not inbox-visible"+ );+ assert!(+ !result_ids.contains("20000007-0000-0000-0000-000000000007"),+ "Thread 7 is inbox but has no .ics attachment"+ );+ assert_eq!(results.len(), 3);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query", "email_dynamic_query_calendar")+ )+)]+async fn test_dynamic_query_calendar_only_combined_with_sender(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::All);+ let limit = 50;++ // calendar_only=true AND [email protected] → {1, 2, 5}. Threads 1, 2, 5 are all+ // from john with an .ics attachment; thread 4 has .ics but is from alice.+ let filter = Arc::new(Expr::and(+ Expr::Literal(EmailLiteral::CalendarOnly(true)),+ Expr::Literal(EmailLiteral::Sender(Email::Complete(+ EmailStr::parse_from_str("[email protected]")?.into_owned(),+ ))),+ ));+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);++ let results =+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?;++ let result_ids: std::collections::HashSet<String> =+ results.iter().map(|r| r.id.to_string()).collect();++ assert!(result_ids.contains("20000001-0000-0000-0000-000000000001"));+ assert!(result_ids.contains("20000002-0000-0000-0000-000000000002"));+ assert!(result_ids.contains("20000005-0000-0000-0000-000000000005"));+ assert!(+ !result_ids.contains("20000004-0000-0000-0000-000000000004"),+ "Thread 4 has .ics but is from alice, not john"+ );+ assert_eq!(results.len(), 3);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(+ path = "../../../../fixtures",+ scripts("email_dynamic_query", "email_dynamic_query_calendar")+ )+)]+async fn test_dynamic_query_calendar_only_false_is_noop(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let link_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")?;+ let view = PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox);+ let limit = 50;++ // calendar_only=false combined with a broad sender filter so the dynamic path is taken.+ // Result set should match the sender filter alone with no additional calendar restriction.+ let with_false = {+ let filter = Arc::new(Expr::and(+ Expr::Literal(EmailLiteral::CalendarOnly(false)),+ Expr::Literal(EmailLiteral::Sender(Email::Partial(+ "example.com".to_string(),+ ))),+ ));+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?+ };+ let baseline = {+ let filter = Arc::new(Expr::Literal(EmailLiteral::Sender(Email::Partial(+ "example.com".to_string(),+ ))));+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query, "").await?+ };++ let with_false_ids: std::collections::HashSet<_> = with_false.iter().map(|r| r.id).collect();+ let baseline_ids: std::collections::HashSet<_> = baseline.iter().map(|r| r.id).collect();+ assert_eq!(with_false_ids, baseline_ids);++ Ok(())+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(diff --git a/rust/cloud-storage/item_filters/src/ast/email.rs b/rust/cloud-storage/item_filters/src/ast/email.rsindex 2082c343a6..f17e6dff2c 100644--- a/rust/cloud-storage/item_filters/src/ast/email.rs+++ b/rust/cloud-storage/item_filters/src/ast/email.rs@@ -37,6 +37,10 @@ pub enum EmailLiteral {NotificationSeen(bool),/// Controls whether shared email threads are included in results.Shared(SharedEmailFilter),+ /// When true, only include threads that have at least one message with an+ /// `.ics` calendar attachment (filename or `application/ics` mime type).+ /// When false, no constraint is applied.+ CalendarOnly(bool),}impl ExpandFrame<EmailLiteral> for EmailFilters {@@ -54,6 +58,7 @@ impl ExpandFrame<EmailLiteral> for EmailFilters {include_labels: _,exclude_labels: _,shared,+ calendar_only,} = input;fn map_email(s: String) -> Email {@@ -101,6 +106,9 @@ impl ExpandFrame<EmailLiteral> for EmailFilters {} else {Some(Expr::Literal(EmailLiteral::Shared(shared)))};+ let calendar_only_node = calendar_only+ .filter(|v| *v)+ .map(|v| Expr::Literal(EmailLiteral::CalendarOnly(v)));Ok([sender_nodes,@@ -113,6 +121,7 @@ impl ExpandFrame<EmailLiteral> for EmailFilters {notification_done_node,notification_seen_node,shared_node,+ calendar_only_node,].into_iter().fold_with(Expr::and))diff --git a/rust/cloud-storage/item_filters/src/lib.rs b/rust/cloud-storage/item_filters/src/lib.rsindex e00210f583..6d75967348 100644--- a/rust/cloud-storage/item_filters/src/lib.rs+++ b/rust/cloud-storage/item_filters/src/lib.rs@@ -246,6 +246,12 @@ pub struct EmailFilters {/// Defaults to "exclude" (only the user's own threads).#[serde(default, skip_serializing_if = "SharedEmailFilter::is_default")]pub shared: SharedEmailFilter,++ /// When `Some(true)`, only include threads that have at least one message+ /// with an iCalendar attachment (`.ics` filename or `application/ics` mime+ /// type). `Some(false)` and `None` apply no constraint.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub calendar_only: Option<bool>,}impl IsEmpty for EmailFilters {@@ -262,6 +268,7 @@ impl IsEmpty for EmailFilters {include_labels,exclude_labels,shared,+ calendar_only,} = self;senders.is_empty()&& cc.is_empty()@@ -274,6 +281,7 @@ impl IsEmpty for EmailFilters {&& include_labels.is_empty()&& exclude_labels.is_empty()&& shared.is_default()+ && !calendar_only.unwrap_or(false)}}diff --git a/rust/cloud-storage/macro_db_client/migrations/20260423120002_idx_email_attachments_calendar.sql b/rust/cloud-storage/macro_db_client/migrations/20260423120002_idx_email_attachments_calendar.sqlnew file mode 100644index 0000000000..f759102a30--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260423120002_idx_email_attachments_calendar.sql@@ -0,0 +1,18 @@+-- no-transaction++-- Partial index to speed up the `calendar_only` email filter.+-- Matches the EXISTS clause in dynamic/filters.rs build_thread_email_filter+-- for EmailLiteral::CalendarOnly(true):+-- filename ILIKE '%.ics' OR mime_type = 'text/calendar' OR mime_type = 'application/ics'.+-- Calendar attachments are sparse (~0.2% of rows), so a partial index is dramatically smaller+-- than indexing the full table and lets the planner cheaply check whether any message in a+-- thread carries an iCalendar attachment.+--+-- This index is typically created ahead of migration via:+-- CREATE INDEX CONCURRENTLY idx_email_attachments_calendar_message_id ...+-- so IF NOT EXISTS makes the migration a no-op when it catches up.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_email_attachments_calendar_message_id+ ON email_attachments (message_id)+ WHERE filename ILIKE '%.ics'+ OR mime_type = 'text/calendar'+ OR mime_type = 'application/ics';