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
fix(soup): Proper email querying (#1654)
Evan Hutnikae421e123611
diff --git a/js/app/packages/app/component/next-soup/filters/inbox-query-filters.ts b/js/app/packages/app/component/next-soup/filters/inbox-query-filters.tsindex c749460675..e7707b22e1 100644--- a/js/app/packages/app/component/next-soup/filters/inbox-query-filters.ts+++ b/js/app/packages/app/component/next-soup/filters/inbox-query-filters.ts@@ -5,6 +5,7 @@ import { EXCLUDE } from './filters';const INBOX_DONE = false;const INBOX_IMPORTANCE = true;const INBOX_TASK_BYPASS = true;+const OTHER_IMPORTANCE = false;const isNonEmptyObject = (obj: Record<string, unknown>) =>Object.keys(obj).length > 0;@@ -98,9 +99,11 @@ export function removeInboxQueryFilters(}: undefined;+ // Strip `importance` if it was set by Inbox (true) or Other (false).+ // If importance was set externally, leave email_filters untouched.const { importance, ...emailRest } = filters.email_filters ?? {};const email_filters =- importance === INBOX_IMPORTANCE+ importance === INBOX_IMPORTANCE || importance === OTHER_IMPORTANCE? isNonEmptyObject(emailRest)? emailRest: undefineddiff --git a/js/app/packages/app/component/next-soup/search-utils.ts b/js/app/packages/app/component/next-soup/search-utils.tsindex e842a68384..4eeb5edb5c 100644--- a/js/app/packages/app/component/next-soup/search-utils.ts+++ b/js/app/packages/app/component/next-soup/search-utils.ts@@ -3,6 +3,13 @@ import { mergeAdjacentMacroEmTags } from '@core/util/searchHighlight';import { createFreshSearch } from '@core/util/freshSort';import type { EntityData, WithSearch } from '@entity';import type { FilterConfig } from './filters/create-filter-state';++export const getValidSearchFilters = <T>(+ filters: readonly FilterConfig<T>[]+) => {+ return filters.filter((f) => f.id !== 'explicit-noise');+};+/** Takes a list of entity pools and returns a list of unique entities that are present in all pools, deduplicating by id */export function intersectEntityPools(pools: readonly EntityData[][]@@ -36,12 +43,6 @@ export function intersectEntityPools(return result;}-export const getValidSearchFilters = <T>(- filters: readonly FilterConfig<T>[]-) => {- return filters.filter((f) => f.id !== 'explicit-noise');-};-/** Adds name highlight to item list based on fuzzy match */export const nameFuzzySearchFilter = (items: EntityData[],diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-toolbar.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-toolbar.tsxindex f54d56937c..9deb342156 100644--- a/js/app/packages/app/component/next-soup/soup-view/soup-toolbar.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/soup-toolbar.tsx@@ -151,6 +151,9 @@ const SoupFilters = () => {setQueryFilters(removeInboxQueryFilters(filters));};+ // Batch filter + query updates so the prefetch effect in soup-view-context+ // sees the final query filters and active filter state in a single tick,+ // avoiding intermediate re-renders with mismatched query keys.const toggleFocus = (id: 'signal' | 'noise') => {const comb = { id, isActive: soup.filters.isActive(id) };diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsxindex b94f206c52..e4ab0da73b 100644--- a/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx@@ -154,10 +154,16 @@ export const SoupViewContextProvider: FlowComponent<};});+ // Signal/noise only show emails in the user's inbox (aka not-done emails). All shows all emails.+ const emailView = () =>+ soup.filters.isActive('signal') || soup.filters.isActive('noise')+ ? 'inbox'+ : 'all';+const soupBody = createMemo((): SoupBody => ({...queryFilters(),- emailView: soup.filters.isActive('signal') ? 'inbox' : 'all',+ emailView: emailView(),}));diff --git a/js/app/packages/app/component/settings/Inbox.tsx b/js/app/packages/app/component/settings/Inbox.tsxindex f47418c7d2..69aaf452cd 100644--- a/js/app/packages/app/component/settings/Inbox.tsx+++ b/js/app/packages/app/component/settings/Inbox.tsx@@ -40,4 +40,3 @@ export function Inbox() {</div>);}-diff --git a/rust/cloud-storage/email/fixtures/email_dynamic_query.sql b/rust/cloud-storage/email/fixtures/email_dynamic_query.sqlindex 9ec08a1170..7fc865b1a6 100644--- a/rust/cloud-storage/email/fixtures/email_dynamic_query.sql+++ b/rust/cloud-storage/email/fixtures/email_dynamic_query.sql@@ -62,7 +62,11 @@ VALUES-- Thread 7: Inbox with CC to [email protected]('20000007-0000-0000-0000-000000000007', 'thread7', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',- true, false, '2024-01-09 04:00:00+00', NULL, '2024-01-09 04:00:00+00', NOW(), NOW());+ true, false, '2024-01-09 04:00:00+00', NULL, '2024-01-09 04:00:00+00', NOW(), NOW()),++ -- Thread 8: Draft with depriority label (CATEGORY_UPDATES) - tests that DRAFT priority overrides depriority+ ('20000008-0000-0000-0000-000000000008', 'thread8', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',+ false, false, NULL, NULL, '2024-01-08 03:00:00+00', NOW(), NOW());-- Insert test messagesINSERT INTO email_messages (@@ -112,7 +116,13 @@ VALUES('30000007-0000-0000-0000-000000000007', '20000007-0000-0000-0000-000000000007','aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'msg7', '40000002-0000-0000-0000-000000000002','Team Update', 'FYI for everyone', '2024-01-09 04:00:00+00',- false, false, false, false, NOW(), NOW());+ false, false, false, false, NOW(), NOW()),++ -- Message 8: Draft with depriority label from [email protected]+ ('30000008-0000-0000-0000-000000000008', '20000008-0000-0000-0000-000000000008',+ 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'msg8', '40000003-0000-0000-0000-000000000003',+ 'Draft With Updates Label', 'Draft that also has a depriority label', '2024-01-08 03:00:00+00',+ true, false, false, false, NOW(), NOW());-- Insert message recipientsINSERT INTO email_message_recipients (message_id, contact_id, recipient_type)@@ -137,7 +147,10 @@ VALUES-- Message 7: To [email protected], CC [email protected]('30000007-0000-0000-0000-000000000007', '40000004-0000-0000-0000-000000000004', 'TO'),- ('30000007-0000-0000-0000-000000000007', '40000003-0000-0000-0000-000000000003', 'CC');+ ('30000007-0000-0000-0000-000000000007', '40000003-0000-0000-0000-000000000003', 'CC'),++ -- Message 8: To [email protected]+ ('30000008-0000-0000-0000-000000000008', '40000004-0000-0000-0000-000000000004', 'TO');-- Insert message-label relationshipsINSERT INTO email_message_labels (message_id, label_id)@@ -171,4 +184,7 @@ VALUES-- Message 6 (thread 6): CATEGORY_UPDATES (depriority label, no priority → NOT important)('30000006-0000-0000-0000-000000000006', '10000009-0000-0000-0000-000000000009'),-- Message 7 (thread 7): CATEGORY_PROMOTIONS (depriority label, no priority → NOT important)- ('30000007-0000-0000-0000-000000000007', '10000010-0000-0000-0000-000000000010');+ ('30000007-0000-0000-0000-000000000007', '10000010-0000-0000-0000-000000000010'),+ -- Message 8 (thread 8): DRAFT + CATEGORY_UPDATES (draft with depriority label → important because DRAFT is priority)+ ('30000008-0000-0000-0000-000000000008', '10000005-0000-0000-0000-000000000005'),+ ('30000008-0000-0000-0000-000000000008', '10000009-0000-0000-0000-000000000009');diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic.rsindex c8ed440643..5d08cb85c9 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/dynamic.rs@@ -131,12 +131,11 @@ fn build_message_email_filter(ast: &Expr<EmailLiteral>) -> String {// Signal: has a priority label OR does not have a depriority labelr#"(m.is_draft = TRUE- OR- EXISTS (+ OR EXISTS (SELECT 1 FROM email_message_labels mlJOIN email_labels l ON ml.label_id = l.idWHERE ml.message_id = m.id- AND l.name IN ('CATEGORY_PERSONAL', 'SENT')+ AND l.name IN ('CATEGORY_PERSONAL', 'SENT', 'DRAFT'))OR NOT EXISTS (SELECT 1 FROM email_message_labels ml@@ -154,7 +153,7 @@ fn build_message_email_filter(ast: &Expr<EmailLiteral>) -> String {SELECT 1 FROM email_message_labels mlJOIN email_labels l ON ml.label_id = l.idWHERE ml.message_id = m.id- AND l.name IN ('CATEGORY_PERSONAL', 'SENT')+ AND l.name IN ('CATEGORY_PERSONAL', 'SENT', 'DRAFT'))AND EXISTS (SELECT 1 FROM email_message_labels ml@@ -254,9 +253,7 @@ fn build_view_thread_filter(view: &PreviewView) -> String {/// Builds message-level WHERE conditions based on the view typefn build_view_message_filter(view: &PreviewView, link_id_param: &str) -> String {match view {- PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox) => {- " AND m.is_draft = FALSE".to_string()- }+ PreviewView::StandardLabel(PreviewViewStandardLabel::Inbox) => String::new(),PreviewView::StandardLabel(PreviewViewStandardLabel::Sent) => {" AND m.is_sent = TRUE".to_string()}diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/test.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/test.rsindex 5f958ab3f0..8437b132b5 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/test.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/test.rs@@ -223,13 +223,12 @@ async fn test_dynamic_query_drafts_view(pool: Pool<Postgres>) -> anyhow::Result<let results =dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;- // Should get draft messages (thread 3)- assert_eq!(results.len(), 1, "Drafts view should return 1 thread");- assert_eq!(- results[0].id.to_string(),- "20000003-0000-0000-0000-000000000003"+ // Should get draft messages (threads 3 and 8)+ assert_eq!(results.len(), 2, "Drafts view should return 2 threads");+ assert!(+ results.iter().all(|r| r.is_draft),+ "All messages should be drafts");- assert!(results[0].is_draft, "Message should be marked as draft");Ok(())}@@ -276,8 +275,8 @@ async fn test_dynamic_query_important_view(pool: Pool<Postgres>) -> anyhow::Resulet results =dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;- // Should get important messages and drafts (threads 5 and 3)- assert_eq!(results.len(), 2, "Important view should return 2 threads");+ // Should get important messages and drafts (threads 3, 5, and 8)+ assert_eq!(results.len(), 3, "Important view should return 3 threads");let result_ids: std::collections::HashSet<String> =results.iter().map(|r| r.id.to_string()).collect();@@ -290,6 +289,10 @@ async fn test_dynamic_query_important_view(pool: Pool<Postgres>) -> anyhow::Resuresult_ids.contains("20000005-0000-0000-0000-000000000005"),"Should include important thread 5");+ assert!(+ result_ids.contains("20000008-0000-0000-0000-000000000008"),+ "Should include draft thread 8"+ );assert!(results.iter().all(|r| r.is_important));Ok(())@@ -309,8 +312,8 @@ async fn test_static_important_query_includes_drafts(pool: Pool<Postgres>) -> anassert_eq!(results.len(),- 2,- "Static important query should return both important and draft threads"+ 3,+ "Static important query should return important and draft threads");let result_ids: std::collections::HashSet<String> =@@ -324,6 +327,10 @@ async fn test_static_important_query_includes_drafts(pool: Pool<Postgres>) -> anresult_ids.contains("20000005-0000-0000-0000-000000000005"),"Should include important thread 5");+ assert!(+ result_ids.contains("20000008-0000-0000-0000-000000000008"),+ "Should include draft thread 8"+ );assert!(results.iter().all(|r| r.is_important));assert!(results.iter().any(|r| r.is_draft));@@ -528,13 +535,13 @@ async fn test_dynamic_query_drafts_with_recipient_filter(let results =dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;- // Should get draft messages to [email protected] (thread 3)+ // Should get draft messages to [email protected] (threads 3 and 8)assert_eq!(results.len(),- 1,- "Should return 1 draft thread to [email protected]"+ 2,+ "Should return 2 draft threads to [email protected]");- assert!(results[0].is_draft, "Should be a draft");+ assert!(results.iter().all(|r| r.is_draft), "All should be drafts");Ok(())}@@ -668,11 +675,12 @@ async fn test_dynamic_query_pagination(pool: Pool<Postgres>) -> anyhow::Result<(// The fixture has:// Thread 1 (msg 1): INBOX + CATEGORY_PERSONAL → important (has priority label)// Thread 2 (msg 2): SENT → important (has priority label)-// Thread 3 (msg 3): DRAFT → important (no depriority label)+// Thread 3 (msg 3): DRAFT → important (DRAFT is a priority label)// Thread 4 (msg 4): STARRED + INBOX → important (no depriority label)// Thread 5 (msg 5): IMPORTANT + INBOX → important (no depriority label)// Thread 6 (msg 6): Work + CATEGORY_UPDATES → NOT important (depriority, no priority)// Thread 7 (msg 7): INBOX + CATEGORY_PROMOTIONS → NOT important (depriority, no priority)+// Thread 8 (msg 8): DRAFT + CATEGORY_UPDATES → important (DRAFT priority overrides depriority)#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))@@ -690,11 +698,11 @@ async fn test_dynamic_query_with_importance_filter(pool: Pool<Postgres>) -> anyhlet results =dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;- // Threads 1 (CATEGORY_PERSONAL), 2 (SENT), 3 (no depriority), 4 (no depriority), 5 (no depriority)+ // Threads 1 (CATEGORY_PERSONAL), 2 (SENT), 3 (DRAFT), 4 (no depriority), 5 (no depriority), 8 (DRAFT overrides depriority)assert_eq!(results.len(),- 5,- "importance=true should return 5 important threads"+ 6,+ "importance=true should return 6 important threads");let result_ids: std::collections::HashSet<String> =@@ -710,7 +718,7 @@ async fn test_dynamic_query_with_importance_filter(pool: Pool<Postgres>) -> anyh);assert!(result_ids.contains("20000003-0000-0000-0000-000000000003"),- "Should include thread 3 (no depriority)"+ "Should include thread 3 (DRAFT)");assert!(result_ids.contains("20000004-0000-0000-0000-000000000004"),@@ -720,6 +728,10 @@ async fn test_dynamic_query_with_importance_filter(pool: Pool<Postgres>) -> anyhresult_ids.contains("20000005-0000-0000-0000-000000000005"),"Should include thread 5 (no depriority)");+ assert!(+ result_ids.contains("20000008-0000-0000-0000-000000000008"),+ "Should include thread 8 (DRAFT overrides CATEGORY_UPDATES depriority)"+ );// Threads 6 and 7 should be excluded (depriority labels, no priority)assert!(@@ -741,10 +753,11 @@ async fn test_dynamic_query_with_importance_filter(pool: Pool<Postgres>) -> anyhdynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;// Threads 6 (CATEGORY_UPDATES) and 7 (CATEGORY_PROMOTIONS)+ // Thread 8 has CATEGORY_UPDATES but is excluded because DRAFT is a priority labelassert_eq!(results.len(),2,- "importance=false should return 2 unimportant threads"+ "importance=false should return 2 unimportant threads (drafts excluded)");let result_ids: std::collections::HashSet<String> =@@ -758,11 +771,59 @@ async fn test_dynamic_query_with_importance_filter(pool: Pool<Postgres>) -> anyhresult_ids.contains("20000007-0000-0000-0000-000000000007"),"Should include thread 7 (CATEGORY_PROMOTIONS)");+ assert!(+ !result_ids.contains("20000008-0000-0000-0000-000000000008"),+ "Should exclude thread 8 (DRAFT priority overrides CATEGORY_UPDATES depriority)"+ );}Ok(())}+// Inbox view + importance=false: the "Other" toggle in the UI.+// Thread 6 (CATEGORY_UPDATES) has importance=false but inbox_visible=false → excluded by Inbox view.+// Thread 7 (CATEGORY_PROMOTIONS) has importance=false AND inbox_visible=true → included.+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))+)]+async fn test_dynamic_query_inbox_view_with_importance_false(+ 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::Importance(false)));+ let query = Query::new(None, SimpleSortMethod::UpdatedAt, filter);++ let results =+ dynamic::dynamic_email_thread_cursor(&pool, &link_id, limit, &view, query).await?;++ // Only thread 7: inbox_visible=true AND importance=false+ assert_eq!(+ results.len(),+ 1,+ "Inbox view with importance=false should return only 1 thread"+ );++ assert_eq!(+ results[0].id.to_string(),+ "20000007-0000-0000-0000-000000000007",+ "Should be thread 7 (CATEGORY_PROMOTIONS, inbox_visible=true)"+ );++ // Thread 6 should be excluded (inbox_visible=false)+ assert!(+ !results+ .iter()+ .any(|r| r.id.to_string() == "20000006-0000-0000-0000-000000000006"),+ "Should exclude thread 6 (inbox_visible=false)"+ );++ Ok(())+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))@@ -821,3 +882,93 @@ async fn test_dynamic_query_thread_id_with_sender_filter(Ok(())}++// Thread 8 is a draft with CATEGORY_UPDATES (depriority label).+// DRAFT is a priority label, so it should appear in importance=true results+// even though it has a depriority label.+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))+)]+async fn test_importance_true_includes_drafts_with_depriority_label(+ 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::Importance(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();++ // Thread 8 has DRAFT + CATEGORY_UPDATES. DRAFT is a priority label,+ // so it should be included despite the depriority label.+ assert!(+ result_ids.contains("20000008-0000-0000-0000-000000000008"),+ "importance=true should include draft thread 8 even though it has CATEGORY_UPDATES"+ );++ // Thread 3 is a plain draft (no depriority label) — should also be included+ assert!(+ result_ids.contains("20000003-0000-0000-0000-000000000003"),+ "importance=true should include draft thread 3"+ );++ Ok(())+}++// Thread 8 is a draft with CATEGORY_UPDATES (depriority label).+// DRAFT is a priority label, so it should NOT appear in importance=false results.+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("email_dynamic_query"))+)]+async fn test_importance_false_excludes_drafts(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::Importance(false)));+ 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();++ // Thread 8 has CATEGORY_UPDATES (depriority) but also DRAFT (priority).+ // Since DRAFT is a priority label, it should be excluded from importance=false.+ assert!(+ !result_ids.contains("20000008-0000-0000-0000-000000000008"),+ "importance=false should exclude draft thread 8 despite having CATEGORY_UPDATES"+ );++ // Thread 3 is a plain draft — should also be excluded (DRAFT is a priority label)+ assert!(+ !result_ids.contains("20000003-0000-0000-0000-000000000003"),+ "importance=false should exclude draft thread 3"+ );++ // Only non-draft threads with depriority labels should appear+ assert!(+ result_ids.contains("20000006-0000-0000-0000-000000000006"),+ "Should include thread 6 (CATEGORY_UPDATES, not a draft)"+ );+ assert!(+ result_ids.contains("20000007-0000-0000-0000-000000000007"),+ "Should include thread 7 (CATEGORY_PROMOTIONS, not a draft)"+ );+ assert_eq!(+ results.len(),+ 2,+ "Only non-draft depriority threads should appear"+ );++ Ok(())+}