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.

seanaye/feat/notify on agent patch (#4337)

Sean Aye967dc595e847
diff --git a/rust/cloud-storage/bot_id/src/lib.rs b/rust/cloud-storage/bot_id/src/lib.rs
index e54de67230..bd54b280d6 100644
--- a/rust/cloud-storage/bot_id/src/lib.rs
+++ b/rust/cloud-storage/bot_id/src/lib.rs
@@ -7,14 +7,9 @@ use uuid::Uuid;
const BOT_STORAGE_PREFIX: &str = "bot|";
-/// Stable UUID for the first-party "Macro AI" system bot.
-///
-/// This id is seeded by a migration and referenced directly by services so
-/// that Macro AI can be recognized without a database lookup.
-pub const MACRO_AI_BOT_UUID: Uuid = Uuid::from_u128(0x0000_0000_0000_0000_0000_0000_0000_a1a1);
-
/// Stable [`BotId`] for the first-party "Macro AI" system bot.
-pub const MACRO_AI_BOT_ID: BotId = BotId::from_uuid(MACRO_AI_BOT_UUID);
+pub const MACRO_AI_BOT_ID: BotId =
+ BotId::from_uuid(Uuid::from_u128(0x0000_0000_0000_0000_0000_0000_0000_a1a1));
/// Stable handle for the "Macro AI" system bot (used for `@` mentions).
pub const MACRO_AI_HANDLE: &str = "macro";
diff --git a/rust/cloud-storage/bots/src/inbound/channel_webhook_router.rs b/rust/cloud-storage/bots/src/inbound/channel_webhook_router.rs
index c6cb2b17db..738eda4307 100644
--- a/rust/cloud-storage/bots/src/inbound/channel_webhook_router.rs
+++ b/rust/cloud-storage/bots/src/inbound/channel_webhook_router.rs
@@ -251,6 +251,7 @@ where
thread_id: None,
attachments: Vec::new(),
nonce: None,
+ notification_policy: Default::default(),
},
)
.await?;
diff --git a/rust/cloud-storage/channel_bots/src/domain/service.rs b/rust/cloud-storage/channel_bots/src/domain/service.rs
index a7d8c716ef..4ccd531dfb 100644
--- a/rust/cloud-storage/channel_bots/src/domain/service.rs
+++ b/rust/cloud-storage/channel_bots/src/domain/service.rs
@@ -4,7 +4,10 @@ use std::collections::HashSet;
use std::fmt::Write as _;
use std::sync::Arc;
-use channels::domain::models::{ParticipantRole, PatchMessageRequest, PostMessageRequest, Sender};
+use channels::domain::models::{
+ ParticipantRole, PatchMessageNotificationPolicy, PatchMessageRequest,
+ PostMessageNotificationPolicy, PostMessageRequest, Sender,
+};
use channels::domain::ports::{ChannelMutationErr, ChannelService};
use uuid::Uuid;
@@ -268,6 +271,7 @@ where
thread_id: Some(event.reply_thread_id),
attachments: Vec::new(),
nonce: None,
+ notification_policy: PostMessageNotificationPolicy::Silent,
},
)
.await?;
@@ -303,6 +307,7 @@ where
attachment_ids_to_delete: None,
attachments_to_add: None,
nonce: None,
+ notification_policy: PatchMessageNotificationPolicy::NotifyAsPostedMessage,
},
)
.await
diff --git a/rust/cloud-storage/channel_bots/src/domain/service/tests.rs b/rust/cloud-storage/channel_bots/src/domain/service/tests.rs
index e361ae89a1..878a038433 100644
--- a/rust/cloud-storage/channel_bots/src/domain/service/tests.rs
+++ b/rust/cloud-storage/channel_bots/src/domain/service/tests.rs
@@ -3,7 +3,8 @@ use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use channels::domain::models::{
AttachmentEntityReference, ChannelAttachmentType, ChannelContextMessage, ChannelMessageFilters,
- ChannelParticipant, MessagePageDirection, MutatedMessage, PostMessageResponse,
+ ChannelParticipant, MessagePageDirection, MutatedMessage, PatchMessageNotificationPolicy,
+ PatchMessageRequest, PostMessageNotificationPolicy, PostMessageRequest, PostMessageResponse,
ResolvedChannelMessage, Sender, ThreadReply,
};
use channels::domain::ports::{
@@ -123,14 +124,18 @@ impl AgentResponder for TestResponder {
/// missing (deleted while the agent ran).
struct MutationChannelService {
thinking_deleted: bool,
+ posted_policies: Mutex<Vec<PostMessageNotificationPolicy>>,
patched: Mutex<Vec<String>>,
+ patched_policies: Mutex<Vec<PatchMessageNotificationPolicy>>,
}
impl MutationChannelService {
fn new(thinking_deleted: bool) -> Self {
Self {
thinking_deleted,
+ posted_policies: Mutex::new(Vec::new()),
patched: Mutex::new(Vec::new()),
+ patched_policies: Mutex::new(Vec::new()),
}
}
}
@@ -214,8 +219,12 @@ impl ChannelService for MutationChannelService {
&self,
_actor: Sender,
_channel_id: Uuid,
- _req: PostMessageRequest,
+ req: PostMessageRequest,
) -> impl Future<Output = Result<PostMessageResponse, ChannelMutationErr>> + Send {
+ self.posted_policies
+ .lock()
+ .unwrap()
+ .push(req.notification_policy);
async move {
Ok(PostMessageResponse {
id: Uuid::new_v4().to_string(),
@@ -232,6 +241,10 @@ impl ChannelService for MutationChannelService {
_message_id: Uuid,
req: PatchMessageRequest,
) -> impl Future<Output = Result<(), ChannelMutationErr>> + Send {
+ self.patched_policies
+ .lock()
+ .unwrap()
+ .push(req.notification_policy);
if !self.thinking_deleted {
self.patched
.lock()
@@ -342,10 +355,18 @@ async fn handle_patches_thinking_message_with_reply() {
.await
.unwrap();
+ assert_eq!(
+ channels.posted_policies.lock().unwrap().clone(),
+ vec![PostMessageNotificationPolicy::Silent]
+ );
assert_eq!(
channels.patched.lock().unwrap().clone(),
vec!["the answer".to_string()]
);
+ assert_eq!(
+ channels.patched_policies.lock().unwrap().clone(),
+ vec![PatchMessageNotificationPolicy::NotifyAsPostedMessage]
+ );
}
#[tokio::test]
diff --git a/rust/cloud-storage/channels/src/domain/events.rs b/rust/cloud-storage/channels/src/domain/events.rs
index 7a5e93f4a7..45d91ed65b 100644
--- a/rust/cloud-storage/channels/src/domain/events.rs
+++ b/rust/cloud-storage/channels/src/domain/events.rs
@@ -2,11 +2,24 @@
use crate::domain::models::{
ChannelMetadata, ChannelParticipant, ChannelType, CountedReaction, MutatedAttachment,
- MutatedMessage, Sender, SimpleMention, TypingAction,
+ MutatedMessage, PostMessageNotificationPolicy, Sender, SimpleMention, TypingAction,
};
use macro_user_id::user_id::MacroUserIdStr;
use uuid::Uuid;
+/// Notification context for a patched message that should notify like a new post.
+#[derive(Debug, Clone)]
+pub struct MessageChangedNotificationContext {
+ /// Resolved channel metadata for downstream notifications.
+ pub metadata: ChannelMetadata,
+ /// Active channel participants at mutation time.
+ pub participants: Vec<ChannelParticipant>,
+ /// Mentions to use for notification routing.
+ pub mentions: Vec<SimpleMention>,
+ /// Whether the message contains attachments after the patch.
+ pub has_attachments: bool,
+}
+
/// Events emitted after durable channel state changes.
#[derive(Debug, Clone)]
pub enum ChannelEvent {
@@ -46,6 +59,8 @@ pub enum ChannelEvent {
attachments: Vec<MutatedAttachment>,
/// Client mutation nonce echoed to realtime listeners.
nonce: Option<String>,
+ /// Internal notification policy for this post.
+ notification_policy: PostMessageNotificationPolicy,
},
/// Message attachments changed.
AttachmentsChanged {
@@ -74,6 +89,8 @@ pub enum ChannelEvent {
recipients: Vec<MacroUserIdStr<'static>>,
/// Client mutation nonce echoed to realtime listeners.
nonce: Option<String>,
+ /// Optional notification context when this patch should notify like a new post.
+ posted_notification: Option<MessageChangedNotificationContext>,
},
/// Message tombstone state changed.
MessageDeleted {
diff --git a/rust/cloud-storage/channels/src/domain/models.rs b/rust/cloud-storage/channels/src/domain/models.rs
index fe644dfe7e..4d23bf0ca0 100644
--- a/rust/cloud-storage/channels/src/domain/models.rs
+++ b/rust/cloud-storage/channels/src/domain/models.rs
@@ -916,6 +916,26 @@ impl ReferencedShareItem {
}
}
+/// Internal notification behavior for a posted channel message.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum PostMessageNotificationPolicy {
+ /// Apply the normal channel notification rules.
+ #[default]
+ Default,
+ /// Do not send notifications for this post. Realtime/search side effects still run.
+ Silent,
+}
+
+/// Internal notification behavior for a patched channel message.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum PatchMessageNotificationPolicy {
+ /// Apply the normal edit behavior: realtime/search only, no notifications.
+ #[default]
+ Default,
+ /// Notify as though the patched message content had just been posted.
+ NotifyAsPostedMessage,
+}
+
/// Request to send a channel message.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
@@ -930,6 +950,10 @@ pub struct PostMessageRequest {
pub attachments: Vec<NewChannelAttachment>,
/// Optional optimistic-update nonce.
pub nonce: Option<String>,
+ /// Internal notification policy for this post.
+ #[serde(skip)]
+ #[cfg_attr(feature = "inbound", schema(ignore))]
+ pub notification_policy: PostMessageNotificationPolicy,
}
/// Response returned after sending a message.
@@ -956,6 +980,10 @@ pub struct PatchMessageRequest {
pub attachments_to_add: Option<Vec<NewChannelAttachment>>,
/// Optional optimistic-update nonce.
pub nonce: Option<String>,
+ /// Internal notification policy for this patch.
+ #[serde(skip)]
+ #[cfg_attr(feature = "inbound", schema(ignore))]
+ pub notification_policy: PatchMessageNotificationPolicy,
}
/// Query parameters for deleting a message.
diff --git a/rust/cloud-storage/channels/src/domain/service.rs b/rust/cloud-storage/channels/src/domain/service.rs
index a1bd2f5cf0..fcc3c7cf21 100644
--- a/rust/cloud-storage/channels/src/domain/service.rs
+++ b/rust/cloud-storage/channels/src/domain/service.rs
@@ -7,10 +7,11 @@ use crate::domain::{
ChannelPreviewData, ChannelType, CreateEntityMentionOptions, DeleteMessageQuery,
EntityMention, GetOrCreateAction, GetOrCreateChannelResponse, GetOrCreateDmRequest,
GetOrCreatePrivateRequest, MessagePageDirection, NewChannelAttachment, ParticipantRole,
- PatchChannelRequest, PatchMessageRequest, PostMessageRequest, PostMessageResponse,
- PostReactionRequest, PostTypingRequest, ReactionAction, ReferencedShareItem,
- RemoveParticipantsRequest, ResolvedChannelMessage, Sender, SimpleMention, ThreadInfo,
- ThreadReply, ThreadReplyRow, TopLevelMessageRow, WithChannelId,
+ PatchChannelRequest, PatchMessageNotificationPolicy, PatchMessageRequest,
+ PostMessageRequest, PostMessageResponse, PostReactionRequest, PostTypingRequest,
+ ReactionAction, ReferencedShareItem, RemoveParticipantsRequest, ResolvedChannelMessage,
+ Sender, SimpleMention, ThreadInfo, ThreadReply, ThreadReplyRow, TopLevelMessageRow,
+ WithChannelId,
},
ports::{
ChannelAttachmentsPage, ChannelEventDispatcher, ChannelMessagesErr,
@@ -594,6 +595,7 @@ where
has_attachments,
attachments,
nonce: req.nonce.clone(),
+ notification_policy: req.notification_policy,
});
Ok(PostMessageResponse {
@@ -609,8 +611,17 @@ where
actor_role: ParticipantRole,
channel_id: Uuid,
message_id: Uuid,
- mut req: PatchMessageRequest,
+ req: PatchMessageRequest,
) -> Result<(), ChannelMutationErr> {
+ let PatchMessageRequest {
+ content,
+ mentions: replacement_mentions,
+ attachment_ids_to_delete,
+ attachments_to_add,
+ nonce,
+ notification_policy,
+ } = req;
+
let actor_storage_id = actor.to_storage_string();
let owner = self
.repo
@@ -624,8 +635,8 @@ where
));
}
- let attachments_to_delete = req.attachment_ids_to_delete.clone().unwrap_or_default();
- let attachments_to_add = req.attachments_to_add.clone().unwrap_or_default();
+ let attachments_to_delete = attachment_ids_to_delete.clone().unwrap_or_default();
+ let attachments_to_add = attachments_to_add.clone().unwrap_or_default();
let attachments_changed =
!attachments_to_delete.is_empty() || !attachments_to_add.is_empty();
@@ -636,19 +647,19 @@ where
message_id,
attachments_to_delete,
attachments_to_add,
- req.nonce.clone(),
+ nonce.clone(),
)
.await?;
}
- if let Some(content) = req.content.clone() {
+ if let Some(content) = content.as_ref() {
let message = self
.repo
- .patch_message(channel_id, message_id, content)
+ .patch_message(channel_id, message_id, content.clone())
.await
.map_err(|e| ChannelMutationErr::Repo(e.into()))?;
- if let Some(mentions) = req.mentions.take() {
+ if let Some(mentions) = replacement_mentions.clone() {
self.repo
.sync_message_mentions(message_id, mentions.clone())
.await
@@ -686,12 +697,53 @@ where
)
};
+ let posted_notification =
+ if notification_policy == PatchMessageNotificationPolicy::NotifyAsPostedMessage {
+ let metadata = if let Some(user_actor) = actor.as_user() {
+ self.repo
+ .get_channel_metadata(channel_id, user_actor.clone())
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?
+ } else {
+ let info = self
+ .repo
+ .get_channel_info(channel_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ ChannelMetadata {
+ channel_type: info.channel_type,
+ channel_name: info.name.unwrap_or_default(),
+ }
+ };
+ let notification_participants = self
+ .repo
+ .get_participants(channel_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ let has_attachments = !self
+ .repo
+ .get_message_attachments(message_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?
+ .is_empty();
+
+ Some(crate::domain::events::MessageChangedNotificationContext {
+ metadata,
+ participants: notification_participants,
+ mentions: replacement_mentions.clone().unwrap_or_default(),
+ has_attachments,
+ })
+ } else {
+ None
+ };
+
self.events.dispatch(ChannelEvent::MessageChanged {
channel_id,
actor: actor.clone(),
message: message.clone(),
recipients: participants,
- nonce: req.nonce.clone(),
+ nonce,
+ posted_notification,
});
if actor.as_user().is_some()
@@ -706,7 +758,7 @@ where
}
if attachments_changed
- && req.content.is_none()
+ && content.is_none()
&& actor.as_user().is_some()
&& let Err(err) = self
.repo
diff --git a/rust/cloud-storage/channels/src/domain/service/test.rs b/rust/cloud-storage/channels/src/domain/service/test.rs
index fe333de253..f803893d7d 100644
--- a/rust/cloud-storage/channels/src/domain/service/test.rs
+++ b/rust/cloud-storage/channels/src/domain/service/test.rs
@@ -826,6 +826,7 @@ async fn post_message_emits_message_posted_event_and_updates_share_permissions()
height: None,
}],
nonce: Some("nonce-1".to_string()),
+ notification_policy: Default::default(),
},
)
.await
@@ -895,6 +896,7 @@ async fn bot_post_message_persists_bot_sender_and_skips_user_only_effects() {
height: None,
}],
nonce: None,
+ notification_policy: Default::default(),
},
)
.await
@@ -939,6 +941,7 @@ async fn patch_message_content_emits_message_changed_event_to_thread_participant
attachment_ids_to_delete: None,
attachments_to_add: None,
nonce: Some("edit-nonce".to_string()),
+ notification_policy: Default::default(),
},
)
.await
@@ -964,6 +967,60 @@ async fn patch_message_content_emits_message_changed_event_to_thread_participant
assert_eq!(recipients[0].as_ref(), "macro|[email protected]");
}
+#[tokio::test]
+async fn patch_message_notify_as_posted_adds_notification_context() {
+ let channel_id = Uuid::new_v4();
+ let thread_id = Uuid::new_v4();
+ let bot_id = BotId::from_uuid(Uuid::new_v4());
+ let bot_sender = bot_id.to_storage_string();
+ let repo = FakeMutationRepo::new(channel_id, &bot_sender);
+ repo.state.lock().unwrap().message.thread_id = Some(thread_id);
+ repo.state.lock().unwrap().message.sender_id = Sender::Bot(bot_id);
+ let message_id = repo.state.lock().unwrap().message.id;
+ let events = FakeEvents::default();
+ let svc = mutation_service(
+ repo.clone(),
+ events.clone(),
+ FakeReferenceSharing::default(),
+ );
+
+ svc.patch_message(
+ Sender::Bot(bot_id),
+ ParticipantRole::Member,
+ channel_id,
+ message_id,
+ PatchMessageRequest {
+ content: Some("final answer".to_string()),
+ mentions: None,
+ attachment_ids_to_delete: None,
+ attachments_to_add: None,
+ nonce: None,
+ notification_policy: PatchMessageNotificationPolicy::NotifyAsPostedMessage,
+ },
+ )
+ .await
+ .unwrap();
+
+ let emitted = events.events.lock().unwrap();
+ assert_eq!(emitted.len(), 1);
+ let ChannelEvent::MessageChanged {
+ message,
+ posted_notification,
+ ..
+ } = &emitted[0]
+ else {
+ panic!("expected MessageChanged event, got {:?}", emitted[0]);
+ };
+ assert_eq!(message.content, "final answer");
+ let posted_notification = posted_notification
+ .as_ref()
+ .expect("expected posted notification context");
+ assert_eq!(posted_notification.metadata.channel_name, "Project");
+ assert_eq!(posted_notification.participants.len(), 2);
+ assert!(posted_notification.mentions.is_empty());
+ assert!(!posted_notification.has_attachments);
+}
+
#[tokio::test]
async fn patch_of_deleted_message_is_not_found() {
let channel_id = Uuid::new_v4();
@@ -990,6 +1047,7 @@ async fn patch_of_deleted_message_is_not_found() {
attachment_ids_to_delete: None,
attachments_to_add: None,
nonce: None,
+ notification_policy: Default::default(),
},
)
.await
diff --git a/rust/cloud-storage/channels/src/domain/side_effects.rs b/rust/cloud-storage/channels/src/domain/side_effects.rs
index 2ec06dda14..2b0b8a73e3 100644
--- a/rust/cloud-storage/channels/src/domain/side_effects.rs
+++ b/rust/cloud-storage/channels/src/domain/side_effects.rs
@@ -4,7 +4,8 @@ use crate::domain::{
events::ChannelEvent,
models::{
BotId, BotSenderProfile, ChannelMetadata, ChannelParticipant, ChannelType, CountedReaction,
- MutatedAttachment, MutatedMessage, Sender, SimpleMention, TypingAction,
+ MutatedAttachment, MutatedMessage, PostMessageNotificationPolicy, Sender, SimpleMention,
+ TypingAction,
},
ports::{
ChannelContactsDispatcher, ChannelEventDispatcher, ChannelEventHandler,
@@ -292,6 +293,7 @@ struct MessagePostedSideEffects {
has_attachments: bool,
attachments: Vec<MutatedAttachment>,
nonce: Option<String>,
+ notification_policy: PostMessageNotificationPolicy,
}
struct InviteNotificationRequest {
@@ -408,6 +410,7 @@ where
has_attachments,
attachments,
nonce,
+ notification_policy,
} => {
self.handle_message_posted(MessagePostedSideEffects {
channel_id,
@@ -418,6 +421,7 @@ where
has_attachments,
attachments,
nonce,
+ notification_policy,
})
.await;
}
@@ -444,18 +448,32 @@ where
message,
recipients,
nonce,
+ posted_notification,
..
} => {
let message_id = message.id;
let bot_profile = self.bot_profile_for_message(&message).await;
self.publish_realtime(ChannelRealtimeEffect::Message {
recipients,
- message,
- bot_profile,
+ message: message.clone(),
+ bot_profile: bot_profile.clone(),
nonce,
})
.await;
self.search.index_message(channel_id, message_id).await;
+
+ if let Some(notification) = posted_notification {
+ self.send_message_posted_notifications(PostedMessageNotificationInputs {
+ channel_id,
+ metadata: notification.metadata,
+ participants: notification.participants,
+ message,
+ mentions: notification.mentions,
+ has_attachments: notification.has_attachments,
+ bot_profile,
+ })
+ .await;
+ }
}
ChannelEvent::MessageDeleted {
channel_id,
@@ -561,6 +579,7 @@ where
has_attachments,
attachments,
nonce,
+ notification_policy,
} = event;
let recipients = participant_ids(&participants);
let bot_profile = self.bot_profile_for_message(&message).await;
@@ -585,22 +604,32 @@ where
self.search.index_message(channel_id, message.id).await;
self.dispatch_bot_triggers(channel_id, &message, &mentions);
- self.send_message_posted_notifications(PostedMessageNotificationInputs {
- channel_id,
- metadata,
- participants,
- message,
- mentions,
- has_attachments,
- bot_profile,
- })
- .await;
+ if notification_policy == PostMessageNotificationPolicy::Default {
+ self.send_message_posted_notifications(PostedMessageNotificationInputs {
+ channel_id,
+ metadata,
+ participants,
+ message,
+ mentions,
+ has_attachments,
+ bot_profile,
+ })
+ .await;
+ }
}
/// Resolve the public bot profile when the message sender is a bot.
async fn bot_profile_for_message(&self, message: &MutatedMessage) -> Option<BotSenderProfile> {
match &message.sender_id {
- Sender::Bot(bot_id) => self.context.get_bot_sender_profile(*bot_id).await,
+ Sender::Bot(bot_id) => {
+ if *bot_id == bot_id::MACRO_AI_BOT_ID {
+ return Some(BotSenderProfile {
+ name: bot_id::MACRO_AI_NAME.to_string(),
+ avatar_url: None,
+ });
+ }
+ self.context.get_bot_sender_profile(*bot_id).await
+ }
Sender::User(_) => None,
}
}
@@ -1107,796 +1136,4 @@ fn contact_sync_users_for_event(event: &ChannelEvent) -> Option<HashSet<MacroUse
}
#[cfg(test)]
-mod tests {
- use super::*;
- use crate::domain::{
- models::{BotId, ParticipantRole, Sender},
- ports::{
- ChannelEventHandler, ChannelNotificationSender, ChannelRealtimePublisher,
- ChannelSearchIndexer, ChannelSideEffectContext,
- },
- };
- use chrono::Utc;
- use std::sync::{Arc, Mutex};
-
- type IndexedMessages = Arc<Mutex<Vec<(Uuid, Uuid)>>>;
- type RemovedMessages = Arc<Mutex<Vec<(Uuid, Option<Uuid>)>>>;
-
- #[derive(Clone)]
- struct FakeContext {
- message_count: i64,
- document_mentions: Vec<ChannelDocumentMention>,
- bot_profile: Option<BotSenderProfile>,
- thread_context: ThreadNotificationContext,
- }
-
- impl Default for FakeContext {
- fn default() -> Self {
- Self {
- message_count: 2,
- document_mentions: Vec::new(),
- bot_profile: Some(BotSenderProfile {
- name: "Test Bot".to_string(),
- avatar_url: Some("https://example.com/bot.png".to_string()),
- }),
- thread_context: ThreadNotificationContext::default(),
- }
- }
- }
-
- impl ChannelSideEffectContext for FakeContext {
- type Err = anyhow::Error;
-
- async fn get_channel_message_count(&self, _channel_id: Uuid) -> Result<i64, Self::Err> {
- Ok(self.message_count)
- }
-
- async fn get_existing_user_ids(
- &self,
- user_ids: Vec<MacroUserIdStr<'static>>,
- ) -> Result<HashSet<String>, Self::Err> {
- Ok(user_ids
- .into_iter()
- .map(|user_id| user_id.as_ref().to_string())
- .collect())
- }
-
- async fn get_document_mentions(
- &self,
- _document_ids: Vec<String>,
- ) -> Result<Vec<ChannelDocumentMention>, Self::Err> {
- Ok(self.document_mentions.clone())
- }
-
- async fn get_thread_notification_context(
- &self,
- _thread_id: Uuid,
- ) -> Result<ThreadNotificationContext, Self::Err> {
- Ok(self.thread_context.clone())
- }
-
- async fn get_sender_profile_picture_url(
- &self,
- _sender_id: MacroUserIdStr<'static>,
- ) -> Option<String> {
- Some("https://example.com/avatar.png".to_string())
- }
-
- async fn get_bot_sender_profile(&self, _bot_id: BotId) -> Option<BotSenderProfile> {
- self.bot_profile.clone()
- }
- }
-
- #[derive(Clone, Default)]
- struct FakeRealtime {
- effects: Arc<Mutex<Vec<ChannelRealtimeEffect>>>,
- }
-
- impl ChannelRealtimePublisher for FakeRealtime {
- type Err = anyhow::Error;
-
- async fn publish(&self, effect: ChannelRealtimeEffect) -> Result<(), Self::Err> {
- self.effects.lock().unwrap().push(effect);
- Ok(())
- }
- }
-
- #[derive(Clone, Default)]
- struct FakeNotifications {
- effects: Arc<Mutex<Vec<ChannelNotificationEffect>>>,
- }
-
- impl ChannelNotificationSender for FakeNotifications {
- type Err = anyhow::Error;
-
- async fn send(&self, notification: ChannelNotificationEffect) -> Result<(), Self::Err> {
- self.effects.lock().unwrap().push(notification);
- Ok(())
- }
- }
-
- #[derive(Clone, Default)]
- struct FakeSearch {
- indexed: IndexedMessages,
- removed: RemovedMessages,
- }
-
- impl ChannelSearchIndexer for FakeSearch {
- async fn index_message(&self, channel_id: Uuid, message_id: Uuid) {
- self.indexed.lock().unwrap().push((channel_id, message_id));
- }
-
- async fn remove_message(&self, channel_id: Uuid, message_id: Option<Uuid>) {
- self.removed.lock().unwrap().push((channel_id, message_id));
- }
- }
-
- #[derive(Clone, Default)]
- struct FakeContacts {
- users: Arc<Mutex<Vec<HashSet<MacroUserIdStr<'static>>>>>,
- }
-
- impl ChannelContactsDispatcher for FakeContacts {
- type Err = anyhow::Error;
-
- async fn enqueue_contacts(
- &self,
- users: HashSet<MacroUserIdStr<'static>>,
- ) -> Result<(), Self::Err> {
- self.users.lock().unwrap().push(users);
- Ok(())
- }
- }
-
- fn user(email: &str) -> MacroUserIdStr<'static> {
- MacroUserIdStr::try_from_email(email).unwrap()
- }
-
- fn users(emails: &[&str]) -> Vec<MacroUserIdStr<'static>> {
- emails.iter().map(|email| user(email)).collect()
- }
-
- #[tokio::test]
- async fn message_posted_derives_realtime_search_and_notification_effects() {
- let channel_id = Uuid::new_v4();
- let message_id = Uuid::new_v4();
- let sender = user("[email protected]");
- let recipient = user("[email protected]");
- let realtime = FakeRealtime::default();
- let notifications = FakeNotifications::default();
- let search = FakeSearch::default();
- let contacts = FakeContacts::default();
- let service = ChannelSideEffectService::new(
- FakeContext::default(),
- realtime.clone(),
- notifications.clone(),
- search.clone(),
- contacts,
- );
- let now = Utc::now();
-
- service
- .handle(ChannelEvent::MessagePosted {
- channel_id,
- metadata: ChannelMetadata {
- channel_type: ChannelType::Private,
- channel_name: "Project".to_string(),
- },
- participants: vec![
- ChannelParticipant {
- channel_id,
- user_id: sender.as_ref().to_string(),
- role: ParticipantRole::Member,
- joined_at: now,
- left_at: None,
- },
- ChannelParticipant {
- channel_id,
- user_id: recipient.as_ref().to_string(),
- role: ParticipantRole::Member,
- joined_at: now,
- left_at: None,
- },
- ],
- message: MutatedMessage {
- id: message_id,
- channel_id,
- thread_id: None,
- sender_id: Sender::User(sender.clone()),
- content: "hello".to_string(),
- created_at: now,
- updated_at: now,
- edited_at: None,
- deleted_at: None,
- },
- mentions: Vec::new(),
- has_attachments: false,
- attachments: Vec::new(),
- nonce: Some("nonce-1".to_string()),
- })
- .await;
-
- let realtime_effects = realtime.effects.lock().unwrap();
- assert_eq!(realtime_effects.len(), 1);
- let ChannelRealtimeEffect::Message {
- recipients,
- message,
- nonce,
- ..
- } = &realtime_effects[0]
- else {
- panic!("expected message realtime effect");
- };
- assert_eq!(message.id, message_id);
- assert_eq!(nonce.as_deref(), Some("nonce-1"));
- assert_eq!(recipients.len(), 2);
- drop(realtime_effects);
-
- assert_eq!(
- *search.indexed.lock().unwrap(),
- vec![(channel_id, message_id)]
- );
-
- let notification_effects = notifications.effects.lock().unwrap();
- assert_eq!(notification_effects.len(), 1);
- let ChannelNotificationEffect::ChannelMessage {
- message_id: notified_message_id,
- sender: notified_sender,
- recipient_ids,
- metadata,
- ..
- } = &notification_effects[0]
- else {
- panic!("expected channel message notification effect");
- };
- assert_eq!(*notified_message_id, message_id);
- assert_eq!(*notified_sender, NotificationSender::User(sender.clone()));
- assert_eq!(metadata.channel_name, "Project");
- assert_eq!(recipient_ids.len(), 1);
- assert!(recipient_ids.contains(&recipient));
- }
-
- /// Build a MessagePosted event for a bot-sent message.
- fn bot_message_posted_event(
- channel_id: Uuid,
- message_id: Uuid,
- thread_id: Option<Uuid>,
- participant_principals: &[&str],
- ) -> ChannelEvent {
- let now = Utc::now();
- ChannelEvent::MessagePosted {
- channel_id,
- metadata: ChannelMetadata {
- channel_type: ChannelType::Private,
- channel_name: "Project".to_string(),
- },
- participants: participant_principals
- .iter()
- .map(|principal| ChannelParticipant {
- channel_id,
- user_id: principal.to_string(),
- role: ParticipantRole::Member,
- joined_at: now,
- left_at: None,
- })
- .collect(),
- message: MutatedMessage {
- id: message_id,
- channel_id,
- thread_id,
- sender_id: Sender::Bot(BotId::from_uuid(Uuid::new_v4())),
- content: "hello".to_string(),
- created_at: now,
- updated_at: now,
- edited_at: None,
- deleted_at: None,
- },
- mentions: Vec::new(),
- has_attachments: false,
- attachments: Vec::new(),
- nonce: None,
- }
- }
-
- #[tokio::test]
- async fn bot_message_posted_sends_channel_message_notification() {
- let channel_id = Uuid::new_v4();
- let message_id = Uuid::new_v4();
- let recipient = user("[email protected]");
- let realtime = FakeRealtime::default();
- let notifications = FakeNotifications::default();
- let search = FakeSearch::default();
- let service = ChannelSideEffectService::new(
- FakeContext::default(),
- realtime.clone(),
- notifications.clone(),
- search.clone(),
- FakeContacts::default(),
- );
-
- service
- .handle(bot_message_posted_event(
- channel_id,
- message_id,
- None,
- &[recipient.as_ref()],
- ))
- .await;
-
- assert_eq!(realtime.effects.lock().unwrap().len(), 1);
- assert_eq!(
- *search.indexed.lock().unwrap(),
- vec![(channel_id, message_id)]
- );
-
- let notification_effects = notifications.effects.lock().unwrap();
- assert_eq!(notification_effects.len(), 1);
- let ChannelNotificationEffect::ChannelMessage {
- sender,
- sender_profile_picture_url,
- recipient_ids,
- ..
- } = &notification_effects[0]
- else {
- panic!("expected channel message notification effect");
- };
- assert_eq!(
- *sender,
- NotificationSender::Bot {
- name: "Test Bot".to_string()
- }
- );
- assert_eq!(
- sender_profile_picture_url.as_deref(),
- Some("https://example.com/bot.png")
- );
- assert_eq!(recipient_ids.len(), 1);
- assert!(recipient_ids.contains(&recipient));
- }
-
- #[tokio::test]
- async fn bot_message_without_profile_skips_notifications() {
- let channel_id = Uuid::new_v4();
- let message_id = Uuid::new_v4();
- let recipient = user("[email protected]");
- let realtime = FakeRealtime::default();
- let notifications = FakeNotifications::default();
- let search = FakeSearch::default();
- let service = ChannelSideEffectService::new(
- FakeContext {
- bot_profile: None,
- ..FakeContext::default()
- },
- realtime.clone(),
- notifications.clone(),
- search.clone(),
- FakeContacts::default(),
- );
-
- service
- .handle(bot_message_posted_event(
- channel_id,
- message_id,
- None,
- &[recipient.as_ref()],
- ))
- .await;
-
- assert_eq!(realtime.effects.lock().unwrap().len(), 1);
- assert_eq!(
- *search.indexed.lock().unwrap(),
- vec![(channel_id, message_id)]
- );
- assert!(notifications.effects.lock().unwrap().is_empty());
- }
-
- #[tokio::test]
- async fn bot_first_message_sends_channel_message_not_invite() {
- let channel_id = Uuid::new_v4();
- let recipient = user("[email protected]");
- let notifications = FakeNotifications::default();
- let service = ChannelSideEffectService::new(
- FakeContext {
- message_count: 1,
- ..FakeContext::default()
- },
- FakeRealtime::default(),
- notifications.clone(),
- FakeSearch::default(),
- FakeContacts::default(),
- );
-
- service
- .handle(bot_message_posted_event(
- channel_id,
- Uuid::new_v4(),
- None,
- &[recipient.as_ref()],
- ))
- .await;
-
- let notification_effects = notifications.effects.lock().unwrap();
- assert_eq!(notification_effects.len(), 1);
- assert!(matches!(
- &notification_effects[0],
- ChannelNotificationEffect::ChannelMessage { .. }
- ));
- }
-
- #[tokio::test]
- async fn bot_thread_reply_sends_reply_notification() {
- let channel_id = Uuid::new_v4();
- let recipient = user("[email protected]");
- let parent_sender = user("[email protected]");
- let notifications = FakeNotifications::default();
- let service = ChannelSideEffectService::new(
- FakeContext {
- thread_context: ThreadNotificationContext {
- participants: vec![recipient.clone(), parent_sender.clone()],
- parent_sender_id: Some(parent_sender.clone()),
- },
- ..FakeContext::default()
- },
- FakeRealtime::default(),
- notifications.clone(),
- FakeSearch::default(),
- FakeContacts::default(),
- );
-
- service
- .handle(bot_message_posted_event(
- channel_id,
- Uuid::new_v4(),
- Some(Uuid::new_v4()),
- &[recipient.as_ref(), parent_sender.as_ref()],
- ))
- .await;
-
- let notification_effects = notifications.effects.lock().unwrap();
- assert_eq!(notification_effects.len(), 1);
- let ChannelNotificationEffect::Reply {
- sender,
- thread_parent_sender_id,
- recipient_ids,
- ..
- } = &notification_effects[0]
- else {
- panic!("expected reply notification effect");
- };
- assert_eq!(
- *sender,
- NotificationSender::Bot {
- name: "Test Bot".to_string()
- }
- );
- assert_eq!(*thread_parent_sender_id, Some(parent_sender.clone()));
- assert!(recipient_ids.contains(&recipient));
- assert!(recipient_ids.contains(&parent_sender));
- }
-
- #[tokio::test]
- async fn bot_participant_is_never_a_notification_recipient() {
- let channel_id = Uuid::new_v4();
- let recipient = user("[email protected]");
- let bot_principal = BotId::from_uuid(Uuid::new_v4()).to_storage_string();
- let notifications = FakeNotifications::default();
- let service = ChannelSideEffectService::new(
- FakeContext::default(),
- FakeRealtime::default(),
- notifications.clone(),
- FakeSearch::default(),
- FakeContacts::default(),
- );
-
- service
- .handle(bot_message_posted_event(
- channel_id,
- Uuid::new_v4(),
- None,
- &[recipient.as_ref(), bot_principal.as_str()],
- ))
- .await;
-
- let notification_effects = notifications.effects.lock().unwrap();
- assert_eq!(notification_effects.len(), 1);
- let ChannelNotificationEffect::ChannelMessage { recipient_ids, .. } =
- &notification_effects[0]
- else {
- panic!("expected channel message notification effect");
- };
- assert_eq!(recipient_ids.len(), 1);
- assert!(recipient_ids.contains(&recipient));
- }
-
- #[tokio::test]
- async fn user_message_with_bot_mention_enqueues_bot_trigger() {
- let channel_id = Uuid::new_v4();
- let message_id = Uuid::new_v4();
- let sender = user("[email protected]");
- let recipient = user("[email protected]");
- let (bot_trigger_sender, mut bot_trigger_receiver) = tokio::sync::mpsc::unbounded_channel();
- let service = ChannelSideEffectService::new(
- FakeContext::default(),
- FakeRealtime::default(),
- FakeNotifications::default(),
- FakeSearch::default(),
- FakeContacts::default(),
- )
- .with_bot_trigger_sender(bot_trigger_sender);
- let now = Utc::now();
-
- service
- .handle(ChannelEvent::MessagePosted {
- channel_id,
- metadata: ChannelMetadata {
- channel_type: ChannelType::Private,
- channel_name: "Project".to_string(),
- },
- participants: vec![
- ChannelParticipant {
- channel_id,
- user_id: sender.as_ref().to_string(),
- role: ParticipantRole::Member,
- joined_at: now,
- left_at: None,
- },
- ChannelParticipant {
- channel_id,
- user_id: recipient.as_ref().to_string(),
- role: ParticipantRole::Member,
- joined_at: now,
- left_at: None,
- },
- ],
- message: MutatedMessage {
- id: message_id,
- channel_id,
- thread_id: None,
- sender_id: Sender::User(sender),
- content: "@macro help".to_string(),
- created_at: now,
- updated_at: now,
- edited_at: None,
- deleted_at: None,
- },
- mentions: vec![SimpleMention {
- entity_type: "user".to_string(),
- entity_id: bot_id::MACRO_AI_BOT_ID.to_string(),
- }],
- has_attachments: false,
- attachments: Vec::new(),
- nonce: None,
- })
- .await;
-
- let trigger = bot_trigger_receiver
- .try_recv()
- .expect("expected bot trigger");
- assert_eq!(trigger.channel_id, channel_id);
- assert_eq!(trigger.message.id, message_id);
- assert_eq!(trigger.bot_ids, vec![bot_id::MACRO_AI_BOT_ID]);
- assert!(bot_trigger_receiver.try_recv().is_err());
- }
-
- #[tokio::test]
- async fn document_mentions_notify_participants_except_sender() {
- let channel_id = Uuid::new_v4();
- let message_id = Uuid::new_v4();
- let sender = user("[email protected]");
- let mentioned = user("[email protected]");
- let other = user("[email protected]");
- let notifications = FakeNotifications::default();
- let service = ChannelSideEffectService::new(
- FakeContext {
- document_mentions: vec![ChannelDocumentMention {
- document_name: "Spec".to_string(),
- owner: sender.clone(),
- file_type: None,
- sub_type: None,
- }],
- ..FakeContext::default()
- },
- FakeRealtime::default(),
- notifications.clone(),
- FakeSearch::default(),
- FakeContacts::default(),
- );
- let now = Utc::now();
-
- service
- .handle(ChannelEvent::MessagePosted {
- channel_id,
- metadata: ChannelMetadata {
- channel_type: ChannelType::Private,
- channel_name: "Project".to_string(),
- },
- participants: vec![
- ChannelParticipant {
- channel_id,
- user_id: sender.as_ref().to_string(),
- role: ParticipantRole::Member,
- joined_at: now,
- left_at: None,
- },
- ChannelParticipant {
- channel_id,
- user_id: mentioned.as_ref().to_string(),
- role: ParticipantRole::Member,
- joined_at: now,
- left_at: None,
- },
- ChannelParticipant {
- channel_id,
- user_id: other.as_ref().to_string(),
- role: ParticipantRole::Member,
- joined_at: now,
- left_at: None,
- },
- ],
- message: MutatedMessage {
- id: message_id,
- channel_id,
- thread_id: None,
- sender_id: Sender::User(sender.clone()),
- content: "hello".to_string(),
- created_at: now,
- updated_at: now,
- edited_at: None,
- deleted_at: None,
- },
- mentions: vec![
- SimpleMention {
- entity_type: "user".to_string(),
- entity_id: mentioned.as_ref().to_string(),
- },
- SimpleMention {
- entity_type: "document".to_string(),
- entity_id: "doc-1".to_string(),
- },
- ],
- has_attachments: false,
- attachments: Vec::new(),
- nonce: None,
- })
- .await;
-
- let notification_effects = notifications.effects.lock().unwrap();
- let document_recipients = notification_effects
- .iter()
- .find_map(|effect| match effect {
- ChannelNotificationEffect::DocumentMention { recipient_ids, .. } => {
- Some(recipient_ids)
- }
- _ => None,
- })
- .expect("expected document mention notification");
- assert!(document_recipients.contains(&mentioned));
- assert!(document_recipients.contains(&other));
- assert!(!document_recipients.contains(&sender));
- }
-
- #[test]
- fn contact_sync_is_derived_from_private_channel_created() {
- let event = ChannelEvent::ChannelCreated {
- channel_id: Uuid::nil(),
- actor: Sender::User(user("[email protected]")),
- channel_type: ChannelType::Private,
- participant_user_ids: users(&["[email protected]", "[email protected]"]),
- };
-
- let contact_users = contact_sync_users_for_event(&event).unwrap();
-
- assert_eq!(contact_users.len(), 2);
- assert!(contact_users.contains(&user("[email protected]")));
- assert!(contact_users.contains(&user("[email protected]")));
- }
-
- #[test]
- fn contact_sync_ignores_public_channel_created() {
- let event = ChannelEvent::ChannelCreated {
- channel_id: Uuid::nil(),
- actor: Sender::User(user("[email protected]")),
- channel_type: ChannelType::Public,
- participant_user_ids: users(&["[email protected]", "[email protected]"]),
- };
-
- assert!(contact_sync_users_for_event(&event).is_none());
- }
-
- #[test]
- fn contact_sync_ignores_bot_actor() {
- let event = ChannelEvent::ParticipantsAdded {
- channel_id: Uuid::nil(),
- channel_type: ChannelType::Team,
- active_participant_user_ids: users(&["[email protected]", "[email protected]"]),
- invited_by: Sender::Bot(BotId::from_uuid(Uuid::new_v4())),
- recipient_user_ids: users(&["[email protected]"]),
- metadata: ChannelMetadata {
- channel_type: ChannelType::Team,
- channel_name: "team".to_string(),
- },
- message_content: None,
- };
-
- assert!(contact_sync_users_for_event(&event).is_none());
- }
-
- #[test]
- fn contact_sync_is_derived_from_team_participants_added() {
- let event = ChannelEvent::ParticipantsAdded {
- channel_id: Uuid::nil(),
- channel_type: ChannelType::Team,
- active_participant_user_ids: users(&["[email protected]", "[email protected]"]),
- invited_by: Sender::User(user("[email protected]")),
- recipient_user_ids: users(&["[email protected]"]),
- metadata: ChannelMetadata {
- channel_type: ChannelType::Team,
- channel_name: "team".to_string(),
- },
- message_content: None,
- };
-
- assert_eq!(contact_sync_users_for_event(&event).unwrap().len(), 2);
- }
-
- #[test]
- fn contact_sync_ignores_single_user_join() {
- let event = ChannelEvent::ParticipantJoined {
- channel_id: Uuid::nil(),
- channel_type: ChannelType::Public,
- user_id: Sender::User(user("[email protected]")),
- active_participant_user_ids: users(&["[email protected]"]),
- };
-
- assert!(contact_sync_users_for_event(&event).is_none());
- }
-
- fn mention(entity_type: &str, entity_id: &str) -> SimpleMention {
- SimpleMention {
- entity_type: entity_type.to_string(),
- entity_id: entity_id.to_string(),
- }
- }
-
- #[test]
- fn bot_mentions_recognize_bot_and_macro_ai_user_tags() {
- let macro_ai = bot_id::MACRO_AI_BOT_ID.as_uuid().to_string();
- let other_bot = Uuid::new_v4().to_string();
- let mentions = vec![
- // Macro AI surfaced through the user-mention UI.
- mention("user", &macro_ai),
- // Duplicate bot mentions are dispatched once.
- mention("user", &macro_ai),
- // A real user mention is ignored.
- mention("user", "macro|[email protected]"),
- // An explicitly bot-tagged mention.
- mention(BOT_MENTION_ENTITY_TYPE, &other_bot),
- mention(BOT_MENTION_ENTITY_TYPE, &other_bot),
- ];
-
- let bots = bot_mention_ids(&mentions);
- assert_eq!(
- bots,
- vec![
- bot_id::MACRO_AI_BOT_ID,
- BotId::parse_uuid_str(&other_bot).unwrap()
- ]
- );
- }
-
- #[test]
- fn macro_ai_user_mention_is_not_a_user_recipient() {
- assert!(is_bot_user_mention(&mention(
- "user",
- &bot_id::MACRO_AI_BOT_ID.as_uuid().to_string()
- )));
- assert!(!is_bot_user_mention(&mention(
- "user",
- )));
- assert!(is_bot_principal(
- &bot_id::MACRO_AI_BOT_ID.to_storage_string()
- ));
- assert!(!is_bot_principal("macro|[email protected]"));
- }
-}
+mod test;
diff --git a/rust/cloud-storage/channels/src/domain/side_effects/test.rs b/rust/cloud-storage/channels/src/domain/side_effects/test.rs
new file mode 100644
index 0000000000..416511352c
--- /dev/null
+++ b/rust/cloud-storage/channels/src/domain/side_effects/test.rs
@@ -0,0 +1,1010 @@
+use super::*;
+use crate::domain::{
+ events::MessageChangedNotificationContext,
+ models::{BotId, ParticipantRole, Sender},
+ ports::{
+ ChannelEventHandler, ChannelNotificationSender, ChannelRealtimePublisher,
+ ChannelSearchIndexer, ChannelSideEffectContext,
+ },
+};
+use chrono::Utc;
+use std::sync::{Arc, Mutex};
+
+type IndexedMessages = Arc<Mutex<Vec<(Uuid, Uuid)>>>;
+type RemovedMessages = Arc<Mutex<Vec<(Uuid, Option<Uuid>)>>>;
+
+#[derive(Clone)]
+struct FakeContext {
+ message_count: i64,
+ document_mentions: Vec<ChannelDocumentMention>,
+ bot_profile: Option<BotSenderProfile>,
+ bot_profile_lookup_count: Arc<Mutex<usize>>,
+ thread_context: ThreadNotificationContext,
+}
+
+impl Default for FakeContext {
+ fn default() -> Self {
+ Self {
+ message_count: 2,
+ document_mentions: Vec::new(),
+ bot_profile: Some(BotSenderProfile {
+ name: "Test Bot".to_string(),
+ avatar_url: Some("https://example.com/bot.png".to_string()),
+ }),
+ bot_profile_lookup_count: Arc::new(Mutex::new(0)),
+ thread_context: ThreadNotificationContext::default(),
+ }
+ }
+}
+
+impl ChannelSideEffectContext for FakeContext {
+ type Err = anyhow::Error;
+
+ async fn get_channel_message_count(&self, _channel_id: Uuid) -> Result<i64, Self::Err> {
+ Ok(self.message_count)
+ }
+
+ async fn get_existing_user_ids(
+ &self,
+ user_ids: Vec<MacroUserIdStr<'static>>,
+ ) -> Result<HashSet<String>, Self::Err> {
+ Ok(user_ids
+ .into_iter()
+ .map(|user_id| user_id.as_ref().to_string())
+ .collect())
+ }
+
+ async fn get_document_mentions(
+ &self,
+ _document_ids: Vec<String>,
+ ) -> Result<Vec<ChannelDocumentMention>, Self::Err> {
+ Ok(self.document_mentions.clone())
+ }
+
+ async fn get_thread_notification_context(
+ &self,
+ _thread_id: Uuid,
+ ) -> Result<ThreadNotificationContext, Self::Err> {
+ Ok(self.thread_context.clone())
+ }
+
+ async fn get_sender_profile_picture_url(
+ &self,
+ _sender_id: MacroUserIdStr<'static>,
+ ) -> Option<String> {
+ Some("https://example.com/avatar.png".to_string())
+ }
+
+ async fn get_bot_sender_profile(&self, _bot_id: BotId) -> Option<BotSenderProfile> {
+ *self.bot_profile_lookup_count.lock().unwrap() += 1;
+ self.bot_profile.clone()
+ }
+}
+
+#[derive(Clone, Default)]
+struct FakeRealtime {
+ effects: Arc<Mutex<Vec<ChannelRealtimeEffect>>>,
+}
+
+impl ChannelRealtimePublisher for FakeRealtime {
+ type Err = anyhow::Error;
+
+ async fn publish(&self, effect: ChannelRealtimeEffect) -> Result<(), Self::Err> {
+ self.effects.lock().unwrap().push(effect);
+ Ok(())
+ }
+}
+
+#[derive(Clone, Default)]
+struct FakeNotifications {
+ effects: Arc<Mutex<Vec<ChannelNotificationEffect>>>,
+}
+
+impl ChannelNotificationSender for FakeNotifications {
+ type Err = anyhow::Error;
+
+ async fn send(&self, notification: ChannelNotificationEffect) -> Result<(), Self::Err> {
+ self.effects.lock().unwrap().push(notification);
+ Ok(())
+ }
+}
+
+#[derive(Clone, Default)]
+struct FakeSearch {
+ indexed: IndexedMessages,
+ removed: RemovedMessages,
+}
+
+impl ChannelSearchIndexer for FakeSearch {
+ async fn index_message(&self, channel_id: Uuid, message_id: Uuid) {
+ self.indexed.lock().unwrap().push((channel_id, message_id));
+ }
+
+ async fn remove_message(&self, channel_id: Uuid, message_id: Option<Uuid>) {
+ self.removed.lock().unwrap().push((channel_id, message_id));
+ }
+}
+
+#[derive(Clone, Default)]
+struct FakeContacts {
+ users: Arc<Mutex<Vec<HashSet<MacroUserIdStr<'static>>>>>,
+}
+
+impl ChannelContactsDispatcher for FakeContacts {
+ type Err = anyhow::Error;
+
+ async fn enqueue_contacts(
+ &self,
+ users: HashSet<MacroUserIdStr<'static>>,
+ ) -> Result<(), Self::Err> {
+ self.users.lock().unwrap().push(users);
+ Ok(())
+ }
+}
+
+fn user(email: &str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email(email).unwrap()
+}
+
+fn users(emails: &[&str]) -> Vec<MacroUserIdStr<'static>> {
+ emails.iter().map(|email| user(email)).collect()
+}
+
+#[tokio::test]
+async fn macro_ai_bot_profile_is_builtin_without_context_lookup() {
+ let lookup_count = Arc::new(Mutex::new(0));
+ let service = ChannelSideEffectService::new(
+ FakeContext {
+ bot_profile: None,
+ bot_profile_lookup_count: lookup_count.clone(),
+ ..FakeContext::default()
+ },
+ FakeRealtime::default(),
+ FakeNotifications::default(),
+ FakeSearch::default(),
+ FakeContacts::default(),
+ );
+ let now = Utc::now();
+ let message = MutatedMessage {
+ id: Uuid::new_v4(),
+ channel_id: Uuid::new_v4(),
+ thread_id: None,
+ sender_id: Sender::Bot(bot_id::MACRO_AI_BOT_ID),
+ content: "hello".to_string(),
+ created_at: now,
+ updated_at: now,
+ edited_at: None,
+ deleted_at: None,
+ };
+
+ let profile = service
+ .bot_profile_for_message(&message)
+ .await
+ .expect("Macro AI should have a built-in profile");
+
+ assert_eq!(profile.name, bot_id::MACRO_AI_NAME);
+ assert_eq!(profile.avatar_url, None);
+ assert_eq!(*lookup_count.lock().unwrap(), 0);
+}
+
+#[tokio::test]
+async fn non_macro_bot_profile_uses_context_lookup() {
+ let lookup_count = Arc::new(Mutex::new(0));
+ let service = ChannelSideEffectService::new(
+ FakeContext {
+ bot_profile_lookup_count: lookup_count.clone(),
+ ..FakeContext::default()
+ },
+ FakeRealtime::default(),
+ FakeNotifications::default(),
+ FakeSearch::default(),
+ FakeContacts::default(),
+ );
+ let now = Utc::now();
+ let message = MutatedMessage {
+ id: Uuid::new_v4(),
+ channel_id: Uuid::new_v4(),
+ thread_id: None,
+ sender_id: Sender::Bot(BotId::from_uuid(Uuid::new_v4())),
+ content: "hello".to_string(),
+ created_at: now,
+ updated_at: now,
+ edited_at: None,
+ deleted_at: None,
+ };
+
+ let profile = service
+ .bot_profile_for_message(&message)
+ .await
+ .expect("non-Macro bot profile should come from context");
+
+ assert_eq!(profile.name, "Test Bot");
+ assert_eq!(*lookup_count.lock().unwrap(), 1);
+}
+
+#[tokio::test]
+async fn message_posted_derives_realtime_search_and_notification_effects() {
+ let channel_id = Uuid::new_v4();
+ let message_id = Uuid::new_v4();
+ let sender = user("[email protected]");
+ let recipient = user("[email protected]");
+ let realtime = FakeRealtime::default();
+ let notifications = FakeNotifications::default();
+ let search = FakeSearch::default();
+ let contacts = FakeContacts::default();
+ let service = ChannelSideEffectService::new(
+ FakeContext::default(),
+ realtime.clone(),
+ notifications.clone(),
+ search.clone(),
+ contacts,
+ );
+ let now = Utc::now();
+
+ service
+ .handle(ChannelEvent::MessagePosted {
+ channel_id,
+ metadata: ChannelMetadata {
+ channel_type: ChannelType::Private,
+ channel_name: "Project".to_string(),
+ },
+ participants: vec![
+ ChannelParticipant {
+ channel_id,
+ user_id: sender.as_ref().to_string(),
+ role: ParticipantRole::Member,
+ joined_at: now,
+ left_at: None,
+ },
+ ChannelParticipant {
+ channel_id,
+ user_id: recipient.as_ref().to_string(),
+ role: ParticipantRole::Member,
+ joined_at: now,
+ left_at: None,
+ },
+ ],
+ message: MutatedMessage {
+ id: message_id,
+ channel_id,
+ thread_id: None,
+ sender_id: Sender::User(sender.clone()),
+ content: "hello".to_string(),
+ created_at: now,
+ updated_at: now,
+ edited_at: None,
+ deleted_at: None,
+ },
+ mentions: Vec::new(),
+ has_attachments: false,
+ attachments: Vec::new(),
+ nonce: Some("nonce-1".to_string()),
+ notification_policy: PostMessageNotificationPolicy::Default,
+ })
+ .await;
+
+ let realtime_effects = realtime.effects.lock().unwrap();
+ assert_eq!(realtime_effects.len(), 1);
+ let ChannelRealtimeEffect::Message {
+ recipients,
+ message,
+ nonce,
+ ..
+ } = &realtime_effects[0]
+ else {
+ panic!("expected message realtime effect");
+ };
+ assert_eq!(message.id, message_id);
+ assert_eq!(nonce.as_deref(), Some("nonce-1"));
+ assert_eq!(recipients.len(), 2);
+ drop(realtime_effects);
+
+ assert_eq!(
+ *search.indexed.lock().unwrap(),
+ vec![(channel_id, message_id)]
+ );
+
+ let notification_effects = notifications.effects.lock().unwrap();
+ assert_eq!(notification_effects.len(), 1);
+ let ChannelNotificationEffect::ChannelMessage {
+ message_id: notified_message_id,
+ sender: notified_sender,
+ recipient_ids,
+ metadata,
+ ..
+ } = &notification_effects[0]
+ else {
+ panic!("expected channel message notification effect");
+ };
+ assert_eq!(*notified_message_id, message_id);
+ assert_eq!(*notified_sender, NotificationSender::User(sender.clone()));
+ assert_eq!(metadata.channel_name, "Project");
+ assert_eq!(recipient_ids.len(), 1);
+ assert!(recipient_ids.contains(&recipient));
+}
+
+/// Build a MessagePosted event for a bot-sent message.
+fn bot_message_posted_event(
+ channel_id: Uuid,
+ message_id: Uuid,
+ thread_id: Option<Uuid>,
+ participant_principals: &[&str],
+) -> ChannelEvent {
+ let now = Utc::now();
+ ChannelEvent::MessagePosted {
+ channel_id,
+ metadata: ChannelMetadata {
+ channel_type: ChannelType::Private,
+ channel_name: "Project".to_string(),
+ },
+ participants: participant_principals
+ .iter()
+ .map(|principal| ChannelParticipant {
+ channel_id,
+ user_id: principal.to_string(),
+ role: ParticipantRole::Member,
+ joined_at: now,
+ left_at: None,
+ })
+ .collect(),
+ message: MutatedMessage {
+ id: message_id,
+ channel_id,
+ thread_id,
+ sender_id: Sender::Bot(BotId::from_uuid(Uuid::new_v4())),
+ content: "hello".to_string(),
+ created_at: now,
+ updated_at: now,
+ edited_at: None,
+ deleted_at: None,
+ },
+ mentions: Vec::new(),
+ has_attachments: false,
+ attachments: Vec::new(),
+ nonce: None,
+ notification_policy: PostMessageNotificationPolicy::Default,
+ }
+}
+
+#[tokio::test]
+async fn silent_message_posted_skips_notifications_only() {
+ let channel_id = Uuid::new_v4();
+ let message_id = Uuid::new_v4();
+ let sender = user("[email protected]");
+ let recipient = user("[email protected]");
+ let realtime = FakeRealtime::default();
+ let notifications = FakeNotifications::default();
+ let search = FakeSearch::default();
+ let service = ChannelSideEffectService::new(
+ FakeContext::default(),
+ realtime.clone(),
+ notifications.clone(),
+ search.clone(),
+ FakeContacts::default(),
+ );
+ let now = Utc::now();
+
+ service
+ .handle(ChannelEvent::MessagePosted {
+ channel_id,
+ metadata: ChannelMetadata {
+ channel_type: ChannelType::Private,
+ channel_name: "Project".to_string(),
+ },
+ participants: vec![
+ ChannelParticipant {
+ channel_id,
+ user_id: sender.as_ref().to_string(),
+ role: ParticipantRole::Member,
+ joined_at: now,
+ left_at: None,
+ },
+ ChannelParticipant {
+ channel_id,
+ user_id: recipient.as_ref().to_string(),
+ role: ParticipantRole::Member,
+ joined_at: now,
+ left_at: None,
+ },
+ ],
+ message: MutatedMessage {
+ id: message_id,
+ channel_id,
+ thread_id: None,
+ sender_id: Sender::User(sender),
+ content: "transient".to_string(),
+ created_at: now,
+ updated_at: now,
+ edited_at: None,
+ deleted_at: None,
+ },
+ mentions: Vec::new(),
+ has_attachments: false,
+ attachments: Vec::new(),
+ nonce: None,
+ notification_policy: PostMessageNotificationPolicy::Silent,
+ })
+ .await;
+
+ assert_eq!(realtime.effects.lock().unwrap().len(), 1);
+ assert_eq!(
+ *search.indexed.lock().unwrap(),
+ vec![(channel_id, message_id)]
+ );
+ assert!(notifications.effects.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn message_changed_with_posted_notification_context_sends_notification() {
+ let channel_id = Uuid::new_v4();
+ let thread_id = Uuid::new_v4();
+ let message_id = Uuid::new_v4();
+ let recipient = user("[email protected]");
+ let parent_sender = user("[email protected]");
+ let notifications = FakeNotifications::default();
+ let service = ChannelSideEffectService::new(
+ FakeContext {
+ thread_context: ThreadNotificationContext {
+ participants: vec![recipient.clone(), parent_sender.clone()],
+ parent_sender_id: Some(parent_sender.clone()),
+ },
+ ..FakeContext::default()
+ },
+ FakeRealtime::default(),
+ notifications.clone(),
+ FakeSearch::default(),
+ FakeContacts::default(),
+ );
+ let now = Utc::now();
+
+ service
+ .handle(ChannelEvent::MessageChanged {
+ channel_id,
+ actor: Sender::Bot(bot_id::MACRO_AI_BOT_ID),
+ message: MutatedMessage {
+ id: message_id,
+ channel_id,
+ thread_id: Some(thread_id),
+ sender_id: Sender::Bot(bot_id::MACRO_AI_BOT_ID),
+ content: "final answer".to_string(),
+ created_at: now,
+ updated_at: now,
+ edited_at: Some(now),
+ deleted_at: None,
+ },
+ recipients: vec![recipient.clone(), parent_sender.clone()],
+ nonce: None,
+ posted_notification: Some(MessageChangedNotificationContext {
+ metadata: ChannelMetadata {
+ channel_type: ChannelType::Private,
+ channel_name: "Project".to_string(),
+ },
+ participants: Vec::new(),
+ mentions: Vec::new(),
+ has_attachments: false,
+ }),
+ })
+ .await;
+
+ let notification_effects = notifications.effects.lock().unwrap();
+ assert_eq!(notification_effects.len(), 1);
+ let ChannelNotificationEffect::Reply {
+ message_id: notified_message_id,
+ sender,
+ recipient_ids,
+ ..
+ } = &notification_effects[0]
+ else {
+ panic!("expected reply notification effect");
+ };
+ assert_eq!(*notified_message_id, message_id);
+ assert_eq!(
+ *sender,
+ NotificationSender::Bot {
+ name: bot_id::MACRO_AI_NAME.to_string()
+ }
+ );
+ assert!(recipient_ids.contains(&recipient));
+ assert!(recipient_ids.contains(&parent_sender));
+}
+
+#[tokio::test]
+async fn bot_message_posted_sends_channel_message_notification() {
+ let channel_id = Uuid::new_v4();
+ let message_id = Uuid::new_v4();
+ let recipient = user("[email protected]");
+ let realtime = FakeRealtime::default();
+ let notifications = FakeNotifications::default();
+ let search = FakeSearch::default();
+ let service = ChannelSideEffectService::new(
+ FakeContext::default(),
+ realtime.clone(),
+ notifications.clone(),
+ search.clone(),
+ FakeContacts::default(),
+ );
+
+ service
+ .handle(bot_message_posted_event(
+ channel_id,
+ message_id,
+ None,
+ &[recipient.as_ref()],
+ ))
+ .await;
+
+ assert_eq!(realtime.effects.lock().unwrap().len(), 1);
+ assert_eq!(
+ *search.indexed.lock().unwrap(),
+ vec![(channel_id, message_id)]
+ );
+
+ let notification_effects = notifications.effects.lock().unwrap();
+ assert_eq!(notification_effects.len(), 1);
+ let ChannelNotificationEffect::ChannelMessage {
+ sender,
+ sender_profile_picture_url,
+ recipient_ids,
+ ..
+ } = &notification_effects[0]
+ else {
+ panic!("expected channel message notification effect");
+ };
+ assert_eq!(
+ *sender,
+ NotificationSender::Bot {
+ name: "Test Bot".to_string()
+ }
+ );
+ assert_eq!(
+ sender_profile_picture_url.as_deref(),
+ Some("https://example.com/bot.png")
+ );
+ assert_eq!(recipient_ids.len(), 1);
+ assert!(recipient_ids.contains(&recipient));
+}
+
+#[tokio::test]
+async fn bot_message_without_profile_skips_notifications() {
+ let channel_id = Uuid::new_v4();
+ let message_id = Uuid::new_v4();
+ let recipient = user("[email protected]");
+ let realtime = FakeRealtime::default();
+ let notifications = FakeNotifications::default();
+ let search = FakeSearch::default();
+ let service = ChannelSideEffectService::new(
+ FakeContext {
+ bot_profile: None,
+ ..FakeContext::default()
+ },
+ realtime.clone(),
+ notifications.clone(),
+ search.clone(),
+ FakeContacts::default(),
+ );
+
+ service
+ .handle(bot_message_posted_event(
+ channel_id,
+ message_id,
+ None,
+ &[recipient.as_ref()],
+ ))
+ .await;
+
+ assert_eq!(realtime.effects.lock().unwrap().len(), 1);
+ assert_eq!(
+ *search.indexed.lock().unwrap(),
+ vec![(channel_id, message_id)]
+ );
+ assert!(notifications.effects.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn bot_first_message_sends_channel_message_not_invite() {
+ let channel_id = Uuid::new_v4();
+ let recipient = user("[email protected]");
+ let notifications = FakeNotifications::default();
+ let service = ChannelSideEffectService::new(
+ FakeContext {
+ message_count: 1,
+ ..FakeContext::default()
+ },
+ FakeRealtime::default(),
+ notifications.clone(),
+ FakeSearch::default(),
+ FakeContacts::default(),
+ );
+
+ service
+ .handle(bot_message_posted_event(
+ channel_id,
+ Uuid::new_v4(),
+ None,
+ &[recipient.as_ref()],
+ ))
+ .await;
+
+ let notification_effects = notifications.effects.lock().unwrap();
+ assert_eq!(notification_effects.len(), 1);
+ assert!(matches!(
+ &notification_effects[0],
+ ChannelNotificationEffect::ChannelMessage { .. }
+ ));
+}
+
+#[tokio::test]
+async fn bot_thread_reply_sends_reply_notification() {
+ let channel_id = Uuid::new_v4();
+ let recipient = user("[email protected]");
+ let parent_sender = user("[email protected]");
+ let notifications = FakeNotifications::default();
+ let service = ChannelSideEffectService::new(
+ FakeContext {
+ thread_context: ThreadNotificationContext {
+ participants: vec![recipient.clone(), parent_sender.clone()],
+ parent_sender_id: Some(parent_sender.clone()),
+ },
+ ..FakeContext::default()
+ },
+ FakeRealtime::default(),
+ notifications.clone(),
+ FakeSearch::default(),
+ FakeContacts::default(),
+ );
+
+ service
+ .handle(bot_message_posted_event(
+ channel_id,
+ Uuid::new_v4(),
+ Some(Uuid::new_v4()),
+ &[recipient.as_ref(), parent_sender.as_ref()],
+ ))
+ .await;
+
+ let notification_effects = notifications.effects.lock().unwrap();
+ assert_eq!(notification_effects.len(), 1);
+ let ChannelNotificationEffect::Reply {
+ sender,
+ thread_parent_sender_id,
+ recipient_ids,
+ ..
+ } = &notification_effects[0]
+ else {
+ panic!("expected reply notification effect");
+ };
+ assert_eq!(
+ *sender,
+ NotificationSender::Bot {
+ name: "Test Bot".to_string()
+ }
+ );
+ assert_eq!(*thread_parent_sender_id, Some(parent_sender.clone()));
+ assert!(recipient_ids.contains(&recipient));
+ assert!(recipient_ids.contains(&parent_sender));
+}
+
+#[tokio::test]
+async fn bot_participant_is_never_a_notification_recipient() {
+ let channel_id = Uuid::new_v4();
+ let recipient = user("[email protected]");
+ let bot_principal = BotId::from_uuid(Uuid::new_v4()).to_storage_string();
+ let notifications = FakeNotifications::default();
+ let service = ChannelSideEffectService::new(
+ FakeContext::default(),
+ FakeRealtime::default(),
+ notifications.clone(),
+ FakeSearch::default(),
+ FakeContacts::default(),
+ );
+
+ service
+ .handle(bot_message_posted_event(
+ channel_id,
+ Uuid::new_v4(),
+ None,
+ &[recipient.as_ref(), bot_principal.as_str()],
+ ))
+ .await;
+
+ let notification_effects = notifications.effects.lock().unwrap();
+ assert_eq!(notification_effects.len(), 1);
+ let ChannelNotificationEffect::ChannelMessage { recipient_ids, .. } = &notification_effects[0]
+ else {
+ panic!("expected channel message notification effect");
+ };
+ assert_eq!(recipient_ids.len(), 1);
+ assert!(recipient_ids.contains(&recipient));
+}
+
+#[tokio::test]
+async fn user_message_with_bot_mention_enqueues_bot_trigger() {
+ let channel_id = Uuid::new_v4();
+ let message_id = Uuid::new_v4();
+ let sender = user("[email protected]");
+ let recipient = user("[email protected]");
+ let (bot_trigger_sender, mut bot_trigger_receiver) = tokio::sync::mpsc::unbounded_channel();
+ let service = ChannelSideEffectService::new(
+ FakeContext::default(),
+ FakeRealtime::default(),
+ FakeNotifications::default(),
+ FakeSearch::default(),
+ FakeContacts::default(),
+ )
+ .with_bot_trigger_sender(bot_trigger_sender);
+ let now = Utc::now();
+
+ service
+ .handle(ChannelEvent::MessagePosted {
+ channel_id,
+ metadata: ChannelMetadata {
+ channel_type: ChannelType::Private,
+ channel_name: "Project".to_string(),
+ },
+ participants: vec![
+ ChannelParticipant {
+ channel_id,
+ user_id: sender.as_ref().to_string(),
+ role: ParticipantRole::Member,
+ joined_at: now,
+ left_at: None,
+ },
+ ChannelParticipant {
+ channel_id,
+ user_id: recipient.as_ref().to_string(),
+ role: ParticipantRole::Member,
+ joined_at: now,
+ left_at: None,
+ },
+ ],
+ message: MutatedMessage {
+ id: message_id,
+ channel_id,
+ thread_id: None,
+ sender_id: Sender::User(sender),
+ content: "@macro help".to_string(),
+ created_at: now,
+ updated_at: now,
+ edited_at: None,
+ deleted_at: None,
+ },
+ mentions: vec![SimpleMention {
+ entity_type: "user".to_string(),
+ entity_id: bot_id::MACRO_AI_BOT_ID.to_string(),
+ }],
+ has_attachments: false,
+ attachments: Vec::new(),
+ nonce: None,
+ notification_policy: PostMessageNotificationPolicy::Default,
+ })
+ .await;
+
+ let trigger = bot_trigger_receiver
+ .try_recv()
+ .expect("expected bot trigger");
+ assert_eq!(trigger.channel_id, channel_id);
+ assert_eq!(trigger.message.id, message_id);
+ assert_eq!(trigger.bot_ids, vec![bot_id::MACRO_AI_BOT_ID]);
+ assert!(bot_trigger_receiver.try_recv().is_err());
+}
+
+#[tokio::test]
+async fn document_mentions_notify_participants_except_sender() {
+ let channel_id = Uuid::new_v4();
+ let message_id = Uuid::new_v4();
+ let sender = user("[email protected]");
+ let mentioned = user("[email protected]");
+ let other = user("[email protected]");
+ let notifications = FakeNotifications::default();
+ let service = ChannelSideEffectService::new(
+ FakeContext {
+ document_mentions: vec![ChannelDocumentMention {
+ document_name: "Spec".to_string(),
+ owner: sender.clone(),
+ file_type: None,
+ sub_type: None,
+ }],
+ ..FakeContext::default()
+ },
+ FakeRealtime::default(),
+ notifications.clone(),
+ FakeSearch::default(),
+ FakeContacts::default(),
+ );
+ let now = Utc::now();
+
+ service
+ .handle(ChannelEvent::MessagePosted {
+ channel_id,
+ metadata: ChannelMetadata {
+ channel_type: ChannelType::Private,
+ channel_name: "Project".to_string(),
+ },
+ participants: vec![
+ ChannelParticipant {
+ channel_id,
+ user_id: sender.as_ref().to_string(),
+ role: ParticipantRole::Member,
+ joined_at: now,
+ left_at: None,
+ },
+ ChannelParticipant {
+ channel_id,
+ user_id: mentioned.as_ref().to_string(),
+ role: ParticipantRole::Member,
+ joined_at: now,
+ left_at: None,
+ },
+ ChannelParticipant {
+ channel_id,
+ user_id: other.as_ref().to_string(),
+ role: ParticipantRole::Member,
+ joined_at: now,
+ left_at: None,
+ },
+ ],
+ message: MutatedMessage {
+ id: message_id,
+ channel_id,
+ thread_id: None,
+ sender_id: Sender::User(sender.clone()),
+ content: "hello".to_string(),
+ created_at: now,
+ updated_at: now,
+ edited_at: None,
+ deleted_at: None,
+ },
+ mentions: vec![
+ SimpleMention {
+ entity_type: "user".to_string(),
+ entity_id: mentioned.as_ref().to_string(),
+ },
+ SimpleMention {
+ entity_type: "document".to_string(),
+ entity_id: "doc-1".to_string(),
+ },
+ ],
+ has_attachments: false,
+ attachments: Vec::new(),
+ nonce: None,
+ notification_policy: PostMessageNotificationPolicy::Default,
+ })
+ .await;
+
+ let notification_effects = notifications.effects.lock().unwrap();
+ let document_recipients = notification_effects
+ .iter()
+ .find_map(|effect| match effect {
+ ChannelNotificationEffect::DocumentMention { recipient_ids, .. } => Some(recipient_ids),
+ _ => None,
+ })
+ .expect("expected document mention notification");
+ assert!(document_recipients.contains(&mentioned));
+ assert!(document_recipients.contains(&other));
+ assert!(!document_recipients.contains(&sender));
+}
+
+#[test]
+fn contact_sync_is_derived_from_private_channel_created() {
+ let event = ChannelEvent::ChannelCreated {
+ channel_id: Uuid::nil(),
+ actor: Sender::User(user("[email protected]")),
+ channel_type: ChannelType::Private,
+ participant_user_ids: users(&["[email protected]", "[email protected]"]),
+ };
+
+ let contact_users = contact_sync_users_for_event(&event).unwrap();
+
+ assert_eq!(contact_users.len(), 2);
+ assert!(contact_users.contains(&user("[email protected]")));
+ assert!(contact_users.contains(&user("[email protected]")));
+}
+
+#[test]
+fn contact_sync_ignores_public_channel_created() {
+ let event = ChannelEvent::ChannelCreated {
+ channel_id: Uuid::nil(),
+ actor: Sender::User(user("[email protected]")),
+ channel_type: ChannelType::Public,
+ participant_user_ids: users(&["[email protected]", "[email protected]"]),
+ };
+
+ assert!(contact_sync_users_for_event(&event).is_none());
+}
+
+#[test]
+fn contact_sync_ignores_bot_actor() {
+ let event = ChannelEvent::ParticipantsAdded {
+ channel_id: Uuid::nil(),
+ channel_type: ChannelType::Team,
+ active_participant_user_ids: users(&["[email protected]", "[email protected]"]),
+ invited_by: Sender::Bot(BotId::from_uuid(Uuid::new_v4())),
+ recipient_user_ids: users(&["[email protected]"]),
+ metadata: ChannelMetadata {
+ channel_type: ChannelType::Team,
+ channel_name: "team".to_string(),
+ },
+ message_content: None,
+ };
+
+ assert!(contact_sync_users_for_event(&event).is_none());
+}
+
+#[test]
+fn contact_sync_is_derived_from_team_participants_added() {
+ let event = ChannelEvent::ParticipantsAdded {
+ channel_id: Uuid::nil(),
+ channel_type: ChannelType::Team,
+ active_participant_user_ids: users(&["[email protected]", "[email protected]"]),
+ invited_by: Sender::User(user("[email protected]")),
+ recipient_user_ids: users(&["[email protected]"]),
+ metadata: ChannelMetadata {
+ channel_type: ChannelType::Team,
+ channel_name: "team".to_string(),
+ },
+ message_content: None,
+ };
+
+ assert_eq!(contact_sync_users_for_event(&event).unwrap().len(), 2);
+}
+
+#[test]
+fn contact_sync_ignores_single_user_join() {
+ let event = ChannelEvent::ParticipantJoined {
+ channel_id: Uuid::nil(),
+ channel_type: ChannelType::Public,
+ user_id: Sender::User(user("[email protected]")),
+ active_participant_user_ids: users(&["[email protected]"]),
+ };
+
+ assert!(contact_sync_users_for_event(&event).is_none());
+}
+
+fn mention(entity_type: &str, entity_id: &str) -> SimpleMention {
+ SimpleMention {
+ entity_type: entity_type.to_string(),
+ entity_id: entity_id.to_string(),
+ }
+}
+
+#[test]
+fn bot_mentions_recognize_bot_and_macro_ai_user_tags() {
+ let macro_ai = bot_id::MACRO_AI_BOT_ID.as_uuid().to_string();
+ let other_bot = Uuid::new_v4().to_string();
+ let mentions = vec![
+ // Macro AI surfaced through the user-mention UI.
+ mention("user", &macro_ai),
+ // Duplicate bot mentions are dispatched once.
+ mention("user", &macro_ai),
+ // A real user mention is ignored.
+ mention("user", "macro|[email protected]"),
+ // An explicitly bot-tagged mention.
+ mention(BOT_MENTION_ENTITY_TYPE, &other_bot),
+ mention(BOT_MENTION_ENTITY_TYPE, &other_bot),
+ ];
+
+ let bots = bot_mention_ids(&mentions);
+ assert_eq!(
+ bots,
+ vec![
+ bot_id::MACRO_AI_BOT_ID,
+ BotId::parse_uuid_str(&other_bot).unwrap()
+ ]
+ );
+}
+
+#[test]
+fn macro_ai_user_mention_is_not_a_user_recipient() {
+ assert!(is_bot_user_mention(&mention(
+ "user",
+ &bot_id::MACRO_AI_BOT_ID.as_uuid().to_string()
+ )));
+ assert!(!is_bot_user_mention(&mention(
+ "user",
+ )));
+ assert!(is_bot_principal(
+ &bot_id::MACRO_AI_BOT_ID.to_storage_string()
+ ));
+ assert!(!is_bot_principal("macro|[email protected]"));
+}