Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(channels): get thread replies api (#1628)
teob79b561a4c8e
diff --git a/rust/cloud-storage/channels/src/domain/ports.rs b/rust/cloud-storage/channels/src/domain/ports.rsindex 7e13f1b52e..ea9aaff0e0 100644--- a/rust/cloud-storage/channels/src/domain/ports.rs+++ b/rust/cloud-storage/channels/src/domain/ports.rs@@ -1,6 +1,6 @@use crate::domain::models::{ChannelAttachment, ChannelParticipant, CountedReaction, MessageAttachment,- MessagePageDirection, ThreadData, TopLevelMessageRow,+ MessagePageDirection, ThreadData, ThreadReply, ThreadReplyRow, TopLevelMessageRow,};use chrono::{DateTime, Utc};use models_pagination::{CreatedAt, Query};@@ -29,6 +29,12 @@ pub trait ChannelMessagesRepo: Send + Sync + 'static {preview_count: u16,) -> impl Future<Output = Result<HashMap<Uuid, ThreadData>, Self::Err>> + Send;+ /// Fetch all non-deleted replies for a parent message, oldest-first.+ fn get_thread_replies(+ &self,+ parent_id: Uuid,+ ) -> impl Future<Output = Result<Vec<ThreadReplyRow>, Self::Err>> + Send;+/// Batch-fetch reactions for a set of message ids.fn get_reactions_batch(&self,@@ -106,6 +112,15 @@ pub trait ChannelMessagesService: Send + Sync + 'static {message_id: Uuid,limit: u16,) -> impl Future<Output = Result<ChannelMessagesPage, ChannelMessagesErr>> + Send;++ /// Fetch all replies for the thread identified by `message_id`.+ ///+ /// If `message_id` is itself a reply, replies are fetched for its top-level parent.+ fn get_thread_replies(+ &self,+ channel_id: Uuid,+ message_id: Uuid,+ ) -> impl Future<Output = Result<Vec<ThreadReply>, ChannelMessagesErr>> + Send;}/// Access check for channel membership. Separated from the business logic service.diff --git a/rust/cloud-storage/channels/src/domain/service.rs b/rust/cloud-storage/channels/src/domain/service.rsindex 9fb1e06a61..c3a4909781 100644--- a/rust/cloud-storage/channels/src/domain/service.rs+++ b/rust/cloud-storage/channels/src/domain/service.rs@@ -255,4 +255,53 @@ whereOk(page)}++ #[tracing::instrument(err, skip(self))]+ async fn get_thread_replies(+ &self,+ channel_id: Uuid,+ message_id: Uuid,+ ) -> Result<Vec<ThreadReply>, ChannelMessagesErr> {+ let parent = self+ .repo+ .resolve_top_level_parent(channel_id, message_id)+ .await+ .map_err(anyhow::Error::from)?+ .ok_or(ChannelMessagesErr::MessageNotFound(message_id))?;++ let reply_rows = self+ .repo+ .get_thread_replies(parent.id)+ .await+ .map_err(anyhow::Error::from)?;++ if reply_rows.is_empty() {+ return Ok(Vec::new());+ }++ let reply_ids: Vec<Uuid> = reply_rows.iter().map(|row| row.id).collect();+ let (reactions, attachments) = tokio::join!(+ self.repo.get_reactions_batch(&reply_ids),+ self.repo.get_attachments_batch(&reply_ids),+ );++ let reactions = reactions.map_err(anyhow::Error::from)?;+ let attachments = attachments.map_err(anyhow::Error::from)?;++ let replies = reply_rows+ .into_iter()+ .map(|row| ThreadReply {+ id: row.id,+ sender_id: row.sender_id,+ content: row.content,+ created_at: row.created_at,+ updated_at: row.updated_at,+ edited_at: row.edited_at,+ reactions: reactions.get(&row.id).cloned().unwrap_or_default(),+ attachments: attachments.get(&row.id).cloned().unwrap_or_default(),+ })+ .collect();++ Ok(replies)+ }}diff --git a/rust/cloud-storage/channels/src/domain/service/test.rs b/rust/cloud-storage/channels/src/domain/service/test.rsindex 62b950699b..278321d45f 100644--- a/rust/cloud-storage/channels/src/domain/service/test.rs+++ b/rust/cloud-storage/channels/src/domain/service/test.rs@@ -48,6 +48,8 @@ fn empty_repo() -> MockChannelMessagesRepo {.returning(|_, _| Box::pin(async { Ok(None) }));repo.expect_get_top_level_messages_around().returning(|_, _, _, _| Box::pin(async { Ok((vec![], vec![])) }));+ repo.expect_get_thread_replies()+ .returning(|_| Box::pin(async { Ok(vec![]) }));repo}@@ -354,3 +356,96 @@ async fn around_resolves_and_hydrates() {assert_eq!(page.items[1].id, anchor.id);assert_eq!(page.items[2].id, before_row.id);}++#[tokio::test]+async fn thread_replies_message_not_found() {+ let svc = ChannelMessagesServiceImpl::new(empty_repo());+ let message_id = Uuid::new_v4();++ let err = svc+ .get_thread_replies(Uuid::nil(), message_id)+ .await+ .unwrap_err();++ assert!(+ matches!(err, ChannelMessagesErr::MessageNotFound(id) if id == message_id),+ "expected MessageNotFound, got {err:?}"+ );+}++#[tokio::test]+async fn thread_replies_resolve_and_hydrate() {+ let parent = make_row(Uuid::new_v4(), 0);+ let reply_1 = ThreadReplyRow {+ id: Uuid::new_v4(),+ thread_id: parent.id,+ sender_id: "macro|[email protected]".into(),+ content: "reply 1".into(),+ created_at: Utc::now(),+ updated_at: Utc::now(),+ edited_at: None,+ };+ let reply_2 = ThreadReplyRow {+ id: Uuid::new_v4(),+ thread_id: parent.id,+ sender_id: "macro|[email protected]".into(),+ content: "reply 2".into(),+ created_at: Utc::now(),+ updated_at: Utc::now(),+ edited_at: None,+ };++ let parent_clone = parent.clone();+ let reply_1_clone = reply_1.clone();+ let reply_2_clone = reply_2.clone();++ let mut repo = MockChannelMessagesRepo::new();++ repo.expect_resolve_top_level_parent()+ .returning(move |_, _| {+ let p = parent_clone.clone();+ Box::pin(async move { Ok(Some(p)) })+ });+ repo.expect_get_thread_replies().returning(move |_| {+ let replies = vec![reply_1_clone.clone(), reply_2_clone.clone()];+ Box::pin(async move { Ok(replies) })+ });+ repo.expect_get_reactions_batch().returning(move |_| {+ let mut map: HashMap<Uuid, Vec<CountedReaction>> = HashMap::new();+ map.insert(+ reply_1.id,+ vec![CountedReaction {+ emoji: "👍".into(),+ users: vec!["macro|[email protected]".into()],+ }],+ );+ Box::pin(async move { Ok(map) })+ });+ repo.expect_get_attachments_batch().returning(move |_| {+ let mut map: HashMap<Uuid, Vec<MessageAttachment>> = HashMap::new();+ map.insert(+ reply_2.id,+ vec![MessageAttachment {+ id: Uuid::new_v4(),+ entity_type: "document".into(),+ entity_id: "doc-1".into(),+ created_at: Utc::now(),+ }],+ );+ Box::pin(async move { Ok(map) })+ });++ let svc = ChannelMessagesServiceImpl::new(repo);+ let replies = svc+ .get_thread_replies(Uuid::nil(), reply_1.id)+ .await+ .unwrap();++ assert_eq!(replies.len(), 2);+ assert_eq!(replies[0].id, reply_1.id);+ assert_eq!(replies[0].reactions.len(), 1);+ assert_eq!(replies[0].attachments.len(), 0);+ assert_eq!(replies[1].id, reply_2.id);+ assert_eq!(replies[1].reactions.len(), 0);+ assert_eq!(replies[1].attachments.len(), 1);+}diff --git a/rust/cloud-storage/channels/src/inbound/axum_router.rs b/rust/cloud-storage/channels/src/inbound/axum_router.rsindex f8411f6afe..686fa55b1c 100644--- a/rust/cloud-storage/channels/src/inbound/axum_router.rs+++ b/rust/cloud-storage/channels/src/inbound/axum_router.rs@@ -24,7 +24,7 @@ use models_pagination::{CursorExtractor, CursorVal, PaginatedOpaqueCursor, Query as PaginationQuery, TypeEraseCursor,};use serde::{Deserialize, Serialize};-use std::sync::Arc;+use std::{collections::HashMap, sync::Arc};use uuid::Uuid;/// State for the channels router.@@ -103,9 +103,15 @@ where.await.map_err(|_| ChannelMemberRejection::Unauthenticated)?;- let Path(channel_id) = Path::<Uuid>::from_request_parts(parts, state)+ let Path(path_params) = Path::<HashMap<String, String>>::from_request_parts(parts, state).await.map_err(|_| ChannelMemberRejection::InvalidPath)?;+ let channel_id = path_params+ .get("channel_id")+ .ok_or(ChannelMemberRejection::InvalidPath)+ .and_then(|raw| {+ Uuid::parse_str(raw.as_str()).map_err(|_| ChannelMemberRejection::InvalidPath)+ })?;let is_member = state.access@@ -133,6 +139,15 @@ pub struct Params {load_around_message_id: Option<Uuid>,}+/// Path params for thread replies endpoint.+#[derive(Debug, Deserialize)]+pub struct ThreadRepliesPath {+ /// Channel ID from path.+ channel_id: Uuid,+ /// Message ID from path.+ message_id: Uuid,+}+fn parse_messages_query(cursor: BidirectionalCursorExtractor<Uuid, CreatedAt, ()>,) -> (@@ -186,6 +201,10 @@ where"/:channel_id/messages",get(get_channel_messages_handler::<S, A>),)+ .route(+ "/:channel_id/messages/:message_id/replies",+ get(get_thread_replies_handler::<S, A>),+ ).route("/:channel_id/attachments",get(get_channel_attachments_handler::<S, A>),@@ -271,6 +290,40 @@ pub async fn get_channel_messages_handler<S: ChannelMessagesService, A: ChannelA}))}+/// Handler for `GET /channels/:channel_id/messages/:message_id/replies`.+#[utoipa::path(+ get,+ operation_id = "get_thread_replies",+ path = "/channels/{channel_id}/messages/{message_id}/replies",+ params(+ ("channel_id" = Uuid, Path, description = "Channel ID"),+ ("message_id" = Uuid, Path, description = "Message ID (thread parent or reply id)")+ ),+ responses(+ (status = 200, body = Vec<ApiThreadReply>),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(err, skip_all)]+pub async fn get_thread_replies_handler<S: ChannelMessagesService, A: ChannelAccessCheck>(+ State(state): State<ChannelsRouterState<S, A>>,+ _member: ChannelMember,+ Path(path): Path<ThreadRepliesPath>,+) -> Result<Json<Vec<ApiThreadReply>>, ChannelsHandlerErr> {+ let channel_id = path.channel_id;+ let message_id = path.message_id;++ let replies = state+ .service+ .get_thread_replies(channel_id, message_id)+ .await?;++ Ok(Json(+ replies.into_iter().map(ApiThreadReply::from).collect(),+ ))+}+/// Handler for `GET /channels/:channel_id/attachments`.#[utoipa::path(get,diff --git a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs b/rust/cloud-storage/channels/src/inbound/axum_router/test.rsindex 7841e1f624..4e3cafc928 100644--- a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs+++ b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs@@ -95,6 +95,14 @@ impl ChannelMessagesService for MockService {.filter_on(()).into_page())}++ async fn get_thread_replies(+ &self,+ _channel_id: Uuid,+ _message_id: Uuid,+ ) -> Result<Vec<crate::domain::models::ThreadReply>, ChannelMessagesErr> {+ Ok(vec![])+ }}struct ErrorService;@@ -134,6 +142,14 @@ impl ChannelMessagesService for ErrorService {) -> Result<ChannelMessagesPage, ChannelMessagesErr> {Err(ChannelMessagesErr::Repo(anyhow::anyhow!("database error")))}++ async fn get_thread_replies(+ &self,+ _channel_id: Uuid,+ _message_id: Uuid,+ ) -> Result<Vec<crate::domain::models::ThreadReply>, ChannelMessagesErr> {+ Err(ChannelMessagesErr::Repo(anyhow::anyhow!("database error")))+ }}struct ParticipantsService;@@ -203,6 +219,14 @@ impl ChannelMessagesService for ParticipantsService {.filter_on(()).into_page())}++ async fn get_thread_replies(+ &self,+ _channel_id: Uuid,+ _message_id: Uuid,+ ) -> Result<Vec<crate::domain::models::ThreadReply>, ChannelMessagesErr> {+ Ok(vec![])+ }}fn user_extension() -> Extension<UserContext> {@@ -451,6 +475,14 @@ impl ChannelMessagesService for NotFoundService {) -> Result<ChannelMessagesPage, ChannelMessagesErr> {Err(ChannelMessagesErr::MessageNotFound(message_id))}++ async fn get_thread_replies(+ &self,+ _channel_id: Uuid,+ message_id: Uuid,+ ) -> Result<Vec<crate::domain::models::ThreadReply>, ChannelMessagesErr> {+ Err(ChannelMessagesErr::MessageNotFound(message_id))+ }}struct AroundHasItemsService;@@ -524,6 +556,14 @@ impl ChannelMessagesService for AroundHasItemsService {.filter_on(()).into_page())}++ async fn get_thread_replies(+ &self,+ _channel_id: Uuid,+ _message_id: Uuid,+ ) -> Result<Vec<crate::domain::models::ThreadReply>, ChannelMessagesErr> {+ Ok(vec![])+ }}#[tokio::test]@@ -590,6 +630,43 @@ async fn messages_around_returns_404_when_not_found() {assert_eq!(json["message"], "Message not found");}+#[tokio::test]+async fn thread_replies_returns_empty_list() {+ let router = mock_router();+ let channel_id = Uuid::new_v4();+ let message_id = Uuid::new_v4();+ let request = Request::builder()+ .uri(format!("/{channel_id}/messages/{message_id}/replies"))+ .body(axum::body::Body::empty())+ .unwrap();++ let res = router.oneshot(request).await.unwrap();+ assert_eq!(res.status(), StatusCode::OK);++ let bytes = res.into_body().collect().await.unwrap().to_bytes();+ let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();+ assert_eq!(json, serde_json::json!([]));+}++#[tokio::test]+async fn thread_replies_returns_404_when_not_found() {+ let router = channels_router(ChannelsRouterState::new(NotFoundService, AlwaysAllow))+ .layer(user_extension());+ let channel_id = Uuid::new_v4();+ let message_id = Uuid::new_v4();+ let request = Request::builder()+ .uri(format!("/{channel_id}/messages/{message_id}/replies"))+ .body(axum::body::Body::empty())+ .unwrap();++ let res = router.oneshot(request).await.unwrap();+ assert_eq!(res.status(), StatusCode::NOT_FOUND);++ let bytes = res.into_body().collect().await.unwrap().to_bytes();+ let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();+ assert_eq!(json["message"], "Message not found");+}+// --- Access control tests ---#[tokio::test]@@ -634,3 +711,17 @@ async fn non_member_cannot_access_participants() {let res = router.oneshot(request).await.unwrap();assert_eq!(res.status(), StatusCode::FORBIDDEN);}++#[tokio::test]+async fn non_member_cannot_access_thread_replies() {+ let router = denied_router();+ let channel_id = Uuid::new_v4();+ let message_id = Uuid::new_v4();+ let request = Request::builder()+ .uri(format!("/{channel_id}/messages/{message_id}/replies"))+ .body(axum::body::Body::empty())+ .unwrap();++ let res = router.oneshot(request).await.unwrap();+ assert_eq!(res.status(), StatusCode::FORBIDDEN);+}diff --git a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rsindex 35fcdd3f73..e7f0c3bc63 100644--- a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs+++ b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs@@ -53,6 +53,18 @@ struct ThreadDataRow {latest_reply_at: Option<chrono::DateTime<chrono::Utc>>,}+/// Intermediate row for full thread replies query.+#[derive(Debug, sqlx::FromRow)]+struct ThreadReplyOnlyRow {+ id: Uuid,+ thread_id: Uuid,+ sender_id: String,+ content: String,+ created_at: chrono::DateTime<chrono::Utc>,+ updated_at: chrono::DateTime<chrono::Utc>,+ edited_at: Option<chrono::DateTime<chrono::Utc>>,+}+/// Intermediate row for reactions.#[derive(Debug)]struct ReactionRow {@@ -276,6 +288,42 @@ impl ChannelMessagesRepo for PgChannelMessagesRepo {Ok(map)}+ #[tracing::instrument(err, skip(self))]+ async fn get_thread_replies(&self, parent_id: Uuid) -> Result<Vec<ThreadReplyRow>, Self::Err> {+ let rows = sqlx::query_as::<_, ThreadReplyOnlyRow>(+ r#"+ SELECT+ id,+ thread_id,+ sender_id,+ content,+ created_at,+ updated_at,+ edited_at::timestamptz AS edited_at+ FROM comms_messages+ WHERE thread_id = $1+ AND deleted_at IS NULL+ ORDER BY created_at ASC, id ASC+ "#,+ )+ .bind(parent_id)+ .fetch_all(&self.pool)+ .await?;++ Ok(rows+ .into_iter()+ .map(|r| ThreadReplyRow {+ id: r.id,+ thread_id: r.thread_id,+ sender_id: r.sender_id,+ content: r.content,+ created_at: r.created_at,+ updated_at: r.updated_at,+ edited_at: r.edited_at,+ })+ .collect())+ }+#[tracing::instrument(err, skip(self))]async fn get_reactions_batch(&self,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.rsindex f61cb8567d..fd73cb18d9 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@@ -282,6 +282,74 @@ async fn thread_data_multiple_parents(pool: Pool<Postgres>) -> anyhow::Result<()Ok(())}+#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn thread_replies_returns_all_active_replies_oldest_first(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool);+ let replies = repo.get_thread_replies(MSG1).await?;++ let ids: Vec<Uuid> = replies.iter().map(|r| r.id).collect();+ assert_eq!(ids.len(), 4);+ assert_eq!(ids[0], REPLY1);+ assert_eq!(+ ids[3],+ Uuid::from_u128(0x00000000_0000_0000_0000_00000000b004)+ );+ let content: Vec<&str> = replies.iter().map(|r| r.content.as_str()).collect();+ assert_eq!(content, vec!["reply 1", "reply 2", "reply 3", "reply 4"]);+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn thread_replies_returns_non_null_edited_at(pool: Pool<Postgres>) -> anyhow::Result<()> {+ sqlx::query(+ r#"+ UPDATE comms_messages+ SET edited_at = '2024-01-01 10:05:00'+ WHERE id = '00000000-0000-0000-0000-00000000b003'+ "#,+ )+ .execute(&pool)+ .await?;++ let repo = repo(pool);+ let replies = repo.get_thread_replies(MSG1).await?;+ let edited_reply = replies+ .into_iter()+ .find(|r| r.id == Uuid::from_u128(0x00000000_0000_0000_0000_00000000b003))+ .expect("expected fixture reply");++ assert!(edited_reply.edited_at.is_some());+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn thread_replies_excludes_deleted_rows(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ let fully_deleted_parent = Uuid::from_u128(0x00000000_0000_0000_0000_000000000004);+ let deleted_parent_replies = repo.get_thread_replies(fully_deleted_parent).await?;+ assert!(+ deleted_parent_replies.is_empty(),+ "deleted replies should not be returned"+ );++ let active_replies = repo.get_thread_replies(MSG2).await?;+ assert_eq!(active_replies.len(), 1);+ assert_eq!(active_replies[0].id, REPLY5);+ assert_eq!(active_replies[0].content, "reply to deleted");+ Ok(())+}+#[sqlx::test(fixtures(path = "../../../fixtures", scripts("channels_repo")),migrator = "MACRO_DB_MIGRATIONS"