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(search): highlight doc names on content-only hits (#2742)
gbirman5c0e3c2ce041
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex a93e1707f2..4e1810d62d 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -7000,6 +7000,7 @@ dependencies = ["models_opensearch","models_search_cursor","non_empty",+ "regex","serde","sqlx","thiserror 2.0.17",diff --git a/rust/cloud-storage/name_search/Cargo.toml b/rust/cloud-storage/name_search/Cargo.tomlindex 77f854f666..64293d8745 100644--- a/rust/cloud-storage/name_search/Cargo.toml+++ b/rust/cloud-storage/name_search/Cargo.toml@@ -12,6 +12,7 @@ macro_user_id = { path = "../macro_user_id" }models_opensearch = { path = "../models_opensearch" }models_search_cursor = { path = "../models_search_cursor" }non_empty = { path = "../non_empty" }+regex = { workspace = true }serde = { workspace = true }sqlx = { workspace = true }thiserror = { workspace = true }diff --git a/rust/cloud-storage/name_search/src/lib.rs b/rust/cloud-storage/name_search/src/lib.rsindex 2610cf8d67..cb70498701 100644--- a/rust/cloud-storage/name_search/src/lib.rs+++ b/rust/cloud-storage/name_search/src/lib.rs@@ -12,7 +12,7 @@ use models_search_cursor::{PaginatedResult, SearchCursorAttributes};pub use project::*;/// Escapes special regex characters in a search term-pub(crate) fn escape_regex(term: &str) -> String {+pub fn escape_regex(term: &str) -> String {let special_chars = ['\\', '.', '+', '*', '?', '(', ')', '[', ']', '{', '}', '^', '$', '|',];@@ -26,6 +26,66 @@ pub(crate) fn escape_regex(term: &str) -> String {escaped}+/// Applies the same `<macro_em>` name-highlight replacement that the Postgres+/// name-search queries apply via `regexp_replace(..., 'gi')`, but against an+/// in-memory name string. Returns `None` when the term is empty or the name+/// does not contain the term (case-insensitive).+pub fn highlight_name(name: &str, term: &str) -> Option<String> {+ let term = term.trim();+ if term.is_empty() {+ return None;+ }+ let re = regex::Regex::new(&format!("(?i)({})", escape_regex(term))).ok()?;+ if !re.is_match(name) {+ return None;+ }+ Some(re.replace_all(name, "<macro_em>$1</macro_em>").into_owned())+}++#[cfg(test)]+mod highlight_test {+ use super::highlight_name;++ #[test]+ fn returns_none_for_empty_term() {+ assert!(highlight_name("testingfoop", "").is_none());+ assert!(highlight_name("testingfoop", " ").is_none());+ }++ #[test]+ fn returns_none_when_name_does_not_match() {+ assert!(highlight_name("unrelated", "test").is_none());+ }++ #[test]+ fn wraps_substring_matches_case_insensitively() {+ assert_eq!(+ highlight_name("testingfoop", "test").as_deref(),+ Some("<macro_em>test</macro_em>ingfoop")+ );+ assert_eq!(+ highlight_name("MD CHECKBOX LIST TEST", "test").as_deref(),+ Some("MD CHECKBOX LIST <macro_em>TEST</macro_em>")+ );+ }++ #[test]+ fn wraps_all_occurrences() {+ assert_eq!(+ highlight_name("test of a test", "test").as_deref(),+ Some("<macro_em>test</macro_em> of a <macro_em>test</macro_em>")+ );+ }++ #[test]+ fn escapes_regex_specials_in_term() {+ assert_eq!(+ highlight_name("plan (v2) draft", "(v2)").as_deref(),+ Some("plan <macro_em>(v2)</macro_em> draft")+ );+ }+}+/// Errors for name search crate#[derive(Debug, thiserror::Error)]pub enum NameSearchError {diff --git a/rust/cloud-storage/search_service/src/api/search/document.rs b/rust/cloud-storage/search_service/src/api/search/document.rsindex 844e2ed9fc..8935f7221d 100644--- a/rust/cloud-storage/search_service/src/api/search/document.rs+++ b/rust/cloud-storage/search_service/src/api/search/document.rs@@ -2,10 +2,12 @@ use crate::api::search::simple::SearchError;use indexmap::IndexMap;use models_opensearch::SearchEntityType;use models_properties::{EntityReference, EntityType};+use models_search::SearchHighlight;use models_search::document::{DocumentSearchResponseItem, DocumentSearchResponseItemWithMetadata, DocumentSearchResult,};use models_soup::SoupProperty;+use name_search::highlight_name;use opensearch_client::search::model::SearchGotoContent;use sqlx::types::Uuid;use std::collections::HashMap;@@ -18,6 +20,7 @@ pub(in crate::api::search) async fn enrich_documents(ctx: &SearchHandlerState,user_id: &str,results: Vec<opensearch_client::search::model::SearchHit>,+ search_term: Option<&str>,) -> Result<Vec<DocumentSearchResponseItemWithMetadata>, SearchError> {let results: Vec<opensearch_client::search::model::SearchHit> = results.into_iter()@@ -77,8 +80,9 @@ pub(in crate::api::search) async fn enrich_documents(};// Construct enriched results- let enriched_results = construct_search_result(results, document_histories, properties_map)- .map_err(SearchError::InternalError)?;+ let enriched_results =+ construct_search_result(results, document_histories, properties_map, search_term)+ .map_err(SearchError::InternalError)?;Ok(enriched_results)}@@ -90,9 +94,10 @@ pub fn construct_search_result(macro_db_client::document::get_document_history::DocumentHistoryInfo,>,properties_map: HashMap<String, Vec<SoupProperty>>,+ search_term: Option<&str>,) -> anyhow::Result<Vec<DocumentSearchResponseItemWithMetadata>> {// construct entity hit map of id -> vec<hits> using IndexMap to preserve insertion order- let entity_id_hit_map: IndexMap<Uuid, Vec<DocumentSearchResult>> = search_results+ let mut entity_id_hit_map: IndexMap<Uuid, Vec<DocumentSearchResult>> = search_results.into_iter().map(|hit| {let result = if let Some(SearchGotoContent::Documents(goto)) = hit.goto {@@ -118,6 +123,33 @@ pub fn construct_search_result(map});+ // Docs that appear via content hits may still have a name that matches the+ // query, but the OpenSearch content query does not search the name field so+ // no `highlight.name` comes back. Synthesize one from the doc's name so the+ // sidebar can render the name highlight for those rows too.+ if let Some(term) = search_term {+ for (entity_id, hits) in entity_id_hit_map.iter_mut() {+ if hits.iter().any(|h| h.highlight.name.is_some()) {+ continue;+ }+ let Some(info) = document_histories.get(&entity_id.to_string()) else {+ continue;+ };+ let Some(highlighted) = highlight_name(&info.file_name, term) else {+ continue;+ };+ hits.push(DocumentSearchResult {+ node_id: None,+ highlight: SearchHighlight {+ name: Some(highlighted),+ ..Default::default()+ },+ raw_content: None,+ score: None,+ });+ }+ }+// now construct the search results in the original search result orderlet result: Vec<DocumentSearchResponseItemWithMetadata> = entity_id_hit_map.into_iter()diff --git a/rust/cloud-storage/search_service/src/api/search/document/test.rs b/rust/cloud-storage/search_service/src/api/search/document/test.rsindex 089eb1097e..686048d70b 100644--- a/rust/cloud-storage/search_service/src/api/search/document/test.rs+++ b/rust/cloud-storage/search_service/src/api/search/document/test.rs@@ -9,7 +9,7 @@ use super::*;#[test]fn test_construct_search_result_empty_input() {- let result = construct_search_result(vec![], HashMap::new(), HashMap::new());+ let result = construct_search_result(vec![], HashMap::new(), HashMap::new(), None);assert!(result.is_ok());assert_eq!(result.unwrap().len(), 0);}@@ -55,7 +55,7 @@ fn test_construct_search_result_single_document() {);let result =- construct_search_result(search_results, document_histories, HashMap::new()).unwrap();+ construct_search_result(search_results, document_histories, HashMap::new(), None).unwrap();assert_eq!(result.len(), 1);assert_eq!(@@ -146,7 +146,7 @@ fn test_construct_search_result_multiple_nodes_same_document() {);let result =- construct_search_result(search_results, document_histories, HashMap::new()).unwrap();+ construct_search_result(search_results, document_histories, HashMap::new(), None).unwrap();assert_eq!(result.len(), 1);assert_eq!(@@ -222,7 +222,7 @@ fn test_document_history_timestamps() {document_histories.insert("11111111-1111-1111-1111-111111111111".to_string(), history);// Call the function under test- let result = construct_search_result(input, document_histories, HashMap::new()).unwrap();+ let result = construct_search_result(input, document_histories, HashMap::new(), None).unwrap();// Verify that timestamps were copied from the document historyassert_eq!(result.len(), 1);@@ -256,7 +256,7 @@ fn test_document_history_missing_entry() {document_histories.insert("22222222-2222-2222-2222-222222222222".to_string(), history);// Call the function under test- let result = construct_search_result(input, document_histories, HashMap::new()).unwrap();+ let result = construct_search_result(input, document_histories, HashMap::new(), None).unwrap();// Documents without history info should not returnassert_eq!(result.len(), 0);@@ -287,7 +287,7 @@ fn test_document_history_null_viewed_at() {document_histories.insert("11111111-1111-1111-1111-111111111111".to_string(), history);// Call the function under test- let result = construct_search_result(input, document_histories, HashMap::new()).unwrap();+ let result = construct_search_result(input, document_histories, HashMap::new(), None).unwrap();// Verify that timestamps were copied correctly and viewed_at is Noneassert_eq!(result.len(), 1);@@ -339,7 +339,7 @@ fn test_document_history_multiple_documents() {document_histories.insert("22222222-2222-2222-2222-222222222222".to_string(), history2);// Call the function under test- let result = construct_search_result(input, document_histories, HashMap::new()).unwrap();+ let result = construct_search_result(input, document_histories, HashMap::new(), None).unwrap();// Verify that timestamps were copied correctly for both documentsassert_eq!(result.len(), 2);@@ -397,7 +397,7 @@ fn test_document_history_partial_missing_entries() {document_histories.insert("11111111-1111-1111-1111-111111111111".to_string(), history);// Call the function under test- let result = construct_search_result(input, document_histories, HashMap::new()).unwrap();+ let result = construct_search_result(input, document_histories, HashMap::new(), None).unwrap();// We should have 2 results - one with real data, one not foundassert_eq!(result.len(), 1);@@ -443,7 +443,7 @@ fn test_document_history_deleted() {);let result =- construct_search_result(input_deleted, document_histories, HashMap::new()).unwrap();+ construct_search_result(input_deleted, document_histories, HashMap::new(), None).unwrap();// Deleted document should be returned with metadata including deleted_atassert_eq!(result.len(), 1);@@ -465,6 +465,7 @@ fn test_document_history_deleted() {input_not_found,document_histories_not_found,HashMap::new(),+ None,).unwrap();@@ -598,12 +599,27 @@ fn test_sort_stability() {);}- let result1 =- construct_search_result(input.clone(), document_histories.clone(), HashMap::new()).unwrap();- let result2 =- construct_search_result(input.clone(), document_histories.clone(), HashMap::new()).unwrap();- let result3 =- construct_search_result(input.clone(), document_histories.clone(), HashMap::new()).unwrap();+ let result1 = construct_search_result(+ input.clone(),+ document_histories.clone(),+ HashMap::new(),+ None,+ )+ .unwrap();+ let result2 = construct_search_result(+ input.clone(),+ document_histories.clone(),+ HashMap::new(),+ None,+ )+ .unwrap();+ let result3 = construct_search_result(+ input.clone(),+ document_histories.clone(),+ HashMap::new(),+ None,+ )+ .unwrap();assert_eq!(result1.len(), 5);assert_eq!(result2.len(), 5);@@ -676,7 +692,7 @@ fn test_properties_enrichment_with_properties() {vec![make_test_soup_property("Assignees")],);- let result = construct_search_result(input, document_histories, properties_map).unwrap();+ let result = construct_search_result(input, document_histories, properties_map, None).unwrap();assert_eq!(result.len(), 1);let props = result[0]@@ -710,8 +726,125 @@ fn test_properties_enrichment_empty_map() {},);- let result = construct_search_result(input, document_histories, HashMap::new()).unwrap();+ let result = construct_search_result(input, document_histories, HashMap::new(), None).unwrap();assert_eq!(result.len(), 1);assert!(result[0].properties.is_none());}++fn make_history(doc_id: &str, file_name: &str) -> DocumentHistoryInfo {+ let now = chrono::Utc::now();+ DocumentHistoryInfo {+ item_id: doc_id.to_string(),+ created_at: now,+ updated_at: now,+ viewed_at: None,+ project_id: None,+ file_type: Some("md".to_string()),+ file_name: file_name.to_string(),+ owner: "user1".to_string(),+ deleted_at: None,+ sub_type: None,+ }+}++#[test]+fn test_synthesizes_name_highlight_for_content_only_hit() {+ let doc_id = "11111111-1111-1111-1111-111111111111";+ let input = vec![create_test_document_response(+ doc_id,+ "node_1",+ Some(vec!["<macro_em>test</macro_em>ing body".to_string()]),+ )];++ let mut document_histories = HashMap::new();+ document_histories.insert(doc_id.to_string(), make_history(doc_id, "testingfoop"));++ let result =+ construct_search_result(input, document_histories, HashMap::new(), Some("test")).unwrap();++ assert_eq!(result.len(), 1);+ let hits = &result[0].extra.document_search_results;+ assert_eq!(hits.len(), 2, "original content hit + synthesized name hit");++ let name_hit = hits+ .iter()+ .find(|h| h.highlight.name.is_some())+ .expect("synthesized name hit should exist");+ assert_eq!(+ name_hit.highlight.name.as_deref(),+ Some("<macro_em>test</macro_em>ingfoop")+ );+ assert!(name_hit.node_id.is_none());+ assert!(name_hit.raw_content.is_none());+}++#[test]+fn test_does_not_synthesize_when_name_hit_already_present() {+ let doc_id = "11111111-1111-1111-1111-111111111111";+ let input = vec![opensearch_client::search::model::SearchHit {+ entity_id: doc_id.parse().unwrap(),+ entity_type: SearchEntityType::Documents,+ goto: None,+ score: None,+ highlight: Highlight {+ name: Some("<macro_em>test</macro_em> doc".to_string()),+ ..Default::default()+ },+ updated_at: None,+ }];++ let mut document_histories = HashMap::new();+ document_histories.insert(doc_id.to_string(), make_history(doc_id, "test doc"));++ let result =+ construct_search_result(input, document_histories, HashMap::new(), Some("test")).unwrap();++ assert_eq!(result[0].extra.document_search_results.len(), 1);+ assert_eq!(+ result[0].extra.document_search_results[0]+ .highlight+ .name+ .as_deref(),+ Some("<macro_em>test</macro_em> doc")+ );+}++#[test]+fn test_does_not_synthesize_when_name_does_not_match() {+ let doc_id = "11111111-1111-1111-1111-111111111111";+ let input = vec![create_test_document_response(+ doc_id,+ "node_1",+ Some(vec!["body matches test".to_string()]),+ )];++ let mut document_histories = HashMap::new();+ document_histories.insert(doc_id.to_string(), make_history(doc_id, "unrelated name"));++ let result =+ construct_search_result(input, document_histories, HashMap::new(), Some("test")).unwrap();++ let hits = &result[0].extra.document_search_results;+ assert_eq!(hits.len(), 1);+ assert!(hits[0].highlight.name.is_none());+}++#[test]+fn test_does_not_synthesize_when_search_term_is_none() {+ let doc_id = "11111111-1111-1111-1111-111111111111";+ let input = vec![create_test_document_response(+ doc_id,+ "node_1",+ Some(vec!["body".to_string()]),+ )];++ let mut document_histories = HashMap::new();+ document_histories.insert(doc_id.to_string(), make_history(doc_id, "testingfoop"));++ let result = construct_search_result(input, document_histories, HashMap::new(), None).unwrap();++ let hits = &result[0].extra.document_search_results;+ assert_eq!(hits.len(), 1);+ assert!(hits[0].highlight.name.is_none());+}diff --git a/rust/cloud-storage/search_service/src/api/search/enrich.rs b/rust/cloud-storage/search_service/src/api/search/enrich.rsindex 6bf08aca7a..bc2a02b3ee 100644--- a/rust/cloud-storage/search_service/src/api/search/enrich.rs+++ b/rust/cloud-storage/search_service/src/api/search/enrich.rs@@ -19,10 +19,11 @@ pub async fn enrich_search_response(user_id: &str,results: Vec<SearchHit>,entity_type: SearchEntityType,+ search_term: Option<&str>,) -> Result<Vec<UnifiedSearchResponseItem>, SearchError> {match entity_type {SearchEntityType::Documents => {- let response = enrich_documents(ctx, user_id, results).await?;+ let response = enrich_documents(ctx, user_id, results, search_term).await?;Ok(response.into_iter().map(UnifiedSearchResponseItem::Document)diff --git a/rust/cloud-storage/search_service/src/api/search/unified.rs b/rust/cloud-storage/search_service/src/api/search/unified.rsindex 32cf0e1eba..56871bb562 100644--- a/rust/cloud-storage/search_service/src/api/search/unified.rs+++ b/rust/cloud-storage/search_service/src/api/search/unified.rs@@ -49,6 +49,14 @@ pub async fn handler("unified_search");+ let document_name_term = match req.search_on {+ models_search::SearchOn::Name | models_search::SearchOn::NameContent => {+ let trimmed = req.query.trim();+ (!trimmed.is_empty()).then(|| trimmed.to_string())+ }+ models_search::SearchOn::Content => None,+ };+let (results, next_cursor) =perform_unified_search(&ctx, &user_context, query_params, req).await?;@@ -75,31 +83,36 @@ pub async fn handler(&ctx,&user_context.user_id,document,- models_opensearch::SearchEntityType::Documents+ models_opensearch::SearchEntityType::Documents,+ document_name_term.as_deref(),),enrich_search_response(&ctx,&user_context.user_id,chat,- models_opensearch::SearchEntityType::Chats+ models_opensearch::SearchEntityType::Chats,+ None,),enrich_search_response(&ctx,&user_context.user_id,channel_message,- models_opensearch::SearchEntityType::Channels+ models_opensearch::SearchEntityType::Channels,+ None,),enrich_search_response(&ctx,&user_context.user_id,project,- models_opensearch::SearchEntityType::Projects+ models_opensearch::SearchEntityType::Projects,+ None,),enrich_search_response(&ctx,&user_context.user_id,email,- models_opensearch::SearchEntityType::Emails+ models_opensearch::SearchEntityType::Emails,+ None,),).map_err(|e| SearchError::InternalError(anyhow::anyhow!("tokio error: {:?}", e)))?;