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): find channels by the name the viewer sees (#8364)
gbirman05108b54c267
diff --git a/.sqlx/query-8a1de26889315defbcc28c2fca5be575c947aa4509645530627c7614b87bbae3.json b/.sqlx/query-8a1de26889315defbcc28c2fca5be575c947aa4509645530627c7614b87bbae3.jsonnew file mode 100644index 0000000000..1e91f7c29b--- /dev/null+++ b/.sqlx/query-8a1de26889315defbcc28c2fca5be575c947aa4509645530627c7614b87bbae3.json@@ -0,0 +1,37 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH viewer_channels AS (\n SELECT c.id, c.name, c.channel_type, c.updated_at\n FROM comms_channel_participants me\n JOIN comms_channels c ON c.id = me.channel_id\n WHERE me.user_id = $1\n AND me.left_at IS NULL\n AND (cardinality($2::uuid[]) = 0 OR c.id = ANY($2::uuid[]))\n AND (cardinality($3::text[]) = 0 OR c.channel_type::text = ANY($3::text[]))\n AND (\n $4::timestamptz IS NULL\n OR (c.updated_at, c.id) < ($4::timestamptz, $5::uuid)\n )\n ),\n patterns AS (\n SELECT pattern, ordinality AS term\n FROM unnest($6::text[]) WITH ORDINALITY AS p(pattern, ordinality)\n ),\n other_participant_names AS (\n SELECT\n vc.id AS channel_id,\n CASE\n WHEN other.user_id LIKE 'bot|%' THEN COALESCE(system_bot.name, bot.name, 'Bot')\n ELSE COALESCE(\n NULLIF(\n concat_ws(\n ' ',\n NULLIF(mui.first_name, 'N/A'),\n NULLIF(mui.last_name, 'N/A')\n ),\n ''\n ),\n split_part(split_part(other.user_id, '|', 2), '@', 1)\n )\n END AS name\n FROM viewer_channels vc\n JOIN comms_channel_participants other\n ON other.channel_id = vc.id\n AND other.left_at IS NULL\n AND other.user_id <> $1\n LEFT JOIN \"User\" u ON u.id = other.user_id\n LEFT JOIN macro_user_info mui ON mui.macro_user_id = u.macro_user_id\n LEFT JOIN unnest($8::uuid[], $9::text[]) AS system_bot(id, name)\n ON other.user_id = 'bot|' || system_bot.id::text\n LEFT JOIN bots bot\n ON other.user_id = 'bot|' || bot.id::text\n AND bot.deleted_at IS NULL\n WHERE vc.channel_type = 'direct_message'\n OR (vc.channel_type = 'private' AND NULLIF(BTRIM(vc.name), '') IS NULL)\n ),\n matched_terms AS (\n SELECT vc.id AS channel_id, p.term\n FROM viewer_channels vc\n CROSS JOIN patterns p\n WHERE NULLIF(BTRIM(vc.name), '') IS NOT NULL\n AND CASE\n WHEN $7::bool THEN vc.name ~* p.pattern\n ELSE vc.name ILIKE p.pattern\n END\n UNION\n SELECT o.channel_id, p.term\n FROM other_participant_names o\n CROSS JOIN patterns p\n WHERE CASE\n WHEN $7::bool THEN o.name ~* p.pattern\n ELSE o.name ILIKE p.pattern\n END\n )\n SELECT vc.id AS \"id!\", vc.updated_at AS \"updated_at!\"\n FROM viewer_channels vc\n JOIN matched_terms m ON m.channel_id = vc.id\n GROUP BY vc.id, vc.updated_at\n HAVING count(DISTINCT m.term) = cardinality($6::text[])\n ORDER BY vc.updated_at DESC, vc.id DESC\n LIMIT $10\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "updated_at!",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "UuidArray",+ "TextArray",+ "Timestamptz",+ "Uuid",+ "TextArray",+ "Bool",+ "UuidArray",+ "TextArray",+ "Int8"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "8a1de26889315defbcc28c2fca5be575c947aa4509645530627c7614b87bbae3"+}diff --git a/.sqlx/query-b2a90ac44fc610837910a4911b23929b64d00021f63415a03e5a110510181b25.json b/.sqlx/query-b2a90ac44fc610837910a4911b23929b64d00021f63415a03e5a110510181b25.jsondeleted file mode 100644index e7e2bf490b..0000000000--- a/.sqlx/query-b2a90ac44fc610837910a4911b23929b64d00021f63415a03e5a110510181b25.json+++ /dev/null@@ -1,39 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT\n c.id as entity_id,\n c.name,\n c.updated_at\n FROM comms_channels c\n INNER JOIN comms_channel_participants cp ON cp.channel_id = c.id\n WHERE cp.user_id = $1\n AND cp.left_at IS NULL\n AND c.id = ANY($2::uuid[])\n AND (\n $3::timestamptz IS NULL\n OR (c.updated_at, c.id) < ($3, $4)\n )\n AND (\n NULLIF(BTRIM(c.name), '') IS NULL\n OR c.name ~* $5\n )\n ORDER BY c.updated_at DESC, c.id DESC\n LIMIT $6\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "entity_id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "name",- "type_info": "Varchar"- },- {- "ordinal": 2,- "name": "updated_at",- "type_info": "Timestamptz"- }- ],- "parameters": {- "Left": [- "Text",- "UuidArray",- "Timestamptz",- "Uuid",- "Text",- "Int8"- ]- },- "nullable": [- false,- true,- false- ]- },- "hash": "b2a90ac44fc610837910a4911b23929b64d00021f63415a03e5a110510181b25"-}diff --git a/Cargo.lock b/Cargo.lockindex 5efff2125b..06e10b9398 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4181,6 +4181,7 @@ dependencies = ["share_permission_db_utils","sqlx","static_file_service_client",+ "strum 0.27.2","thiserror 2.0.18","tokio","tokio-retry",diff --git a/crates/channels/AGENTS.md b/crates/channels/AGENTS.mdindex 19d3826e75..34f650100f 100644--- a/crates/channels/AGENTS.md+++ b/crates/channels/AGENTS.md@@ -17,6 +17,8 @@ DMs, and the shared message store other domains discuss things on.- `src/inbound/toolset.rs`: AI tools over channels (feature `ai_tools`).- `src/outbound/pg_channels_repo.rs`, `src/outbound/connection_gateway_realtime.rs`:storage and realtime delivery adapters.+- `src/outbound/channel_name.rs`: the viewer-dependent channel naming rule —+ batch name resolution and the SQL name search behind `name_search`.## Scopediff --git a/crates/channels/Cargo.toml b/crates/channels/Cargo.tomlindex 05a4778bb8..472c55c63b 100644--- a/crates/channels/Cargo.toml+++ b/crates/channels/Cargo.toml@@ -141,6 +141,7 @@ serde_json = { workspace = true, optional = true }share_permission_db_utils = { path = "../share_permission_db_utils", optional = true }sqlx = { workspace = true, optional = true }static_file_service_client = { path = "../static_file_service_client", optional = true }+strum = { workspace = true }thiserror = { workspace = true }tokio = { workspace = true, features = ["macros", "sync"], optional = true }tokio-retry = { workspace = true, optional = true }diff --git a/crates/channels/src/domain/models.rs b/crates/channels/src/domain/models.rsindex fa66b6d81f..986c0b56b4 100644--- a/crates/channels/src/domain/models.rs+++ b/crates/channels/src/domain/models.rs@@ -398,7 +398,9 @@ pub struct ThreadReplyRow {}/// Type of channel.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[derive(+ Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, strum::Display, strum::EnumString,+)]#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]#[cfg_attr(feature = "outbound", derive(sqlx::Type))]#[cfg_attr(@@ -406,6 +408,7 @@ pub struct ThreadReplyRow {sqlx(type_name = "comms_channel_type", rename_all = "snake_case"))]#[serde(rename_all = "snake_case")]+#[strum(serialize_all = "snake_case")]pub enum ChannelType {/// Public channel.Public,@@ -417,17 +420,6 @@ pub enum ChannelType {Team,}-impl std::fmt::Display for ChannelType {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- match self {- ChannelType::Public => f.write_str("public"),- ChannelType::Private => f.write_str("private"),- ChannelType::DirectMessage => f.write_str("direct_message"),- ChannelType::Team => f.write_str("team"),- }- }-}-/// Request to add a user to all organization channels.#[derive(Debug, Serialize, Deserialize)]#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]diff --git a/crates/channels/src/outbound/channel_name.rs b/crates/channels/src/outbound/channel_name.rsindex 0507623f23..92c2319efd 100644--- a/crates/channels/src/outbound/channel_name.rs+++ b/crates/channels/src/outbound/channel_name.rs@@ -1,12 +1,25 @@-//! Batch channel-name resolution backed by Postgres.+//! Viewer-aware channel names, backed by Postgres: batch resolution and name+//! search share one rule. A channel is known by its stored name when it has+//! one. DMs and unnamed private channels are known by the *other*+//! participants: people by `first_name last_name` from `macro_user_info`+//! (skipping `N/A` parts) or else the local part of their email, bots by their+//! registry name or `bots` row. Unnamed public and team channels fall back to+//! `#<id prefix>`. [`match_channel_names`] applies the same rule in SQL, so a+//! search finds exactly the channels whose resolved name the viewer would+//! recognise.use std::collections::{HashMap, HashSet};+use bot_id::BotId;+use chrono::{DateTime, Utc};use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use sqlx::PgPool;use uuid::Uuid;-use crate::domain::models::{ChannelType, NameLookup, fallback_user_name};+use super::pg_channels_repo::{+ load_bot_display_names, load_user_display_names, principal_display_name,+};+use crate::domain::models::{ChannelType, NameLookup};/// Batch-resolve display names for a list of channel ids from the perspective/// of `viewer_user_id`. The viewer is only used to pick the right "other@@ -24,25 +37,20 @@ pub async fn batch_resolve_channel_names<'a>(}let channels = load_channels(pool, channel_ids).await?;- let (participants_by_channel, name_lookup) =- load_viewer_dependent_names(pool, &channels).await?;+ let names = load_viewer_dependent_names(pool, &channels).await?;- let mut resolved: HashMap<Uuid, String> = HashMap::with_capacity(channels.len());- for (channel_id, (name, channel_type)) in &channels {- let empty = Vec::new();- let participants = participants_by_channel.get(channel_id).unwrap_or(&empty);- let resolved_name = resolve_channel_name(- *channel_type,- name.as_deref(),- *channel_id,- viewer_user_id.as_ref(),- participants,- &name_lookup,- );- resolved.insert(*channel_id, resolved_name);- }-- Ok(resolved)+ Ok(channels+ .iter()+ .map(|(channel_id, (name, channel_type))| {+ let resolved_name = names.resolve(+ *channel_type,+ name.as_deref(),+ *channel_id,+ viewer_user_id.as_ref(),+ );+ (*channel_id, resolved_name)+ })+ .collect())}/// Resolve the display name of one channel from the perspective of each of@@ -70,27 +78,190 @@ pub async fn resolve_channel_name_for_viewers<'a>(let Some((name, channel_type)) = channels.get(&channel_id) else {return Ok(HashMap::new());};- let (participants_by_channel, name_lookup) =- load_viewer_dependent_names(pool, &channels).await?;- let empty = Vec::new();- let participants = participants_by_channel.get(&channel_id).unwrap_or(&empty);+ let names = load_viewer_dependent_names(pool, &channels).await?;Ok(viewer_user_ids.iter().map(|viewer| {- let resolved_name = resolve_channel_name(- *channel_type,- name.as_deref(),- channel_id,- viewer.as_ref(),- participants,- &name_lookup,- );+ let resolved_name =+ names.resolve(*channel_type, name.as_deref(), channel_id, viewer.as_ref());(viewer.clone().into_owned(), resolved_name)}).collect())}+/// A channel whose viewer-facing name matched a [`ChannelNameSearch`].+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ChannelNameMatch {+ /// The matched channel.+ pub channel_id: Uuid,+ /// The channel's `updated_at`, which orders the matches.+ pub updated_at: DateTime<Utc>,+}++/// A name search over the channels a viewer actively participates in.+#[derive(Debug)]+pub struct ChannelNameSearch<'a> {+ /// Whose channels to search, and whose view of each name to match.+ pub viewer_user_id: MacroUserIdStr<'a>,+ /// One pattern per search term. A channel matches when every pattern+ /// matches its stored name or the display name of some participant other+ /// than the viewer.+ pub patterns: &'a [String],+ /// Patterns are case-insensitive POSIX regexes when set, `ILIKE` patterns+ /// otherwise.+ pub regex_patterns: bool,+ /// Only these channels; empty means every channel.+ pub channel_ids: &'a [Uuid],+ /// Only these channel types; empty means every type.+ pub channel_types: &'a [ChannelType],+ /// Keyset cursor: only channels ordered strictly after `(updated_at, id)`.+ pub after: Option<(DateTime<Utc>, Uuid)>,+ /// Maximum number of channels to return.+ pub limit: i64,+}++/// Channels, newest `updated_at` first, whose name as the viewer sees it+/// matches every pattern of `search`: each pattern must match the stored name+/// or the display name of some participant other than the viewer, so a+/// two-term search finds an unnamed group by two of its members. Only the+/// viewer's active participations are considered, which also scopes the+/// search to channels the viewer may see.+#[tracing::instrument(+ skip_all,+ fields(+ user_id = %search.viewer_user_id.as_ref(),+ pattern_count = search.patterns.len(),+ channel_types = ?search.channel_types,+ channel_id_count = search.channel_ids.len(),+ limit = search.limit,+ result_count = tracing::field::Empty,+ ),+ err+)]+pub async fn match_channel_names(+ pool: &PgPool,+ search: ChannelNameSearch<'_>,+) -> Result<Vec<ChannelNameMatch>, sqlx::Error> {+ if search.patterns.is_empty() || search.limit <= 0 {+ return Ok(Vec::new());+ }+ let channel_types: Vec<String> = search+ .channel_types+ .iter()+ .map(ToString::to_string)+ .collect();+ let (after_updated_at, after_channel_id) = match search.after {+ Some((updated_at, channel_id)) => (Some(updated_at), Some(channel_id)),+ None => (None, None),+ };+ // First-party bots have no `bots` row; their names come from the registry.+ let (system_bot_ids, system_bot_names): (Vec<Uuid>, Vec<String>) = bot_id::SYSTEM_BOTS+ .iter()+ .map(|bot| (bot.id.as_uuid(), bot.name.to_string()))+ .unzip();++ let rows = sqlx::query!(+ r#"+ WITH viewer_channels AS (+ SELECT c.id, c.name, c.channel_type, c.updated_at+ FROM comms_channel_participants me+ JOIN comms_channels c ON c.id = me.channel_id+ WHERE me.user_id = $1+ AND me.left_at IS NULL+ AND (cardinality($2::uuid[]) = 0 OR c.id = ANY($2::uuid[]))+ AND (cardinality($3::text[]) = 0 OR c.channel_type::text = ANY($3::text[]))+ AND (+ $4::timestamptz IS NULL+ OR (c.updated_at, c.id) < ($4::timestamptz, $5::uuid)+ )+ ),+ patterns AS (+ SELECT pattern, ordinality AS term+ FROM unnest($6::text[]) WITH ORDINALITY AS p(pattern, ordinality)+ ),+ other_participant_names AS (+ SELECT+ vc.id AS channel_id,+ CASE+ WHEN other.user_id LIKE 'bot|%' THEN COALESCE(system_bot.name, bot.name, 'Bot')+ ELSE COALESCE(+ NULLIF(+ concat_ws(+ ' ',+ NULLIF(mui.first_name, 'N/A'),+ NULLIF(mui.last_name, 'N/A')+ ),+ ''+ ),+ split_part(split_part(other.user_id, '|', 2), '@', 1)+ )+ END AS name+ FROM viewer_channels vc+ JOIN comms_channel_participants other+ ON other.channel_id = vc.id+ AND other.left_at IS NULL+ AND other.user_id <> $1+ LEFT JOIN "User" u ON u.id = other.user_id+ LEFT JOIN macro_user_info mui ON mui.macro_user_id = u.macro_user_id+ LEFT JOIN unnest($8::uuid[], $9::text[]) AS system_bot(id, name)+ ON other.user_id = 'bot|' || system_bot.id::text+ LEFT JOIN bots bot+ ON other.user_id = 'bot|' || bot.id::text+ AND bot.deleted_at IS NULL+ WHERE vc.channel_type = 'direct_message'+ OR (vc.channel_type = 'private' AND NULLIF(BTRIM(vc.name), '') IS NULL)+ ),+ matched_terms AS (+ SELECT vc.id AS channel_id, p.term+ FROM viewer_channels vc+ CROSS JOIN patterns p+ WHERE NULLIF(BTRIM(vc.name), '') IS NOT NULL+ AND CASE+ WHEN $7::bool THEN vc.name ~* p.pattern+ ELSE vc.name ILIKE p.pattern+ END+ UNION+ SELECT o.channel_id, p.term+ FROM other_participant_names o+ CROSS JOIN patterns p+ WHERE CASE+ WHEN $7::bool THEN o.name ~* p.pattern+ ELSE o.name ILIKE p.pattern+ END+ )+ SELECT vc.id AS "id!", vc.updated_at AS "updated_at!"+ FROM viewer_channels vc+ JOIN matched_terms m ON m.channel_id = vc.id+ GROUP BY vc.id, vc.updated_at+ HAVING count(DISTINCT m.term) = cardinality($6::text[])+ ORDER BY vc.updated_at DESC, vc.id DESC+ LIMIT $10+ "#,+ search.viewer_user_id.as_ref(),+ search.channel_ids,+ &channel_types,+ after_updated_at,+ after_channel_id,+ search.patterns,+ search.regex_patterns,+ &system_bot_ids,+ &system_bot_names,+ search.limit,+ )+ .fetch_all(pool)+ .await?;+ tracing::Span::current().record("result_count", rows.len());++ Ok(rows+ .into_iter()+ .map(|row| ChannelNameMatch {+ channel_id: row.id,+ updated_at: row.updated_at,+ })+ .collect())+}+type LoadedChannels = HashMap<Uuid, (Option<String>, ChannelType)>;async fn load_channels(pool: &PgPool, channel_ids: &[Uuid]) -> Result<LoadedChannels, sqlx::Error> {@@ -111,12 +282,44 @@ async fn load_channels(pool: &PgPool, channel_ids: &[Uuid]) -> Result<LoadedChan.collect())}-/// Load participants and display names only for the channels whose name-/// depends on who is looking (DMs and unnamed private channels).+/// Participants and display names of the channels whose name depends on who+/// is looking (DMs and unnamed private channels).+#[derive(Default)]+struct ViewerDependentNames {+ participants_by_channel: HashMap<Uuid, Vec<String>>,+ user_names: NameLookup,+ bot_names: HashMap<BotId, String>,+}++impl ViewerDependentNames {+ fn resolve(+ &self,+ channel_type: ChannelType,+ stored_name: Option<&str>,+ channel_id: Uuid,+ viewer_user_id: &str,+ ) -> String {+ let participants = self+ .participants_by_channel+ .get(&channel_id)+ .map(Vec::as_slice)+ .unwrap_or_default();+ resolve_channel_name(+ channel_type,+ stored_name,+ channel_id,+ viewer_user_id,+ participants,+ &self.user_names,+ &self.bot_names,+ )+ }+}+async fn load_viewer_dependent_names(pool: &PgPool,channels: &LoadedChannels,-) -> Result<(HashMap<Uuid, Vec<MacroUserIdStr<'static>>>, NameLookup), sqlx::Error> {+) -> Result<ViewerDependentNames, sqlx::Error> {let needs_participants: Vec<Uuid> = channels.iter().filter(|(_, (name, ct))| {@@ -128,71 +331,44 @@ async fn load_viewer_dependent_names(.collect();if needs_participants.is_empty() {- return Ok((HashMap::new(), HashMap::new()));+ return Ok(ViewerDependentNames::default());}- load_participants_and_names(pool, &needs_participants).await-}-async fn load_participants_and_names(- pool: &PgPool,- channel_ids: &[Uuid],-) -> Result<(HashMap<Uuid, Vec<MacroUserIdStr<'static>>>, NameLookup), sqlx::Error> {let participant_rows = sqlx::query!(r#"SELECT channel_id, user_idFROM comms_channel_participantsWHERE channel_id = ANY($1) AND left_at IS NULL"#,- channel_ids+ &needs_participants).fetch_all(pool).await?;- let mut participants_by_channel: HashMap<Uuid, Vec<MacroUserIdStr<'static>>> = HashMap::new();- let mut all_user_ids: HashSet<MacroUserIdStr<'static>> = HashSet::new();+ let mut participants_by_channel: HashMap<Uuid, Vec<String>> = HashMap::new();+ let mut user_ids: HashSet<MacroUserIdStr<'static>> = HashSet::new();+ let mut bot_ids: HashSet<BotId> = HashSet::new();for row in participant_rows {- let Ok(user_id) = MacroUserIdStr::try_from(row.user_id) else {- continue;- };- all_user_ids.insert(user_id.clone());+ if let Ok(user_id) = MacroUserIdStr::try_from(row.user_id.clone()) {+ user_ids.insert(user_id);+ } else if let Ok(bot) = bot_id::BotIdStr::parse_from_str(&row.user_id) {+ bot_ids.insert(bot.bot_id());+ }participants_by_channel.entry(row.channel_id).or_default()- .push(user_id);+ .push(row.user_id);}+ let user_ids: Vec<MacroUserIdStr<'static>> = user_ids.into_iter().collect();+ let bot_ids: Vec<BotId> = bot_ids.into_iter().collect();+ let user_names = load_user_display_names(pool, &user_ids).await?;+ let bot_names = load_bot_display_names(pool, &bot_ids).await?;- let user_id_strings: Vec<String> = all_user_ids- .iter()- .map(|user_id| user_id.as_ref().to_string())- .collect();- let user_ids_by_string: HashMap<_, _> = all_user_ids- .into_iter()- .map(|user_id| (user_id.as_ref().to_string(), user_id))- .collect();- let name_rows = sqlx::query!(- r#"- SELECT u.id as user_profile_id, mui.first_name, mui.last_name- FROM macro_user_info mui- JOIN "User" u ON mui.macro_user_id = u.macro_user_id- WHERE u.id = ANY($1)- "#,- &user_id_strings- )- .fetch_all(pool)- .await?;-- let mut name_lookup = NameLookup::new();- for row in name_rows {- let Some(name) = display_name(row.first_name.as_deref(), row.last_name.as_deref()) else {- continue;- };- let Some(user_id) = user_ids_by_string.get(&row.user_profile_id) else {- continue;- };- name_lookup.insert(user_id.clone(), name);- }-- Ok((participants_by_channel, name_lookup))+ Ok(ViewerDependentNames {+ participants_by_channel,+ user_names,+ bot_names,+ })}fn resolve_channel_name(@@ -200,21 +376,24 @@ fn resolve_channel_name(stored_name: Option<&str>,channel_id: Uuid,viewer_user_id: &str,- participants: &[MacroUserIdStr<'static>],- name_lookup: &NameLookup,+ participants: &[String],+ user_names: &NameLookup,+ bot_names: &HashMap<BotId, String>,) -> String {if let Some(name) = stored_name.filter(|name| !name.trim().is_empty()) {return name.to_string();}+ let other_names = || {+ participants+ .iter()+ .filter(|principal| principal.as_str() != viewer_user_id)+ .filter_map(|principal| principal_display_name(principal, user_names, bot_names))+ };match channel_type {ChannelType::Public | ChannelType::Team => format!("#{}", &channel_id.to_string()[..8]),ChannelType::Private => {- let mut names: Vec<_> = participants- .iter()- .filter(|id| id.as_ref() != viewer_user_id)- .map(|id| id_to_display_name(id, name_lookup))- .collect();+ let mut names: Vec<String> = other_names().collect();names.sort();if names.is_empty() {"Private channel".to_string()@@ -222,45 +401,11 @@ fn resolve_channel_name(names.join(", ")}}- ChannelType::DirectMessage => participants- .iter()- .find(|id| id.as_ref() != viewer_user_id)- .map(|id| id_to_display_name(id, name_lookup))+ ChannelType::DirectMessage => other_names()+ .next().unwrap_or_else(|| "Direct message".to_string()),}}-fn id_to_display_name(user_id: &MacroUserIdStr<'static>, name_lookup: &NameLookup) -> String {- match name_lookup.get(user_id) {- Some(name) if !name.trim().is_empty() => name.clone(),- _ => fallback_user_name(user_id),- }-}--fn display_name(first: Option<&str>, last: Option<&str>) -> Option<String> {- const NA: &str = "N/A";- match (first.filter(|v| *v != NA), last.filter(|v| *v != NA)) {- (None, None) => None,- (None, Some(last)) => Some(last.to_string()),- (Some(first), None) => Some(first.to_string()),- (Some(first), Some(last)) => Some(format!("{first} {last}")),- }-}-#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn id_to_display_name_falls_back_to_email_local_part() {- let name_lookup = NameLookup::new();-- let user_id =- MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap();-- assert_eq!(- id_to_display_name(&user_id, &name_lookup),- "shepherd.hatton"- );- }-}+mod test;diff --git a/crates/channels/src/outbound/channel_name/test.rs b/crates/channels/src/outbound/channel_name/test.rsnew file mode 100644index 0000000000..4dd88adaa0--- /dev/null+++ b/crates/channels/src/outbound/channel_name/test.rs@@ -0,0 +1,48 @@+use super::*;++#[test]+fn direct_message_falls_back_to_the_other_participants_email_local_part() {+ let participants = vec![+ "macro|[email protected]".to_string(),+ "macro|[email protected]".to_string(),+ ];++ let name = resolve_channel_name(+ ChannelType::DirectMessage,+ None,+ Uuid::nil(),+ "macro|[email protected]",+ &participants,+ &NameLookup::new(),+ &HashMap::new(),+ );++ assert_eq!(name, "shepherd.hatton");+}++#[test]+fn unnamed_private_channel_lists_people_and_bots_but_not_the_viewer() {+ let participants = vec![+ "macro|[email protected]".to_string(),+ "macro|[email protected]".to_string(),+ "bot|00000000-0000-0000-0000-00000000c1a0".to_string(),+ ];+ let mut user_names = NameLookup::new();+ user_names.insert(+ MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap(),+ "Gabriel Birman".to_string(),+ );+ let bot_names = HashMap::from([(bot_id::CLAUDE_BOT_ID, "Claude".to_string())]);++ let name = resolve_channel_name(+ ChannelType::Private,+ Some(" "),+ Uuid::nil(),+ "macro|[email protected]",+ &participants,+ &user_names,+ &bot_names,+ );++ assert_eq!(name, "Claude, Gabriel Birman");+}diff --git a/crates/channels/src/outbound/pg_channels_repo.rs b/crates/channels/src/outbound/pg_channels_repo.rsindex bc2e315b23..595d7b72a1 100644--- a/crates/channels/src/outbound/pg_channels_repo.rs+++ b/crates/channels/src/outbound/pg_channels_repo.rs@@ -293,7 +293,7 @@ async fn resolve_channel_display_name(/// Display name for a participant principal: users resolve through the name/// lookup, bots through the bot-name lookup (Macro AI is code-defined)./// Unrecognized principals yield `None`.-fn principal_display_name(+pub(super) fn principal_display_name(principal: &str,name_lookup: &NameLookup,bot_name_lookup: &HashMap<BotId, String>,@@ -332,10 +332,10 @@ async fn load_active_participant_principals(Ok(rows.into_iter().map(|row| row.user_id).collect())}-async fn load_bot_display_names(+pub(super) async fn load_bot_display_names(pool: &PgPool,bot_ids: &[BotId],-) -> anyhow::Result<HashMap<BotId, String>> {+) -> Result<HashMap<BotId, String>, sqlx::Error> {if bot_ids.is_empty() {return Ok(HashMap::new());}@@ -369,10 +369,10 @@ async fn load_bot_display_names(Ok(names)}-async fn load_user_display_names(+pub(super) async fn load_user_display_names(pool: &PgPool,user_ids: &[MacroUserIdStr<'static>],-) -> anyhow::Result<NameLookup> {+) -> Result<NameLookup, sqlx::Error> {if user_ids.is_empty() {return Ok(NameLookup::new());}diff --git a/crates/macro_db_client/migrations/20261020170927_channel_name_trgm_index.sql b/crates/macro_db_client/migrations/20261020170927_channel_name_trgm_index.sqlnew file mode 100644index 0000000000..dc46c69002--- /dev/null+++ b/crates/macro_db_client/migrations/20261020170927_channel_name_trgm_index.sql@@ -0,0 +1,6 @@+-- no-transaction++-- Channel name search matches `comms_channels.name ILIKE '%term%'`; a trigram+-- index serves that substring match (pg_trgm is created by 20260106165341).+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_comms_channels_name_trgm+ ON comms_channels USING gin (name gin_trgm_ops);diff --git a/crates/models_search/src/channel.rs b/crates/models_search/src/channel.rsindex 66da311d61..a69417cf0a 100644--- a/crates/models_search/src/channel.rs+++ b/crates/models_search/src/channel.rs@@ -86,9 +86,10 @@ pub struct ChannelSearchResponseItemWithMetadata {/// Request for viewer-aware channel name search.#[derive(Debug, Serialize, Deserialize, ToSchema, JsonSchema)]pub struct ChannelNameSearchRequest {- /// Channel name prefix or exact token to search for.+ /// Channel name text to search for; every whitespace- or comma-separated+ /// term must match the name the viewer sees.pub query: String,- /// Whether to use prefix or exact-token matching.+ /// Whether terms match as substrings or as whole tokens.pub match_type: MatchType,}diff --git a/crates/models_search_cursor/src/lib.rs b/crates/models_search_cursor/src/lib.rsindex cc544415e4..286746e4cd 100644--- a/crates/models_search_cursor/src/lib.rs+++ b/crates/models_search_cursor/src/lib.rs@@ -162,6 +162,10 @@ pub struct SearchCursor {/// before CRM search existed still decode (defaults to a fresh cursor).#[serde(default)]pub crm_company_cursor: SearchCursorOption,+ /// The channel name cursor. `#[serde(default)]` so cursors minted before+ /// channels were name-searched in Postgres still decode.+ #[serde(default)]+ pub channel_name_cursor: SearchCursorOption,}impl SearchCursor {@@ -186,6 +190,7 @@ impl SearchCursor {&& self.content_cursor.is_done()&& self.project_name_cursor.is_done()&& self.crm_company_cursor.is_done()+ && self.channel_name_cursor.is_done()}}@@ -212,6 +217,20 @@ mod test {assert!(!cursor.is_exhausted());}+ /// A cursor minted before channels were name-searched in Postgres (no+ /// `channel_name_cursor` field) decodes with a fresh channel cursor, so+ /// the next page runs the channel search from the start.+ #[test]+ fn decodes_legacy_cursor_without_channel_name_field() {+ let legacy = r#"{"chat_name_cursor":"Done","content_cursor":"Done","project_name_cursor":"Done","crm_company_cursor":"Done"}"#;+ let encoded = BASE64.encode(legacy);++ let cursor = SearchCursor::decode(&encoded).expect("legacy cursor should decode");++ assert!(cursor.channel_name_cursor.has_more());+ assert!(!cursor.is_exhausted());+ }+#[test]fn crm_cursor_round_trips() {let cursor = SearchCursor {@@ -223,12 +242,13 @@ mod test {}#[test]- fn is_exhausted_requires_crm_done() {+ fn is_exhausted_requires_every_source_done() {let mut cursor = SearchCursor {chat_name_cursor: SearchCursorOption::Done,content_cursor: SearchCursorOption::Done,project_name_cursor: SearchCursorOption::Done,crm_company_cursor: SearchCursorOption::Done,+ channel_name_cursor: SearchCursorOption::Done,};assert!(cursor.is_exhausted());@@ -237,5 +257,12 @@ mod test {!cursor.is_exhausted(),"a not-done CRM cursor must keep the aggregate cursor alive");++ cursor.crm_company_cursor = SearchCursorOption::Done;+ cursor.channel_name_cursor = SearchCursorOption::NotDone(None);+ assert!(+ !cursor.is_exhausted(),+ "a not-done channel name cursor must keep the aggregate cursor alive"+ );}}diff --git a/crates/name_search/AGENTS.md b/crates/name_search/AGENTS.mdindex e966d0c547..d9348a53b0 100644--- a/crates/name_search/AGENTS.md+++ b/crates/name_search/AGENTS.md@@ -2,13 +2,18 @@## What it is-Part of the Search feature. Postgres queries for server-side name search-over channels and chats (used by AI tools and `search_service`'s name-match-path), plus match highlighting.+Part of the Search feature. Postgres name search over channels and chats,+used by `search_service`'s name-match path (unified `/search` in `name` and+`name_content` mode, `/search/channel/name`) and by AI tools, plus match+highlighting.## Start here-- `src/channel.rs` + `src/channel/test.rs`: `search_channel_names`.+- `src/channel.rs` + `src/channel/test.rs`: `search_channel_names`. Viewer-aware:+ a DM is found by the other participant, an unnamed private channel by any+ other member, a persona DM by its bot. The SQL match is+ `channels::outbound::channel_name::match_channel_names`; this crate splits+ the query into terms, builds the patterns, pages, resolves and highlights.- `src/chat.rs` + `src/chat/test.rs`: `search_chat_names`.- `src/highlight.rs`: `highlight_name` — marks up matched substrings.- `fixtures/`: SQL seed fixtures (`channel.sql`, `chat.sql`, `chat_tags.sql`)@@ -16,9 +21,12 @@ path), plus match highlighting.## Scope-- Owns: name-search SQL queries and result cursors for channels/chats.-- Not here: content/full-text search → `models_search`, `search_service`;- the OpenSearch-indexed entity types → `models_opensearch`.+- Owns: name-search patterns, cursors and highlighting for channels/chats; the+ chat name SQL.+- Not here: the channel naming rule and its SQL → `channels`+ (`src/outbound/channel_name.rs`); content/full-text search →+ `models_search`, `search_service`; the OpenSearch-indexed entity types →+ `models_opensearch`.## Boundariesdiff --git a/crates/name_search/fixtures/channel.sql b/crates/name_search/fixtures/channel.sqlindex a0078f2377..03b7f9aa03 100644--- a/crates/name_search/fixtures/channel.sql+++ b/crates/name_search/fixtures/channel.sql@@ -1,3 +1,32 @@+INSERT INTO macro_user (id, username, email, stripe_customer_id)+VALUES+ ('a0000000-0000-0000-0000-000000000000', 'member', '[email protected]', 'cus_member'),+ ('a0000000-0000-0000-0000-000000000001', 'gabriel', '[email protected]', 'cus_gabriel'),+ ('a0000000-0000-0000-0000-000000000002', 'peter', '[email protected]', 'cus_peter'),+ ('a0000000-0000-0000-0000-000000000003', 'teo', '[email protected]', 'cus_teo'),+ ('a0000000-0000-0000-0000-000000000004', 'hollis', '[email protected]', 'cus_hollis');++INSERT INTO "User" (id, email, macro_user_id)+VALUES+ ('macro|[email protected]', '[email protected]', 'a0000000-0000-0000-0000-000000000000'),+ ('macro|[email protected]', '[email protected]', 'a0000000-0000-0000-0000-000000000001'),+ ('macro|[email protected]', '[email protected]', 'a0000000-0000-0000-0000-000000000002'),+ ('macro|[email protected]', '[email protected]', 'a0000000-0000-0000-0000-000000000003'),+ ('macro|[email protected]', '[email protected]', 'a0000000-0000-0000-0000-000000000004');++-- The member has no profile and [email protected] has no user row at all:+-- both fall back to the local part of their email.+INSERT INTO macro_user_info (macro_user_id, first_name, last_name)+VALUES+ ('a0000000-0000-0000-0000-000000000001', 'Gabriel', 'Birman'),+ ('a0000000-0000-0000-0000-000000000002', 'Peter', 'Chinman'),+ ('a0000000-0000-0000-0000-000000000003', 'Teo', 'Nys'),+ ('a0000000-0000-0000-0000-000000000004', 'Hollis', 'N/A');++INSERT INTO bots (id, kind, owner_user_id, name, handle, created_by)+VALUES+ ('b0000000-0000-0000-0000-000000000001', 'owned', 'macro|[email protected]', 'Deal Desk', 'deal-desk', 'macro|[email protected]');+INSERT INTO comms_channels (id, name, channel_type, owner_id, created_at, updated_at)VALUES('11111111-1111-1111-1111-111111111111', 'Macro', 'private', 'macro|[email protected]', '2024-01-01 10:00:00+00', '2024-12-01 10:00:00+00'),@@ -5,7 +34,14 @@ VALUES('33333333-3333-3333-3333-333333333333', 'Macaroni', 'private', 'macro|[email protected]', '2024-01-03 10:00:00+00', '2024-12-03 10:00:00+00'),('44444444-4444-4444-4444-444444444444', 'Macro Secret', 'private', 'macro|[email protected]', '2024-01-04 10:00:00+00', '2024-12-04 10:00:00+00'),('55555555-5555-5555-5555-555555555555', 'Macro Former', 'private', 'macro|[email protected]', '2024-01-05 10:00:00+00', '2024-12-05 10:00:00+00'),- ('66666666-6666-6666-6666-666666666666', NULL, 'direct_message', 'macro|[email protected]', '2024-01-06 10:00:00+00', '2024-12-06 10:00:00+00');+ ('66666666-6666-6666-6666-666666666666', NULL, 'direct_message', 'macro|[email protected]', '2024-01-06 10:00:00+00', '2024-12-06 10:00:00+00'),+ ('77777777-7777-7777-7777-777777777777', NULL, 'private', 'macro|[email protected]', '2024-01-07 10:00:00+00', '2024-12-07 10:00:00+00'),+ ('88888888-8888-8888-8888-888888888888', NULL, 'direct_message', 'macro|[email protected]', '2024-01-08 10:00:00+00', '2024-12-08 10:00:00+00'),+ ('99999999-9999-9999-9999-999999999999', NULL, 'direct_message', 'macro|[email protected]', '2024-01-09 10:00:00+00', '2024-12-09 10:00:00+00'),+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', NULL, 'direct_message', 'macro|[email protected]', '2024-01-10 10:00:00+00', '2024-12-10 10:00:00+00'),+ ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'Design Decks', 'public', 'macro|[email protected]', '2024-01-11 10:00:00+00', '2024-12-11 10:00:00+00'),+ ('cccccccc-cccc-cccc-cccc-cccccccccccc', NULL, 'direct_message', 'macro|[email protected]', '2024-01-12 10:00:00+00', '2024-12-12 10:00:00+00'),+ ('dddddddd-dddd-dddd-dddd-dddddddddddd', NULL, 'direct_message', 'macro|[email protected]', '2024-01-13 10:00:00+00', '2024-12-13 10:00:00+00');INSERT INTO comms_channel_participants (channel_id, role, user_id, left_at)VALUES@@ -15,4 +51,19 @@ VALUES('44444444-4444-4444-4444-444444444444', 'owner', 'macro|[email protected]', NULL),('55555555-5555-5555-5555-555555555555', 'owner', 'macro|[email protected]', '2024-06-01 10:00:00+00'),('66666666-6666-6666-6666-666666666666', 'owner', 'macro|[email protected]', NULL),- ('66666666-6666-6666-6666-666666666666', 'member', 'macro|[email protected]', NULL);+ ('66666666-6666-6666-6666-666666666666', 'member', 'macro|[email protected]', NULL),+ ('77777777-7777-7777-7777-777777777777', 'owner', 'macro|[email protected]', NULL),+ ('77777777-7777-7777-7777-777777777777', 'member', 'macro|[email protected]', NULL),+ ('77777777-7777-7777-7777-777777777777', 'member', 'macro|[email protected]', NULL),+ ('88888888-8888-8888-8888-888888888888', 'owner', 'macro|[email protected]', NULL),+ ('88888888-8888-8888-8888-888888888888', 'member', 'macro|[email protected]', NULL),+ ('99999999-9999-9999-9999-999999999999', 'owner', 'macro|[email protected]', NULL),+ ('99999999-9999-9999-9999-999999999999', 'member', 'bot|00000000-0000-0000-0000-00000000c1a0', NULL),+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'owner', 'macro|[email protected]', NULL),+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'member', 'bot|b0000000-0000-0000-0000-000000000001', NULL),+ ('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'owner', 'macro|[email protected]', NULL),+ ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'owner', 'macro|[email protected]', NULL),+ ('cccccccc-cccc-cccc-cccc-cccccccccccc', 'member', 'macro|[email protected]', NULL),+ -- A bot with no `bots` row (deleted or unknown) shows as "Bot".+ ('dddddddd-dddd-dddd-dddd-dddddddddddd', 'owner', 'macro|[email protected]', NULL),+ ('dddddddd-dddd-dddd-dddd-dddddddddddd', 'member', 'bot|b0000000-0000-0000-0000-000000000002', NULL);diff --git a/crates/name_search/src/channel.rs b/crates/name_search/src/channel.rsindex ddf72392d9..7f0284473e 100644--- a/crates/name_search/src/channel.rs+++ b/crates/name_search/src/channel.rs@@ -1,8 +1,11 @@-//! This module contains logic for searching channels by name.+//! Viewer-aware channel name search. Postgres finds the channels whose name,+//! as the viewer sees it, matches (`channels::outbound::channel_name`); the+//! page of hits is then resolved to those names and highlighted.-#[cfg(not(test))]-use cached::proc_macro::cached;-use channels::outbound::channel_name::batch_resolve_channel_names;+use channels::domain::models::ChannelType;+use channels::outbound::channel_name::{+ ChannelNameSearch, batch_resolve_channel_names, match_channel_names,+};use macro_user_id::{lowercased::Lowercase,user_id::{MacroUserId, MacroUserIdStr},@@ -12,170 +15,106 @@ use sqlx::{Pool, Postgres};use uuid::Uuid;use crate::{- NameSearchError, NameSearchResult, PaginatedResult, SearchEntityType, escape_regex,- highlight_name,+ NameSearchError, NameSearchResult, PaginatedResult, SearchEntityType, escape_like,+ escape_regex, highlight::highlight_name_terms,};-const CANDIDATE_BATCH_SIZE: i64 = 256;+/// Narrows a channel name search beyond the viewer's own participation.+#[derive(Debug, Default)]+pub struct ChannelNameSearchScope<'a> {+ /// Only these channels; empty means every channel the viewer is in.+ pub channel_ids: &'a [Uuid],+ /// Only these channel types; empty means every type.+ pub channel_types: &'a [ChannelType],+}-/// Searches the names of channels in which the user is an active participant.-#[tracing::instrument(skip(db), err)]-#[cfg_attr(- not(test),- cached(- time = 30,- result = true,- key = "String",- convert = r#"{ format!("{}-{:?}-{}-{}-{}-{:?}", macro_user_id.as_ref(), channel_ids, term, exact_match, limit, cursor.as_ref().and_then(|c| c.as_updated_at()).map(|(id, ts)| format!("{}-{}", id, ts)).unwrap_or_default()) }"#- )-)]-pub async fn search_channel_names<'a>(- db: &Pool<Postgres>,- macro_user_id: &MacroUserId<Lowercase<'a>>,- channel_ids: &[Uuid],- term: String,- exact_match: bool,- limit: u32,- cursor: Option<SearchMethodCursor>,-) -> Result<PaginatedResult<NameSearchResult>, NameSearchError> {- search_channel_names_in_batches(- db,- macro_user_id,- channel_ids,- term,+/// Searches the names of channels in which the user is an active participant,+/// as that user sees them: stored names, and for DMs and unnamed private+/// channels the other participants' names. `term` splits on whitespace and+/// commas; every part must match the stored name or some other participant,+/// as a case-insensitive substring, or as a whole word when `exact_match` is+/// set. Results are newest `updated_at` first with the matched name+/// highlighted.+#[tracing::instrument(+ skip_all,+ fields(+ user_id = %macro_user_id.as_ref(),+ channel_types = ?scope.channel_types,+ channel_id_count = scope.channel_ids.len(),+ term_len = term.len(),exact_match,limit,- cursor,- CANDIDATE_BATCH_SIZE,- )- .await-}--#[allow(clippy::too_many_arguments)]-async fn search_channel_names_in_batches<'a>(+ result_count = tracing::field::Empty,+ ),+ err+)]+pub async fn search_channel_names<'a>(db: &Pool<Postgres>,macro_user_id: &MacroUserId<Lowercase<'a>>,- channel_ids: &[Uuid],+ scope: ChannelNameSearchScope<'_>,term: String,exact_match: bool,limit: u32,cursor: Option<SearchMethodCursor>,- candidate_batch_size: i64,) -> Result<PaginatedResult<NameSearchResult>, NameSearchError> {- if term.is_empty() {+ let terms: Vec<&str> = term+ .split(|c: char| c.is_whitespace() || c == ',')+ .filter(|part| !part.is_empty())+ .collect();+ if terms.is_empty() {return Err(NameSearchError::EmptySearchTerm);}- if cursor.as_ref().is_some_and(|c| c.as_updated_at().is_none()) {- return Err(NameSearchError::IncompatibleCursor);- }- if channel_ids.is_empty() {- return Ok(PaginatedResult {- items: vec![],- cursor: SearchCursorOption::Done,- });- }-- let mut scan_cursor = cursor- .as_ref()- .and_then(|c| c.as_updated_at())- .map(|(id, ts)| (ts, id));- let viewer_user_id = MacroUserIdStr(macro_user_id.clone());- let search_pattern = if exact_match {- format!(r"(^|\W){}($|\W)", escape_regex(&term))- } else {- format!(r"(^|\W){}", escape_regex(&term))- };- let match_pattern = regex::Regex::new(&format!("(?i){search_pattern}"))- .expect("escaped search terms always form valid regexes");- let match_limit = limit as usize + 1;- let mut results = Vec::with_capacity(match_limit);-- loop {- let (cursor_updated_at, cursor_entity_id) = scan_cursor- .map(|(ts, id)| (Some(ts), Some(id)))- .unwrap_or((None, None));- let rows = sqlx::query!(- r#"- SELECT- c.id as entity_id,- c.name,- c.updated_at- FROM comms_channels c- INNER JOIN comms_channel_participants cp ON cp.channel_id = c.id- WHERE cp.user_id = $1- AND cp.left_at IS NULL- AND c.id = ANY($2::uuid[])- AND (- $3::timestamptz IS NULL- OR (c.updated_at, c.id) < ($3, $4)- )- AND (- NULLIF(BTRIM(c.name), '') IS NULL- OR c.name ~* $5- )- ORDER BY c.updated_at DESC, c.id DESC- LIMIT $6- "#,- macro_user_id.as_ref(),- channel_ids,- cursor_updated_at,- cursor_entity_id,- search_pattern,- candidate_batch_size,- )- .fetch_all(db)- .await- .map_err(NameSearchError::DatabaseError)?;-- if rows.is_empty() {- break;+ let after = match cursor {+ None => None,+ Some(cursor) => {+ let (entity_id, updated_at) = cursor+ .as_updated_at()+ .ok_or(NameSearchError::IncompatibleCursor)?;+ Some((updated_at, entity_id))}+ };+ let patterns: Vec<String> = terms+ .iter()+ .map(|part| {+ if exact_match {+ format!(r"(^|\W){}($|\W)", escape_regex(part))+ } else {+ format!("%{}%", escape_like(part))+ }+ })+ .collect();+ let viewer_user_id = MacroUserIdStr(macro_user_id.clone());- let batch_exhausted = rows.len() < candidate_batch_size as usize;- let last = rows.last().expect("non-empty batch");- let next_scan_cursor = (last.updated_at, last.entity_id);- let candidate_ids: Vec<Uuid> = rows- .iter()- .filter(|row| row.name.as_ref().is_none_or(|name| name.trim().is_empty()))- .map(|row| row.entity_id)- .collect();- let mut resolved_names =- batch_resolve_channel_names(db, &candidate_ids, viewer_user_id.clone())- .await- .map_err(NameSearchError::DatabaseError)?;+ let matches = match_channel_names(+ db,+ ChannelNameSearch {+ viewer_user_id: viewer_user_id.clone(),+ patterns: &patterns,+ regex_patterns: exact_match,+ channel_ids: scope.channel_ids,+ channel_types: scope.channel_types,+ after,+ limit: i64::from(limit) + 1,+ },+ )+ .await?;+ let channel_ids: Vec<Uuid> = matches.iter().map(|hit| hit.channel_id).collect();+ let mut names = batch_resolve_channel_names(db, &channel_ids, viewer_user_id).await?;- for row in rows {- let name = match row.name.filter(|name| !name.trim().is_empty()) {- Some(name) => name,- None => {- let Some(name) = resolved_names.remove(&row.entity_id) else {- continue;- };- name- }- };- if !match_pattern.is_match(&name) {- continue;- }- let Some(name) = highlight_name(&name, &term) else {- continue;- };- results.push(NameSearchResult {- entity_id: row.entity_id,+ let results: Vec<NameSearchResult> = matches+ .into_iter()+ .filter_map(|hit| {+ let name = names.remove(&hit.channel_id)?;+ let highlighted = highlight_name_terms(&name, &terms);+ Some(NameSearchResult {+ entity_id: hit.channel_id,entity_type: SearchEntityType::Channels,- name,- updated_at: row.updated_at,- });- if results.len() == match_limit {- break;- }- }-- if results.len() == match_limit || batch_exhausted {- break;- }- scan_cursor = Some(next_scan_cursor);- }+ name: highlighted.unwrap_or(name),+ updated_at: hit.updated_at,+ })+ })+ .collect();+ tracing::Span::current().record("result_count", results.len());Ok(SearchCursorOption::paginate(results, limit as usize))}diff --git a/crates/name_search/src/channel/test.rs b/crates/name_search/src/channel/test.rsindex e25fdd3a50..158b762782 100644--- a/crates/name_search/src/channel/test.rs+++ b/crates/name_search/src/channel/test.rs@@ -1,26 +1,37 @@//! Tests for channel name search.+use std::collections::BTreeSet;+use macro_db_migrator::MACRO_DB_MIGRATIONS;use sqlx::{Pool, Postgres};use super::*;+const MACRO: &str = "11111111-1111-1111-1111-111111111111";+const MACRO_PLANNING: &str = "22222222-2222-2222-2222-222222222222";+const MACARONI: &str = "33333333-3333-3333-3333-333333333333";+const GABRIEL_DM: &str = "66666666-6666-6666-6666-666666666666";+const PETER_TEO_GROUP: &str = "77777777-7777-7777-7777-777777777777";+const NAMELESS_DM: &str = "88888888-8888-8888-8888-888888888888";+const CLAUDE_DM: &str = "99999999-9999-9999-9999-999999999999";+const DEAL_DESK_DM: &str = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";+const DESIGN_DECKS: &str = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb";+const HOLLIS_DM: &str = "cccccccc-cccc-cccc-cccc-cccccccccccc";+const UNKNOWN_BOT_DM: &str = "dddddddd-dddd-dddd-dddd-dddddddddddd";++const MEMBER: &str = "macro|[email protected]";+const GABRIEL: &str = "macro|[email protected]";+fn user(id: &str) -> MacroUserId<Lowercase<'_>> {MacroUserId::parse_from_str(id).unwrap().lowercase()}-fn channel_ids() -> Vec<Uuid> {- [- "11111111-1111-1111-1111-111111111111",- "22222222-2222-2222-2222-222222222222",- "33333333-3333-3333-3333-333333333333",- "44444444-4444-4444-4444-444444444444",- "55555555-5555-5555-5555-555555555555",- "66666666-6666-6666-6666-666666666666",- ]- .into_iter()- .map(|id| id.parse().unwrap())- .collect()+fn ids(results: &PaginatedResult<NameSearchResult>) -> Vec<String> {+ results+ .items+ .iter()+ .map(|hit| hit.entity_id.to_string())+ .collect()}#[sqlx::test(@@ -32,8 +43,8 @@ async fn member_sees_matching_channels_but_non_member_does_not() -> anyhow::Result<()> {let member_results = search_channel_names(&pool,- &user("macro|[email protected]"),- &channel_ids(),+ &user(MEMBER),+ ChannelNameSearchScope::default(),"Macro".to_string(),false,10,@@ -41,7 +52,7 @@ async fn member_sees_matching_channels_but_non_member_does_not().await?;- assert_eq!(member_results.items.len(), 2);+ assert_eq!(ids(&member_results), [MACRO_PLANNING, MACRO]);assert!(member_results.items.iter().all(|hit| {hit.entity_type == SearchEntityType::Channels&& hit.name.contains("<macro_em>Macro</macro_em>")@@ -50,7 +61,7 @@ async fn member_sees_matching_channels_but_non_member_does_not(let non_member_results = search_channel_names(&pool,&user("macro|[email protected]"),- &channel_ids(),+ ChannelNameSearchScope::default(),"Macro".to_string(),false,10,@@ -66,56 +77,56 @@ async fn member_sees_matching_channels_but_non_member_does_not(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../fixtures", scripts("channel")))]-async fn partial_matches_prefix_while_exact_requires_a_complete_token(+async fn partial_matches_substrings_while_exact_requires_a_complete_token(pool: Pool<Postgres>,) -> anyhow::Result<()> {- let partial = search_channel_names(+ let prefix = search_channel_names(&pool,- &user("macro|[email protected]"),- &channel_ids(),+ &user(MEMBER),+ ChannelNameSearchScope::default(),"Mac".to_string(),false,10,None,).await?;- assert_eq!(partial.items.len(), 3);+ assert_eq!(ids(&prefix), [MACARONI, MACRO_PLANNING, MACRO]);- let non_prefix = search_channel_names(+ let infix = search_channel_names(&pool,- &user("macro|[email protected]"),- &channel_ids(),+ &user(MEMBER),+ ChannelNameSearchScope::default(),"acro".to_string(),false,10,None,).await?;- assert!(non_prefix.items.is_empty());+ assert_eq!(ids(&infix), [MACRO_PLANNING, MACRO]);- let exact = search_channel_names(+ let exact_prefix = search_channel_names(&pool,- &user("macro|[email protected]"),- &channel_ids(),+ &user(MEMBER),+ ChannelNameSearchScope::default(),"Mac".to_string(),true,10,None,).await?;- assert!(exact.items.is_empty());+ assert!(exact_prefix.items.is_empty());- let exact_macro = search_channel_names(+ let exact_token = search_channel_names(&pool,- &user("macro|[email protected]"),- &channel_ids(),+ &user(MEMBER),+ ChannelNameSearchScope::default(),"Macro".to_string(),true,10,None,).await?;- assert_eq!(exact_macro.items.len(), 2);+ assert_eq!(ids(&exact_token), [MACRO_PLANNING, MACRO]);Ok(())}@@ -127,7 +138,7 @@ async fn former_participant_cannot_find_channel(pool: Pool<Postgres>) -> anyhow:let results = search_channel_names(&pool,&user("macro|[email protected]"),- &channel_ids(),+ ChannelNameSearchScope::default(),"Macro".to_string(),false,10,@@ -143,22 +154,40 @@ async fn former_participant_cannot_find_channel(pool: Pool<Postgres>) -> anyhow:migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../fixtures", scripts("channel")))]-async fn member_can_find_direct_message_by_resolved_name(+async fn direct_message_is_found_by_the_other_participants_name(pool: Pool<Postgres>,) -> anyhow::Result<()> {- let results = search_channel_names(+ let by_first_name = search_channel_names(&pool,- &user("macro|[email protected]"),- &channel_ids(),+ &user(MEMBER),+ ChannelNameSearchScope::default(),"Gab".to_string(),false,10,None,).await?;+ assert_eq!(ids(&by_first_name), [GABRIEL_DM]);+ assert_eq!(+ by_first_name.items[0].name,+ "<macro_em>Gab</macro_em>riel Birman"+ );- assert_eq!(results.items.len(), 1);- assert_eq!(results.items[0].name, "<macro_em>gab</macro_em>riel");+ let by_last_name = search_channel_names(+ &pool,+ &user(MEMBER),+ ChannelNameSearchScope::default(),+ "birman".to_string(),+ false,+ 10,+ None,+ )+ .await?;+ assert_eq!(ids(&by_last_name), [GABRIEL_DM]);+ assert_eq!(+ by_last_name.items[0].name,+ "Gabriel <macro_em>Birman</macro_em>"+ );Ok(())}@@ -166,47 +195,457 @@ async fn member_can_find_direct_message_by_resolved_name(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../fixtures", scripts("channel")))]-async fn scans_past_non_matching_batches_and_preserves_result_cursor(+async fn direct_message_falls_back_to_the_email_local_part(pool: Pool<Postgres>,) -> anyhow::Result<()> {- let first_page = search_channel_names_in_batches(+ let no_user_row = search_channel_names(&pool,- &user("macro|[email protected]"),- &channel_ids(),- "Macro".to_string(),+ &user(MEMBER),+ ChannelNameSearchScope::default(),+ "nameless".to_string(),false,- 1,+ 10,+ None,+ )+ .await?;+ assert_eq!(ids(&no_user_row), [NAMELESS_DM]);+ assert_eq!(no_user_row.items[0].name, "<macro_em>nameless</macro_em>");++ let no_profile = search_channel_names(+ &pool,+ &user(GABRIEL),+ ChannelNameSearchScope::default(),+ "member".to_string(),+ false,+ 10,+ None,+ )+ .await?;+ assert_eq!(ids(&no_profile), [GABRIEL_DM]);+ assert_eq!(no_profile.items[0].name, "<macro_em>member</macro_em>");+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("channel"))+)]+async fn viewer_is_never_part_of_their_own_direct_message_name(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let gabriel_searching_gabriel = search_channel_names(+ &pool,+ &user(GABRIEL),+ ChannelNameSearchScope::default(),+ "gab".to_string(),+ false,+ 10,+ None,+ )+ .await?;+ assert!(gabriel_searching_gabriel.items.is_empty());++ let member_searching_member = search_channel_names(+ &pool,+ &user(MEMBER),+ ChannelNameSearchScope::default(),+ "member".to_string(),+ false,+ 10,+ None,+ )+ .await?;+ assert!(member_searching_member.items.is_empty());+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("channel"))+)]+async fn display_name_skips_not_available_parts(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let results = search_channel_names(+ &pool,+ &user(MEMBER),+ ChannelNameSearchScope::default(),+ "hollis".to_string(),+ false,+ 10,None,- 1,).await?;- assert_eq!(first_page.items.len(), 1);+ assert_eq!(ids(&results), [HOLLIS_DM]);+ assert_eq!(results.items[0].name, "<macro_em>Hollis</macro_em>");+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("channel"))+)]+async fn unnamed_private_channel_is_found_by_any_other_participant(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let by_first_participant = search_channel_names(+ &pool,+ &user(MEMBER),+ ChannelNameSearchScope::default(),+ "peter".to_string(),+ false,+ 10,+ None,+ )+ .await?;+ assert_eq!(ids(&by_first_participant), [PETER_TEO_GROUP]);+ assert_eq!(+ by_first_participant.items[0].name,+ "<macro_em>Peter</macro_em> Chinman, Teo Nys"+ );++ let by_second_participant = search_channel_names(+ &pool,+ &user(MEMBER),+ ChannelNameSearchScope::default(),+ "nys".to_string(),+ false,+ 10,+ None,+ )+ .await?;+ assert_eq!(ids(&by_second_participant), [PETER_TEO_GROUP]);+ assert_eq!(+ by_second_participant.items[0].name,+ "Peter Chinman, Teo <macro_em>Nys</macro_em>"+ );+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("channel"))+)]+async fn every_term_must_match_the_stored_name_or_some_other_participant(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let two_participants = search_channel_names(+ &pool,+ &user(MEMBER),+ ChannelNameSearchScope::default(),+ "peter teo".to_string(),+ false,+ 10,+ None,+ )+ .await?;+ assert_eq!(ids(&two_participants), [PETER_TEO_GROUP]);+ assert_eq!(+ two_participants.items[0].name,+ "<macro_em>Peter</macro_em> Chinman, <macro_em>Teo</macro_em> Nys"+ );++ let comma_separated = search_channel_names(+ &pool,+ &user(MEMBER),+ ChannelNameSearchScope::default(),+ "teo, peter".to_string(),+ false,+ 10,+ None,+ )+ .await?;+ assert_eq!(ids(&comma_separated), [PETER_TEO_GROUP]);++ let participants_of_different_channels = search_channel_names(+ &pool,+ &user(MEMBER),+ ChannelNameSearchScope::default(),+ "peter gabriel".to_string(),+ false,+ 10,+ None,+ )+ .await?;+ assert!(participants_of_different_channels.items.is_empty());++ let two_words_of_a_stored_name = search_channel_names(+ &pool,+ &user(MEMBER),+ ChannelNameSearchScope::default(),+ "Macro Plan".to_string(),+ false,+ 10,+ None,+ )+ .await?;+ assert_eq!(ids(&two_words_of_a_stored_name), [MACRO_PLANNING]);assert_eq!(- first_page.items[0].entity_id,- "22222222-2222-2222-2222-222222222222".parse::<Uuid>()?+ two_words_of_a_stored_name.items[0].name,+ "<macro_em>Macro</macro_em> <macro_em>Plan</macro_em>ning");+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("channel"))+)]+async fn persona_direct_messages_are_found_by_bot_name(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let system_bot = search_channel_names(+ &pool,+ &user(MEMBER),+ ChannelNameSearchScope::default(),+ "claude".to_string(),+ false,+ 10,+ None,+ )+ .await?;+ assert_eq!(ids(&system_bot), [CLAUDE_DM]);+ assert_eq!(system_bot.items[0].name, "<macro_em>Claude</macro_em>");++ let owned_bot = search_channel_names(+ &pool,+ &user(MEMBER),+ ChannelNameSearchScope::default(),+ "deal".to_string(),+ false,+ 10,+ None,+ )+ .await?;+ assert_eq!(ids(&owned_bot), [DEAL_DESK_DM]);+ assert_eq!(owned_bot.items[0].name, "<macro_em>Deal</macro_em> Desk");++ let bot_without_row = search_channel_names(+ &pool,+ &user(MEMBER),+ ChannelNameSearchScope::default(),+ "bot".to_string(),+ false,+ 10,+ None,+ )+ .await?;+ assert_eq!(ids(&bot_without_row), [UNKNOWN_BOT_DM]);+ assert_eq!(bot_without_row.items[0].name, "<macro_em>Bot</macro_em>");+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("channel"))+)]+async fn channel_types_narrow_the_search(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let every_type = search_channel_names(+ &pool,+ &user(MEMBER),+ ChannelNameSearchScope::default(),+ "des".to_string(),+ false,+ 10,+ None,+ )+ .await?;+ assert_eq!(ids(&every_type), [DESIGN_DECKS, DEAL_DESK_DM]);++ let direct_messages = search_channel_names(+ &pool,+ &user(MEMBER),+ ChannelNameSearchScope {+ channel_ids: &[],+ channel_types: &[ChannelType::DirectMessage],+ },+ "des".to_string(),+ false,+ 10,+ None,+ )+ .await?;+ assert_eq!(ids(&direct_messages), [DEAL_DESK_DM]);++ let group_channels = search_channel_names(+ &pool,+ &user(MEMBER),+ ChannelNameSearchScope {+ channel_ids: &[],+ channel_types: &[ChannelType::Public, ChannelType::Private, ChannelType::Team],+ },+ "des".to_string(),+ false,+ 10,+ None,+ )+ .await?;+ assert_eq!(ids(&group_channels), [DESIGN_DECKS]);+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("channel"))+)]+async fn channel_ids_narrow_the_search(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let results = search_channel_names(+ &pool,+ &user(MEMBER),+ ChannelNameSearchScope {+ channel_ids: &[MACRO.parse()?],+ channel_types: &[],+ },+ "mac".to_string(),+ false,+ 10,+ None,+ )+ .await?;++ assert_eq!(ids(&results), [MACRO]);+ Ok(())+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("channel"))+)]+async fn pages_through_mixed_named_and_direct_message_results(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let first_page = search_channel_names(+ &pool,+ &user(MEMBER),+ ChannelNameSearchScope::default(),+ "des".to_string(),+ false,+ 1,+ None,+ )+ .await?;+ assert_eq!(ids(&first_page), [DESIGN_DECKS]);let SearchCursorOption::NotDone(Some(cursor)) = first_page.cursor else {anyhow::bail!("expected another page");};- let second_page = search_channel_names_in_batches(+ let second_page = search_channel_names(&pool,- &user("macro|[email protected]"),- &channel_ids(),- "Macro".to_string(),+ &user(MEMBER),+ ChannelNameSearchScope::default(),+ "des".to_string(),false,1,Some(cursor),- 1,).await?;-- assert_eq!(second_page.items.len(), 1);- assert_eq!(- second_page.items[0].entity_id,- "11111111-1111-1111-1111-111111111111".parse::<Uuid>()?- );+ assert_eq!(ids(&second_page), [DEAL_DESK_DM]);assert!(second_page.cursor.is_done());Ok(())}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("channel"))+)]+async fn blank_terms_and_thread_cursors_are_rejected(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let blank = search_channel_names(+ &pool,+ &user(MEMBER),+ ChannelNameSearchScope::default(),+ " , ".to_string(),+ false,+ 10,+ None,+ )+ .await;+ assert!(matches!(blank, Err(NameSearchError::EmptySearchTerm)));++ let thread_cursor = search_channel_names(+ &pool,+ &user(MEMBER),+ ChannelNameSearchScope::default(),+ "Macro".to_string(),+ false,+ 10,+ Some(SearchMethodCursor::Thread {+ thread_id: Uuid::nil(),+ message_id: Uuid::nil(),+ }),+ )+ .await;+ assert!(matches!(+ thread_cursor,+ Err(NameSearchError::IncompatibleCursor)+ ));+ Ok(())+}++/// The SQL match and the Rust name resolution implement one rule: a channel is+/// returned exactly when the name the viewer sees contains every term.+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../fixtures", scripts("channel"))+)]+async fn results_match_the_names_the_viewer_sees(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let viewer = user(MEMBER);+ let channel_ids: Vec<Uuid> = sqlx::query_scalar!(+ "SELECT channel_id FROM comms_channel_participants WHERE user_id = $1 AND left_at IS NULL",+ MEMBER+ )+ .fetch_all(&pool)+ .await?;+ let resolved_names =+ batch_resolve_channel_names(&pool, &channel_ids, MacroUserIdStr(viewer.clone())).await?;+ assert_eq!(resolved_names.len(), 11);++ for term in [+ "mac",+ "acro",+ "gab",+ "birman",+ "peter",+ "teo",+ "nys",+ "nameless",+ "claude",+ "deal",+ "des",+ "an",+ "hollis",+ "member",+ "peter teo",+ "macro plan",+ "bot",+ "zzz",+ ] {+ let expected: BTreeSet<Uuid> = resolved_names+ .iter()+ .filter(|(_, name)| {+ term.split([' ', ','])+ .filter(|part| !part.is_empty())+ .all(|part| name.to_lowercase().contains(part))+ })+ .map(|(channel_id, _)| *channel_id)+ .collect();++ let results = search_channel_names(+ &pool,+ &viewer,+ ChannelNameSearchScope::default(),+ term.to_string(),+ false,+ 100,+ None,+ )+ .await?;++ let actual: BTreeSet<Uuid> = results.items.iter().map(|hit| hit.entity_id).collect();+ assert_eq!(actual, expected, "channels matching {term:?}");+ assert!(+ results+ .items+ .iter()+ .all(|hit| hit.name.contains("<macro_em>")),+ "every hit for {term:?} is highlighted"+ );+ }+ Ok(())+}diff --git a/crates/name_search/src/highlight.rs b/crates/name_search/src/highlight.rsindex f7caf4f2d3..8b5157f6df 100644--- a/crates/name_search/src/highlight.rs+++ b/crates/name_search/src/highlight.rs@@ -3,20 +3,55 @@use crate::escape_regex;+const OPEN_TAG: &str = "<macro_em>";+const CLOSE_TAG: &str = "</macro_em>";+/// 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;+ highlight_name_terms(name, &[term])+}++/// Wraps every case-insensitive occurrence of each of `terms` in `name` in+/// `<macro_em>` tags. Overlapping and adjacent matches merge into one span so+/// tags never nest. Returns `None` when the terms are blank or none of them+/// occurs in the name.+pub(crate) fn highlight_name_terms(name: &str, terms: &[&str]) -> Option<String> {+ let mut ranges: Vec<(usize, usize)> = Vec::new();+ for term in terms+ .iter()+ .map(|term| term.trim())+ .filter(|term| !term.is_empty())+ {+ let re = regex::Regex::new(&format!("(?i){}", escape_regex(term))).ok()?;+ ranges.extend(re.find_iter(name).map(|m| (m.start(), m.end())));}- let re = regex::Regex::new(&format!("(?i)({})", escape_regex(term))).ok()?;- if !re.is_match(name) {+ if ranges.is_empty() {return None;}- Some(re.replace_all(name, "<macro_em>$1</macro_em>").into_owned())+ ranges.sort_unstable();+ let mut merged: Vec<(usize, usize)> = Vec::with_capacity(ranges.len());+ for (start, end) in ranges {+ match merged.last_mut() {+ Some((_, last_end)) if start <= *last_end => *last_end = (*last_end).max(end),+ _ => merged.push((start, end)),+ }+ }++ let mut highlighted =+ String::with_capacity(name.len() + merged.len() * (OPEN_TAG.len() + CLOSE_TAG.len()));+ let mut copied_to = 0;+ for (start, end) in merged {+ highlighted.push_str(&name[copied_to..start]);+ highlighted.push_str(OPEN_TAG);+ highlighted.push_str(&name[start..end]);+ highlighted.push_str(CLOSE_TAG);+ copied_to = end;+ }+ highlighted.push_str(&name[copied_to..]);+ Some(highlighted)}#[cfg(test)]diff --git a/crates/name_search/src/highlight/test.rs b/crates/name_search/src/highlight/test.rsindex d086b38074..0d02a430bc 100644--- a/crates/name_search/src/highlight/test.rs+++ b/crates/name_search/src/highlight/test.rs@@ -38,3 +38,24 @@ fn escapes_regex_specials_in_term() {Some("plan <macro_em>(v2)</macro_em> draft"));}++#[test]+fn highlights_every_term_of_a_multi_term_query() {+ assert_eq!(+ super::highlight_name_terms("Peter Chinman, Teo Nys", &["peter", "teo"]).as_deref(),+ Some("<macro_em>Peter</macro_em> Chinman, <macro_em>Teo</macro_em> Nys")+ );+}++#[test]+fn merges_overlapping_term_matches_into_one_span() {+ assert_eq!(+ super::highlight_name_terms("Macro Planning", &["plan", "lann"]).as_deref(),+ Some("Macro <macro_em>Plann</macro_em>ing")+ );+}++#[test]+fn returns_none_when_no_term_matches() {+ assert!(super::highlight_name_terms("Macro Planning", &["teo", " "]).is_none());+}diff --git a/crates/name_search/src/lib.rs b/crates/name_search/src/lib.rsindex 5f1c345e00..2f3a765b71 100644--- a/crates/name_search/src/lib.rs+++ b/crates/name_search/src/lib.rs@@ -5,7 +5,7 @@ mod channel;mod chat;mod highlight;-pub use channel::search_channel_names;+pub use channel::{ChannelNameSearchScope, search_channel_names};pub use chat::search_chat_names;pub use highlight::highlight_name;pub use models_opensearch::SearchEntityType;@@ -25,6 +25,18 @@ pub fn escape_regex(term: &str) -> String {escaped}+/// Escapes `LIKE` wildcards in a search term so it matches literally.+pub fn escape_like(term: &str) -> String {+ let mut escaped = String::with_capacity(term.len() * 2);+ for c in term.chars() {+ if matches!(c, '\\' | '%' | '_') {+ escaped.push('\\');+ }+ escaped.push(c);+ }+ escaped+}+/// Errors for name search crate#[derive(Debug, thiserror::Error)]pub enum NameSearchError {diff --git a/crates/search_service/AGENTS.md b/crates/search_service/AGENTS.mdindex b092ebd183..492eaa3e30 100644--- a/crates/search_service/AGENTS.md+++ b/crates/search_service/AGENTS.md@@ -14,6 +14,10 @@ per-entity-type search plus a unified search across them — mounted into`agent_session.rs`), plus `unified.rs` for cross-type search.- `src/api/search/simple/`: a second, simpler request/response shape per typeused by AI tools — kept in sync with the full one by hand.+- Name mode sources: chats (`simple/simple_chat.rs`) and channels+ (`simple/simple_channel.rs`) name-search in Postgres through `name_search`;+ every other type name-searches in OpenSearch. `simple_unified.rs` merges+ them and keeps one cursor slot per source.- `src/api/context.rs`: `SearchHandlerState`, the shared handler state.- `src/outbound.rs` + `src/outbound/agent_session.rs`: the OpenSearch querybuilders.diff --git a/crates/search_service/src/api/search/channel.rs b/crates/search_service/src/api/search/channel.rsindex 67d4fece57..877f645300 100644--- a/crates/search_service/src/api/search/channel.rs+++ b/crates/search_service/src/api/search/channel.rs@@ -169,11 +169,24 @@ fn construct_channel_name_items(.collect()}+/// Splits channel hits into message hits (OpenSearch content matches, which+/// carry goto content) and name hits (Postgres channel name matches, which+/// carry none).+pub(in crate::api::search) fn split_channel_hits(+ hits: Vec<opensearch_client::search::model::SearchHit>,+) -> (+ Vec<opensearch_client::search::model::SearchHit>,+ Vec<opensearch_client::search::model::SearchHit>,+) {+ hits.into_iter().partition(|hit| hit.goto.is_some())+}+/// Builds one per-message item per content hit. Drops hits whose channel has/// no history info for the caller (no access / channel gone) and hits whose/// message no longer exists in the DB (stale OpenSearch entries); soft-deleted-/// messages are kept with `deleted_at` set. The channels index carries no-/// name field, so every hit has message goto content.+/// messages are kept with `deleted_at` set. Name hits from the Postgres channel+/// name search carry no goto content and are skipped here; they become channel+/// items through `construct_channel_name_items`.pub fn construct_channel_message_items(search_results: Vec<opensearch_client::search::model::SearchHit>,channel_histories: HashMap<Uuid, ChannelHistoryInfo>,@@ -326,13 +339,6 @@ pub async fn name_handler(.map_err(|_| SearchError::InvalidUserId(user_context.user_id.clone()))?.lowercase();let filters = item_filters::ChannelFilters::default();- let channels = simple_channel::filter_channels(- &ctx,- user_id.as_ref(),- user_context.organization_id,- &filters,- )- .await?;let cursor = query_params.cursor.as_deref()@@ -342,7 +348,7 @@ pub async fn name_handler(let (hits, next_cursor) = simple_channel::search_names(&ctx.db,&user_id,- &channels,+ &filters,query.to_string(),req.match_type == MatchType::Exact,page_size,diff --git a/crates/search_service/src/api/search/channel/test.rs b/crates/search_service/src/api/search/channel/test.rsindex d47b3aaee8..7ed14f5303 100644--- a/crates/search_service/src/api/search/channel/test.rs+++ b/crates/search_service/src/api/search/channel/test.rs@@ -928,3 +928,59 @@ fn test_construct_search_result_breaks_created_at_ties_by_message_id() {"tied: smaller uuidv7 last");}++#[test]+fn name_hits_split_from_message_hits_and_never_become_message_items() {+ let channel_id: Uuid = "550e8400-e29b-41d4-a716-446655440000".parse().unwrap();+ let message_id: Uuid = "11111111-1111-1111-1111-111111111111".parse().unwrap();+ let name_hit = opensearch_client::search::model::SearchHit {+ entity_id: channel_id,+ entity_type: SearchEntityType::Channels,+ score: None,+ highlight: Highlight {+ name: Some("<macro_em>Gab</macro_em>riel Birman".to_string()),+ ..Default::default()+ },+ goto: None,+ updated_at: Some(Utc::now()),+ };+ let message_hit = opensearch_client::search::model::SearchHit {+ entity_id: channel_id,+ entity_type: SearchEntityType::Channels,+ score: None,+ highlight: Highlight::default(),+ goto: Some(SearchGotoContent::Channels(+ opensearch_client::search::model::SearchGotoChannel {+ channel_message_id: message_id,+ created_at: DateTime::from_timestamp(1234567890, 0).unwrap(),+ updated_at: DateTime::from_timestamp(1234567891, 0).unwrap(),+ thread_id: None,+ sender_id: "user1".to_string(),+ },+ )),+ updated_at: Some(Utc::now()),+ };+ let histories = HashMap::from([(channel_id, create_channel_history(&channel_id.to_string()))]);+ let message_states = HashMap::from([(message_id, None)]);++ let (message_hits, name_hits) = split_channel_hits(vec![name_hit.clone(), message_hit]);+ assert_eq!(message_hits.len(), 1);+ assert_eq!(name_hits.len(), 1);+ assert!(name_hits[0].goto.is_none());++ let skipped =+ construct_channel_message_items(vec![name_hit], histories.clone(), message_states.clone());+ assert!(skipped.is_empty(), "a name hit has no message to build");++ let message_items =+ construct_channel_message_items(message_hits, histories.clone(), message_states);+ assert_eq!(message_items.len(), 1);+ assert_eq!(message_items[0].message_id, message_id);++ let name_items = construct_channel_name_items(name_hits, histories);+ assert_eq!(name_items.len(), 1);+ assert_eq!(+ name_items[0].highlight.name.as_deref(),+ Some("<macro_em>Gab</macro_em>riel Birman")+ );+}diff --git a/crates/search_service/src/api/search/enrich.rs b/crates/search_service/src/api/search/enrich.rsindex 60fdc78214..c531d38b42 100644--- a/crates/search_service/src/api/search/enrich.rs+++ b/crates/search_service/src/api/search/enrich.rs@@ -7,9 +7,14 @@ use opensearch_client::search::model::SearchHit;use crate::api::{context::SearchHandlerState,search::{- calendar_event::enrich_calendar_events, call_record::enrich_call_records,- channel::enrich_channel_messages, chat::enrich_chats, document::enrich_documents,- email::enrich_emails, project::enrich_projects, simple::SearchError,+ calendar_event::enrich_calendar_events,+ call_record::enrich_call_records,+ channel::{enrich_channel_messages, enrich_channel_names, split_channel_hits},+ chat::enrich_chats,+ document::enrich_documents,+ email::enrich_emails,+ project::enrich_projects,+ simple::SearchError,},};@@ -45,10 +50,17 @@ pub async fn enrich_search_response(.collect())}SearchEntityType::Channels => {- let response = enrich_channel_messages(ctx, user_id, results).await?;- Ok(response+ // Message hits from OpenSearch carry goto content; name hits from+ // the Postgres channel name search have none and become channels.+ let (message_hits, name_hits) = split_channel_hits(results);+ let (messages, channels) = tokio::try_join!(+ enrich_channel_messages(ctx, user_id, message_hits),+ enrich_channel_names(ctx, user_id, name_hits),+ )?;+ Ok(messages.into_iter().map(UnifiedSearchResponseItem::ChannelMessage)+ .chain(channels.into_iter().map(UnifiedSearchResponseItem::Channel)).collect())}SearchEntityType::Chats => {diff --git a/crates/search_service/src/api/search/simple.rs b/crates/search_service/src/api/search/simple.rsindex 3132a82d4b..9c2d4f91b0 100644--- a/crates/search_service/src/api/search/simple.rs+++ b/crates/search_service/src/api/search/simple.rs@@ -57,6 +57,12 @@ pub enum SearchError {/// An agent-session filter is not a UUID.#[error("invalid agent session id: {0}")]InvalidAgentSessionId(String),+ /// A channel filter id is not a UUID.+ #[error("invalid channel id: {0}")]+ InvalidChannelId(String),+ /// A channel type filter is not a known channel type.+ #[error("invalid channel type: {0}")]+ InvalidChannelType(String),/// Opensearch error occurred#[error("unable to search")]Search(#[from] OpensearchClientError),@@ -80,6 +86,8 @@ impl IntoResponse for SearchError {| SearchError::InvalidCursor| SearchError::InvalidCrmCompanyId(_)| SearchError::InvalidAgentSessionId(_)+ | SearchError::InvalidChannelId(_)+ | SearchError::InvalidChannelType(_)| SearchError::NoQueryOrTermsProvided| SearchError::NoChannelIds => StatusCode::BAD_REQUEST,SearchError::NameSearch(NameSearchError::IncompatibleCursor) => StatusCode::BAD_REQUEST,diff --git a/crates/search_service/src/api/search/simple/simple_channel.rs b/crates/search_service/src/api/search/simple/simple_channel.rsindex 3d42e738a4..9bc248ef8c 100644--- a/crates/search_service/src/api/search/simple/simple_channel.rs+++ b/crates/search_service/src/api/search/simple/simple_channel.rs@@ -1,7 +1,10 @@use crate::api::search::simple::SearchError;+use channels::domain::models::ChannelType;use item_filters::ChannelFilters;use macro_user_id::user_id::MacroUserId;+use name_search::ChannelNameSearchScope;use opensearch_client::search::model::{Highlight, SearchHit};+use sqlx::types::Uuid;use std::collections::HashSet;use crate::api::context::SearchHandlerState;@@ -11,13 +14,15 @@ pub(in crate::api::search) struct FilterChannelResponse {pub channel_ids: Vec<sqlx::types::Uuid>,}-/// Performs the name search over channel names.-#[allow(clippy::too_many_arguments)]-#[tracing::instrument(skip(db), err)]+/// Performs the viewer-aware name search over the channels the user is in,+/// narrowed by the filters' `channel_ids` and `channel_types`. Organization+/// channels no longer exist (`comms_channels.org_id` is always null), so an+/// `org_id` filter matches no channel, as it does for the message index.+#[tracing::instrument(skip(db, filters, term), fields(term_len = term.len()), err)]pub(in crate::api::search) async fn search_names<'a>(db: &sqlx::Pool<sqlx::Postgres>,user_id: &MacroUserId<macro_user_id::lowercased::Lowercase<'a>>,- filter_channel_response: &FilterChannelResponse,+ filters: &ChannelFilters,term: String,exact_match: bool,limit: u32,@@ -29,11 +34,34 @@ pub(in crate::api::search) async fn search_names<'a>(}models_search_cursor::SearchCursorOption::NotDone(c) => c,};+ if filters.org_id.is_some() {+ return Ok((vec![], models_search_cursor::SearchCursorOption::Done));+ }+ let channel_ids = filters+ .channel_ids+ .iter()+ .map(|id| {+ id.parse::<Uuid>()+ .map_err(|_| SearchError::InvalidChannelId(id.clone()))+ })+ .collect::<Result<Vec<_>, _>>()?;+ let channel_types = filters+ .channel_types+ .iter()+ .map(|label| {+ label+ .parse::<ChannelType>()+ .map_err(|_| SearchError::InvalidChannelType(label.clone()))+ })+ .collect::<Result<Vec<_>, _>>()?;name_search::search_channel_names(db,user_id,- &filter_channel_response.channel_ids,+ ChannelNameSearchScope {+ channel_ids: &channel_ids,+ channel_types: &channel_types,+ },term,exact_match,limit,@@ -110,3 +138,6 @@ pub(in crate::api::search) async fn filter_channels(Ok(FilterChannelResponse { channel_ids })}++#[cfg(test)]+mod test;diff --git a/crates/search_service/src/api/search/simple/simple_channel/test.rs b/crates/search_service/src/api/search/simple/simple_channel/test.rsnew file mode 100644index 0000000000..5c3a3942ed--- /dev/null+++ b/crates/search_service/src/api/search/simple/simple_channel/test.rs@@ -0,0 +1,33 @@+use super::*;+use models_search_cursor::SearchCursorOption;++/// Organization channels no longer exist, so an `org_id` filter matches no+/// channel. The search returns before touching the database, which a lazy+/// pool that never connects proves.+#[tokio::test]+async fn org_filter_matches_no_channel_names() {+ let db = sqlx::PgPool::connect_lazy("postgres://unused@localhost:1/unused")+ .expect("a lazy pool needs no server");+ let user_id = MacroUserId::parse_from_str("macro|[email protected]")+ .unwrap()+ .lowercase();+ let filters = ChannelFilters {+ org_id: Some(42),+ ..Default::default()+ };++ let (hits, cursor) = search_names(+ &db,+ &user_id,+ &filters,+ "macro".to_string(),+ false,+ 10,+ SearchCursorOption::NotDone(None),+ )+ .await+ .expect("an org filter is not an error");++ assert!(hits.is_empty());+ assert!(cursor.is_done());+}diff --git a/crates/search_service/src/api/search/simple/simple_unified.rs b/crates/search_service/src/api/search/simple/simple_unified.rsindex d84f490fe1..a5a26dfb4a 100644--- a/crates/search_service/src/api/search/simple/simple_unified.rs+++ b/crates/search_service/src/api/search/simple/simple_unified.rs@@ -1,7 +1,7 @@use crate::api::search::simple::filter::FilterVariantToSearchArgs;use crate::api::search::crm_company;-use crate::api::search::simple::simple_chat;+use crate::api::search::simple::{simple_channel, simple_chat};use crate::api::{context::{SearchAuthorizationService, SearchHandlerState},search::{SearchPaginationParams, simple::SearchError},@@ -16,7 +16,7 @@ use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};use macro_user_id::user_id::MacroUserId;use model::{response::ErrorResponse, user::UserContext};use models_search::unified::SearchEntityFilters;-use models_search::{SearchOn, SimpleSearchResponse, unified::UnifiedSearchRequest};+use models_search::{MatchType, SearchOn, SimpleSearchResponse, unified::UnifiedSearchRequest};use models_search_cursor::{SearchCursor, SearchCursorOption, SearchMethodCursor};use opensearch_client::search::agent_sessions::{AgentSessionSearchArgs, AgentSessionSearchMode};use opensearch_client::search::call_records::CallRecordSearchMode;@@ -38,6 +38,7 @@ fn calendar_events_searchable(requested: bool, flag_enabled: bool) -> bool {#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum SearchSource {ChatName,+ ChannelName,Content,CrmCompany,}@@ -291,6 +292,10 @@ pub(in crate::api::search) async fn perform_unified_search(// emails, call records, calendar events — stays included and applies the// filter itself.let should_include_channels = search_filters.should_include_channels && !tags_active;+ // Channel names are searched in Postgres below; only a content search+ // needs the viewer's channel ids for the OpenSearch messages index.+ let should_search_channel_messages =+ should_include_channels && !matches!(search_on, SearchOn::Name);let should_include_chats = search_filters.should_include_chats;let should_include_projects = search_filters.should_include_projects;let should_include_emails = search_filters.should_include_emails;@@ -321,7 +326,7 @@ pub(in crate::api::search) async fn perform_unified_search(ctx,user_id.as_ref(),user_organization_id,- should_include_channels,+ should_search_channel_messages,),chat_filters.filter_to_search_args(ctx,@@ -422,10 +427,16 @@ pub(in crate::api::search) async fn perform_unified_search(.map(|c| c.crm_company_cursor.clone()).unwrap_or_default();+ let channel_name_cursor = cursor+ .as_ref()+ .map(|c| c.channel_name_cursor.clone())+ .unwrap_or_default();+// Clone cursors for passing to search functions (originals needed for cursor regeneration)let chat_cursor_for_search = chat_cursor.clone();let content_cursor_for_search = content_cursor.clone();let crm_cursor_for_search = crm_cursor.clone();+ let channel_name_cursor_for_search = channel_name_cursor.clone();let unified_search_args = UnifiedSearchArgs {agent_session_search_args: AgentSessionSearchArgs {@@ -465,7 +476,7 @@ pub(in crate::api::search) async fn perform_unified_search(if should_include_emails {indices.insert(models_opensearch::OpenSearchEntityType::Emails);}- if should_include_channels && !filter_channel_response.channel_ids.is_empty() {+ if should_search_channel_messages && !filter_channel_response.channel_ids.is_empty() {indices.insert(models_opensearch::OpenSearchEntityType::Channels);}if should_include_call_records && !filter_call_record_response.call_ids.is_empty() {@@ -498,7 +509,7 @@ pub(in crate::api::search) async fn perform_unified_search(// Call search functions in parallel for included entity types// search_names handles Done cursors internally by returning early- let (chat_results, content_results, crm_results) = tokio::join!(+ let (chat_results, channel_results, content_results, crm_results) = tokio::join!(async {if should_include_chats {match search_on {@@ -524,15 +535,34 @@ pub(in crate::api::search) async fn perform_unified_search(Ok((vec![], SearchCursorOption::Done))}},+ async {+ // Channel names depend on the viewer (a DM is named after the+ // other participant), so they are matched in Postgres rather than+ // the message-level channels index.+ match search_on {+ SearchOn::Name | SearchOn::NameContent if should_include_channels => {+ simple_channel::search_names(+ &ctx.db,+ &user_id,+ &channel_filters,+ name_search_term.clone(),+ match_type == MatchType::Exact,+ page_size,+ channel_name_cursor_for_search,+ )+ .await+ }+ _ => Ok((vec![], SearchCursorOption::Done)),+ }+ },async {// Documents, email subjects, project names, call names, and// calendar event titles are name-searched in OpenSearch. In Name- // mode keep only those indices: chats still name-search in- // Postgres above, and channels have no name concept. Documents- // match `document_name`, emails their subject, projects their- // `name`, calls their `name`, calendar events their `title`.- // Projects and calendar events have no content, so a content-only- // search drops them.+ // mode keep only those indices: chats and channels name-search in+ // Postgres above. Documents match `document_name`, emails their+ // subject, projects their `name`, calls their `name`, calendar+ // events their `title`. Projects and calendar events have no+ // content, so a content-only search drops them.let mut args = unified_search_args;match search_on {SearchOn::Name => {@@ -590,11 +620,13 @@ pub(in crate::api::search) async fn perform_unified_search(// Extract results and next cursorslet (chat_hits, chat_next_cursor) = chat_results?;+ let (channel_hits, channel_next_cursor) = channel_results?;let (content_hits, content_next_cursor) = content_results?;let (crm_hits, crm_next_cursor) = crm_results?;// Track original counts before combininglet chat_name_count = chat_hits.len();+ let channel_name_count = channel_hits.len();// Content hits are chunk-level (many per document), so the page budget counts// distinct documents. Name/crm sub-searches return one row per entity, so// their hit count already equals their entity count.@@ -608,6 +640,10 @@ pub(in crate::api::search) async fn perform_unified_search(hit,source: SearchSource::ChatName,}));+ combined.extend(channel_hits.into_iter().map(|hit| TaggedSearchHit {+ hit,+ source: SearchSource::ChannelName,+ }));combined.extend(content_hits.into_iter().map(|hit| TaggedSearchHit {hit,source: SearchSource::Content,@@ -639,6 +675,10 @@ pub(in crate::api::search) async fn perform_unified_search(.iter().filter(|h| h.source == SearchSource::ChatName).count();+ let included_channel_names = final_tagged+ .iter()+ .filter(|h| h.source == SearchSource::ChannelName)+ .count();let included_content = distinct_entity_count(final_tagged.iter()@@ -659,6 +699,14 @@ pub(in crate::api::search) async fn perform_unified_search(&chat_cursor,);+ let new_channel_cursor = compute_next_cursor(+ &channel_next_cursor,+ included_channel_names,+ channel_name_count,+ find_last_of_source(&final_tagged, SearchSource::ChannelName),+ &channel_name_cursor,+ );+let new_content_cursor = compute_next_cursor(&content_next_cursor,included_content,@@ -677,6 +725,7 @@ pub(in crate::api::search) async fn perform_unified_search(// Build next cursor if any source has more resultslet has_more = new_chat_cursor.has_more()+ || new_channel_cursor.has_more()|| new_content_cursor.has_more()|| new_crm_cursor.has_more();@@ -688,6 +737,7 @@ pub(in crate::api::search) async fn perform_unified_search(// stays only so older cursors still decode.project_name_cursor: SearchCursorOption::Done,crm_company_cursor: new_crm_cursor,+ channel_name_cursor: new_channel_cursor,};cursor.encode()} else {diff --git a/crates/search_service/src/api/search/simple/simple_unified/test.rs b/crates/search_service/src/api/search/simple/simple_unified/test.rsindex 6e974b1cca..54d80bbbb4 100644--- a/crates/search_service/src/api/search/simple/simple_unified/test.rs+++ b/crates/search_service/src/api/search/simple/simple_unified/test.rs@@ -558,3 +558,29 @@ fn the_calendar_flag_overrides_what_the_request_asked_for() {);assert!(!calendar_events_searchable(false, false));}++#[test]+fn channel_name_cursor_round_trips_through_the_unified_cursor() {+ let entity_id = Uuid::now_v7();+ let cursor = SearchCursor {+ chat_name_cursor: SearchCursorOption::Done,+ content_cursor: SearchCursorOption::Done,+ project_name_cursor: SearchCursorOption::Done,+ crm_company_cursor: SearchCursorOption::Done,+ channel_name_cursor: SearchCursorOption::NotDone(Some(SearchMethodCursor::UpdatedAt {+ entity_id,+ updated_at: ts(1000),+ })),+ };++ let decoded = SearchCursor::decode(&cursor.encode().expect("encode")).expect("decode");++ assert!(+ !decoded.is_exhausted(),+ "a pending channel name cursor keeps the page alive"+ );+ let SearchCursorOption::NotDone(Some(channel_cursor)) = decoded.channel_name_cursor else {+ panic!("expected the channel name cursor to survive the round trip");+ };+ assert_eq!(channel_cursor.as_updated_at(), Some((entity_id, ts(1000))));+}