Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(channels): distinguish DM invitation emails from channel invites (#7964)
Sean Ayed710e2769b45
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/channelInviteMetadata.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/channelInviteMetadata.tsindex ae5001d57f..2b557c8a7e 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/channelInviteMetadata.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/channelInviteMetadata.ts@@ -15,6 +15,9 @@ export interface ChannelInviteMetadata {channelName?: string;/** The user who sent the invitation */invitedBy: string;+ /** Whether this is a direct message rather than a channel invitation.+Older notification payloads retain channel-invitation wording. */+ isDirectMessage?: boolean;/** Message content to show in the invite email, when the invite was triggered by a message. */messageContent?: ChannelInviteMetadataMessageContent;/** The sender's profile picture URL, if available. */diff --git a/apps/web/src/lib/service-clients/service-notification/generated/zod.ts b/apps/web/src/lib/service-clients/service-notification/generated/zod.tsindex c9f1205d93..08bf6f2ab9 100644--- a/apps/web/src/lib/service-clients/service-notification/generated/zod.ts+++ b/apps/web/src/lib/service-clients/service-notification/generated/zod.ts@@ -718,6 +718,12 @@ export const listTypedNotificationsResponse = zodinvitedBy: zod.string().describe('The user who sent the invitation'),+ isDirectMessage: zod+ .boolean()+ .optional()+ .describe(+ 'Whether this is a direct message rather than a channel invitation.\nOlder notification payloads retain channel-invitation wording.'+ ),messageContent: zod.string().nullish()@@ -2614,6 +2620,12 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zodinvitedBy: zod.string().describe('The user who sent the invitation'),+ isDirectMessage: zod+ .boolean()+ .optional()+ .describe(+ 'Whether this is a direct message rather than a channel invitation.\nOlder notification payloads retain channel-invitation wording.'+ ),messageContent: zod.string().nullish()@@ -4504,6 +4516,12 @@ export const getTypedNotificationsByEventItemIdResponse = zodinvitedBy: zod.string().describe('The user who sent the invitation'),+ isDirectMessage: zod+ .boolean()+ .optional()+ .describe(+ 'Whether this is a direct message rather than a channel invitation.\nOlder notification payloads retain channel-invitation wording.'+ ),messageContent: zod.string().nullish()@@ -6361,6 +6379,12 @@ export const getTypedNotificationByIdResponse = zodinvitedBy: zod.string().describe('The user who sent the invitation'),+ isDirectMessage: zod+ .boolean()+ .optional()+ .describe(+ 'Whether this is a direct message rather than a channel invitation.\nOlder notification payloads retain channel-invitation wording.'+ ),messageContent: zod.string().nullish()diff --git a/apps/web/src/lib/service-clients/service-notification/openapi.json b/apps/web/src/lib/service-clients/service-notification/openapi.jsonindex e1f34e9b3d..52207c5ba2 100644--- a/apps/web/src/lib/service-clients/service-notification/openapi.json+++ b/apps/web/src/lib/service-clients/service-notification/openapi.json@@ -1365,6 +1365,10 @@"type": "string","description": "The user who sent the invitation"},+ "isDirectMessage": {+ "type": "boolean",+ "description": "Whether this is a direct message rather than a channel invitation.\nOlder notification payloads retain channel-invitation wording."+ },"messageContent": {"type": ["string", "null"],"description": "Message content to show in the invite email, when the invite was triggered by a message."diff --git a/crates/channels/src/outbound/notification_sender.rs b/crates/channels/src/outbound/notification_sender.rsindex 09e5274150..c2f964f3ba 100644--- a/crates/channels/src/outbound/notification_sender.rs+++ b/crates/channels/src/outbound/notification_sender.rs@@ -18,6 +18,9 @@ use notification_hex::domain::{use std::{collections::HashSet, sync::Arc};use uuid::Uuid;+#[cfg(test)]+mod test;+/// Notification ingress adapter for channel notification effects.#[derive(Clone)]pub struct NotificationChannelSender<I> {@@ -70,18 +73,23 @@ async fn send_invite_notifications(message_content,common,} = delivery;+ let notification = ChannelInviteMetadata {+ invited_by: invited_by_user_id.clone(),+ channel_name: common.channel_name,+ is_direct_message: matches!(+ common.channel_type,+ model_notifications::ChannelType::DirectMessage+ ),+ sender_profile_picture_url,+ message_content,+ };let _ = tokio::try_join!(ingress.send_notification(SendNotificationRequestBuilder {notification_entity: model_entity::EntityType::Channel.with_entity_string(channel_id.to_string()),secondary_notification_entity: None,- notification: ChannelInviteMetadata {- invited_by: invited_by_user_id.clone(),- channel_name: common.channel_name.clone(),- sender_profile_picture_url: sender_profile_picture_url.clone(),- message_content: message_content.clone(),- },+ notification: notification.clone(),sender_id: Some(invited_by_user_id.clone()),recipient_ids: registered_recipient_ids,}@@ -94,12 +102,7 @@ async fn send_invite_notifications(notification_entity: model_entity::EntityType::Channel.with_entity_string(channel_id.to_string()),secondary_notification_entity: None,- notification: ChannelInviteMetadata {- invited_by: invited_by_user_id.clone(),- channel_name: common.channel_name.clone(),- sender_profile_picture_url,- message_content,- },+ notification,sender_id: Some(invited_by_user_id.clone()),recipient_ids: unregistered_recipient_ids,}diff --git a/crates/channels/src/outbound/notification_sender/test.rs b/crates/channels/src/outbound/notification_sender/test.rsnew file mode 100644index 0000000000..ea24699329--- /dev/null+++ b/crates/channels/src/outbound/notification_sender/test.rs@@ -0,0 +1,123 @@+use super::*;+use notification_hex::domain::{+ models::{Notification, SendNotificationRequest, request::NotificationResult},+ service::SendNotificationError,+};+use rootcause::Report;+use serde::Serialize;+use serde_json::{Value, json};+use std::sync::Mutex;++#[derive(Default)]+struct CapturingIngress {+ sent: Mutex<Vec<Value>>,+}++impl NotificationIngress for CapturingIngress {+ async fn send_notification<+ 'a,+ T: Notification + Clone + 'static,+ U: Serialize + Send + Sync + 'static,+ >(+ &'a self,+ req: SendNotificationRequest<'a, T, U>,+ ) -> Result<Option<NotificationResult<'a>>, Report<SendNotificationError>> {+ self.sent+ .lock()+ .unwrap()+ .push(serde_json::to_value(req).unwrap());+ Ok(None)+ }+}++#[tokio::test]+async fn invite_delivery_preserves_dm_context_for_email_and_push() {+ for channel_type in [+ ChannelType::DirectMessage,+ ChannelType::Private,+ ChannelType::Team,+ ChannelType::Public,+ ] {+ let is_dm = matches!(channel_type, ChannelType::DirectMessage);+ let channel_name = if is_dm {+ "julia+scribbington"+ } else {+ "general"+ };+ let ingress = Arc::new(CapturingIngress::default());+ let channel_id = Uuid::from_u128(1);+ let sender = MacroUserIdStr::try_from_email("[email protected]").unwrap();+ let registered = MacroUserIdStr::try_from_email("[email protected]").unwrap();+ let unregistered =+ MacroUserIdStr::try_from_email("[email protected]").unwrap();++ NotificationChannelSender::new(ingress.clone())+ .send(ChannelNotificationEffect::Invite {+ channel_id,+ invited_by_user_id: sender,+ registered_recipient_ids: HashSet::from([registered.clone()]),+ unregistered_recipient_ids: HashSet::from([unregistered.clone()]),+ sender_profile_picture_url: None,+ message_content: Some("Hey".to_string()),+ metadata: ChannelMetadata {+ channel_type,+ channel_name: channel_name.to_string(),+ },+ })+ .await+ .unwrap();++ let sent = ingress.sent.lock().unwrap();+ assert_eq!(sent.len(), 2);+ for request in sent.iter() {+ let notification = &request["req"]["notification"];+ assert_eq!(notification["tag"], "channel_invite");+ assert_eq!(notification["content"]["isDirectMessage"], is_dm);+ assert_eq!(notification["content"]["channelName"], channel_name);+ assert_eq!(notification["content"]["messageContent"], "Hey");+ assert_eq!(+ request["req"]["notification_entity"]["entity_id"],+ channel_id.to_string()+ );+ }++ let email = sent+ .iter()+ .find(|req| !req["build_email"].is_null())+ .unwrap();+ assert_eq!(email["req"]["recipient_ids"], json!([unregistered]));+ let email_content = &email["build_email"]["content"];+ assert_eq!(+ email_content["subject"],+ if is_dm {+ "[email protected] sent you a message on Macro"+ } else {+ "[email protected] has invited you to join #general"+ }+ );+ let body = email_content["body"].as_str().unwrap();+ assert!(body.contains("Hey"));+ if is_dm {+ assert!(!body.contains(channel_name));+ assert!(body.contains(">View message</a"));+ } else {+ assert!(body.contains("<strong>#general</strong>"));+ assert!(body.contains(">Join channel</a"));+ }++ let push = sent+ .iter()+ .find(|req| !req["build_apns"].is_null())+ .unwrap();+ assert_eq!(push["req"]["recipient_ids"], json!([registered]));+ assert_eq!(push["send_conn_gateway"], true);+ assert_eq!(+ push["build_apns"]["notif"]["aps"]["alert"]["title"],+ if is_dm {+ "[email protected] sent you a message"+ } else {+ "[email protected] invited you to join #general"+ }+ );+ }+}diff --git a/crates/invite_email/src/lib.rs b/crates/invite_email/src/lib.rsindex c79837fb95..b2b8b9ad99 100644--- a/crates/invite_email/src/lib.rs+++ b/crates/invite_email/src/lib.rs@@ -141,6 +141,10 @@ pub struct ChannelInviteMetadata {#[serde(default)]#[serde(alias = "channel_name")]pub channel_name: String,+ /// Whether this is a direct message rather than a channel invitation.+ /// Older notification payloads retain channel-invitation wording.+ #[serde(default)]+ pub is_direct_message: bool,/// Message content to show in the invite email, when the invite was triggered by a message.#[serde(default)]pub message_content: Option<String>,@@ -170,10 +174,14 @@ impl NotificationTitle for ChannelInviteMetadata {) -> Result<String, rootcause::Report> {let email = self.invited_by.email_part();let sender = email.email_str();- Ok(format!(- "{sender} invited you to join #{}",- self.channel_name- ))+ if self.is_direct_message {+ Ok(format!("{sender} sent you a message"))+ } else {+ Ok(format!(+ "{sender} invited you to join #{}",+ self.channel_name+ ))+ }}fn format_body(@@ -188,7 +196,11 @@ impl NotificationExtEmail for ChannelInviteMetadata {fn format_email(&self) -> EmailContent {let sender = self.sender_display();EmailContent {- subject: format!("{sender} has invited you to join #{}", self.channel_name),+ subject: if self.is_direct_message {+ format!("{sender} sent you a message on Macro")+ } else {+ format!("{sender} has invited you to join #{}", self.channel_name)+ },body: self.render().expect("ChannelInviteMetadata template render failed in format_email"),diff --git a/crates/invite_email/src/test.rs b/crates/invite_email/src/test.rsindex 690138ed41..69780af909 100644--- a/crates/invite_email/src/test.rs+++ b/crates/invite_email/src/test.rs@@ -125,6 +125,140 @@ fn colleague_joined_serde_round_trip_keeps_the_wire_shape() {assert_eq!(String::from(parsed.recipient_email), "[email protected]");}+fn make_channel_invite() -> ChannelInviteMetadata {+ ChannelInviteMetadata {+ invited_by: MacroUserIdStr::try_from_email("[email protected]").unwrap(),+ channel_name: "general".to_string(),+ is_direct_message: false,+ message_content: None,+ sender_profile_picture_url: None,+ }+}++#[test]+fn dm_invite_names_the_sender_not_the_recipient() {+ let invite = ChannelInviteMetadata {+ channel_name: "julia+scribbington".to_string(),+ is_direct_message: true,+ message_content: Some("Hey".to_string()),+ ..make_channel_invite()+ };+ let email = invite.format_email();+ assert_eq!(+ email.subject,+ "[email protected] sent you a message on Macro"+ );+ assert!(+ .body+ .contains("[email protected] sent you a message on Macro.")+ );+ assert!(email.body.contains("Hey"));+ assert!(email.body.contains(">View message</a"));+ assert!(email.body.contains("/app/signup\""));+ assert!(!email.body.contains("julia+scribbington"));+ assert!(!email.body.contains("invited"));+ assert!(!email.body.contains("Join channel"));+ assert_eq!(+ invite.format_title(None).unwrap(),+ "[email protected] sent you a message"+ );+}++#[test]+fn dm_invite_without_message_content_keeps_dm_wording() {+ let email = ChannelInviteMetadata {+ is_direct_message: true,+ ..make_channel_invite()+ }+ .format_email();+ assert!(email.body.contains("Sign up to read and reply."));+ assert!(!email.body.contains("general"));+ assert!(!email.body.contains("A shared space for your team"));+}++#[test]+fn named_channel_invite_keeps_channel_wording_with_or_without_a_message() {+ for message_content in [None, Some("Hey".to_string())] {+ let invite = ChannelInviteMetadata {+ message_content,+ ..make_channel_invite()+ };+ let email = invite.format_email();+ assert_eq!(+ email.subject,+ "[email protected] has invited you to join #general"+ );+ assert!(email.body.contains("<strong>#general</strong> on Macro."));+ assert!(email.body.contains(">Join channel</a"));+ assert!(!email.body.contains("sent you a message"));+ assert_eq!(+ invite.format_title(None).unwrap(),+ "[email protected] invited you to join #general"+ );+ }+}++#[test]+fn invite_email_escapes_message_content_and_channel_names() {+ for is_direct_message in [false, true] {+ let email = ChannelInviteMetadata {+ channel_name: "<script>channel</script>".to_string(),+ is_direct_message,+ message_content: Some("<script>message</script>".to_string()),+ ..make_channel_invite()+ }+ .format_email();+ assert!(!email.body.contains("<script>"));+ assert!(+ .body+ .contains("<script>message</script>")+ );+ if !is_direct_message {+ assert!(+ .body+ .contains("<script>channel</script>")+ );+ }+ }+}++#[test]+fn legacy_channel_invites_default_to_channel_wording() {+ for wire in [+ serde_json::json!({+ "invitedBy": "macro|[email protected]",+ "channelName": "general",+ }),+ serde_json::json!({+ "invited_by": "macro|[email protected]",+ "channel_name": "general",+ }),+ ] {+ let invite: ChannelInviteMetadata = serde_json::from_value(wire).unwrap();+ assert!(!invite.is_direct_message);+ assert_eq!(+ invite.format_email().subject,+ "[email protected] has invited you to join #general"+ );+ }+}++#[test]+fn dm_invite_serde_round_trip_preserves_dm_wording() {+ let invite = ChannelInviteMetadata {+ is_direct_message: true,+ ..make_channel_invite()+ };+ let wire = serde_json::to_value(&invite).unwrap();+ assert_eq!(wire["isDirectMessage"], true);+ let parsed: ChannelInviteMetadata = serde_json::from_value(wire).unwrap();+ assert!(parsed.is_direct_message);+ assert_eq!(parsed.format_email().subject, invite.format_email().subject);+}+fn make_invite() -> InviteToMacro {InviteToMacro {recipient_email: EmailStr::try_from("[email protected]".to_string()).unwrap(),diff --git a/crates/invite_email/templates/invite_to_channel.html b/crates/invite_email/templates/invite_to_channel.htmlindex 879e35e596..54a0b93f2f 100644--- a/crates/invite_email/templates/invite_to_channel.html+++ b/crates/invite_email/templates/invite_to_channel.html@@ -10,7 +10,11 @@/><meta name="color-scheme" content="light" /><meta name="supported-color-schemes" content="light" />+ {% if is_direct_message %}+ <title>{{ sender_display() }} sent you a message on Macro</title>+ {% else %}<title>You're invited to join #{{ channel_name }}</title>+ {% endif %}<!--[if mso]><noscript><xml@@ -53,7 +57,11 @@mso-hide: all;">+ {% if is_direct_message %}+ {{ sender_display() }} sent you a message on Macro.+ {% else %}An invitation to join a channel on Macro.+ {% endif %}</div><tablerole="presentation"@@ -160,8 +168,12 @@color: #525252;">+ {% if is_direct_message %}+ {{ sender_display() }} sent you a message on Macro.+ {% else %}{{ sender_display() }} has invited you to join<strong>#{{ channel_name }}</strong> on Macro.+ {% endif %}</p>{% if let Some(content) = message_content %}<table@@ -196,8 +208,12 @@color: #525252;">+ {% if is_direct_message %}+ Sign up to read and reply.+ {% else %}A shared space for your team to talk, share work, and movethings forward.+ {% endif %}</p>{% endif %}<table@@ -230,7 +246,7 @@text-decoration: none;mso-padding-alt: 0;"- >Join channel</a+ >{% if is_direct_message %}View message{% else %}Join channel{% endif %}</a></td></tr>diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.mdindex e6670af385..8730945199 100644--- a/docs/AGENT_GUIDE/channels.md+++ b/docs/AGENT_GUIDE/channels.md@@ -10,6 +10,13 @@Team channels are always discoverable to the team. Private channels can only be viewed or joined by invitation. A DM is a channel between two users.An external email can be selected as a channel participant. For an unregistered recipient, clicking `Add` sends an email invite.+The first message in a DM to an unregistered recipient sends an email saying+`<sender email> sent you a message on Macro`, with the message and a **View message**+button leading to signup. It must not invite the recipient to `#<their own name>`.+Named-channel invites still show `#<channel name>` and **Join channel**.+Verify both emails in local Mailpit using distinct, unregistered test addresses;+repeat with a plus-addressed DM recipient to check the email-name fallback.+## Imported Slack historyImport starts from the **Import from Slack** chip below the Chat sidebar tabs,diff --git a/packages/sdk/generated/notification/types.gen.ts b/packages/sdk/generated/notification/types.gen.tsindex 5437733a4a..f92061b1fe 100644--- a/packages/sdk/generated/notification/types.gen.ts+++ b/packages/sdk/generated/notification/types.gen.ts@@ -252,6 +252,11 @@ export type ChannelInviteMetadata = {* The user who sent the invitation*/invitedBy: string;+ /**+ * Whether this is a direct message rather than a channel invitation.+ * Older notification payloads retain channel-invitation wording.+ */+ isDirectMessage?: boolean;/*** Message content to show in the invite email, when the invite was triggered by a message.*/diff --git a/packages/sdk/specs/notification.json b/packages/sdk/specs/notification.jsonindex e1f34e9b3d..52207c5ba2 100644--- a/packages/sdk/specs/notification.json+++ b/packages/sdk/specs/notification.json@@ -1365,6 +1365,10 @@"type": "string","description": "The user who sent the invitation"},+ "isDirectMessage": {+ "type": "boolean",+ "description": "Whether this is a direct message rather than a channel invitation.\nOlder notification payloads retain channel-invitation wording."+ },"messageContent": {"type": ["string", "null"],"description": "Message content to show in the invite email, when the invite was triggered by a message."