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): Thread metadata in previews (#366)
Evan Hutnikeab8e94de25d
diff --git a/infra/stacks/email-service/index.ts b/infra/stacks/email-service/index.tsindex 636fdc0e7f..232364df1a 100644--- a/infra/stacks/email-service/index.ts+++ b/infra/stacks/email-service/index.ts@@ -251,7 +251,7 @@ const emailService = new EmailService('email-service', {containerEnvVars: [{name: 'RUST_LOG',- value: `email_service=${stack === 'prod' ? 'debug' : 'debug'},email_db_client=${stack === 'prod' ? 'info' : 'debug'},gmail_client=${stack === 'prod' ? 'info' : 'debug'},tower_http=info,insight_service_client=${stack === 'prod' ? 'info' : 'debug'}`,+ value: `email=${stack === 'prod' ? 'debug' : 'debug'},email_service=${stack === 'prod' ? 'debug' : 'debug'},email_db_client=${stack === 'prod' ? 'info' : 'debug'},gmail_client=${stack === 'prod' ? 'info' : 'debug'},tower_http=info,insight_service_client=${stack === 'prod' ? 'info' : 'debug'}`,},{name: 'ENVIRONMENT',diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 910270c395..c91a0c83e6 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -2836,6 +2836,7 @@ dependencies = ["chrono","doppleganger","either",+ "email_utils","filter_ast","frecency","item_filters",diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rsindex 9f76161b42..1dde0d237a 100644--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs@@ -101,6 +101,10 @@ use model::{use models_permissions::share_permission::channel_share_permission::UpdateOperation;use models_soup::chat::SoupChat;use models_soup::document::SoupDocument;+use models_soup::email_thread::{+ SoupAttachment, SoupContact, SoupEmailThreadPreview, SoupEmailThreadPreviewMetadata,+ SoupEnrichedEmailThreadPreview, SoupMacroAttachment,+};use models_soup::item::SoupItem;use models_soup::item::SoupItemType;use models_soup::project::SoupProject;@@ -203,7 +207,6 @@ use utoipa::OpenApi;// /recentsrecents::recently_deleted::handler,-saved_views::create_view_handler,saved_views::get_views_handler,saved_views::delete_view_handler,@@ -280,6 +283,12 @@ use utoipa::OpenApi;SoupItemType,SoupApiSort,SoupPage,+ SoupEnrichedEmailThreadPreview,+ SoupEmailThreadPreview,+ SoupAttachment,+ SoupMacroAttachment,+ SoupContact,+ SoupEmailThreadPreviewMetadata,PostSoupRequest,diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex 51f653249b..103c449f6d 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -32,8 +32,8 @@ mod service;#[tokio::main]async fn main() -> anyhow::Result<()> {- let env = Environment::new_or_prod();MacroEntrypoint::default().init();+ let env = Environment::new_or_prod();let aws_config = aws_config::defaults(aws_config::BehaviorVersion::latest()).region("us-east-1")diff --git a/rust/cloud-storage/email/.sqlx/query-f29e4bf80c1ceb89a1b6169f39b83fe8f49d30d99a4308f9b3cae25fff097d82.json b/rust/cloud-storage/email/.sqlx/query-5872188529ff33ad61652722274e0b1a9725cd2ce86589e9669470a819554d93.jsonsimilarity index 64%rename from rust/cloud-storage/email/.sqlx/query-f29e4bf80c1ceb89a1b6169f39b83fe8f49d30d99a4308f9b3cae25fff097d82.jsonrename to rust/cloud-storage/email/.sqlx/query-5872188529ff33ad61652722274e0b1a9725cd2ce86589e9669470a819554d93.jsonindex bb06211076..4fb1968443 100644--- a/rust/cloud-storage/email/.sqlx/query-f29e4bf80c1ceb89a1b6169f39b83fe8f49d30d99a4308f9b3cae25fff097d82.json+++ b/rust/cloud-storage/email/.sqlx/query-5872188529ff33ad61652722274e0b1a9725cd2ce86589e9669470a819554d93.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT \n a.id,\n a.message_id,\n a.provider_attachment_id,\n a.filename,\n a.mime_type,\n a.size_bytes,\n a.content_id,\n a.created_at,\n m.thread_id\n FROM \n email_attachments a\n JOIN\n email_messages m ON a.message_id = m.id\n WHERE \n m.thread_id = ANY($1)\n ORDER BY \n a.created_at ASC\n ",+ "query": "\n SELECT\n a.id,\n a.message_id,\n a.provider_attachment_id,\n a.filename,\n a.mime_type,\n a.size_bytes,\n a.content_id,\n a.created_at,\n m.thread_id\n FROM\n email_attachments a\n JOIN\n email_messages m ON a.message_id = m.id\n WHERE\n m.thread_id = ANY($1)\n ORDER BY\n a.created_at ASC\n ","describe": {"columns": [{@@ -66,5 +66,5 @@false]},- "hash": "f29e4bf80c1ceb89a1b6169f39b83fe8f49d30d99a4308f9b3cae25fff097d82"+ "hash": "5872188529ff33ad61652722274e0b1a9725cd2ce86589e9669470a819554d93"}diff --git a/rust/cloud-storage/email/.sqlx/query-9664c74048343a599597cd14915ea3177893f42df9040b6cdd37d949588a58ed.json b/rust/cloud-storage/email/.sqlx/query-9664c74048343a599597cd14915ea3177893f42df9040b6cdd37d949588a58ed.jsonnew file mode 100644index 0000000000..5374df682d--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-9664c74048343a599597cd14915ea3177893f42df9040b6cdd37d949588a58ed.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH user_link AS (\n SELECT id as link_id, email_address\n FROM email_links\n WHERE id = $1\n LIMIT 1\n ),\n -- Get all email addresses the user has previously sent messages to\n previously_contacted AS (\n SELECT DISTINCT c.email_address\n FROM email_messages m\n JOIN email_message_recipients mr ON m.id = mr.message_id\n JOIN email_contacts c ON mr.contact_id = c.id\n CROSS JOIN user_link\n WHERE m.link_id = user_link.link_id\n AND m.is_sent = true\n AND c.email_address != user_link.email_address\n )\n -- Find threads where any sender is in the previously contacted list\n SELECT DISTINCT m.thread_id\n FROM email_messages m\n JOIN email_contacts c ON m.from_contact_id = c.id\n WHERE m.thread_id = ANY($2)\n AND EXISTS (\n SELECT 1\n FROM previously_contacted pc\n WHERE pc.email_address = c.email_address\n )\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "thread_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "UuidArray"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "9664c74048343a599597cd14915ea3177893f42df9040b6cdd37d949588a58ed"+}diff --git a/rust/cloud-storage/email/.sqlx/query-ecbe0b20fae1b19509f693cc4f1acf51e5028a38a9b13cad6f5d6bca58676feb.json b/rust/cloud-storage/email/.sqlx/query-ecbe0b20fae1b19509f693cc4f1acf51e5028a38a9b13cad6f5d6bca58676feb.jsonnew file mode 100644index 0000000000..27a1910c1e--- /dev/null+++ b/rust/cloud-storage/email/.sqlx/query-ecbe0b20fae1b19509f693cc4f1acf51e5028a38a9b13cad6f5d6bca58676feb.json@@ -0,0 +1,40 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n m.thread_id,\n -- Check if any message in thread has table HTML\n COALESCE(bool_or(m.body_html_sanitized LIKE '%<table%'), false) as \"has_table!\",\n -- Check if any message has calendar invite attachment\n COALESCE(bool_or(has_calendar.has_invite), false) as \"has_calendar_invite!\",\n -- Collect all unique sender emails in the thread\n COALESCE(array_agg(DISTINCT c.email_address), ARRAY[]::text[]) as \"sender_emails!: Vec<String>\"\n FROM email_messages m\n LEFT JOIN email_contacts c ON m.from_contact_id = c.id\n LEFT JOIN LATERAL (\n SELECT true as has_invite\n FROM email_attachments a\n WHERE a.message_id = m.id AND a.mime_type = 'application/ics'\n LIMIT 1\n ) has_calendar ON true\n WHERE m.thread_id = ANY($1)\n GROUP BY m.thread_id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "thread_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "has_table!",+ "type_info": "Bool"+ },+ {+ "ordinal": 2,+ "name": "has_calendar_invite!",+ "type_info": "Bool"+ },+ {+ "ordinal": 3,+ "name": "sender_emails!: Vec<String>",+ "type_info": "VarcharArray"+ }+ ],+ "parameters": {+ "Left": [+ "UuidArray"+ ]+ },+ "nullable": [+ false,+ null,+ null,+ null+ ]+ },+ "hash": "ecbe0b20fae1b19509f693cc4f1acf51e5028a38a9b13cad6f5d6bca58676feb"+}diff --git a/rust/cloud-storage/email/Cargo.toml b/rust/cloud-storage/email/Cargo.tomlindex f9aa46b5dc..dcb1fa34c7 100644--- a/rust/cloud-storage/email/Cargo.toml+++ b/rust/cloud-storage/email/Cargo.toml@@ -26,6 +26,7 @@ axum-extra = { workspace = true, optional = true }chrono = { workspace = true, features = ["serde"] }doppleganger = { workspace = true, features = ["chrono", "uuid"] }either = { workspace = true }+email_utils = { path = "../email_utils" }filter_ast = { path = "../filter_ast" }frecency = { path = "../frecency" }item_filters = { path = "../item_filters" }diff --git a/rust/cloud-storage/email/fixtures/email_thread_metadata.sql b/rust/cloud-storage/email/fixtures/email_thread_metadata.sqlnew file mode 100644index 0000000000..93c3bdf3eb--- /dev/null+++ b/rust/cloud-storage/email/fixtures/email_thread_metadata.sql@@ -0,0 +1,28 @@+-- Link+INSERT INTO public.email_links (id, macro_id, fusionauth_user_id, email_address, provider)+VALUES ('00000000-0000-0000-0000-000000000001', 'user_1', 'fa_user_1', '[email protected]', 'GMAIL');++-- Contacts+INSERT INTO public.email_contacts (id, link_id, email_address, name) VALUES+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '00000000-0000-0000-0000-000000000001', '[email protected]', 'Sender One'),+ ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', '00000000-0000-0000-0000-000000000001', '[email protected]', 'Sender Two');++-- Thread 1: Has table HTML, single sender, NO calendar invite+INSERT INTO public.email_threads (id, link_id) VALUES ('11111111-1111-1111-1111-111111111111', '00000000-0000-0000-0000-000000000001');+INSERT INTO public.email_messages (id, thread_id, link_id, from_contact_id, body_html_sanitized) VALUES+ ('10000000-0000-0000-0000-000000000001', '11111111-1111-1111-1111-111111111111', '00000000-0000-0000-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '<div><table><tr><td>Data</td></tr></table></div>');++-- Thread 2: No table, HAS calendar invite, multiple senders+INSERT INTO public.email_threads (id, link_id) VALUES ('22222222-2222-2222-2222-222222222222', '00000000-0000-0000-0000-000000000001');+INSERT INTO public.email_messages (id, thread_id, link_id, from_contact_id, body_html_sanitized) VALUES+ ('20000000-0000-0000-0000-000000000001', '22222222-2222-2222-2222-222222222222', '00000000-0000-0000-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '<p>Here is the invite</p>'),+ ('20000000-0000-0000-0000-000000000002', '22222222-2222-2222-2222-222222222222', '00000000-0000-0000-0000-000000000001', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', '<p>Thanks</p>');++INSERT INTO public.email_attachments (id, message_id, mime_type, filename) VALUES+ ('20000000-0000-0000-0000-00000000000a', '20000000-0000-0000-0000-000000000001', 'application/ics', 'invite.ics');++-- Thread 3: Duplicate sender test (same contact sends multiple messages), plain text+INSERT INTO public.email_threads (id, link_id) VALUES ('33333333-3333-3333-3333-333333333333', '00000000-0000-0000-0000-000000000001');+INSERT INTO public.email_messages (id, thread_id, link_id, from_contact_id, body_html_sanitized) VALUES+ ('30000000-0000-0000-0000-000000000001', '33333333-3333-3333-3333-333333333333', '00000000-0000-0000-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Message 1'),+ ('30000000-0000-0000-0000-000000000002', '33333333-3333-3333-3333-333333333333', '00000000-0000-0000-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'Message 2');\ No newline at end of filediff --git a/rust/cloud-storage/email/fixtures/threads_with_known_senders.sql b/rust/cloud-storage/email/fixtures/threads_with_known_senders.sqlnew file mode 100644index 0000000000..4087dd8428--- /dev/null+++ b/rust/cloud-storage/email/fixtures/threads_with_known_senders.sql@@ -0,0 +1,53 @@+-- Link (The User)+INSERT INTO public.email_links (id, macro_id, fusionauth_user_id, email_address, provider)+VALUES ('00000000-0000-0000-0000-000000000001', 'user_1', 'fa_user_1', '[email protected]', 'GMAIL');++-- Contacts+INSERT INTO public.email_contacts (id, link_id, email_address, name) VALUES+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '00000000-0000-0000-0000-000000000001', '[email protected]', 'Known Contact A'),+ ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', '00000000-0000-0000-0000-000000000001', '[email protected]', 'Unknown Contact B'),+ ('cccccccc-cccc-cccc-cccc-cccccccccccc', '00000000-0000-0000-0000-000000000001', '[email protected]', 'Known Contact C'),+ ('55555555-5555-5555-5555-555555555555', '00000000-0000-0000-0000-000000000001', '[email protected]', 'Me');++-- Establish "Known" contacts logic:+-- The query looks for contacts the user has SENT emails TO.++-- 1. User sent email to Contact A (making A "known")+INSERT INTO public.email_threads (id, link_id) VALUES ('99999999-9999-9999-9999-999999999991', '00000000-0000-0000-0000-000000000001');+INSERT INTO public.email_messages (id, thread_id, link_id, is_sent, from_contact_id) VALUES+ ('90000000-0000-0000-0000-000000000001', '99999999-9999-9999-9999-999999999991', '00000000-0000-0000-0000-000000000001', true, '55555555-5555-5555-5555-555555555555');++INSERT INTO public.email_message_recipients (message_id, contact_id, recipient_type) VALUES+ ('90000000-0000-0000-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'TO');++-- 2. User sent email to Contact C (making C "known")+INSERT INTO public.email_threads (id, link_id) VALUES ('99999999-9999-9999-9999-999999999992', '00000000-0000-0000-0000-000000000001');+INSERT INTO public.email_messages (id, thread_id, link_id, is_sent, from_contact_id) VALUES+ ('90000000-0000-0000-0000-000000000002', '99999999-9999-9999-9999-999999999992', '00000000-0000-0000-0000-000000000001', true, '55555555-5555-5555-5555-555555555555');++INSERT INTO public.email_message_recipients (message_id, contact_id, recipient_type) VALUES+ ('90000000-0000-0000-0000-000000000002', 'cccccccc-cccc-cccc-cccc-cccccccccccc', 'TO');+++-- Test Threads to Query Against++-- Thread 1: Incoming message from Contact A (Known) -> Should Match+INSERT INTO public.email_threads (id, link_id) VALUES ('11111111-1111-1111-1111-111111111111', '00000000-0000-0000-0000-000000000001');+INSERT INTO public.email_messages (id, thread_id, link_id, from_contact_id, is_sent) VALUES+ ('10000000-0000-0000-0000-000000000001', '11111111-1111-1111-1111-111111111111', '00000000-0000-0000-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', false);++-- Thread 2: Incoming message from Contact B (Unknown) -> Should NOT Match+INSERT INTO public.email_threads (id, link_id) VALUES ('22222222-2222-2222-2222-222222222222', '00000000-0000-0000-0000-000000000001');+INSERT INTO public.email_messages (id, thread_id, link_id, from_contact_id, is_sent) VALUES+ ('20000000-0000-0000-0000-000000000001', '22222222-2222-2222-2222-222222222222', '00000000-0000-0000-0000-000000000001', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', false);++-- Thread 3: Incoming message from Contact C (Known) -> Should Match+INSERT INTO public.email_threads (id, link_id) VALUES ('33333333-3333-3333-3333-333333333333', '00000000-0000-0000-0000-000000000001');+INSERT INTO public.email_messages (id, thread_id, link_id, from_contact_id, is_sent) VALUES+ ('30000000-0000-0000-0000-000000000001', '33333333-3333-3333-3333-333333333333', '00000000-0000-0000-0000-000000000001', 'cccccccc-cccc-cccc-cccc-cccccccccccc', false);++-- Thread 4: Mixed Thread. Contact B (Unknown) + Contact A (Known) -> Should Match (because A is there)+INSERT INTO public.email_threads (id, link_id) VALUES ('44444444-4444-4444-4444-444444444444', '00000000-0000-0000-0000-000000000001');+INSERT INTO public.email_messages (id, thread_id, link_id, from_contact_id, created_at) VALUES+ ('40000000-0000-0000-0000-000000000001', '44444444-4444-4444-4444-444444444444', '00000000-0000-0000-0000-000000000001', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', '2023-01-01 10:00:00Z'), -- Unknown B+ ('40000000-0000-0000-0000-000000000002', '44444444-4444-4444-4444-444444444444', '00000000-0000-0000-0000-000000000001', 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', '2023-01-01 11:00:00Z'); -- Known A\ No newline at end of filediff --git a/rust/cloud-storage/email/src/domain/models.rs b/rust/cloud-storage/email/src/domain/models.rsindex 54ab03e46e..c6f7c1d91e 100644--- a/rust/cloud-storage/email/src/domain/models.rs+++ b/rust/cloud-storage/email/src/domain/models.rs@@ -89,6 +89,7 @@ pub struct EnrichedEmailThreadPreview {pub attachments: Vec<Attachment>,pub attachments_macro: Vec<AttachmentMacro>,pub labels: Vec<Label>,+ pub metadata: EmailThreadPreviewMetadata,pub frecency_score: Option<AggregateFrecency>,pub participants: Vec<Contact>,}@@ -123,6 +124,19 @@ impl SortOn<SimpleSortMethod> for EnrichedEmailThreadPreview {}}+/// derived metadata for the email thread that the FE uses for filtering+#[derive(Debug, Clone, Default)]+pub struct EmailThreadPreviewMetadata {+ /// if user has previously emailed any sender+ pub known_sender: bool,+ /// if any email contains a <table> html tag+ pub tabular: bool,+ /// if any email contains a calendar invite+ pub calendar_invite: bool,+ /// if any sender is a generic email+ pub generic_sender: bool,+}+#[derive(Debug, Clone)]#[non_exhaustive]pub struct Attachment {@@ -253,3 +267,12 @@ pub struct Link {pub created_at: DateTime<Utc>,pub updated_at: DateTime<Utc>,}++/// thread values needed to build thread preview metadata+#[derive(Debug)]+pub struct IntermediateThreadMetadata {+ pub thread_id: Uuid,+ pub has_table: bool,+ pub has_calendar_invite: bool,+ pub sender_emails: Vec<String>,+}diff --git a/rust/cloud-storage/email/src/domain/ports.rs b/rust/cloud-storage/email/src/domain/ports.rsindex 3e76e85259..cfd8cee613 100644--- a/rust/cloud-storage/email/src/domain/ports.rs+++ b/rust/cloud-storage/email/src/domain/ports.rs@@ -1,6 +1,6 @@use crate::domain::models::{Attachment, AttachmentMacro, Contact, EmailErr, EmailThreadPreview, EnrichedEmailThreadPreview,- GetEmailsRequest, Label, Link, PreviewCursorQuery, UserProvider,+ GetEmailsRequest, IntermediateThreadMetadata, Label, Link, PreviewCursorQuery, UserProvider,};use macro_user_id::user_id::MacroUserIdStr;use models_pagination::{PaginatedCursor, SimpleSortMethod};@@ -40,6 +40,15 @@ pub trait EmailRepo: Send + Sync + 'static {macro_id: MacroUserIdStr<'_>,provider: UserProvider,) -> impl Future<Output = Result<Option<Link>, Self::Err>> + Send;+ fn threads_with_known_senders(+ &self,+ link_id: &Uuid,+ thread_ids: &[Uuid],+ ) -> impl Future<Output = Result<Vec<Uuid>, Self::Err>> + Send;+ fn thread_metadata_by_thread_ids(+ &self,+ thread_ids: &[Uuid],+ ) -> impl Future<Output = Result<Vec<IntermediateThreadMetadata>, Self::Err>> + Send;}pub trait EmailService: Send + Sync + 'static {diff --git a/rust/cloud-storage/email/src/domain/service.rs b/rust/cloud-storage/email/src/domain/service.rsindex 6cc52d3e3b..9683dbe8b2 100644--- a/rust/cloud-storage/email/src/domain/service.rs+++ b/rust/cloud-storage/email/src/domain/service.rs@@ -1,3 +1,5 @@+mod preview_metadata;+use crate::domain::{models::{EmailErr, EnrichedEmailThreadPreview, GetEmailsRequest, PreviewCursorQuery, UserProvider,@@ -88,12 +90,14 @@ wheremacro_attachment_map_result,participant_result,labels_result,+ metadata_result,frecency_scores,) = tokio::join!(self.email_repo.attachments_by_thread_ids(&thread_ids),self.email_repo.macro_attachments_by_thread_ids(&thread_ids),self.email_repo.contacts_by_thread_ids(&thread_ids),self.email_repo.labels_by_thread_ids(&thread_ids),+ self.get_preview_metadata(&previews, &link_id),self.frecency_service.get_frecencies_by_ids(frecency_request));@@ -114,6 +118,7 @@ where.map_err(anyhow::Error::from)?.into_iter().group_by(|v| v.thread_id);+ let mut metadata_map = metadata_result.map_err(anyhow::Error::from)?;let mut frecency_scores_map: HashMap<AggregateId<'static>, FrecencyData> =frecency_scores?.into_inner();@@ -131,6 +136,7 @@ whereattachments_macro: macro_attachment_map.remove(&thread.id).unwrap_or_default(),labels: labels_map.remove(&thread.id).unwrap_or_default(),participants: participant_map.remove(&thread.id).unwrap_or_default(),+ metadata: metadata_map.remove(&thread.id).unwrap_or_default(),frecency_score: frecency_scores_map.remove(&id).map(|data| id.into_aggregate(data)),diff --git a/rust/cloud-storage/email/src/domain/service/preview_metadata.rs b/rust/cloud-storage/email/src/domain/service/preview_metadata.rsnew file mode 100644index 0000000000..315aed8832--- /dev/null+++ b/rust/cloud-storage/email/src/domain/service/preview_metadata.rs@@ -0,0 +1,61 @@+use crate::domain::models::{+ EmailThreadPreview, EmailThreadPreviewMetadata, IntermediateThreadMetadata,+};+use crate::domain::ports::EmailRepo;+use crate::domain::service::EmailServiceImpl;+use frecency::domain::ports::FrecencyQueryService;+use std::collections::HashMap;+use uuid::Uuid;++impl<T, U> EmailServiceImpl<T, U>+where+ T: EmailRepo,+ U: FrecencyQueryService,+{+ /// get metadata for thread previews, used by FE for filtering Important vs Other threads+ pub async fn get_preview_metadata(+ &self,+ previews: &[EmailThreadPreview],+ link_id: &Uuid,+ ) -> Result<HashMap<Uuid, EmailThreadPreviewMetadata>, T::Err> {+ let thread_ids: Vec<Uuid> = previews.iter().map(|p| p.id).collect();++ let (known_senders_threads, thread_metadata) = tokio::join!(+ self.email_repo+ .threads_with_known_senders(link_id, &thread_ids),+ self.email_repo.thread_metadata_by_thread_ids(&thread_ids)+ );++ let known_senders_threads = known_senders_threads?;+ let thread_metadata = thread_metadata?;++ let metadata_map_by_thread: HashMap<Uuid, &IntermediateThreadMetadata> =+ thread_metadata.iter().map(|m| (m.thread_id, m)).collect();++ let metadata_map: HashMap<Uuid, EmailThreadPreviewMetadata> = thread_ids+ .into_iter()+ .map(|id| {+ let metadata = metadata_map_by_thread.get(&id);+ let generic_sender = metadata+ .map(|m| {+ m.sender_emails+ .iter()+ .any(|e| email_utils::is_generic_email(e))+ })+ .unwrap_or(false);++ (+ id,+ EmailThreadPreviewMetadata {+ known_sender: known_senders_threads.contains(&id),+ tabular: metadata.map(|m| m.has_table).unwrap_or(false),+ calendar_invite: metadata.map(|m| m.has_calendar_invite).unwrap_or(false),+ generic_sender,+ },+ )+ })+ .collect();++ Ok(metadata_map)+ }+}diff --git a/rust/cloud-storage/email/src/inbound/axum/api_types.rs b/rust/cloud-storage/email/src/inbound/axum/api_types.rsindex 994dffe232..65ab8bd250 100644--- a/rust/cloud-storage/email/src/inbound/axum/api_types.rs+++ b/rust/cloud-storage/email/src/inbound/axum/api_types.rs@@ -8,8 +8,8 @@ use utoipa::ToSchema;use uuid::Uuid;use crate::domain::models::{- Attachment, AttachmentMacro, Contact, EmailThreadPreview, EnrichedEmailThreadPreview, Label,- LabelListVisibility, LabelType, MessageListVisibility,+ Attachment, AttachmentMacro, Contact, EmailThreadPreview, EmailThreadPreviewMetadata,+ EnrichedEmailThreadPreview, Label, LabelListVisibility, LabelType, MessageListVisibility,};/// common types of sorts based on timestamps@@ -50,6 +50,7 @@ struct ApiThreadPreviewCursor {#[dg(rename = "participants")]contacts: Vec<ApiContact>,labels: Vec<ApiLabel>,+ metadata: APIEmailThreadPreviewMetadata,#[dg(map = map_frecency)]frecency_score: Option<f64>,}@@ -180,6 +181,20 @@ pub enum ApiLabelType {User,}+#[derive(Debug, ToSchema, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Doppleganger)]+#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]+#[dg(backward = EmailThreadPreviewMetadata)]+pub struct APIEmailThreadPreviewMetadata {+ /// if user has previously emailed any sender in the thread+ pub known_sender: bool,+ /// if any email contains a <table> html tag+ pub tabular: bool,+ /// if any email contains a calendar invite+ pub calendar_invite: bool,+ /// if any sender in the thread is a generic email+ pub generic_sender: bool,+}+#[derive(Debug, ToSchema, Serialize, Deserialize)]#[cfg_attr(feature = "ai_schema", derive(schemars::JsonSchema))]pub struct ApiPaginatedThreadCursor {diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo.rsindex e93773e9fd..f6c18aec30 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo.rs@@ -1,4 +1,4 @@-use crate::domain::models::Label;+use crate::domain::models::{IntermediateThreadMetadata, Label};use crate::domain::{models::{Attachment, AttachmentMacro, Contact, EmailThreadPreview, Link, PreviewCursorQuery,@@ -118,7 +118,7 @@ impl EmailRepo for EmailPgRepo {Ok(sqlx::query_as!(AttachmentDbRow,r#"- SELECT+ SELECTa.id,a.message_id,a.provider_attachment_id,@@ -128,13 +128,13 @@ impl EmailRepo for EmailPgRepo {a.content_id,a.created_at,m.thread_id- FROM+ FROMemail_attachments aJOINemail_messages m ON a.message_id = m.id- WHERE+ WHEREm.thread_id = ANY($1)- ORDER BY+ ORDER BYa.created_at ASC"#,thread_ids@@ -276,4 +276,85 @@ impl EmailRepo for EmailPgRepo {.transpose().map_err(|e| sqlx::Error::Decode(Box::new(e)))}++ async fn threads_with_known_senders(+ &self,+ link_id: &Uuid,+ thread_ids: &[Uuid],+ ) -> Result<Vec<Uuid>, Self::Err> {+ // Returns thread IDs where the user has emailed at least one sender in the thread+ let result = sqlx::query_scalar!(+ r#"+ WITH user_link AS (+ SELECT id as link_id, email_address+ FROM email_links+ WHERE id = $1+ LIMIT 1+ ),+ -- Get all email addresses the user has previously sent messages to+ previously_contacted AS (+ SELECT DISTINCT c.email_address+ FROM email_messages m+ JOIN email_message_recipients mr ON m.id = mr.message_id+ JOIN email_contacts c ON mr.contact_id = c.id+ CROSS JOIN user_link+ WHERE m.link_id = user_link.link_id+ AND m.is_sent = true+ AND c.email_address != user_link.email_address+ )+ -- Find threads where any sender is in the previously contacted list+ SELECT DISTINCT m.thread_id+ FROM email_messages m+ JOIN email_contacts c ON m.from_contact_id = c.id+ WHERE m.thread_id = ANY($2)+ AND EXISTS (+ SELECT 1+ FROM previously_contacted pc+ WHERE pc.email_address = c.email_address+ )+ "#,+ link_id,+ thread_ids+ )+ .fetch_all(&self.pool)+ .await?;++ Ok(result)+ }++ async fn thread_metadata_by_thread_ids(+ &self,+ thread_ids: &[Uuid],+ ) -> Result<Vec<IntermediateThreadMetadata>, Self::Err> {+ // Returns thread metadata for the provided thread IDs.+ Ok(sqlx::query_as!(+ IntermediateThreadMetadataDbRow,+ r#"+ SELECT+ m.thread_id,+ -- Check if any message in thread has table HTML+ COALESCE(bool_or(m.body_html_sanitized LIKE '%<table%'), false) as "has_table!",+ -- Check if any message has calendar invite attachment+ COALESCE(bool_or(has_calendar.has_invite), false) as "has_calendar_invite!",+ -- Collect all unique sender emails in the thread+ COALESCE(array_agg(DISTINCT c.email_address), ARRAY[]::text[]) as "sender_emails!: Vec<String>"+ FROM email_messages m+ LEFT JOIN email_contacts c ON m.from_contact_id = c.id+ LEFT JOIN LATERAL (+ SELECT true as has_invite+ FROM email_attachments a+ WHERE a.message_id = m.id AND a.mime_type = 'application/ics'+ LIMIT 1+ ) has_calendar ON true+ WHERE m.thread_id = ANY($1)+ GROUP BY m.thread_id+ "#,+ thread_ids+ )+ .fetch_all(&self.pool)+ .await?+ .into_iter()+ .map(crate::outbound::email_pg_repo::IntermediateThreadMetadataDbRow::mirror)+ .collect())+ }}diff --git a/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs b/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rsindex 3fce6da3bf..95f4ea0e71 100644--- a/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs+++ b/rust/cloud-storage/email/src/outbound/email_pg_repo/db_types.rs@@ -1,6 +1,6 @@use crate::domain::models::{- Attachment, AttachmentMacro, EmailThreadPreview, Label, LabelListVisibility, LabelType, Link,- MessageListVisibility,+ Attachment, AttachmentMacro, EmailThreadPreview, IntermediateThreadMetadata, Label,+ LabelListVisibility, LabelType, Link, MessageListVisibility,};use chrono::{DateTime, Utc};use doppleganger::{Doppleganger, Mirror};@@ -108,6 +108,17 @@ pub struct LabelDbRow {pub type_: LabelTypeDbRow,}+/// database values needed to build thread preview metadata+#[derive(Doppleganger)]+#[dg(forward = IntermediateThreadMetadata)]+#[derive(Debug, Clone)]+pub struct IntermediateThreadMetadataDbRow {+ pub thread_id: Uuid,+ pub has_table: bool,+ pub has_calendar_invite: bool,+ pub sender_emails: Vec<String>,+}+impl ThreadPreviewCursorDbRow {pub fn with_user_id(self, owner_id: MacroUserIdStr<'_>) -> EmailThreadPreview {let ThreadPreviewCursorDbRow {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 80352d575f..14ccb6895d 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@@ -623,3 +623,201 @@ async fn test_dynamic_query_pagination(pool: Pool<Postgres>) -> anyhow::Result<(Ok(())}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("email_thread_metadata"))+)]+async fn test_thread_metadata_has_table(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool);+ let thread_id = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;++ let metadata = repo.thread_metadata_by_thread_ids(&[thread_id]).await?;++ assert_eq!(metadata.len(), 1);+ let item = &metadata[0];++ assert_eq!(item.thread_id, thread_id);+ assert!(item.has_table, "Should detect HTML table");+ assert!(+ !item.has_calendar_invite,+ "Should not detect calendar invite"+ );+ assert_eq!(item.sender_emails.len(), 1);+ assert_eq!(item.sender_emails[0], "[email protected]");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("email_thread_metadata"))+)]+async fn test_thread_metadata_has_calendar_invite(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool);+ let thread_id = Uuid::parse_str("22222222-2222-2222-2222-222222222222")?;++ let metadata = repo.thread_metadata_by_thread_ids(&[thread_id]).await?;++ assert_eq!(metadata.len(), 1);+ let item = &metadata[0];++ assert_eq!(item.thread_id, thread_id);+ assert!(!item.has_table, "Should not detect HTML table");+ assert!(item.has_calendar_invite, "Should detect calendar invite");++ // Verify multiple senders are collected+ assert_eq!(item.sender_emails.len(), 2);+ assert!(+ item.sender_emails+ .contains(&"[email protected]".to_string())+ );+ assert!(+ item.sender_emails+ .contains(&"[email protected]".to_string())+ );++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("email_thread_metadata"))+)]+async fn test_thread_metadata_sender_deduplication(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool);+ // Thread 3 has 2 messages from the same sender+ let thread_id = Uuid::parse_str("33333333-3333-3333-3333-333333333333")?;++ let metadata = repo.thread_metadata_by_thread_ids(&[thread_id]).await?;++ assert_eq!(metadata.len(), 1);+ let item = &metadata[0];++ assert_eq!(+ item.sender_emails.len(),+ 1,+ "Should deduplicate identical senders"+ );+ assert_eq!(item.sender_emails[0], "[email protected]");++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("email_thread_metadata"))+)]+async fn test_thread_metadata_batch_retrieval(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool);+ let t1 = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;+ let t2 = Uuid::parse_str("22222222-2222-2222-2222-222222222222")?;++ let metadata = repo.thread_metadata_by_thread_ids(&[t1, t2]).await?;++ assert_eq!(metadata.len(), 2);++ let meta1 = metadata.iter().find(|m| m.thread_id == t1).unwrap();+ assert!(meta1.has_table);++ let meta2 = metadata.iter().find(|m| m.thread_id == t2).unwrap();+ assert!(meta2.has_calendar_invite);++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("threads_with_known_senders"))+)]+async fn test_known_senders_single_match(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool);+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000001")?;++ // Thread 1 is from Known Contact A+ let thread_id = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;++ let result = repo+ .threads_with_known_senders(&link_id, &[thread_id])+ .await?;++ assert_eq!(result.len(), 1);+ assert_eq!(+ result[0], thread_id,+ "Should identify thread from known sender"+ );++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("threads_with_known_senders"))+)]+async fn test_known_senders_no_match(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool);+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000001")?;++ // Thread 2 is from Unknown Contact B+ let thread_id = Uuid::parse_str("22222222-2222-2222-2222-222222222222")?;++ let result = repo+ .threads_with_known_senders(&link_id, &[thread_id])+ .await?;++ assert!(+ result.is_empty(),+ "Should NOT return thread from unknown sender"+ );++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("threads_with_known_senders"))+)]+async fn test_known_senders_mixed_input(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool);+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000001")?;++ let t1_known = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;+ let t2_unknown = Uuid::parse_str("22222222-2222-2222-2222-222222222222")?;+ let t3_known = Uuid::parse_str("33333333-3333-3333-3333-333333333333")?;++ let result = repo+ .threads_with_known_senders(&link_id, &[t1_known, t2_unknown, t3_known])+ .await?;++ assert_eq!(result.len(), 2);+ assert!(result.contains(&t1_known));+ assert!(result.contains(&t3_known));+ assert!(!result.contains(&t2_unknown));++ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("threads_with_known_senders"))+)]+async fn test_known_senders_mixed_thread_participants(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = EmailPgRepo::new(pool);+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000001")?;++ // Thread 4 has messages from both Unknown B and Known A+ let thread_id = Uuid::parse_str("44444444-4444-4444-4444-444444444444")?;++ let result = repo+ .threads_with_known_senders(&link_id, &[thread_id])+ .await?;++ assert_eq!(+ result.len(),+ 1,+ "Should match because at least one participant is known"+ );+ assert_eq!(result[0], thread_id);++ Ok(())+}diff --git a/rust/cloud-storage/models_soup/src/email_thread.rs b/rust/cloud-storage/models_soup/src/email_thread.rsindex 62e39eaacd..8f6c062d4c 100644--- a/rust/cloud-storage/models_soup/src/email_thread.rs+++ b/rust/cloud-storage/models_soup/src/email_thread.rs@@ -17,6 +17,22 @@ pub struct SoupContact {pub sfs_photo_url: Option<String>,}+#[derive(Debug, Doppleganger, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[cfg_attr(feature = "mock", derive(PartialEq, Eq))]+#[dg(backward = email::domain::models::EmailThreadPreviewMetadata)]+#[serde(rename_all = "camelCase")]+pub struct SoupEmailThreadPreviewMetadata {+ /// if user has previously emailed any sender+ pub known_sender: bool,+ /// if any email contains a <table> html tag+ pub tabular: bool,+ /// if any email contains a calendar invite+ pub calendar_invite: bool,+ /// if any sender is a generic email+ pub generic_sender: bool,+}+#[derive(Debug, Doppleganger, Serialize, Deserialize)]#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]#[cfg_attr(feature = "mock", derive(PartialEq, Eq))]@@ -92,4 +108,5 @@ pub struct SoupEnrichedEmailThreadPreview {pub attachments: Vec<SoupAttachment>,pub attachments_macro: Vec<SoupMacroAttachment>,pub participants: Vec<SoupContact>,+ pub metadata: SoupEmailThreadPreviewMetadata,}