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.

24.2 KB
Raw Blame
use channel_sender::ChannelSender;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

#[cfg(test)]
mod test;

/// A validated document identifier. Historical document ids need not be UUIDs.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
pub struct DocumentId(String);

impl TryFrom<String> for DocumentId {
    type Error = InvalidParent;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        if value.is_empty() || value.trim() != value || value.chars().any(char::is_control) {
            return Err(InvalidParent);
        }
        Ok(Self(value))
    }
}

impl From<DocumentId> for String {
    fn from(value: DocumentId) -> Self {
        value.0
    }
}

/// Invalid or unsupported message parent.
#[derive(Debug, Clone, Copy, thiserror::Error)]
#[error("invalid message parent")]
pub struct InvalidParent;

/// The entity whose permissions and lifecycle govern a message.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(tag = "type", content = "id", rename_all = "snake_case")]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
pub enum MessageParent {
    /// A channel, including direct messages.
    Channel(Uuid),
    /// A document, including tasks and PDFs.
    Document(DocumentId),
    /// An initiative, presented as a project in the application.
    Initiative(Uuid),
    /// A CRM company.
    CrmCompany(Uuid),
    /// A CRM contact.
    CrmContact(Uuid),
    /// A video call and its persistent chat thread.
    Call(Uuid),
}

impl MessageParent {
    /// Parse a persisted or URL parent reference.
    pub fn parse(entity_type: &str, entity_id: &str) -> Result<Self, InvalidParent> {
        match entity_type {
            "channel" => Ok(Self::Channel(entity_id.parse().map_err(|_| InvalidParent)?)),
            "document" => Ok(Self::Document(entity_id.to_owned().try_into()?)),
            "initiative" => Ok(Self::Initiative(
                entity_id.parse().map_err(|_| InvalidParent)?,
            )),
            "crm_company" => Ok(Self::CrmCompany(
                entity_id.parse().map_err(|_| InvalidParent)?,
            )),
            "crm_contact" => Ok(Self::CrmContact(
                entity_id.parse().map_err(|_| InvalidParent)?,
            )),
            "call" => Ok(Self::Call(entity_id.parse().map_err(|_| InvalidParent)?)),
            _ => Err(InvalidParent),
        }
    }

    /// Canonical parent type used in persistence and routes.
    pub fn entity_type(&self) -> &'static str {
        match self {
            Self::Channel(_) => "channel",
            Self::Document(_) => "document",
            Self::Initiative(_) => "initiative",
            Self::CrmCompany(_) => "crm_company",
            Self::CrmContact(_) => "crm_contact",
            Self::Call(_) => "call",
        }
    }

    /// Canonical parent identifier.
    pub fn entity_id(&self) -> String {
        match self {
            Self::Channel(id)
            | Self::Call(id)
            | Self::Initiative(id)
            | Self::CrmCompany(id)
            | Self::CrmContact(id) => id.to_string(),
            Self::Document(id) => id.0.clone(),
        }
    }

    /// Whether messages are presented as comments on an entity.
    pub fn is_discussion(&self) -> bool {
        !matches!(self, Self::Channel(_) | Self::Call(_))
    }

    /// Entity type whose permissions govern messages on this parent.
    #[cfg(feature = "ports")]
    pub fn access_entity_type(&self) -> entity_access::domain::models::EntityType {
        match self {
            Self::Channel(_) => entity_access::domain::models::EntityType::Channel,
            Self::Document(_) => entity_access::domain::models::EntityType::Document,
            Self::Initiative(_) => entity_access::domain::models::EntityType::Initiative,
            Self::CrmCompany(_) => entity_access::domain::models::EntityType::CrmCompany,
            Self::CrmContact(_) => entity_access::domain::models::EntityType::CrmContact,
            Self::Call(_) => entity_access::domain::models::EntityType::Call,
        }
    }
}

/// A thread's location within its document. PDF geometry remains annotation-owned.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
pub enum ThreadAnchor {
    /// Stable Lexical mark identity, independent of transient node keys.
    Markdown {
        /// Mark UUID serialized in the document.
        mark_id: Uuid,
        /// The marked text as it read when the discussion was created, already
        /// trimmed and bounded. Absent on threads created or imported before
        /// snapshots were captured: the text a mark covers cannot be recovered
        /// from the mark id alone.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        marked_text: Option<String>,
    },
    /// An independently existing PDF highlight.
    PdfHighlight {
        /// Highlight annotation UUID.
        anchor_id: Uuid,
        /// The text the highlight covers, trimmed and bounded like a markdown
        /// snapshot. The highlight owns it and it can be edited there, so it is
        /// read from the highlight whenever the thread is, never stored on the
        /// thread. Absent when the highlight carries no text.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        marked_text: Option<String>,
    },
    /// A comment-only placeable PDF annotation. It marks a point on a page,
    /// not a span of text, so it has no marked text.
    PdfPlaceable {
        /// Placeable annotation UUID.
        anchor_id: Uuid,
    },
    /// A cell or rectangular range in a native spreadsheet.
    #[serde(rename_all = "camelCase")]
    Spreadsheet {
        /// Stable sheet identity within the workbook.
        sheet_id: String,
        /// Sheet name when the discussion was created.
        sheet_name: String,
        /// A1 cell or range, such as B4 or B4:C9.
        range: String,
    },
    /// A point pinned on a design (`.fig`): on a layer, or on the page
    /// canvas when no layer was under it.
    #[serde(rename_all = "camelCase")]
    Fig {
        /// Page (canvas) the pin is on.
        page_id: String,
        /// Layer the pin follows; absent for a pin on the bare canvas.
        node_id: Option<String>,
        /// Horizontal offset from the layer's origin, or the page's when
        /// the pin is on no layer, in design units.
        x: f64,
        /// Vertical offset, measured like `x`.
        y: f64,
    },
}

/// Location supplied when creating a document discussion.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
pub enum NewThreadAnchor {
    /// Attach a discussion to a stable Markdown mark.
    Markdown {
        /// Serialized mark identifier.
        mark_id: Uuid,
        /// The document text the mark covers, captured by the editor as the
        /// comment is written. Trimmed and bounded before it is stored, so an
        /// oversized or whitespace-only claim cannot reach the thread row.
        #[serde(default)]
        marked_text: Option<String>,
    },
    /// Attach an independently existing highlight on this document.
    PdfHighlight {
        /// Highlight annotation identifier.
        anchor_id: Uuid,
    },
    /// Atomically create a placeable annotation with the root message.
    PdfPlaceable {
        /// Client-generated annotation identifier used by optimistic rendering.
        anchor_id: Uuid,
        /// PDF page number.
        page: i32,
        /// Horizontal position as a fraction of the page width.
        x_pct: f64,
        /// Vertical position as a fraction of the page height.
        y_pct: f64,
        /// Width as a fraction of the page width.
        width_pct: f64,
        /// Height as a fraction of the page height.
        height_pct: f64,
    },
    /// A cell or rectangular range in a native spreadsheet.
    #[serde(rename_all = "camelCase")]
    Spreadsheet {
        /// Stable sheet identity within the workbook.
        sheet_id: String,
        /// Sheet name when the discussion was created.
        sheet_name: String,
        /// A1 cell or range, such as B4 or B4:C9.
        range: String,
    },
    /// A point pinned on a design (`.fig`): on a layer, or on the page
    /// canvas when no layer was under it.
    #[serde(rename_all = "camelCase")]
    Fig {
        /// Page (canvas) the pin is on.
        page_id: String,
        /// Layer the pin follows; absent or null for a pin on the bare canvas.
        #[serde(default)]
        node_id: Option<String>,
        /// Horizontal offset from the layer's origin, or the page's when
        /// the pin is on no layer, in design units.
        x: f64,
        /// Vertical offset, measured like `x`.
        y: f64,
    },
}

/// Longest marked-text snapshot kept with a discussion. A comment marks a
/// phrase or a paragraph; a longer range is elided so that one highlight
/// cannot crowd out the rest of an agent prompt.
pub const MARKED_TEXT_LIMIT: usize = 1000;

/// The storable form of text a mark covers: trimmed, elided at
/// [`MARKED_TEXT_LIMIT`] characters, and absent when it carries nothing. The
/// only way a snapshot enters a thread row, so no client claim is stored whole.
pub fn marked_text_snapshot(text: &str) -> Option<String> {
    let text = text.trim();
    if text.is_empty() {
        return None;
    }
    let mut snapshot: String = text.chars().take(MARKED_TEXT_LIMIT).collect();
    // The ellipsis is the whole truncation signal, on the wire and in the row.
    if text.chars().nth(MARKED_TEXT_LIMIT).is_some() {
        snapshot.push('\u{2026}');
    }
    Some(snapshot)
}

impl NewThreadAnchor {
    /// Thread-owned reference after annotation geometry has been persisted.
    pub fn reference(&self) -> ThreadAnchor {
        match self {
            Self::Spreadsheet {
                sheet_id,
                sheet_name,
                range,
            } => ThreadAnchor::Spreadsheet {
                sheet_id: sheet_id.clone(),
                sheet_name: sheet_name.clone(),
                range: range.clone(),
            },
            Self::Markdown {
                mark_id,
                marked_text,
            } => ThreadAnchor::Markdown {
                mark_id: *mark_id,
                marked_text: marked_text.as_deref().and_then(marked_text_snapshot),
            },
            Self::PdfHighlight { anchor_id } => ThreadAnchor::PdfHighlight {
                anchor_id: *anchor_id,
                marked_text: None,
            },
            Self::PdfPlaceable { anchor_id, .. } => ThreadAnchor::PdfPlaceable {
                anchor_id: *anchor_id,
            },
            Self::Fig {
                page_id,
                node_id,
                x,
                y,
            } => ThreadAnchor::Fig {
                page_id: page_id.clone(),
                node_id: node_id.clone(),
                x: *x,
                y: *y,
            },
        }
    }
}

/// State belonging to a whole thread, keyed by its root message.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
pub struct ThreadState {
    /// Root message UUID; there is no separate thread identity.
    pub root_id: Uuid,
    /// User who owns this discussion, including imported discussions.
    pub user_id: String,
    /// Whether this discussion has been resolved.
    pub resolved: bool,
    /// No anchor means a discussion on the entire parent. Deleted Markdown
    /// threads retain their mark identity so closed documents can reconcile it.
    pub anchor: Option<ThreadAnchor>,
    /// Creation time of the discussion.
    pub created_at: DateTime<Utc>,
    /// Last state change.
    pub updated_at: DateTime<Utc>,
    /// Explicit deletion of the entire thread, distinct from root deletion.
    pub deleted_at: Option<DateTime<Utc>>,
}

/// Partial changes to discussion lifecycle or document anchor placement.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
pub struct ThreadPatch {
    /// Resolve or reopen the discussion; absent preserves its state.
    pub resolved: Option<bool>,
    /// Move a Markdown discussion to the document when its marked text is removed.
    #[serde(default)]
    pub detach_anchor: bool,
    /// Client nonce for the shared thread update event.
    pub nonce: Option<String>,
}

/// Public bot profile attached to bot-authored messages.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
pub struct BotSenderProfile {
    /// Bot display name.
    pub name: String,
    /// Bot avatar URL.
    pub avatar_url: Option<String>,
}

/// Display attribution for a comment imported from an external document.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
pub struct ImportedAuthor {
    /// Original author text; never interpreted as an authenticated principal.
    pub name: String,
}

/// Reaction emoji and the users who added it.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
pub struct CountedReaction {
    /// Emoji being reacted with.
    pub emoji: String,
    /// User identifiers.
    pub users: Vec<String>,
}

/// An entity attached to a message.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
pub struct MessageAttachment {
    /// Attachment UUID.
    pub id: Uuid,
    /// Attached entity type.
    pub entity_type: String,
    /// Attached entity identifier.
    pub entity_id: String,
    /// Optional media width.
    pub width: Option<i32>,
    /// Optional media height.
    pub height: Option<i32>,
    /// When the attachment was added.
    pub created_at: DateTime<Utc>,
}

/// An attachment to add to a message.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
pub struct NewAttachment {
    /// Attached entity type.
    pub entity_type: String,
    /// Attached entity identifier.
    pub entity_id: String,
    /// Optional media width.
    pub width: Option<i32>,
    /// Optional media height.
    pub height: Option<i32>,
}

/// A mention tracked in a message body.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
pub struct SimpleMention {
    /// Mentioned entity type.
    pub entity_type: String,
    /// Mentioned entity identifier.
    pub entity_id: String,
}

impl SimpleMention {
    /// Construct a tracked mention of a Macro user.
    pub fn user(user_id: &macro_user_id::user_id::MacroUserIdStr<'_>) -> Self {
        Self {
            entity_type: "user".to_string(),
            entity_id: user_id.as_ref().to_string(),
        }
    }
}

impl std::fmt::Display for SimpleMention {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}:{}", self.entity_type, self.entity_id)
    }
}

/// What a persisted message is. Set by the server, never by a client.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum MessageKind {
    /// Something someone wrote.
    #[default]
    Message,
    /// The root of a channel call's thread. Its id is the call id, and it
    /// stands for the call rather than for anything the caller said.
    CallRoot,
}

/// Shared message representation for channel timelines and entity discussions.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
pub struct Message {
    /// Message UUID.
    pub id: Uuid,
    /// Entity that owns this conversation.
    pub parent: MessageParent,
    /// Root message UUID for replies; absent on roots.
    pub thread_id: Option<Uuid>,
    /// What this message is.
    #[serde(default)]
    pub kind: MessageKind,
    /// Authenticated actor or owner of imported content.
    #[cfg_attr(feature = "schema", schema(value_type = String))]
    #[cfg_attr(feature = "json-schema", schemars(with = "String"))]
    pub sender_id: ChannelSender<'static>,
    /// Display name of a verified call guest, retained after the call ends.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub guest_name: Option<String>,
    /// Original external author, when imported.
    pub imported_author: Option<ImportedAuthor>,
    /// Public bot name and avatar for rendering shared message authors.
    pub bot_profile: Option<BotSenderProfile>,
    /// Tracked mentions, retained when a caller changes attachments only.
    pub mentions: Vec<SimpleMention>,
    /// User who triggered a bot-authored message.
    pub triggered_by: Option<String>,
    /// Self-reported name of the client the user triggered it through, such
    /// as "Claude Code"; a display label only.
    #[serde(default)]
    pub triggered_via: Option<String>,
    /// Macro Markdown body.
    pub content: String,
    /// Creation time.
    pub created_at: DateTime<Utc>,
    /// Last persisted update.
    pub updated_at: DateTime<Utc>,
    /// Last content edit, if any.
    pub edited_at: Option<DateTime<Utc>>,
    /// Message tombstone, independent of thread deletion.
    pub deleted_at: Option<DateTime<Utc>>,
    /// Attached entities.
    pub attachments: Vec<MessageAttachment>,
    /// Aggregated reactions.
    pub reactions: Vec<CountedReaction>,
}

impl Message {
    /// Canonical thread identity for roots and replies alike.
    pub fn root_id(&self) -> Uuid {
        self.thread_id.unwrap_or(self.id)
    }
}

/// A discussion with its root and ordered replies, including root tombstones.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
pub struct MessageThread {
    /// Shared thread lifecycle and anchor state.
    pub state: ThreadState,
    /// Root message, which may be a tombstone.
    pub root: Message,
    /// Replies in display order.
    pub replies: Vec<Message>,
}

/// Internal notification behavior for a posted channel message.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
pub enum PostMessageNotificationPolicy {
    /// Apply the normal channel notification rules.
    #[default]
    Default,
    /// Notify tracked mentions without reply, channel-message, or channel-invite notifications.
    MentionsOnly,
    /// Do not send notifications for this post. Realtime/search side effects still run.
    Silent,
}

/// Internal notification behavior for a patched channel message.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
pub enum PatchMessageNotificationPolicy {
    /// Apply the normal edit behavior: realtime/search only, no notifications.
    #[default]
    Default,
    /// Notify as though the patched message content had just been posted.
    NotifyAsPostedMessage,
}

/// Attribution of a trusted bot post, distinct from the scope used to authorize it.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum MessageAttribution {
    /// A user invoked the agent; use the verified acting user from its capability.
    #[default]
    ActingUser,
    /// A user invoked the agent through a named client, such as an MCP client;
    /// the post records the acting user and the client's label.
    ActingUserVia {
        /// The client's self-reported name, for display only.
        client: String,
    },
    /// An account manager posted with its credential for the sender's account;
    /// the post records the manager's account.
    AccountManager {
        /// The agent account holding the credential.
        manager_user_id: String,
    },
    /// Autonomous webhook delivery has no invoking user.
    Unprompted,
}

impl MessageAttribution {
    /// Whether the post records the verified acting user as its trigger.
    pub fn has_acting_user(&self) -> bool {
        match self {
            Self::ActingUser | Self::ActingUserVia { .. } => true,
            Self::AccountManager { .. } | Self::Unprompted => false,
        }
    }
}

/// Create a root or reply. Thread state may only be supplied on a root.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
pub struct PostMessage {
    /// Internal authorship context; clients cannot override attribution.
    #[serde(skip)]
    #[cfg_attr(feature = "schema", schema(ignore))]
    pub attribution: MessageAttribution,
    /// Notification behavior chosen by a trusted server caller.
    #[serde(skip)]
    #[cfg_attr(feature = "schema", schema(ignore))]
    pub notification_policy: PostMessageNotificationPolicy,
    /// Client-minted UUIDv7 for the new message, so an optimistic message
    /// already carries its final id; the server mints one when absent.
    #[serde(default)]
    pub id: Option<Uuid>,
    /// Macro Markdown body.
    pub content: String,
    /// Root to reply to, if this is a reply.
    pub thread_id: Option<Uuid>,
    /// Optional document location for a new discussion.
    pub anchor: Option<NewThreadAnchor>,
    /// Mentions tracked by the editor.
    #[serde(default)]
    pub mentions: Vec<SimpleMention>,
    /// Initial attachments.
    #[serde(default)]
    pub attachments: Vec<NewAttachment>,
    /// Client nonce for optimistic reconciliation.
    pub nonce: Option<String>,
}

/// Root message with its small thread preview, independent of its parent type.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
pub struct MessageListItem {
    /// The same canonical message returned by item reads and writes.
    #[serde(flatten)]
    pub message: Message,
    /// Thread metadata, independent of the first message's lifecycle.
    pub state: ThreadState,
    /// Bounded reply preview; full replies load on expansion.
    pub thread: MessageThreadPreview,
}

/// Thread counts and its oldest three live replies.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
pub struct MessageThreadPreview {
    /// Total live reply count.
    pub reply_count: i64,
    /// Creation time of the latest live reply.
    pub latest_reply_at: Option<DateTime<Utc>>,
    /// Bounded preview using the canonical message shape.
    pub preview: Vec<Message>,
}

impl models_pagination::Identify for MessageListItem {
    type Id = Uuid;
    fn id(&self) -> Uuid {
        self.message.id
    }
}
impl models_pagination::SortOn<models_pagination::CreatedAt> for MessageListItem {
    fn sort_on(
        sort_type: models_pagination::CreatedAt,
    ) -> impl FnMut(&Self) -> models_pagination::CursorVal<models_pagination::CreatedAt> {
        move |item| models_pagination::CursorVal {
            sort_type,
            last_val: item.message.created_at,
        }
    }
}