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
mod access_request;
mod calendar_join_request;
mod channel_push;
pub use access_request::{
ChannelAccessRequestedMetadata, EntityAccessGrantedMetadata, EntityAccessRequestedMetadata,
RequestedAccessLevel,
};
pub use calendar_join_request::CalendarEventJoinRequestMetadata;
use chrono::{DateTime, NaiveDate, Utc};
pub use invite_email::{
ChannelInviteMetadata, ColleagueJoinedMacro, InviteToTeamMetadata, InviteePlan,
};
use macro_user_id::cowlike::CowLike;
use macro_user_id::{email::ReadEmailParts, user_id::MacroUserIdStr};
use mention_utils::parse::{ParsedXmlText, PlainTextFormatter, XmlFormatter};
use model_entity::Entity;
use model_entity::EntityType;
use model_owner::Owner;
pub use notification::domain::models::NotificationTitle;
use notification::domain::models::{
NotifCollapseKey, Notification, NotificationExtIos,
apple::{
APNSPushNotification, Alert, AlertDictionary, Aps, InterruptionLevel, PushNotificationData,
},
};
use rootcause::Report;
use rootcause::report;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use uuid::Uuid;
#[cfg(test)]
mod test;
#[derive(Debug, Clone, ToSchema, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AiResponseMetadata {
pub summary: String,
pub message_id: String,
}
/// The normalized lifecycle status for a GitHub pull request notification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ToSchema, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum GithubPrEventStatus {
/// The pull request is open.
Open,
/// The pull request is closed without being merged.
Closed,
/// The pull request is closed and merged.
Merged,
}
/// The GitHub pull request webhook action that triggered the notification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ToSchema, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum GithubPrEventAction {
/// The pull request was opened.
Opened,
/// The pull request was reopened.
Reopened,
/// The pull request was closed.
Closed,
}
/// The maximum number of characters kept by [`GithubPrNotificationCommon::snippet`].
const GITHUB_SNIPPET_MAX_CHARS: usize = 280;
/// Fields shared by every GitHub pull request notification type.
///
/// Embedded with `#[serde(flatten)]` so the wire shape keeps these keys at the
/// top level of the metadata object.
#[derive(Debug, Clone, PartialEq, Eq, ToSchema, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GithubPrNotificationCommon {
/// The source-specific internal foreign entity row id for this pull request.
pub foreign_entity_id: Uuid,
/// The external GitHub key, in `owner/repo/pull/number` format.
pub github_key: String,
/// The GitHub repository owner or organization.
pub owner: String,
/// The GitHub repository name.
pub repo: String,
/// The GitHub pull request number.
pub number: u64,
/// The public GitHub URL for the pull request.
pub url: String,
/// A compact label suitable for display in the UI.
pub display_name: String,
/// The GitHub pull request title. Falls back to `display_name` when GitHub has no title.
pub title: String,
/// The GitHub login for the sender, when available.
pub sender_github_login: Option<String>,
/// The stable GitHub numeric user id for the sender, serialized as a string.
pub sender_github_user_id: Option<String>,
/// The GitHub avatar URL for the sender, when available.
pub sender_github_avatar_url: Option<String>,
}
impl GithubPrNotificationCommon {
/// Build a required title value, falling back to the display name when GitHub has no title.
pub fn title_or_display_name(title: Option<String>, display_name: &str) -> String {
match title {
Some(title) if !title.trim().is_empty() => title,
_ => display_name.to_string(),
}
}
/// Trim and truncate free-form GitHub text (comment or review bodies) to a
/// display-friendly snippet, keeping character boundaries intact.
pub fn snippet(text: &str) -> String {
let trimmed = text.trim();
if trimmed.chars().count() <= GITHUB_SNIPPET_MAX_CHARS {
return trimmed.to_string();
}
let mut snippet: String = trimmed.chars().take(GITHUB_SNIPPET_MAX_CHARS).collect();
snippet.push('…');
snippet
}
/// The displayed actor is always the GitHub login, never the linked Macro
/// user (whose id still rides along as the notification sender).
fn actor_name(&self) -> Option<String> {
self.sender_github_login.clone()
}
/// The shared body format: the compact PR label, plus the PR title when it
/// adds information beyond the label.
fn format_body(&self) -> String {
if self.title == self.display_name {
return self.display_name.clone();
}
format!("{}: {}", self.display_name, self.title)
}
/// The shared body format with free-form text (a comment or review
/// snippet) in place of the PR title, when any is present.
fn format_body_with_text(&self, text: &str) -> String {
if text.trim().is_empty() {
return self.format_body();
}
format!("{}: {}", self.display_name, text.trim())
}
}
/// Metadata for a GitHub pull request lifecycle notification.
#[derive(Debug, Clone, PartialEq, Eq, ToSchema, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GithubPrStatusChanged {
/// Fields shared with the other GitHub pull request notifications.
#[serde(flatten)]
pub common: GithubPrNotificationCommon,
/// The current normalized pull request status.
pub status: GithubPrEventStatus,
/// The webhook action that triggered this notification.
pub action: GithubPrEventAction,
/// The prior normalized pull request status, when known.
pub previous_status: Option<GithubPrEventStatus>,
/// The pull request head branch, when available.
pub head_branch: Option<String>,
/// The pull request base branch, when available.
pub base_branch: Option<String>,
/// When the pull request was merged, when available.
pub merged_at: Option<DateTime<Utc>>,
}
impl GithubPrStatusChanged {
fn action_verb(&self) -> &'static str {
if self.status == GithubPrEventStatus::Merged {
return "merged";
}
match self.action {
GithubPrEventAction::Opened => "opened",
GithubPrEventAction::Reopened => "reopened",
GithubPrEventAction::Closed => "closed",
}
}
}
impl Notification for GithubPrStatusChanged {
const TYPE_NAME: &'static str = "github_pr_status_changed";
}
impl NotificationTitle for GithubPrStatusChanged {
fn format_title(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
let verb = self.action_verb();
let title = match self.common.actor_name() {
Some(actor) => format!("{actor} {verb} a pull request"),
None => format!("Pull request {verb}"),
};
Ok(title)
}
fn format_body(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
Ok(self.common.format_body())
}
}
/// The normalized result state for a GitHub pull request check-run notification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ToSchema, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum GithubPrCheckRunState {
/// The check run completed successfully.
Completed,
/// The check run completed with a failure-like conclusion.
Failed,
}
/// Metadata for a notification that a GitHub pull request check run completed.
#[derive(Debug, Clone, PartialEq, Eq, ToSchema, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GithubPrCheckRun {
/// Fields shared with the other GitHub pull request notifications.
#[serde(flatten)]
pub common: GithubPrNotificationCommon,
/// The GitHub numeric id of the check run.
pub check_run_github_id: u64,
/// The display name GitHub reported for the check run.
pub check_name: String,
/// The raw GitHub check run status.
pub check_status: String,
/// The raw GitHub check run conclusion.
pub conclusion: String,
/// The normalized notification state for this check run.
pub state: GithubPrCheckRunState,
/// The public GitHub URL for the check run.
pub check_url: String,
/// When GitHub marked the check run as complete.
pub completed_at: DateTime<Utc>,
}
impl GithubPrCheckRun {
fn state_verb(&self) -> &'static str {
match self.state {
GithubPrCheckRunState::Completed => "completed",
GithubPrCheckRunState::Failed => "failed",
}
}
fn display_check_name(&self) -> &str {
let check_name = self.check_name.trim();
if check_name.is_empty() {
return "Check";
}
check_name
}
}
impl Notification for GithubPrCheckRun {
const TYPE_NAME: &'static str = "github_pr_check_run";
}
impl NotificationTitle for GithubPrCheckRun {
fn format_title(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
Ok(format!(
"{} {} on a pull request",
self.display_check_name(),
self.state_verb()
))
}
fn format_body(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
Ok(self.common.format_body())
}
}
/// Metadata for a notification that the user's review was requested on a GitHub pull request.
#[derive(Debug, Clone, PartialEq, Eq, ToSchema, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GithubReviewRequested {
/// Fields shared with the other GitHub pull request notifications.
#[serde(flatten)]
pub common: GithubPrNotificationCommon,
/// The GitHub login of the requested reviewer, when available.
pub requested_reviewer_github_login: Option<String>,
/// The stable GitHub numeric user id of the requested reviewer, serialized as a string.
pub requested_reviewer_github_user_id: Option<String>,
}
impl Notification for GithubReviewRequested {
const TYPE_NAME: &'static str = "github_review_requested";
}
impl NotificationTitle for GithubReviewRequested {
fn format_title(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
let title = match self.common.actor_name() {
Some(actor) => format!("{actor} requested your review"),
None => "Your review was requested".to_string(),
};
Ok(title)
}
fn format_body(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
Ok(self.common.format_body())
}
}
/// The kind of GitHub comment that triggered a [`GithubPrComment`] notification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ToSchema, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GithubPrCommentKind {
/// A top-level conversation comment (GitHub `issue_comment`).
Issue,
/// An inline code review comment (GitHub `pull_request_review_comment`).
ReviewComment,
}
/// Metadata for a notification that a GitHub pull request was commented on.
#[derive(Debug, Clone, PartialEq, Eq, ToSchema, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GithubPrComment {
/// Fields shared with the other GitHub pull request notifications.
#[serde(flatten)]
pub common: GithubPrNotificationCommon,
/// The kind of comment that was posted.
pub comment_kind: GithubPrCommentKind,
/// The GitHub numeric id of the comment, when available.
pub comment_github_id: Option<u64>,
/// The public GitHub URL for the comment, when available.
pub comment_url: Option<String>,
/// A truncated excerpt of the comment body.
pub comment_snippet: String,
}
impl Notification for GithubPrComment {
const TYPE_NAME: &'static str = "github_pr_comment";
}
impl NotificationTitle for GithubPrComment {
fn format_title(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
let title = match self.common.actor_name() {
Some(actor) => format!("{actor} commented on a pull request"),
None => "New comment on a pull request".to_string(),
};
Ok(title)
}
fn format_body(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
Ok(self.common.format_body_with_text(&self.comment_snippet))
}
}
/// Where in a GitHub pull request the user was mentioned.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ToSchema, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GithubPrMentionLocation {
/// The pull request description.
PrBody,
/// A top-level conversation comment.
Comment,
/// A review summary body.
Review,
/// An inline code review comment.
ReviewComment,
}
/// Metadata for a notification that the user was mentioned on a GitHub pull request.
#[derive(Debug, Clone, PartialEq, Eq, ToSchema, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GithubPrMention {
/// Fields shared with the other GitHub pull request notifications.
#[serde(flatten)]
pub common: GithubPrNotificationCommon,
/// Where the mention appeared.
pub location: GithubPrMentionLocation,
/// The GitHub numeric id of the comment or review containing the mention, when available.
pub comment_github_id: Option<u64>,
/// The public GitHub URL for the text containing the mention, when available.
pub comment_url: Option<String>,
/// A truncated excerpt of the text containing the mention.
pub text_snippet: String,
}
impl Notification for GithubPrMention {
const TYPE_NAME: &'static str = "github_pr_mention";
}
impl NotificationTitle for GithubPrMention {
fn format_title(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
let title = match self.common.actor_name() {
Some(actor) => format!("{actor} mentioned you on a pull request"),
None => "You were mentioned on a pull request".to_string(),
};
Ok(title)
}
fn format_body(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
Ok(self.common.format_body_with_text(&self.text_snippet))
}
}
/// The state of a submitted GitHub pull request review.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ToSchema, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GithubPrReviewState {
/// The reviewer approved the pull request.
Approved,
/// The reviewer requested changes.
ChangesRequested,
/// The reviewer left a comment review without an approval decision.
Commented,
}
/// Metadata for a notification that a review was submitted on the user's GitHub pull request.
#[derive(Debug, Clone, PartialEq, Eq, ToSchema, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GithubPrReview {
/// Fields shared with the other GitHub pull request notifications.
#[serde(flatten)]
pub common: GithubPrNotificationCommon,
/// The GitHub numeric id of the review, when available.
pub review_github_id: Option<u64>,
/// The public GitHub URL for the review, when available.
pub review_url: Option<String>,
/// The review decision state.
pub state: GithubPrReviewState,
/// A truncated excerpt of the review body, when any was written.
pub review_snippet: Option<String>,
}
impl Notification for GithubPrReview {
const TYPE_NAME: &'static str = "github_pr_review";
}
impl NotificationTitle for GithubPrReview {
fn format_title(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
let actor = self.common.actor_name();
let title = match (self.state, actor) {
(GithubPrReviewState::Approved, Some(actor)) => {
format!("{actor} approved your pull request")
}
(GithubPrReviewState::Approved, None) => "Your pull request was approved".to_string(),
(GithubPrReviewState::ChangesRequested, Some(actor)) => {
format!("{actor} requested changes on your pull request")
}
(GithubPrReviewState::ChangesRequested, None) => {
"Changes were requested on your pull request".to_string()
}
(GithubPrReviewState::Commented, Some(actor)) => {
format!("{actor} reviewed your pull request")
}
(GithubPrReviewState::Commented, None) => "Your pull request was reviewed".to_string(),
};
Ok(title)
}
fn format_body(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
Ok(self
.common
.format_body_with_text(self.review_snippet.as_deref().unwrap_or_default()))
}
}
#[derive(Debug, Clone, Copy, ToSchema, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ChannelType {
#[serde(alias = "Public", alias = "public")]
Public,
#[serde(alias = "Private", alias = "private")]
Private,
#[serde(alias = "DirectMessage", alias = "direct_message")]
DirectMessage,
#[serde(alias = "Team", alias = "team")]
Team,
}
/// Common metadata for notifications on channels
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct CommonChannelMetadata {
// The type of the channel
#[serde(alias = "channel_type")]
pub channel_type: ChannelType,
// the name of the channel
#[serde(default)]
#[serde(alias = "channel_name")]
pub channel_name: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ChannelMessageSendMetadata {
/// The user who sent the message, when sent by a user
#[serde(default)]
#[serde(alias = "invited_by")]
#[serde(alias = "invitedBy")]
#[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")]
pub message_content: String,
/// The message id
#[serde(alias = "message_id")]
pub message_id: String,
/// Whether the message includes attachments.
#[serde(skip)]
pub has_attachments: bool,
#[serde(flatten)]
pub common: CommonChannelMetadata,
#[serde(default)]
pub sender_profile_picture_url: Option<String>,
}
/// Metadata for a reaction added to one of the recipient's channel messages.
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ChannelMessageReactionMetadata {
/// The reacted-to message id.
#[serde(alias = "message_id")]
pub message_id: String,
/// The thread root id when the reacted-to message is a reply.
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(alias = "thread_id")]
pub thread_id: Option<String>,
/// The reacted-to message content.
#[serde(alias = "message_content")]
pub message_content: String,
/// The emoji added by the reactor.
pub emoji: String,
#[serde(flatten)]
pub common: CommonChannelMetadata,
/// Optional reactor profile picture URL.
#[serde(default)]
pub sender_profile_picture_url: Option<String>,
}
/// Metadata for when a item is shared with a user
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ItemSharedMetadata {
/// List of user IDs that the item is shared with
#[serde(alias = "user_ids")]
pub user_ids: Vec<String>,
/// The type of item being shared
#[serde(alias = "item_type")]
pub item_type: EntityType,
/// The name/title of the shared item (optional)
#[serde(alias = "item_id")]
pub item_id: String,
/// The name/title of the shared item
#[serde(alias = "item_name")]
pub item_name: Option<String>,
#[serde(alias = "shared_by")]
#[schema(value_type = String)]
pub shared_by: MacroUserIdStr<'static>,
/// Permission level granted (read, write, admin, etc.)
#[serde(alias = "permission_level")]
pub permission_level: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ChannelMentionMetadata {
/// The message you were mentioned in
#[serde(alias = "message_id")]
pub message_id: String,
/// The message content
#[serde(alias = "message_content")]
pub message_content: String,
/// Whether the message includes attachments.
#[serde(skip)]
pub has_attachments: bool,
/// the id of the thread
#[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)]
pub sender_profile_picture_url: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ChannelReplyMetadata {
/// The id of the thread that has the reply
#[serde(alias = "thread_id")]
pub thread_id: String,
/// The id of the new message
#[serde(alias = "message_id")]
pub message_id: String,
/// The sender id of the reply, when sent by a user
#[serde(default)]
#[serde(alias = "user_id")]
#[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,
/// Whether the message includes attachments.
#[serde(skip)]
pub has_attachments: bool,
/// The user who sent the root message of the thread
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(alias = "thread_parent_sender_id")]
#[schema(value_type = Option<String>)]
pub thread_parent_sender_id: Option<MacroUserIdStr<'static>>,
#[serde(flatten)]
pub common: CommonChannelMetadata,
#[serde(default)]
pub sender_profile_picture_url: Option<String>,
}
/// The sub type of a document in a notification.
/// Serializes as `{ "type": "task" }` matching the storage service pattern.
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema, PartialEq, Eq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum NotificationDocumentSubType {
Task,
Snippet,
Skill,
InitiativeDescription,
}
/// Someone mentioned a document in a channel
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct DocumentMentionMetadata {
/// The name of the document
#[serde(alias = "document_name")]
pub document_name: String,
/// The owner of the document
#[schema(value_type = String)]
pub owner: Owner,
/// The file type of the document
#[serde(alias = "file_type")]
pub file_type: Option<String>,
/// The sub type of the document (e.g. task)
#[serde(alias = "sub_type")]
#[serde(default)]
pub sub_type: Option<NotificationDocumentSubType>,
#[serde(flatten)]
pub channel: ChannelMentionMetadata,
}
impl From<DocumentMentionMetadata> for serde_json::Value {
fn from(val: DocumentMentionMetadata) -> Self {
serde_json::to_value(val).unwrap()
}
}
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct NewEmailMetadata {
pub sender: Option<String>,
#[serde(alias = "to_email")]
pub to_email: String,
#[serde(alias = "thread_id")]
pub thread_id: String,
pub subject: String,
pub snippet: String,
}
/// Metadata for a notification that a linked inbox's grant has died and the
/// inbox must be reconnected. Fanned out to the inbox owner and every delegate,
/// since any of them holding the Google grant can restore sync.
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct InboxReauthRequiredMetadata {
/// The address of the inbox that needs to be reconnected.
#[serde(alias = "email_address")]
pub email_address: String,
}
impl notification::domain::models::Notification for InboxReauthRequiredMetadata {
const TYPE_NAME: &'static str = "inbox_reauth_required";
}
impl NotificationTitle for InboxReauthRequiredMetadata {
fn format_title(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
Ok(format!("Reconnect {}", self.email_address))
}
fn format_body(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
Ok(
"Sync stopped because the Google connection expired. Reconnect to restore it."
.to_string(),
)
}
}
impl notification::domain::models::Notification for NewEmailMetadata {
const TYPE_NAME: &'static str = "new_email";
}
impl NewEmailMetadata {
/// Lock-screen title: the sender's display name (or email), when present.
fn sender_line(&self) -> Option<&str> {
self.sender
.as_deref()
.map(str::trim)
.filter(|sender| !sender.is_empty())
}
}
impl NotificationTitle for NewEmailMetadata {
fn format_title(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
Ok(self
.sender_line()
.unwrap_or(self.subject.trim())
.to_string())
}
fn format_body(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
Ok(self.snippet.clone())
}
}
impl NotificationExtIos for NewEmailMetadata {
type NotifData = PushNotificationData;
fn collapse_key(&self, _entity: &Entity<'_>) -> NotifCollapseKey {
// Collapse on the thread so a new message replaces the unread
// lock-screen alert for that conversation.
NotifCollapseKey::new(Self::TYPE_NAME).append(&self.thread_id)
}
fn as_apns<'a>(
&self,
sender_id: Option<MacroUserIdStr<'a>>,
_entity: &Entity<'_>,
notification_id: Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
let mut apns = alert_apns(self, sender_id, notification_id, None).ok()?;
if let Some(Alert::Dictionary(alert)) = &mut apns.aps.alert {
let subject = self.subject.trim();
if self.sender_line().is_some() && !subject.is_empty() {
alert.subtitle = Some(subject.to_string());
}
}
apns.aps.thread_id = Some(self.thread_id.clone());
Some(apns)
}
}
impl notification::domain::models::Notification for AiResponseMetadata {
const TYPE_NAME: &'static str = "ai_response";
}
impl notification::domain::models::Notification for ChannelMessageSendMetadata {
const TYPE_NAME: &'static str = "channel_message_send";
}
impl notification::domain::models::Notification for ChannelMessageReactionMetadata {
const TYPE_NAME: &'static str = "channel_message_reaction";
}
impl notification::domain::models::Notification for ChannelMentionMetadata {
const TYPE_NAME: &'static str = "channel_mention";
}
impl notification::domain::models::Notification for ChannelReplyMetadata {
const TYPE_NAME: &'static str = "channel_message_reply";
}
impl notification::domain::models::Notification for DocumentMentionMetadata {
const TYPE_NAME: &'static str = "document_mention";
}
impl NotificationTitle for ChannelMentionMetadata {
fn format_title(
&self,
sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
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!("{sender} mentioned you")
}
_ => format!("{sender} mentioned you in #{}", self.common.channel_name),
})
}
fn format_body(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
parse_message_plain_text_or_attachment(&self.message_content, self.has_attachments)
}
}
impl NotificationTitle for DocumentMentionMetadata {
fn format_title(
&self,
sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
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))?;
let noun = match self.sub_type {
Some(NotificationDocumentSubType::Task) => "task",
_ => "document",
};
Ok(format!("{sender} sent a {noun}"))
}
fn format_body(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
let file_type_str = self.file_type.as_deref().unwrap_or("");
Ok(format!("{}.{}", self.document_name, file_type_str))
}
}
impl NotificationTitle for ChannelMessageSendMetadata {
fn format_title(
&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 => sender,
_ => format!("{sender} <{}>", self.common.channel_name),
};
Ok(title)
}
fn format_body(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
parse_message_plain_text_or_attachment(&self.message_content, self.has_attachments)
}
}
const CHANNEL_REACTION_EXCERPT_MAX_CHARS: usize = 80;
impl NotificationTitle for ChannelMessageReactionMetadata {
fn format_title(
&self,
sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
let sender = sender_id
.map(|sender| sender.email_part().local_part().to_string())
.ok_or_else(|| report!("Expected sender id to exist for {:?}", &self))?;
let message = parse_message_plain_text(&self.message_content)?
.split_whitespace()
.collect::<Vec<_>>()
.join(" ");
let excerpt: String = message
.chars()
.take(CHANNEL_REACTION_EXCERPT_MAX_CHARS)
.collect();
let suffix = if message.chars().count() > CHANNEL_REACTION_EXCERPT_MAX_CHARS {
"…"
} else {
""
};
Ok(format!(
"{sender} reacted with {} to “{excerpt}{suffix}”",
self.emoji
))
}
fn format_body(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
Ok(match self.common.channel_type {
ChannelType::DirectMessage => "Direct message".to_string(),
_ => format!("#{}", self.common.channel_name),
})
}
}
impl NotificationTitle for MentionedInDocumentCommentMetadata {
fn format_title(
&self,
sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
let sender = comment_sender_label(sender_id, self.sender_display_name.as_deref());
let title = match &self.file_type {
Some(ft) => format!("{sender} mentioned you in {}.{ft}", self.document_name),
None => format!("{sender} mentioned you in {}", self.document_name),
};
Ok(title)
}
fn format_body(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
parse_message_plain_text(&self.text)
}
}
impl NotificationTitle for ChannelReplyMetadata {
fn format_title(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
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(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
parse_message_plain_text_or_attachment(&self.message_content, self.has_attachments)
}
}
/// Metadata for when a user is assigned to a task
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct TaskAssignedMetadata {
/// The unique identifier of the task
#[serde(alias = "task_id")]
pub task_id: String,
/// The name of the task (optional)
#[serde(alias = "task_name")]
pub task_name: Option<String>,
/// The sub type of the backing document (task).
#[serde(alias = "sub_type")]
#[serde(default)]
pub sub_type: Option<NotificationDocumentSubType>,
/// The user who assigned the task
#[serde(alias = "assigned_by")]
#[schema(value_type = String)]
pub assigned_by: MacroUserIdStr<'static>,
#[serde(default)]
pub sender_profile_picture_url: Option<String>,
}
/// Helper to parse XML message content to plain text, returning None on failure.
fn parse_message_plain_text(content: &str) -> Result<String, Report> {
let parsed = ParsedXmlText::parse(content)?;
Ok(PlainTextFormatter::format_xml_text(parsed).0)
}
fn parse_message_plain_text_or_attachment(
content: &str,
has_attachments: bool,
) -> Result<String, Report> {
let mut text = parse_message_plain_text(content)?;
let attached_items = "[attached items]";
if has_attachments && text.trim().is_empty() {
return Ok(attached_items.to_string());
}
if has_attachments {
text.push('\n');
text.push_str(attached_items);
}
Ok(text)
}
/// Helper to create an alert-style APNS notification with title and body.
fn alert_apns<T: NotificationTitle>(
notif: &T,
sender_id: Option<MacroUserIdStr<'_>>,
notification_id: Uuid,
sender_profile_picture_url: Option<String>,
) -> Result<APNSPushNotification<PushNotificationData>, Report> {
let title = notif.format_title(sender_id.as_ref().map(CowLike::copied))?;
let body = notif.format_body(sender_id)?;
let mutable_content = if sender_profile_picture_url.is_some() {
Some(1)
} else {
None
};
Ok(APNSPushNotification {
aps: Aps {
alert: Some(notification::domain::models::apple::Alert::Dictionary(
AlertDictionary {
title: Some(title),
body: Some(body),
..Default::default()
},
)),
mutable_content,
..Default::default()
},
push_notification_data: PushNotificationData {
notification_id,
sender_profile_picture_url,
recipient_id: None,
navigation: None,
},
})
}
impl NotificationTitle for AiResponseMetadata {
fn format_title(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
Ok("AI Response".to_string())
}
fn format_body(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
Ok(self.summary.clone())
}
}
impl NotificationExtIos for AiResponseMetadata {
type NotifData = ::notification::domain::models::apple::PushNotificationData;
fn collapse_key(&self, _entity: &Entity<'_>) -> NotifCollapseKey {
NotifCollapseKey::new(&self.message_id)
}
fn as_apns<'a>(
&self,
sender_id: Option<MacroUserIdStr<'a>>,
_entity: &Entity<'_>,
notification_id: Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
alert_apns(self, sender_id, notification_id, None).ok()
}
}
impl NotificationExtIos for ChannelMessageSendMetadata {
type NotifData = ::notification::domain::models::apple::PushNotificationData;
fn collapse_key(&self, _entity: &Entity<'_>) -> NotifCollapseKey {
NotifCollapseKey::new(&self.message_id)
}
fn as_apns<'a>(
&self,
sender_id: Option<MacroUserIdStr<'a>>,
entity: &Entity<'_>,
notification_id: Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
let profile_pic = self.sender_profile_picture_url.clone();
channel_push::channel_apns(
self,
sender_id,
notification_id,
profile_pic,
entity,
&self.message_id,
None,
)
}
}
impl NotificationExtIos for ChannelMessageReactionMetadata {
type NotifData = ::notification::domain::models::apple::PushNotificationData;
fn collapse_key(&self, _entity: &Entity<'_>) -> NotifCollapseKey {
NotifCollapseKey::new(&self.message_id).append(&self.emoji)
}
fn as_apns<'a>(
&self,
sender_id: Option<MacroUserIdStr<'a>>,
entity: &Entity<'_>,
notification_id: Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
channel_push::channel_apns(
self,
sender_id,
notification_id,
self.sender_profile_picture_url.clone(),
entity,
&self.message_id,
self.thread_id.as_deref(),
)
}
}
impl NotificationExtIos for ChannelMentionMetadata {
type NotifData = ::notification::domain::models::apple::PushNotificationData;
fn collapse_key(&self, _entity: &Entity<'_>) -> NotifCollapseKey {
NotifCollapseKey::new(&self.message_id)
}
fn as_apns<'a>(
&self,
sender_id: Option<MacroUserIdStr<'a>>,
entity: &Entity<'_>,
notification_id: Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
let profile_pic = self.sender_profile_picture_url.clone();
channel_push::channel_apns(
self,
sender_id,
notification_id,
profile_pic,
entity,
&self.message_id,
self.thread_id.as_deref(),
)
}
}
impl NotificationExtIos for ChannelReplyMetadata {
type NotifData = ::notification::domain::models::apple::PushNotificationData;
fn collapse_key(&self, _entity: &Entity<'_>) -> NotifCollapseKey {
NotifCollapseKey::new(&self.message_id)
}
fn as_apns<'a>(
&self,
sender_id: Option<MacroUserIdStr<'a>>,
entity: &Entity<'_>,
notification_id: Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
let profile_pic = self.sender_profile_picture_url.clone();
channel_push::channel_apns(
self,
sender_id,
notification_id,
profile_pic,
entity,
&self.message_id,
Some(&self.thread_id),
)
}
}
impl NotificationExtIos for DocumentMentionMetadata {
type NotifData = ::notification::domain::models::apple::PushNotificationData;
fn collapse_key(&self, _entity: &Entity<'_>) -> NotifCollapseKey {
NotifCollapseKey::new(&self.channel.message_id)
}
fn as_apns<'a>(
&self,
sender_id: Option<MacroUserIdStr<'a>>,
entity: &Entity<'_>,
notification_id: Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
let profile_pic = self.channel.sender_profile_picture_url.clone();
channel_push::channel_apns(
self,
sender_id,
notification_id,
profile_pic,
entity,
&self.channel.message_id,
self.channel.thread_id.as_deref(),
)
}
}
impl notification::domain::models::Notification for TaskAssignedMetadata {
const TYPE_NAME: &'static str = "task_assigned";
}
impl NotificationTitle for TaskAssignedMetadata {
fn format_title(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
let email = self.assigned_by.email_part();
let sender = email.email_str();
Ok(format!("Task assigned by {sender}"))
}
fn format_body(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
let body = if let Some(ref task_name) = self.task_name {
format!("assigned you to {}", task_name)
} else {
"New Task".to_string()
};
Ok(body)
}
}
impl NotificationExtIos for TaskAssignedMetadata {
type NotifData = ::notification::domain::models::apple::PushNotificationData;
fn collapse_key(&self, entity: &Entity<'_>) -> NotifCollapseKey {
let entity_type: &'static str = entity.entity_type.into();
NotifCollapseKey::new(entity_type).append(&entity.entity_id)
}
fn as_apns<'a>(
&self,
sender_id: Option<MacroUserIdStr<'a>>,
_entity: &Entity<'_>,
notification_id: Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
let profile_pic = self.sender_profile_picture_url.clone();
alert_apns(self, sender_id, notification_id, profile_pic).ok()
}
}
/// Identity of a document comment or its thread. Comments written before the
/// shared message store carry the legacy numeric ids; comments in the shared
/// store carry the message and root UUIDs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
#[serde(untagged)]
pub enum CommentRef {
/// Legacy `Comment.id` or `Thread.id`.
Legacy(i64),
/// Message or root id in the shared message store.
Message(Uuid),
}
impl From<i64> for CommentRef {
fn from(id: i64) -> Self {
Self::Legacy(id)
}
}
impl From<Uuid> for CommentRef {
fn from(id: Uuid) -> Self {
Self::Message(id)
}
}
impl std::fmt::Display for CommentRef {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Legacy(id) => write!(f, "{id}"),
Self::Message(id) => write!(f, "{id}"),
}
}
}
/// Sender wording shared by the document comment notifications: the acting
/// user's email, then a bot's public name, then a generic agent label.
fn comment_sender_label(
sender_id: Option<MacroUserIdStr<'_>>,
sender_display_name: Option<&str>,
) -> String {
sender_id
.map(|id| id.0.email_part().email_str().to_owned())
.or_else(|| sender_display_name.map(str::to_owned))
.unwrap_or_else(|| "Agent".to_owned())
}
/// Notification sent when a user is mentioned in a document comment.
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct MentionedInDocumentCommentMetadata {
/// Public bot name when the author is an agent rather than a Macro user.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sender_display_name: Option<String>,
/// The name of the document.
pub document_name: String,
/// The owner of the document.
#[schema(value_type = String)]
pub owner: Owner,
/// The file type of the document.
pub file_type: Option<String>,
/// The sub type of the document (e.g. task).
#[serde(alias = "sub_type")]
#[serde(default)]
pub sub_type: Option<NotificationDocumentSubType>,
/// The mention ID.
pub mention_id: String,
/// the comment id
pub comment_id: CommentRef,
/// the thread id
pub thread_id: CommentRef,
/// the text of the comment
pub text: String,
#[serde(default)]
pub sender_profile_picture_url: Option<String>,
}
impl Notification for MentionedInDocumentCommentMetadata {
const TYPE_NAME: &'static str = "mentioned_in_document_comment";
}
impl NotificationExtIos for MentionedInDocumentCommentMetadata {
type NotifData = ::notification::domain::models::apple::PushNotificationData;
fn collapse_key(&self, entity: &Entity<'_>) -> NotifCollapseKey {
let entity_type: &'static str = entity.entity_type.into();
NotifCollapseKey::new(entity_type).append(&entity.entity_id)
}
fn as_apns<'a>(
&self,
sender_id: Option<MacroUserIdStr<'a>>,
_entity: &Entity<'_>,
notification_id: Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
let profile_pic = self.sender_profile_picture_url.clone();
alert_apns(self, sender_id, notification_id, profile_pic).ok()
}
}
/// Notification sent when someone replies to a document comment thread.
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct RepliedToDocumentCommentThreadMetadata {
/// Public bot name when the author is an agent rather than a Macro user.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sender_display_name: Option<String>,
/// The name of the document.
pub document_name: String,
/// The owner of the document.
#[schema(value_type = String)]
pub owner: Owner,
/// The file type of the document.
pub file_type: Option<String>,
/// The sub type of the document (e.g. task).
#[serde(alias = "sub_type")]
#[serde(default)]
pub sub_type: Option<NotificationDocumentSubType>,
/// the comment id
pub comment_id: CommentRef,
/// the thread id
pub thread_id: CommentRef,
/// the text of the comment
pub text: String,
#[serde(default)]
pub sender_profile_picture_url: Option<String>,
}
impl Notification for RepliedToDocumentCommentThreadMetadata {
const TYPE_NAME: &'static str = "replied_to_document_comment_thread";
}
impl NotificationTitle for RepliedToDocumentCommentThreadMetadata {
fn format_title(
&self,
sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
let sender = comment_sender_label(sender_id, self.sender_display_name.as_deref());
let title = match &self.file_type {
Some(ft) => format!("{sender} replied in {}.{ft}", self.document_name),
None => format!("{sender} replied in {}", self.document_name),
};
Ok(title)
}
fn format_body(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
parse_message_plain_text(&self.text)
}
}
impl NotificationExtIos for RepliedToDocumentCommentThreadMetadata {
type NotifData = ::notification::domain::models::apple::PushNotificationData;
fn collapse_key(&self, entity: &Entity<'_>) -> NotifCollapseKey {
let entity_type: &'static str = entity.entity_type.into();
NotifCollapseKey::new(entity_type).append(&entity.entity_id)
}
fn as_apns<'a>(
&self,
sender_id: Option<MacroUserIdStr<'a>>,
_entity: &Entity<'_>,
notification_id: Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
let profile_pic = self.sender_profile_picture_url.clone();
alert_apns(self, sender_id, notification_id, profile_pic).ok()
}
}
/// Notification sent when someone comments on a document the user owns.
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct CommentedOnDocumentMetadata {
/// Public bot name when the author is an agent rather than a Macro user.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sender_display_name: Option<String>,
/// The name of the document.
pub document_name: String,
/// The owner of the document.
#[schema(value_type = String)]
pub owner: Owner,
/// The file type of the document.
pub file_type: Option<String>,
/// The sub type of the document (e.g. task).
#[serde(alias = "sub_type")]
#[serde(default)]
pub sub_type: Option<NotificationDocumentSubType>,
/// the comment id
pub comment_id: CommentRef,
/// the thread id
pub thread_id: CommentRef,
/// the text of the comment
pub text: String,
#[serde(default)]
pub sender_profile_picture_url: Option<String>,
}
impl Notification for CommentedOnDocumentMetadata {
const TYPE_NAME: &'static str = "commented_on_document";
}
impl NotificationTitle for CommentedOnDocumentMetadata {
fn format_title(
&self,
sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
let sender = comment_sender_label(sender_id, self.sender_display_name.as_deref());
let title = match &self.file_type {
Some(ft) => format!("{sender} commented on {}.{ft}", self.document_name),
None => format!("{sender} commented on {}", self.document_name),
};
Ok(title)
}
fn format_body(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
parse_message_plain_text(&self.text)
}
}
impl NotificationExtIos for CommentedOnDocumentMetadata {
type NotifData = ::notification::domain::models::apple::PushNotificationData;
fn collapse_key(&self, entity: &Entity<'_>) -> NotifCollapseKey {
let entity_type: &'static str = entity.entity_type.into();
NotifCollapseKey::new(entity_type).append(&entity.entity_id)
}
fn as_apns<'a>(
&self,
sender_id: Option<MacroUserIdStr<'a>>,
_entity: &Entity<'_>,
notification_id: Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
let profile_pic = self.sender_profile_picture_url.clone();
alert_apns(self, sender_id, notification_id, profile_pic).ok()
}
}
/// Metadata for a notification that a call has started in a channel.
///
/// Mirrors the producer-side `CallStartedNotification` in the `call` crate:
/// both serialize the same wire shape (snake_case fields) under the same
/// `call_started` [`Notification::TYPE_NAME`]. This type is the read-side
/// model used by [`crate::NotifEvent`]; the producer keeps its own type
/// because it additionally builds the incoming-call APNS/VoIP push.
///
/// Rows persisted before the type name was normalized used the kebab-case
/// `call-started`; the [`crate::NotifEvent::CallStarted`] variant carries a
/// `#[serde(alias = "call-started")]` so those rows still deserialize.
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
pub struct CallStartedMetadata {
/// The name of the channel the call started in, when available.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub channel_name: Option<String>,
/// Profile picture URL of the user who started the call, when available.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sender_profile_picture_url: Option<String>,
}
impl Notification for CallStartedMetadata {
const TYPE_NAME: &'static str = "call_started";
}
impl NotificationTitle for CallStartedMetadata {
fn format_title(
&self,
sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
let title = match sender_id {
Some(sender) => format!("{} started a call", sender.email_part().local_part()),
None => "Call started".to_string(),
};
Ok(title)
}
fn format_body(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
Ok(self.channel_name.clone().unwrap_or_default())
}
}
/// Metadata for a reminder the user set for themselves coming due.
///
/// There is no sender: a reminder is self-set, so the dispatcher sends it with
/// `sender_id: None` (a recipient who is also the sender is filtered out of
/// their own notification). Every formatter here must therefore work without
/// one.
///
/// The associated entity, when there is one, lives on the notification row
/// rather than in here, and clients resolve its name from that — so the
/// dispatcher does not have to look up a name across five entity types.
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ReminderMetadata {
/// The reminder that fired.
#[schema(value_type = String, format = Uuid)]
pub reminder_id: Uuid,
/// What the user asked to be reminded about.
pub description: String,
/// Which firing this is — the occurrence the reminder came due for.
///
/// What distinguishes two firings of the same recurring reminder, which are
/// otherwise identical: same id, same description. The collapse key is
/// built from it, so without it Tuesday's alert would replace Monday's
/// unread one on the lock screen.
///
/// Optional because notifications written before recurring dispatch existed
/// have no such field, and they still have to read back.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schema(value_type = Option<String>, format = DateTime)]
pub scheduled_for: Option<DateTime<Utc>>,
}
impl Notification for ReminderMetadata {
const TYPE_NAME: &'static str = "reminder";
}
impl NotificationTitle for ReminderMetadata {
fn format_title(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
let subject: String = self.description.chars().take(128).collect();
Ok(format!("Reminder: {subject}"))
}
fn format_body(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
// A description can be 2000 characters, which is 8 KB of UTF-8 at four
// bytes each — twice Apple's 4 KB push payload limit, and the alert
// renders only a few lines anyway. Cut on a char boundary.
Ok(
match self.description.char_indices().nth(REMINDER_BODY_MAX_CHARS) {
None => self.description.clone(),
Some((cut, _)) => format!("{}…", &self.description[..cut]),
},
)
}
}
/// Characters of a reminder description kept in the notification body, chosen
/// so the APNS payload stays well inside Apple's 4 KB limit.
const REMINDER_BODY_MAX_CHARS: usize = 512;
impl NotificationExtIos for ReminderMetadata {
type NotifData = PushNotificationData;
fn collapse_key(&self, _entity: &Entity<'_>) -> NotifCollapseKey {
// Keyed on the reminder rather than the entity: a redelivery of the
// same firing should replace the alert, but a reminder is not "about"
// the entity in the way a mention is, so two reminders on one document
// stay two alerts.
//
// The firing is part of the key for the same reason. Two occurrences of
// a daily reminder share an id and a description, so on the id alone
// today's alert would quietly replace yesterday's unread one — which is
// right for a redelivery and wrong for a new day.
let key = NotifCollapseKey::new(Self::TYPE_NAME).append(&self.reminder_id.to_string());
match self.scheduled_for {
Some(scheduled_for) => key.append(&scheduled_for.timestamp().to_string()),
None => key,
}
}
fn as_apns<'a>(
&self,
sender_id: Option<MacroUserIdStr<'a>>,
_entity: &Entity<'_>,
notification_id: Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
alert_apns(self, sender_id, notification_id, None).ok()
}
}
/// A calendar event alarm came due. Like [`ReminderMetadata`], these are
/// self-notifications: `sender_id` must stay `None` or the only recipient is
/// filtered out. Everything the alert renders rides in here so the
/// dispatcher never has to resolve the event again at display time.
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct CalendarEventReminderMetadata {
/// The calendar event entity the alarm belongs to.
#[schema(value_type = String, format = Uuid)]
pub event_id: Uuid,
/// Stable occurrence key of the instance that is starting.
pub occurrence_key: String,
/// Event display title at dispatch time.
pub title: String,
/// Instance start, for timed events.
pub starts_at: Option<DateTime<Utc>>,
/// Instance end, for timed events.
pub ends_at: Option<DateTime<Utc>>,
/// Instance start date, for all-day events.
#[schema(value_type = Option<String>, format = Date)]
pub start_date: Option<NaiveDate>,
/// IANA zone for rendering local clock times, when known.
pub time_zone: Option<String>,
/// Minutes before the start the alarm was configured to fire.
pub minutes_before: i32,
}
impl CalendarEventReminderMetadata {
fn display_zone(&self) -> Option<chrono_tz::Tz> {
self.time_zone.as_deref()?.parse().ok()
}
}
impl Notification for CalendarEventReminderMetadata {
const TYPE_NAME: &'static str = "calendar_event_reminder";
}
impl NotificationTitle for CalendarEventReminderMetadata {
fn format_title(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
Ok(if self.title.is_empty() {
"(No title)".to_string()
} else {
self.title.clone()
})
}
fn format_body(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
if let (Some(starts_at), Some(zone)) = (self.starts_at, self.display_zone()) {
let start = starts_at.with_timezone(&zone).format("%-I:%M %p");
return Ok(match self.ends_at {
Some(ends_at) => {
let end = ends_at.with_timezone(&zone).format("%-I:%M %p");
format!("{start} – {end}")
}
None => start.to_string(),
});
}
if self.start_date.is_some() {
return Ok("All day".to_string());
}
// No renderable local time; fall back to the configured offset.
Ok(match self.minutes_before {
minutes if minutes <= 0 => "Starting now".to_string(),
minutes if minutes % 1440 == 0 => match minutes / 1440 {
1 => "Starts in 1 day".to_string(),
days => format!("Starts in {days} days"),
},
minutes if minutes % 60 == 0 => match minutes / 60 {
1 => "Starts in 1 hour".to_string(),
hours => format!("Starts in {hours} hours"),
},
1 => "Starts in 1 minute".to_string(),
minutes => format!("Starts in {minutes} minutes"),
})
}
}
impl notification::domain::models::NotificationExtEmail for CalendarEventReminderMetadata {
fn format_email(&self) -> notification::domain::models::queue_message::EmailContent {
let title = self
.format_title(None)
.unwrap_or_else(|_| "Calendar reminder".into());
let when = self.format_body(None).unwrap_or_default();
notification::domain::models::queue_message::EmailContent::new(
format!("Reminder: {}", title.replace(['\r', '\n'], " ")),
format!(
"<p>{}</p><p>{}</p><p>Calendar reminder from Macro.</p>",
html_escape::encode_text(&title),
html_escape::encode_text(&when)
),
)
}
fn rate_limit_config() -> notification::domain::models::RateLimitConfig {
notification::domain::models::RateLimitConfig {
max_count: 1,
window: std::time::Duration::from_secs(86400),
}
}
fn rate_limit_key(&self) -> notification::domain::models::RateLimitKey {
notification::domain::models::RateLimitKey::from_str_hashed(&format!(
"calendar-reminder:{}:{}:{}:{:?}:{:?}",
self.event_id,
self.occurrence_key,
self.minutes_before,
self.starts_at,
self.start_date
))
}
}
impl NotificationExtIos for CalendarEventReminderMetadata {
type NotifData = PushNotificationData;
fn collapse_key(&self, _entity: &Entity<'_>) -> NotifCollapseKey {
// Keyed on the exact firing so a redelivery replaces its alert while
// distinct offsets on the same occurrence stay separate alerts.
NotifCollapseKey::new(Self::TYPE_NAME)
.append(&self.event_id.to_string())
.append(&self.occurrence_key)
.append(&self.minutes_before.to_string())
}
fn as_apns<'a>(
&self,
sender_id: Option<MacroUserIdStr<'a>>,
_entity: &Entity<'_>,
notification_id: Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
alert_apns(self, sender_id, notification_id, None).ok()
}
}
/// The most of an agent's prose a lock-screen alert or inbox row shows.
const AGENT_EXCERPT_MAX_CHARS: usize = 280;
/// The session an agent-session notification is about, and where its magic
/// chip lives when it was opened from a thread.
///
/// The conversation an agent session was opened from: a channel, document,
/// or initiative. Spelled like the message API's parent for client routing.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, ToSchema)]
pub struct AgentSessionOriginParent {
/// `channel`, `document`, or `initiative`.
#[serde(rename = "type")]
pub kind: String,
/// The parent entity id.
pub id: String,
}
/// Flattened into each agent-session kind so the wire keeps these keys at the
/// top level of the metadata, the way [`CommonChannelMetadata`] does.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct AgentSessionNotificationRef {
/// The session; what a click opens.
pub session_id: Uuid,
/// The session's name at the time of the event.
pub session_name: String,
/// The bot the session runs for. A string on the wire: system bots have
/// fixed ids like `00000000-0000-0000-0000-00000000a2a2`, which are not
/// RFC 4122 uuids and fail a `format: uuid` check on the client.
#[schema(value_type = String)]
pub bot_id: Uuid,
/// The bot's display name; agent notifications have no user sender, so
/// this is who they read as being from.
pub bot_name: String,
/// The channel or document the session was opened from, when it was.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parent: Option<AgentSessionOriginParent>,
/// The channel the session was opened from, when it was opened from a
/// channel thread.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub channel_id: Option<Uuid>,
/// The thread the session was opened from, when it was.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub thread_id: Option<Uuid>,
/// The magic-chip message for the turn in question, when one was posted.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub announcement_message_id: Option<Uuid>,
}
/// An agent finished a turn with nothing queued behind it.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct AgentSessionSettledMetadata {
#[serde(flatten)]
pub session: AgentSessionNotificationRef,
/// The turn that ended.
pub turn: u32,
/// Who prompted the turn, absent when a bot acted on nobody's behalf.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schema(value_type = Option<String>)]
pub actor: Option<MacroUserIdStr<'static>>,
/// The ACP stop reason, or `error`.
pub stop_reason: String,
/// The agent's last prose in the turn, whole; `None` when it wrote none.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub excerpt: Option<String>,
}
/// An agent is blocked on a question only the session's owner can answer.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct AgentSessionWaitingForInputMetadata {
#[serde(flatten)]
pub session: AgentSessionNotificationRef,
/// The turn asking.
pub turn: u32,
/// The question, as the agent phrased it.
pub question: String,
}
/// Someone named the recipient in a prompt to an agent session.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct AgentSessionMentionedMetadata {
#[serde(flatten)]
pub session: AgentSessionNotificationRef,
/// Who wrote the prompt, absent when a bot acted on nobody's behalf.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schema(value_type = Option<String>)]
pub mentioned_by: Option<MacroUserIdStr<'static>>,
/// The action carrying the prompt.
pub action_id: Uuid,
}
impl Notification for AgentSessionSettledMetadata {
const TYPE_NAME: &'static str = "agent_session_settled";
}
impl Notification for AgentSessionWaitingForInputMetadata {
const TYPE_NAME: &'static str = "agent_session_waiting_for_input";
}
impl Notification for AgentSessionMentionedMetadata {
const TYPE_NAME: &'static str = "agent_session_mentioned";
}
/// The first `AGENT_EXCERPT_MAX_CHARS` of an agent's prose, on one line, with
/// its Macro mention tags replaced by the names they show, as channel alerts
/// do for messages.
fn agent_excerpt(text: &str) -> String {
let plain = PlainTextFormatter::format_xml_text(ParsedXmlText::parse_lenient(text)).0;
let flat = plain.split_whitespace().collect::<Vec<_>>().join(" ");
if flat.chars().count() <= AGENT_EXCERPT_MAX_CHARS {
return flat;
}
let mut cut: String = flat.chars().take(AGENT_EXCERPT_MAX_CHARS - 1).collect();
cut.push('…');
cut
}
impl NotificationTitle for AgentSessionSettledMetadata {
fn format_title(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
Ok(format!("{} finished", self.session.bot_name))
}
fn format_body(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
Ok(self
.excerpt
.as_deref()
.map(agent_excerpt)
.filter(|excerpt| !excerpt.is_empty())
.unwrap_or_else(|| self.session.session_name.clone()))
}
}
impl NotificationTitle for AgentSessionWaitingForInputMetadata {
fn format_title(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
Ok(format!("{} needs an answer", self.session.bot_name))
}
fn format_body(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
Ok(agent_excerpt(&self.question))
}
}
impl NotificationTitle for AgentSessionMentionedMetadata {
fn format_title(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
Ok(match &self.mentioned_by {
Some(author) => format!(
"{} mentioned you in {}",
author.email_part().local_part(),
self.session.session_name
),
None => format!("You were mentioned in {}", self.session.session_name),
})
}
fn format_body(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
Ok(format!("An agent session with {}", self.session.bot_name))
}
}
/// The alert for an agent-session kind: title and body from the metadata,
/// grouped with the chip's thread on the lock screen when there is one.
fn agent_session_apns<T: NotificationTitle>(
notif: &T,
session: &AgentSessionNotificationRef,
sender_id: Option<MacroUserIdStr<'_>>,
notification_id: Uuid,
) -> Option<APNSPushNotification<PushNotificationData>> {
let mut apns = alert_apns(notif, sender_id, notification_id, None).ok()?;
apns.aps.thread_id = session.thread_id.map(|thread| thread.to_string());
Some(apns)
}
impl NotificationExtIos for AgentSessionSettledMetadata {
type NotifData = PushNotificationData;
fn collapse_key(&self, _entity: &Entity<'_>) -> NotifCollapseKey {
// One alert per session: the next turn's replaces the last one's.
NotifCollapseKey::new(Self::TYPE_NAME).append(&self.session.session_id.to_string())
}
fn as_apns<'a>(
&self,
sender_id: Option<MacroUserIdStr<'a>>,
_entity: &Entity<'_>,
notification_id: Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
agent_session_apns(self, &self.session, sender_id, notification_id)
}
}
impl NotificationExtIos for AgentSessionWaitingForInputMetadata {
type NotifData = PushNotificationData;
fn collapse_key(&self, _entity: &Entity<'_>) -> NotifCollapseKey {
NotifCollapseKey::new(Self::TYPE_NAME).append(&self.session.session_id.to_string())
}
fn as_apns<'a>(
&self,
sender_id: Option<MacroUserIdStr<'a>>,
_entity: &Entity<'_>,
notification_id: Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
let mut apns = agent_session_apns(self, &self.session, sender_id, notification_id)?;
// A machine is blocked on a person: worth breaking through Focus.
apns.aps.interruption_level = Some(InterruptionLevel::TimeSensitive);
Some(apns)
}
}
impl NotificationExtIos for AgentSessionMentionedMetadata {
type NotifData = PushNotificationData;
fn collapse_key(&self, _entity: &Entity<'_>) -> NotifCollapseKey {
// Each prompt that names you is its own alert.
NotifCollapseKey::new(Self::TYPE_NAME).append(&self.action_id.to_string())
}
fn as_apns<'a>(
&self,
sender_id: Option<MacroUserIdStr<'a>>,
_entity: &Entity<'_>,
notification_id: Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
agent_session_apns(self, &self.session, sender_id, notification_id)
}
}
mod initiative_discussion;
pub use initiative_discussion::{InitiativeDiscussionMetadata, InitiativeDiscussionReason};
mod crm_discussion;
pub use crm_discussion::{CrmDiscussionMetadata, CrmDiscussionReason};
/// A live message in an independently shared external chat.
#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ExternalChatMessageMetadata {
/// The messaging service the chat lives in.
pub provider: model_entity::ExternalChatProvider,
/// The chat's name.
pub chat_name: String,
/// Stable message id; retries use it as their notification id.
pub message_id: Uuid,
}
impl Notification for ExternalChatMessageMetadata {
const TYPE_NAME: &'static str = "external_chat_message";
}
impl NotificationTitle for ExternalChatMessageMetadata {
fn format_title(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
Ok(self.chat_name.clone())
}
fn format_body(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
Ok(format!("New {} message", self.provider.label()))
}
}
impl NotificationExtIos for ExternalChatMessageMetadata {
type NotifData = PushNotificationData;
fn collapse_key(&self, entity: &Entity<'_>) -> NotifCollapseKey {
NotifCollapseKey::new("external_chat").append(&entity.entity_id)
}
fn as_apns<'a>(
&self,
sender_id: Option<MacroUserIdStr<'a>>,
_entity: &Entity<'_>,
notification_id: Uuid,
) -> Option<APNSPushNotification<Self::NotifData>> {
alert_apns(self, sender_id, notification_id, None).ok()
}
}
/// How a routine run ended, as its notification reports it.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum RoutineRunOutcome {
/// The run did its work.
Succeeded,
/// The run failed or was cut short.
Failed,
}
/// One of the recipient's routines finished a run. Every run notifies,
/// whether it succeeded or failed.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct RoutineRunFinishedMetadata {
/// The routine that ran.
pub routine_id: Uuid,
/// The routine's name when it ran.
pub routine_name: String,
/// How the run ended.
pub outcome: RoutineRunOutcome,
}
impl Notification for RoutineRunFinishedMetadata {
const TYPE_NAME: &'static str = "routine_run_finished";
}
impl NotificationTitle for RoutineRunFinishedMetadata {
fn format_title(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
Ok(match self.outcome {
RoutineRunOutcome::Succeeded => format!("{} finished", self.routine_name),
RoutineRunOutcome::Failed => format!("{} failed", self.routine_name),
})
}
fn format_body(
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
Ok(match self.outcome {
RoutineRunOutcome::Succeeded => "A routine run finished.".to_string(),
RoutineRunOutcome::Failed => {
"A routine run failed. Open its history to see why.".to_string()
}
})
}
}