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.

Seanaye/feat/improve channel sender typing (#4457)

Sean Aye0b6bb4578cc1
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 3bd1bb3b22..9a63124d3b 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -28,6 +28,7 @@
"authentication_service_client",
"bot_id",
"call",
+ "channel_sender",
"channels",
"chat",
"connection",
@@ -168,6 +169,7 @@
"authentication_service_client",
"bot_id",
"call",
+ "channel_sender",
"channels",
"chat",
"connection",
@@ -299,6 +301,7 @@
"authentication_service_client",
"bot_id",
"call",
+ "channel_sender",
"channels",
"comms_db_client",
"connection",
@@ -427,6 +430,7 @@
],
"bot_id": [
"bot_id",
+ "cowlike",
"workspace-hack"
],
"bots": [
@@ -437,6 +441,7 @@
"authentication_service_client",
"bot_id",
"bots",
+ "channel_sender",
"channels",
"connection_gateway_client",
"connection_gateway_models",
@@ -509,6 +514,7 @@
"authentication_service_client",
"bot_id",
"call",
+ "channel_sender",
"channels",
"connection",
"connection_gateway_client",
@@ -588,6 +594,7 @@
"bot_id",
"call",
"channel_bots",
+ "channel_sender",
"channels",
"chat",
"connection",
@@ -674,6 +681,13 @@
"user_quota",
"workspace-hack"
],
+ "channel_sender": [
+ "bot_id",
+ "channel_sender",
+ "cowlike",
+ "macro_user_id",
+ "workspace-hack"
+ ],
"channels": [
"agent",
"ai_toolset",
@@ -681,6 +695,7 @@
"attachment",
"authentication_service_client",
"bot_id",
+ "channel_sender",
"channels",
"connection_gateway_client",
"connection_gateway_models",
@@ -774,6 +789,7 @@
"attachment",
"authentication_service_client",
"bot_id",
+ "channel_sender",
"channels",
"comms_db_client",
"connection_gateway_client",
@@ -1201,6 +1217,7 @@
"authentication_service_client",
"bot_id",
"call",
+ "channel_sender",
"channels",
"chat",
"connection",
@@ -1313,6 +1330,7 @@
"cal",
"call",
"channel_bots",
+ "channel_sender",
"channels",
"chat",
"comms_db_client",
@@ -1479,6 +1497,7 @@
"authentication_service_client",
"bot_id",
"call",
+ "channel_sender",
"channels",
"connection",
"connection_gateway_client",
@@ -1563,6 +1582,7 @@
"authentication_service_client",
"bot_id",
"call",
+ "channel_sender",
"channels",
"connection",
"connection_gateway_client",
@@ -1745,6 +1765,8 @@
],
"email_formatting": [
"ai_toolset",
+ "bot_id",
+ "channel_sender",
"cowlike",
"decode_jwt",
"email_formatting",
@@ -1855,6 +1877,8 @@
"ai_usage",
"attachment",
"authentication_service_client",
+ "bot_id",
+ "channel_sender",
"connection_gateway_client",
"connection_gateway_models",
"contacts",
@@ -2151,6 +2175,7 @@
"authentication_service_client",
"bot_id",
"call",
+ "channel_sender",
"channels",
"connection",
"connection_gateway_client",
@@ -2246,6 +2271,7 @@
"authentication_service_client",
"bot_id",
"call",
+ "channel_sender",
"channels",
"connection",
"connection_gateway_client",
@@ -2419,6 +2445,7 @@
"authentication_service_client",
"bot_id",
"call",
+ "channel_sender",
"channels",
"connection",
"connection_gateway_client",
@@ -2735,6 +2762,7 @@
"authentication_service_client",
"bot_id",
"call",
+ "channel_sender",
"channels",
"chat",
"connection",
@@ -2837,6 +2865,7 @@
"authentication_service_client",
"bot_id",
"call",
+ "channel_sender",
"channels",
"chat",
"connection",
@@ -2925,6 +2954,10 @@
"workspace-hack"
],
"mention_utils": [
+ "bot_id",
+ "channel_sender",
+ "cowlike",
+ "macro_user_id",
"mention_utils",
"workspace-hack"
],
@@ -2969,6 +3002,8 @@
],
"model_notifications": [
"ai_toolset",
+ "bot_id",
+ "channel_sender",
"cowlike",
"decode_jwt",
"invite_email",
@@ -3052,6 +3087,7 @@
"authentication_service_client",
"bot_id",
"call",
+ "channel_sender",
"channels",
"connection",
"connection_gateway_client",
@@ -3133,6 +3169,7 @@
"authentication_service_client",
"bot_id",
"call",
+ "channel_sender",
"channels",
"connection",
"connection_gateway_client",
@@ -3243,6 +3280,8 @@
],
"notification_db_client": [
"ai_toolset",
+ "bot_id",
+ "channel_sender",
"cowlike",
"decode_jwt",
"invite_email",
@@ -3267,6 +3306,8 @@
],
"notification_sandbox": [
"ai_toolset",
+ "bot_id",
+ "channel_sender",
"cowlike",
"decode_jwt",
"email_formatting",
@@ -3296,6 +3337,8 @@
"ai_toolset",
"ai_usage",
"attachment",
+ "bot_id",
+ "channel_sender",
"cowlike",
"decode_jwt",
"document_sub_type",
@@ -3450,6 +3493,8 @@
"ai_toolset",
"ai_usage",
"attachment",
+ "bot_id",
+ "channel_sender",
"cowlike",
"decode_jwt",
"document_sub_type",
@@ -3505,6 +3550,8 @@
"ai_toolset",
"ai_usage",
"attachment",
+ "bot_id",
+ "channel_sender",
"cowlike",
"decode_jwt",
"document_sub_type",
@@ -3618,6 +3665,7 @@
"authentication_service_client",
"bot_id",
"call",
+ "channel_sender",
"channels",
"chat",
"connection",
@@ -3718,6 +3766,7 @@
"authentication_service_client",
"bot_id",
"call",
+ "channel_sender",
"channels",
"comms_db_client",
"connection",
@@ -3803,6 +3852,7 @@
"authentication_service_client",
"bot_id",
"call",
+ "channel_sender",
"channels",
"comms_db_client",
"connection",
@@ -3882,6 +3932,7 @@
"authentication_service_client",
"bot_id",
"call",
+ "channel_sender",
"channels",
"connection",
"connection_gateway_client",
@@ -4005,6 +4056,7 @@
"attachment",
"authentication_service_client",
"bot_id",
+ "channel_sender",
"channels",
"comms_db_client",
"connection_gateway_client",
@@ -4109,6 +4161,7 @@
"authentication_service_client",
"bot_id",
"call",
+ "channel_sender",
"channels",
"connection",
"connection_gateway_client",
@@ -4329,6 +4382,7 @@
"authentication_service_client",
"bot_id",
"call",
+ "channel_sender",
"channels",
"connection",
"connection_gateway_client",
@@ -4405,6 +4459,8 @@
"ai_usage",
"attachment",
"authentication_service_client",
+ "bot_id",
+ "channel_sender",
"cowlike",
"crm",
"decode_jwt",
diff --git a/js/app/packages/channel/Input/ChannelInput.tsx b/js/app/packages/channel/Input/ChannelInput.tsx
index ef8bbf2a9f..6f280e3357 100644
--- a/js/app/packages/channel/Input/ChannelInput.tsx
+++ b/js/app/packages/channel/Input/ChannelInput.tsx
@@ -32,7 +32,7 @@ import {
Show,
Switch,
} from 'solid-js';
-import { MACRO_AI_BOT_ID, macroAiMentionUser } from '../macroAi';
+import { isMacroAiId, macroAiMentionUser } from '../macroAi';
import { CHANNEL_FILE_PICKER_ACCEPT } from './accepted-file-types';
import { createInputAttachmentTracker } from './attachment-tracker';
import { createConfiguredChannelMarkdownEditor } from './configured-markdown-editor';
@@ -220,7 +220,7 @@ export function ChannelInput(props: ChannelInputProps) {
// `@`-mention typeahead as participants and re-tagged as a bot at send time.
const mentionUsers: Accessor<IUser[]> = () => {
const base = props.participants?.() ?? [];
- return base.some((user) => user.id === MACRO_AI_BOT_ID)
+ return base.some((user) => isMacroAiId(user.id))
? base
: [macroAiMentionUser(), ...base];
};
diff --git a/js/app/packages/channel/macroAi.ts b/js/app/packages/channel/macroAi.ts
index ebf8231f8e..e8d9cbd5e6 100644
--- a/js/app/packages/channel/macroAi.ts
+++ b/js/app/packages/channel/macroAi.ts
@@ -1,6 +1,6 @@
import {
- MACRO_AGENT_BOT_ID,
MACRO_AGENT_NAME,
+ MACRO_AGENT_PRINCIPAL_ID,
} from '@core/constant/macroAgent';
import type { IUser } from '@core/user/types';
@@ -10,17 +10,20 @@ export {
MACRO_AGENT_BOT_ID as MACRO_AI_BOT_ID,
MACRO_AGENT_HANDLE as MACRO_AI_HANDLE,
MACRO_AGENT_NAME as MACRO_AI_NAME,
+ MACRO_AGENT_PRINCIPAL_ID as MACRO_AI_PRINCIPAL_ID,
} from '@core/constant/macroAgent';
/**
* A synthetic [`IUser`] entry so Macro appears in the channel `@`-mention
* typeahead. The mention rides the existing user-mention machinery and is
* re-tagged as a bot mention at send time (see `expandMentions`). `email` is set
- * to the display name so the typeahead shows just "Macro".
+ * to the display name so the typeahead shows just "Macro". The id uses the
+ * canonical `bot|<uuid>` principal form so persisted mention content matches
+ * bot sender/participant ids.
*/
export function macroAiMentionUser(): IUser {
return {
- id: MACRO_AGENT_BOT_ID,
+ id: MACRO_AGENT_PRINCIPAL_ID,
name: MACRO_AGENT_NAME,
email: MACRO_AGENT_NAME,
};
diff --git a/js/app/packages/core/constant/macroAgent.ts b/js/app/packages/core/constant/macroAgent.ts
index 883fed1f7a..927dbf9e4f 100644
--- a/js/app/packages/core/constant/macroAgent.ts
+++ b/js/app/packages/core/constant/macroAgent.ts
@@ -5,6 +5,13 @@
*/
export const MACRO_AGENT_BOT_ID = '00000000-0000-0000-0000-00000000a1a1';
+/**
+ * Canonical principal id for Macro, matching the `bot|<uuid>` form used for
+ * bot senders and participants everywhere else. New mentions must always use
+ * this form; the bare UUID is only accepted for historical content.
+ */
+export const MACRO_AGENT_PRINCIPAL_ID = `bot|${MACRO_AGENT_BOT_ID}`;
+
/** Display name for Macro. */
export const MACRO_AGENT_NAME = 'Macro';
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index 8b7b6dcb1a..315c6e5b88 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -9298,7 +9298,8 @@
"items": {
"type": "string"
},
- "description": "User ids to add."
+ "description": "User ids to add.",
+ "uniqueItems": true
}
}
},
@@ -11765,7 +11766,8 @@
"items": {
"type": "string"
},
- "description": "Participants to add, excluding the owner."
+ "description": "Participants to add, excluding the owner.",
+ "uniqueItems": true
},
"team_id": {
"type": ["string", "null"],
@@ -15091,7 +15093,8 @@
"items": {
"type": "string"
},
- "description": "Recipient user ids."
+ "description": "Recipient user ids.",
+ "uniqueItems": true
}
}
},
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 5155095f17..114f51032a 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -2022,6 +2022,8 @@ dependencies = [
name = "bot_id"
version = "0.1.0"
dependencies = [
+ "cowlike",
+ "nom 8.0.0",
"serde",
"sqlx",
"thiserror 2.0.18",
@@ -2396,6 +2398,19 @@ dependencies = [
"workspace-hack",
]
+[[package]]
+name = "channel_sender"
+version = "0.1.0"
+dependencies = [
+ "bot_id",
+ "either",
+ "macro_user_id",
+ "serde",
+ "serde_json",
+ "uuid",
+ "workspace-hack",
+]
+
[[package]]
name = "channels"
version = "0.1.0"
@@ -2406,6 +2421,7 @@ dependencies = [
"attachment",
"axum",
"bot_id",
+ "channel_sender",
"chrono",
"connection_gateway_client",
"contacts",
@@ -3018,6 +3034,9 @@ checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
name = "cowlike"
version = "0.1.0"
dependencies = [
+ "bot_id",
+ "either",
+ "macro_user_id",
"workspace-hack",
]
@@ -7964,7 +7983,10 @@ dependencies = [
name = "mention_utils"
version = "0.1.0"
dependencies = [
+ "channel_sender",
"cool_asserts",
+ "either",
+ "macro_user_id",
"nom 8.0.0",
"serde",
"serde_json",
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 3fc96cf5d5..131b5e9a0c 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -33,15 +33,21 @@ members = [
"email_suppression_handler",
"embedding",
"foreign_entity",
+ "graphql_soup",
"image_optimizer",
"image_proxy_service",
"integration_tests/local_e2e",
+ "macro_config",
+ "macro_event_broker",
+ "macro_event_topics",
+ "macro_queues",
"mcp_service",
"memory",
"notification_sandbox",
"notification_service",
"organization_retention_handler",
"organization_retention_trigger",
+ "prompt",
"properties_service",
"scheduled_action",
"search_processing_service",
@@ -52,32 +58,26 @@ members = [
"static_file_service",
"task_dedup",
"tools/native_app_server",
+ "tools/xtask",
"unfurl",
"unfurl_service",
"upload_extractor_lambda_handler",
"upload_extractor_lambda_trigger",
"user_link_cleanup_handler",
"worker_trigger",
- "macro_config",
- "macro_event_broker",
- "macro_event_topics",
- "macro_queues",
- "prompt",
"workspace-hack",
- "tools/xtask",
- "graphql_soup",
]
[workspace.dependencies]
anyhow = "1.0.100"
askama = "0.14"
+async-graphql = "7.2.1"
async-openai = { version = "0.36.1", features = [
"byot",
"chat-completion",
"completions",
"embedding",
] }
-async-graphql = "7.2.1"
async-stream = "0.3.6"
async-trait = "0.1.86"
automod = "1"
@@ -111,8 +111,8 @@ hmac = "0.12.1"
http = "1"
http-body-util = "0.1.2"
image = "0.25"
-inquire = "0.7"
indexmap = "2"
+inquire = "0.7"
itertools = "0.14"
jsonwebtoken = { git = "https://github.com/whutchinson98/jsonwebtoken", features = [
"rust_crypto",
@@ -141,7 +141,10 @@ opentelemetry-otlp = { version = "0.31.0", default-features = false, features =
opentelemetry_sdk = { version = "0.31.0", features = ["rt-tokio"] }
ordered-float = "5"
paste = "1"
-pdfium-render = { version = "0.8.37", default-features = false, features = ["pdfium_7543", "thread_safe"] }
+pdfium-render = { version = "0.8.37", default-features = false, features = [
+ "pdfium_7543",
+ "thread_safe",
+] }
pgvector = { version = "0.4", features = ["postgres", "sqlx"] }
quote = "1"
rand = "0.9.0"
@@ -219,6 +222,7 @@ bzip2 = { version = "0.5.1", default-features = false, features = [
] }
derive_builder = "0.20.2"
doppleganger = "0.5"
+doppler-config = "0.1.2"
js-sys = "0.3"
once_cell = "1.21.3"
scraper = "0.18"
@@ -227,4 +231,3 @@ strum_macros = "0.27.1"
unicode-segmentation = "1.9.0"
url = "2.5.0"
zip = "=2.4.2"
-doppler-config = "0.1.2"
diff --git a/rust/cloud-storage/bot_id/Cargo.toml b/rust/cloud-storage/bot_id/Cargo.toml
index b5ac1e628e..1c773b2d0b 100644
--- a/rust/cloud-storage/bot_id/Cargo.toml
+++ b/rust/cloud-storage/bot_id/Cargo.toml
@@ -9,6 +9,8 @@ schema = ["dep:utoipa"]
sqlx = ["dep:sqlx"]
[dependencies]
+cowlike = { path = "../cowlike" }
+nom = { workspace = true }
serde = { workspace = true }
sqlx = { workspace = true, optional = true }
thiserror = { workspace = true }
diff --git a/rust/cloud-storage/bot_id/src/lib.rs b/rust/cloud-storage/bot_id/src/lib.rs
index bd54b280d6..c20725b8c0 100644
--- a/rust/cloud-storage/bot_id/src/lib.rs
+++ b/rust/cloud-storage/bot_id/src/lib.rs
@@ -2,14 +2,57 @@
//! Bot identity primitives.
+use cowlike::{ArcCowStr, CowLike};
+use nom::{
+ Finish, IResult, Parser,
+ bytes::complete::tag,
+ character::complete::char,
+ combinator::{eof, map_res, recognize},
+};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
-const BOT_STORAGE_PREFIX: &str = "bot|";
+pub use cowlike;
+
+#[cfg(test)]
+mod test;
+
+const BOT_STORAGE_PREFIX: &str = "bot";
+const UUID_HYPHENATED_LEN: usize = 36;
+
+fn uuid_literal(input: &str) -> IResult<&str, BotId> {
+ map_res(
+ recognize(nom::bytes::complete::take_while_m_n(
+ UUID_HYPHENATED_LEN,
+ UUID_HYPHENATED_LEN,
+ |c: char| c.is_ascii_hexdigit() || c == '-',
+ )),
+ |value| Uuid::parse_str(value).map(BotId),
+ )
+ .parse(input)
+}
+
+fn bot_id_str(input: &str) -> IResult<&str, BotIdStorage<ArcCowStr<'_>>> {
+ let (rest, (((prefix, pipe), bot_id), _eof)) = tag(BOT_STORAGE_PREFIX)
+ .and(char('|'))
+ .and(uuid_literal)
+ .and(eof)
+ .parse(input)?;
+
+ let bot_id_part_offset = prefix.len() + pipe.len_utf8();
+ Ok((
+ rest,
+ BotIdStorage {
+ bot_id,
+ bot_id_part_offset,
+ storage_id: ArcCowStr::Borrowed(input),
+ },
+ ))
+}
/// Stable [`BotId`] for the first-party "Macro AI" system bot.
pub const MACRO_AI_BOT_ID: BotId =
- BotId::from_uuid(Uuid::from_u128(0x0000_0000_0000_0000_0000_0000_0000_a1a1));
+ BotId::new_from_uuid(Uuid::from_u128(0x0000_0000_0000_0000_0000_0000_0000_a1a1));
/// Stable handle for the "Macro AI" system bot (used for `@` mentions).
pub const MACRO_AI_HANDLE: &str = "macro";
@@ -17,14 +60,14 @@ pub const MACRO_AI_HANDLE: &str = "macro";
/// Display name for the "Macro" system bot.
pub const MACRO_AI_NAME: &str = "Macro";
-/// A bot id.
+/// A bot id UUID.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct BotId(Uuid);
impl BotId {
/// Build a bot id from its UUID.
- pub const fn from_uuid(id: Uuid) -> Self {
+ pub const fn new_from_uuid(id: Uuid) -> Self {
Self(id)
}
@@ -40,43 +83,213 @@ impl BotId {
.map_err(|_| BotIdParseError::invalid(value))
}
- /// Parse the existing storage principal representation, `bot|<uuid>`.
- pub fn parse_storage_str(value: &str) -> Result<Self, BotIdParseError> {
- let Some(id) = value.strip_prefix(BOT_STORAGE_PREFIX) else {
- return Err(BotIdParseError::invalid(value));
- };
- Self::parse_uuid_str(id).map_err(|_| BotIdParseError::invalid(value))
+ /// Canonical storage representation as a parsed [`BotIdStr`].
+ pub fn into_storage_id(self) -> BotIdStr<'static> {
+ let storage_id = format!("{BOT_STORAGE_PREFIX}|{}", self.0);
+ BotIdStr(BotIdStorage {
+ bot_id: self,
+ bot_id_part_offset: BOT_STORAGE_PREFIX.len() + 1,
+ storage_id: ArcCowStr::Owned(storage_id.into()),
+ })
}
+}
- /// Canonical storage representation for existing TEXT sender/participant columns.
- pub fn to_storage_string(self) -> String {
- format!("{BOT_STORAGE_PREFIX}{}", self.0)
+impl std::fmt::Display for BotId {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", self.0)
}
}
-impl From<Uuid> for BotId {
- fn from(value: Uuid) -> Self {
- Self::from_uuid(value)
+impl std::str::FromStr for BotId {
+ type Err = BotIdParseError;
+
+ fn from_str(value: &str) -> Result<Self, Self::Err> {
+ Self::parse_uuid_str(value)
}
}
-impl From<BotId> for Uuid {
- fn from(value: BotId) -> Self {
- value.as_uuid()
+/// A parsed bot storage principal, `bot|<uuid>`.
+#[derive(Clone, Copy)]
+pub struct BotIdStorage<T> {
+ bot_id: BotId,
+ bot_id_part_offset: usize,
+ storage_id: T,
+}
+
+impl<T> std::fmt::Debug for BotIdStorage<T>
+where
+ T: AsRef<str>,
+{
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", self.storage_id.as_ref())
}
}
-impl std::fmt::Display for BotId {
+impl<T> PartialEq for BotIdStorage<T>
+where
+ T: PartialEq,
+{
+ fn eq(&self, other: &Self) -> bool {
+ self.bot_id == other.bot_id
+ }
+}
+
+impl<T> Eq for BotIdStorage<T> where T: Eq {}
+
+impl<T> std::hash::Hash for BotIdStorage<T>
+where
+ T: std::hash::Hash,
+{
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ self.bot_id.hash(state);
+ }
+}
+
+impl<T> BotIdStorage<T> {
+ fn map<F, U>(self, f: F) -> BotIdStorage<U>
+ where
+ F: FnOnce(T) -> U,
+ {
+ BotIdStorage {
+ bot_id: self.bot_id,
+ bot_id_part_offset: self.bot_id_part_offset,
+ storage_id: f(self.storage_id),
+ }
+ }
+}
+
+impl<T> AsRef<str> for BotIdStorage<T>
+where
+ T: AsRef<str>,
+{
+ fn as_ref(&self) -> &str {
+ self.storage_id.as_ref()
+ }
+}
+
+impl<T> BotIdStorage<T>
+where
+ T: AsRef<str>,
+{
+ /// Return the parsed bot UUID newtype.
+ pub const fn bot_id(&self) -> BotId {
+ self.bot_id
+ }
+
+ /// Return the UUID portion as a string slice.
+ pub fn uuid_str(&self) -> &str {
+ let storage_id = self.storage_id.as_ref();
+ &storage_id[self.bot_id_part_offset..]
+ }
+}
+
+impl<'a, T> CowLike<'a> for BotIdStorage<T>
+where
+ T: CowLike<'a>,
+{
+ type Owned<'b> = BotIdStorage<T::Owned<'b>>;
+
+ fn into_owned(self) -> BotIdStorage<T::Owned<'static>> {
+ self.map(CowLike::into_owned)
+ }
+
+ fn copied(&'a self) -> Self {
+ BotIdStorage {
+ bot_id: self.bot_id,
+ bot_id_part_offset: self.bot_id_part_offset,
+ storage_id: self.storage_id.copied(),
+ }
+ }
+}
+
+impl<'a> BotIdStorage<ArcCowStr<'a>> {
+ /// Attempt to create a borrowed parsed bot storage principal from an input string.
+ pub fn parse_from_str(input: &'a str) -> Result<Self, BotIdParseError> {
+ let (_, out) = bot_id_str(input)
+ .finish()
+ .map_err(|_| BotIdParseError::invalid(input))?;
+ Ok(out)
+ }
+}
+
+/// The standard string newtype for a parsed bot storage principal, `bot|<uuid>`.
+#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
+#[serde(try_from = "String", into = "String")]
+pub struct BotIdStr<'a>(pub BotIdStorage<ArcCowStr<'a>>);
+
+impl<'a> std::fmt::Debug for BotIdStr<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "{}", self.0)
+ write!(f, "{}", self.0.as_ref())
}
}
-impl std::str::FromStr for BotId {
- type Err = BotIdParseError;
+impl<'a> std::fmt::Display for BotIdStr<'a> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", self.0.as_ref())
+ }
+}
- fn from_str(value: &str) -> Result<Self, Self::Err> {
- Self::parse_uuid_str(value)
+impl<'a> AsRef<str> for BotIdStr<'a> {
+ fn as_ref(&self) -> &str {
+ self.0.as_ref()
+ }
+}
+
+impl<'a> BotIdStr<'a> {
+ /// Parse the inner value from the input string.
+ pub fn parse_from_str(s: &'a str) -> Result<Self, BotIdParseError> {
+ BotIdStorage::parse_from_str(s).map(BotIdStr)
+ }
+
+ /// Return the parsed bot UUID newtype.
+ pub const fn bot_id(&self) -> BotId {
+ self.0.bot_id
+ }
+
+ /// Return the parsed UUID.
+ pub const fn as_uuid(&self) -> Uuid {
+ self.0.bot_id.as_uuid()
+ }
+}
+
+impl From<BotId> for BotIdStr<'static> {
+ fn from(value: BotId) -> Self {
+ BotId::into_storage_id(value)
+ }
+}
+
+impl TryFrom<String> for BotIdStr<'static> {
+ type Error = BotIdParseError;
+
+ fn try_from(value: String) -> Result<Self, Self::Error> {
+ let s = value.as_str();
+ BotIdStr::try_from(s).map(|x| x.into_owned())
+ }
+}
+
+impl<'a> TryFrom<&'a str> for BotIdStr<'a> {
+ type Error = BotIdParseError;
+
+ fn try_from(value: &'a str) -> Result<Self, Self::Error> {
+ Self::parse_from_str(value)
+ }
+}
+
+impl From<BotIdStr<'_>> for String {
+ fn from(value: BotIdStr<'_>) -> Self {
+ value.0.as_ref().to_string()
+ }
+}
+
+impl<'a> CowLike<'a> for BotIdStr<'a> {
+ type Owned<'b> = BotIdStr<'b>;
+
+ fn into_owned(self) -> Self::Owned<'static> {
+ BotIdStr(self.0.into_owned())
+ }
+
+ fn copied(&'a self) -> Self {
+ BotIdStr(self.0.copied())
}
}
@@ -149,23 +362,10 @@ impl<'r> sqlx::Decode<'r, sqlx::Postgres> for BotId {
}
}
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn storage_string_round_trips() {
- let uuid = Uuid::new_v4();
- let bot_id = BotId::from_uuid(uuid);
-
- assert_eq!(
- BotId::parse_storage_str(&bot_id.to_storage_string()).unwrap(),
- bot_id
- );
- }
-
- #[test]
- fn rejects_non_bot_storage_string() {
- assert!(BotId::parse_storage_str("macro|[email protected]").is_err());
+#[cfg(feature = "sqlx")]
+impl<'r> sqlx::Decode<'r, sqlx::Postgres> for BotIdStr<'static> {
+ fn decode(value: sqlx::postgres::PgValueRef<'r>) -> Result<Self, sqlx::error::BoxDynError> {
+ let value = <String as sqlx::Decode<sqlx::Postgres>>::decode(value)?;
+ BotIdStr::try_from(value).map_err(Into::into)
}
}
diff --git a/rust/cloud-storage/bot_id/src/test.rs b/rust/cloud-storage/bot_id/src/test.rs
new file mode 100644
index 0000000000..8ecf43c054
--- /dev/null
+++ b/rust/cloud-storage/bot_id/src/test.rs
@@ -0,0 +1,73 @@
+use super::*;
+
+#[test]
+fn storage_string_round_trips() {
+ let uuid = Uuid::new_v4();
+ let bot_id = BotId::new_from_uuid(uuid);
+
+ assert_eq!(
+ BotIdStr::parse_from_str(bot_id.into_storage_id().as_ref())
+ .unwrap()
+ .bot_id(),
+ bot_id
+ );
+}
+
+#[test]
+fn bot_id_str_parses_storage_string() {
+ let uuid = Uuid::new_v4();
+ let bot_id = BotId::new_from_uuid(uuid);
+ let storage = format!("bot|{uuid}");
+
+ let parsed = BotIdStr::parse_from_str(&storage).unwrap();
+
+ assert_eq!(parsed.bot_id(), bot_id);
+ assert_eq!(parsed.as_uuid(), uuid);
+ assert_eq!(parsed.bot_id().as_uuid().to_string(), uuid.to_string());
+ assert_eq!(parsed.as_ref(), storage);
+}
+
+#[test]
+fn bot_id_str_from_bot_id_creates_storage_string() {
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
+ let storage = BotIdStr::from(bot_id);
+
+ assert_eq!(storage.bot_id(), bot_id);
+ assert_eq!(storage.to_string(), format!("bot|{bot_id}"));
+}
+
+#[test]
+fn rejects_non_bot_storage_string() {
+ assert!(BotIdStr::parse_from_str("macro|[email protected]").is_err());
+}
+
+#[test]
+fn rejects_trailing_storage_content() {
+ let uuid = Uuid::new_v4();
+
+ assert!(BotIdStr::parse_from_str(&format!("bot|{uuid}|extra")).is_err());
+}
+
+#[test]
+fn rejects_non_canonical_storage_uuid() {
+ let uuid = Uuid::new_v4().simple().to_string();
+
+ assert!(BotIdStr::parse_from_str(&format!("bot|{uuid}")).is_err());
+}
+
+#[test]
+fn equality_and_hash_ignore_uuid_case() {
+ let lowercase = "bot|0a0b0c0d-0000-0000-0000-00000000a1a1".to_string();
+ let uppercase = "bot|0A0B0C0D-0000-0000-0000-00000000A1A1".to_string();
+
+ let lower = BotIdStr::parse_from_str(&lowercase).unwrap();
+ let upper = BotIdStr::parse_from_str(&uppercase).unwrap();
+
+ // Different original strings, same bot: equal and hash-compatible.
+ assert_eq!(lower, upper);
+ assert_eq!(lower.bot_id(), upper.bot_id());
+
+ let set: std::collections::HashSet<BotIdStr<'_>> =
+ [lower.clone(), upper.clone()].into_iter().collect();
+ assert_eq!(set.len(), 1);
+}
diff --git a/rust/cloud-storage/bots/src/inbound/axum_router/tests.rs b/rust/cloud-storage/bots/src/inbound/axum_router/tests.rs
index 7da8c9b343..6185cb8735 100644
--- a/rust/cloud-storage/bots/src/inbound/axum_router/tests.rs
+++ b/rust/cloud-storage/bots/src/inbound/axum_router/tests.rs
@@ -402,7 +402,7 @@ async fn read_bot_channels(response: axum::response::Response) -> Vec<BotChannel
async fn bot_owner_can_list_bot_channels_via_http() {
let channel_id = Uuid::new_v4();
let service = TestBotService::with_bot_channels(TestBotMode::Ok, vec![bot_channel(channel_id)]);
- let bot_id = BotId::from_uuid(Uuid::new_v4());
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
let request = Request::builder()
.method("GET")
.uri(format!("/bots/{bot_id}/channels"))
@@ -426,7 +426,7 @@ async fn bot_owner_can_list_bot_channels_via_http() {
#[tokio::test]
async fn bot_listing_requires_bot_usability() {
let service = TestBotService::new(TestBotMode::Unauthorized);
- let bot_id = BotId::from_uuid(Uuid::new_v4());
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
let request = Request::builder()
.method("GET")
.uri(format!("/bots/{bot_id}/channels"))
@@ -446,7 +446,7 @@ async fn bot_listing_requires_bot_usability() {
async fn bot_owner_can_remove_bot_from_channel_via_bot_route_without_channel_admin() {
let service = TestBotService::new(TestBotMode::Ok);
let channel_id = Uuid::new_v4();
- let bot_id = BotId::from_uuid(Uuid::new_v4());
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
let request = Request::builder()
.method("DELETE")
.uri(format!("/bots/{bot_id}/channels/{channel_id}"))
@@ -466,7 +466,7 @@ async fn bot_owner_can_remove_bot_from_channel_via_bot_route_without_channel_adm
async fn bot_remove_channel_requires_bot_usability() {
let service = TestBotService::new(TestBotMode::Unauthorized);
let channel_id = Uuid::new_v4();
- let bot_id = BotId::from_uuid(Uuid::new_v4());
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
let request = Request::builder()
.method("DELETE")
.uri(format!("/bots/{bot_id}/channels/{channel_id}"))
@@ -486,7 +486,7 @@ async fn bot_remove_channel_requires_bot_usability() {
async fn channel_member_cannot_add_bot_to_channel() {
let service = TestBotService::new(TestBotMode::Ok);
let channel_id = Uuid::new_v4();
- let bot_id = BotId::from_uuid(Uuid::new_v4());
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
let request = Request::builder()
.method("POST")
.uri(format!("/channels/{channel_id}/bots"))
@@ -509,7 +509,7 @@ async fn channel_member_cannot_add_bot_to_channel() {
async fn channel_admin_still_needs_bot_usability_to_add_bot() {
let service = TestBotService::new(TestBotMode::Unauthorized);
let channel_id = Uuid::new_v4();
- let bot_id = BotId::from_uuid(Uuid::new_v4());
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
let request = Request::builder()
.method("POST")
.uri(format!("/channels/{channel_id}/bots"))
@@ -532,7 +532,7 @@ async fn channel_admin_still_needs_bot_usability_to_add_bot() {
async fn channel_member_cannot_remove_bot_from_channel() {
let service = TestBotService::new(TestBotMode::Ok);
let channel_id = Uuid::new_v4();
- let bot_id = BotId::from_uuid(Uuid::new_v4());
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
let request = Request::builder()
.method("DELETE")
.uri(format!("/channels/{channel_id}/bots/{bot_id}"))
@@ -552,7 +552,7 @@ async fn channel_member_cannot_remove_bot_from_channel() {
async fn channel_admin_still_needs_bot_usability_to_remove_bot() {
let service = TestBotService::new(TestBotMode::Unauthorized);
let channel_id = Uuid::new_v4();
- let bot_id = BotId::from_uuid(Uuid::new_v4());
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
let request = Request::builder()
.method("DELETE")
.uri(format!("/channels/{channel_id}/bots/{bot_id}"))
@@ -598,7 +598,7 @@ async fn bot_owner_can_list_and_remove_bot_channels_via_bot_routes(
.add_bot_to_channel(macro_user_id(BOT_OWNER_ID), channel_id, bot.id)
.await?;
- let bot_principal_id = bot.id.to_storage_string();
+ let bot_principal_id = bot.id.into_storage_id().to_string();
let router = real_router(pool.clone(), BOT_OWNER_ID);
let list_request = Request::builder()
.method("GET")
@@ -680,7 +680,7 @@ async fn channel_admin_can_add_and_remove_owned_bot_via_http(pool: PgPool) -> an
)
.await?;
- let bot_principal_id = bot.id.to_storage_string();
+ let bot_principal_id = bot.id.into_storage_id().to_string();
let router = real_router(pool.clone(), ADMIN_USER_ID);
let add_request = Request::builder()
.method("POST")
diff --git a/rust/cloud-storage/bots/src/inbound/channel_webhook_router.rs b/rust/cloud-storage/bots/src/inbound/channel_webhook_router.rs
index 14e560f01e..8bea646770 100644
--- a/rust/cloud-storage/bots/src/inbound/channel_webhook_router.rs
+++ b/rust/cloud-storage/bots/src/inbound/channel_webhook_router.rs
@@ -243,7 +243,7 @@ where
let response = state
.channel_poster
.post_message(
- Sender::Bot(authenticated.bot_id),
+ Sender::new_from_bot(authenticated.bot_id),
path.channel_id,
PostMessageRequest {
content,
diff --git a/rust/cloud-storage/bots/src/inbound/channel_webhook_router/tests.rs b/rust/cloud-storage/bots/src/inbound/channel_webhook_router/tests.rs
index a0abfd0fbd..4963c5f936 100644
--- a/rust/cloud-storage/bots/src/inbound/channel_webhook_router/tests.rs
+++ b/rust/cloud-storage/bots/src/inbound/channel_webhook_router/tests.rs
@@ -478,7 +478,7 @@ fn scoped_bot_request_body() -> Body {
#[tokio::test]
async fn channel_webhook_router_member_cannot_create_scoped_bot() {
- let bot_id = BotId::from_uuid(Uuid::new_v4());
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
let service = TestBotService::for_create(scoped_bot_response(bot_id));
let poster = TestChannelPoster::new();
let channel_id = Uuid::new_v4();
@@ -500,7 +500,7 @@ async fn channel_webhook_router_member_cannot_create_scoped_bot() {
#[tokio::test]
async fn channel_webhook_router_admin_can_create_scoped_bot() {
- let bot_id = BotId::from_uuid(Uuid::new_v4());
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
let service = TestBotService::for_create(scoped_bot_response(bot_id));
let poster = TestChannelPoster::new();
let channel_id = Uuid::new_v4();
@@ -532,7 +532,7 @@ async fn channel_webhook_router_admin_can_create_scoped_bot() {
#[tokio::test]
async fn channel_webhook_router_valid_json_posts_as_bot() {
let channel_id = Uuid::new_v4();
- let bot_id = BotId::from_uuid(Uuid::new_v4());
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
let token = "mbot_test_valid";
let service = TestBotService::for_webhook(channel_id, token, bot_id);
let poster = TestChannelPoster::new();
@@ -566,7 +566,7 @@ async fn channel_webhook_router_valid_json_posts_as_bot() {
let calls = poster.calls.lock().expect("posted message mutex poisoned");
assert_eq!(calls.len(), 1);
let call = &calls[0];
- assert_eq!(call.actor, Sender::Bot(bot_id));
+ assert_eq!(call.actor, Sender::new_from_bot(bot_id));
assert_eq!(call.channel_id, channel_id);
assert_eq!(call.req.content, "hello");
assert!(call.req.mentions.is_empty());
@@ -578,7 +578,7 @@ async fn channel_webhook_router_valid_json_posts_as_bot() {
#[tokio::test]
async fn channel_webhook_router_raw_body_starting_with_brace_posts_as_bot() {
let channel_id = Uuid::new_v4();
- let bot_id = BotId::from_uuid(Uuid::new_v4());
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
let token = "mbot_test_valid";
let content = "{raw alert payload";
let service = TestBotService::for_webhook(channel_id, token, bot_id);
@@ -602,7 +602,7 @@ async fn channel_webhook_router_raw_body_starting_with_brace_posts_as_bot() {
let calls = poster.calls.lock().expect("posted message mutex poisoned");
assert_eq!(calls.len(), 1);
let call = &calls[0];
- assert_eq!(call.actor, Sender::Bot(bot_id));
+ assert_eq!(call.actor, Sender::new_from_bot(bot_id));
assert_eq!(call.channel_id, channel_id);
assert_eq!(call.req.content, content);
}
@@ -610,7 +610,7 @@ async fn channel_webhook_router_raw_body_starting_with_brace_posts_as_bot() {
#[tokio::test]
async fn channel_webhook_router_invalid_token_returns_unauthorized_without_posting() {
let channel_id = Uuid::new_v4();
- let bot_id = BotId::from_uuid(Uuid::new_v4());
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
let service = TestBotService::for_webhook(channel_id, "mbot_test_valid", bot_id);
let poster = TestChannelPoster::new();
let request = Request::builder()
@@ -673,7 +673,7 @@ async fn channel_webhook_router_missing_token_header_returns_unauthorized_withou
async fn channel_webhook_router_wrong_channel_returns_unauthorized_without_posting() {
let expected_channel_id = Uuid::new_v4();
let requested_channel_id = Uuid::new_v4();
- let bot_id = BotId::from_uuid(Uuid::new_v4());
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
let token = "mbot_test_valid";
let service = TestBotService::for_webhook(expected_channel_id, token, bot_id);
let poster = TestChannelPoster::new();
diff --git a/rust/cloud-storage/bots/src/outbound/pg_bots_repo.rs b/rust/cloud-storage/bots/src/outbound/pg_bots_repo.rs
index a620b468c7..2c31117f7c 100644
--- a/rust/cloud-storage/bots/src/outbound/pg_bots_repo.rs
+++ b/rust/cloud-storage/bots/src/outbound/pg_bots_repo.rs
@@ -31,7 +31,7 @@ impl PgBotsRepo {
}
fn principal_id(bot_id: BotId) -> String {
- bot_id.to_storage_string()
+ bot_id.into_storage_id().to_string()
}
fn owner_columns(owner: BotOwner) -> (Option<String>, Option<Uuid>) {
@@ -72,7 +72,7 @@ impl TryFrom<BotRow> for Bot {
};
Ok(Self {
- id: BotId::from_uuid(row.id),
+ id: BotId::new_from_uuid(row.id),
kind,
owner,
name: row.name,
@@ -129,7 +129,7 @@ impl From<BotTokenRow> for BotToken {
fn from(row: BotTokenRow) -> Self {
Self {
id: row.id,
- bot_id: BotId::from_uuid(row.bot_id),
+ bot_id: BotId::new_from_uuid(row.bot_id),
token: row.token,
label: row.label,
last_used_at: row.last_used_at,
@@ -155,7 +155,7 @@ struct TokenCandidateRow {
impl TokenCandidateRow {
fn into_candidate(self) -> anyhow::Result<BotTokenCandidate> {
- let bot_id = BotId::from_uuid(self.bot_id);
+ let bot_id = BotId::new_from_uuid(self.bot_id);
let kind = self
.kind
.parse::<BotKind>()
@@ -199,7 +199,7 @@ impl BotRepo for PgBotsRepo {
created_by: MacroUserIdStr<'static>,
req: CreateBotRequest,
) -> Result<Bot, Self::Err> {
- let bot_id = BotId::from_uuid(macro_uuid::generate_uuid_v7());
+ let bot_id = BotId::new_from_uuid(macro_uuid::generate_uuid_v7());
let (owner_user_id, team_id) = owner_columns(owner);
let row = sqlx::query_as!(
BotRow,
@@ -246,7 +246,7 @@ impl BotRepo for PgBotsRepo {
token: String,
req: CreateChannelScopedBotRequest,
) -> Result<(Bot, BotToken), Self::Err> {
- let bot_id = BotId::from_uuid(macro_uuid::generate_uuid_v7());
+ let bot_id = BotId::new_from_uuid(macro_uuid::generate_uuid_v7());
let token_id = macro_uuid::generate_uuid_v7();
let (owner_user_id, team_id) = owner_columns(owner);
let mut tx = self
diff --git a/rust/cloud-storage/channel_bots/src/domain/service.rs b/rust/cloud-storage/channel_bots/src/domain/service.rs
index aab864fb5b..102480b8ab 100644
--- a/rust/cloud-storage/channel_bots/src/domain/service.rs
+++ b/rust/cloud-storage/channel_bots/src/domain/service.rs
@@ -38,8 +38,8 @@ const CHANNEL_CONTEXT_INSTRUCTION: &str = "Recent messages in the channel around
/// Human-readable label for a message sender storage id.
fn sender_label(sender_id: &str) -> String {
- if let Ok(bot) = bot_id::BotId::parse_storage_str(sender_id) {
- return if bot == bot_id::MACRO_AI_BOT_ID {
+ if let Ok(bot) = bot_id::BotIdStr::parse_from_str(sender_id) {
+ return if bot.bot_id() == bot_id::MACRO_AI_BOT_ID {
bot_id::MACRO_AI_NAME.to_string()
} else {
"Bot".to_string()
@@ -253,7 +253,7 @@ where
/// React to a Macro AI mention.
#[tracing::instrument(skip(self, event), fields(channel_id = %event.channel_id), err)]
pub(crate) async fn handle(&self, event: &BotEvent) -> anyhow::Result<()> {
- let actor = Sender::Bot(bot_id::MACRO_AI_BOT_ID);
+ let actor = Sender::new_from_bot(bot_id::MACRO_AI_BOT_ID);
// 1. Gather conversational context (before posting, so our own
// "thinking" message is not included).
diff --git a/rust/cloud-storage/channel_bots/src/domain/service/tests.rs b/rust/cloud-storage/channel_bots/src/domain/service/tests.rs
index d7cfb27197..71fe503c02 100644
--- a/rust/cloud-storage/channel_bots/src/domain/service/tests.rs
+++ b/rust/cloud-storage/channel_bots/src/domain/service/tests.rs
@@ -328,7 +328,7 @@ fn mention_event(
id: trigger_id,
channel_id,
thread_id,
- sender_id: Sender::User(user_id(sender_email)),
+ sender_id: Sender::new_from_user(user_id(sender_email)),
content: content.to_string(),
created_at: Utc::now(),
updated_at: Utc::now(),
diff --git a/rust/cloud-storage/channel_sender/Cargo.toml b/rust/cloud-storage/channel_sender/Cargo.toml
new file mode 100644
index 0000000000..724a8fa009
--- /dev/null
+++ b/rust/cloud-storage/channel_sender/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+edition = "2024"
+name = "channel_sender"
+publish = false
+version = "0.1.0"
+
+[dependencies]
+bot_id = { path = "../bot_id" }
+either = { workspace = true }
+macro_user_id = { path = "../macro_user_id" }
+serde = { workspace = true }
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
+
+[dev-dependencies]
+serde_json = { workspace = true }
+uuid = { workspace = true }
diff --git a/rust/cloud-storage/channel_sender/src/lib.rs b/rust/cloud-storage/channel_sender/src/lib.rs
new file mode 100644
index 0000000000..5fdf0dfb23
--- /dev/null
+++ b/rust/cloud-storage/channel_sender/src/lib.rs
@@ -0,0 +1,99 @@
+#![deny(missing_docs)]
+//! This crate defines the [ChannelSender] which is a wrapper type which denotes either a first party macro user, OR, a bot user
+
+use bot_id::{BotId, BotIdStr, cowlike::CowLike};
+use either::Either;
+use macro_user_id::{error::ParseErr, user_id::MacroUserIdStr};
+use serde::{Deserialize, Serialize};
+
+#[cfg(test)]
+mod test;
+
+type InnerVal<'a> = Either<BotIdStr<'a>, MacroUserIdStr<'a>>;
+
+/// Actor identity for channel mutations.
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(try_from = "String", into = "String")]
+pub struct ChannelSender<'a>(pub InnerVal<'a>);
+
+impl<'a> TryFrom<&'a str> for ChannelSender<'a> {
+ type Error = ParseErr;
+
+ fn try_from(value: &'a str) -> Result<Self, Self::Error> {
+ Self::parse_from_str(value)
+ }
+}
+
+impl TryFrom<String> for ChannelSender<'static> {
+ type Error = ParseErr;
+
+ fn try_from(value: String) -> Result<Self, Self::Error> {
+ ChannelSender::parse_from_str(&value).map(CowLike::into_owned)
+ }
+}
+
+impl From<ChannelSender<'_>> for String {
+ fn from(value: ChannelSender<'_>) -> Self {
+ value.as_ref().to_string()
+ }
+}
+
+impl<'a> CowLike<'a> for ChannelSender<'a> {
+ type Owned<'b> = ChannelSender<'b>;
+
+ fn into_owned(self) -> Self::Owned<'static> {
+ ChannelSender(self.0.into_owned())
+ }
+
+ fn copied(&'a self) -> Self {
+ ChannelSender(self.0.copied())
+ }
+}
+
+impl<'a> ChannelSender<'a> {
+ /// attempt to return the user id str if this value contains a user
+ pub fn as_user(&self) -> Option<&MacroUserIdStr<'a>> {
+ self.0.as_ref().right()
+ }
+ /// attempt to return the bot id str if this value contains a bot
+ pub fn as_bot(&self) -> Option<&BotIdStr<'a>> {
+ self.0.as_ref().left()
+ }
+ /// attempt to return the user id str if this value contains a user
+ pub fn into_user(self) -> Option<MacroUserIdStr<'a>> {
+ self.0.right()
+ }
+ /// attempt to return the bot id str if this value contains a bot
+ pub fn into_bot(self) -> Option<BotIdStr<'a>> {
+ self.0.left()
+ }
+
+ /// attempt to parse a value of self from an input str
+ pub fn parse_from_str(value: &'a str) -> Result<Self, ParseErr> {
+ match BotIdStr::try_from(value) {
+ Ok(bot_id) => Ok(ChannelSender(Either::Left(bot_id))),
+ Err(_) => MacroUserIdStr::try_from(value)
+ .map(Either::Right)
+ .map(ChannelSender),
+ }
+ }
+
+ /// create a new instance of self containing a [MacroUserIdStr]
+ pub fn new_from_user(user: MacroUserIdStr<'a>) -> Self {
+ Self(InnerVal::Right(user))
+ }
+
+ /// create a new instance of self containing a [BotIdStr] derived from the given [BotId]
+ pub fn new_from_bot(bot_id: BotId) -> ChannelSender<'static> {
+ ChannelSender(Either::Left(bot_id.into_storage_id()))
+ }
+}
+
+impl<'a> AsRef<str> for ChannelSender<'a> {
+ fn as_ref(&self) -> &str {
+ match &self.0 {
+ Either::Left(l) => l.as_ref(),
+ Either::Right(r) => r.as_ref(),
+ }
+ }
+}
diff --git a/rust/cloud-storage/channel_sender/src/test.rs b/rust/cloud-storage/channel_sender/src/test.rs
new file mode 100644
index 0000000000..cfd35e816d
--- /dev/null
+++ b/rust/cloud-storage/channel_sender/src/test.rs
@@ -0,0 +1,34 @@
+use macro_user_id::email::ReadEmailParts;
+use uuid::Uuid;
+
+use super::*;
+
+#[test]
+fn sender_round_trips_user_storage_string() {
+ let sender = ChannelSender::parse_from_str("macro|[email protected]").unwrap();
+
+ assert_eq!(sender.as_ref(), "macro|[email protected]");
+ assert!(matches!(sender.0, InnerVal::Right(_)));
+}
+
+#[test]
+fn sender_round_trips_bot_storage_string() {
+ let id = Uuid::new_v4();
+ let storage = format!("bot|{id}");
+ let sender = ChannelSender::parse_from_str(&storage).unwrap();
+
+ assert_eq!(sender.as_ref(), storage);
+ let serialized = serde_json::to_value(&sender).unwrap();
+ assert_eq!(serialized, storage);
+
+ let deserialized: ChannelSender<'static> = serde_json::from_value(serialized).unwrap();
+ assert_eq!(deserialized.as_ref(), storage);
+ assert!(matches!(deserialized.0, InnerVal::Left(_)));
+}
+
+#[test]
+fn fallback_user_name_uses_email_local_part() {
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ assert_eq!(user_id.email_part().local_part(), "shepherd.hatton");
+}
diff --git a/rust/cloud-storage/channels/Cargo.toml b/rust/cloud-storage/channels/Cargo.toml
index ce5614fe1c..cb1e0cf38c 100644
--- a/rust/cloud-storage/channels/Cargo.toml
+++ b/rust/cloud-storage/channels/Cargo.toml
@@ -5,6 +5,14 @@ publish = false
version = "0.1.0"
[features]
+ai_tools = [
+ "dep:ai_toolset",
+ "dep:async-trait",
+ "dep:entity_access",
+ "dep:schemars",
+ "entity_access/ports",
+ "ports",
+]
attachment = [
"dep:attachment",
"dep:entity_access",
@@ -14,21 +22,13 @@ attachment = [
"entity_access/ports",
"ports",
]
-ai_tools = [
- "dep:ai_toolset",
- "dep:async-trait",
- "dep:entity_access",
- "dep:schemars",
- "entity_access/ports",
- "ports",
-]
inbound = [
"dep:axum",
"dep:entity_access",
- "entity_access/inbound",
"dep:model-error-response",
"dep:model_user",
"dep:utoipa",
+ "entity_access/inbound",
"models_pagination/axum",
"ports",
]
@@ -44,12 +44,9 @@ list = [
"ports",
]
outbound = [
- "list",
- "ports",
"dep:connection_gateway_client",
"dep:contacts",
"dep:entity_access",
- "entity_access/ports",
"dep:entity_access_db_utils",
"dep:macro_uuid",
"dep:model-entity",
@@ -58,9 +55,12 @@ outbound = [
"dep:notification_hex",
"dep:serde_json",
"dep:share_permission_db_utils",
- "dep:sqs_client",
"dep:sqlx",
+ "dep:sqs_client",
+ "entity_access/ports",
+ "list",
"macro_user_id/sqlx",
+ "ports",
]
ports = ["dep:tokio"]
@@ -69,32 +69,37 @@ anyhow = { workspace = true }
attachment = { path = "../attachment", optional = true }
axum = { workspace = true, optional = true }
bot_id = { path = "../bot_id" }
+channel_sender = { path = "../channel_sender" }
chrono = { workspace = true }
connection_gateway_client = { path = "../connection_gateway_client", optional = true }
-contacts = { path = "../contacts", default-features = false, features = ["outbound"], optional = true }
+contacts = { path = "../contacts", default-features = false, features = [
+ "outbound",
+], optional = true }
entity_access = { path = "../entity_access", optional = true, default-features = false }
entity_access_db_utils = { path = "../entity_access_db_utils", optional = true }
filter_ast = { path = "../filter_ast", optional = true }
frecency = { path = "../frecency", optional = true }
futures = { workspace = true, optional = true }
-model-error-response = { path = "../model-error-response", optional = true }
+item_filters = { path = "../item_filters", optional = true }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid", optional = true }
model-entity = { path = "../model-entity", optional = true }
+model-error-response = { path = "../model-error-response", optional = true }
model_notifications = { path = "../model_notifications", optional = true }
model_user = { path = "../model_user", optional = true, features = ["axum"] }
models_pagination = { path = "../models_pagination" }
models_permissions = { path = "../models_permissions", optional = true }
-item_filters = { path = "../item_filters", optional = true }
non_empty = { path = "../non_empty", optional = true }
notification_hex = { path = "../notification", package = "notification", optional = true }
+recursion = { workspace = true, optional = true }
+rootcause = { workspace = true, optional = true }
serde = { workspace = true }
serde_json = { workspace = true, optional = true }
share_permission_db_utils = { path = "../share_permission_db_utils", optional = true }
sqlx = { workspace = true, optional = true }
-sqs_client = { path = "../sqs_client", default-features = false, features = ["search"], optional = true }
-recursion = { workspace = true, optional = true }
-rootcause = { workspace = true, optional = true }
+sqs_client = { path = "../sqs_client", default-features = false, features = [
+ "search",
+], optional = true }
thiserror = { workspace = true }
tokio = { workspace = true, features = ["macros", "sync"], optional = true }
tracing = { workspace = true }
diff --git a/rust/cloud-storage/channels/src/domain/events.rs b/rust/cloud-storage/channels/src/domain/events.rs
index 45d91ed65b..3162015915 100644
--- a/rust/cloud-storage/channels/src/domain/events.rs
+++ b/rust/cloud-storage/channels/src/domain/events.rs
@@ -4,6 +4,7 @@ use crate::domain::models::{
ChannelMetadata, ChannelParticipant, ChannelType, CountedReaction, MutatedAttachment,
MutatedMessage, PostMessageNotificationPolicy, Sender, SimpleMention, TypingAction,
};
+use channel_sender::ChannelSender;
use macro_user_id::user_id::MacroUserIdStr;
use uuid::Uuid;
@@ -28,7 +29,7 @@ pub enum ChannelEvent {
/// Created channel id.
channel_id: Uuid,
/// Actor that created the channel.
- actor: Sender,
+ actor: ChannelSender<'static>,
/// Type of channel that was created.
channel_type: ChannelType,
/// Active participants after creation.
@@ -39,7 +40,7 @@ pub enum ChannelEvent {
/// Deleted channel id.
channel_id: Uuid,
/// Actor that deleted the channel.
- actor: Sender,
+ actor: ChannelSender<'static>,
},
/// A message was posted.
MessagePosted {
diff --git a/rust/cloud-storage/channels/src/domain/models.rs b/rust/cloud-storage/channels/src/domain/models.rs
index 7c8a19f2e0..02767bbc54 100644
--- a/rust/cloud-storage/channels/src/domain/models.rs
+++ b/rust/cloud-storage/channels/src/domain/models.rs
@@ -1,3 +1,4 @@
+pub use channel_sender::ChannelSender;
use chrono::{DateTime, Utc};
#[cfg(feature = "list")]
use item_filters::ast::{
@@ -8,98 +9,14 @@ use macro_user_id::{email::ReadEmailParts, user_id::MacroUserIdStr};
use models_pagination::{CreatedAt, CursorVal, Identify, SortOn};
#[cfg(feature = "list")]
use models_pagination::{Query, SimpleSortMethod};
-use serde::{Deserialize, Serialize, Serializer};
-use std::collections::HashMap;
+use serde::{Deserialize, Serialize};
+use std::collections::{HashMap, HashSet};
use uuid::Uuid;
pub use bot_id::BotId;
-/// Error returned when a sender storage string is not a user or bot id.
-#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
-#[error("invalid sender id: {value}")]
-pub struct SenderParseError {
- value: String,
-}
-
-impl SenderParseError {
- fn invalid(value: &str) -> Self {
- Self {
- value: value.to_string(),
- }
- }
-}
-
/// Actor identity for channel mutations.
-#[derive(Debug, Clone, PartialEq, Eq, Hash)]
-pub enum Sender {
- /// A first-party Macro user.
- User(MacroUserIdStr<'static>),
- /// A channel-scoped or system bot.
- Bot(BotId),
-}
-
-impl Sender {
- /// Parse a sender id from the existing TEXT storage representation.
- pub fn parse_storage_str(value: &str) -> Result<Self, SenderParseError> {
- if let Ok(bot_id) = BotId::parse_storage_str(value) {
- return Ok(Self::Bot(bot_id));
- }
-
- MacroUserIdStr::try_from(value.to_string())
- .map(Self::User)
- .map_err(|_| SenderParseError::invalid(value))
- }
-
- /// Canonical storage representation for existing TEXT sender/participant columns.
- pub fn to_storage_string(&self) -> String {
- match self {
- Self::User(user_id) => user_id.as_ref().to_string(),
- Self::Bot(bot_id) => bot_id.to_storage_string(),
- }
- }
-
- /// Return the authenticated user id when the sender is a user.
- pub fn as_user(&self) -> Option<&MacroUserIdStr<'static>> {
- match self {
- Self::User(user_id) => Some(user_id),
- Self::Bot(_) => None,
- }
- }
-
- /// Whether this sender is a bot.
- pub const fn is_bot(&self) -> bool {
- matches!(self, Self::Bot(_))
- }
-}
-
-impl From<MacroUserIdStr<'static>> for Sender {
- fn from(user_id: MacroUserIdStr<'static>) -> Self {
- Self::User(user_id)
- }
-}
-
-impl std::str::FromStr for Sender {
- type Err = SenderParseError;
-
- fn from_str(value: &str) -> Result<Self, Self::Err> {
- Self::parse_storage_str(value)
- }
-}
-
-impl std::fmt::Display for Sender {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- f.write_str(&self.to_storage_string())
- }
-}
-
-impl Serialize for Sender {
- fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
- where
- S: Serializer,
- {
- serializer.serialize_str(&self.to_storage_string())
- }
-}
+pub type Sender = ChannelSender<'static>;
/// Public bot profile attached to bot-authored messages.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
@@ -782,7 +699,8 @@ pub struct CreateChannelRequest {
/// Team id for team channels.
pub team_id: Option<Uuid>,
/// Participants to add, excluding the owner.
- pub participants: Vec<String>,
+ #[cfg_attr(feature = "inbound", schema(value_type = HashSet<String>))]
+ pub participants: HashSet<MacroUserIdStr<'static>>,
}
/// Response returned after creating a channel.
@@ -798,7 +716,8 @@ pub struct CreateChannelResponse {
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
pub struct GetOrCreateDmRequest {
/// Recipient user id.
- pub recipient_id: String,
+ #[cfg_attr(feature = "inbound", schema(value_type = String))]
+ pub recipient_id: MacroUserIdStr<'static>,
}
/// Request to get or create a private channel.
@@ -806,7 +725,8 @@ pub struct GetOrCreateDmRequest {
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
pub struct GetOrCreatePrivateRequest {
/// Recipient user ids.
- pub recipients: Vec<String>,
+ #[cfg_attr(feature = "inbound", schema(value_type = HashSet<String>))]
+ pub recipients: HashSet<MacroUserIdStr<'static>>,
}
/// Response for get-or-create channel operations.
@@ -1040,7 +960,8 @@ pub struct PostTypingRequest {
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
pub struct AddParticipantsRequest {
/// User ids to add.
- pub participants: Vec<String>,
+ #[cfg_attr(feature = "inbound", schema(value_type = HashSet<String>))]
+ pub participants: HashSet<MacroUserIdStr<'static>>,
}
/// Request to remove participants.
@@ -1070,7 +991,7 @@ pub struct MutatedMessage {
/// Thread parent id.
pub thread_id: Option<Uuid>,
/// Sender actor id.
- pub sender_id: Sender,
+ pub sender_id: ChannelSender<'static>,
/// For an agent (bot) message, the id of the user who triggered it.
pub triggered_by: Option<String>,
/// Message body.
@@ -1452,33 +1373,3 @@ pub struct DeleteEntityMentionResponse {
/// Whether the mention was deleted.
pub deleted: bool,
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn sender_round_trips_user_storage_string() {
- let sender = Sender::parse_storage_str("macro|[email protected]").unwrap();
-
- assert_eq!(sender.to_storage_string(), "macro|[email protected]");
- assert!(matches!(sender, Sender::User(_)));
- }
-
- #[test]
- fn sender_round_trips_bot_storage_string() {
- let id = Uuid::new_v4();
- let storage = format!("bot|{id}");
- let sender = Sender::parse_storage_str(&storage).unwrap();
-
- assert_eq!(sender.to_storage_string(), storage);
- assert_eq!(serde_json::to_value(&sender).unwrap(), storage);
- }
-
- #[test]
- fn fallback_user_name_uses_email_local_part() {
- let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
-
- assert_eq!(fallback_user_name(&user_id), "shepherd.hatton");
- }
-}
diff --git a/rust/cloud-storage/channels/src/domain/ports.rs b/rust/cloud-storage/channels/src/domain/ports.rs
index f3eb2b1ade..732ed472de 100644
--- a/rust/cloud-storage/channels/src/domain/ports.rs
+++ b/rust/cloud-storage/channels/src/domain/ports.rs
@@ -23,6 +23,7 @@ use crate::domain::side_effects::{
ChannelDocumentMention, ChannelNotificationEffect, ChannelRealtimeEffect,
ThreadNotificationContext,
};
+use channel_sender::ChannelSender;
use chrono::{DateTime, Utc};
use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{CreatedAt, Query};
@@ -253,24 +254,24 @@ pub trait ChannelRepo: Send + Sync + 'static {
) -> impl Future<Output = Result<bool, Self::Err>> + Send;
/// Create a channel.
- fn create_channel(
+ fn create_channel<'a>(
&self,
- owner_id: String,
+ owner_id: MacroUserIdStr<'a>,
org_id: Option<i64>,
req: CreateChannelRequest,
) -> impl Future<Output = Result<Uuid, Self::Err>> + Send;
/// Fetch an existing direct message channel.
- fn maybe_get_dm(
+ fn maybe_get_dm<'a>(
&self,
- user_id: String,
- recipient_id: String,
+ user_id: MacroUserIdStr<'a>,
+ recipient_id: MacroUserIdStr<'a>,
) -> impl Future<Output = Result<Option<Uuid>, Self::Err>> + Send;
/// Fetch an existing private channel.
- fn maybe_get_private_channel(
+ fn maybe_get_private_channel<'a>(
&self,
- participants: Vec<String>,
+ participants: HashSet<MacroUserIdStr<'a>>,
) -> impl Future<Output = Result<Option<Uuid>, Self::Err>> + Send;
/// Patch a channel.
@@ -289,10 +290,10 @@ pub trait ChannelRepo: Send + Sync + 'static {
) -> impl Future<Output = Result<(), Self::Err>> + Send;
/// Add a participant.
- fn add_participant(
+ fn add_participant<'a>(
&self,
channel_id: Uuid,
- user_id: String,
+ user_id: MacroUserIdStr<'a>,
role: super::models::ParticipantRole,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
@@ -308,10 +309,10 @@ pub trait ChannelRepo: Send + Sync + 'static {
/// `triggered_by_user_id` is the id of the user who triggered an agent
/// (bot) message, persisted to the nullable `triggered_by_user_id` column;
/// `None` for ordinary human messages.
- fn create_message(
+ fn create_message<'a>(
&self,
channel_id: Uuid,
- sender_id: String,
+ sender_id: ChannelSender<'a>,
triggered_by_user_id: Option<String>,
content: String,
thread_id: Option<Uuid>,
@@ -409,7 +410,7 @@ pub trait ChannelRepo: Send + Sync + 'static {
&self,
channel_id: Uuid,
message_id: Uuid,
- ) -> impl Future<Output = Result<Option<String>, Self::Err>> + Send;
+ ) -> impl Future<Output = Result<Option<ChannelSender<'static>>, Self::Err>> + Send;
/// Fetch active participants.
fn get_participants(
@@ -424,9 +425,9 @@ pub trait ChannelRepo: Send + Sync + 'static {
) -> impl Future<Output = Result<Vec<MacroUserIdStr<'static>>, Self::Err>> + Send;
/// Upsert activity for the user in the channel.
- fn upsert_activity(
+ fn upsert_activity<'a>(
&self,
- user_id: String,
+ user_id: ChannelSender<'a>,
channel_id: Uuid,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
@@ -445,21 +446,21 @@ pub trait ChannelRepo: Send + Sync + 'static {
) -> impl Future<Output = Result<Activity, Self::Err>> + Send;
/// Add a reaction to a message within a channel.
- fn add_reaction(
+ fn add_reaction<'a>(
&self,
channel_id: Uuid,
message_id: Uuid,
emoji: String,
- user_id: String,
+ user_id: ChannelSender<'a>,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
/// Remove a reaction from a message within a channel.
- fn remove_reaction(
+ fn remove_reaction<'a>(
&self,
channel_id: Uuid,
message_id: Uuid,
emoji: String,
- user_id: String,
+ user_id: ChannelSender<'a>,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
/// Get grouped reactions for a message within a channel.
diff --git a/rust/cloud-storage/channels/src/domain/service.rs b/rust/cloud-storage/channels/src/domain/service.rs
index df7e0c5c6b..b62aca1e08 100644
--- a/rust/cloud-storage/channels/src/domain/service.rs
+++ b/rust/cloud-storage/channels/src/domain/service.rs
@@ -19,6 +19,9 @@ use crate::domain::{
ChannelRepo, ChannelService,
},
};
+use bot_id::BotIdStr;
+use bot_id::cowlike::CowLike;
+use channel_sender::ChannelSender;
use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{CreatedAt, PaginateOn, Query};
use std::collections::{HashMap, HashSet};
@@ -222,7 +225,8 @@ where
) -> Result<HashMap<BotId, BotSenderProfile>, ChannelMessagesErr> {
let bot_ids: HashSet<BotId> = sender_ids
.into_iter()
- .filter_map(|id| BotId::parse_storage_str(id).ok())
+ .filter_map(|id| BotIdStr::parse_from_str(id).ok())
+ .map(|x| x.bot_id())
.collect();
if bot_ids.is_empty() {
return Ok(HashMap::new());
@@ -242,25 +246,10 @@ fn bot_profile_for(
profiles: &HashMap<BotId, BotSenderProfile>,
sender_id: &str,
) -> Option<BotSenderProfile> {
- let bot_id = BotId::parse_storage_str(sender_id).ok()?;
+ let bot_id = BotIdStr::parse_from_str(sender_id).ok()?.bot_id();
profiles.get(&bot_id).cloned()
}
-fn lower_macro_users(users: &[String]) -> Vec<String> {
- users
- .iter()
- .map(|u| u.to_lowercase())
- .filter(|u| u.starts_with("macro|"))
- .collect()
-}
-
-fn parse_macro_user_id(
- user_id: impl Into<String>,
-) -> Result<MacroUserIdStr<'static>, ChannelMutationErr> {
- MacroUserIdStr::try_from(user_id.into())
- .map_err(|_| ChannelMutationErr::BadRequest("invalid user id".to_string()))
-}
-
fn require_user_actor(actor: &Sender) -> Result<MacroUserIdStr<'static>, ChannelMutationErr> {
actor
.as_user()
@@ -294,24 +283,15 @@ fn is_admin_or_owner(role: ParticipantRole) -> bool {
matches!(role, ParticipantRole::Owner | ParticipantRole::Admin)
}
-fn parse_user_ids(
- users: impl IntoIterator<Item = String>,
-) -> Result<Vec<MacroUserIdStr<'static>>, ChannelMutationErr> {
- users
+/// returns all user participants in a channel given an iterator of participants and the channel owner
+fn created_channel_participant_ids<'a>(
+ owner_id: MacroUserIdStr<'a>,
+ participants: impl IntoIterator<Item = MacroUserIdStr<'a>>,
+) -> HashSet<MacroUserIdStr<'a>> {
+ participants
.into_iter()
- .map(parse_macro_user_id)
- .collect::<Result<Vec<_>, _>>()
-}
-
-fn created_channel_participant_ids(
- owner_id: &str,
- participants: &[String],
-) -> Result<Vec<MacroUserIdStr<'static>>, ChannelMutationErr> {
- let mut users = participants.to_vec();
- if !users.iter().any(|user| user == owner_id) {
- users.push(owner_id.to_string());
- }
- parse_user_ids(users)
+ .chain(std::iter::once(owner_id))
+ .collect()
}
impl<R, E, P> ChannelServiceImpl<R, E, P>
@@ -351,26 +331,26 @@ where
}
let org_id = None;
- let participants = lower_macro_users(&req.participants);
- if participants.is_empty() {
+ if req.participants.is_empty() {
return Err(ChannelMutationErr::BadRequest(
"participants must be a non-empty list of 'macro|<email>'".to_string(),
));
}
- let create_req = crate::domain::models::CreateChannelRequest {
- participants: participants.clone(),
- ..req.clone()
- };
+
+ let participants_clone = req.participants.clone();
+ let channel_type = req.channel_type;
let channel_id = self
- .create_channel_record(actor.as_ref().to_string(), org_id, create_req)
+ .create_channel_record(actor.copied(), org_id, req)
.await?;
self.events.dispatch(ChannelEvent::ChannelCreated {
channel_id,
- actor: Sender::User(actor.clone()),
- channel_type: req.channel_type,
- participant_user_ids: created_channel_participant_ids(actor.as_ref(), &participants)?,
+ actor: Sender::new_from_user(actor.clone()),
+ channel_type,
+ participant_user_ids: created_channel_participant_ids(actor, participants_clone)
+ .into_iter()
+ .collect(),
});
Ok(crate::domain::models::CreateChannelResponse {
@@ -378,27 +358,15 @@ where
})
}
- #[tracing::instrument(err, skip(self, req))]
+ #[tracing::instrument(err, skip(self, recipient_id))]
async fn get_or_create_dm(
&self,
actor: Sender,
- req: GetOrCreateDmRequest,
+ GetOrCreateDmRequest { recipient_id }: GetOrCreateDmRequest,
) -> Result<GetOrCreateChannelResponse, ChannelMutationErr> {
let actor = require_user_actor(&actor)?;
- let recipient_id = req.recipient_id.to_lowercase();
- let user_id = actor.as_ref().to_lowercase();
- if recipient_id.is_empty() {
- return Err(ChannelMutationErr::BadRequest(
- "recipient_id must be a non-empty string".to_string(),
- ));
- }
- if !recipient_id.starts_with("macro|") {
- return Err(ChannelMutationErr::BadRequest(
- "recipient_id must be 'macro|<email>'".to_string(),
- ));
- }
- if recipient_id == user_id {
+ if actor == recipient_id {
return Err(ChannelMutationErr::BadRequest(
"recipient_id cannot be the same as the user_id".to_string(),
));
@@ -406,19 +374,19 @@ where
let existing_channel_id = self
.repo
- .maybe_get_dm(user_id.clone(), recipient_id.clone())
+ .maybe_get_dm(actor.clone(), recipient_id.clone())
.await
.map_err(|e| ChannelMutationErr::Repo(e.into()))?;
self.get_or_create_channel(
existing_channel_id,
- user_id.clone(),
+ actor.clone(),
None,
crate::domain::models::CreateChannelRequest {
name: None,
channel_type: ChannelType::DirectMessage,
team_id: None,
- participants: vec![user_id.clone(), recipient_id.clone()],
+ participants: HashSet::from([actor, recipient_id.clone()]),
},
)
.await
@@ -428,19 +396,17 @@ where
async fn get_or_create_private(
&self,
actor: Sender,
- mut req: GetOrCreatePrivateRequest,
+ req: GetOrCreatePrivateRequest,
) -> Result<GetOrCreateChannelResponse, ChannelMutationErr> {
let actor = require_user_actor(&actor)?;
- req.recipients = lower_macro_users(&req.recipients);
if req.recipients.is_empty() {
return Err(ChannelMutationErr::BadRequest(
"recipients must be a non-empty list of 'macro|<email>'".to_string(),
));
}
- let user_id = actor.as_ref().to_lowercase();
let mut lookup = req.recipients.clone();
- lookup.push(user_id.clone());
+ lookup.insert(actor.clone());
let existing_channel_id = self
.repo
.maybe_get_private_channel(lookup)
@@ -449,7 +415,7 @@ where
self.get_or_create_channel(
existing_channel_id,
- user_id,
+ actor,
None,
crate::domain::models::CreateChannelRequest {
name: None,
@@ -498,7 +464,7 @@ where
.map_err(|e| ChannelMutationErr::Repo(e.into()))?;
self.events.dispatch(ChannelEvent::ChannelDeleted {
channel_id,
- actor: Sender::User(actor),
+ actor: Sender::new_from_user(actor),
});
Ok(())
}
@@ -510,12 +476,11 @@ where
channel_id: Uuid,
req: PostMessageRequest,
) -> Result<PostMessageResponse, ChannelMutationErr> {
- let actor_storage_id = actor.to_storage_string();
let message = self
.repo
.create_message(
channel_id,
- actor_storage_id.clone(),
+ actor.clone(),
req.triggered_by.clone(),
req.content.clone(),
req.thread_id,
@@ -574,10 +539,7 @@ where
.map_err(|e| ChannelMutationErr::Repo(e.into()))?;
if actor.as_user().is_some()
- && let Err(err) = self
- .repo
- .upsert_activity(actor_storage_id, channel_id)
- .await
+ && let Err(err) = self.repo.upsert_activity(actor, channel_id).await
{
let err: anyhow::Error = err.into();
tracing::error!(error=?err, "unable to upsert activity for message");
@@ -626,14 +588,13 @@ where
notification_policy,
} = req;
- let actor_storage_id = actor.to_storage_string();
let owner = self
.repo
.get_message_owner(channel_id, message_id)
.await
.map_err(|e| ChannelMutationErr::Repo(e.into()))?
.ok_or_else(|| ChannelMutationErr::NotFound("message not found".to_string()))?;
- if owner.as_str() != actor_storage_id.as_str() && !is_admin_or_owner(actor_role) {
+ if owner != actor && !is_admin_or_owner(actor_role) {
return Err(ChannelMutationErr::Unauthorized(
"user is not authorized to edit this message".to_string(),
));
@@ -751,10 +712,7 @@ where
});
if actor.as_user().is_some()
- && let Err(err) = self
- .repo
- .upsert_activity(actor_storage_id.clone(), channel_id)
- .await
+ && let Err(err) = self.repo.upsert_activity(actor.clone(), channel_id).await
{
let err: anyhow::Error = err.into();
tracing::error!(error=?err, "unable to upsert activity for message");
@@ -764,10 +722,7 @@ where
if attachments_changed
&& content.is_none()
&& actor.as_user().is_some()
- && let Err(err) = self
- .repo
- .upsert_activity(actor_storage_id, channel_id)
- .await
+ && let Err(err) = self.repo.upsert_activity(actor, channel_id).await
{
let err: anyhow::Error = err.into();
tracing::error!(error=?err, "unable to upsert activity for attachment patch");
@@ -785,7 +740,6 @@ where
message_id: Uuid,
query: DeleteMessageQuery,
) -> Result<(), ChannelMutationErr> {
- let actor_storage_id = actor.to_storage_string();
let owner = self
.repo
.get_message_owner(channel_id, message_id)
@@ -793,11 +747,8 @@ where
.map_err(|e| ChannelMutationErr::Repo(e.into()))?
.ok_or_else(|| ChannelMutationErr::NotFound("message not found".to_string()))?;
// Any participant may delete bot-authored messages.
- let owner_is_bot = Sender::parse_storage_str(&owner).is_ok_and(|owner| owner.is_bot());
- if owner.as_str() != actor_storage_id.as_str()
- && !owner_is_bot
- && !is_admin_or_owner(actor_role)
- {
+ let owner_is_bot = owner.as_bot().is_some();
+ if owner != actor && !owner_is_bot && !is_admin_or_owner(actor_role) {
return Err(ChannelMutationErr::Unauthorized(
"user is not authorized to delete this message".to_string(),
));
@@ -831,7 +782,6 @@ where
channel_id: Uuid,
req: PostReactionRequest,
) -> Result<(), ChannelMutationErr> {
- let actor_storage_id = actor.to_storage_string();
let message_id = Uuid::parse_str(&req.message_id)
.map_err(|err| ChannelMutationErr::BadRequest(err.to_string()))?;
self.repo
@@ -842,12 +792,12 @@ where
match req.action {
ReactionAction::Add => {
self.repo
- .add_reaction(channel_id, message_id, req.emoji, actor_storage_id.clone())
+ .add_reaction(channel_id, message_id, req.emoji, actor.clone())
.await
}
ReactionAction::Remove => {
self.repo
- .remove_reaction(channel_id, message_id, req.emoji, actor_storage_id.clone())
+ .remove_reaction(channel_id, message_id, req.emoji, actor.clone())
.await
}
}
@@ -874,10 +824,7 @@ where
});
if actor.as_user().is_some()
- && let Err(err) = self
- .repo
- .upsert_activity(actor_storage_id, channel_id)
- .await
+ && let Err(err) = self.repo.upsert_activity(actor, channel_id).await
{
let err: anyhow::Error = err.into();
tracing::error!(error=?err, "unable to upsert activity for reaction");
@@ -933,10 +880,9 @@ where
));
}
- let participants_to_add = lower_macro_users(&req.participants);
- for participant in &participants_to_add {
+ for participant in &req.participants {
self.repo
- .add_participant(channel_id, participant.clone(), ParticipantRole::Member)
+ .add_participant(channel_id, participant.copied(), ParticipantRole::Member)
.await
.map_err(|e| ChannelMutationErr::Repo(e.into()))?;
}
@@ -947,10 +893,6 @@ where
.await
.map_err(|e| ChannelMutationErr::Repo(e.into()))?;
- let recipients = participants_to_add
- .iter()
- .filter_map(|id| MacroUserIdStr::try_from(id.clone()).ok())
- .collect();
let channel_metadata = self
.repo
.get_channel_metadata(channel_id, actor_user.clone())
@@ -961,8 +903,8 @@ where
channel_id,
channel_type: info.channel_type,
active_participant_user_ids,
- invited_by: Sender::User(actor_user),
- recipient_user_ids: recipients,
+ invited_by: Sender::new_from_user(actor_user),
+ recipient_user_ids: req.participants.into_iter().collect(),
metadata: channel_metadata,
message_content: None,
});
@@ -1032,11 +974,7 @@ where
.await
.map_err(|e| ChannelMutationErr::Repo(e.into()))?;
self.repo
- .add_participant(
- channel_id,
- actor_user.as_ref().to_string(),
- ParticipantRole::Member,
- )
+ .add_participant(channel_id, actor_user.copied(), ParticipantRole::Member)
.await
.map_err(|e| ChannelMutationErr::Repo(e.into()))?;
@@ -1050,7 +988,7 @@ where
self.events.dispatch(ChannelEvent::ParticipantJoined {
channel_id,
channel_type: info.channel_type,
- user_id: Sender::User(actor_user),
+ user_id: Sender::new_from_user(actor_user),
active_participant_user_ids,
});
Ok(())
@@ -1094,9 +1032,9 @@ where
E: ChannelEventDispatcher,
P: ChannelReferenceSharePermissions,
{
- async fn create_channel_record(
+ async fn create_channel_record<'a>(
&self,
- owner_id: String,
+ owner_id: MacroUserIdStr<'a>,
org_id: Option<i64>,
req: crate::domain::models::CreateChannelRequest,
) -> Result<Uuid, ChannelMutationErr> {
@@ -1109,7 +1047,7 @@ where
async fn get_or_create_channel(
&self,
existing_channel_id: Option<Uuid>,
- owner_id: String,
+ owner_id: MacroUserIdStr<'static>,
org_id: Option<i64>,
create_req: crate::domain::models::CreateChannelRequest,
) -> Result<GetOrCreateChannelResponse, ChannelMutationErr> {
@@ -1121,10 +1059,11 @@ where
}
let channel_type = create_req.channel_type;
+ let owner_sender = ChannelSender::new_from_user(owner_id.clone());
let participant_user_ids =
- created_channel_participant_ids(&owner_id, &create_req.participants)?;
- let owner_sender = Sender::parse_storage_str(&owner_id)
- .map_err(|err| ChannelMutationErr::BadRequest(format!("invalid owner id: {err}")))?;
+ created_channel_participant_ids(owner_id.clone(), create_req.participants.clone())
+ .into_iter()
+ .collect();
let channel_id = self
.create_channel_record(owner_id, org_id, create_req)
.await?;
@@ -1469,7 +1408,7 @@ where
) -> Result<Activity, ChannelMutationErr> {
let activity = self
.repo
- .set_activity(actor.to_storage_string(), channel_id, activity_type)
+ .set_activity(actor.as_ref().to_string(), channel_id, activity_type)
.await
.map_err(anyhow::Error::from)?;
diff --git a/rust/cloud-storage/channels/src/domain/service/test.rs b/rust/cloud-storage/channels/src/domain/service/test.rs
index 98c358e6fa..5cd578998f 100644
--- a/rust/cloud-storage/channels/src/domain/service/test.rs
+++ b/rust/cloud-storage/channels/src/domain/service/test.rs
@@ -16,8 +16,9 @@ use crate::domain::{
TopLevelMessagesQueryResult,
},
};
+use channel_sender::ChannelSender;
use chrono::Utc;
-use macro_user_id::user_id::MacroUserIdStr;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use std::{
collections::HashMap,
sync::{Arc, Mutex},
@@ -185,20 +186,20 @@ async fn returns_messages_with_thread_info() {
#[tokio::test]
async fn attaches_bot_profiles_to_bot_authored_messages() {
- let seeded_bot = BotId::from_uuid(Uuid::new_v4());
+ let seeded_bot = BotId::new_from_uuid(Uuid::new_v4());
let unseeded_bot = bot_id::MACRO_AI_BOT_ID;
let parent_id = Uuid::new_v4();
let macro_ai_msg_id = Uuid::new_v4();
let mut bot_row = make_row(parent_id, 10);
- bot_row.sender_id = seeded_bot.to_storage_string();
+ bot_row.sender_id = seeded_bot.into_storage_id().to_string();
let mut macro_ai_row = make_row(macro_ai_msg_id, 5);
- macro_ai_row.sender_id = unseeded_bot.to_storage_string();
+ macro_ai_row.sender_id = unseeded_bot.into_storage_id().to_string();
let reply_row = ThreadReplyRow {
id: Uuid::new_v4(),
thread_id: parent_id,
- sender_id: seeded_bot.to_storage_string(),
+ sender_id: seeded_bot.into_storage_id().to_string(),
triggered_by: None,
content: "reply".into(),
created_at: Utc::now(),
@@ -299,7 +300,7 @@ impl FakeMutationRepo {
id: Uuid::new_v4(),
channel_id,
thread_id: None,
- sender_id: Sender::parse_storage_str(sender).unwrap(),
+ sender_id: ChannelSender::parse_from_str(sender).unwrap().into_owned(),
triggered_by: None,
content: "hello".to_string(),
created_at: now,
@@ -490,7 +491,7 @@ impl ChannelRepo for FakeMutationRepo {
async fn create_channel(
&self,
- _owner_id: String,
+ _owner_id: MacroUserIdStr<'_>,
_org_id: Option<i64>,
_req: crate::domain::models::CreateChannelRequest,
) -> Result<Uuid, Self::Err> {
@@ -499,15 +500,15 @@ impl ChannelRepo for FakeMutationRepo {
async fn maybe_get_dm(
&self,
- _user_id: String,
- _recipient_id: String,
+ _user_id: MacroUserIdStr<'_>,
+ _recipient_id: MacroUserIdStr<'_>,
) -> Result<Option<Uuid>, Self::Err> {
Ok(None)
}
async fn maybe_get_private_channel(
&self,
- _participants: Vec<String>,
+ _participants: std::collections::HashSet<MacroUserIdStr<'_>>,
) -> Result<Option<Uuid>, Self::Err> {
Ok(None)
}
@@ -528,7 +529,7 @@ impl ChannelRepo for FakeMutationRepo {
async fn add_participant(
&self,
_channel_id: Uuid,
- _user_id: String,
+ _user_id: MacroUserIdStr<'_>,
_role: ParticipantRole,
) -> Result<(), Self::Err> {
Ok(())
@@ -550,14 +551,14 @@ impl ChannelRepo for FakeMutationRepo {
async fn create_message(
&self,
channel_id: Uuid,
- sender_id: String,
+ sender_id: ChannelSender<'_>,
triggered_by_user_id: Option<String>,
content: String,
thread_id: Option<Uuid>,
) -> Result<MutatedMessage, Self::Err> {
let mut state = self.state.lock().unwrap();
state.message.channel_id = channel_id;
- state.message.sender_id = Sender::parse_storage_str(&sender_id).unwrap();
+ state.message.sender_id = sender_id.into_owned();
state.message.triggered_by = triggered_by_user_id;
state.message.content = content;
state.message.thread_id = thread_id;
@@ -679,12 +680,15 @@ impl ChannelRepo for FakeMutationRepo {
&self,
_channel_id: Uuid,
_message_id: Uuid,
- ) -> Result<Option<String>, Self::Err> {
+ ) -> Result<Option<ChannelSender<'static>>, Self::Err> {
let state = self.state.lock().unwrap();
if state.message.deleted_at.is_some() {
return Ok(None);
}
- Ok(Some(state.owner.clone()))
+ ChannelSender::parse_from_str(&state.owner)
+ .map(CowLike::into_owned)
+ .map(Some)
+ .map_err(Into::into)
}
async fn get_participants(
@@ -701,7 +705,11 @@ impl ChannelRepo for FakeMutationRepo {
Ok(self.state.lock().unwrap().thread_participants.clone())
}
- async fn upsert_activity(&self, _user_id: String, _channel_id: Uuid) -> Result<(), Self::Err> {
+ async fn upsert_activity(
+ &self,
+ _user_id: ChannelSender<'_>,
+ _channel_id: Uuid,
+ ) -> Result<(), Self::Err> {
self.state.lock().unwrap().activity_upserts += 1;
Ok(())
}
@@ -733,7 +741,7 @@ impl ChannelRepo for FakeMutationRepo {
_channel_id: Uuid,
_message_id: Uuid,
_emoji: String,
- _user_id: String,
+ _user_id: ChannelSender<'_>,
) -> Result<(), Self::Err> {
Ok(())
}
@@ -743,7 +751,7 @@ impl ChannelRepo for FakeMutationRepo {
_channel_id: Uuid,
_message_id: Uuid,
_emoji: String,
- _user_id: String,
+ _user_id: ChannelSender<'_>,
) -> Result<(), Self::Err> {
Ok(())
}
@@ -810,7 +818,7 @@ fn macro_id(user_id: &str) -> MacroUserIdStr<'static> {
}
fn sender(user_id: &str) -> Sender {
- Sender::User(macro_id(user_id))
+ Sender::new_from_user(macro_id(user_id))
}
#[tokio::test]
@@ -886,8 +894,8 @@ async fn post_message_emits_message_posted_event_and_updates_share_permissions()
#[tokio::test]
async fn bot_post_message_persists_bot_sender_and_skips_user_only_effects() {
let channel_id = Uuid::new_v4();
- let bot_id = BotId::from_uuid(Uuid::new_v4());
- let actor = Sender::Bot(bot_id);
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
+ let actor = Sender::new_from_bot(bot_id);
let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
let events = FakeEvents::default();
let share = FakeReferenceSharing::default();
@@ -926,8 +934,8 @@ async fn bot_post_message_persists_bot_sender_and_skips_user_only_effects() {
panic!("expected MessagePosted event, got {:?}", emitted[0]);
};
assert_eq!(
- message.sender_id.to_storage_string(),
- bot_id.to_storage_string()
+ message.sender_id.as_ref(),
+ bot_id.into_storage_id().as_ref()
);
}
@@ -986,11 +994,11 @@ async fn patch_message_content_emits_message_changed_event_to_thread_participant
async fn patch_message_notify_as_posted_adds_notification_context() {
let channel_id = Uuid::new_v4();
let thread_id = Uuid::new_v4();
- let bot_id = BotId::from_uuid(Uuid::new_v4());
- let bot_sender = bot_id.to_storage_string();
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
+ let bot_sender = bot_id.into_storage_id().to_string();
let repo = FakeMutationRepo::new(channel_id, &bot_sender);
repo.state.lock().unwrap().message.thread_id = Some(thread_id);
- repo.state.lock().unwrap().message.sender_id = Sender::Bot(bot_id);
+ repo.state.lock().unwrap().message.sender_id = Sender::new_from_bot(bot_id);
let message_id = repo.state.lock().unwrap().message.id;
let events = FakeEvents::default();
let svc = mutation_service(
@@ -1000,7 +1008,7 @@ async fn patch_message_notify_as_posted_adds_notification_context() {
);
svc.patch_message(
- Sender::Bot(bot_id),
+ Sender::new_from_bot(bot_id),
ParticipantRole::Member,
channel_id,
message_id,
@@ -1039,7 +1047,9 @@ async fn patch_message_notify_as_posted_adds_notification_context() {
#[tokio::test]
async fn patch_of_deleted_message_is_not_found() {
let channel_id = Uuid::new_v4();
- let bot_sender = BotId::from_uuid(Uuid::new_v4()).to_storage_string();
+ let bot_sender = BotId::new_from_uuid(Uuid::new_v4())
+ .into_storage_id()
+ .to_string();
let repo = FakeMutationRepo::new(channel_id, &bot_sender);
let message_id = repo.state.lock().unwrap().message.id;
repo.state.lock().unwrap().message.deleted_at = Some(Utc::now());
@@ -1052,7 +1062,9 @@ async fn patch_of_deleted_message_is_not_found() {
let err = svc
.patch_message(
- Sender::parse_storage_str(&bot_sender).unwrap(),
+ ChannelSender::parse_from_str(&bot_sender)
+ .unwrap()
+ .into_owned(),
ParticipantRole::Member,
channel_id,
message_id,
@@ -1075,7 +1087,9 @@ async fn patch_of_deleted_message_is_not_found() {
#[tokio::test]
async fn member_can_delete_bot_authored_message() {
let channel_id = Uuid::new_v4();
- let bot_sender = BotId::from_uuid(Uuid::new_v4()).to_storage_string();
+ let bot_sender = BotId::new_from_uuid(Uuid::new_v4())
+ .into_storage_id()
+ .to_string();
let repo = FakeMutationRepo::new(channel_id, &bot_sender);
let message_id = repo.state.lock().unwrap().message.id;
let events = FakeEvents::default();
diff --git a/rust/cloud-storage/channels/src/domain/side_effects.rs b/rust/cloud-storage/channels/src/domain/side_effects.rs
index de38341bd6..4f5f56992b 100644
--- a/rust/cloud-storage/channels/src/domain/side_effects.rs
+++ b/rust/cloud-storage/channels/src/domain/side_effects.rs
@@ -4,7 +4,7 @@ use crate::domain::{
events::ChannelEvent,
models::{
BotId, BotSenderProfile, ChannelMetadata, ChannelParticipant, ChannelType, CountedReaction,
- MutatedAttachment, MutatedMessage, PostMessageNotificationPolicy, Sender, SimpleMention,
+ MutatedAttachment, MutatedMessage, PostMessageNotificationPolicy, SimpleMention,
TypingAction,
},
ports::{
@@ -13,6 +13,7 @@ use crate::domain::{
ChannelSideEffectContext,
},
};
+use bot_id::BotIdStr;
use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use std::collections::HashSet;
use tokio::sync::mpsc::UnboundedSender;
@@ -40,27 +41,38 @@ pub type ChannelBotTriggerSender = UnboundedSender<ChannelBotTrigger>;
/// Bot mentions normally arrive tagged `bot`, but Macro AI is surfaced through
/// the user-mention UI, so a `user` mention whose id is exactly the Macro AI
/// bot is recognized as a bot mention too.
+///
+/// Ids must be in the canonical `bot|<uuid>` principal form; bare UUIDs are
+/// rejected (historical bare-UUID content is normalized by migration).
fn bot_mention_ids(mentions: &[SimpleMention]) -> Vec<BotId> {
let mut seen = HashSet::new();
mentions
.iter()
.filter_map(|mention| match mention.entity_type.as_str() {
- BOT_MENTION_ENTITY_TYPE => BotId::parse_uuid_str(&mention.entity_id).ok(),
- "user" => BotId::parse_uuid_str(&mention.entity_id)
- .ok()
- .filter(|id| *id == bot_id::MACRO_AI_BOT_ID),
+ BOT_MENTION_ENTITY_TYPE => mention_bot_id(&mention.entity_id),
+ "user" => {
+ mention_bot_id(&mention.entity_id).filter(|id| *id == bot_id::MACRO_AI_BOT_ID)
+ }
_ => None,
})
.filter(|id| seen.insert(*id))
.collect()
}
+/// Parse a mention entity id in the canonical `bot|<uuid>` principal form.
+fn mention_bot_id(entity_id: &str) -> Option<BotId> {
+ BotIdStr::parse_from_str(entity_id)
+ .ok()
+ .map(|id| id.bot_id())
+}
+
/// Whether a `user`-tagged mention actually targets a bot (and so must not be
-/// treated as a user recipient). Real user ids are not bare UUIDs, so this only
-/// matches the Macro AI bot surfaced through the user-mention UI.
+/// treated as a user recipient). Real user ids are `macro|<email>` strings,
+/// never `bot|<uuid>` principals, so this only matches the Macro AI bot
+/// surfaced through the user-mention UI.
fn is_bot_user_mention(mention: &SimpleMention) -> bool {
mention.entity_type == "user"
- && BotId::parse_uuid_str(&mention.entity_id).ok() == Some(bot_id::MACRO_AI_BOT_ID)
+ && mention_bot_id(&mention.entity_id) == Some(bot_id::MACRO_AI_BOT_ID)
}
/// Realtime update requested by the channel domain.
@@ -523,7 +535,7 @@ where
self.publish_realtime(ChannelRealtimeEffect::Typing {
recipients,
channel_id,
- user_id: actor.to_storage_string(),
+ user_id: actor.as_ref().to_string(),
action,
thread_id,
nonce,
@@ -620,18 +632,14 @@ where
/// Resolve the public bot profile when the message sender is a bot.
async fn bot_profile_for_message(&self, message: &MutatedMessage) -> Option<BotSenderProfile> {
- match &message.sender_id {
- Sender::Bot(bot_id) => {
- if *bot_id == bot_id::MACRO_AI_BOT_ID {
- return Some(BotSenderProfile {
- name: bot_id::MACRO_AI_NAME.to_string(),
- avatar_url: None,
- });
- }
- self.context.get_bot_sender_profile(*bot_id).await
- }
- Sender::User(_) => None,
+ let bot_id = message.sender_id.as_bot()?.bot_id();
+ if bot_id == bot_id::MACRO_AI_BOT_ID {
+ return Some(BotSenderProfile {
+ name: bot_id::MACRO_AI_NAME.to_string(),
+ avatar_url: None,
+ });
}
+ self.context.get_bot_sender_profile(bot_id).await
}
async fn publish_realtime(&self, effect: ChannelRealtimeEffect) {
@@ -658,15 +666,17 @@ where
has_attachments,
bot_profile,
} = inputs;
- let resolved_sender = match &message.sender_id {
- Sender::User(user_id) => ResolvedNotificationSender {
+ let resolved_sender = if let Some(user_id) = message.sender_id.as_user() {
+ let user_id = user_id.clone();
+ 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 {
+ }
+ } else if let Some(bot_id) = message.sender_id.as_bot().map(|id| id.bot_id()) {
+ match bot_profile {
Some(profile) => ResolvedNotificationSender {
sender: NotificationSender::Bot { name: profile.name },
profile_picture_url: profile.avatar_url,
@@ -675,7 +685,9 @@ where
tracing::warn!(bot_id = %bot_id, "missing bot profile, skipping message notifications");
return;
}
- },
+ }
+ } else {
+ return;
};
let context = match self
.build_posted_message_context(
@@ -1084,7 +1096,7 @@ struct PostedMessageNotificationContext {
/// Bots are not user recipients and are not valid `MacroUserIdStr`s, so they are
/// skipped before parsing to avoid spurious parse warnings.
fn is_bot_principal(id: &str) -> bool {
- BotId::parse_storage_str(id).is_ok()
+ BotIdStr::parse_from_str(id).is_ok()
}
fn participant_ids(participants: &[ChannelParticipant]) -> Vec<MacroUserIdStr<'static>> {
@@ -1113,22 +1125,24 @@ fn contact_sync_users_for_event(event: &ChannelEvent) -> Option<HashSet<MacroUse
match event {
ChannelEvent::ChannelCreated {
channel_type: ChannelType::Private | ChannelType::DirectMessage,
- actor: Sender::User(_),
+ actor,
participant_user_ids,
..
- } => Some(participant_user_ids.iter().cloned().collect()),
+ } if actor.as_user().is_some() => Some(participant_user_ids.iter().cloned().collect()),
ChannelEvent::ParticipantsAdded {
channel_type: ChannelType::Private | ChannelType::Team,
- invited_by: Sender::User(_),
+ invited_by,
active_participant_user_ids,
..
- } => Some(active_participant_user_ids.iter().cloned().collect()),
+ } if invited_by.as_user().is_some() => {
+ Some(active_participant_user_ids.iter().cloned().collect())
+ }
ChannelEvent::ParticipantJoined {
channel_type: ChannelType::Public | ChannelType::Private | ChannelType::Team,
- user_id: Sender::User(_),
+ user_id,
active_participant_user_ids,
..
- } if active_participant_user_ids.len() > 1 => {
+ } if user_id.as_user().is_some() && active_participant_user_ids.len() > 1 => {
Some(active_participant_user_ids.iter().cloned().collect())
}
_ => None,
diff --git a/rust/cloud-storage/channels/src/domain/side_effects/test.rs b/rust/cloud-storage/channels/src/domain/side_effects/test.rs
index aeca9808b2..048df3deaa 100644
--- a/rust/cloud-storage/channels/src/domain/side_effects/test.rs
+++ b/rust/cloud-storage/channels/src/domain/side_effects/test.rs
@@ -169,7 +169,7 @@ async fn macro_ai_bot_profile_is_builtin_without_context_lookup() {
id: Uuid::new_v4(),
channel_id: Uuid::new_v4(),
thread_id: None,
- sender_id: Sender::Bot(bot_id::MACRO_AI_BOT_ID),
+ sender_id: Sender::new_from_bot(bot_id::MACRO_AI_BOT_ID),
triggered_by: None,
content: "hello".to_string(),
created_at: now,
@@ -206,7 +206,7 @@ async fn non_macro_bot_profile_uses_context_lookup() {
id: Uuid::new_v4(),
channel_id: Uuid::new_v4(),
thread_id: None,
- sender_id: Sender::Bot(BotId::from_uuid(Uuid::new_v4())),
+ sender_id: Sender::new_from_bot(BotId::new_from_uuid(Uuid::new_v4())),
triggered_by: None,
content: "hello".to_string(),
created_at: now,
@@ -270,7 +270,7 @@ async fn message_posted_derives_realtime_search_and_notification_effects() {
id: message_id,
channel_id,
thread_id: None,
- sender_id: Sender::User(sender.clone()),
+ sender_id: Sender::new_from_user(sender.clone()),
triggered_by: None,
content: "hello".to_string(),
created_at: now,
@@ -354,7 +354,7 @@ fn bot_message_posted_event(
id: message_id,
channel_id,
thread_id,
- sender_id: Sender::Bot(BotId::from_uuid(Uuid::new_v4())),
+ sender_id: Sender::new_from_bot(BotId::new_from_uuid(Uuid::new_v4())),
triggered_by: None,
content: "hello".to_string(),
created_at: now,
@@ -415,7 +415,7 @@ async fn silent_message_posted_skips_notifications_only() {
id: message_id,
channel_id,
thread_id: None,
- sender_id: Sender::User(sender),
+ sender_id: Sender::new_from_user(sender),
triggered_by: None,
content: "transient".to_string(),
created_at: now,
@@ -465,12 +465,12 @@ async fn message_changed_with_posted_notification_context_sends_notification() {
service
.handle(ChannelEvent::MessageChanged {
channel_id,
- actor: Sender::Bot(bot_id::MACRO_AI_BOT_ID),
+ actor: Sender::new_from_bot(bot_id::MACRO_AI_BOT_ID),
message: MutatedMessage {
id: message_id,
channel_id,
thread_id: Some(thread_id),
- sender_id: Sender::Bot(bot_id::MACRO_AI_BOT_ID),
+ sender_id: Sender::new_from_bot(bot_id::MACRO_AI_BOT_ID),
triggered_by: None,
content: "final answer".to_string(),
created_at: now,
@@ -694,7 +694,9 @@ async fn bot_thread_reply_sends_reply_notification() {
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 bot_principal = BotId::new_from_uuid(Uuid::new_v4())
+ .into_storage_id()
+ .to_string();
let notifications = FakeNotifications::default();
let service = ChannelSideEffectService::new(
FakeContext::default(),
@@ -767,7 +769,7 @@ async fn user_message_with_bot_mention_enqueues_bot_trigger() {
id: message_id,
channel_id,
thread_id: None,
- sender_id: Sender::User(sender),
+ sender_id: Sender::new_from_user(sender),
triggered_by: None,
content: "@macro help".to_string(),
created_at: now,
@@ -777,7 +779,7 @@ async fn user_message_with_bot_mention_enqueues_bot_trigger() {
},
mentions: vec![SimpleMention {
entity_type: "user".to_string(),
- entity_id: bot_id::MACRO_AI_BOT_ID.to_string(),
+ entity_id: bot_id::MACRO_AI_BOT_ID.into_storage_id().to_string(),
}],
has_attachments: false,
attachments: Vec::new(),
@@ -854,7 +856,7 @@ async fn document_mentions_notify_participants_except_sender() {
id: message_id,
channel_id,
thread_id: None,
- sender_id: Sender::User(sender.clone()),
+ sender_id: Sender::new_from_user(sender.clone()),
triggered_by: None,
content: "hello".to_string(),
created_at: now,
@@ -896,7 +898,7 @@ async fn document_mentions_notify_participants_except_sender() {
fn contact_sync_is_derived_from_private_channel_created() {
let event = ChannelEvent::ChannelCreated {
channel_id: Uuid::nil(),
- actor: Sender::User(user("[email protected]")),
+ actor: Sender::new_from_user(user("[email protected]")),
channel_type: ChannelType::Private,
participant_user_ids: users(&["[email protected]", "[email protected]"]),
};
@@ -912,7 +914,7 @@ fn contact_sync_is_derived_from_private_channel_created() {
fn contact_sync_ignores_public_channel_created() {
let event = ChannelEvent::ChannelCreated {
channel_id: Uuid::nil(),
- actor: Sender::User(user("[email protected]")),
+ actor: Sender::new_from_user(user("[email protected]")),
channel_type: ChannelType::Public,
participant_user_ids: users(&["[email protected]", "[email protected]"]),
};
@@ -926,7 +928,7 @@ fn contact_sync_ignores_bot_actor() {
channel_id: Uuid::nil(),
channel_type: ChannelType::Team,
active_participant_user_ids: users(&["[email protected]", "[email protected]"]),
- invited_by: Sender::Bot(BotId::from_uuid(Uuid::new_v4())),
+ invited_by: Sender::new_from_bot(BotId::new_from_uuid(Uuid::new_v4())),
recipient_user_ids: users(&["[email protected]"]),
metadata: ChannelMetadata {
channel_type: ChannelType::Team,
@@ -944,7 +946,7 @@ fn contact_sync_is_derived_from_team_participants_added() {
channel_id: Uuid::nil(),
channel_type: ChannelType::Team,
active_participant_user_ids: users(&["[email protected]", "[email protected]"]),
- invited_by: Sender::User(user("[email protected]")),
+ invited_by: Sender::new_from_user(user("[email protected]")),
recipient_user_ids: users(&["[email protected]"]),
metadata: ChannelMetadata {
channel_type: ChannelType::Team,
@@ -961,7 +963,7 @@ fn contact_sync_ignores_single_user_join() {
let event = ChannelEvent::ParticipantJoined {
channel_id: Uuid::nil(),
channel_type: ChannelType::Public,
- user_id: Sender::User(user("[email protected]")),
+ user_id: Sender::new_from_user(user("[email protected]")),
active_participant_user_ids: users(&["[email protected]"]),
};
@@ -977,8 +979,9 @@ fn mention(entity_type: &str, entity_id: &str) -> SimpleMention {
#[test]
fn bot_mentions_recognize_bot_and_macro_ai_user_tags() {
- let macro_ai = bot_id::MACRO_AI_BOT_ID.as_uuid().to_string();
- let other_bot = Uuid::new_v4().to_string();
+ let macro_ai = bot_id::MACRO_AI_BOT_ID.into_storage_id().to_string();
+ let other_bot = BotId::new_from_uuid(Uuid::new_v4());
+ let other_bot_principal = other_bot.into_storage_id().to_string();
let mentions = vec![
// Macro AI surfaced through the user-mention UI.
mention("user", &macro_ai),
@@ -987,23 +990,34 @@ fn bot_mentions_recognize_bot_and_macro_ai_user_tags() {
// A real user mention is ignored.
mention("user", "macro|[email protected]"),
// An explicitly bot-tagged mention.
- mention(BOT_MENTION_ENTITY_TYPE, &other_bot),
- mention(BOT_MENTION_ENTITY_TYPE, &other_bot),
+ mention(BOT_MENTION_ENTITY_TYPE, &other_bot_principal),
+ mention(BOT_MENTION_ENTITY_TYPE, &other_bot_principal),
];
let bots = bot_mention_ids(&mentions);
- assert_eq!(
- bots,
- vec![
- bot_id::MACRO_AI_BOT_ID,
- BotId::parse_uuid_str(&other_bot).unwrap()
- ]
- );
+ assert_eq!(bots, vec![bot_id::MACRO_AI_BOT_ID, other_bot]);
+}
+
+#[test]
+fn bot_mentions_reject_bare_uuid_ids() {
+ // Bare UUIDs are a legacy encoding; producers must send `bot|<uuid>`
+ // and historical content is normalized by migration.
+ let mentions = vec![
+ mention("user", &bot_id::MACRO_AI_BOT_ID.as_uuid().to_string()),
+ mention(BOT_MENTION_ENTITY_TYPE, &Uuid::new_v4().to_string()),
+ ];
+
+ assert!(bot_mention_ids(&mentions).is_empty());
}
#[test]
fn macro_ai_user_mention_is_not_a_user_recipient() {
assert!(is_bot_user_mention(&mention(
+ "user",
+ bot_id::MACRO_AI_BOT_ID.into_storage_id().as_ref()
+ )));
+ // The legacy bare-UUID encoding is no longer treated as a bot mention.
+ assert!(!is_bot_user_mention(&mention(
"user",
&bot_id::MACRO_AI_BOT_ID.as_uuid().to_string()
)));
@@ -1012,7 +1026,7 @@ fn macro_ai_user_mention_is_not_a_user_recipient() {
)));
assert!(is_bot_principal(
- &bot_id::MACRO_AI_BOT_ID.to_storage_string()
+ bot_id::MACRO_AI_BOT_ID.into_storage_id().as_ref()
));
assert!(!is_bot_principal("macro|[email protected]"));
}
diff --git a/rust/cloud-storage/channels/src/inbound/axum_router.rs b/rust/cloud-storage/channels/src/inbound/axum_router.rs
index af929d883d..e8e9c7b79f 100644
--- a/rust/cloud-storage/channels/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/channels/src/inbound/axum_router.rs
@@ -29,6 +29,7 @@ use axum::{
response::IntoResponse,
routing::{delete, get, patch, post},
};
+use channel_sender::ChannelSender;
use chrono::{DateTime, Utc};
use entity_access::{
domain::{
@@ -119,7 +120,7 @@ fn actor_from_receipt<T: RequiredPermission>(
receipt: &EntityAccessReceipt<T>,
) -> Result<Sender, ChannelsHandlerErr> {
match receipt.auth() {
- EntityAccessAuth::Authenticated(user_id) => Ok(Sender::User(user_id.clone())),
+ EntityAccessAuth::Authenticated(user_id) => Ok(Sender::new_from_user(user_id.clone())),
EntityAccessAuth::Unauthenticated | EntityAccessAuth::Internal => Err(
ChannelsHandlerErr::BadRequest("authenticated actor required"),
),
@@ -132,7 +133,7 @@ fn user_actor_from_receipt<T: RequiredPermission>(
receipt
.get_authenticated_user()
.cloned()
- .map(Sender::User)
+ .map(Sender::new_from_user)
.map_err(|_| ChannelsHandlerErr::BadRequest("authenticated user required"))
}
@@ -368,7 +369,7 @@ pub async fn create_channel_handler<S: ChannelService, Svc: EntityAccessService>
let res = state
.service
.create_channel(
- Sender::User(user.macro_user_id),
+ Sender::new_from_user(user.macro_user_id),
user.user_context.organization_id.map(i64::from),
req,
)
@@ -399,7 +400,7 @@ pub async fn get_or_create_dm_handler<S: ChannelService, Svc: EntityAccessServic
) -> Result<(StatusCode, Json<GetOrCreateChannelResponse>), ChannelsHandlerErr> {
let res = state
.service
- .get_or_create_dm(Sender::User(user.macro_user_id), req)
+ .get_or_create_dm(Sender::new_from_user(user.macro_user_id), req)
.await?;
Ok((StatusCode::OK, Json(res)))
}
@@ -427,7 +428,7 @@ pub async fn get_or_create_private_handler<S: ChannelService, Svc: EntityAccessS
) -> Result<(StatusCode, Json<GetOrCreateChannelResponse>), ChannelsHandlerErr> {
let res = state
.service
- .get_or_create_private(Sender::User(user.macro_user_id), req)
+ .get_or_create_private(Sender::new_from_user(user.macro_user_id), req)
.await?;
Ok((StatusCode::OK, Json(res)))
}
@@ -751,7 +752,7 @@ pub async fn join_channel_handler<S: ChannelService, Svc: EntityAccessService>(
let channel_id = path.channel_id;
state
.service
- .join_channel(Sender::User(user.macro_user_id), channel_id)
+ .join_channel(Sender::new_from_user(user.macro_user_id), channel_id)
.await?;
Ok(StatusCode::OK)
}
@@ -1534,7 +1535,7 @@ pub async fn post_activity_handler<S: ChannelService, Svc: EntityAccessService>(
let activity = state
.service
.post_activity(
- Sender::User(user.macro_user_id),
+ Sender::new_from_user(user.macro_user_id),
channel_id,
req.activity_type,
)
@@ -1626,28 +1627,40 @@ pub enum ApiMessageSenderType {
impl ApiMessageSender {
fn from_storage_string(sender_id: &str) -> Self {
- match Sender::parse_storage_str(sender_id) {
- Ok(Sender::Bot(bot_id)) => Self {
+ let Ok(sender) = ChannelSender::parse_from_str(sender_id) else {
+ return Self {
+ sender_type: ApiMessageSenderType::User,
+ id: sender_id.to_string(),
+ name: None,
+ avatar_url: None,
+ triggered_by: None,
+ };
+ };
+
+ if let Some(bot_id) = sender.as_bot() {
+ Self {
sender_type: ApiMessageSenderType::Bot,
id: bot_id.as_uuid().to_string(),
name: None,
avatar_url: None,
triggered_by: None,
- },
- Ok(Sender::User(user_id)) => Self {
+ }
+ } else if let Some(user_id) = sender.as_user() {
+ Self {
sender_type: ApiMessageSenderType::User,
id: user_id.to_string(),
name: None,
avatar_url: None,
triggered_by: None,
- },
- Err(_) => Self {
+ }
+ } else {
+ Self {
sender_type: ApiMessageSenderType::User,
id: sender_id.to_string(),
name: None,
avatar_url: None,
triggered_by: None,
- },
+ }
}
}
diff --git a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
index b6ce5d645c..ad5b1b0ef3 100644
--- a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
+++ b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
@@ -745,7 +745,7 @@ async fn post_message_route_uses_entity_access_and_mutation_service() {
let posts = posts.lock().unwrap();
assert_eq!(posts.len(), 1);
- assert_eq!(posts[0].0.to_storage_string(), "macro|[email protected]");
+ assert_eq!(posts[0].0.as_ref(), "macro|[email protected]");
assert_eq!(posts[0].1, channel_id);
assert_eq!(posts[0].2.content, "hello");
}
@@ -1728,7 +1728,7 @@ impl ChannelService for ActivityService {
.push((actor.clone(), channel_id, activity_type));
Ok(Activity {
id: Uuid::nil(),
- user_id: actor.to_storage_string(),
+ user_id: actor.as_ref().to_string(),
channel_id,
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
@@ -1789,7 +1789,7 @@ async fn post_activity_records_and_returns_activity() {
let posts = posts.lock().unwrap();
assert_eq!(posts.len(), 1);
- assert_eq!(posts[0].0.to_storage_string(), "macro|[email protected]");
+ assert_eq!(posts[0].0.as_ref(), "macro|[email protected]");
assert_eq!(posts[0].1, channel_id);
assert!(matches!(posts[0].2, ActivityType::View));
}
diff --git a/rust/cloud-storage/channels/src/inbound/toolset/send_channel_message.rs b/rust/cloud-storage/channels/src/inbound/toolset/send_channel_message.rs
index 9ff86ddce0..9dfffc1b32 100644
--- a/rust/cloud-storage/channels/src/inbound/toolset/send_channel_message.rs
+++ b/rust/cloud-storage/channels/src/inbound/toolset/send_channel_message.rs
@@ -54,7 +54,7 @@ where
// AI sends as the Macro agent bot; the triggering user is recorded
// separately so the client can render a "from <user>" pill.
- let actor = Sender::Bot(bot_id::MACRO_AI_BOT_ID);
+ let actor = Sender::new_from_bot(bot_id::MACRO_AI_BOT_ID);
let triggered_by = Some(request_context.user_id.as_ref().to_string());
let req = PostMessageRequest {
diff --git a/rust/cloud-storage/channels/src/outbound/connection_gateway_realtime.rs b/rust/cloud-storage/channels/src/outbound/connection_gateway_realtime.rs
index 0b34d77204..e471ad00bf 100644
--- a/rust/cloud-storage/channels/src/outbound/connection_gateway_realtime.rs
+++ b/rust/cloud-storage/channels/src/outbound/connection_gateway_realtime.rs
@@ -4,12 +4,11 @@
mod test;
use crate::domain::{
- models::{
- BotSenderProfile, CountedReaction, MutatedAttachment, MutatedMessage, Sender, TypingAction,
- },
+ models::{BotSenderProfile, CountedReaction, MutatedAttachment, MutatedMessage, TypingAction},
ports::ChannelRealtimePublisher,
side_effects::ChannelRealtimeEffect,
};
+use channel_sender::ChannelSender;
use connection_gateway_client::ConnectionGatewayClient;
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::EntityType as GatewayEntityType;
@@ -181,25 +180,28 @@ struct MessageRealtimeSender {
impl MessageRealtimeSender {
fn new(
- sender: &Sender,
+ sender: &ChannelSender<'_>,
triggered_by: Option<String>,
bot_profile: Option<BotSenderProfile>,
) -> Self {
- match sender {
- Sender::Bot(bot_id) => Self {
+ if let Some(bot_id) = sender.as_bot() {
+ Self {
sender_type: "bot",
id: bot_id.as_uuid().to_string(),
name: bot_profile.as_ref().map(|profile| profile.name.clone()),
avatar_url: bot_profile.and_then(|profile| profile.avatar_url),
triggered_by,
- },
- Sender::User(user_id) => Self {
+ }
+ } else if let Some(user_id) = sender.as_user() {
+ Self {
sender_type: "user",
id: user_id.as_ref().to_string(),
name: None,
avatar_url: None,
triggered_by: None,
- },
+ }
+ } else {
+ unreachable!("channel sender is always either a user or a bot")
}
}
}
diff --git a/rust/cloud-storage/channels/src/outbound/connection_gateway_realtime/test.rs b/rust/cloud-storage/channels/src/outbound/connection_gateway_realtime/test.rs
index e2a8c2d643..06bc2e39cc 100644
--- a/rust/cloud-storage/channels/src/outbound/connection_gateway_realtime/test.rs
+++ b/rust/cloud-storage/channels/src/outbound/connection_gateway_realtime/test.rs
@@ -1,5 +1,5 @@
use super::*;
-use crate::domain::models::MutatedMessage;
+use crate::domain::models::{MutatedMessage, Sender};
use bot_id::BotId;
use chrono::Utc;
@@ -21,8 +21,8 @@ fn message(sender_id: Sender) -> MutatedMessage {
#[test]
fn bot_message_payload_includes_enriched_sender() {
- let bot_id = BotId::from_uuid(Uuid::new_v4());
- let message = message(Sender::Bot(bot_id));
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
+ let message = message(Sender::new_from_bot(bot_id));
let sender = MessageRealtimeSender::new(
&message.sender_id,
None,
@@ -39,7 +39,7 @@ fn bot_message_payload_includes_enriched_sender() {
.unwrap();
// Flattened message fields stay at the top level for existing clients.
- assert_eq!(payload["sender_id"], bot_id.to_storage_string());
+ assert_eq!(payload["sender_id"], bot_id.into_storage_id().as_ref());
assert_eq!(payload["content"], "hello");
assert_eq!(payload["nonce"], "nonce-1");
assert_eq!(payload["sender"]["type"], "bot");
@@ -53,8 +53,8 @@ fn bot_message_payload_includes_enriched_sender() {
#[test]
fn agent_message_payload_includes_triggering_user() {
- let bot_id = BotId::from_uuid(Uuid::new_v4());
- let message = message(Sender::Bot(bot_id));
+ let bot_id = BotId::new_from_uuid(Uuid::new_v4());
+ let message = message(Sender::new_from_bot(bot_id));
let sender = MessageRealtimeSender::new(
&message.sender_id,
Some("macro|[email protected]".to_string()),
@@ -79,7 +79,7 @@ fn agent_message_payload_includes_triggering_user() {
fn user_message_payload_omits_bot_fields() {
let user = macro_user_id::user_id::MacroUserIdStr::try_from_email("[email protected]")
.expect("valid email");
- let message = message(Sender::User(user.clone()));
+ let message = message(Sender::new_from_user(user.clone()));
let sender = MessageRealtimeSender::new(&message.sender_id, None, None);
let payload = serde_json::to_value(WithNonce {
diff --git a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs
index b59ef6441b..d204b5ba95 100644
--- a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs
+++ b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs
@@ -15,13 +15,14 @@ use crate::domain::{
CreateChannelRequest, CreateEntityMentionOptions, EntityMention, GetChannelsParams,
GetThreadReplyRowsParams, LatestMessage, MessageAttachment, MessagePageDirection,
MutatedAttachment, MutatedMessage, NameLookup, NewChannelAttachment, ParticipantRole,
- PatchChannelRequest, RecentChannelMessage, ResolvedChannelMessage, Sender, SimpleMention,
+ PatchChannelRequest, RecentChannelMessage, ResolvedChannelMessage, SimpleMention,
ThreadData, ThreadInfo, ThreadReply, ThreadReplyRow, TopLevelMessageRow, UserName,
fallback_user_name,
},
ports::{ChannelRepo, TopLevelMessagesQueryResult},
};
use anyhow::Context;
+use channel_sender::ChannelSender;
use chrono::{DateTime, Utc};
#[cfg(feature = "list")]
use filter_ast::Expr;
@@ -58,7 +59,9 @@ fn bot_profile_for_sender(
profiles: &HashMap<BotId, BotSenderProfile>,
sender_id: &str,
) -> Option<BotSenderProfile> {
- let bot_id = BotId::parse_storage_str(sender_id).ok()?;
+ use bot_id::BotIdStr;
+
+ let bot_id = BotIdStr::parse_from_str(sender_id).ok()?.bot_id();
profiles.get(&bot_id).cloned()
}
@@ -282,7 +285,8 @@ struct ExistsRow {
}
fn mutated_message_from_row(row: MutatedMessageRow) -> anyhow::Result<MutatedMessage> {
- let sender_id = Sender::parse_storage_str(&row.sender_id)
+ let sender_id = ChannelSender::parse_from_str(&row.sender_id)
+ .map(CowLike::into_owned)
.with_context(|| format!("invalid message sender_id {}", row.sender_id))?;
Ok(MutatedMessage {
id: row.id,
@@ -447,7 +451,7 @@ async fn get_message_owner(
pool: &PgPool,
channel_id: Uuid,
message_id: Uuid,
-) -> anyhow::Result<Option<String>> {
+) -> anyhow::Result<Option<ChannelSender<'static>>> {
let row = sqlx::query_as!(
SenderIdRow,
r#"
@@ -462,7 +466,12 @@ async fn get_message_owner(
.fetch_optional(pool)
.await
.context("unable to get message owner")?;
- Ok(row.map(|row| row.sender_id.to_string()))
+ row.map(|row| {
+ ChannelSender::parse_from_str(&row.sender_id)
+ .map(CowLike::into_owned)
+ .with_context(|| format!("invalid message sender_id {}", row.sender_id))
+ })
+ .transpose()
}
async fn get_channel_participants_for_thread_id(
@@ -1317,6 +1326,8 @@ impl ChannelListRepo for PgChannelsRepo {
&self,
params: GetThreadReplyRowsParams,
) -> Result<Vec<ChannelMessage>, rootcause::Report> {
+ use bot_id::BotIdStr;
+
let parents: Vec<TopLevelMessageRow> = build_channel_thread_rows_query(&params)
.build()
.try_map(|row: PgRow| {
@@ -1359,7 +1370,8 @@ impl ChannelListRepo for PgChannelsRepo {
let bot_ids: Vec<BotId> = sender_ids
.into_iter()
- .filter_map(|sender_id| BotId::parse_storage_str(sender_id).ok())
+ .filter_map(|sender_id| BotIdStr::parse_from_str(sender_id).ok())
+ .map(|x| x.bot_id())
.collect::<HashSet<_>>()
.into_iter()
.collect();
@@ -2607,7 +2619,7 @@ impl ChannelRepo for PgChannelsRepo {
async fn create_channel(
&self,
- owner_id: String,
+ owner_id: MacroUserIdStr<'_>,
_org_id: Option<i64>,
req: CreateChannelRequest,
) -> Result<Uuid, Self::Err> {
@@ -2620,7 +2632,7 @@ impl ChannelRepo for PgChannelsRepo {
"#,
channel_id,
req.name.as_deref(),
- &owner_id,
+ owner_id.as_ref(),
None::<i64>,
req.team_id,
req.channel_type as ChannelType,
@@ -2636,7 +2648,7 @@ impl ChannelRepo for PgChannelsRepo {
"#,
channel_id,
ParticipantRole::Owner as ParticipantRole,
- &owner_id,
+ owner_id.as_ref(),
)
.execute(&mut *transaction)
.await
@@ -2645,7 +2657,7 @@ impl ChannelRepo for PgChannelsRepo {
for participant in req
.participants
.into_iter()
- .filter(|participant| participant != &owner_id)
+ .filter(|participant| participant.as_ref() != owner_id.as_ref())
{
sqlx::query!(
r#"
@@ -2654,14 +2666,14 @@ impl ChannelRepo for PgChannelsRepo {
"#,
channel_id,
ParticipantRole::Member as ParticipantRole,
- participant,
+ participant.as_ref(),
)
.execute(&mut *transaction)
.await
.context("unable to create channel participant")?;
}
- create_activity(&mut *transaction, channel_id, &owner_id)
+ create_activity(&mut *transaction, channel_id, owner_id.as_ref())
.await
.context("unable to create activity for channel")?;
transaction
@@ -2673,8 +2685,8 @@ impl ChannelRepo for PgChannelsRepo {
async fn maybe_get_dm(
&self,
- user_id: String,
- recipient_id: String,
+ user_id: MacroUserIdStr<'_>,
+ recipient_id: MacroUserIdStr<'_>,
) -> Result<Option<Uuid>, Self::Err> {
let row = sqlx::query_as!(
ChannelIdRow,
@@ -2695,8 +2707,8 @@ impl ChannelRepo for PgChannelsRepo {
AND cp.user_id = $2
)
"#,
- user_id,
- recipient_id,
+ user_id.as_ref(),
+ recipient_id.as_ref(),
)
.fetch_optional(&self.pool)
.await
@@ -2706,8 +2718,12 @@ impl ChannelRepo for PgChannelsRepo {
async fn maybe_get_private_channel(
&self,
- participants: Vec<String>,
+ participants: HashSet<MacroUserIdStr<'_>>,
) -> Result<Option<Uuid>, Self::Err> {
+ let participants: Vec<String> = participants
+ .iter()
+ .map(|participant| participant.as_ref().to_string())
+ .collect();
let row = sqlx::query_as!(
ChannelIdRow,
r#"
@@ -2816,7 +2832,7 @@ impl ChannelRepo for PgChannelsRepo {
async fn add_participant(
&self,
channel_id: Uuid,
- user_id: String,
+ user_id: MacroUserIdStr<'_>,
role: ParticipantRole,
) -> Result<(), Self::Err> {
sqlx::query!(
@@ -2825,7 +2841,7 @@ impl ChannelRepo for PgChannelsRepo {
VALUES ($1, $2, $3)
"#,
channel_id,
- user_id,
+ user_id.as_ref(),
role as ParticipantRole,
)
.execute(&self.pool)
@@ -2852,7 +2868,7 @@ impl ChannelRepo for PgChannelsRepo {
async fn create_message(
&self,
channel_id: Uuid,
- sender_id: String,
+ sender_id: ChannelSender<'_>,
triggered_by_user_id: Option<String>,
content: String,
thread_id: Option<Uuid>,
@@ -2877,7 +2893,7 @@ impl ChannelRepo for PgChannelsRepo {
"#,
message_id,
channel_id,
- sender_id,
+ sender_id.as_ref(),
triggered_by_user_id,
content,
thread_id,
@@ -3190,7 +3206,7 @@ impl ChannelRepo for PgChannelsRepo {
&self,
channel_id: Uuid,
message_id: Uuid,
- ) -> Result<Option<String>, Self::Err> {
+ ) -> Result<Option<ChannelSender<'static>>, Self::Err> {
get_message_owner(&self.pool, channel_id, message_id).await
}
@@ -3238,7 +3254,11 @@ impl ChannelRepo for PgChannelsRepo {
get_channel_participants_for_thread_id(&self.pool, thread_id).await
}
- async fn upsert_activity(&self, user_id: String, channel_id: Uuid) -> Result<(), Self::Err> {
+ async fn upsert_activity(
+ &self,
+ user_id: ChannelSender<'_>,
+ channel_id: Uuid,
+ ) -> Result<(), Self::Err> {
sqlx::query!(
r#"
INSERT INTO comms_activity (id, user_id, channel_id, interacted_at)
@@ -3247,7 +3267,7 @@ impl ChannelRepo for PgChannelsRepo {
SET interacted_at = NOW(), updated_at = NOW()
"#,
macro_uuid::generate_uuid_v7(),
- user_id,
+ user_id.as_ref(),
channel_id,
)
.execute(&self.pool)
@@ -3374,7 +3394,7 @@ impl ChannelRepo for PgChannelsRepo {
channel_id: Uuid,
message_id: Uuid,
emoji: String,
- user_id: String,
+ user_id: ChannelSender<'_>,
) -> Result<(), Self::Err> {
let row = sqlx::query_as!(
ExistsRow,
@@ -3395,7 +3415,7 @@ impl ChannelRepo for PgChannelsRepo {
channel_id,
message_id,
emoji,
- user_id,
+ user_id.as_ref(),
)
.fetch_one(&self.pool)
.await
@@ -3411,7 +3431,7 @@ impl ChannelRepo for PgChannelsRepo {
channel_id: Uuid,
message_id: Uuid,
emoji: String,
- user_id: String,
+ user_id: ChannelSender<'_>,
) -> Result<(), Self::Err> {
let row = sqlx::query_as!(
ExistsRow,
@@ -3433,7 +3453,7 @@ impl ChannelRepo for PgChannelsRepo {
channel_id,
message_id,
emoji,
- user_id,
+ user_id.as_ref(),
)
.fetch_one(&self.pool)
.await
@@ -3496,7 +3516,7 @@ impl ChannelRepo for PgChannelsRepo {
.into_iter()
.map(|row| {
(
- BotId::from_uuid(row.id),
+ BotId::new_from_uuid(row.id),
BotSenderProfile {
name: row.name,
avatar_url: row.avatar_url,
diff --git a/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs b/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs
index 838107a1c7..690227d016 100644
--- a/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs
+++ b/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs
@@ -1881,21 +1881,25 @@ async fn bot_profiles_includes_soft_deleted_bots(pool: Pool<Postgres>) -> anyhow
.execute(&pool)
.await?;
- let missing = BotId::from_uuid(Uuid::new_v4());
+ let missing = BotId::new_from_uuid(Uuid::new_v4());
let profiles = repo(pool)
- .get_bot_profiles(&[BotId::from_uuid(active), BotId::from_uuid(deleted), missing])
+ .get_bot_profiles(&[
+ BotId::new_from_uuid(active),
+ BotId::new_from_uuid(deleted),
+ missing,
+ ])
.await?;
assert_eq!(profiles.len(), 2);
assert_eq!(
- profiles.get(&BotId::from_uuid(active)),
+ profiles.get(&BotId::new_from_uuid(active)),
Some(&BotSenderProfile {
name: "Active Bot".to_string(),
avatar_url: Some("https://example.com/a.png".to_string()),
})
);
assert_eq!(
- profiles.get(&BotId::from_uuid(deleted)),
+ profiles.get(&BotId::new_from_uuid(deleted)),
Some(&BotSenderProfile {
name: "Deleted Bot".to_string(),
avatar_url: None,
diff --git a/rust/cloud-storage/comms_db_client/src/participants/get_participants.rs b/rust/cloud-storage/comms_db_client/src/participants/get_participants.rs
index 2519633dd9..5398d44c65 100644
--- a/rust/cloud-storage/comms_db_client/src/participants/get_participants.rs
+++ b/rust/cloud-storage/comms_db_client/src/participants/get_participants.rs
@@ -1,5 +1,5 @@
use anyhow::{Context, Result};
-use channels::domain::models::{ChannelParticipant, Sender};
+use channels::domain::models::{ChannelParticipant, ChannelSender};
use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
use sqlx::Transaction;
@@ -26,7 +26,7 @@ impl From<DbParticipantRole> for channels::domain::models::ParticipantRole {
// XXX: This is a shim until we correctly implement https://macro.com/app/task/019ed710-f261-7059-b890-5ade6e11f4cd
fn validate_participant_user_id(user_id: &str) -> Result<(), sqlx::Error> {
- Sender::parse_storage_str(user_id)
+ ChannelSender::parse_from_str(user_id)
.map(|_| ())
.map_err(|err| sqlx::Error::Decode(Box::new(err)))
}
diff --git a/rust/cloud-storage/cowlike/Cargo.toml b/rust/cloud-storage/cowlike/Cargo.toml
index d5791c4693..1272e9130f 100644
--- a/rust/cloud-storage/cowlike/Cargo.toml
+++ b/rust/cloud-storage/cowlike/Cargo.toml
@@ -5,4 +5,9 @@ publish = false
version = "0.1.0"
[dependencies]
+either = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
+
+[dev-dependencies]
+bot_id = { path = "../bot_id" }
+macro_user_id = { path = "../macro_user_id" }
diff --git a/rust/cloud-storage/cowlike/src/lib.rs b/rust/cloud-storage/cowlike/src/lib.rs
index 09702254f5..add1510c39 100644
--- a/rust/cloud-storage/cowlike/src/lib.rs
+++ b/rust/cloud-storage/cowlike/src/lib.rs
@@ -2,8 +2,13 @@
//! This crate exposes the [CowLike] trait
//! And the ArcCowStr
+#[cfg(test)]
+mod test;
+
use std::sync::Arc;
+use either::Either;
+
/// Defines Cow-like behaviour for some type T
/// We often cant use acutal Cows because of the limitations
/// on the lifetimes of the [ToOwned] and [Borrow] traits
@@ -70,3 +75,23 @@ impl<'a> std::hash::Hash for ArcCowStr<'a> {
self.as_ref().hash(state);
}
}
+
+impl<'a, T, U> CowLike<'a> for Either<T, U>
+where
+ T: CowLike<'a>,
+ U: CowLike<'a>,
+{
+ type Owned<'b> = Either<T::Owned<'b>, U::Owned<'b>>;
+
+ fn into_owned(self) -> Self::Owned<'static> {
+ self.map_left(CowLike::into_owned)
+ .map_right(CowLike::into_owned)
+ }
+
+ fn copied(&'a self) -> Self {
+ match self {
+ Either::Left(l) => Either::Left(l.copied()),
+ Either::Right(r) => Either::Right(r.copied()),
+ }
+ }
+}
diff --git a/rust/cloud-storage/cowlike/src/test.rs b/rust/cloud-storage/cowlike/src/test.rs
new file mode 100644
index 0000000000..bf71c963b3
--- /dev/null
+++ b/rust/cloud-storage/cowlike/src/test.rs
@@ -0,0 +1,33 @@
+use bot_id::{BotIdStr, cowlike::CowLike};
+use either::Either;
+use macro_user_id::user_id::MacroUserIdStr;
+
+#[test]
+fn either_left_bot_id_str_into_owned_and_copied_preserve_contents() {
+ let storage = "bot|00000000-0000-0000-0000-00000000a1a1";
+
+ let copied_value: Either<BotIdStr<'_>, MacroUserIdStr<'_>> =
+ Either::Left(BotIdStr::parse_from_str(storage).unwrap());
+ let copied = copied_value.copied();
+ assert!(matches!(copied, Either::Left(bot_id) if bot_id.as_ref() == storage));
+
+ let owned_value: Either<BotIdStr<'_>, MacroUserIdStr<'_>> =
+ Either::Left(BotIdStr::parse_from_str(storage).unwrap());
+ let owned = owned_value.into_owned();
+ assert!(matches!(owned, Either::Left(bot_id) if bot_id.as_ref() == storage));
+}
+
+#[test]
+fn either_right_macro_user_id_str_into_owned_and_copied_preserve_contents() {
+ let storage = "macro|[email protected]";
+
+ let copied_value: Either<BotIdStr<'_>, MacroUserIdStr<'_>> =
+ Either::Right(MacroUserIdStr::parse_from_str(storage).unwrap());
+ let copied = copied_value.copied();
+ assert!(matches!(copied, Either::Right(user_id) if user_id.as_ref() == storage));
+
+ let owned_value: Either<BotIdStr<'_>, MacroUserIdStr<'_>> =
+ Either::Right(MacroUserIdStr::parse_from_str(storage).unwrap());
+ let owned = owned_value.into_owned();
+ assert!(matches!(owned, Either::Right(user_id) if user_id.as_ref() == storage));
+}
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260702200905_normalize_macro_bot_mention_ids.sql b/rust/cloud-storage/macro_db_client/migrations/20260702200905_normalize_macro_bot_mention_ids.sql
new file mode 100644
index 0000000000..5a69988f92
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260702200905_normalize_macro_bot_mention_ids.sql
@@ -0,0 +1,61 @@
+-- Normalize Macro-bot mention ids to the canonical `bot|<uuid>` principal form.
+--
+-- Historically the frontend surfaced the Macro AI bot through the user-mention
+-- typeahead with a bare UUID id (`00000000-0000-0000-0000-00000000a1a1`), so:
+-- * persisted message content contains
+-- `<m-user-mention>{"userId":"<bare uuid>", ...}</m-user-mention>`,
+-- * `comms_entity_mentions` rows tagged `bot` carry a bare UUID `entity_id`,
+-- and
+-- * `comms_messages.sender_id` may carry a bare UUID for bot-authored rows
+-- written before the `bot|<uuid>` form was enforced.
+--
+-- The strict mention parser rejects bare UUIDs, which made these messages fail
+-- search indexing (see PR #4410). The producer now always emits `bot|<uuid>`;
+-- this migration backfills the historical rows to match.
+--
+-- NOTE: after this migration is deployed, previously DLQ'd / unindexed channel
+-- messages still need a reindex via
+-- `POST /internal/backfill/channels` on search_processing_service.
+
+-- 1. Rewrite bare-UUID Macro mention ids inside persisted message content.
+-- Only the Macro AI bot was ever produced with a bare UUID (channel bots
+-- already used `bot|<uuid>` participant ids), so the rewrite is scoped to
+-- its constant id. Whitespace around the JSON colon is tolerated and the
+-- match is case-insensitive; already-normalized `bot|<uuid>` ids do not
+-- match the pattern, so the rewrite is idempotent.
+UPDATE comms_messages
+SET content = regexp_replace(
+ content,
+ '"userId"[[:space:]]*:[[:space:]]*"(00000000-0000-0000-0000-00000000a1a1)"',
+ '"userId":"bot|\1"',
+ 'gi'
+)
+WHERE content ILIKE '%"userId"%00000000-0000-0000-0000-00000000a1a1%'
+ AND content ~* '"userId"[[:space:]]*:[[:space:]]*"00000000-0000-0000-0000-00000000a1a1"';
+
+-- 2. Normalize `bot`-tagged mention rows that carry a bare UUID entity id.
+-- These rows are read back (e.g. for search indexing) and must use the
+-- same canonical form as newly produced mentions.
+UPDATE comms_entity_mentions
+SET entity_id = 'bot|' || entity_id
+WHERE entity_type = 'bot'
+ AND entity_id ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$';
+
+-- 3. Retag legacy `user`-tagged Macro mention rows (from clients that predate
+-- the bot re-tagging at send time). A bare Macro UUID is never a real user
+-- id, so these rows can only be Macro bot mentions.
+UPDATE comms_entity_mentions
+SET entity_type = 'bot',
+ entity_id = 'bot|' || entity_id
+WHERE entity_type = 'user'
+ AND lower(entity_id) = '00000000-0000-0000-0000-00000000a1a1';
+
+-- 4. Normalize bare-UUID message senders to the canonical `bot|<uuid>` form.
+-- Real user senders are `macro|<email>` strings, so a bare UUID sender can
+-- only be a bot-authored message. The typed sender parser
+-- (`ChannelSender::parse_from_str`) rejects bare UUIDs, which would fail
+-- message-owner lookups for these rows. Any sender ids that remain
+-- unparseable after this rewrite are accepted as hard errors.
+UPDATE comms_messages
+SET sender_id = 'bot|' || sender_id
+WHERE sender_id ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$';
diff --git a/rust/cloud-storage/macro_db_client/tests/normalize_macro_bot_mention_ids.rs b/rust/cloud-storage/macro_db_client/tests/normalize_macro_bot_mention_ids.rs
new file mode 100644
index 0000000000..64827d34bf
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/tests/normalize_macro_bot_mention_ids.rs
@@ -0,0 +1,208 @@
+use sqlx::{Pool, Postgres};
+
+const NORMALIZED_MACRO_BOT_ID: &str = "bot|00000000-0000-0000-0000-00000000a1a1";
+const OTHER_UUID: &str = "11111111-1111-1111-1111-111111111111";
+const MIGRATION: &str =
+ include_str!("../migrations/20260702200905_normalize_macro_bot_mention_ids.sql");
+
+#[sqlx::test(migrations = false)]
+async fn migration_normalizes_macro_bot_user_ids_in_message_content(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ create_minimal_tables(&pool).await?;
+
+ sqlx::query(
+ r#"
+ INSERT INTO comms_messages (id, content)
+ VALUES
+ ('bare-macro', '<m-user-mention>{"userId":"00000000-0000-0000-0000-00000000a1a1","label":"Macro"}</m-user-mention>'),
+ ('spaced-uppercase-key', '<m-user-mention>{"USERID" : "00000000-0000-0000-0000-00000000a1a1"}</m-user-mention>'),
+ ('already-normalized', '<m-user-mention>{"userId":"bot|00000000-0000-0000-0000-00000000a1a1"}</m-user-mention>'),
+ ('other-user', '<m-user-mention>{"userId":"11111111-1111-1111-1111-111111111111"}</m-user-mention>')
+ "#,
+ )
+ .execute(&pool)
+ .await?;
+
+ run_migration(&pool).await?;
+ // Run it twice to ensure the content rewrite is idempotent.
+ run_migration(&pool).await?;
+
+ let rows =
+ sqlx::query_as::<_, (String, String)>("SELECT id, content FROM comms_messages ORDER BY id")
+ .fetch_all(&pool)
+ .await?;
+
+ assert_eq!(
+ rows,
+ vec![
+ (
+ "already-normalized".to_owned(),
+ format!(
+ r#"<m-user-mention>{{"userId":"{NORMALIZED_MACRO_BOT_ID}"}}</m-user-mention>"#
+ ),
+ ),
+ (
+ "bare-macro".to_owned(),
+ format!(
+ r#"<m-user-mention>{{"userId":"{NORMALIZED_MACRO_BOT_ID}","label":"Macro"}}</m-user-mention>"#
+ ),
+ ),
+ (
+ "other-user".to_owned(),
+ format!(r#"<m-user-mention>{{"userId":"{OTHER_UUID}"}}</m-user-mention>"#),
+ ),
+ (
+ "spaced-uppercase-key".to_owned(),
+ format!(
+ r#"<m-user-mention>{{"userId":"{NORMALIZED_MACRO_BOT_ID}"}}</m-user-mention>"#
+ ),
+ ),
+ ]
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(migrations = false)]
+async fn migration_normalizes_comms_entity_mentions(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ create_minimal_tables(&pool).await?;
+
+ sqlx::query(
+ r#"
+ INSERT INTO comms_entity_mentions (id, entity_type, entity_id)
+ VALUES
+ ('bot-bare-macro', 'bot', '00000000-0000-0000-0000-00000000a1a1'),
+ ('bot-bare-other', 'bot', '11111111-1111-1111-1111-111111111111'),
+ ('bot-already-normalized', 'bot', 'bot|00000000-0000-0000-0000-00000000a1a1'),
+ ('user-bare-macro', 'user', '00000000-0000-0000-0000-00000000a1a1'),
+ ('user-bare-other', 'user', '11111111-1111-1111-1111-111111111111')
+ "#,
+ )
+ .execute(&pool)
+ .await?;
+
+ run_migration(&pool).await?;
+ // Run it twice to ensure mention-row normalization is idempotent.
+ run_migration(&pool).await?;
+
+ let rows = sqlx::query_as::<_, (String, String, String)>(
+ "SELECT id, entity_type, entity_id FROM comms_entity_mentions ORDER BY id",
+ )
+ .fetch_all(&pool)
+ .await?;
+
+ assert_eq!(
+ rows,
+ vec![
+ (
+ "bot-already-normalized".to_owned(),
+ "bot".to_owned(),
+ NORMALIZED_MACRO_BOT_ID.to_owned(),
+ ),
+ (
+ "bot-bare-macro".to_owned(),
+ "bot".to_owned(),
+ NORMALIZED_MACRO_BOT_ID.to_owned(),
+ ),
+ (
+ "bot-bare-other".to_owned(),
+ "bot".to_owned(),
+ format!("bot|{OTHER_UUID}"),
+ ),
+ (
+ "user-bare-macro".to_owned(),
+ "bot".to_owned(),
+ NORMALIZED_MACRO_BOT_ID.to_owned(),
+ ),
+ (
+ "user-bare-other".to_owned(),
+ "user".to_owned(),
+ OTHER_UUID.to_owned(),
+ ),
+ ]
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(migrations = false)]
+async fn migration_normalizes_bare_uuid_message_senders(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ create_minimal_tables(&pool).await?;
+
+ sqlx::query(
+ r#"
+ INSERT INTO comms_messages (id, content, sender_id)
+ VALUES
+ ('bare-uuid-bot', 'hello', '11111111-1111-1111-1111-111111111111'),
+ ('bare-uuid-bot-uppercase', 'hello', '22222222-2222-2222-2222-22222222AAAA'),
+ ('already-normalized-bot', 'hello', 'bot|00000000-0000-0000-0000-00000000a1a1'),
+ ('user-sender', 'hello', 'macro|[email protected]'),
+ ('dirty-sender', 'hello', 'not-a-principal')
+ "#,
+ )
+ .execute(&pool)
+ .await?;
+
+ run_migration(&pool).await?;
+ // Run it twice to ensure sender normalization is idempotent.
+ run_migration(&pool).await?;
+
+ let rows = sqlx::query_as::<_, (String, String)>(
+ "SELECT id, sender_id FROM comms_messages ORDER BY id",
+ )
+ .fetch_all(&pool)
+ .await?;
+
+ assert_eq!(
+ rows,
+ vec![
+ (
+ "already-normalized-bot".to_owned(),
+ NORMALIZED_MACRO_BOT_ID.to_owned(),
+ ),
+ ("bare-uuid-bot".to_owned(), format!("bot|{OTHER_UUID}"),),
+ (
+ "bare-uuid-bot-uppercase".to_owned(),
+ "bot|22222222-2222-2222-2222-22222222AAAA".to_owned(),
+ ),
+ ("dirty-sender".to_owned(), "not-a-principal".to_owned()),
+ (
+ "user-sender".to_owned(),
+ "macro|[email protected]".to_owned(),
+ ),
+ ]
+ );
+
+ Ok(())
+}
+
+async fn create_minimal_tables(pool: &Pool<Postgres>) -> anyhow::Result<()> {
+ sqlx::raw_sql(
+ r#"
+ CREATE TABLE comms_messages (
+ id text PRIMARY KEY,
+ content text NOT NULL,
+ sender_id text NOT NULL DEFAULT 'macro|[email protected]'
+ );
+
+ CREATE TABLE comms_entity_mentions (
+ id text PRIMARY KEY,
+ entity_type text NOT NULL,
+ entity_id text NOT NULL
+ );
+ "#,
+ )
+ .execute(pool)
+ .await?;
+
+ Ok(())
+}
+
+async fn run_migration(pool: &Pool<Postgres>) -> anyhow::Result<()> {
+ sqlx::raw_sql(MIGRATION).execute(pool).await?;
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/macro_user_id/src/user_id.rs b/rust/cloud-storage/macro_user_id/src/user_id.rs
index 9f061d5dfd..5f57553dd5 100644
--- a/rust/cloud-storage/macro_user_id/src/user_id.rs
+++ b/rust/cloud-storage/macro_user_id/src/user_id.rs
@@ -152,10 +152,16 @@ impl TryFrom<String> for MacroUserIdStr<'static> {
type Error = ParseErr;
fn try_from(value: String) -> Result<Self, Self::Error> {
- MacroUserId::parse_from_str(&value)
- .map(CowLike::into_owned)
- .map(|i| i.lowercase())
- .map(MacroUserIdStr)
+ let s = value.as_str();
+ MacroUserIdStr::try_from(s).map(CowLike::into_owned)
+ }
+}
+
+impl<'a> TryFrom<&'a str> for MacroUserIdStr<'a> {
+ type Error = ParseErr;
+
+ fn try_from(value: &'a str) -> Result<Self, Self::Error> {
+ MacroUserIdStr::parse_from_str(value)
}
}
diff --git a/rust/cloud-storage/mention_utils/Cargo.toml b/rust/cloud-storage/mention_utils/Cargo.toml
index bce66d1887..a26d95d1d3 100644
--- a/rust/cloud-storage/mention_utils/Cargo.toml
+++ b/rust/cloud-storage/mention_utils/Cargo.toml
@@ -5,6 +5,9 @@ publish = false
version = "0.1.0"
[dependencies]
+channel_sender = { path = "../channel_sender" }
+either = { workspace = true }
+macro_user_id = { path = "../macro_user_id" }
nom = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
diff --git a/rust/cloud-storage/mention_utils/src/parse.rs b/rust/cloud-storage/mention_utils/src/parse.rs
index 11a98d9d78..1ca8eb2bf0 100644
--- a/rust/cloud-storage/mention_utils/src/parse.rs
+++ b/rust/cloud-storage/mention_utils/src/parse.rs
@@ -1,3 +1,5 @@
+use channel_sender::ChannelSender;
+use either::Either;
use nom::{
Finish, IResult, Parser,
branch::alt,
@@ -56,9 +58,7 @@ pub trait XmlTaggedParsed<'de>: Deserialize<'de> {
#[non_exhaustive]
pub struct ParsedUserMention<'a> {
#[serde(borrow)]
- pub user_id: Cow<'a, str>,
- #[serde(borrow)]
- pub email: Cow<'a, str>,
+ pub user_id: ChannelSender<'a>,
}
impl<'de> XmlTaggedParsed<'de> for ParsedUserMention<'de> {
@@ -319,7 +319,10 @@ impl XmlFormatter for PlainTextFormatter {
}
fn format_user(user: &ParsedUserMention<'_>, f: &mut Formatter<'_>) -> std::fmt::Result {
- write!(f, "{}", user.email)
+ match &user.user_id.0 {
+ Either::Left(_l) => write!(f, "Macro"),
+ Either::Right(r) => write!(f, "{}", r.email_part().as_ref()),
+ }
}
fn format_contact(
diff --git a/rust/cloud-storage/mention_utils/src/tests.rs b/rust/cloud-storage/mention_utils/src/tests.rs
index f63286b0e8..7d52b4cc37 100644
--- a/rust/cloud-storage/mention_utils/src/tests.rs
+++ b/rust/cloud-storage/mention_utils/src/tests.rs
@@ -78,10 +78,9 @@ fn parse_single_user_mention() {
let input = r#"<m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention>"#;
let out = ParsedXmlText::parse(input).unwrap();
assert_matches!(out.0, [
- TextSegment::Xml(XmlTag::User(ParsedUserMention { user_id, email }))
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { user_id }))
] => {
assert_eq!(user_id.as_ref(), "macro|[email protected]");
- assert_eq!(email.as_ref(), "[email protected]");
});
}
@@ -91,25 +90,15 @@ fn parse_multiple_user_mentions() {
let out = ParsedXmlText::parse(input).unwrap();
assert_matches!(out.0, [
TextSegment::Plain("Hello "),
- TextSegment::Xml(XmlTag::User(ParsedUserMention { user_id: uid1, email: email1 })),
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { user_id: uid1 })),
TextSegment::Plain(" and "),
- TextSegment::Xml(XmlTag::User(ParsedUserMention { user_id: uid2, email: email2 })),
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { user_id: uid2 })),
] => {
assert_eq!(uid1.as_ref(), "macro|[email protected]");
- assert_eq!(email1.as_ref(), "[email protected]");
assert_eq!(uid2.as_ref(), "macro|[email protected]");
- assert_eq!(email2.as_ref(), "[email protected]");
});
}
-#[test]
-fn parse_user_mention_missing_email() {
- // Missing "email" field - should fail to parse
- let input = r#"<m-user-mention>{"userId":"macro|[email protected]"}</m-user-mention>"#;
- let result = ParsedXmlText::parse(input);
- assert!(result.is_err());
-}
-
#[test]
fn parse_user_mention_invalid_json() {
let input = r#"<m-user-mention>invalid</m-user-mention>"#;
@@ -123,14 +112,13 @@ fn parse_user_mention_invalid_json() {
#[test]
fn parse_bare_uuid_bot_mention() {
- let input = r#"<m-user-mention>{"userId":"00000000-0000-0000-0000-00000000a1a1","email":"Macro"}</m-user-mention> there will come a day when I shall liberate you"#;
+ let input = r#"<m-user-mention>{"userId":"bot|00000000-0000-0000-0000-00000000a1a1","email":"Macro"}</m-user-mention> there will come a day when I shall liberate you"#;
let out = ParsedXmlText::parse(input).unwrap();
assert_matches!(out.0, [
- TextSegment::Xml(XmlTag::User(ParsedUserMention { user_id, email })),
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { user_id })),
TextSegment::Plain(" there will come a day when I shall liberate you"),
] => {
- assert_eq!(user_id.as_ref(), "00000000-0000-0000-0000-00000000a1a1");
- assert_eq!(email.as_ref(), "Macro");
+ assert_eq!(user_id.into_bot().unwrap().as_uuid().to_string(), "00000000-0000-0000-0000-00000000a1a1");
});
}
@@ -139,16 +127,15 @@ fn parse_prefixed_bot_mention() {
let input = r#"<m-user-mention>{"userId":"bot|00000000-0000-0000-0000-00000000a1a1","email":"Macro"}</m-user-mention>"#;
let out = ParsedXmlText::parse(input).unwrap();
assert_matches!(out.0, [
- TextSegment::Xml(XmlTag::User(ParsedUserMention { user_id, email })),
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { user_id })),
] => {
assert_eq!(user_id.as_ref(), "bot|00000000-0000-0000-0000-00000000a1a1");
- assert_eq!(email.as_ref(), "Macro");
});
}
#[test]
fn bot_mention_renders_display_name() {
- let input = r#"hi <m-user-mention>{"userId":"00000000-0000-0000-0000-00000000a1a1","email":"Macro"}</m-user-mention> ok"#;
+ let input = r#"hi <m-user-mention>{"userId":"bot|00000000-0000-0000-0000-00000000a1a1","email":"Macro"}</m-user-mention> ok"#;
let parsed = ParsedXmlText::parse(input).unwrap();
let rendered = PlainTextFormatter::format_xml_text(parsed).0;
assert_eq!(rendered, "hi Macro ok");
@@ -156,7 +143,7 @@ fn bot_mention_renders_display_name() {
#[test]
fn bot_mention_null_formatter_strips_mention() {
- let input = r#"hi <m-user-mention>{"userId":"00000000-0000-0000-0000-00000000a1a1","email":"Macro"}</m-user-mention> ok"#;
+ let input = r#"hi <m-user-mention>{"userId":"bot|00000000-0000-0000-0000-00000000a1a1","email":"Macro"}</m-user-mention> ok"#;
let parsed = ParsedXmlText::parse(input).unwrap();
let rendered = NullXmlFormatter::format_xml_text(parsed).0;
assert_eq!(rendered, "hi ok");
@@ -363,7 +350,7 @@ fn parse_mixed_mentions() {
let out = ParsedXmlText::parse(input).unwrap();
assert_matches!(out.0, [
TextSegment::Plain("Hi "),
- TextSegment::Xml(XmlTag::User(ParsedUserMention { email, .. })),
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { .. })),
TextSegment::Plain(", let's discuss "),
TextSegment::Xml(XmlTag::Document(ParsedDocumentMention { document_name })),
TextSegment::Plain(" with "),
@@ -371,7 +358,6 @@ fn parse_mixed_mentions() {
TextSegment::Plain(" on "),
TextSegment::Xml(XmlTag::Date(ParsedDateMention { display_format })),
] => {
- assert_eq!(email.as_ref(), "[email protected]");
assert_eq!(document_name.as_ref(), "Test Doc 34");
assert_eq!(name.as_ref(), "Ness Chu");
assert_eq!(display_format.as_ref(), "Mon, Dec 1, 2025");
@@ -384,13 +370,12 @@ fn parse_mixed_mentions_with_links() {
let out = ParsedXmlText::parse(input).unwrap();
assert_matches!(out.0, [
TextSegment::Plain("Hi "),
- TextSegment::Xml(XmlTag::User(ParsedUserMention { email, .. })),
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { .. })),
TextSegment::Plain(", check out "),
TextSegment::Xml(XmlTag::Link(ParsedLink { text, url })),
TextSegment::Plain(" and "),
TextSegment::Xml(XmlTag::Document(ParsedDocumentMention { document_name })),
] => {
- assert_eq!(email.as_ref(), "[email protected]");
assert_eq!(text.as_ref(), "Our Docs");
assert_eq!(url.as_ref(), "https://docs.example.com");
assert_eq!(document_name.as_ref(), "Test Doc 34");
@@ -402,13 +387,12 @@ fn parse_content_with_multiple_document_and_user_mentions() {
let input = r#"<m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention> I'm testing sending a message with a document <m-document-mention>{"documentId":"doc-1","blockName":"md","documentName":"Document 1","blockParams":{}}</m-document-mention> mention <m-document-mention>{"documentId":"doc-2","blockName":"md","documentName":"Document 2","blockParams":{}}</m-document-mention>"#;
let out = ParsedXmlText::parse(input).unwrap();
assert_matches!(out.0, [
- TextSegment::Xml(XmlTag::User(ParsedUserMention { email, .. })),
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { .. })),
TextSegment::Plain(" I'm testing sending a message with a document "),
TextSegment::Xml(XmlTag::Document(ParsedDocumentMention { document_name: name1 })),
TextSegment::Plain(" mention "),
TextSegment::Xml(XmlTag::Document(ParsedDocumentMention { document_name: name2 })),
] => {
- assert_eq!(email.as_ref(), "[email protected]");
assert_eq!(name1.as_ref(), "Document 1");
assert_eq!(name2.as_ref(), "Document 2");
});
@@ -431,13 +415,13 @@ fn parse_text_with_angle_brackets_but_no_mentions() {
fn parse_consecutive_mentions_no_space() {
let input = r#"<m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention><m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention>"#;
let out = ParsedXmlText::parse(input).unwrap();
- assert_matches!(out.0, [
- TextSegment::Xml(XmlTag::User(ParsedUserMention { email: e1, .. })),
- TextSegment::Xml(XmlTag::User(ParsedUserMention { email: e2, .. })),
- ] => {
- assert_eq!(e1.as_ref(), "[email protected]");
- assert_eq!(e2.as_ref(), "[email protected]");
- });
+ assert_matches!(
+ out.0,
+ [
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { .. })),
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { .. })),
+ ]
+ );
}
#[test]
@@ -445,12 +429,13 @@ fn parse_mention_at_start() {
let input =
r#"<m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention> hello"#;
let out = ParsedXmlText::parse(input).unwrap();
- assert_matches!(out.0, [
- TextSegment::Xml(XmlTag::User(ParsedUserMention { email, .. })),
- TextSegment::Plain(" hello"),
- ] => {
- assert_eq!(email.as_ref(), "[email protected]");
- });
+ assert_matches!(
+ out.0,
+ [
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { .. })),
+ TextSegment::Plain(" hello"),
+ ]
+ );
}
#[test]
@@ -458,12 +443,13 @@ fn parse_mention_at_end() {
let input =
r#"hello <m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention>"#;
let out = ParsedXmlText::parse(input).unwrap();
- assert_matches!(out.0, [
- TextSegment::Plain("hello "),
- TextSegment::Xml(XmlTag::User(ParsedUserMention { email, .. })),
- ] => {
- assert_eq!(email.as_ref(), "[email protected]");
- });
+ assert_matches!(
+ out.0,
+ [
+ TextSegment::Plain("hello "),
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { .. })),
+ ]
+ );
}
// =============================================================================
@@ -474,13 +460,14 @@ fn parse_mention_at_end() {
fn parse_user_mention_with_surrounding_text() {
let input = r#"asdf <m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention> asdf"#;
let out = ParsedXmlText::parse(input).unwrap();
- assert_matches!(out.0, [
- TextSegment::Plain("asdf "),
- TextSegment::Xml(XmlTag::User(ParsedUserMention { email, .. })),
- TextSegment::Plain(" asdf"),
- ] => {
- assert_eq!(email.as_ref(), "[email protected]");
- });
+ assert_matches!(
+ out.0,
+ [
+ TextSegment::Plain("asdf "),
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { .. })),
+ TextSegment::Plain(" asdf"),
+ ]
+ );
}
#[test]
@@ -583,7 +570,7 @@ fn parse_mixed_mentions_with_multiple_links() {
let out = ParsedXmlText::parse(input).unwrap();
assert_matches!(out.0, [
TextSegment::Plain("Hi "),
- TextSegment::Xml(XmlTag::User(ParsedUserMention { email, .. })),
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { .. })),
TextSegment::Plain(", check out "),
TextSegment::Xml(XmlTag::Link(ParsedLink { text: t1, .. })),
TextSegment::Plain(" and "),
@@ -593,7 +580,6 @@ fn parse_mixed_mentions_with_multiple_links() {
TextSegment::Plain(" or visit "),
TextSegment::Xml(XmlTag::Link(ParsedLink { text: t2, url: u2 })),
] => {
- assert_eq!(email.as_ref(), "[email protected]");
assert_eq!(t1.as_ref(), "Our Docs");
assert_eq!(document_name.as_ref(), "Test Doc 34");
assert_eq!(display_format.as_ref(), "Mon, Dec 1, 2025");
@@ -610,13 +596,12 @@ fn parse_link_user_document_mixed() {
TextSegment::Plain("Check out "),
TextSegment::Xml(XmlTag::Link(ParsedLink { text, url })),
TextSegment::Plain(" and "),
- TextSegment::Xml(XmlTag::User(ParsedUserMention { email, .. })),
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { .. })),
TextSegment::Plain(" this doc "),
TextSegment::Xml(XmlTag::Document(ParsedDocumentMention { document_name })),
] => {
assert_eq!(text.as_ref(), "Example");
assert_eq!(url.as_ref(), "https://example.com");
- assert_eq!(email.as_ref(), "[email protected]");
assert_eq!(document_name.as_ref(), "Document 1");
});
}
@@ -655,13 +640,6 @@ fn parse_contact_mention_missing_name_with_suffix() {
assert!(result.is_err());
}
-#[test]
-fn parse_user_mention_missing_email_with_suffix() {
- let input = r#"<m-user-mention>{"userId":"macro|[email protected]"}</m-user-mention> asdf"#;
- let result = ParsedXmlText::parse(input);
- assert!(result.is_err());
-}
-
#[test]
fn parse_document_mention_missing_name_with_suffix() {
let input = r#"<m-document-mention>{"documentId":"6e01eaf5-f497-4b2e-96d0-ea3d527ef47d","blockName":"md","blockParams":{},"collapsed":false}</m-document-mention> asdf"#;
@@ -718,10 +696,9 @@ fn parse_group_mention_with_user_mention() {
assert_matches!(out.0, [
TextSegment::Xml(XmlTag::Group(ParsedGroupMention { group_alias })),
TextSegment::Plain(" and "),
- TextSegment::Xml(XmlTag::User(ParsedUserMention { email, .. })),
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { .. })),
] => {
assert_eq!(group_alias.as_ref(), "here");
- assert_eq!(email.as_ref(), "[email protected]");
});
}
@@ -784,10 +761,11 @@ fn parse_self_closing_unknown_tag_alone_is_skipped() {
fn parse_unknown_tag_mixed_with_recognized() {
let input = r#"<m-await>{"text":"thinking"}</m-await> Hi <m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention>"#;
let out = ParsedXmlText::parse(input).unwrap();
- assert_matches!(out.0, [
- TextSegment::Plain(" Hi "),
- TextSegment::Xml(XmlTag::User(ParsedUserMention { email, .. })),
- ] => {
- assert_eq!(email.as_ref(), "[email protected]");
- });
+ assert_matches!(
+ out.0,
+ [
+ TextSegment::Plain(" Hi "),
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { .. })),
+ ]
+ );
}
diff --git a/rust/cloud-storage/models_soup/src/comms.rs b/rust/cloud-storage/models_soup/src/comms.rs
index 5cd1546be3..ea5f8ead46 100644
--- a/rust/cloud-storage/models_soup/src/comms.rs
+++ b/rust/cloud-storage/models_soup/src/comms.rs
@@ -460,25 +460,36 @@ impl SoupChannel {
impl SoupMessageSender {
fn from_storage_string(sender_id: &str) -> Self {
- match channels::domain::models::Sender::parse_storage_str(sender_id) {
- Ok(channels::domain::models::Sender::Bot(bot_id)) => Self {
+ let Ok(sender) = channels::domain::models::ChannelSender::parse_from_str(sender_id) else {
+ return Self {
+ sender_type: SoupMessageSenderType::User,
+ id: sender_id.to_string(),
+ name: None,
+ avatar_url: None,
+ };
+ };
+
+ if let Some(bot_id) = sender.as_bot() {
+ Self {
sender_type: SoupMessageSenderType::Bot,
id: bot_id.as_uuid().to_string(),
name: None,
avatar_url: None,
- },
- Ok(channels::domain::models::Sender::User(user_id)) => Self {
+ }
+ } else if let Some(user_id) = sender.as_user() {
+ Self {
sender_type: SoupMessageSenderType::User,
id: user_id.to_string(),
name: None,
avatar_url: None,
- },
- Err(_) => Self {
+ }
+ } else {
+ Self {
sender_type: SoupMessageSenderType::User,
id: sender_id.to_string(),
name: None,
avatar_url: None,
- },
+ }
}
}