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.

feat(bot): add channel notifications for bot messages (#3934)

Will Hutchinsona7e55b91c7bd
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/channelMentionMetadataAllOf.ts b/js/app/packages/service-clients/service-notification/generated/schemas/channelMentionMetadataAllOf.ts
index 845977dc79..b4aa8c7aa6 100644
--- a/js/app/packages/service-clients/service-notification/generated/schemas/channelMentionMetadataAllOf.ts
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/channelMentionMetadataAllOf.ts
@@ -4,6 +4,7 @@
* notification_service
* OpenAPI spec version: 0.1.0
*/
+import type { ChannelMentionMetadataAllOfSenderDisplayName } from './channelMentionMetadataAllOfSenderDisplayName';
import type { ChannelMentionMetadataAllOfSenderProfilePictureUrl } from './channelMentionMetadataAllOfSenderProfilePictureUrl';
import type { ChannelMentionMetadataAllOfThreadId } from './channelMentionMetadataAllOfThreadId';
@@ -12,6 +13,8 @@ export type ChannelMentionMetadataAllOf = {
messageContent: string;
/** The message you were mentioned in */
messageId: string;
+ /** Display name for non-user senders such as bots */
+ senderDisplayName?: ChannelMentionMetadataAllOfSenderDisplayName;
senderProfilePictureUrl?: ChannelMentionMetadataAllOfSenderProfilePictureUrl;
/** the id of the thread */
threadId?: ChannelMentionMetadataAllOfThreadId;
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/channelMentionMetadataAllOfSenderDisplayName.ts b/js/app/packages/service-clients/service-notification/generated/schemas/channelMentionMetadataAllOfSenderDisplayName.ts
new file mode 100644
index 0000000000..d317dde7f5
--- /dev/null
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/channelMentionMetadataAllOfSenderDisplayName.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Display name for non-user senders such as bots
+ */
+export type ChannelMentionMetadataAllOfSenderDisplayName = string | null;
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/channelMessageSendMetadataAllOf.ts b/js/app/packages/service-clients/service-notification/generated/schemas/channelMessageSendMetadataAllOf.ts
index 8c7aec2bd1..b1a01f88d2 100644
--- a/js/app/packages/service-clients/service-notification/generated/schemas/channelMessageSendMetadataAllOf.ts
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/channelMessageSendMetadataAllOf.ts
@@ -4,6 +4,8 @@
* notification_service
* OpenAPI spec version: 0.1.0
*/
+import type { ChannelMessageSendMetadataAllOfSender } from './channelMessageSendMetadataAllOfSender';
+import type { ChannelMessageSendMetadataAllOfSenderDisplayName } from './channelMessageSendMetadataAllOfSenderDisplayName';
import type { ChannelMessageSendMetadataAllOfSenderProfilePictureUrl } from './channelMessageSendMetadataAllOfSenderProfilePictureUrl';
export type ChannelMessageSendMetadataAllOf = {
@@ -11,7 +13,9 @@ export type ChannelMessageSendMetadataAllOf = {
messageContent?: string;
/** The message id */
messageId: string;
- /** The user who sent the message */
- sender: string;
+ /** The user who sent the message, when sent by a user */
+ sender?: ChannelMessageSendMetadataAllOfSender;
+ /** Display name for non-user senders such as bots */
+ senderDisplayName?: ChannelMessageSendMetadataAllOfSenderDisplayName;
senderProfilePictureUrl?: ChannelMessageSendMetadataAllOfSenderProfilePictureUrl;
};
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/channelMessageSendMetadataAllOfSender.ts b/js/app/packages/service-clients/service-notification/generated/schemas/channelMessageSendMetadataAllOfSender.ts
new file mode 100644
index 0000000000..3e0c7973cb
--- /dev/null
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/channelMessageSendMetadataAllOfSender.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The user who sent the message, when sent by a user
+ */
+export type ChannelMessageSendMetadataAllOfSender = string | null;
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/channelMessageSendMetadataAllOfSenderDisplayName.ts b/js/app/packages/service-clients/service-notification/generated/schemas/channelMessageSendMetadataAllOfSenderDisplayName.ts
new file mode 100644
index 0000000000..b0da89fb42
--- /dev/null
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/channelMessageSendMetadataAllOfSenderDisplayName.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Display name for non-user senders such as bots
+ */
+export type ChannelMessageSendMetadataAllOfSenderDisplayName = string | null;
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/channelReplyMetadataAllOf.ts b/js/app/packages/service-clients/service-notification/generated/schemas/channelReplyMetadataAllOf.ts
index 6b60bccd9f..4cf2c907ac 100644
--- a/js/app/packages/service-clients/service-notification/generated/schemas/channelReplyMetadataAllOf.ts
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/channelReplyMetadataAllOf.ts
@@ -4,19 +4,23 @@
* notification_service
* OpenAPI spec version: 0.1.0
*/
+import type { ChannelReplyMetadataAllOfSenderDisplayName } from './channelReplyMetadataAllOfSenderDisplayName';
import type { ChannelReplyMetadataAllOfSenderProfilePictureUrl } from './channelReplyMetadataAllOfSenderProfilePictureUrl';
import type { ChannelReplyMetadataAllOfThreadParentSenderId } from './channelReplyMetadataAllOfThreadParentSenderId';
+import type { ChannelReplyMetadataAllOfUserId } from './channelReplyMetadataAllOfUserId';
export type ChannelReplyMetadataAllOf = {
/** The message content */
messageContent: string;
/** The id of the new message */
messageId: string;
+ /** Display name for non-user senders such as bots */
+ senderDisplayName?: ChannelReplyMetadataAllOfSenderDisplayName;
senderProfilePictureUrl?: ChannelReplyMetadataAllOfSenderProfilePictureUrl;
/** The id of the thread that has the reply */
threadId: string;
/** The user who sent the root message of the thread */
threadParentSenderId?: ChannelReplyMetadataAllOfThreadParentSenderId;
- /** The sender id of the reply */
- userId: string;
+ /** The sender id of the reply, when sent by a user */
+ userId?: ChannelReplyMetadataAllOfUserId;
};
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/channelReplyMetadataAllOfSenderDisplayName.ts b/js/app/packages/service-clients/service-notification/generated/schemas/channelReplyMetadataAllOfSenderDisplayName.ts
new file mode 100644
index 0000000000..381ec57ab5
--- /dev/null
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/channelReplyMetadataAllOfSenderDisplayName.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Display name for non-user senders such as bots
+ */
+export type ChannelReplyMetadataAllOfSenderDisplayName = string | null;
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/channelReplyMetadataAllOfUserId.ts b/js/app/packages/service-clients/service-notification/generated/schemas/channelReplyMetadataAllOfUserId.ts
new file mode 100644
index 0000000000..6d4e6c7ed0
--- /dev/null
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/channelReplyMetadataAllOfUserId.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The sender id of the reply, when sent by a user
+ */
+export type ChannelReplyMetadataAllOfUserId = string | null;
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/index.ts b/js/app/packages/service-clients/service-notification/generated/schemas/index.ts
index c090b471e2..c2be2f2162 100644
--- a/js/app/packages/service-clients/service-notification/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/index.ts
@@ -18,15 +18,20 @@ export * from './channelInviteMetadataMessageContent';
export * from './channelInviteMetadataSenderProfilePictureUrl';
export * from './channelMentionMetadata';
export * from './channelMentionMetadataAllOf';
+export * from './channelMentionMetadataAllOfSenderDisplayName';
export * from './channelMentionMetadataAllOfSenderProfilePictureUrl';
export * from './channelMentionMetadataAllOfThreadId';
export * from './channelMessageSendMetadata';
export * from './channelMessageSendMetadataAllOf';
+export * from './channelMessageSendMetadataAllOfSender';
+export * from './channelMessageSendMetadataAllOfSenderDisplayName';
export * from './channelMessageSendMetadataAllOfSenderProfilePictureUrl';
export * from './channelReplyMetadata';
export * from './channelReplyMetadataAllOf';
+export * from './channelReplyMetadataAllOfSenderDisplayName';
export * from './channelReplyMetadataAllOfSenderProfilePictureUrl';
export * from './channelReplyMetadataAllOfThreadParentSenderId';
+export * from './channelReplyMetadataAllOfUserId';
export * from './channelType';
export * from './commentedOnDocumentMetadata';
export * from './commentedOnDocumentMetadataFileType';
diff --git a/js/app/packages/service-clients/service-notification/generated/zod.ts b/js/app/packages/service-clients/service-notification/generated/zod.ts
index e6e5a39e36..fce03e6f17 100644
--- a/js/app/packages/service-clients/service-notification/generated/zod.ts
+++ b/js/app/packages/service-clients/service-notification/generated/zod.ts
@@ -171,6 +171,12 @@ export const listTypedNotificationsResponse = zod
messageId: zod
.string()
.describe('The message you were mentioned in'),
+ senderDisplayName: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Display name for non-user senders such as bots'
+ ),
senderProfilePictureUrl: zod.string().nullish(),
threadId: zod
.string()
@@ -204,6 +210,12 @@ export const listTypedNotificationsResponse = zod
messageId: zod
.string()
.describe('The message you were mentioned in'),
+ senderDisplayName: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Display name for non-user senders such as bots'
+ ),
senderProfilePictureUrl: zod.string().nullish(),
threadId: zod
.string()
@@ -415,7 +427,16 @@ export const listTypedNotificationsResponse = zod
messageId: zod.string().describe('The message id'),
sender: zod
.string()
- .describe('The user who sent the message'),
+ .nullish()
+ .describe(
+ 'The user who sent the message, when sent by a user'
+ ),
+ senderDisplayName: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Display name for non-user senders such as bots'
+ ),
senderProfilePictureUrl: zod.string().nullish(),
})
),
@@ -445,6 +466,12 @@ export const listTypedNotificationsResponse = zod
messageId: zod
.string()
.describe('The id of the new message'),
+ senderDisplayName: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Display name for non-user senders such as bots'
+ ),
senderProfilePictureUrl: zod.string().nullish(),
threadId: zod
.string()
@@ -459,7 +486,10 @@ export const listTypedNotificationsResponse = zod
),
userId: zod
.string()
- .describe('The sender id of the reply'),
+ .nullish()
+ .describe(
+ 'The sender id of the reply, when sent by a user'
+ ),
})
),
tag: zod.enum(['channel_message_reply']),
@@ -794,6 +824,12 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zod
messageId: zod
.string()
.describe('The message you were mentioned in'),
+ senderDisplayName: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Display name for non-user senders such as bots'
+ ),
senderProfilePictureUrl: zod.string().nullish(),
threadId: zod
.string()
@@ -827,6 +863,12 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zod
messageId: zod
.string()
.describe('The message you were mentioned in'),
+ senderDisplayName: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Display name for non-user senders such as bots'
+ ),
senderProfilePictureUrl: zod.string().nullish(),
threadId: zod
.string()
@@ -1038,7 +1080,16 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zod
messageId: zod.string().describe('The message id'),
sender: zod
.string()
- .describe('The user who sent the message'),
+ .nullish()
+ .describe(
+ 'The user who sent the message, when sent by a user'
+ ),
+ senderDisplayName: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Display name for non-user senders such as bots'
+ ),
senderProfilePictureUrl: zod.string().nullish(),
})
),
@@ -1068,6 +1119,12 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zod
messageId: zod
.string()
.describe('The id of the new message'),
+ senderDisplayName: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Display name for non-user senders such as bots'
+ ),
senderProfilePictureUrl: zod.string().nullish(),
threadId: zod
.string()
@@ -1082,7 +1139,10 @@ export const bulkGetTypedNotificationsByEventItemIdsResponse = zod
),
userId: zod
.string()
- .describe('The sender id of the reply'),
+ .nullish()
+ .describe(
+ 'The sender id of the reply, when sent by a user'
+ ),
})
),
tag: zod.enum(['channel_message_reply']),
@@ -1411,6 +1471,12 @@ export const getTypedNotificationsByEventItemIdResponse = zod
messageId: zod
.string()
.describe('The message you were mentioned in'),
+ senderDisplayName: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Display name for non-user senders such as bots'
+ ),
senderProfilePictureUrl: zod.string().nullish(),
threadId: zod
.string()
@@ -1444,6 +1510,12 @@ export const getTypedNotificationsByEventItemIdResponse = zod
messageId: zod
.string()
.describe('The message you were mentioned in'),
+ senderDisplayName: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Display name for non-user senders such as bots'
+ ),
senderProfilePictureUrl: zod.string().nullish(),
threadId: zod
.string()
@@ -1655,7 +1727,16 @@ export const getTypedNotificationsByEventItemIdResponse = zod
messageId: zod.string().describe('The message id'),
sender: zod
.string()
- .describe('The user who sent the message'),
+ .nullish()
+ .describe(
+ 'The user who sent the message, when sent by a user'
+ ),
+ senderDisplayName: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Display name for non-user senders such as bots'
+ ),
senderProfilePictureUrl: zod.string().nullish(),
})
),
@@ -1685,6 +1766,12 @@ export const getTypedNotificationsByEventItemIdResponse = zod
messageId: zod
.string()
.describe('The id of the new message'),
+ senderDisplayName: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Display name for non-user senders such as bots'
+ ),
senderProfilePictureUrl: zod.string().nullish(),
threadId: zod
.string()
@@ -1699,7 +1786,10 @@ export const getTypedNotificationsByEventItemIdResponse = zod
),
userId: zod
.string()
- .describe('The sender id of the reply'),
+ .nullish()
+ .describe(
+ 'The sender id of the reply, when sent by a user'
+ ),
})
),
tag: zod.enum(['channel_message_reply']),
@@ -2037,6 +2127,12 @@ export const getTypedNotificationByIdResponse = zod
messageId: zod
.string()
.describe('The message you were mentioned in'),
+ senderDisplayName: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Display name for non-user senders such as bots'
+ ),
senderProfilePictureUrl: zod.string().nullish(),
threadId: zod
.string()
@@ -2068,6 +2164,12 @@ export const getTypedNotificationByIdResponse = zod
messageId: zod
.string()
.describe('The message you were mentioned in'),
+ senderDisplayName: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Display name for non-user senders such as bots'
+ ),
senderProfilePictureUrl: zod.string().nullish(),
threadId: zod
.string()
@@ -2261,7 +2363,16 @@ export const getTypedNotificationByIdResponse = zod
messageId: zod.string().describe('The message id'),
sender: zod
.string()
- .describe('The user who sent the message'),
+ .nullish()
+ .describe(
+ 'The user who sent the message, when sent by a user'
+ ),
+ senderDisplayName: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Display name for non-user senders such as bots'
+ ),
senderProfilePictureUrl: zod.string().nullish(),
})
),
@@ -2289,6 +2400,12 @@ export const getTypedNotificationByIdResponse = zod
messageId: zod
.string()
.describe('The id of the new message'),
+ senderDisplayName: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Display name for non-user senders such as bots'
+ ),
senderProfilePictureUrl: zod.string().nullish(),
threadId: zod
.string()
@@ -2299,7 +2416,12 @@ export const getTypedNotificationByIdResponse = zod
.describe(
'The user who sent the root message of the thread'
),
- userId: zod.string().describe('The sender id of the reply'),
+ userId: zod
+ .string()
+ .nullish()
+ .describe(
+ 'The sender id of the reply, when sent by a user'
+ ),
})
),
tag: zod.enum(['channel_message_reply']),
diff --git a/js/app/packages/service-clients/service-notification/openapi.json b/js/app/packages/service-clients/service-notification/openapi.json
index c9b580fbd5..19e336a25b 100644
--- a/js/app/packages/service-clients/service-notification/openapi.json
+++ b/js/app/packages/service-clients/service-notification/openapi.json
@@ -1143,6 +1143,10 @@
"type": "string",
"description": "The message you were mentioned in"
},
+ "senderDisplayName": {
+ "type": ["string", "null"],
+ "description": "Display name for non-user senders such as bots"
+ },
"senderProfilePictureUrl": {
"type": ["string", "null"]
},
@@ -1161,7 +1165,7 @@
},
{
"type": "object",
- "required": ["sender", "messageId"],
+ "required": ["messageId"],
"properties": {
"messageContent": {
"type": "string",
@@ -1172,8 +1176,12 @@
"description": "The message id"
},
"sender": {
- "type": "string",
- "description": "The user who sent the message"
+ "type": ["string", "null"],
+ "description": "The user who sent the message, when sent by a user"
+ },
+ "senderDisplayName": {
+ "type": ["string", "null"],
+ "description": "Display name for non-user senders such as bots"
},
"senderProfilePictureUrl": {
"type": ["string", "null"]
@@ -1189,7 +1197,7 @@
},
{
"type": "object",
- "required": ["threadId", "messageId", "userId", "messageContent"],
+ "required": ["threadId", "messageId", "messageContent"],
"properties": {
"messageContent": {
"type": "string",
@@ -1199,6 +1207,10 @@
"type": "string",
"description": "The id of the new message"
},
+ "senderDisplayName": {
+ "type": ["string", "null"],
+ "description": "Display name for non-user senders such as bots"
+ },
"senderProfilePictureUrl": {
"type": ["string", "null"]
},
@@ -1211,8 +1223,8 @@
"description": "The user who sent the root message of the thread"
},
"userId": {
- "type": "string",
- "description": "The sender id of the reply"
+ "type": ["string", "null"],
+ "description": "The sender id of the reply, when sent by a user"
}
}
}
diff --git a/rust/cloud-storage/channels/src/domain/side_effects.rs b/rust/cloud-storage/channels/src/domain/side_effects.rs
index a030c5378a..2ec06dda14 100644
--- a/rust/cloud-storage/channels/src/domain/side_effects.rs
+++ b/rust/cloud-storage/channels/src/domain/side_effects.rs
@@ -119,6 +119,36 @@ pub enum ChannelRealtimeEffect {
},
}
+/// The sender of a channel message for notification purposes.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum NotificationSender {
+ /// A user sender.
+ User(MacroUserIdStr<'static>),
+ /// A bot sender resolved to its public display name.
+ Bot {
+ /// Bot display name.
+ name: String,
+ },
+}
+
+impl NotificationSender {
+ /// The sender's user id, when the sender is a user.
+ pub fn as_user(&self) -> Option<&MacroUserIdStr<'static>> {
+ match self {
+ NotificationSender::User(id) => Some(id),
+ NotificationSender::Bot { .. } => None,
+ }
+ }
+
+ /// The sender's display name, when the sender is a bot.
+ pub fn display_name(&self) -> Option<&str> {
+ match self {
+ NotificationSender::User(_) => None,
+ NotificationSender::Bot { name } => Some(name),
+ }
+ }
+}
+
/// Shared channel-message notification payload.
#[derive(Debug, Clone)]
pub struct ChannelMentionNotification {
@@ -136,8 +166,8 @@ pub struct ChannelMentionNotification {
pub metadata: ChannelMetadata,
/// Optional sender profile picture URL.
pub sender_profile_picture_url: Option<String>,
- /// Sender user id.
- pub sender_id: MacroUserIdStr<'static>,
+ /// Message sender.
+ pub sender: NotificationSender,
}
/// Metadata for a mentioned document.
@@ -189,8 +219,8 @@ pub enum ChannelNotificationEffect {
thread_id: Uuid,
/// Reply message id.
message_id: Uuid,
- /// Sender user id.
- sender_id: MacroUserIdStr<'static>,
+ /// Message sender.
+ sender: NotificationSender,
/// Reply body.
message_content: String,
/// Whether the reply has attachments.
@@ -210,8 +240,8 @@ pub enum ChannelNotificationEffect {
channel_id: Uuid,
/// Message id.
message_id: Uuid,
- /// Sender user id.
- sender_id: MacroUserIdStr<'static>,
+ /// Message sender.
+ sender: NotificationSender,
/// Message body.
message_content: String,
/// Whether the message has attachments.
@@ -537,7 +567,7 @@ where
self.publish_realtime(ChannelRealtimeEffect::Message {
recipients: recipients.clone(),
message: message.clone(),
- bot_profile,
+ bot_profile: bot_profile.clone(),
nonce: nonce.clone(),
})
.await;
@@ -555,17 +585,15 @@ where
self.search.index_message(channel_id, message.id).await;
self.dispatch_bot_triggers(channel_id, &message, &mentions);
- if message.sender_id.is_bot() {
- return;
- }
- self.send_message_posted_notifications(
+ self.send_message_posted_notifications(PostedMessageNotificationInputs {
channel_id,
metadata,
participants,
message,
mentions,
has_attachments,
- )
+ bot_profile,
+ })
.await;
}
@@ -591,17 +619,34 @@ where
}
}
- async fn send_message_posted_notifications(
- &self,
- channel_id: Uuid,
- metadata: ChannelMetadata,
- participants: Vec<ChannelParticipant>,
- message: MutatedMessage,
- mentions: Vec<SimpleMention>,
- has_attachments: bool,
- ) {
- let Some(sender_id) = message.sender_id.as_user().cloned() else {
- return;
+ async fn send_message_posted_notifications(&self, inputs: PostedMessageNotificationInputs) {
+ let PostedMessageNotificationInputs {
+ channel_id,
+ metadata,
+ participants,
+ message,
+ mentions,
+ has_attachments,
+ bot_profile,
+ } = inputs;
+ let resolved_sender = match &message.sender_id {
+ Sender::User(user_id) => ResolvedNotificationSender {
+ sender: NotificationSender::User(user_id.clone()),
+ profile_picture_url: self
+ .context
+ .get_sender_profile_picture_url(user_id.clone())
+ .await,
+ },
+ Sender::Bot(bot_id) => match bot_profile {
+ Some(profile) => ResolvedNotificationSender {
+ sender: NotificationSender::Bot { name: profile.name },
+ profile_picture_url: profile.avatar_url,
+ },
+ None => {
+ tracing::warn!(bot_id = %bot_id, "missing bot profile, skipping message notifications");
+ return;
+ }
+ },
};
let context = match self
.build_posted_message_context(
@@ -609,7 +654,7 @@ where
metadata,
&participants,
&message,
- sender_id,
+ resolved_sender,
mentions,
)
.await
@@ -635,7 +680,10 @@ where
&context,
)
.await;
- } else if context.is_first_top_level_message {
+ } else if context.is_first_top_level_message && context.sender.as_user().is_some() {
+ // Bot first messages fall through to a regular channel-message
+ // notification; invites (which can email unregistered users) are
+ // only sent on behalf of user senders.
self.send_first_message_invites(channel_id, &message, context)
.await;
} else {
@@ -650,16 +698,20 @@ where
metadata: ChannelMetadata,
participants: &[ChannelParticipant],
message: &MutatedMessage,
- sender_id: MacroUserIdStr<'static>,
+ resolved_sender: ResolvedNotificationSender,
mentions: Vec<SimpleMention>,
) -> anyhow::Result<PostedMessageNotificationContext> {
+ let ResolvedNotificationSender {
+ sender,
+ profile_picture_url: sender_profile_picture_url,
+ } = resolved_sender;
let message_count = self
.context
.get_channel_message_count(channel_id)
.await
.map_err(Into::into)?;
let is_first_top_level_message = message_count <= 1 && message.thread_id.is_none();
- let existing_user_ids = if is_first_top_level_message {
+ let existing_user_ids = if is_first_top_level_message && sender.as_user().is_some() {
let participant_ids: Vec<_> = participants
.iter()
.filter_map(|participant| MacroUserIdStr::parse_from_str(&participant.user_id).ok())
@@ -690,19 +742,17 @@ where
let thread_context = self
.load_thread_notification_context(message.thread_id)
.await;
- let sender_profile_picture_url = self
- .context
- .get_sender_profile_picture_url(sender_id.clone())
- .await;
-
- let excluded_user_ids = std::iter::once(sender_id.as_ref().to_string())
+ let excluded_user_ids = sender
+ .as_user()
+ .map(|user_id| user_id.as_ref().to_string())
+ .into_iter()
.chain(user_mentions.iter().cloned())
.collect::<Vec<_>>();
let recipients_without_sender = recipients_excluding(
participants
.iter()
.map(|participant| participant.user_id.as_str()),
- std::iter::once(sender_id.as_ref()),
+ sender.as_user().map(|user_id| user_id.as_ref()),
)
.collect();
let recipients_without_sender_and_mentions = recipients_excluding(
@@ -715,7 +765,7 @@ where
Ok(PostedMessageNotificationContext {
metadata,
- sender_id,
+ sender,
sender_profile_picture_url,
user_mentions,
document_mentions,
@@ -784,11 +834,11 @@ where
thread_id: message.thread_id,
metadata: context.metadata.clone(),
sender_profile_picture_url: context.sender_profile_picture_url.clone(),
- sender_id: context.sender_id.clone(),
+ sender: context.sender.clone(),
},
recipient_ids: recipients_excluding(
context.user_mentions.iter().map(String::as_str),
- std::iter::once(context.sender_id.as_ref()),
+ context.sender.as_user().map(|user_id| user_id.as_ref()),
)
.collect(),
})
@@ -816,7 +866,7 @@ where
thread_id: message.thread_id,
metadata: context.metadata.clone(),
sender_profile_picture_url: context.sender_profile_picture_url.clone(),
- sender_id: context.sender_id.clone(),
+ sender: context.sender.clone(),
},
document: document.clone(),
recipient_ids: context.recipients_without_sender.clone(),
@@ -842,7 +892,7 @@ where
channel_id,
thread_id,
message_id: message.id,
- sender_id: context.sender_id.clone(),
+ sender: context.sender.clone(),
message_content: message.content.clone(),
has_attachments,
thread_parent_sender_id: context.thread_context.parent_sender_id.clone(),
@@ -867,9 +917,12 @@ where
message: &MutatedMessage,
context: PostedMessageNotificationContext,
) {
+ let Some(invited_by_user_id) = context.sender.as_user().cloned() else {
+ return;
+ };
self.send_invite_notification(InviteNotificationRequest {
channel_id,
- invited_by_user_id: context.sender_id.clone(),
+ invited_by_user_id,
recipient_user_ids: context
.recipients_without_sender_and_mentions
.into_iter()
@@ -892,7 +945,7 @@ where
self.send_notification(ChannelNotificationEffect::ChannelMessage {
channel_id,
message_id: message.id,
- sender_id: context.sender_id.clone(),
+ sender: context.sender.clone(),
message_content: message.content.clone(),
has_attachments,
metadata: context.metadata.clone(),
@@ -967,9 +1020,26 @@ where
}
}
+/// Inputs for deriving notifications from a posted message.
+struct PostedMessageNotificationInputs {
+ channel_id: Uuid,
+ metadata: ChannelMetadata,
+ participants: Vec<ChannelParticipant>,
+ message: MutatedMessage,
+ mentions: Vec<SimpleMention>,
+ has_attachments: bool,
+ bot_profile: Option<BotSenderProfile>,
+}
+
+/// Sender identity and avatar resolved for notification delivery.
+struct ResolvedNotificationSender {
+ sender: NotificationSender,
+ profile_picture_url: Option<String>,
+}
+
struct PostedMessageNotificationContext {
metadata: ChannelMetadata,
- sender_id: MacroUserIdStr<'static>,
+ sender: NotificationSender,
sender_profile_picture_url: Option<String>,
user_mentions: Vec<String>,
document_mentions: Vec<ChannelDocumentMention>,
@@ -1056,6 +1126,22 @@ mod tests {
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 {
@@ -1086,7 +1172,7 @@ mod tests {
&self,
_thread_id: Uuid,
) -> Result<ThreadNotificationContext, Self::Err> {
- Ok(ThreadNotificationContext::default())
+ Ok(self.thread_context.clone())
}
async fn get_sender_profile_picture_url(
@@ -1097,10 +1183,7 @@ mod tests {
}
async fn get_bot_sender_profile(&self, _bot_id: BotId) -> Option<BotSenderProfile> {
- Some(BotSenderProfile {
- name: "Test Bot".to_string(),
- avatar_url: Some("https://example.com/bot.png".to_string()),
- })
+ self.bot_profile.clone()
}
}
@@ -1184,10 +1267,7 @@ mod tests {
let search = FakeSearch::default();
let contacts = FakeContacts::default();
let service = ChannelSideEffectService::new(
- FakeContext {
- message_count: 2,
- document_mentions: Vec::new(),
- },
+ FakeContext::default(),
realtime.clone(),
notifications.clone(),
search.clone(),
@@ -1261,6 +1341,7 @@ mod tests {
assert_eq!(notification_effects.len(), 1);
let ChannelNotificationEffect::ChannelMessage {
message_id: notified_message_id,
+ sender: notified_sender,
recipient_ids,
metadata,
..
@@ -1269,13 +1350,112 @@ mod tests {
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_keeps_realtime_and_search_but_skips_notifications() {
+ 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]");
@@ -1284,46 +1464,22 @@ mod tests {
let search = FakeSearch::default();
let service = ChannelSideEffectService::new(
FakeContext {
- message_count: 2,
- document_mentions: Vec::new(),
+ bot_profile: None,
+ ..FakeContext::default()
},
realtime.clone(),
notifications.clone(),
search.clone(),
FakeContacts::default(),
);
- let now = Utc::now();
service
- .handle(ChannelEvent::MessagePosted {
+ .handle(bot_message_posted_event(
channel_id,
- metadata: ChannelMetadata {
- channel_type: ChannelType::Private,
- channel_name: "Project".to_string(),
- },
- participants: vec![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::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,
- })
+ message_id,
+ None,
+ &[recipient.as_ref()],
+ ))
.await;
assert_eq!(realtime.effects.lock().unwrap().len(), 1);
@@ -1334,6 +1490,124 @@ mod tests {
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();
@@ -1342,10 +1616,7 @@ mod tests {
let recipient = user("[email protected]");
let (bot_trigger_sender, mut bot_trigger_receiver) = tokio::sync::mpsc::unbounded_channel();
let service = ChannelSideEffectService::new(
- FakeContext {
- message_count: 2,
- document_mentions: Vec::new(),
- },
+ FakeContext::default(),
FakeRealtime::default(),
FakeNotifications::default(),
FakeSearch::default(),
@@ -1417,13 +1688,13 @@ mod tests {
let notifications = FakeNotifications::default();
let service = ChannelSideEffectService::new(
FakeContext {
- message_count: 2,
document_mentions: vec![ChannelDocumentMention {
document_name: "Spec".to_string(),
owner: sender.clone(),
file_type: None,
sub_type: None,
}],
+ ..FakeContext::default()
},
FakeRealtime::default(),
notifications.clone(),
diff --git a/rust/cloud-storage/channels/src/outbound/notification_sender.rs b/rust/cloud-storage/channels/src/outbound/notification_sender.rs
index e8e069df19..6c3652dc4b 100644
--- a/rust/cloud-storage/channels/src/outbound/notification_sender.rs
+++ b/rust/cloud-storage/channels/src/outbound/notification_sender.rs
@@ -115,6 +115,7 @@ fn to_channel_mention_metadata(mention: ChannelMentionNotification) -> ChannelMe
message_id: mention.message_id.to_string(),
has_attachments: mention.has_attachments,
thread_id: mention.thread_id.map(|thread_id| thread_id.to_string()),
+ sender_display_name: mention.sender.display_name().map(ToOwned::to_owned),
common: to_common_metadata(mention.metadata),
sender_profile_picture_url: mention.sender_profile_picture_url,
}
@@ -133,14 +134,14 @@ where
recipient_ids,
} => {
let channel_id = mention.channel_id;
- let sender_id = mention.sender_id.clone();
+ let sender_id = mention.sender.as_user().cloned();
self.ingress
.send_notification(
SendNotificationRequestBuilder {
notification_entity: model_entity::EntityType::Channel
.with_entity_string(channel_id.to_string()),
notification: to_channel_mention_metadata(mention),
- sender_id: Some(sender_id),
+ sender_id,
recipient_ids,
}
.into_request()
@@ -156,7 +157,7 @@ where
recipient_ids,
} => {
let channel_id = mention.channel_id;
- let sender_id = mention.sender_id.clone();
+ let sender_id = mention.sender.as_user().cloned();
self.ingress
.send_notification(
SendNotificationRequestBuilder {
@@ -172,7 +173,7 @@ where
},
channel: to_channel_mention_metadata(mention),
},
- sender_id: Some(sender_id),
+ sender_id,
recipient_ids,
}
.into_request()
@@ -186,7 +187,7 @@ where
channel_id,
thread_id,
message_id,
- sender_id,
+ sender,
message_content,
has_attachments,
thread_parent_sender_id,
@@ -202,14 +203,15 @@ where
notification: ChannelReplyMetadata {
thread_id: thread_id.to_string(),
message_id: message_id.to_string(),
- user_id: sender_id.clone(),
+ user_id: sender.as_user().cloned(),
+ sender_display_name: sender.display_name().map(ToOwned::to_owned),
message_content,
has_attachments,
thread_parent_sender_id,
common: to_common_metadata(metadata),
sender_profile_picture_url,
},
- sender_id: Some(sender_id),
+ sender_id: sender.as_user().cloned(),
recipient_ids,
}
.into_request()
@@ -222,7 +224,7 @@ where
ChannelNotificationEffect::ChannelMessage {
channel_id,
message_id,
- sender_id,
+ sender,
message_content,
has_attachments,
metadata,
@@ -236,13 +238,14 @@ where
.with_entity_string(channel_id.to_string()),
notification: ChannelMessageSendMetadata {
message_id: message_id.to_string(),
- sender: sender_id.clone(),
+ sender: sender.as_user().cloned(),
+ sender_display_name: sender.display_name().map(ToOwned::to_owned),
message_content,
has_attachments,
common: to_common_metadata(metadata),
sender_profile_picture_url,
},
- sender_id: Some(sender_id),
+ sender_id: sender.as_user().cloned(),
recipient_ids,
}
.into_request()
diff --git a/rust/cloud-storage/model_notifications/src/metadata.rs b/rust/cloud-storage/model_notifications/src/metadata.rs
index 92ecb0676e..1f7c9d3d8f 100644
--- a/rust/cloud-storage/model_notifications/src/metadata.rs
+++ b/rust/cloud-storage/model_notifications/src/metadata.rs
@@ -190,11 +190,15 @@ pub struct CommonChannelMetadata {
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ChannelMessageSendMetadata {
- /// The user who sent the message
+ /// The user who sent the message, when sent by a user
+ #[serde(default)]
#[serde(alias = "invited_by")]
#[serde(alias = "invitedBy")]
- #[schema(value_type = String)]
- pub sender: MacroUserIdStr<'static>,
+ #[schema(value_type = Option<String>)]
+ pub sender: Option<MacroUserIdStr<'static>>,
+ /// Display name for non-user senders such as bots
+ #[serde(default)]
+ pub sender_display_name: Option<String>,
/// The content of the message
#[serde(default)]
#[serde(alias = "message_content")]
@@ -251,6 +255,9 @@ pub struct ChannelMentionMetadata {
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(alias = "thread_id")]
pub thread_id: Option<String>,
+ /// Display name for non-user senders such as bots
+ #[serde(default)]
+ pub sender_display_name: Option<String>,
#[serde(flatten)]
pub common: CommonChannelMetadata,
#[serde(default)]
@@ -266,10 +273,14 @@ pub struct ChannelReplyMetadata {
/// The id of the new message
#[serde(alias = "message_id")]
pub message_id: String,
- /// The sender id of the reply
+ /// The sender id of the reply, when sent by a user
+ #[serde(default)]
#[serde(alias = "user_id")]
- #[schema(value_type = String)]
- pub user_id: MacroUserIdStr<'static>,
+ #[schema(value_type = Option<String>)]
+ pub user_id: Option<MacroUserIdStr<'static>>,
+ /// Display name for non-user senders such as bots
+ #[serde(default)]
+ pub sender_display_name: Option<String>,
/// The message content
#[serde(alias = "message_content")]
pub message_content: String,
@@ -379,17 +390,15 @@ impl NotificationTitle for ChannelMentionMetadata {
&self,
sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
- let sender =
- sender_id.ok_or_else(|| report!("Expected sender id to exist for {:?}", &self))?;
+ let sender = sender_id
+ .map(|sender| sender.email_part().local_part().to_string())
+ .or_else(|| self.sender_display_name.clone())
+ .ok_or_else(|| report!("Expected sender id to exist for {:?}", &self))?;
Ok(match self.common.channel_type {
ChannelType::DirectMessage => {
- format!("{} mentioned you", sender.email_part().local_part())
+ format!("{sender} mentioned you")
}
- _ => format!(
- "{} mentioned you in #{}",
- sender.email_part().local_part(),
- self.common.channel_name
- ),
+ _ => format!("{sender} mentioned you in #{}", self.common.channel_name),
})
}
@@ -406,9 +415,10 @@ impl NotificationTitle for DocumentMentionMetadata {
&self,
sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
- let sender =
- sender_id.ok_or_else(|| report!("Expected sender id to exist for {:?}", &self))?;
- let sender = sender.0.email_part().email_str().to_string();
+ let sender = sender_id
+ .map(|sender| sender.0.email_part().email_str().to_string())
+ .or_else(|| self.channel.sender_display_name.clone())
+ .ok_or_else(|| report!("Expected sender id to exist for {:?}", &self))?;
Ok(format!("{sender} sent a document",))
}
@@ -426,13 +436,15 @@ impl NotificationTitle for ChannelMessageSendMetadata {
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
+ let sender = self
+ .sender
+ .as_ref()
+ .map(|sender| sender.email_part().local_part().to_string())
+ .or_else(|| self.sender_display_name.clone())
+ .ok_or_else(|| report!("Expected sender to exist for {:?}", &self))?;
let title = match self.common.channel_type {
- ChannelType::DirectMessage => self.sender.email_part().local_part().to_string(),
- _ => format!(
- "{} <{}>",
- self.sender.email_part().local_part(),
- self.common.channel_name
- ),
+ ChannelType::DirectMessage => sender,
+ _ => format!("{sender} <{}>", self.common.channel_name),
};
Ok(title)
}
@@ -474,10 +486,13 @@ impl NotificationTitle for ChannelReplyMetadata {
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
- Ok(format!(
- "Reply from {}",
- self.user_id.email_part().local_part()
- ))
+ let sender = self
+ .user_id
+ .as_ref()
+ .map(|sender| sender.email_part().local_part().to_string())
+ .or_else(|| self.sender_display_name.clone())
+ .ok_or_else(|| report!("Expected sender to exist for {:?}", &self))?;
+ Ok(format!("Reply from {sender}"))
}
fn format_body(
diff --git a/rust/cloud-storage/model_notifications/src/metadata/test.rs b/rust/cloud-storage/model_notifications/src/metadata/test.rs
index 36e36445c9..95b2ff2a5c 100644
--- a/rust/cloud-storage/model_notifications/src/metadata/test.rs
+++ b/rust/cloud-storage/model_notifications/src/metadata/test.rs
@@ -148,7 +148,8 @@ fn channel_reply_title_uses_reply_sender_from_metadata() {
let notification = ChannelReplyMetadata {
thread_id: Uuid::nil().to_string(),
message_id: Uuid::nil().to_string(),
- user_id: uid("macro|[email protected]"),
+ user_id: Some(uid("macro|[email protected]")),
+ sender_display_name: None,
message_content: "hello".to_string(),
has_attachments: false,
thread_parent_sender_id: None,
@@ -165,3 +166,131 @@ fn channel_reply_title_uses_reply_sender_from_metadata() {
assert_eq!(title, "Reply from reply.sender");
}
+
+fn bot_channel_message_send() -> ChannelMessageSendMetadata {
+ ChannelMessageSendMetadata {
+ sender: None,
+ sender_display_name: Some("Helper Bot".to_string()),
+ message_content: "hello".to_string(),
+ message_id: Uuid::nil().to_string(),
+ has_attachments: false,
+ common: CommonChannelMetadata {
+ channel_type: ChannelType::Team,
+ channel_name: "AI Team".to_string(),
+ },
+ sender_profile_picture_url: None,
+ }
+}
+
+#[test]
+fn channel_message_send_title_falls_back_to_bot_display_name() {
+ let notification = bot_channel_message_send();
+
+ assert_eq!(
+ notification.format_title(None).unwrap(),
+ "Helper Bot <AI Team>"
+ );
+
+ let dm = ChannelMessageSendMetadata {
+ common: CommonChannelMetadata {
+ channel_type: ChannelType::DirectMessage,
+ channel_name: String::new(),
+ },
+ ..bot_channel_message_send()
+ };
+ assert_eq!(dm.format_title(None).unwrap(), "Helper Bot");
+}
+
+#[test]
+fn channel_message_send_title_errors_without_any_sender() {
+ let notification = ChannelMessageSendMetadata {
+ sender_display_name: None,
+ ..bot_channel_message_send()
+ };
+
+ assert!(notification.format_title(None).is_err());
+}
+
+#[test]
+fn channel_reply_title_falls_back_to_bot_display_name() {
+ let notification = ChannelReplyMetadata {
+ thread_id: Uuid::nil().to_string(),
+ message_id: Uuid::nil().to_string(),
+ user_id: None,
+ sender_display_name: Some("Helper Bot".to_string()),
+ message_content: "hello".to_string(),
+ has_attachments: false,
+ thread_parent_sender_id: None,
+ common: CommonChannelMetadata {
+ channel_type: ChannelType::Team,
+ channel_name: "AI Team".to_string(),
+ },
+ sender_profile_picture_url: None,
+ };
+
+ let title = notification.format_title(None).unwrap();
+
+ assert_eq!(title, "Reply from Helper Bot");
+}
+
+#[test]
+fn channel_mention_title_falls_back_to_bot_display_name() {
+ let notification = ChannelMentionMetadata {
+ message_id: Uuid::nil().to_string(),
+ message_content: "hello".to_string(),
+ has_attachments: false,
+ thread_id: None,
+ sender_display_name: Some("Helper Bot".to_string()),
+ common: CommonChannelMetadata {
+ channel_type: ChannelType::Public,
+ channel_name: "general".to_string(),
+ },
+ sender_profile_picture_url: None,
+ };
+
+ let title = notification.format_title(None).unwrap();
+
+ assert_eq!(title, "Helper Bot mentioned you in #general");
+}
+
+#[test]
+fn channel_message_send_legacy_json_deserializes_with_required_sender() {
+ let legacy: ChannelMessageSendMetadata = serde_json::from_value(serde_json::json!({
+ "sender": "macro|[email protected]",
+ "messageId": "m1",
+ "messageContent": "hi",
+ "channelType": "public",
+ "channelName": "general"
+ }))
+ .unwrap();
+
+ assert_eq!(legacy.sender, Some(uid("macro|[email protected]")));
+ assert_eq!(legacy.sender_display_name, None);
+}
+
+#[test]
+fn channel_message_send_bot_json_serializes_explicit_null_sender_and_round_trips() {
+ let bot = bot_channel_message_send();
+
+ let value = serde_json::to_value(&bot).unwrap();
+
+ // The sender key must be present (as null) rather than skipped: older
+ // notification_service binaries permanently delete stored notifications
+ // whose metadata fails to deserialize with a `missing field sender` error.
+ assert!(value.get("sender").is_some_and(serde_json::Value::is_null));
+ assert_eq!(value["senderDisplayName"], "Helper Bot");
+
+ let event: crate::NotifEvent = serde_json::from_value(serde_json::json!({
+ "tag": "channel_message_send",
+ "content": value,
+ }))
+ .unwrap();
+ let crate::NotifEvent::ChannelMessageSend(round_trip) = event else {
+ panic!("expected channel_message_send variant");
+ };
+ assert_eq!(round_trip.sender, None);
+ assert_eq!(
+ round_trip.sender_display_name.as_deref(),
+ Some("Helper Bot")
+ );
+}
diff --git a/rust/cloud-storage/notification_sandbox/src/main.rs b/rust/cloud-storage/notification_sandbox/src/main.rs
index ce69f803f9..ce9d542d34 100644
--- a/rust/cloud-storage/notification_sandbox/src/main.rs
+++ b/rust/cloud-storage/notification_sandbox/src/main.rs
@@ -298,7 +298,8 @@ async fn run_notification_cycle<I: NotificationIngress>(
notification_entity: EntityType::Channel
.with_entity_string(uuid::Uuid::now_v7().to_string()),
notification: ChannelMessageSendMetadata {
- sender: MacroUserIdStr::try_from_email("[email protected]").unwrap(),
+ sender: Some(MacroUserIdStr::try_from_email("[email protected]").unwrap()),
+ sender_display_name: None,
message_content: "This is a message".to_string(),
message_id: uuid::Uuid::now_v7().to_string(),
has_attachments: false,
diff --git a/rust/cloud-storage/notification_service/src/api/user_notification/test.rs b/rust/cloud-storage/notification_service/src/api/user_notification/test.rs
index fbd6ef5d1f..fc2d6f0fa6 100644
--- a/rust/cloud-storage/notification_service/src/api/user_notification/test.rs
+++ b/rust/cloud-storage/notification_service/src/api/user_notification/test.rs
@@ -317,6 +317,7 @@ fn api_user_notification_and_conn_gateway_inner_notif_metadata_serialize_identic
message_content: "Hello @user".to_string(),
has_attachments: false,
thread_id: None,
+ sender_display_name: None,
common: model_notifications::CommonChannelMetadata {
channel_type: model_notifications::ChannelType::Public,
channel_name: "general".to_string(),
@@ -396,6 +397,7 @@ fn conn_gateway_inner_val_has_identical_serialization() {
message_content: "some data".to_string(),
has_attachments: false,
thread_id: Some("threadid".to_string()),
+ sender_display_name: None,
common: model_notifications::CommonChannelMetadata {
channel_type: model_notifications::ChannelType::Public,
channel_name: "my channel".to_string(),