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.

56.9 KB
Raw Blame
use super::*;
use crate::domain::{
    events::ReactionNotificationContext,
    models::{BotId, ChannelType, EntityMention, ParticipantRole, Sender},
    ports::{
        ChannelEventHandler, ChannelNotificationSender, ChannelRealtimePublisher,
        ChannelSideEffectContext,
    },
};
use chrono::Utc;
use std::sync::{Arc, Mutex};

#[derive(Clone)]
struct FakeContext {
    message_count: i64,
    fail_existing_user_lookup: bool,
    unregistered_users: HashSet<String>,
    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,
            fail_existing_user_lookup: false,
            unregistered_users: HashSet::new(),
            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> {
        if self.fail_existing_user_lookup {
            anyhow::bail!("existing-user lookup failed");
        }
        Ok(user_ids
            .into_iter()
            .map(|user_id| user_id.as_ref().to_string())
            .filter(|id| !self.unregistered_users.contains(id))
            .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>>>,
    fail_next: Arc<Mutex<bool>>,
}

impl ChannelNotificationSender for FakeNotifications {
    type Err = anyhow::Error;

    async fn send(&self, notification: ChannelNotificationEffect) -> Result<(), Self::Err> {
        self.effects.lock().unwrap().push(notification);
        if std::mem::take(&mut *self.fail_next.lock().unwrap()) {
            anyhow::bail!("notification queue unavailable");
        }
        Ok(())
    }
}

#[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 picture_changes_refresh_all_participant_sessions_without_notifications() {
    let realtime = FakeRealtime::default();
    let notifications = FakeNotifications::default();
    let contacts = FakeContacts::default();
    let service = ChannelSideEffectService::new(
        FakeContext::default(),
        realtime.clone(),
        notifications.clone(),
        contacts.clone(),
    );
    let channel_id = Uuid::new_v4();
    let recipients = users(&["[email protected]", "[email protected]"]);
    service
        .handle(ChannelEvent::PictureChanged {
            actor: user("[email protected]"),
            channel_id,
            recipients: recipients.clone(),
        })
        .await;
    let effects = realtime.effects.lock().unwrap();
    assert!(
        matches!(&effects[..], [ChannelRealtimeEffect::PictureChanged { channel_id: id, recipients: actual }]
        if *id == channel_id && actual == &recipients)
    );
    assert!(notifications.effects.lock().unwrap().is_empty());
    assert!(contacts.users.lock().unwrap().is_empty());
}

#[tokio::test]
async fn added_reaction_notifies_message_author() {
    let realtime = FakeRealtime::default();
    let notifications = FakeNotifications::default();
    let service = ChannelSideEffectService::new(
        FakeContext::default(),
        realtime.clone(),
        notifications.clone(),
        FakeContacts::default(),
    );
    let channel_id = Uuid::new_v4();
    let message_id = Uuid::new_v4();
    let reactor = user("[email protected]");
    let author = user("[email protected]");

    service
        .handle(ChannelEvent::ReactionAdded {
            channel_id,
            actor: Sender::new_from_user(reactor.clone()),
            message_id,
            notification: ReactionNotificationContext {
                emoji: "👍".to_string(),
                message_sender: Sender::new_from_user(author.clone()),
                thread_id: None,
                message_content: "Great idea".to_string(),
                metadata: ChannelMetadata {
                    channel_type: ChannelType::Public,
                    channel_name: "general".to_string(),
                },
            },
        })
        .await;

    assert!(realtime.effects.lock().unwrap().is_empty());
    assert!(matches!(
        &notifications.effects.lock().unwrap()[..],
        [ChannelNotificationEffect::Reaction {
            sender_id,
            recipient_id,
            emoji,
            message_content,
            message_id: actual_message_id,
            ..
        }] if sender_id == &reactor
            && recipient_id == &author
            && emoji == "👍"
            && message_content == "Great idea"
            && *actual_message_id == message_id
    ));
}

#[tokio::test]
async fn self_reactions_do_not_notify() {
    let notifications = FakeNotifications::default();
    let service = ChannelSideEffectService::new(
        FakeContext::default(),
        FakeRealtime::default(),
        notifications.clone(),
        FakeContacts::default(),
    );
    let user_id = user("[email protected]");

    service
        .handle(ChannelEvent::ReactionAdded {
            channel_id: Uuid::new_v4(),
            actor: Sender::new_from_user(user_id.clone()),
            message_id: Uuid::new_v4(),
            notification: ReactionNotificationContext {
                emoji: "👍".to_string(),
                message_sender: Sender::new_from_user(user_id),
                thread_id: None,
                message_content: "No notification".to_string(),
                metadata: ChannelMetadata {
                    channel_type: ChannelType::Public,
                    channel_name: "general".to_string(),
                },
            },
        })
        .await;

    assert!(notifications.effects.lock().unwrap().is_empty());
}

#[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(),
        FakeContacts::default(),
    );
    let now = Utc::now();
    let message = MutatedMessage {
        id: Uuid::new_v4(),
        channel_id: Uuid::new_v4(),
        thread_id: None,
        sender_id: Sender::new_from_bot(bot_id::MACRO_AI_BOT_ID),
        triggered_by: None,
        triggered_via: None,
        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 mcp_client_post_is_named_after_the_client() {
    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(),
        FakeContacts::default(),
    );
    let now = Utc::now();
    let message = MutatedMessage {
        id: Uuid::new_v4(),
        channel_id: Uuid::new_v4(),
        thread_id: None,
        sender_id: Sender::new_from_bot(bot_id::MACRO_AI_BOT_ID),
        triggered_by: Some("macro|[email protected]".to_string()),
        triggered_via: Some("Claude Code".to_string()),
        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("a client post should have a profile");

    assert_eq!(profile.name, "Claude Code");
    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(),
        FakeContacts::default(),
    );
    let now = Utc::now();
    let message = MutatedMessage {
        id: Uuid::new_v4(),
        channel_id: Uuid::new_v4(),
        thread_id: None,
        sender_id: Sender::new_from_bot(BotId::new_from_uuid(Uuid::new_v4())),
        triggered_by: None,
        triggered_via: None,
        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_notification_effects_without_legacy_realtime() {
    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 contacts = FakeContacts::default();
    let service = ChannelSideEffectService::new(
        FakeContext::default(),
        realtime.clone(),
        notifications.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::new_from_user(sender.clone()),
                triggered_by: None,
                triggered_via: None,
                content: "hello".to_string(),
                created_at: now,
                updated_at: now,
                edited_at: None,
                deleted_at: None,
            },
            mentions: Vec::new(),
            has_attachments: false,
            notification_policy: PostMessageNotificationPolicy::Default,
        })
        .await;

    // The shared message service sends the common `message_update` payload;
    // the channel side effects no longer publish message frames of their own.
    assert!(realtime.effects.lock().unwrap().is_empty());

    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::new_from_bot(BotId::new_from_uuid(Uuid::new_v4())),
            triggered_by: None,
            triggered_via: None,
            content: "hello".to_string(),
            created_at: now,
            updated_at: now,
            edited_at: None,
            deleted_at: None,
        },
        mentions: Vec::new(),
        has_attachments: false,
        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 service = ChannelSideEffectService::new(
        FakeContext::default(),
        realtime.clone(),
        notifications.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::new_from_user(sender),
                triggered_by: None,
                triggered_via: None,
                content: "transient".to_string(),
                created_at: now,
                updated_at: now,
                edited_at: None,
                deleted_at: None,
            },
            mentions: Vec::new(),
            has_attachments: false,
            notification_policy: PostMessageNotificationPolicy::Silent,
        })
        .await;

    assert!(realtime.effects.lock().unwrap().is_empty());
    assert!(notifications.effects.lock().unwrap().is_empty());
}

#[tokio::test]
async fn mentions_only_skips_failing_invite_lookup_and_sends_mention() {
    let channel_id = Uuid::new_v4();
    let message_id = Uuid::new_v4();
    let sender = user("[email protected]");
    let mentioned = user("[email protected]");
    let jacob = user("[email protected]");
    let teo = user("[email protected]");
    let notifications = FakeNotifications::default();
    let service = ChannelSideEffectService::new(
        FakeContext {
            message_count: 1,
            fail_existing_user_lookup: true,
            ..FakeContext::default()
        },
        FakeRealtime::default(),
        notifications.clone(),
        FakeContacts::default(),
    );
    let now = Utc::now();
    let participants = [&sender, &mentioned, &jacob, &teo]
        .into_iter()
        .map(|user_id| ChannelParticipant {
            channel_id,
            user_id: user_id.as_ref().to_string(),
            role: ParticipantRole::Member,
            joined_at: now,
            left_at: None,
        })
        .collect();

    service
        .handle(ChannelEvent::MessagePosted {
            channel_id,
            metadata: ChannelMetadata {
                channel_type: ChannelType::Private,
                channel_name: "Macro Support".to_string(),
            },
            participants,
            message: MutatedMessage {
                id: message_id,
                channel_id,
                thread_id: None,
                sender_id: Sender::new_from_user(sender),
                triggered_by: None,
                triggered_via: None,
                content: "welcome".to_string(),
                created_at: now,
                updated_at: now,
                edited_at: None,
                deleted_at: None,
            },
            mentions: vec![SimpleMention::user(&mentioned)],
            has_attachments: false,
            notification_policy: PostMessageNotificationPolicy::MentionsOnly,
        })
        .await;

    let notification_effects = notifications.effects.lock().unwrap();
    assert_eq!(notification_effects.len(), 1);
    let ChannelNotificationEffect::UserMention { recipient_ids, .. } = &notification_effects[0]
    else {
        panic!("expected only a user mention notification");
    };
    assert_eq!(recipient_ids, &HashSet::from([mentioned]));
}

#[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 service = ChannelSideEffectService::new(
        FakeContext::default(),
        realtime.clone(),
        notifications.clone(),
        FakeContacts::default(),
    );

    service
        .handle(bot_message_posted_event(
            channel_id,
            message_id,
            None,
            &[recipient.as_ref()],
        ))
        .await;

    assert!(realtime.effects.lock().unwrap().is_empty());
    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 service = ChannelSideEffectService::new(
        FakeContext {
            bot_profile: None,
            ..FakeContext::default()
        },
        realtime.clone(),
        notifications.clone(),
        FakeContacts::default(),
    );

    service
        .handle(bot_message_posted_event(
            channel_id,
            message_id,
            None,
            &[recipient.as_ref()],
        ))
        .await;

    assert!(realtime.effects.lock().unwrap().is_empty());
    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(),
        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 {
                connected_call_participants: vec![],
                participants: vec![recipient.clone(), parent_sender.clone()],
                parent_sender_id: Some(parent_sender.clone()),
            },
            ..FakeContext::default()
        },
        FakeRealtime::default(),
        notifications.clone(),
        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 people_connected_to_the_threads_call_get_no_reply_notification() {
    let channel_id = Uuid::new_v4();
    let connected = user("[email protected]");
    let away = user("[email protected]");
    let notifications = FakeNotifications::default();
    let service = ChannelSideEffectService::new(
        FakeContext {
            thread_context: ThreadNotificationContext {
                connected_call_participants: vec![connected.clone()],
                participants: vec![connected.clone(), away.clone()],
                parent_sender_id: None,
            },
            ..FakeContext::default()
        },
        FakeRealtime::default(),
        notifications.clone(),
        FakeContacts::default(),
    );

    service
        .handle(bot_message_posted_event(
            channel_id,
            Uuid::new_v4(),
            Some(Uuid::new_v4()),
            &[connected.as_ref(), away.as_ref()],
        ))
        .await;

    let notification_effects = notifications.effects.lock().unwrap();
    let ChannelNotificationEffect::Reply { recipient_ids, .. } = &notification_effects[0] else {
        panic!("expected a reply notification");
    };
    assert_eq!(recipient_ids, &HashSet::from([away]));
}

#[tokio::test]
async fn a_mention_of_someone_connected_to_the_threads_call_is_dropped() {
    let channel_id = Uuid::new_v4();
    let now = Utc::now();
    let sender = user("[email protected]");
    let connected = user("[email protected]");
    let away = user("[email protected]");
    let notifications = FakeNotifications::default();
    let service = ChannelSideEffectService::new(
        FakeContext {
            thread_context: ThreadNotificationContext {
                connected_call_participants: vec![connected.clone()],
                participants: vec![sender.clone()],
                parent_sender_id: None,
            },
            ..FakeContext::default()
        },
        FakeRealtime::default(),
        notifications.clone(),
        FakeContacts::default(),
    );

    service
        .handle(ChannelEvent::MessagePosted {
            channel_id,
            metadata: ChannelMetadata {
                channel_type: ChannelType::Private,
                channel_name: "Product".to_string(),
            },
            participants: vec![],
            message: MutatedMessage {
                id: Uuid::new_v4(),
                channel_id,
                thread_id: Some(Uuid::new_v4()),
                sender_id: Sender::new_from_user(sender),
                triggered_by: None,
                triggered_via: None,
                content: "look at this".to_string(),
                created_at: now,
                updated_at: now,
                edited_at: None,
                deleted_at: None,
            },
            mentions: vec![SimpleMention::user(&connected), SimpleMention::user(&away)],
            has_attachments: false,
            notification_policy: PostMessageNotificationPolicy::MentionsOnly,
        })
        .await;

    let notification_effects = notifications.effects.lock().unwrap();
    let ChannelNotificationEffect::UserMention { recipient_ids, .. } = &notification_effects[0]
    else {
        panic!("expected a mention notification");
    };
    assert_eq!(recipient_ids, &HashSet::from([away]));
}

#[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::new_from_uuid(Uuid::new_v4())
        .into_storage_id()
        .to_string();
    let notifications = FakeNotifications::default();
    let service = ChannelSideEffectService::new(
        FakeContext::default(),
        FakeRealtime::default(),
        notifications.clone(),
        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 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(),
        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::new_from_user(sender.clone()),
                triggered_by: None,
                triggered_via: None,
                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,
            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));
}

#[tokio::test]
async fn document_mentions_in_a_reply_notify_only_thread_participants() {
    let channel_id = Uuid::new_v4();
    let message_id = Uuid::new_v4();
    let thread_id = Uuid::new_v4();
    let sender = user("[email protected]");
    let participant = user("[email protected]");
    let outsider = 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,
            }],
            thread_context: ThreadNotificationContext {
                connected_call_participants: vec![],
                participants: vec![sender.clone(), participant.clone()],
                parent_sender_id: Some(participant.clone()),
            },
            ..FakeContext::default()
        },
        FakeRealtime::default(),
        notifications.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: [&sender, &participant, &outsider]
                .into_iter()
                .map(|user| ChannelParticipant {
                    channel_id,
                    user_id: user.as_ref().to_string(),
                    role: ParticipantRole::Member,
                    joined_at: now,
                    left_at: None,
                })
                .collect(),
            message: MutatedMessage {
                id: message_id,
                channel_id,
                thread_id: Some(thread_id),
                sender_id: Sender::new_from_user(sender.clone()),
                triggered_by: None,
                triggered_via: None,
                content: "see this".to_string(),
                created_at: now,
                updated_at: now,
                edited_at: None,
                deleted_at: None,
            },
            mentions: vec![SimpleMention {
                entity_type: "document".to_string(),
                entity_id: "doc-1".to_string(),
            }],
            has_attachments: false,
            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(&participant));
    assert!(!document_recipients.contains(&outsider));
    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::new_from_user(user("[email protected]")),
        on_behalf_of: None,
        channel_type: ChannelType::Private,
        channel_name: None,
        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_system_channel_created_with_subject() {
    let event = ChannelEvent::ChannelCreated {
        channel_id: Uuid::nil(),
        actor: Sender::new_from_bot(bot_id::MACRO_SYSTEM_BOT_ID),
        on_behalf_of: Some(user("[email protected]")),
        channel_type: ChannelType::Private,
        channel_name: Some("Macro Support x owner".to_string()),
        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_bot_channel_created_without_subject() {
    let event = ChannelEvent::ChannelCreated {
        channel_id: Uuid::nil(),
        actor: Sender::new_from_bot(bot_id::MACRO_SYSTEM_BOT_ID),
        on_behalf_of: None,
        channel_type: ChannelType::Private,
        channel_name: None,
        participant_user_ids: users(&["[email protected]", "[email protected]"]),
    };

    assert!(contact_sync_users_for_event(&event).is_none());
}

#[test]
fn contact_sync_ignores_public_channel_created() {
    let event = ChannelEvent::ChannelCreated {
        channel_id: Uuid::nil(),
        actor: Sender::new_from_user(user("[email protected]")),
        on_behalf_of: None,
        channel_type: ChannelType::Public,
        channel_name: None,
        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::new_from_bot(BotId::new_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::new_from_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::new_from_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 macro_ai_user_mention_is_not_a_user_recipient() {
    assert!(is_bot_user_mention(&mention(
        "user",
        bot_id::MACRO_AI_BOT_ID.into_storage_id().as_ref()
    )));
    // The legacy bare-UUID encoding is no longer treated as a bot mention.
    assert!(!is_bot_user_mention(&mention(
        "user",
        &bot_id::MACRO_AI_BOT_ID.as_uuid().to_string()
    )));
    assert!(!is_bot_user_mention(&mention(
        "user",
        "macro|[email protected]"
    )));
    assert!(is_bot_principal(
        bot_id::MACRO_AI_BOT_ID.into_storage_id().as_ref()
    ));
    assert!(!is_bot_principal("macro|[email protected]"));
}

#[derive(Clone, Default)]
struct TestEventBroker {
    published: Arc<Mutex<Vec<PublishedEvent>>>,
}

#[derive(Debug, Clone)]
struct PublishedEvent {
    topic: String,
    key: String,
    envelope: serde_json::Value,
}

impl MacroEventBroker for TestEventBroker {
    fn send_event<E: macro_event_broker::MacroEvent + ?Sized>(
        &self,
        event: &E,
    ) -> Result<
        tokio::task::JoinHandle<Result<(), macro_event_broker::EventBrokerError>>,
        macro_event_broker::EventBrokerError,
    > {
        self.published.lock().unwrap().push(PublishedEvent {
            topic: event.topic().to_string(),
            key: event.key().to_string(),
            envelope: serde_json::to_value(event.event())?,
        });
        Ok(tokio::spawn(async { Ok(()) }))
    }
}

fn broker_service(
    broker: TestEventBroker,
) -> ChannelSideEffectService<
    FakeContext,
    FakeRealtime,
    FakeNotifications,
    FakeContacts,
    TestEventBroker,
> {
    ChannelSideEffectService::new(
        FakeContext::default(),
        FakeRealtime::default(),
        FakeNotifications::default(),
        FakeContacts::default(),
    )
    .with_macro_event_broker(broker)
}

#[tokio::test]
async fn handle_publishes_channel_created_event() {
    let broker = TestEventBroker::default();
    let service = broker_service(broker.clone());
    let channel_id = Uuid::new_v4();

    service
        .handle(ChannelEvent::ChannelCreated {
            channel_id,
            actor: Sender::new_from_user(user("[email protected]")),
            on_behalf_of: None,
            channel_type: ChannelType::Private,
            channel_name: Some("general".to_string()),
            participant_user_ids: users(&["[email protected]", "[email protected]"]),
        })
        .await;

    let published = broker.published.lock().unwrap();
    assert_eq!(published.len(), 1);
    assert_eq!(published[0].topic, "macro.channels");
    assert_eq!(published[0].key, channel_id.to_string());
    assert_eq!(published[0].envelope["event_type"], "channel.created");
    assert_eq!(published[0].envelope["metadata"]["channel_name"], "general");
    assert_eq!(
        published[0].envelope["metadata"]["actor"],
        "macro|[email protected]"
    );
}

#[tokio::test]
async fn handle_publishes_participant_events() {
    let broker = TestEventBroker::default();
    let service = broker_service(broker.clone());
    let channel_id = Uuid::new_v4();

    service
        .handle(ChannelEvent::ParticipantsRemoved {
            channel_id,
            channel_type: ChannelType::Team,
            actor: user("[email protected]"),
            removed_user_ids: users(&["[email protected]"]),
        })
        .await;

    let published = broker.published.lock().unwrap();
    assert_eq!(published.len(), 1);
    assert_eq!(
        published[0].envelope["event_type"],
        "channel.participant_removed"
    );
    assert_eq!(
        published[0].envelope["metadata"]["removed_by"],
        "macro|[email protected]"
    );
    assert_eq!(
        published[0].envelope["metadata"]["removed_user_ids"][0],
        "macro|[email protected]"
    );
}

#[tokio::test]
async fn handle_publishes_no_channel_topic_facts_for_posted_messages() {
    let broker = TestEventBroker::default();
    let service = broker_service(broker.clone());
    let channel_id = Uuid::new_v4();

    service
        .handle(bot_message_posted_event(
            channel_id,
            Uuid::new_v4(),
            None,
            &["macro|[email protected]"],
        ))
        .await;

    // Message facts travel on `macro.messages` with their parent.
    assert!(
        broker
            .published
            .lock()
            .unwrap()
            .iter()
            .all(|event| event.topic != "macro.channels")
    );
}

#[test]
fn broker_events_map_participant_joined_to_participant_added() {
    use macro_event_broker::MacroEvent as _;
    let channel_id = Uuid::new_v4();
    let events = broker_events_for_event(&ChannelEvent::ParticipantJoined {
        channel_id,
        channel_type: ChannelType::Public,
        user_id: Sender::new_from_user(user("[email protected]")),
        active_participant_user_ids: users(&["[email protected]"]),
    });

    assert_eq!(events.len(), 1);
    let envelope = serde_json::to_value(events[0].event()).unwrap();
    assert_eq!(envelope["event_type"], "channel.participant_added");
    assert_eq!(envelope["metadata"]["added_by"], "macro|[email protected]");
    assert_eq!(
        envelope["metadata"]["added_user_ids"][0],
        "macro|[email protected]"
    );
}

#[test]
fn broker_events_map_channel_updated() {
    use macro_event_broker::MacroEvent as _;
    let channel_id = Uuid::new_v4();
    let events = broker_events_for_event(&ChannelEvent::ChannelUpdated {
        channel_id,
        actor: user("[email protected]"),
        previous_name: Some("old".to_string()),
        channel_name: Some("new".to_string()),
    });

    assert_eq!(events.len(), 1);
    let envelope = serde_json::to_value(events[0].event()).unwrap();
    assert_eq!(envelope["event_type"], "channel.updated");
    assert_eq!(envelope["metadata"]["previous_name"], "old");
    assert_eq!(envelope["metadata"]["channel_name"], "new");
}

fn entity_mention(entity_type: &str, entity_id: &str) -> EntityMention {
    EntityMention {
        id: Uuid::new_v4(),
        source_entity_type: "document".to_string(),
        source_entity_id: "doc-1".to_string(),
        entity_type: entity_type.to_string(),
        entity_id: entity_id.to_string(),
        user_id: Some("macro|[email protected]".to_string()),
        created_at: Utc::now(),
    }
}

#[test]
fn broker_events_skip_entity_mention_events() {
    assert!(
        broker_events_for_event(&ChannelEvent::EntityMentionCreated {
            mention: entity_mention("bot", "bot-1"),
        })
        .is_empty()
    );
    assert!(
        broker_events_for_event(&ChannelEvent::EntityMentionDeleted {
            mention: entity_mention("bot", "bot-1"),
        })
        .is_empty()
    );
}

#[test]
fn mention_broker_events_map_message_posted_mentions() {
    use macro_event_broker::MacroEvent as _;
    let channel_id = Uuid::new_v4();
    let message_id = Uuid::new_v4();
    let now = Utc::now();

    let events = mention_broker_events_for_event(&ChannelEvent::MessagePosted {
        channel_id,
        metadata: ChannelMetadata {
            channel_type: ChannelType::Team,
            channel_name: "Project".to_string(),
        },
        participants: Vec::new(),
        message: MutatedMessage {
            id: message_id,
            channel_id,
            thread_id: None,
            sender_id: Sender::new_from_user(user("[email protected]")),
            triggered_by: None,
            triggered_via: None,
            content: "@bot @doc-1".to_string(),
            created_at: now,
            updated_at: now,
            edited_at: None,
            deleted_at: None,
        },
        mentions: vec![
            SimpleMention {
                entity_type: "bot".to_string(),
                entity_id: "bot-1".to_string(),
            },
            SimpleMention {
                entity_type: "document".to_string(),
                entity_id: "doc-1".to_string(),
            },
        ],
        has_attachments: false,
        notification_policy: PostMessageNotificationPolicy::Default,
    });

    assert_eq!(events.len(), 2);
    assert_eq!(events[0].key(), "bot-1");
    assert_eq!(events[1].key(), "doc-1");
    let envelope = serde_json::to_value(events[0].event()).unwrap();
    assert_eq!(envelope["event_type"], "mention.message_sent");
    assert_eq!(envelope["metadata"]["source"]["kind"], "message");
    assert_eq!(envelope["metadata"]["source"]["id"], message_id.to_string());
    assert_eq!(envelope["metadata"]["mentioned"]["kind"], "bot");
    assert_eq!(envelope["metadata"]["mentioned"]["id"], "bot-1");
}

#[test]
fn mention_broker_events_map_entity_mention_created_and_deleted() {
    use macro_event_broker::MacroEvent as _;
    let mention = entity_mention("bot", "bot-1");

    let created = mention_broker_events_for_event(&ChannelEvent::EntityMentionCreated {
        mention: mention.clone(),
    });
    assert_eq!(created.len(), 1);
    assert_eq!(created[0].key(), "bot-1");
    let envelope = serde_json::to_value(created[0].event()).unwrap();
    assert_eq!(envelope["event_type"], "mention.created");
    assert_eq!(envelope["metadata"]["source"]["kind"], "document");
    assert_eq!(envelope["metadata"]["source"]["id"], "doc-1");
    assert_eq!(envelope["metadata"]["mentioned"]["kind"], "bot");
    assert_eq!(envelope["metadata"]["mentioned"]["id"], "bot-1");

    let deleted = mention_broker_events_for_event(&ChannelEvent::EntityMentionDeleted { mention });
    assert_eq!(deleted.len(), 1);
    let envelope = serde_json::to_value(deleted[0].event()).unwrap();
    assert_eq!(envelope["event_type"], "mention.deleted");
}

#[test]
fn mention_broker_events_skip_unrelated_events() {
    let events = mention_broker_events_for_event(&ChannelEvent::PictureChanged {
        actor: user("[email protected]"),
        channel_id: Uuid::new_v4(),
        recipients: Vec::new(),
    });
    assert!(events.is_empty());
}

#[tokio::test]
async fn handle_publishes_mention_events_alongside_channel_events() {
    let broker = TestEventBroker::default();
    let service = broker_service(broker.clone());

    service
        .handle(ChannelEvent::EntityMentionCreated {
            mention: entity_mention("bot", "bot-1"),
        })
        .await;

    let published = broker.published.lock().unwrap();
    assert_eq!(published.len(), 1);
    assert_eq!(published[0].topic, "macro.mentions");
    assert_eq!(published[0].key, "bot-1");
    assert_eq!(published[0].envelope["event_type"], "mention.created");
}

#[tokio::test]
async fn nonuser_dm_messages_email_once_including_mentions_and_replies() {
    for message_count in [1, 2] {
        for is_reply in [false, true] {
            for mentioned in [false, true] {
                let channel_id = Uuid::new_v4();
                let message_id = Uuid::new_v4();
                let recipient = user("[email protected]");
                let sender = user("[email protected]");
                let notifications = FakeNotifications::default();
                let service = ChannelSideEffectService::new(
                    FakeContext {
                        message_count,
                        unregistered_users: HashSet::from([recipient.to_string()]),
                        ..FakeContext::default()
                    },
                    FakeRealtime::default(),
                    notifications.clone(),
                    FakeContacts::default(),
                );
                let mut event = bot_message_posted_event(
                    channel_id,
                    message_id,
                    is_reply.then(Uuid::new_v4),
                    &[sender.as_ref(), recipient.as_ref()],
                );
                if let ChannelEvent::MessagePosted {
                    metadata,
                    message,
                    mentions,
                    ..
                } = &mut event
                {
                    metadata.channel_type = ChannelType::DirectMessage;
                    message.sender_id = Sender::new_from_user(sender.clone());
                    if mentioned {
                        mentions.push(SimpleMention::user(&recipient));
                    }
                }
                service.handle(event).await;
                let effects = notifications.effects.lock().unwrap();
                let emails: Vec<_> = effects
                    .iter()
                    .filter_map(|effect| match effect {
                        ChannelNotificationEffect::Invite {
                            message_id,
                            unregistered_recipient_ids,
                            message_content,
                            ..
                        } if !unregistered_recipient_ids.is_empty() => {
                            Some((message_id, unregistered_recipient_ids, message_content))
                        }
                        _ => None,
                    })
                    .collect();
                assert_eq!(emails.len(), 1);
                assert_eq!(*emails[0].0, Some(message_id));
                assert_eq!(*emails[0].1, HashSet::from([recipient]));
                assert_eq!(emails[0].2.as_deref(), Some("hello"));
            }
        }
    }
}

#[tokio::test]
async fn immediate_dm_email_excludes_registered_users_bots_and_silent_messages() {
    for (registered, bot, policy, channel_type) in [
        (
            true,
            false,
            PostMessageNotificationPolicy::Default,
            ChannelType::DirectMessage,
        ),
        (
            false,
            true,
            PostMessageNotificationPolicy::Default,
            ChannelType::DirectMessage,
        ),
        (
            false,
            false,
            PostMessageNotificationPolicy::Silent,
            ChannelType::DirectMessage,
        ),
        (
            false,
            false,
            PostMessageNotificationPolicy::MentionsOnly,
            ChannelType::DirectMessage,
        ),
        (
            false,
            false,
            PostMessageNotificationPolicy::Default,
            ChannelType::Private,
        ),
    ] {
        let sender = user("[email protected]");
        let recipient = user("[email protected]");
        let notifications = FakeNotifications::default();
        let service = ChannelSideEffectService::new(
            FakeContext {
                unregistered_users: if registered {
                    HashSet::new()
                } else {
                    HashSet::from([recipient.to_string()])
                },
                ..FakeContext::default()
            },
            FakeRealtime::default(),
            notifications.clone(),
            FakeContacts::default(),
        );
        let mut event = bot_message_posted_event(
            Uuid::new_v4(),
            Uuid::new_v4(),
            None,
            &[sender.as_ref(), recipient.as_ref()],
        );
        if let ChannelEvent::MessagePosted {
            metadata,
            message,
            notification_policy,
            ..
        } = &mut event
        {
            metadata.channel_type = channel_type;
            *notification_policy = policy;
            if !bot {
                message.sender_id = Sender::new_from_user(sender);
            }
        }
        service.handle(event).await;
        assert!(!notifications.effects.lock().unwrap().iter().any(|effect| matches!(effect, ChannelNotificationEffect::Invite { unregistered_recipient_ids, .. } if !unregistered_recipient_ids.is_empty())));
    }
}

#[tokio::test]
async fn creating_empty_dm_does_not_send_email_or_notifications() {
    let recipient = user("[email protected]");
    let notifications = FakeNotifications::default();
    let service = ChannelSideEffectService::new(
        FakeContext {
            unregistered_users: HashSet::from([recipient.to_string()]),
            ..FakeContext::default()
        },
        FakeRealtime::default(),
        notifications.clone(),
        FakeContacts::default(),
    );
    service
        .handle(ChannelEvent::ChannelCreated {
            channel_id: Uuid::new_v4(),
            actor: Sender::new_from_user(user("[email protected]")),
            on_behalf_of: None,
            channel_type: ChannelType::DirectMessage,
            channel_name: None,
            participant_user_ids: vec![user("[email protected]"), recipient],
        })
        .await;
    assert!(notifications.effects.lock().unwrap().is_empty());
}

#[tokio::test]
async fn first_dm_email_fallback_preserves_message_deduplication_key() {
    let sender = user("[email protected]");
    let recipient = user("[email protected]");
    let message_id = Uuid::new_v4();
    let notifications = FakeNotifications::default();
    *notifications.fail_next.lock().unwrap() = true;
    let service = ChannelSideEffectService::new(
        FakeContext {
            message_count: 1,
            unregistered_users: HashSet::from([recipient.to_string()]),
            ..FakeContext::default()
        },
        FakeRealtime::default(),
        notifications.clone(),
        FakeContacts::default(),
    );
    let mut event = bot_message_posted_event(
        Uuid::new_v4(),
        message_id,
        None,
        &[sender.as_ref(), recipient.as_ref()],
    );
    if let ChannelEvent::MessagePosted {
        metadata, message, ..
    } = &mut event
    {
        metadata.channel_type = ChannelType::DirectMessage;
        message.sender_id = Sender::new_from_user(sender);
    }
    service.handle(event).await;
    let effects = notifications.effects.lock().unwrap();
    assert_eq!(effects.len(), 2);
    for effect in effects.iter() {
        let ChannelNotificationEffect::Invite {
            message_id: key,
            unregistered_recipient_ids,
            ..
        } = effect
        else {
            panic!("expected email attempt");
        };
        assert_eq!(*key, Some(message_id));
        assert_eq!(
            *unregistered_recipient_ids,
            HashSet::from([recipient.clone()])
        );
    }
}