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: search importance filter + make ai search important only (#1680)
gbirmanffb8649de8e0
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 1921a990ea..2a76a24faf 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@@ -20,7 +20,9 @@ export interface EmailFilters {/** Exclude emails that have any of these labels. Supports both Gmail system labels (e.g. "CATEGORY_PROMOTIONS") and user-created labels. Empty to not exclude any labels.Note: SPAM and TRASH emails are not indexed in OpenSearch, so they are already excluded by default. */exclude_labels?: string[];- /** Filter by email importance. None to ignore, true to pass through (no clause), false to short-circuit and return nothing. */+ /** Filter by email importance. None to not filter. True to show only important emails+(drafts, personal, sent, or uncategorized). False to show only unimportant emails+(those categorized as promotions, social, updates, or forums). */importance?: EmailFiltersImportance;/** Only include emails that have at least one of these labels. Supports both Gmail system labels (e.g. "INBOX", "CATEGORY_PROMOTIONS") and user-created labels (e.g. "github"). Empty to not filter by included labels.Note: SPAM and TRASH emails are not indexed in OpenSearch, so they will never appear in results regardless of this filter. */diff --git a/js/app/packages/service-clients/service-search/generated/models/emailFiltersImportance.ts b/js/app/packages/service-clients/service-search/generated/models/emailFiltersImportance.tsindex 3b2fc32a6d..7350195003 100644--- a/js/app/packages/service-clients/service-search/generated/models/emailFiltersImportance.ts+++ b/js/app/packages/service-clients/service-search/generated/models/emailFiltersImportance.ts@@ -6,6 +6,8 @@*//**- * Filter by email importance. None to ignore, true to pass through (no clause), false to short-circuit and return nothing.+ * Filter by email importance. None to not filter. True to show only important emails+(drafts, personal, sent, or uncategorized). False to show only unimportant emails+(those categorized as promotions, social, updates, or forums).*/export type EmailFiltersImportance = boolean | null;diff --git a/js/app/packages/service-clients/service-search/openapi.json b/js/app/packages/service-clients/service-search/openapi.jsonindex 7e1b0bb99e..37b525656f 100644--- a/js/app/packages/service-clients/service-search/openapi.json+++ b/js/app/packages/service-clients/service-search/openapi.json@@ -910,7 +910,7 @@},"importance": {"type": ["boolean", "null"],- "description": "Filter by email importance. None to ignore, true to pass through (no clause), false to short-circuit and return nothing."+ "description": "Filter by email importance. None to not filter. True to show only important emails\n(drafts, personal, sent, or uncategorized). False to show only unimportant emails\n(those categorized as promotions, social, updates, or forums)."},"include_labels": {"type": "array",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 44d8390f36..1e8063291c 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@@ -20,7 +20,9 @@ export interface EmailFilters {/** Exclude emails that have any of these labels. Supports both Gmail system labels (e.g. "CATEGORY_PROMOTIONS") and user-created labels. Empty to not exclude any labels.Note: SPAM and TRASH emails are not indexed in OpenSearch, so they are already excluded by default. */exclude_labels?: string[];- /** Filter by email importance. None to ignore, true to pass through (no clause), false to short-circuit and return nothing. */+ /** Filter by email importance. None to not filter. True to show only important emails+(drafts, personal, sent, or uncategorized). False to show only unimportant emails+(those categorized as promotions, social, updates, or forums). */importance?: EmailFiltersImportance;/** Only include emails that have at least one of these labels. Supports both Gmail system labels (e.g. "INBOX", "CATEGORY_PROMOTIONS") and user-created labels (e.g. "github"). Empty to not filter by included labels.Note: SPAM and TRASH emails are not indexed in OpenSearch, so they will never appear in results regardless of this filter. */diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/emailFiltersImportance.ts b/js/app/packages/service-clients/service-storage/generated/schemas/emailFiltersImportance.tsindex 7e3f74df99..0b4aaa58fd 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/emailFiltersImportance.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/emailFiltersImportance.ts@@ -6,6 +6,8 @@*//**- * Filter by email importance. None to ignore, true to pass through (no clause), false to short-circuit and return nothing.+ * Filter by email importance. None to not filter. True to show only important emails+(drafts, personal, sent, or uncategorized). False to show only unimportant emails+(those categorized as promotions, social, updates, or forums).*/export type EmailFiltersImportance = boolean | null;diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex dd6f078944..34462668b5 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -4208,7 +4208,7 @@ export const postItemsSoupBody = zod.boolean().nullish().describe(- 'Filter by email importance. None to ignore, true to pass through (no clause), false to short-circuit and return nothing.'+ 'Filter by email importance. None to not filter. True to show only important emails\n(drafts, personal, sent, or uncategorized). False to show only unimportant emails\n(those categorized as promotions, social, updates, or forums).'),include_labels: zod.array(zod.string())diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 122d7dd6c4..9346b9c6e2 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -6774,7 +6774,7 @@},"importance": {"type": ["boolean", "null"],- "description": "Filter by email importance. None to ignore, true to pass through (no clause), false to short-circuit and return nothing."+ "description": "Filter by email importance. None to not filter. True to show only important emails\n(drafts, personal, sent, or uncategorized). False to show only unimportant emails\n(those categorized as promotions, social, updates, or forums)."},"include_labels": {"type": "array",diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 0faaf08071..c9e19e6f6d 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -100,6 +100,7 @@ dependencies = ["email","email_service_client","frecency",+ "item_filters","lazy_static","macro_db_client","model",diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.tomlindex 792fa45bc9..9ace4e658e 100644--- a/rust/cloud-storage/ai_tools/Cargo.toml+++ b/rust/cloud-storage/ai_tools/Cargo.toml@@ -15,6 +15,7 @@ comms = { path = "../comms", features = ["outbound"] }email = { path = "../email", features = ["ai_schema", "axum", "outbound"] }email_service_client = { path = "../email_service_client" }frecency = { path = "../frecency", features = ["outbound", "postgres"] }+item_filters = { path = "../item_filters" }lazy_static.workspace = truemacro_db_client = { path = "../macro_db_client" }model = { path = "../model" }diff --git a/rust/cloud-storage/ai_tools/src/search/search_service/content.rs b/rust/cloud-storage/ai_tools/src/search/search_service/content.rsindex 74c925bd93..69a5f849a5 100644--- a/rust/cloud-storage/ai_tools/src/search/search_service/content.rs+++ b/rust/cloud-storage/ai_tools/src/search/search_service/content.rs@@ -1,9 +1,10 @@use super::types::{PAGE_SIZE, SearchToolResponse};use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};use async_trait::async_trait;+use item_filters::EmailFilters;use models_search::{MatchType,- unified::{UnifiedSearchIndex, UnifiedSearchRequest},+ unified::{UnifiedSearchFilters, UnifiedSearchIndex, UnifiedSearchRequest},};use schemars::JsonSchema;use search_service_client::SearchServiceClient;@@ -52,7 +53,13 @@ impl AsyncTool<Arc<SearchServiceClient>> for ContentSearch {query: Some(self.query.to_owned()),terms: None,match_type: MatchType::Partial,- filters: None,+ filters: Some(UnifiedSearchFilters {+ email: Some(EmailFilters {+ importance: Some(true),+ ..Default::default()+ }),+ ..Default::default()+ }),search_on: models_search::SearchOn::Content,collapse: Some(true),include: self.entity_types.clone(),diff --git a/rust/cloud-storage/ai_tools/src/search/search_service/name.rs b/rust/cloud-storage/ai_tools/src/search/search_service/name.rsindex f5bfb5c468..0e61a5c90a 100644--- a/rust/cloud-storage/ai_tools/src/search/search_service/name.rs+++ b/rust/cloud-storage/ai_tools/src/search/search_service/name.rs@@ -1,9 +1,10 @@use super::types::{PAGE_SIZE, SearchToolResponse};use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};use async_trait::async_trait;+use item_filters::EmailFilters;use models_search::{MatchType,- unified::{UnifiedSearchIndex, UnifiedSearchRequest},+ unified::{UnifiedSearchFilters, UnifiedSearchIndex, UnifiedSearchRequest},};use schemars::JsonSchema;use search_service_client::SearchServiceClient;@@ -52,7 +53,13 @@ impl AsyncTool<Arc<SearchServiceClient>> for NameSearch {query: Some(self.name.to_owned()),terms: None,match_type: MatchType::Partial,- filters: None,+ filters: Some(UnifiedSearchFilters {+ email: Some(EmailFilters {+ importance: Some(true),+ ..Default::default()+ }),+ ..Default::default()+ }),search_on: models_search::SearchOn::Name,collapse: Some(true),include: self.entity_types.clone(),diff --git a/rust/cloud-storage/item_filters/src/lib.rs b/rust/cloud-storage/item_filters/src/lib.rsindex 445b05ee81..a20221e5a3 100644--- a/rust/cloud-storage/item_filters/src/lib.rs+++ b/rust/cloud-storage/item_filters/src/lib.rs@@ -185,7 +185,9 @@ pub struct EmailFilters {#[serde(default, skip_serializing_if = "Vec::is_empty")]pub email_thread_ids: Vec<String>,- /// Filter by email importance. None to ignore, true to pass through (no clause), false to short-circuit and return nothing.+ /// Filter by email importance. None to not filter. True to show only important emails+ /// (drafts, personal, sent, or uncategorized). False to show only unimportant emails+ /// (those categorized as promotions, social, updates, or forums).#[serde(default, skip_serializing_if = "Option::is_none")]pub importance: Option<bool>,diff --git a/rust/cloud-storage/opensearch_client/src/search/emails.rs b/rust/cloud-storage/opensearch_client/src/search/emails.rsindex a9b121060e..c2f1db1296 100644--- a/rust/cloud-storage/opensearch_client/src/search/emails.rs+++ b/rust/cloud-storage/opensearch_client/src/search/emails.rs@@ -11,7 +11,9 @@ use crate::{use crate::SearchOn;use models_opensearch::{SearchEntityType, SearchIndex};-use opensearch_query_builder::{BoolQueryBuilder, QueryType, SearchRequest, ToOpenSearchJson};+use opensearch_query_builder::{+ BoolQuery, BoolQueryBuilder, QueryType, SearchRequest, ToOpenSearchJson,+};use crate::search::model::DefaultSearchResponse;use serde_json::Value;@@ -40,6 +42,10 @@ pub(crate) struct EmailQueryBuilder {include_labels: Vec<String>,/// Labels to exclude (emails must not have any)exclude_labels: Vec<String>,+ /// Filter by importance. All filters (importance, include_labels, exclude_labels) are+ /// ANDed together. Contradictory combinations (e.g. importance=true with+ /// include_labels=["CATEGORY_PROMOTIONS"]) will return no results.+ importance: Option<bool>,}impl EmailQueryBuilder {@@ -53,6 +59,7 @@ impl EmailQueryBuilder {recipients: Vec::new(),include_labels: Vec::new(),exclude_labels: Vec::new(),+ importance: None,}}@@ -104,6 +111,11 @@ impl EmailQueryBuilder {self}+ pub fn importance(mut self, importance: Option<bool>) -> Self {+ self.importance = importance;+ self+ }+pub fn build_bool_query<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {let mut content_bool_query = self.inner.build_content_bool_query()?;@@ -143,6 +155,49 @@ impl EmailQueryBuilder {for label in &self.exclude_labels {content_bool_query.must_not(QueryType::term("labels", label.clone()));}++ // Importance filter. Source of truth for the label logic is in+ // email/src/outbound/email_pg_repo/dynamic.rs (EmailLiteral::Importance).+ match self.importance {+ Some(true) => {+ // Exclude emails that have depriority labels UNLESS they also have a priority label.+ let importance_exclude = BoolQuery::new()+ .filter(QueryType::terms(+ "labels",+ [+ "CATEGORY_UPDATES",+ "CATEGORY_PROMOTIONS",+ "CATEGORY_SOCIAL",+ "CATEGORY_FORUMS",+ ],+ ))+ .must_not(QueryType::terms(+ "labels",+ ["CATEGORY_PERSONAL", "SENT", "DRAFT"],+ ));+ content_bool_query.must_not(QueryType::Bool(importance_exclude));+ }+ Some(false) => {+ // Only show deprioritized emails: must have a depriority label+ // AND must not have a priority label.+ let depriority_filter = BoolQuery::new()+ .filter(QueryType::terms(+ "labels",+ [+ "CATEGORY_UPDATES",+ "CATEGORY_PROMOTIONS",+ "CATEGORY_SOCIAL",+ "CATEGORY_FORUMS",+ ],+ ))+ .must_not(QueryType::terms(+ "labels",+ ["CATEGORY_PERSONAL", "SENT", "DRAFT"],+ ));+ content_bool_query.filter(QueryType::Bool(depriority_filter));+ }+ None => {}+ }// END CUSTOM ATTRIBUTES SECTIONOk(content_bool_query)@@ -206,6 +261,7 @@ pub struct EmailSearchArgs {pub recipients: Vec<String>,pub include_labels: Vec<String>,pub exclude_labels: Vec<String>,+ pub importance: Option<bool>,pub page: u32,pub page_size: u32,pub match_type: String,@@ -231,6 +287,7 @@ impl From<EmailSearchArgs> for EmailQueryBuilder {.recipients(args.recipients).include_labels(args.include_labels).exclude_labels(args.exclude_labels)+ .importance(args.importance).collapse(args.collapse).ids_only(args.ids_only).disable_recency(args.disable_recency)diff --git a/rust/cloud-storage/opensearch_client/src/search/emails/test.rs b/rust/cloud-storage/opensearch_client/src/search/emails/test.rsindex b9edff82c1..9405e1213b 100644--- a/rust/cloud-storage/opensearch_client/src/search/emails/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/emails/test.rs@@ -140,3 +140,148 @@ fn test_build_search_request() -> anyhow::Result<()> {Ok(())}++#[test]+fn test_importance_true_excludes_depriority_unless_priority() -> anyhow::Result<()> {+ let builder = EmailQueryBuilder::new(vec!["test".to_string()])+ .match_type("partial")+ .page_size(10)+ .page(0)+ .user_id("user123")+ .search_on(SearchOn::Content)+ .collapse(false)+ .importance(Some(true));++ let bool_query = builder.build_bool_query()?;+ let json = bool_query.build().to_json();++ let must_not = json["bool"]["must_not"].as_array().unwrap();+ assert_eq!(must_not.len(), 1);++ let nested_bool = &must_not[0]["bool"];+ let filter = nested_bool["filter"].as_array().unwrap();+ assert_eq!(filter.len(), 1);+ let depriority = filter[0]["terms"]["labels"].as_array().unwrap();+ assert_eq!(depriority.len(), 4);++ let inner_must_not = nested_bool["must_not"].as_array().unwrap();+ assert_eq!(inner_must_not.len(), 1);+ let priority = inner_must_not[0]["terms"]["labels"].as_array().unwrap();+ assert_eq!(priority.len(), 3);++ Ok(())+}++#[test]+fn test_importance_false_filters_to_depriority_only() -> anyhow::Result<()> {+ let builder = EmailQueryBuilder::new(vec!["test".to_string()])+ .match_type("partial")+ .page_size(10)+ .page(0)+ .user_id("user123")+ .search_on(SearchOn::Content)+ .collapse(false)+ .importance(Some(false));++ let bool_query = builder.build_bool_query()?;+ let json = bool_query.build().to_json();++ let filters = json["bool"]["filter"].as_array().unwrap();+ let nested_bool = filters+ .iter()+ .find(|f| f["bool"]["filter"].is_array() && f["bool"]["must_not"].is_array())+ .expect("should have nested importance filter");++ let depriority = nested_bool["bool"]["filter"][0]["terms"]["labels"]+ .as_array()+ .unwrap();+ assert_eq!(depriority.len(), 4);++ let priority = nested_bool["bool"]["must_not"][0]["terms"]["labels"]+ .as_array()+ .unwrap();+ assert_eq!(priority.len(), 3);++ Ok(())+}++#[test]+fn test_importance_none_no_importance_filter() -> anyhow::Result<()> {+ let builder = EmailQueryBuilder::new(vec!["test".to_string()])+ .match_type("partial")+ .page_size(10)+ .page(0)+ .user_id("user123")+ .search_on(SearchOn::Content)+ .collapse(false)+ .importance(None);++ let bool_query = builder.build_bool_query()?;+ let json = bool_query.build().to_json();++ assert!(json["bool"]["must_not"].is_null());++ Ok(())+}++#[test]+fn test_importance_true_with_exclude_labels_both_apply() -> anyhow::Result<()> {+ let builder = EmailQueryBuilder::new(vec!["test".to_string()])+ .match_type("partial")+ .page_size(10)+ .page(0)+ .user_id("user123")+ .search_on(SearchOn::Content)+ .collapse(false)+ .importance(Some(true))+ .exclude_labels(vec!["INBOX".to_string()]);++ let bool_query = builder.build_bool_query()?;+ let json = bool_query.build().to_json();++ let must_not = json["bool"]["must_not"].as_array().unwrap();+ // Should have both: the explicit exclude_label AND the importance nested bool+ assert_eq!(must_not.len(), 2);++ // One should be the INBOX term exclusion+ let has_inbox_exclusion = must_not.iter().any(|q| q["term"]["labels"] == "INBOX");+ assert!(has_inbox_exclusion);++ // One should be the nested importance bool+ let has_importance = must_not.iter().any(|q| q["bool"]["filter"].is_array());+ assert!(has_importance);++ Ok(())+}++#[test]+fn test_importance_false_with_exclude_labels_both_apply() -> anyhow::Result<()> {+ let builder = EmailQueryBuilder::new(vec!["test".to_string()])+ .match_type("partial")+ .page_size(10)+ .page(0)+ .user_id("user123")+ .search_on(SearchOn::Content)+ .collapse(false)+ .importance(Some(false))+ .exclude_labels(vec!["CATEGORY_SOCIAL".to_string()]);++ let bool_query = builder.build_bool_query()?;+ let json = bool_query.build().to_json();++ let must_not = json["bool"]["must_not"].as_array().unwrap();+ // Should have the explicit CATEGORY_SOCIAL exclusion+ let has_social_exclusion = must_not+ .iter()+ .any(|q| q["term"]["labels"] == "CATEGORY_SOCIAL");+ assert!(has_social_exclusion);++ // Should have the importance filter in filter array+ let filters = json["bool"]["filter"].as_array().unwrap();+ let has_importance_filter = filters+ .iter()+ .any(|f| f["bool"]["filter"].is_array() && f["bool"]["must_not"].is_array());+ assert!(has_importance_filter);++ Ok(())+}diff --git a/rust/cloud-storage/opensearch_client/src/search/unified.rs b/rust/cloud-storage/opensearch_client/src/search/unified.rsindex 585c5cffa6..8466f24358 100644--- a/rust/cloud-storage/opensearch_client/src/search/unified.rs+++ b/rust/cloud-storage/opensearch_client/src/search/unified.rs@@ -89,6 +89,7 @@ impl From<UnifiedSearchArgs> for EmailSearchArgs {recipients: args.email_search_args.recipients,include_labels: args.email_search_args.include_labels,exclude_labels: args.email_search_args.exclude_labels,+ importance: args.email_search_args.importance,}}}@@ -154,6 +155,7 @@ pub struct UnifiedEmailSearchArgs {pub recipients: Vec<String>,pub include_labels: Vec<String>,pub exclude_labels: Vec<String>,+ pub importance: Option<bool>,}#[derive(Debug, Default, Clone)]diff --git a/rust/cloud-storage/search_service/src/api/search/simple/filter.rs b/rust/cloud-storage/search_service/src/api/search/simple/filter.rsindex ca051a43b5..44f1f0c6f2 100644--- a/rust/cloud-storage/search_service/src/api/search/simple/filter.rs+++ b/rust/cloud-storage/search_service/src/api/search/simple/filter.rs@@ -155,6 +155,7 @@ impl FilterVariantToSearchArgs for item_filters::EmailFilters {recipients: self.recipients.clone(),include_labels: self.include_labels.clone(),exclude_labels: self.exclude_labels.clone(),+ importance: self.importance,})}}