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): use call record name instead of channel name (#2964)
gbirmane90ec9ff6ff8
diff --git a/js/app/packages/entity/src/components/CallChannelName.tsx b/js/app/packages/entity/src/components/CallChannelName.tsxdeleted file mode 100644index 372bdcec14..0000000000--- a/js/app/packages/entity/src/components/CallChannelName.tsx+++ /dev/null@@ -1,60 +0,0 @@-import { blockNameToDefaultFile } from '@core/constant/allBlocks';-import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';-import { unifiedListMarkdownTheme } from '@core/component/LexicalMarkdown/theme';-import { isChannelPreviewItem, useItemPreview } from '@queries/preview';-import { Show } from 'solid-js';-import type { CallEntity } from '../types/entity';-import { isSearchEntity } from '../types/search';--/** Channel name for a call row — falls back to the preview endpoint when- * transform-utils couldn't resolve it locally. */-export function CallChannelName(props: { entity: CallEntity }) {- const highlight = () =>- isSearchEntity(props.entity)- ? (props.entity.search.nameHighlight ?? undefined)- : undefined;-- return (- <Show- when={highlight()}- fallback={<CallChannelNameText entity={props.entity} />}- >- {(h) => (- <StaticMarkdown- markdown={h()}- theme={unifiedListMarkdownTheme}- singleLine={true}- />- )}- </Show>- );-}--function CallChannelNameText(props: { entity: CallEntity }) {- return (- <Show- when={props.entity.name}- fallback={- <CallChannelNameFromPreview channelId={props.entity.channelId} />- }- >- {props.entity.name}- </Show>- );-}--// TODO: once we have call record rename/preview, we should use that instead of the channel name-function CallChannelNameFromPreview(props: { channelId: string }) {- const [preview] = useItemPreview(() => ({- id: props.channelId,- type: 'channel' as const,- }));-- const name = () => {- const p = preview();- if (isChannelPreviewItem(p)) return p.name;- return blockNameToDefaultFile('call');- };-- return <>{name()}</>;-}diff --git a/js/app/packages/entity/src/components/CallRecordName.tsx b/js/app/packages/entity/src/components/CallRecordName.tsxnew file mode 100644index 0000000000..80ced7accf--- /dev/null+++ b/js/app/packages/entity/src/components/CallRecordName.tsx@@ -0,0 +1,26 @@+import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';+import { unifiedListMarkdownTheme } from '@core/component/LexicalMarkdown/theme';+import { Show } from 'solid-js';+import type { CallEntity } from '../types/entity';+import { isSearchEntity } from '../types/search';++/** Display name for a call record. Renders the search highlight when present,+ * otherwise the entity's resolved name. */+export function CallRecordName(props: { entity: CallEntity }) {+ const highlight = () =>+ isSearchEntity(props.entity)+ ? (props.entity.search.nameHighlight ?? undefined)+ : undefined;++ return (+ <Show when={highlight()} fallback={props.entity.name}>+ {(h) => (+ <StaticMarkdown+ markdown={h()}+ theme={unifiedListMarkdownTheme}+ singleLine={true}+ />+ )}+ </Show>+ );+}diff --git a/js/app/packages/entity/src/composed/list-entity/call.tsx b/js/app/packages/entity/src/composed/list-entity/call.tsxindex 7f7abc007d..cb82b838f9 100644--- a/js/app/packages/entity/src/composed/list-entity/call.tsx+++ b/js/app/packages/entity/src/composed/list-entity/call.tsx@@ -1,4 +1,4 @@-import { For, Show, Suspense } from 'solid-js';+import { For, Show } from 'solid-js';import { usePropertyEntityDisplay } from '@core/component/Properties/hooks';import { UserGroup } from '@core/component/Properties/component/propertyValue/UserGroup';import type { EntityReference } from '@core/component/Properties/types';@@ -9,7 +9,7 @@ import { formatCallDuration } from '@block-call/utils';import UserCircleIcon from '@icon/regular/user-circle.svg';import { EntityType } from '@service-properties/generated/schemas/entityType';import { AttendanceBadge } from '../../components/Badges';-import { CallChannelName } from '../../components/CallChannelName';+import { CallRecordName } from '../../components/CallRecordName';import { Entity } from '../../entity';import { HitSnippet } from '../../extractors-search/HitSnippet';import { SearchSender } from '../../extractors-search/search-sender';@@ -81,9 +81,7 @@ export function CallNarrowBody(props: {when={hit()}fallback={<span class="text-ink-muted text-xs truncate">- <Suspense>- <CallChannelName entity={props.entity} />- </Suspense>+ <CallRecordName entity={props.entity} /></span>}>@@ -132,9 +130,7 @@ export function CallWideContent(props: {return (<><span class="truncate">- <Suspense>- <CallChannelName entity={props.entity} />- </Suspense>+ <CallRecordName entity={props.entity} /></span><Showwhen={hit()}diff --git a/js/app/packages/queries/soup/transform-utils.ts b/js/app/packages/queries/soup/transform-utils.tsindex 78707a425e..6a56077d47 100644--- a/js/app/packages/queries/soup/transform-utils.ts+++ b/js/app/packages/queries/soup/transform-utils.ts@@ -384,8 +384,7 @@ export const useSearchResponseItemMapper = () => {{type: 'call',id: result.call_id,- // NOTE: leave empty, the CallChannelName will fall back to the preview endpoint.- name: result.name ?? channelName ?? '',+ name: result.name ?? channelName ?? blockNameToDefaultFile('call'),channelId: result.channel_id,channelName,ownerId: result.owner_id,diff --git a/rust/cloud-storage/.sqlx/query-6dae1be229aa02fd589a494c2219f9ffafb95d71284c9062109b4fc7ccf80206.json b/rust/cloud-storage/.sqlx/query-4103298cf62438b69d534ac4092423b210d7bcf2202ca38480fd7ce026977166.jsonsimilarity index 59%rename from rust/cloud-storage/.sqlx/query-6dae1be229aa02fd589a494c2219f9ffafb95d71284c9062109b4fc7ccf80206.jsonrename to rust/cloud-storage/.sqlx/query-4103298cf62438b69d534ac4092423b210d7bcf2202ca38480fd7ce026977166.jsonindex 4905496d03..a1def484e8 100644--- a/rust/cloud-storage/.sqlx/query-6dae1be229aa02fd589a494c2219f9ffafb95d71284c9062109b4fc7ccf80206.json+++ b/rust/cloud-storage/.sqlx/query-4103298cf62438b69d534ac4092423b210d7bcf2202ca38480fd7ce026977166.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT channel_id, user_id\n FROM comms_channel_participants\n WHERE channel_id = ANY($1) AND left_at IS NULL\n ",+ "query": "\n SELECT channel_id, user_id\n FROM comms_channel_participants\n WHERE channel_id = ANY($1) AND left_at IS NULL\n ","describe": {"columns": [{@@ -24,5 +24,5 @@false]},- "hash": "6dae1be229aa02fd589a494c2219f9ffafb95d71284c9062109b4fc7ccf80206"+ "hash": "4103298cf62438b69d534ac4092423b210d7bcf2202ca38480fd7ce026977166"}diff --git a/rust/cloud-storage/.sqlx/query-c35b200b4901483cf44b5c34cb7711954310f6eedb582fcc4aa3ecebcb1bd79b.json b/rust/cloud-storage/.sqlx/query-5945da24df02edef42222564bd97f153d87be6e876568063a7bdb183c41a01e9.jsonsimilarity index 55%rename from rust/cloud-storage/.sqlx/query-c35b200b4901483cf44b5c34cb7711954310f6eedb582fcc4aa3ecebcb1bd79b.jsonrename to rust/cloud-storage/.sqlx/query-5945da24df02edef42222564bd97f153d87be6e876568063a7bdb183c41a01e9.jsonindex a16c429dfe..caa71c967c 100644--- a/rust/cloud-storage/.sqlx/query-c35b200b4901483cf44b5c34cb7711954310f6eedb582fcc4aa3ecebcb1bd79b.json+++ b/rust/cloud-storage/.sqlx/query-5945da24df02edef42222564bd97f153d87be6e876568063a7bdb183c41a01e9.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n cr.id AS \"call_id!\",\n cr.created_by AS \"created_by!\",\n cr.started_at AS \"started_at!\",\n cr.ended_at AS \"ended_at!\",\n cr.duration_ms AS \"duration_ms!\",\n cc.name AS \"channel_name?\",\n EXISTS (\n SELECT 1 FROM call_record_participants crp\n WHERE crp.call_record_id = cr.id AND crp.user_id = $2\n ) AS \"attended!\"\n FROM call_records cr\n LEFT JOIN comms_channels cc ON cc.id = cr.channel_id\n WHERE cr.id = ANY($1)\n ",+ "query": "\n SELECT\n cr.id AS \"call_id!\",\n cr.channel_id AS \"channel_id!\",\n cr.created_by AS \"created_by!\",\n cr.started_at AS \"started_at!\",\n cr.ended_at AS \"ended_at!\",\n cr.duration_ms AS \"duration_ms!\",\n cr.custom_name AS \"custom_name?\",\n EXISTS (\n SELECT 1 FROM call_record_participants crp\n WHERE crp.call_record_id = cr.id AND crp.user_id = $2\n ) AS \"attended!\"\n FROM call_records cr\n WHERE cr.id = ANY($1)\n ","describe": {"columns": [{@@ -10,31 +10,36 @@},{"ordinal": 1,+ "name": "channel_id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 2,"name": "created_by!","type_info": "Text"},{- "ordinal": 2,+ "ordinal": 3,"name": "started_at!","type_info": "Timestamptz"},{- "ordinal": 3,+ "ordinal": 4,"name": "ended_at!","type_info": "Timestamptz"},{- "ordinal": 4,+ "ordinal": 5,"name": "duration_ms!","type_info": "Int8"},{- "ordinal": 5,- "name": "channel_name?",- "type_info": "Varchar"+ "ordinal": 6,+ "name": "custom_name?",+ "type_info": "Text"},{- "ordinal": 6,+ "ordinal": 7,"name": "attended!","type_info": "Bool"}@@ -51,9 +56,10 @@false,false,false,+ false,true,null]},- "hash": "c35b200b4901483cf44b5c34cb7711954310f6eedb582fcc4aa3ecebcb1bd79b"+ "hash": "5945da24df02edef42222564bd97f153d87be6e876568063a7bdb183c41a01e9"}diff --git a/rust/cloud-storage/.sqlx/query-6ca02c6511b3279813710cb93a275d215c3edeb60072739f71e5e7324772349c.json b/rust/cloud-storage/.sqlx/query-6ca02c6511b3279813710cb93a275d215c3edeb60072739f71e5e7324772349c.jsondeleted file mode 100644index 0322fc82a7..0000000000--- a/rust/cloud-storage/.sqlx/query-6ca02c6511b3279813710cb93a275d215c3edeb60072739f71e5e7324772349c.json+++ /dev/null@@ -1,34 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT id, name, channel_type::text as \"channel_type!\"\n FROM comms_channels\n WHERE id = ANY($1)\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "name",- "type_info": "Varchar"- },- {- "ordinal": 2,- "name": "channel_type!",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "UuidArray"- ]- },- "nullable": [- false,- true,- null- ]- },- "hash": "6ca02c6511b3279813710cb93a275d215c3edeb60072739f71e5e7324772349c"-}diff --git a/rust/cloud-storage/.sqlx/query-80ec8203f3090c1d40c0c782808e4a2bfbc92a06c2c37ab8a8e243f54eb93d03.json b/rust/cloud-storage/.sqlx/query-80ec8203f3090c1d40c0c782808e4a2bfbc92a06c2c37ab8a8e243f54eb93d03.jsondeleted file mode 100644index a3dd0b24d4..0000000000--- a/rust/cloud-storage/.sqlx/query-80ec8203f3090c1d40c0c782808e4a2bfbc92a06c2c37ab8a8e243f54eb93d03.json+++ /dev/null@@ -1,22 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT user_id\n FROM comms_channel_participants\n WHERE channel_id = $1 AND left_at IS NULL\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "user_id",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": [- false- ]- },- "hash": "80ec8203f3090c1d40c0c782808e4a2bfbc92a06c2c37ab8a8e243f54eb93d03"-}diff --git a/rust/cloud-storage/.sqlx/query-32d668d355465b6e54567a087cf54754567424b802606a92cf204041a9b70bf4.json b/rust/cloud-storage/.sqlx/query-940e7b0eb134ebfeff080733ed64ee795af7afc2cf14a910b0baf5838c4284e6.jsonsimilarity index 59%rename from rust/cloud-storage/.sqlx/query-32d668d355465b6e54567a087cf54754567424b802606a92cf204041a9b70bf4.jsonrename to rust/cloud-storage/.sqlx/query-940e7b0eb134ebfeff080733ed64ee795af7afc2cf14a910b0baf5838c4284e6.jsonindex 2073a4b13b..0856672b4f 100644--- a/rust/cloud-storage/.sqlx/query-32d668d355465b6e54567a087cf54754567424b802606a92cf204041a9b70bf4.json+++ b/rust/cloud-storage/.sqlx/query-940e7b0eb134ebfeff080733ed64ee795af7afc2cf14a910b0baf5838c4284e6.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT u.id as user_profile_id, mui.first_name, mui.last_name\n FROM macro_user_info mui\n JOIN \"User\" u ON mui.macro_user_id = u.macro_user_id\n WHERE u.id = ANY($1)\n ",+ "query": "\n SELECT u.id as user_profile_id, mui.first_name, mui.last_name\n FROM macro_user_info mui\n JOIN \"User\" u ON mui.macro_user_id = u.macro_user_id\n WHERE u.id = ANY($1)\n ","describe": {"columns": [{@@ -30,5 +30,5 @@true]},- "hash": "32d668d355465b6e54567a087cf54754567424b802606a92cf204041a9b70bf4"+ "hash": "940e7b0eb134ebfeff080733ed64ee795af7afc2cf14a910b0baf5838c4284e6"}diff --git a/rust/cloud-storage/.sqlx/query-c5d7f14d70f0de5fd07ae24e50441f5a5dd574ae4492f2adebd98021dbaab771.json b/rust/cloud-storage/.sqlx/query-c5d7f14d70f0de5fd07ae24e50441f5a5dd574ae4492f2adebd98021dbaab771.jsonnew file mode 100644index 0000000000..2310e27b0d--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-c5d7f14d70f0de5fd07ae24e50441f5a5dd574ae4492f2adebd98021dbaab771.json@@ -0,0 +1,47 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, name, channel_type as \"channel_type!: ChannelType\"\n FROM comms_channels\n WHERE id = ANY($1)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "name",+ "type_info": "Varchar"+ },+ {+ "ordinal": 2,+ "name": "channel_type!: ChannelType",+ "type_info": {+ "Custom": {+ "name": "comms_channel_type",+ "kind": {+ "Enum": [+ "public",+ "organization",+ "private",+ "direct_message",+ "team"+ ]+ }+ }+ }+ }+ ],+ "parameters": {+ "Left": [+ "UuidArray"+ ]+ },+ "nullable": [+ false,+ true,+ false+ ]+ },+ "hash": "c5d7f14d70f0de5fd07ae24e50441f5a5dd574ae4492f2adebd98021dbaab771"+}diff --git a/rust/cloud-storage/.sqlx/query-f4f6aabb3ebbf6f8d2361b1cf8a63948bd3b0becdfdd21d780a08ffa05b2b963.json b/rust/cloud-storage/.sqlx/query-f4f6aabb3ebbf6f8d2361b1cf8a63948bd3b0becdfdd21d780a08ffa05b2b963.jsondeleted file mode 100644index a8cc7e657a..0000000000--- a/rust/cloud-storage/.sqlx/query-f4f6aabb3ebbf6f8d2361b1cf8a63948bd3b0becdfdd21d780a08ffa05b2b963.json+++ /dev/null@@ -1,28 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT name, channel_type::text as \"channel_type!\"\n FROM comms_channels\n WHERE id = $1\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "name",- "type_info": "Varchar"- },- {- "ordinal": 1,- "name": "channel_type!",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": [- true,- null- ]- },- "hash": "f4f6aabb3ebbf6f8d2361b1cf8a63948bd3b0becdfdd21d780a08ffa05b2b963"-}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 14e83a76e9..e7f0283681 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -1795,6 +1795,7 @@ dependencies = ["aws-sdk-s3","axum","chrono",+ "comms","connection","entity_access","entity_access_db_utils",@@ -9684,6 +9685,7 @@ dependencies = ["aws-sdk-secretsmanager","axum","chrono",+ "comms","comms_db_client","document_sub_type","email_db_client",diff --git a/rust/cloud-storage/call/Cargo.toml b/rust/cloud-storage/call/Cargo.tomlindex ded953beb4..240b63a9e7 100644--- a/rust/cloud-storage/call/Cargo.toml+++ b/rust/cloud-storage/call/Cargo.toml@@ -18,6 +18,7 @@ inbound = [outbound = ["dep:ai","dep:aws-sdk-s3",+ "comms/outbound","dep:entity_access_db_utils","dep:livekit-api","dep:livekit-protocol",@@ -34,6 +35,7 @@ async-trait = { workspace = true, optional = true }aws-sdk-s3 = { workspace = true, optional = true }axum = { workspace = true, optional = true }chrono = { workspace = true }+comms = { path = "../comms", default-features = false }connection = { path = "../connection", default-features = false, features = ["ports",] }diff --git a/rust/cloud-storage/call/src/domain/channel_name.rs b/rust/cloud-storage/call/src/domain/channel_name.rsdeleted file mode 100644index 217a83c10e..0000000000--- a/rust/cloud-storage/call/src/domain/channel_name.rs+++ /dev/null@@ -1,121 +0,0 @@-//! Channel name resolution logic.-//!-//! Resolves the display name for a channel based on its type, stored name,-//! and participants. Mirrors the logic in the `comms` crate's-//! `domain::models::channel_name` module.--use std::collections::HashMap;--use macro_user_id::{cowlike::CowLike, email::ReadEmailParts, user_id::MacroUserIdStr};-use uuid::Uuid;--/// Maps user IDs to display names.-pub type NameLookup = HashMap<String, String>;--/// Resolve the display name for a channel.-///-/// `channel_type` is the raw Postgres enum value (`"public"`,-/// `"organization"`, `"private"`, `"direct_message"`, `"team"`).-pub fn resolve_channel_name(- channel_type: &str,- channel_name: Option<&str>,- participant_user_ids: &[MacroUserIdStr<'_>],- channel_id: &Uuid,- user_id: MacroUserIdStr<'_>,- name_lookup: &NameLookup,-) -> String {- match channel_type {- "organization" | "public" => channel_name.map(|n| n.to_string()).unwrap_or_else(|| {- tracing::warn!(- ?channel_id,- "organization or public channel should have a name"- );- if channel_type == "organization" {- "Organization"- } else {- "Public"- }- .to_string()- }),- "private" => resolve_private_channel_name(channel_name, participant_user_ids, name_lookup),- "direct_message" => resolve_direct_message_channel_name(- channel_name,- participant_user_ids,- channel_id,- user_id,- name_lookup,- ),- "team" => channel_name.map(|n| n.to_string()).unwrap_or_else(|| {- tracing::warn!(?channel_id, "team channel should have a name");- "Team".to_string()- }),- _ => channel_name.unwrap_or("Unknown").to_string(),- }-}--fn resolve_private_channel_name(- channel_name: Option<&str>,- participant_user_ids: &[MacroUserIdStr<'_>],- name_lookup: &NameLookup,-) -> String {- if let Some(name) = channel_name- && !name.trim().is_empty()- {- return name.to_string();- }-- participant_user_ids- .iter()- .map(|id| id_to_display_name(id.copied(), name_lookup))- .collect::<Vec<String>>()- .join(", ")-}--fn resolve_direct_message_channel_name(- channel_name: Option<&str>,- participant_user_ids: &[MacroUserIdStr<'_>],- channel_id: &Uuid,- user_id: MacroUserIdStr<'_>,- name_lookup: &NameLookup,-) -> String {- if channel_name.is_some() {- tracing::warn!(?channel_id, "direct message channel should not have a name");- }-- if !participant_user_ids- .iter()- .any(|p| p.as_ref() == user_id.as_ref())- {- return resolve_private_channel_name(channel_name, participant_user_ids, name_lookup);- }-- let other = participant_user_ids- .iter()- .find(|p| p.as_ref() != user_id.as_ref());-- if let Some(other) = other {- id_to_display_name(other.copied(), name_lookup)- } else {- "Unknown".to_string()- }-}--fn id_to_display_name(id: MacroUserIdStr<'_>, name_lookup: &NameLookup) -> String {- match name_lookup.get(id.as_ref()) {- Some(name) if !name.trim().is_empty() => name.clone(),- _ => id.email_part().local_part().to_string(),- }-}--/// Build a display name from optional first and last name parts.-///-/// Returns `None` if both are missing or `"N/A"`.-pub 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}")),- }-}diff --git a/rust/cloud-storage/call/src/domain/mod.rs b/rust/cloud-storage/call/src/domain/mod.rsindex 5139551d58..f080d971b1 100644--- a/rust/cloud-storage/call/src/domain/mod.rs+++ b/rust/cloud-storage/call/src/domain/mod.rs@@ -1,6 +1,3 @@-/// Channel name resolution logic.-pub mod channel_name;-/// Domain models for calls.pub mod models;diff --git a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs b/rust/cloud-storage/call/src/outbound/pg_call_repo.rsindex 0dbbaca060..5c678c2e11 100644--- a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo.rs@@ -8,6 +8,7 @@ mod test;use std::collections::{HashMap, HashSet};use chrono::Utc;+use comms::outbound::postgres::channel_name::batch_resolve_channel_names;use entity_access::domain::models::AccessLevel;use filter_ast::Expr;use item_filters::ast::{LiteralTree, call::CallLiteral};@@ -17,7 +18,6 @@ use models_permissions::share_permission::channel_share_permission::ChannelShareuse sqlx::PgPool;use uuid::Uuid;-use crate::domain::channel_name::{NameLookup, display_name, resolve_channel_name};use crate::domain::models::{AddParticipantError, Call, CallParticipant, CallRecord, CallRecordParticipant,CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CustomSpeakerAssignment,@@ -94,112 +94,6 @@ impl PgCallRepo {pub fn new(pool: PgPool) -> Self {Self { pool }}-- /// 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 person" for DM channels; it is not an authorization check.- ///- /// Channels the query can't find simply have no entry in the returned map.- async fn batch_resolve_channel_names<'a>(- &self,- channel_ids: &[Uuid],- viewer_user_id: MacroUserIdStr<'a>,- ) -> Result<HashMap<Uuid, String>, sqlx::Error> {- if channel_ids.is_empty() {- return Ok(HashMap::new());- }-- let channel_info_rows = sqlx::query!(- r#"- SELECT id, name, channel_type::text as "channel_type!"- FROM comms_channels- WHERE id = ANY($1)- "#,- channel_ids,- )- .fetch_all(&self.pool)- .await?;-- let channel_map: HashMap<Uuid, (Option<String>, String)> = channel_info_rows- .into_iter()- .map(|r| (r.id, (r.name, r.channel_type)))- .collect();-- // Channels that need participant-derived names (DMs, unnamed privates).- let needs_participants: Vec<Uuid> = channel_map- .iter()- .filter(|(_, (name, ct))| {- ct == "direct_message"- || (ct == "private" && name.as_ref().is_none_or(|n| n.trim().is_empty()))- })- .map(|(id, _)| *id)- .collect();-- let (participant_map, name_lookup) = if needs_participants.is_empty() {- (HashMap::new(), NameLookup::new())- } else {- let participant_rows = sqlx::query!(- r#"- SELECT channel_id, user_id- FROM comms_channel_participants- WHERE channel_id = ANY($1) AND left_at IS NULL- "#,- &needs_participants- )- .fetch_all(&self.pool)- .await?;-- let mut part_map: HashMap<Uuid, Vec<MacroUserIdStr<'static>>> = HashMap::new();- let mut all_user_ids = HashSet::new();- for row in participant_rows {- let uid = MacroUserIdStr::parse_from_str(&row.user_id)- .expect("valid user id from db")- .into_owned();- all_user_ids.insert(row.user_id);- part_map.entry(row.channel_id).or_default().push(uid);- }-- let user_id_strings: Vec<String> = all_user_ids.into_iter().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(&self.pool)- .await?;-- let lookup: NameLookup = name_rows- .into_iter()- .filter_map(|row| {- let name = display_name(row.first_name.as_deref(), row.last_name.as_deref())?;- Some((row.user_profile_id, name))- })- .collect();-- (part_map, lookup)- };-- let mut resolved: HashMap<Uuid, String> = HashMap::with_capacity(channel_map.len());- for (channel_id, (name, channel_type)) in &channel_map {- let empty = Vec::new();- let participants = participant_map.get(channel_id).unwrap_or(&empty);- let resolved_name = resolve_channel_name(- channel_type,- name.as_deref(),- participants,- channel_id,- viewer_user_id.copied(),- &name_lookup,- );- resolved.insert(*channel_id, resolved_name);- }-- Ok(resolved)- }}impl CallRepository for PgCallRepo {@@ -996,9 +890,8 @@ impl CallRepository for PgCallRepo {.collect()};- let channel_names = self- .batch_resolve_channel_names(&unique_channel_ids, user_id)- .await?;+ let channel_names =+ batch_resolve_channel_names(&self.pool, &unique_channel_ids, user_id).await?;let previews = unique_call_ids.into_iter()@@ -1183,9 +1076,8 @@ impl CallRepository for PgCallRepo {.collect()};- let channel_names = self- .batch_resolve_channel_names(&unique_channel_ids, user_id.copied())- .await?;+ let channel_names =+ batch_resolve_channel_names(&self.pool, &unique_channel_ids, user_id.copied()).await?;for record in &mut records {record.channel_name = channel_names.get(&record.channel_id).cloned();@@ -1220,83 +1112,8 @@ impl CallRepository for PgCallRepo {channel_id: &Uuid,user_id: MacroUserIdStr<'a>,) -> Result<Option<String>, Self::Err> {- let Some(channel_info) = sqlx::query!(- r#"- SELECT name, channel_type::text as "channel_type!"- FROM comms_channels- WHERE id = $1- "#,- channel_id- )- .fetch_optional(&self.pool)- .await?- else {- return Ok(None);- };-- let channel_type = &channel_info.channel_type;- let needs_participants = channel_type == "direct_message"- || (channel_type == "private"- && channel_info- .name- .as_ref()- .is_none_or(|n| n.trim().is_empty()));-- let (participant_ids, name_lookup) = if !needs_participants {- (Vec::new(), NameLookup::new())- } else {- let participant_rows = sqlx::query!(- r#"- SELECT user_id- FROM comms_channel_participants- WHERE channel_id = $1 AND left_at IS NULL- "#,- channel_id- )- .fetch_all(&self.pool)- .await?;-- let mut ids = Vec::new();- let mut all_user_ids = Vec::new();- for row in participant_rows {- let uid = MacroUserIdStr::parse_from_str(&row.user_id)- .expect("valid user id from db")- .into_owned();- all_user_ids.push(row.user_id);- ids.push(uid);- }-- 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)- "#,- &all_user_ids- )- .fetch_all(&self.pool)- .await?;-- let lookup: NameLookup = name_rows- .into_iter()- .filter_map(|row| {- let name = display_name(row.first_name.as_deref(), row.last_name.as_deref())?;- Some((row.user_profile_id, name))- })- .collect();-- (ids, lookup)- };-- Ok(Some(resolve_channel_name(- channel_type,- channel_info.name.as_deref(),- &participant_ids,- channel_id,- user_id.copied(),- &name_lookup,- )))+ let mut map = batch_resolve_channel_names(&self.pool, &[*channel_id], user_id).await?;+ Ok(map.remove(channel_id))}#[tracing::instrument(err, skip(self))]diff --git a/rust/cloud-storage/comms/src/outbound/postgres.rs b/rust/cloud-storage/comms/src/outbound/postgres.rsindex 9c44293db9..0e4d55e7da 100644--- a/rust/cloud-storage/comms/src/outbound/postgres.rs+++ b/rust/cloud-storage/comms/src/outbound/postgres.rs@@ -1,2 +1,3 @@+pub mod channel_name;pub mod comms_repo;pub mod user_repo;diff --git a/rust/cloud-storage/comms/src/outbound/postgres/channel_name.rs b/rust/cloud-storage/comms/src/outbound/postgres/channel_name.rsnew file mode 100644index 0000000000..2aa3575fa8--- /dev/null+++ b/rust/cloud-storage/comms/src/outbound/postgres/channel_name.rs@@ -0,0 +1,155 @@+//! Batch channel-name resolution backed by Postgres.+//!+//! Queries channels, their participants, and user display names, then+//! delegates to the canonical [`resolve_channel_name`] domain function.++use std::collections::{HashMap, HashSet};++use chrono::{DateTime, Utc};+use doppleganger::Mirror;+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};+use models_comms::channel::{ChannelId, ChannelParticipant, ParticipantRole};+use sqlx::PgPool;+use uuid::Uuid;++use crate::domain::models::channel_name::{NameLookup, resolve_channel_name};+use crate::outbound::postgres::comms_repo::ChannelType;++/// 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+/// person" for DM channels; it is not an authorization check.+///+/// Channels the query can't find simply have no entry in the returned map.+#[tracing::instrument(skip(pool), err)]+pub async fn batch_resolve_channel_names<'a>(+ pool: &PgPool,+ channel_ids: &[Uuid],+ viewer_user_id: MacroUserIdStr<'a>,+) -> Result<HashMap<Uuid, String>, sqlx::Error> {+ if channel_ids.is_empty() {+ return Ok(HashMap::new());+ }++ let channel_rows = sqlx::query!(+ r#"+ SELECT id, name, channel_type as "channel_type!: ChannelType"+ FROM comms_channels+ WHERE id = ANY($1)+ "#,+ channel_ids,+ )+ .fetch_all(pool)+ .await?;++ let channels: HashMap<Uuid, (Option<String>, models_comms::channel::ChannelType)> =+ channel_rows+ .into_iter()+ .map(|r| (r.id, (r.name, ChannelType::mirror(r.channel_type))))+ .collect();++ // Channels that need participant-derived names (DMs, unnamed privates).+ let needs_participants: Vec<Uuid> = channels+ .iter()+ .filter(|(_, (name, ct))| {+ matches!(ct, models_comms::channel::ChannelType::DirectMessage)+ || (matches!(ct, models_comms::channel::ChannelType::Private)+ && name.as_ref().is_none_or(|n| n.trim().is_empty()))+ })+ .map(|(id, _)| *id)+ .collect();++ let (participants_by_channel, name_lookup) = if needs_participants.is_empty() {+ (HashMap::new(), NameLookup::new())+ } else {+ load_participants_and_names(pool, &needs_participants).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(),+ participants,+ &ChannelId(*channel_id),+ viewer_user_id.copied(),+ &name_lookup,+ );+ resolved.insert(*channel_id, resolved_name);+ }++ Ok(resolved)+}++async fn load_participants_and_names(+ pool: &PgPool,+ channel_ids: &[Uuid],+) -> Result<(HashMap<Uuid, Vec<ChannelParticipant>>, NameLookup), sqlx::Error> {+ let participant_rows = sqlx::query!(+ r#"+ SELECT channel_id, user_id+ FROM comms_channel_participants+ WHERE channel_id = ANY($1) AND left_at IS NULL+ "#,+ channel_ids+ )+ .fetch_all(pool)+ .await?;++ let mut participants_by_channel: HashMap<Uuid, Vec<ChannelParticipant>> = HashMap::new();+ let mut all_user_ids: HashSet<String> = HashSet::new();+ let placeholder_ts: DateTime<Utc> = DateTime::<Utc>::from_timestamp(0, 0).expect("epoch");+ for row in participant_rows {+ let user_id = MacroUserIdStr::parse_from_str(&row.user_id)+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?+ .into_owned();+ all_user_ids.insert(row.user_id);+ participants_by_channel+ .entry(row.channel_id)+ .or_default()+ .push(ChannelParticipant {+ channel_id: ChannelId(row.channel_id),+ user_id,+ role: ParticipantRole::Member,+ joined_at: placeholder_ts,+ left_at: None,+ });+ }++ let user_id_strings: Vec<String> = all_user_ids.into_iter().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 user_id = MacroUserIdStr::parse_from_str(&row.user_profile_id)+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?+ .into_owned();+ name_lookup.insert(user_id, name);+ }++ Ok((participants_by_channel, name_lookup))+}++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}")),+ }+}diff --git a/rust/cloud-storage/macro_db_client/src/call_record/get.rs b/rust/cloud-storage/macro_db_client/src/call_record/get.rsindex 4edf6e48b4..51ab0d2389 100644--- a/rust/cloud-storage/macro_db_client/src/call_record/get.rs+++ b/rust/cloud-storage/macro_db_client/src/call_record/get.rs@@ -9,11 +9,12 @@ pub struct CallRecordSearchBackfill {#[derive(Debug, Clone)]pub struct CallRecordMetadataRow {pub call_id: Uuid,+ pub channel_id: Uuid,pub created_by: String,pub started_at: DateTime<Utc>,pub ended_at: DateTime<Utc>,pub duration_ms: i64,- pub channel_name: Option<String>,+ pub custom_name: Option<String>,/// Whether the requesting user was a participant on the call.pub attended: bool,}@@ -185,17 +186,17 @@ pub async fn get_call_records_metadata(r#"SELECTcr.id AS "call_id!",+ cr.channel_id AS "channel_id!",cr.created_by AS "created_by!",cr.started_at AS "started_at!",cr.ended_at AS "ended_at!",cr.duration_ms AS "duration_ms!",- cc.name AS "channel_name?",+ cr.custom_name AS "custom_name?",EXISTS (SELECT 1 FROM call_record_participants crpWHERE crp.call_record_id = cr.id AND crp.user_id = $2) AS "attended!"FROM call_records cr- LEFT JOIN comms_channels cc ON cc.id = cr.channel_idWHERE cr.id = ANY($1)"#,call_ids,diff --git a/rust/cloud-storage/search_service/Cargo.toml b/rust/cloud-storage/search_service/Cargo.tomlindex 6890f0e339..a4c6363ceb 100644--- a/rust/cloud-storage/search_service/Cargo.toml+++ b/rust/cloud-storage/search_service/Cargo.toml@@ -18,6 +18,7 @@ aws-sdk-secretsmanager = { workspace = true }macro_aws_config = { path = "../macro_aws_config" }axum = { workspace = true }chrono = { workspace = true }+comms = { path = "../comms", default-features = false, features = ["outbound"] }comms_db_client = { path = "../comms_db_client" }document_sub_type = { path = "../document_sub_type" }email_db_client = { path = "../email_db_client" }diff --git a/rust/cloud-storage/search_service/src/api/search/call_record.rs b/rust/cloud-storage/search_service/src/api/search/call_record.rsindex 86a356b594..53cce9d959 100644--- a/rust/cloud-storage/search_service/src/api/search/call_record.rs+++ b/rust/cloud-storage/search_service/src/api/search/call_record.rs@@ -1,4 +1,6 @@+use comms::outbound::postgres::channel_name::batch_resolve_channel_names;use indexmap::IndexMap;+use macro_user_id::user_id::MacroUserIdStr;use models_search::call_record::{CallRecordMetadata, CallRecordSearchResponseItem, CallRecordSearchResponseItemWithMetadata,CallRecordSearchResult,@@ -36,9 +38,27 @@ pub(in crate::api::search) async fn enrich_call_records(.await.map_err(SearchError::InternalError)?;+ let viewer_user_id = MacroUserIdStr::parse_from_str(user_id)+ .map_err(|_| SearchError::InvalidUserId(user_id.to_string()))?;+ let unique_channel_ids: Vec<Uuid> = {+ let mut seen: std::collections::HashSet<Uuid> = std::collections::HashSet::new();+ metadata_rows+ .iter()+ .filter_map(|r| seen.insert(r.channel_id).then_some(r.channel_id))+ .collect()+ };+ let channel_names_by_id =+ batch_resolve_channel_names(&ctx.db, &unique_channel_ids, viewer_user_id)+ .await+ .map_err(|e| SearchError::InternalError(e.into()))?;++ let mut custom_name_by_id: std::collections::HashMap<Uuid, Option<String>> =+ std::collections::HashMap::new();let metadata_by_id: std::collections::HashMap<Uuid, CallRecordMetadata> = metadata_rows.into_iter().map(|row| {+ custom_name_by_id.insert(row.call_id, row.custom_name);+ let channel_name = channel_names_by_id.get(&row.channel_id).cloned();(row.call_id,CallRecordMetadata {@@ -47,7 +67,7 @@ pub(in crate::api::search) async fn enrich_call_records(ended_at: row.ended_at,duration_ms: row.duration_ms,updated_at: row.ended_at,- channel_name: row.channel_name,+ channel_name,attended: row.attended,},)@@ -98,7 +118,7 @@ pub(in crate::api::search) async fn enrich_call_records(CallRecordSearchResponseItemWithMetadata {extra: CallRecordSearchResponseItem {id: call_id,- name: metadata.as_ref().and_then(|m| m.channel_name.clone()),+ name: custom_name_by_id.get(&call_id).cloned().flatten(),owner_id: metadata.as_ref().map(|m| m.created_by.clone())