Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(call): name DM call notifications after the caller, not the callee (#6820)

teo5c886e95a4e2
diff --git a/crates/call/src/domain/ports.rs b/crates/call/src/domain/ports.rs
index 2f6b1a082a..f24c88e985 100644
--- a/crates/call/src/domain/ports.rs
+++ b/crates/call/src/domain/ports.rs
@@ -2,6 +2,7 @@
//!
//! These traits define the contracts that adapters must implement.
+use std::collections::HashMap;
use std::fmt::Debug;
use std::future::Future;
@@ -280,6 +281,19 @@ pub trait CallRepository: Send + Sync + 'static {
user_id: MacroUserIdStr<'a>,
) -> impl Future<Output = Result<Option<String>, Self::Err>> + Send;
+ /// Resolve the display name of one channel as each of `viewer_ids` sees
+ /// it, keyed by viewer.
+ ///
+ /// DM and unnamed private channels are named after the *other*
+ /// participants, so the name differs per viewer; named channels resolve
+ /// to the same name for everyone. Viewers are not authorized here. The
+ /// map is empty when the channel does not exist.
+ fn resolve_channel_name_for_viewers<'a>(
+ &self,
+ channel_id: &Uuid,
+ viewer_ids: &[MacroUserIdStr<'a>],
+ ) -> impl Future<Output = Result<HashMap<MacroUserIdStr<'static>, String>, Self::Err>> + Send;
+
/// Delete a row from `call_records` by id. Participants and transcript
/// segments are removed via `ON DELETE CASCADE`. No-op if no row matches.
/// Returns the deleted row's storage object keys so the caller can clean
diff --git a/crates/call/src/domain/service.rs b/crates/call/src/domain/service.rs
index e39790c388..42569cf461 100644
--- a/crates/call/src/domain/service.rs
+++ b/crates/call/src/domain/service.rs
@@ -473,6 +473,28 @@ fn exclude_voip_recipients<'a>(
.collect()
}
+/// Group call recipients by the channel name each of them sees.
+///
+/// A DM is named after the *other* participant, so resolving the channel
+/// name from the caller's perspective would label the incoming call with the
+/// callee's own name. Every recipient is pushed the name they know the
+/// channel by; recipients whose name could not be resolved share a `None`
+/// group. Named channels collapse into a single group.
+fn group_recipients_by_channel_name<'a>(
+ recipient_ids: impl IntoIterator<Item = MacroUserIdStr<'a>>,
+ channel_names_by_recipient: &HashMap<MacroUserIdStr<'static>, String>,
+) -> HashMap<Option<String>, HashSet<MacroUserIdStr<'a>>> {
+ let mut groups: HashMap<Option<String>, HashSet<MacroUserIdStr<'a>>> = HashMap::new();
+ for recipient_id in recipient_ids {
+ let channel_name = channel_names_by_recipient
+ .iter()
+ .find(|(viewer, _)| viewer.as_ref() == recipient_id.as_ref())
+ .map(|(_, name)| name.clone());
+ groups.entry(channel_name).or_default().insert(recipient_id);
+ }
+ groups
+}
+
/// Producer-side payload for the "call started" notification.
///
/// Shares its wire shape and [`Notification::TYPE_NAME`] (`call_started`) with
@@ -674,12 +696,6 @@ impl<
// Send push notification and VoIP push to channel members (best-effort).
let _: Result<(), anyhow::Error> = async {
- let channel_name = self
- .repo
- .resolve_channel_name(channel_id, user_id.copied())
- .await
- .map_err(Into::into)?;
-
let channel_id_str = channel_id.to_string();
let recipient_ids: HashSet<MacroUserIdStr<'_>> = self
.entity_access_service
@@ -688,6 +704,24 @@ impl<
.into_iter()
.filter(|u| u.as_ref() != user_id.as_ref())
.collect();
+ if recipient_ids.is_empty() {
+ return Ok(());
+ }
+
+ // Resolve the channel name from each recipient's
+ // perspective: a DM is named after the other
+ // participant, so the caller's view of the name
+ // would be the callee's own name.
+ let recipient_vec: Vec<MacroUserIdStr<'static>> = recipient_ids
+ .iter()
+ .cloned()
+ .map(CowLike::into_owned)
+ .collect();
+ let channel_names_by_recipient = self
+ .repo
+ .resolve_channel_name_for_viewers(channel_id, &recipient_vec)
+ .await
+ .map_err(Into::into)?;
let sender_profile_picture_url = self
.repo
@@ -707,11 +741,6 @@ impl<
// Send VoIP push for the native iOS incoming-call sheet first.
// Recipients with successful VoIP delivery do not need the regular
// APNS alert banner as well.
- let recipient_vec: Vec<MacroUserIdStr<'static>> = recipient_ids
- .iter()
- .cloned()
- .map(CowLike::into_owned)
- .collect();
// Resolve VoIP endpoints before minting tokens:
// users without PushKit endpoints should not get
@@ -732,13 +761,6 @@ impl<
Vec::new()
}
};
- let voip_target_recipient_ids: Vec<MacroUserIdStr<'static>> =
- voip_targets
- .iter()
- .map(|target| target.recipient_id.clone())
- .collect();
-
- let voip_channel_name = channel_name.clone().unwrap_or_default();
let ring_status_url =
self.ring_status_base_url.as_deref().map(|base| {
format!(
@@ -747,24 +769,37 @@ impl<
call.id
)
});
- let payloads = self
- .rtc_client
- .build_voip_push_payloads(VoipPushPayloadRequest {
- recipients: &voip_target_recipient_ids,
- room_name: &call.room_name,
- call_id: call.id,
- channel_id: &channel_id_str,
- channel_name: &voip_channel_name,
- caller_name: &caller_name,
- livekit_server_url: &self.server_url,
- ring_status_url: ring_status_url.as_deref(),
- })
- .await;
-
+ // One payload batch per distinct channel name, so
+ // each recipient's native sheet shows the name they
+ // know the channel by.
let mut payloads_by_recipient: HashMap<
MacroUserIdStr<'static>,
VoipPushPayload,
- > = payloads.into_iter().collect();
+ > = HashMap::new();
+ let voip_groups = group_recipients_by_channel_name(
+ voip_targets
+ .iter()
+ .map(|target| target.recipient_id.clone()),
+ &channel_names_by_recipient,
+ );
+ for (voip_channel_name, voip_group_recipients) in voip_groups {
+ let voip_group_recipients: Vec<MacroUserIdStr<'static>> =
+ voip_group_recipients.into_iter().collect();
+ let payloads = self
+ .rtc_client
+ .build_voip_push_payloads(VoipPushPayloadRequest {
+ recipients: &voip_group_recipients,
+ room_name: &call.room_name,
+ call_id: call.id,
+ channel_id: &channel_id_str,
+ channel_name: voip_channel_name.as_deref().unwrap_or(""),
+ caller_name: &caller_name,
+ livekit_server_url: &self.server_url,
+ ring_status_url: ring_status_url.as_deref(),
+ })
+ .await;
+ payloads_by_recipient.extend(payloads);
+ }
// Rejoin resolved endpoints with successfully
// minted payloads. A failed token mint skips only
// that recipient's VoIP push.
@@ -785,18 +820,26 @@ impl<
// APNS is the fallback/default path. Recipients
// with a successful VoIP delivery skip the regular
- // alert to avoid duplicate incoming-call UI.
- if !apns_recipient_ids.is_empty() {
+ // alert to avoid duplicate incoming-call UI. One
+ // request per distinct channel name, so the alert
+ // title and stored metadata match what each
+ // recipient calls the channel.
+ let apns_groups = group_recipients_by_channel_name(
+ apns_recipient_ids,
+ &channel_names_by_recipient,
+ );
+ for (channel_name, apns_group_recipients) in apns_groups {
let req = SendNotificationRequestBuilder {
notification_entity: EntityType::Channel
.with_entity_string(channel_id_str.clone()),
secondary_notification_entity: None,
notification: CallStartedNotification {
- sender_profile_picture_url,
- channel_name: channel_name.clone(),
+ sender_profile_picture_url: sender_profile_picture_url
+ .clone(),
+ channel_name,
},
sender_id: Some(user_id.copied()),
- recipient_ids: apns_recipient_ids,
+ recipient_ids: apns_group_recipients,
}
.into_request()
.with_apns();
diff --git a/crates/call/src/domain/service/test.rs b/crates/call/src/domain/service/test.rs
index ec65aac74e..0f2ae1eb27 100644
--- a/crates/call/src/domain/service/test.rs
+++ b/crates/call/src/domain/service/test.rs
@@ -35,7 +35,7 @@ use crate::domain::ports::{
use super::{
CallServiceImpl, NoopCallSummarizer, derive_preview_key_from_recording_key,
derive_preview_keys_from_recording_key, exclude_voip_recipients, extract_recording_key,
- resolve_ring_status,
+ group_recipients_by_channel_name, resolve_ring_status,
};
#[cfg(feature = "outbound")]
@@ -397,16 +397,8 @@ fn mock_get_or_create_repo(
repo.expect_create_call()
.times(1)
.return_once(move |_, _, _, _| Box::pin(async move { Ok(Some(call)) }));
-
- repo.expect_resolve_channel_name()
- .times(1)
- .returning(|_, _| {
- Box::pin(async {
- Err(anyhow::anyhow!(
- "skip push notifications in get_or_create_call tests"
- ))
- })
- });
+ // Push notifications are skipped: `NoOpEntityAccessService`
+ // fails recipient lookup before any channel name is resolved.
}
GetOrCreateScenario::RaceLoses => {
let mut sequence = mockall::Sequence::new();
@@ -2688,6 +2680,75 @@ fn derive_preview_keys_from_recording_key_includes_new_and_legacy_mp4_paths() {
);
}
+#[test]
+fn group_recipients_by_channel_name_uses_each_recipients_own_view_of_a_dm() {
+ // Jacob calls Teo in their DM. Teo sees the DM as "Jacob Beckerman"; the
+ // caller's view ("Teo Nys") must never be what Teo is pushed.
+ let teo = user("[email protected]");
+ let names = HashMap::from([(teo.clone().into_owned(), "Jacob Beckerman".to_string())]);
+
+ let groups = group_recipients_by_channel_name([teo.clone()], &names);
+
+ assert_eq!(
+ groups,
+ HashMap::from([(Some("Jacob Beckerman".to_string()), HashSet::from([teo]))])
+ );
+}
+
+#[test]
+fn group_recipients_by_channel_name_collapses_a_named_channel_into_one_group() {
+ let alice = user("[email protected]");
+ let bob = user("[email protected]");
+ let names = HashMap::from([
+ (alice.clone().into_owned(), "general".to_string()),
+ (bob.clone().into_owned(), "general".to_string()),
+ ]);
+
+ let groups = group_recipients_by_channel_name([alice.clone(), bob.clone()], &names);
+
+ assert_eq!(
+ groups,
+ HashMap::from([(Some("general".to_string()), HashSet::from([alice, bob]))])
+ );
+}
+
+#[test]
+fn group_recipients_by_channel_name_splits_unnamed_group_dm_per_viewer() {
+ let alice = user("[email protected]");
+ let bob = user("[email protected]");
+ let names = HashMap::from([
+ (alice.clone().into_owned(), "Bob, Carla".to_string()),
+ (bob.clone().into_owned(), "Alice, Carla".to_string()),
+ ]);
+
+ let groups = group_recipients_by_channel_name([alice.clone(), bob.clone()], &names);
+
+ assert_eq!(
+ groups,
+ HashMap::from([
+ (Some("Bob, Carla".to_string()), HashSet::from([alice])),
+ (Some("Alice, Carla".to_string()), HashSet::from([bob])),
+ ])
+ );
+}
+
+#[test]
+fn group_recipients_by_channel_name_buckets_unresolved_recipients_under_none() {
+ let alice = user("[email protected]");
+ let bob = user("[email protected]");
+ let names = HashMap::from([(alice.clone().into_owned(), "general".to_string())]);
+
+ let groups = group_recipients_by_channel_name([alice.clone(), bob.clone()], &names);
+
+ assert_eq!(
+ groups,
+ HashMap::from([
+ (Some("general".to_string()), HashSet::from([alice])),
+ (None, HashSet::from([bob])),
+ ])
+ );
+}
+
#[test]
fn exclude_voip_recipients_keeps_users_without_voip_delivery() {
let alice = user("[email protected]");
diff --git a/crates/call/src/outbound/pg_call_repo.rs b/crates/call/src/outbound/pg_call_repo.rs
index 781d60ef6d..6a0ac38cbb 100644
--- a/crates/call/src/outbound/pg_call_repo.rs
+++ b/crates/call/src/outbound/pg_call_repo.rs
@@ -8,7 +8,9 @@ mod test;
use std::collections::{HashMap, HashSet};
-use channels::outbound::channel_name::batch_resolve_channel_names;
+use channels::outbound::channel_name::{
+ batch_resolve_channel_names, resolve_channel_name_for_viewers,
+};
use chrono::{SubsecRound, Utc};
use entity_access::domain::models::AccessLevel;
use filter_ast::Expr;
@@ -1774,6 +1776,15 @@ impl CallRepository for PgCallRepo {
Ok(map.remove(channel_id))
}
+ #[tracing::instrument(err, skip(self))]
+ async fn resolve_channel_name_for_viewers<'a>(
+ &self,
+ channel_id: &Uuid,
+ viewer_ids: &[MacroUserIdStr<'a>],
+ ) -> Result<HashMap<MacroUserIdStr<'static>, String>, Self::Err> {
+ resolve_channel_name_for_viewers(&self.pool, *channel_id, viewer_ids).await
+ }
+
#[tracing::instrument(err, skip(self))]
async fn delete_call_record(
&self,
diff --git a/crates/call/src/outbound/pg_call_repo/test.rs b/crates/call/src/outbound/pg_call_repo/test.rs
index 81aed4ac61..4cfcc58763 100644
--- a/crates/call/src/outbound/pg_call_repo/test.rs
+++ b/crates/call/src/outbound/pg_call_repo/test.rs
@@ -2921,3 +2921,135 @@ async fn patch_call_transcript_custom_speakers_unknown_diarized_id_is_noop(
assert_eq!(record.transcript[2].speaker_id, "macro|[email protected]");
Ok(())
}
+
+// -- resolve_channel_name_for_viewers -----------------------------------------
+
+const DM_CHANNEL: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000d01);
+
+async fn insert_named_user(
+ pool: &Pool<Postgres>,
+ user_id: &MacroUserIdStr<'_>,
+ macro_user_id: Uuid,
+ first_name: &str,
+ last_name: &str,
+) -> anyhow::Result<()> {
+ insert_user_mapping(pool, user_id, macro_user_id).await?;
+ sqlx::query!(
+ r#"
+ INSERT INTO macro_user_info (macro_user_id, first_name, last_name)
+ VALUES ($1, $2, $3)
+ ON CONFLICT (macro_user_id) DO UPDATE
+ SET first_name = EXCLUDED.first_name, last_name = EXCLUDED.last_name
+ "#,
+ macro_user_id,
+ first_name,
+ last_name,
+ )
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
+async fn insert_dm_channel(
+ pool: &Pool<Postgres>,
+ channel_id: Uuid,
+ participants: &[&MacroUserIdStr<'_>],
+) -> anyhow::Result<()> {
+ sqlx::query!(
+ r#"
+ INSERT INTO comms_channels (id, name, channel_type, org_id, owner_id, created_at, updated_at)
+ VALUES ($1, NULL, 'direct_message', NULL, $2, now(), now())
+ "#,
+ channel_id,
+ participants[0].as_ref(),
+ )
+ .execute(pool)
+ .await?;
+ for participant in participants {
+ sqlx::query!(
+ r#"
+ INSERT INTO comms_channel_participants (channel_id, user_id, role, joined_at)
+ VALUES ($1, $2, 'member', now())
+ "#,
+ channel_id,
+ participant.as_ref(),
+ )
+ .execute(pool)
+ .await?;
+ }
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn resolve_channel_name_for_viewers_names_a_dm_after_the_other_participant(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ insert_named_user(&pool, USER_A.deref(), MACRO_USER_A, "Jacob", "Beckerman").await?;
+ insert_named_user(&pool, USER_B.deref(), MACRO_USER_B, "Teo", "Nys").await?;
+ insert_dm_channel(&pool, DM_CHANNEL, &[USER_A.deref(), USER_B.deref()]).await?;
+ let repo = repo(pool);
+
+ // User A (Jacob) starts the call; user B (Teo) is the only recipient.
+ let names = repo
+ .resolve_channel_name_for_viewers(&DM_CHANNEL, &[USER_B.deref().copied()])
+ .await?;
+
+ assert_eq!(
+ names.get(USER_B.deref()).map(String::as_str),
+ Some("Jacob Beckerman"),
+ "the callee must see the caller's name, not their own"
+ );
+
+ // The caller's own view, which the old code pushed to everyone, is the
+ // callee's name.
+ assert_eq!(
+ repo.resolve_channel_name(&DM_CHANNEL, USER_A.deref().copied())
+ .await?
+ .as_deref(),
+ Some("Teo Nys")
+ );
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn resolve_channel_name_for_viewers_uses_the_stored_name_for_every_viewer(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = repo(pool);
+
+ let names = repo
+ .resolve_channel_name_for_viewers(&CH1, &[USER_B.deref().copied(), USER_C.deref().copied()])
+ .await?;
+
+ assert_eq!(names.len(), 2);
+ assert!(
+ names.values().all(|name| name == "call-test-channel"),
+ "named channels read the same to everyone: {names:?}"
+ );
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn resolve_channel_name_for_viewers_is_empty_for_unknown_channel_or_no_viewers(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = repo(pool);
+
+ let unknown = repo
+ .resolve_channel_name_for_viewers(&Uuid::now_v7(), &[USER_B.deref().copied()])
+ .await?;
+ assert!(unknown.is_empty());
+
+ let no_viewers = repo.resolve_channel_name_for_viewers(&CH1, &[]).await?;
+ assert!(no_viewers.is_empty());
+ Ok(())
+}
diff --git a/crates/channels/src/outbound/channel_name.rs b/crates/channels/src/outbound/channel_name.rs
index c26f7304b8..0507623f23 100644
--- a/crates/channels/src/outbound/channel_name.rs
+++ b/crates/channels/src/outbound/channel_name.rs
@@ -2,7 +2,7 @@
use std::collections::{HashMap, HashSet};
-use macro_user_id::user_id::MacroUserIdStr;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use sqlx::PgPool;
use uuid::Uuid;
@@ -23,6 +23,77 @@ pub async fn batch_resolve_channel_names<'a>(
return Ok(HashMap::new());
}
+ let channels = load_channels(pool, channel_ids).await?;
+ let (participants_by_channel, name_lookup) =
+ 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)
+}
+
+/// Resolve the display name of one channel from the perspective of each of
+/// `viewer_user_ids`, keyed by viewer.
+///
+/// DM and unnamed private channels are named after the *other* participants,
+/// so the same channel reads differently to each member: to the caller a DM
+/// is named after the callee, and to the callee it is named after the caller.
+/// Use this when addressing several users about one channel (e.g. notifying
+/// channel members) so each sees the name they know the channel by.
+///
+/// Returns an empty map when the channel does not exist. The viewer is not an
+/// authorization check.
+#[tracing::instrument(skip(pool), err)]
+pub async fn resolve_channel_name_for_viewers<'a>(
+ pool: &PgPool,
+ channel_id: Uuid,
+ viewer_user_ids: &[MacroUserIdStr<'a>],
+) -> Result<HashMap<MacroUserIdStr<'static>, String>, sqlx::Error> {
+ if viewer_user_ids.is_empty() {
+ return Ok(HashMap::new());
+ }
+
+ let channels = load_channels(pool, &[channel_id]).await?;
+ 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);
+
+ 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,
+ );
+ (viewer.clone().into_owned(), resolved_name)
+ })
+ .collect())
+}
+
+type LoadedChannels = HashMap<Uuid, (Option<String>, ChannelType)>;
+
+async fn load_channels(pool: &PgPool, channel_ids: &[Uuid]) -> Result<LoadedChannels, sqlx::Error> {
let channel_rows = sqlx::query!(
r#"
SELECT id, name, channel_type as "channel_type!: ChannelType"
@@ -34,11 +105,18 @@ pub async fn batch_resolve_channel_names<'a>(
.fetch_all(pool)
.await?;
- let channels: HashMap<Uuid, (Option<String>, ChannelType)> = channel_rows
+ Ok(channel_rows
.into_iter()
.map(|r| (r.id, (r.name, r.channel_type)))
- .collect();
+ .collect())
+}
+/// Load participants and display names only for the channels whose name
+/// depends on who is looking (DMs and unnamed private channels).
+async fn load_viewer_dependent_names(
+ pool: &PgPool,
+ channels: &LoadedChannels,
+) -> Result<(HashMap<Uuid, Vec<MacroUserIdStr<'static>>>, NameLookup), sqlx::Error> {
let needs_participants: Vec<Uuid> = channels
.iter()
.filter(|(_, (name, ct))| {
@@ -49,28 +127,10 @@ pub async fn batch_resolve_channel_names<'a>(
.map(|(id, _)| *id)
.collect();
- let (participants_by_channel, name_lookup) = if needs_participants.is_empty() {
- (HashMap::new(), HashMap::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(),
- *channel_id,
- viewer_user_id.as_ref(),
- participants,
- &name_lookup,
- );
- resolved.insert(*channel_id, resolved_name);
+ if needs_participants.is_empty() {
+ return Ok((HashMap::new(), HashMap::new()));
}
-
- Ok(resolved)
+ load_participants_and_names(pool, &needs_participants).await
}
async fn load_participants_and_names(