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): support message_ids filter in get_channel_messages (#2708)
teod98ed7a6f4c8
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageFilters.ts b/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageFilters.tsnew file mode 100644index 0000000000..5c18e8f755--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/channelMessageFilters.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Filters for channel message queries.+ */+export interface ChannelMessageFilters {+ /** When non-empty, only return messages with these IDs. */+ message_ids?: string[];+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.tsindex ad3c0c1463..710105f935 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts@@ -98,6 +98,7 @@ export * from './channelFiltersOrgId';export * from './channelFiltersTeamId';export * from './channelMessage';export * from './channelMessageDeletedAt';+export * from './channelMessageFilters';export * from './channelMessageThreadId';export * from './channelName';export * from './channelOrgId';@@ -440,6 +441,7 @@ export * from './pdfPlaceableCommentAnchorRequest';export * from './pdfPlaceableCommentAnchorRequestUuid';export * from './pinnedItem';export * from './pinRequest';+export * from './postChannelMessagesParams';export * from './postItemsSoupAstParams';export * from './postItemsSoupParams';export * from './postSoupAstRequest';diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/postChannelMessagesParams.ts b/js/app/packages/service-clients/service-storage/generated/schemas/postChannelMessagesParams.tsnew file mode 100644index 0000000000..9eb7271637--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/postChannelMessagesParams.ts@@ -0,0 +1,26 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type PostChannelMessagesParams = {+ /**+ * Page size (1-100, default 50)+ * @minimum 0+ */+ limit?: number;+ /**+ * Base64 encoded cursor value for older messages+ */+ cursor?: string;+ /**+ * Base64 encoded cursor value for newer messages+ */+ previous_cursor?: string;+ /**+ * Return a centered window around this message ID+ */+ load_around_message_id?: string;+};diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex c88c1f409e..f747d48262 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -1322,6 +1322,201 @@ export const getChannelMessagesResponse = zod}).describe('Paginated response of channel messages.');+/**+ * @summary Handler for `POST /channels/{channel_id}/messages`.+ */+export const postChannelMessagesParams = zod.object({+ channel_id: zod.string().uuid().describe('Channel ID'),+});++export const postChannelMessagesQueryLimitMin = 0;++export const postChannelMessagesQueryParams = zod.object({+ limit: zod+ .number()+ .min(postChannelMessagesQueryLimitMin)+ .optional()+ .describe('Page size (1-100, default 50)'),+ cursor: zod+ .string()+ .optional()+ .describe('Base64 encoded cursor value for older messages'),+ previous_cursor: zod+ .string()+ .optional()+ .describe('Base64 encoded cursor value for newer messages'),+ load_around_message_id: zod+ .string()+ .uuid()+ .optional()+ .describe('Return a centered window around this message ID'),+});++export const postChannelMessagesBody = zod+ .object({+ message_ids: zod+ .array(zod.string().uuid())+ .optional()+ .describe('When non-empty, only return messages with these IDs.'),+ })+ .describe('Filters for channel message queries.');++export const postChannelMessagesResponse = zod+ .object({+ items: zod+ .array(+ zod+ .object({+ attachments: zod+ .array(+ zod+ .object({+ created_at: zod+ .string()+ .datetime({})+ .describe('When the attachment was created.'),+ entity_id: zod.string().describe('Entity id.'),+ entity_type: zod.string().describe('Type of entity.'),+ height: zod+ .number()+ .nullish()+ .describe('Height (for images).'),+ id: zod.string().uuid().describe('Attachment id.'),+ width: zod+ .number()+ .nullish()+ .describe('Width (for images).'),+ })+ .describe('An attachment on a message.')+ )+ .describe('Attachments on this message.'),+ channel_id: zod.string().uuid().describe('Channel id.'),+ content: zod.string().describe('Message content.'),+ created_at: zod+ .string()+ .datetime({})+ .describe('When the message was created.'),+ deleted_at: zod+ .string()+ .datetime({})+ .nullish()+ .describe('When the message was soft-deleted.'),+ edited_at: zod+ .string()+ .datetime({})+ .nullish()+ .describe('When the message was edited.'),+ id: zod.string().uuid().describe('Message id.'),+ reactions: zod+ .array(+ zod+ .object({+ emoji: zod.string().describe('The emoji string.'),+ users: zod+ .array(zod.string())+ .describe('User ids who added this reaction.'),+ })+ .describe('A reaction with emoji and user list.')+ )+ .describe('Reactions on this message.'),+ sender_id: zod.string().describe('Sender user id.'),+ thread: zod+ .object({+ latest_reply_at: zod+ .string()+ .datetime({})+ .nullish()+ .describe('Timestamp of the latest reply.'),+ preview: zod+ .array(+ zod+ .object({+ attachments: zod+ .array(+ zod+ .object({+ created_at: zod+ .string()+ .datetime({})+ .describe('When the attachment was created.'),+ entity_id: zod.string().describe('Entity id.'),+ entity_type: zod+ .string()+ .describe('Type of entity.'),+ height: zod+ .number()+ .nullish()+ .describe('Height (for images).'),+ id: zod+ .string()+ .uuid()+ .describe('Attachment id.'),+ width: zod+ .number()+ .nullish()+ .describe('Width (for images).'),+ })+ .describe('An attachment on a message.')+ )+ .describe('Attachments on this reply.'),+ content: zod.string().describe('Reply content.'),+ created_at: zod+ .string()+ .datetime({})+ .describe('When the reply was created.'),+ edited_at: zod+ .string()+ .datetime({})+ .nullish()+ .describe('When the reply was edited.'),+ id: zod.string().uuid().describe('Reply id.'),+ reactions: zod+ .array(+ zod+ .object({+ emoji: zod+ .string()+ .describe('The emoji string.'),+ users: zod+ .array(zod.string())+ .describe(+ 'User ids who added this reaction.'+ ),+ })+ .describe('A reaction with emoji and user list.')+ )+ .describe('Reactions on this reply.'),+ sender_id: zod.string().describe('Sender user id.'),+ updated_at: zod+ .string()+ .datetime({})+ .describe('When the reply was last updated.'),+ })+ .describe('A thread reply shown in preview.')+ )+ .describe('Last N replies for thread preview.'),+ reply_count: zod.number().describe('Total reply count.'),+ })+ .describe('Thread metadata and preview replies.'),+ updated_at: zod+ .string()+ .datetime({})+ .describe('When the message was last updated.'),+ })+ .describe('A top-level channel message with thread info.')+ )+ .describe('Messages on this page.'),+ next_cursor: zod+ .string()+ .nullish()+ .describe('Cursor for the next page, null if no more pages.'),+ previous_cursor: zod+ .string()+ .nullish()+ .describe('Cursor for the previous page, null if no newer page exists.'),+ })+ .describe('Paginated response of channel messages.');+/*** @summary Handler for `GET /channels/{channel_id}/messages/{message_id}/replies`.*/diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 3fcd65cf7c..77b82280d5 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -1280,6 +1280,124 @@}}}+ },+ "post": {+ "tags": ["channels::inbound::axum_router"],+ "summary": "Handler for `POST /channels/{channel_id}/messages`.",+ "operationId": "post_channel_messages",+ "parameters": [+ {+ "name": "channel_id",+ "in": "path",+ "description": "Channel ID",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ },+ {+ "name": "limit",+ "in": "query",+ "description": "Page size (1-100, default 50)",+ "required": false,+ "schema": {+ "type": "integer",+ "format": "int32",+ "minimum": 0+ }+ },+ {+ "name": "cursor",+ "in": "query",+ "description": "Base64 encoded cursor value for older messages",+ "required": false,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "previous_cursor",+ "in": "query",+ "description": "Base64 encoded cursor value for newer messages",+ "required": false,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "load_around_message_id",+ "in": "query",+ "description": "Return a centered window around this message ID",+ "required": false,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ChannelMessageFilters"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiChannelMessagesPage"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }}},"/channels/{channel_id}/messages/{message_id}/replies": {@@ -6339,6 +6457,20 @@}}},+ "ChannelMessageFilters": {+ "type": "object",+ "description": "Filters for channel message queries.",+ "properties": {+ "message_ids": {+ "type": "array",+ "items": {+ "type": "string",+ "format": "uuid"+ },+ "description": "When non-empty, only return messages with these IDs."+ }+ }+ },"ChannelParticipant": {"type": "object","required": ["channel_id", "user_id", "role", "joined_at"],diff --git a/rust/cloud-storage/channels/.sqlx/query-e370c8ac63367ff5f64f67376057512c24bd0ff50a8cd514f9c806620dc08d0d.json b/rust/cloud-storage/channels/.sqlx/query-18e88dcc063b70409ffbba9265b382056a22e0fceea057bd654a8d777fd8657d.jsonsimilarity index 86%rename from rust/cloud-storage/channels/.sqlx/query-e370c8ac63367ff5f64f67376057512c24bd0ff50a8cd514f9c806620dc08d0d.jsonrename to rust/cloud-storage/channels/.sqlx/query-18e88dcc063b70409ffbba9265b382056a22e0fceea057bd654a8d777fd8657d.jsonindex 60ced823ee..72f2fc1c87 100644--- a/rust/cloud-storage/channels/.sqlx/query-e370c8ac63367ff5f64f67376057512c24bd0ff50a8cd514f9c806620dc08d0d.json+++ b/rust/cloud-storage/channels/.sqlx/query-18e88dcc063b70409ffbba9265b382056a22e0fceea057bd654a8d777fd8657d.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n m.id,\n m.channel_id,\n m.sender_id,\n m.content,\n m.created_at,\n m.updated_at,\n m.edited_at::timestamptz AS \"edited_at?\",\n m.deleted_at::timestamptz AS \"deleted_at?\"\n FROM comms_messages m\n WHERE m.channel_id = $1\n AND m.thread_id IS NULL\n AND (m.deleted_at IS NULL OR EXISTS (\n SELECT 1 FROM comms_messages r\n WHERE r.thread_id = m.id AND r.deleted_at IS NULL\n ))\n AND ($2::timestamptz IS NOT NULL AND (m.created_at, m.id) > ($2, $3))\n ORDER BY m.created_at ASC, m.id ASC\n LIMIT $4\n ",+ "query": "\n SELECT\n m.id,\n m.channel_id,\n m.sender_id,\n m.content,\n m.created_at,\n m.updated_at,\n m.edited_at::timestamptz AS \"edited_at?\",\n m.deleted_at::timestamptz AS \"deleted_at?\"\n FROM comms_messages m\n WHERE m.channel_id = $1\n AND m.thread_id IS NULL\n AND (m.deleted_at IS NULL OR EXISTS (\n SELECT 1 FROM comms_messages r\n WHERE r.thread_id = m.id AND r.deleted_at IS NULL\n ))\n AND ($2::timestamptz IS NOT NULL AND (m.created_at, m.id) > ($2, $3))\n AND ($5::uuid[] IS NULL OR m.id = ANY($5))\n ORDER BY m.created_at ASC, m.id ASC\n LIMIT $4\n ","describe": {"columns": [{@@ -49,7 +49,8 @@"Uuid","Timestamptz","Uuid",- "Int8"+ "Int8",+ "UuidArray"]},"nullable": [@@ -63,5 +64,5 @@null]},- "hash": "e370c8ac63367ff5f64f67376057512c24bd0ff50a8cd514f9c806620dc08d0d"+ "hash": "18e88dcc063b70409ffbba9265b382056a22e0fceea057bd654a8d777fd8657d"}diff --git a/rust/cloud-storage/channels/.sqlx/query-f5bbf9adae5783fab3e4ab384c5232bb49f8f0323f5a117f2cc8421e143ae797.json b/rust/cloud-storage/channels/.sqlx/query-bcb3ab4393f39aad3c3e76f634585b43fedb48da0081ea896bf39a7c18f261bd.jsonsimilarity index 86%rename from rust/cloud-storage/channels/.sqlx/query-f5bbf9adae5783fab3e4ab384c5232bb49f8f0323f5a117f2cc8421e143ae797.jsonrename to rust/cloud-storage/channels/.sqlx/query-bcb3ab4393f39aad3c3e76f634585b43fedb48da0081ea896bf39a7c18f261bd.jsonindex 195ba1d6fc..6bf4125490 100644--- a/rust/cloud-storage/channels/.sqlx/query-f5bbf9adae5783fab3e4ab384c5232bb49f8f0323f5a117f2cc8421e143ae797.json+++ b/rust/cloud-storage/channels/.sqlx/query-bcb3ab4393f39aad3c3e76f634585b43fedb48da0081ea896bf39a7c18f261bd.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n m.id,\n m.channel_id,\n m.sender_id,\n m.content,\n m.created_at,\n m.updated_at,\n m.edited_at::timestamptz AS \"edited_at?\",\n m.deleted_at::timestamptz AS \"deleted_at?\"\n FROM comms_messages m\n WHERE m.channel_id = $1\n AND m.thread_id IS NULL\n AND (m.deleted_at IS NULL OR EXISTS (\n SELECT 1 FROM comms_messages r\n WHERE r.thread_id = m.id AND r.deleted_at IS NULL\n ))\n AND ($2::timestamptz IS NULL OR (m.created_at, m.id) < ($2, $3))\n ORDER BY m.created_at DESC, m.id DESC\n LIMIT $4\n ",+ "query": "\n SELECT\n m.id,\n m.channel_id,\n m.sender_id,\n m.content,\n m.created_at,\n m.updated_at,\n m.edited_at::timestamptz AS \"edited_at?\",\n m.deleted_at::timestamptz AS \"deleted_at?\"\n FROM comms_messages m\n WHERE m.channel_id = $1\n AND m.thread_id IS NULL\n AND (m.deleted_at IS NULL OR EXISTS (\n SELECT 1 FROM comms_messages r\n WHERE r.thread_id = m.id AND r.deleted_at IS NULL\n ))\n AND ($2::timestamptz IS NULL OR (m.created_at, m.id) < ($2, $3))\n AND ($5::uuid[] IS NULL OR m.id = ANY($5))\n ORDER BY m.created_at DESC, m.id DESC\n LIMIT $4\n ","describe": {"columns": [{@@ -49,7 +49,8 @@"Uuid","Timestamptz","Uuid",- "Int8"+ "Int8",+ "UuidArray"]},"nullable": [@@ -63,5 +64,5 @@null]},- "hash": "f5bbf9adae5783fab3e4ab384c5232bb49f8f0323f5a117f2cc8421e143ae797"+ "hash": "bcb3ab4393f39aad3c3e76f634585b43fedb48da0081ea896bf39a7c18f261bd"}diff --git a/rust/cloud-storage/channels/src/domain/models.rs b/rust/cloud-storage/channels/src/domain/models.rsindex c1baac6e47..d49db0004b 100644--- a/rust/cloud-storage/channels/src/domain/models.rs+++ b/rust/cloud-storage/channels/src/domain/models.rs@@ -1,5 +1,6 @@use chrono::{DateTime, Utc};use models_pagination::{CreatedAt, CursorVal, Identify, SortOn};+use serde::Deserialize;use uuid::Uuid;/// Request to fetch a page of channel messages.@@ -11,6 +12,15 @@ pub struct GetChannelMessagesRequest {pub limit: u16,}+/// Filters for channel message queries.+#[derive(Debug, Clone, Default, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+pub struct ChannelMessageFilters {+ /// When non-empty, only return messages with these IDs.+ #[serde(default)]+ pub message_ids: Vec<Uuid>,+}+/// Direction for cursor-based message pagination.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum MessagePageDirection {diff --git a/rust/cloud-storage/channels/src/domain/ports.rs b/rust/cloud-storage/channels/src/domain/ports.rsindex 964a65f51c..abb049acff 100644--- a/rust/cloud-storage/channels/src/domain/ports.rs+++ b/rust/cloud-storage/channels/src/domain/ports.rs@@ -1,6 +1,7 @@use crate::domain::models::{- ChannelAttachment, ChannelParticipant, CountedReaction, MessageAttachment,- MessagePageDirection, ThreadData, ThreadReply, ThreadReplyRow, TopLevelMessageRow,+ ChannelAttachment, ChannelMessageFilters, ChannelParticipant, CountedReaction,+ MessageAttachment, MessagePageDirection, ThreadData, ThreadReply, ThreadReplyRow,+ TopLevelMessageRow,};use chrono::{DateTime, Utc};use models_pagination::{CreatedAt, Query};@@ -20,6 +21,7 @@ pub trait ChannelMessagesRepo: Send + Sync + 'static {query: &Query<Uuid, CreatedAt, ()>,direction: MessagePageDirection,limit: u16,+ filters: &ChannelMessageFilters,) -> impl Future<Output = Result<TopLevelMessagesQueryResult, Self::Err>> + Send;/// Batch-fetch thread data (stats + preview replies) for parent messages in a single query.@@ -89,6 +91,7 @@ pub trait ChannelMessagesService: Send + Sync + 'static {query: Query<Uuid, CreatedAt, ()>,direction: MessagePageDirection,limit: u16,+ filters: &ChannelMessageFilters,) -> impl Future<Output = Result<ChannelMessagesQueryResult, ChannelMessagesErr>> + Send;/// Fetch a paginated page of channel-level attachments.diff --git a/rust/cloud-storage/channels/src/domain/service.rs b/rust/cloud-storage/channels/src/domain/service.rsindex 884a75223b..c8f1d77613 100644--- a/rust/cloud-storage/channels/src/domain/service.rs+++ b/rust/cloud-storage/channels/src/domain/service.rs@@ -1,7 +1,7 @@use crate::domain::{models::{- ChannelMessage, ChannelParticipant, MessagePageDirection, ThreadInfo, ThreadReply,- TopLevelMessageRow,+ ChannelMessage, ChannelMessageFilters, ChannelParticipant, MessagePageDirection,+ ThreadInfo, ThreadReply, TopLevelMessageRow,},ports::{ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesPage,@@ -161,12 +161,13 @@ wherequery: Query<Uuid, CreatedAt, ()>,direction: MessagePageDirection,limit: u16,+ filters: &ChannelMessageFilters,) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {let limit = limit.clamp(1, 100);let rows_result = self.repo- .get_top_level_messages(channel_id, &query, direction, limit)+ .get_top_level_messages(channel_id, &query, direction, limit, filters).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.rsindex 627d290a37..daa3803d87 100644--- a/rust/cloud-storage/channels/src/domain/service/test.rs+++ b/rust/cloud-storage/channels/src/domain/service/test.rs@@ -1,8 +1,8 @@use super::*;use crate::domain::{models::{- CountedReaction, MessageAttachment, MessagePageDirection, ThreadData, ThreadReplyRow,- TopLevelMessageRow,+ ChannelMessageFilters, CountedReaction, MessageAttachment, MessagePageDirection,+ ThreadData, ThreadReplyRow, TopLevelMessageRow,},ports::{MockChannelMessagesRepo, TopLevelMessagesQueryResult},};@@ -26,7 +26,7 @@ fn make_row(id: Uuid, minutes_ago: i64) -> TopLevelMessageRow {fn empty_repo() -> MockChannelMessagesRepo {let mut repo = MockChannelMessagesRepo::new();repo.expect_get_top_level_messages()- .returning(|_, _, _, _| {+ .returning(|_, _, _, _, _| {Box::pin(async {Ok(TopLevelMessagesQueryResult {rows: vec![],@@ -62,6 +62,7 @@ async fn returns_empty_page_for_no_messages() {Query::Sort(CreatedAt, ()),MessagePageDirection::Older,50,+ &ChannelMessageFilters::default(),).await.unwrap();@@ -92,7 +93,7 @@ async fn returns_messages_with_thread_info() {let row_clone = row.clone();repo.expect_get_top_level_messages()- .returning(move |_, _, _, _| {+ .returning(move |_, _, _, _, _| {let r = row_clone.clone();Box::pin(async move {Ok(TopLevelMessagesQueryResult {@@ -149,6 +150,7 @@ async fn returns_messages_with_thread_info() {Query::Sort(CreatedAt, ()),MessagePageDirection::Older,50,+ &ChannelMessageFilters::default(),).await.unwrap();@@ -167,8 +169,8 @@ async fn returns_messages_with_thread_info() {async fn clamps_limit() {let mut repo = MockChannelMessagesRepo::new();repo.expect_get_top_level_messages()- .withf(|_, _, _, limit| *limit == 100)- .returning(|_, _, _, _| {+ .withf(|_, _, _, limit, _| *limit == 100)+ .returning(|_, _, _, _, _| {Box::pin(async {Ok(TopLevelMessagesQueryResult {rows: vec![],@@ -190,6 +192,7 @@ async fn clamps_limit() {Query::Sort(CreatedAt, ()),MessagePageDirection::Older,200,+ &ChannelMessageFilters::default(),).await.unwrap();diff --git a/rust/cloud-storage/channels/src/inbound/axum_router.rs b/rust/cloud-storage/channels/src/inbound/axum_router.rsindex 32ac93beda..8e09015c45 100644--- a/rust/cloud-storage/channels/src/inbound/axum_router.rs+++ b/rust/cloud-storage/channels/src/inbound/axum_router.rs@@ -1,6 +1,7 @@#[cfg(test)]mod test;+pub use crate::domain::models::ChannelMessageFilters;use crate::domain::models::{ChannelAttachment, ChannelMessage, ChannelParticipant, CountedReaction, MessageAttachment,MessagePageDirection, ParticipantRole, ThreadInfo, ThreadReply,@@ -70,6 +71,8 @@ fn channel_id_from_receipt<T: RequiredPermission>(.map_err(|_| ChannelsHandlerErr::BadRequest("Invalid channel_id"))}+const MAX_MESSAGE_ID_FILTERS: usize = 100;+/// Query parameters for the messages endpoint.#[derive(Debug, Default, Deserialize)]pub struct Params {@@ -142,7 +145,8 @@ whereRouter::new().route("/{channel_id}/messages",- get(get_channel_messages_handler::<S, Svc>),+ get(get_channel_messages_handler::<S, Svc>)+ .post(post_channel_messages_handler::<S, Svc>),).route("/{channel_id}/messages/{message_id}/replies",@@ -195,10 +199,68 @@ pub async fn get_channel_messages_handler<S: ChannelMessagesService, Svc: Entityaccess: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,Query(params): Query<Params>,cursor: Option<BidirectionalCursor<Uuid, CreatedAt, ()>>,+) -> Result<Json<ApiChannelMessagesPage>, ChannelsHandlerErr> {+ let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;+ let filters = ChannelMessageFilters::default();+ channel_messages_response(&state, params, cursor, channel_id, &filters).await+}++/// Handler for `POST /channels/{channel_id}/messages`.+#[utoipa::path(+ post,+ operation_id = "post_channel_messages",+ path = "/channels/{channel_id}/messages",+ params(+ ("channel_id" = Uuid, Path, description = "Channel ID"),+ ("limit" = Option<u16>, Query, description = "Page size (1-100, default 50)"),+ ("cursor" = Option<String>, Query, description = "Base64 encoded cursor value for older messages"),+ ("previous_cursor" = Option<String>, Query, description = "Base64 encoded cursor value for newer messages"),+ ("load_around_message_id" = Option<Uuid>, Query, description = "Return a centered window around this message ID"),+ ),+ request_body = ChannelMessageFilters,+ responses(+ (status = 200, body = ApiChannelMessagesPage),+ (status = 401, body = ErrorResponse),+ (status = 400, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(+ err,+ skip_all,+ fields(+ channel_id = tracing::field::Empty,+ limit = tracing::field::Empty,+ page_direction = tracing::field::Empty,+ has_cursor = tracing::field::Empty,+ load_around_message_id = tracing::field::Empty+ )+)]+pub async fn post_channel_messages_handler<S: ChannelMessagesService, Svc: EntityAccessService>(+ State(state): State<ChannelsRouterState<S, Svc>>,+ access: ChannelAccessLevelExtractor<MemberParticipantRole, Svc>,+ Query(params): Query<Params>,+ cursor: Option<BidirectionalCursor<Uuid, CreatedAt, ()>>,+ Json(filters): Json<ChannelMessageFilters>,+) -> Result<Json<ApiChannelMessagesPage>, ChannelsHandlerErr> {+ let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;+ if filters.message_ids.len() > MAX_MESSAGE_ID_FILTERS {+ return Err(ChannelsHandlerErr::BadRequest("too many message_ids"));+ }+ channel_messages_response(&state, params, cursor, channel_id, &filters).await+}++async fn channel_messages_response<S: ChannelMessagesService, Svc>(+ state: &ChannelsRouterState<S, Svc>,+ params: Params,+ cursor: Option<BidirectionalCursor<Uuid, CreatedAt, ()>>,+ channel_id: Uuid,+ filters: &ChannelMessageFilters,) -> Result<Json<ApiChannelMessagesPage>, ChannelsHandlerErr> {let limit = params.limit.unwrap_or(50).clamp(1, 100);let (query, direction, has_cursor) = parse_messages_query(cursor);- let channel_id = channel_id_from_receipt(&access.entity_access_receipt)?;+let span = tracing::Span::current();span.record("channel_id", tracing::field::display(channel_id));span.record("limit", limit);@@ -223,7 +285,7 @@ pub async fn get_channel_messages_handler<S: ChannelMessagesService, Svc: Entityhas_more_newer,} = state.service- .get_channel_messages(channel_id, query, direction, limit)+ .get_channel_messages(channel_id, query, direction, limit, filters).await?;(page, has_more_newer)}diff --git a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs b/rust/cloud-storage/channels/src/inbound/axum_router/test.rsindex 346efa857d..ccff754cea 100644--- a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs+++ b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs@@ -1,6 +1,7 @@use super::*;use crate::domain::models::{- ChannelAttachment, ChannelMessage, ChannelParticipant, MessagePageDirection, ParticipantRole,+ ChannelAttachment, ChannelMessage, ChannelMessageFilters, ChannelParticipant,+ MessagePageDirection, ParticipantRole,};use crate::domain::ports::{ChannelAttachmentsPage, ChannelMessagesErr, ChannelMessagesPage, ChannelMessagesQueryResult,@@ -171,6 +172,7 @@ impl ChannelMessagesService for MockService {_query: Query<Uuid, CreatedAt, ()>,_direction: MessagePageDirection,_limit: u16,+ _filters: &ChannelMessageFilters,) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {Ok(ChannelMessagesQueryResult {page: Vec::<ChannelMessage>::new()@@ -233,6 +235,7 @@ impl ChannelMessagesService for ErrorService {_query: Query<Uuid, CreatedAt, ()>,_direction: MessagePageDirection,_limit: u16,+ _filters: &ChannelMessageFilters,) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {Err(ChannelMessagesErr::Repo(anyhow::anyhow!("database error")))}@@ -280,6 +283,7 @@ impl ChannelMessagesService for ParticipantsService {_query: Query<Uuid, CreatedAt, ()>,_direction: MessagePageDirection,_limit: u16,+ _filters: &ChannelMessageFilters,) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {Ok(ChannelMessagesQueryResult {page: Vec::<ChannelMessage>::new()@@ -578,6 +582,7 @@ impl ChannelMessagesService for NotFoundService {_query: Query<Uuid, CreatedAt, ()>,_direction: MessagePageDirection,_limit: u16,+ _filters: &ChannelMessageFilters,) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {Ok(ChannelMessagesQueryResult {page: Vec::<ChannelMessage>::new()@@ -636,6 +641,7 @@ impl ChannelMessagesService for AroundHasItemsService {_query: Query<Uuid, CreatedAt, ()>,_direction: MessagePageDirection,_limit: u16,+ _filters: &ChannelMessageFilters,) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {Ok(ChannelMessagesQueryResult {page: Vec::<ChannelMessage>::new()@@ -778,6 +784,161 @@ async fn messages_around_returns_404_when_not_found() {assert_eq!(json["message"], "Message not found");}+// --- POST /messages filter tests ---++struct CapturingService {+ captured: std::sync::Mutex<Option<ChannelMessageFilters>>,+}++impl CapturingService {+ fn new() -> std::sync::Arc<Self> {+ std::sync::Arc::new(Self {+ captured: std::sync::Mutex::new(None),+ })+ }+}++impl ChannelMessagesService for std::sync::Arc<CapturingService> {+ async fn get_channel_messages(+ &self,+ _channel_id: Uuid,+ _query: Query<Uuid, CreatedAt, ()>,+ _direction: MessagePageDirection,+ _limit: u16,+ filters: &ChannelMessageFilters,+ ) -> Result<ChannelMessagesQueryResult, ChannelMessagesErr> {+ *self.captured.lock().unwrap() = Some(filters.clone());+ Ok(ChannelMessagesQueryResult {+ page: Vec::<ChannelMessage>::new()+ .into_iter()+ .paginate_on(50, CreatedAt)+ .filter_on(())+ .into_page(),+ has_more_newer: false,+ })+ }++ async fn get_channel_attachments(+ &self,+ _channel_id: Uuid,+ _query: Query<Uuid, CreatedAt, ()>,+ _limit: u16,+ ) -> Result<ChannelAttachmentsPage, ChannelMessagesErr> {+ Ok(Vec::<ChannelAttachment>::new()+ .into_iter()+ .paginate_on(50, CreatedAt)+ .filter_on(())+ .into_page())+ }++ async fn get_channel_participants(+ &self,+ _channel_id: Uuid,+ ) -> Result<Vec<ChannelParticipant>, ChannelMessagesErr> {+ Ok(vec![])+ }++ async fn get_channel_messages_around(+ &self,+ _channel_id: Uuid,+ _message_id: Uuid,+ _limit: u16,+ ) -> Result<ChannelMessagesPage, ChannelMessagesErr> {+ Ok(Vec::<ChannelMessage>::new()+ .into_iter()+ .paginate_on(50, CreatedAt)+ .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]+async fn post_messages_empty_body_uses_default_filters() {+ let svc = CapturingService::new();+ let router = channels_router(ChannelsRouterState::new(+ svc.clone(),+ TestAccessService::allow(),+ ))+ .layer(user_extension());++ let channel_id = Uuid::new_v4();+ let request = Request::builder()+ .method("POST")+ .uri(format!("/{channel_id}/messages"))+ .header("content-type", "application/json")+ .body(axum::body::Body::from("{}"))+ .unwrap();++ let res = router.oneshot(request).await.unwrap();+ assert_eq!(res.status(), StatusCode::OK);++ let captured = svc.captured.lock().unwrap().clone().unwrap();+ assert!(captured.message_ids.is_empty());+}++#[tokio::test]+async fn post_messages_forwards_message_ids_filter() {+ let svc = CapturingService::new();+ let router = channels_router(ChannelsRouterState::new(+ svc.clone(),+ TestAccessService::allow(),+ ))+ .layer(user_extension());++ let channel_id = Uuid::new_v4();+ let id_a = Uuid::new_v4();+ let id_b = Uuid::new_v4();+ let body = serde_json::json!({ "message_ids": [id_a, id_b] }).to_string();++ let request = Request::builder()+ .method("POST")+ .uri(format!("/{channel_id}/messages"))+ .header("content-type", "application/json")+ .body(axum::body::Body::from(body))+ .unwrap();++ let res = router.oneshot(request).await.unwrap();+ assert_eq!(res.status(), StatusCode::OK);++ let captured = svc.captured.lock().unwrap().clone().unwrap();+ assert_eq!(captured.message_ids, vec![id_a, id_b]);+}++#[tokio::test]+async fn post_messages_rejects_oversized_filter_list() {+ let router = channels_router(ChannelsRouterState::new(+ MockService,+ TestAccessService::allow(),+ ))+ .layer(user_extension());++ let channel_id = Uuid::new_v4();+ let ids: Vec<Uuid> = (0..101).map(|_| Uuid::new_v4()).collect();+ let body = serde_json::json!({ "message_ids": ids }).to_string();++ let request = Request::builder()+ .method("POST")+ .uri(format!("/{channel_id}/messages"))+ .header("content-type", "application/json")+ .body(axum::body::Body::from(body))+ .unwrap();++ let res = router.oneshot(request).await.unwrap();+ assert_eq!(res.status(), StatusCode::BAD_REQUEST);++ 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"], "too many message_ids");+}+#[tokio::test]async fn thread_replies_returns_empty_list() {let router = mock_router();diff --git a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rsindex 90f0e4e4ba..fdc1c88560 100644--- a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs+++ b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs@@ -3,8 +3,9 @@ mod tests;use crate::domain::{models::{- ChannelAttachment, ChannelParticipant, CountedReaction, MessageAttachment,- MessagePageDirection, ParticipantRole, ThreadData, ThreadReplyRow, TopLevelMessageRow,+ ChannelAttachment, ChannelMessageFilters, ChannelParticipant, CountedReaction,+ MessageAttachment, MessagePageDirection, ParticipantRole, ThreadData, ThreadReplyRow,+ TopLevelMessageRow,},ports::{ChannelMessagesRepo, TopLevelMessagesQueryResult},};@@ -119,6 +120,7 @@ impl ChannelMessagesRepo for PgChannelMessagesRepo {query: &Query<Uuid, CreatedAt, ()>,direction: MessagePageDirection,limit: u16,+ filters: &ChannelMessageFilters,) -> Result<TopLevelMessagesQueryResult, Self::Err> {let (cursor_created_at, cursor_id) = match query.vals() {(Some(id), Some(val)) => (Some(*val), Some(*id)),@@ -127,6 +129,12 @@ impl ChannelMessagesRepo for PgChannelMessagesRepo {let limit_i64 = i64::from(limit);let limit_usize = usize::from(limit);+ let message_ids_filter: Option<&[Uuid]> = if filters.message_ids.is_empty() {+ None+ } else {+ Some(&filters.message_ids)+ };+let (rows, has_more_newer) = match direction {MessagePageDirection::Older => {let rows = sqlx::query_as!(@@ -149,6 +157,7 @@ impl ChannelMessagesRepo for PgChannelMessagesRepo {WHERE r.thread_id = m.id AND r.deleted_at IS NULL))AND ($2::timestamptz IS NULL OR (m.created_at, m.id) < ($2, $3))+ AND ($5::uuid[] IS NULL OR m.id = ANY($5))ORDER BY m.created_at DESC, m.id DESCLIMIT $4"#,@@ -156,17 +165,14 @@ impl ChannelMessagesRepo for PgChannelMessagesRepo {cursor_created_at,cursor_id,limit_i64,+ message_ids_filter as Option<&[Uuid]>,).fetch_all(&self.pool).await?;- // For older pagination with a cursor, there is always at least one newer item- // (the cursor anchor itself) from the API's perspective.(rows, cursor_created_at.is_some())}MessagePageDirection::Newer => {- // Query in ASC so we can overfetch one newer row and trim while preserving the- // "nearest newer page" semantics before reversing back to DESC.let mut rows = sqlx::query_as!(TopLevelRow,r#"@@ -187,6 +193,7 @@ impl ChannelMessagesRepo for PgChannelMessagesRepo {WHERE r.thread_id = m.id AND r.deleted_at IS NULL))AND ($2::timestamptz IS NOT NULL AND (m.created_at, m.id) > ($2, $3))+ AND ($5::uuid[] IS NULL OR m.id = ANY($5))ORDER BY m.created_at ASC, m.id ASCLIMIT $4"#,@@ -194,6 +201,7 @@ impl ChannelMessagesRepo for PgChannelMessagesRepo {cursor_created_at,cursor_id,limit_i64 + 1,+ message_ids_filter as Option<&[Uuid]>,).fetch_all(&self.pool).await?;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 0b1b6e7c3d..86bcb1c1de 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@@ -1,4 +1,4 @@-use crate::domain::models::{MessagePageDirection, ParticipantRole};+use crate::domain::models::{ChannelMessageFilters, MessagePageDirection, ParticipantRole};use crate::domain::ports::ChannelMessagesRepo;use crate::outbound::pg_channels_repo::PgChannelMessagesRepo;use macro_db_migrator::MACRO_DB_MIGRATIONS;@@ -6,6 +6,10 @@ use models_pagination::{CreatedAt, Cursor, CursorVal, Query};use sqlx::{Pool, Postgres};use uuid::Uuid;+const NO_FILTERS: ChannelMessageFilters = ChannelMessageFilters {+ message_ids: Vec::new(),+};+const CH1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c01);const CH2: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c02);const MSG1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000001);@@ -33,6 +37,7 @@ async fn top_level_excludes_thread_replies_and_fully_deleted(&Query::Sort(CreatedAt, ()),MessagePageDirection::Older,50,+ &NO_FILTERS,).await?;let rows = result.rows;@@ -61,6 +66,7 @@ async fn top_level_ordered_newest_first(pool: Pool<Postgres>) -> anyhow::Result<&Query::Sort(CreatedAt, ()),MessagePageDirection::Older,50,+ &NO_FILTERS,).await?;let rows = result.rows;@@ -83,6 +89,7 @@ async fn top_level_cursor_skips_earlier_messages(pool: Pool<Postgres>) -> anyhow&Query::Sort(CreatedAt, ()),MessagePageDirection::Older,50,+ &NO_FILTERS,).await?.rows;@@ -99,7 +106,7 @@ async fn top_level_cursor_skips_earlier_messages(pool: Pool<Postgres>) -> anyhowfilter: (),});let page2 = repo- .get_top_level_messages(CH1, &cursor, MessagePageDirection::Older, 50)+ .get_top_level_messages(CH1, &cursor, MessagePageDirection::Older, 50, &NO_FILTERS).await?.rows;let ids: Vec<Uuid> = page2.iter().map(|r| r.id).collect();@@ -121,6 +128,7 @@ async fn top_level_newer_direction_returns_nearest_newer_page(&Query::Sort(CreatedAt, ()),MessagePageDirection::Older,50,+ &NO_FILTERS,).await?.rows;@@ -136,7 +144,7 @@ async fn top_level_newer_direction_returns_nearest_newer_page(filter: (),});let page = repo- .get_top_level_messages(CH1, &cursor, MessagePageDirection::Newer, 2)+ .get_top_level_messages(CH1, &cursor, MessagePageDirection::Newer, 2, &NO_FILTERS).await?;let ids: Vec<Uuid> = page.rows.iter().map(|r| r.id).collect();@@ -159,6 +167,7 @@ async fn top_level_newer_direction_sets_has_more_newer_with_overfetch(&Query::Sort(CreatedAt, ()),MessagePageDirection::Older,50,+ &NO_FILTERS,).await?.rows;@@ -174,7 +183,7 @@ async fn top_level_newer_direction_sets_has_more_newer_with_overfetch(filter: (),});let page = repo- .get_top_level_messages(CH1, &cursor, MessagePageDirection::Newer, 1)+ .get_top_level_messages(CH1, &cursor, MessagePageDirection::Newer, 1, &NO_FILTERS).await?;let ids: Vec<Uuid> = page.rows.iter().map(|r| r.id).collect();@@ -195,6 +204,7 @@ async fn top_level_limit_is_respected(pool: Pool<Postgres>) -> anyhow::Result<()&Query::Sort(CreatedAt, ()),MessagePageDirection::Older,2,+ &NO_FILTERS,).await?;let rows = result.rows;@@ -218,6 +228,7 @@ async fn top_level_scoped_to_channel(pool: Pool<Postgres>) -> anyhow::Result<()>&Query::Sort(CreatedAt, ()),MessagePageDirection::Older,50,+ &NO_FILTERS,).await?;let rows = result.rows;@@ -227,6 +238,30 @@ async fn top_level_scoped_to_channel(pool: Pool<Postgres>) -> anyhow::Result<()>Ok(())}+#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn top_level_message_ids_filter_limits_to_subset(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ let filters = ChannelMessageFilters {+ message_ids: vec![MSG1, MSG3],+ };+ let result = repo+ .get_top_level_messages(+ CH1,+ &Query::Sort(CreatedAt, ()),+ MessagePageDirection::Older,+ 50,+ &filters,+ )+ .await?;++ let ids: Vec<Uuid> = result.rows.iter().map(|r| r.id).collect();+ assert_eq!(ids, vec![MSG3, MSG1]);+ Ok(())+}+#[sqlx::test(fixtures(path = "../../../fixtures", scripts("channels_repo")),migrator = "MACRO_DB_MIGRATIONS"diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rsindex 0584927808..50535e2f18 100644--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs@@ -65,7 +65,7 @@ use crate::{use channels::inbound::axum_router::{ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelMessage, ApiChannelMessagesPage,ApiChannelParticipant, ApiCountedReaction, ApiMessageAttachment, ApiParticipantRole,- ApiThreadInfo, ApiThreadReply,+ ApiThreadInfo, ApiThreadReply, ChannelMessageFilters,};use document_sub_type::DocumentSubType;use documents_hex::inbound::axum_router::ShortIdResponse;@@ -187,6 +187,7 @@ use utoipa::OpenApi;// channelschannels::inbound::axum_router::get_channel_messages_handler,+ channels::inbound::axum_router::post_channel_messages_handler,channels::inbound::axum_router::get_thread_replies_handler,channels::inbound::axum_router::get_channel_attachments_handler,channels::inbound::axum_router::get_channel_participants_handler,@@ -338,6 +339,7 @@ use utoipa::OpenApi;ApiChannelAttachment,ApiChannelParticipant,ApiParticipantRole,+ ChannelMessageFilters,// Callscall::domain::models::CallTokenResponse,