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/soup threads 2 (#4166)

Sean Aye10c83a0fc694
diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts
index 1a44a48fca..aae507e41c 100644
--- a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts
@@ -576,6 +576,7 @@ export const ListEntities = z.object({
callf: z.any().default(null),
cf: z.any().default(null),
chanf: z.any().default(null),
+ cthf: z.any().default(null),
df: z.any().default(null),
ef: z.any().default(null),
emailPreset: z.union([z.literal('signal'), z.null()]).optional(),
@@ -591,6 +592,7 @@ export const ListEntities = z.object({
z.literal('project'),
z.literal('email'),
z.literal('channel'),
+ z.literal('channel_thread'),
z.literal('call'),
z.literal('foreign_entity'),
];
diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts
index dedbcad5fe..f2fc2fbef9 100644
--- a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts
@@ -250,6 +250,7 @@ export type ItemType =
| 'project'
| 'email'
| 'channel'
+ | 'channel_thread'
| 'call'
| 'foreign_entity';
/**
@@ -1365,6 +1366,12 @@ export interface ListEntities {
chanf?: {
[k: string]: unknown;
};
+ /**
+ * Full soup AST channel thread filter (cthf).
+ */
+ cthf?: {
+ [k: string]: unknown;
+ };
/**
* Full soup AST document filter (df). Use the same shape as /items/soup/ast, e.g. {"l":{"id":"..."}}. For Macro tasks, use {"l":{"dst":"task"}}. For "completed yesterday", AND the task subtype with updatedAt bounds, e.g. {"&":[{"l":{"dst":"task"}},{"&":[{"l":{"ua":{"gte":"<start>"}}},{"l":{"ua":{"lt":"<end>"}}}]}]} using ISO timestamps.
*/
diff --git a/js/app/packages/service-clients/service-search/generated/models/channelThreadFilters.ts b/js/app/packages/service-clients/service-search/generated/models/channelThreadFilters.ts
new file mode 100644
index 0000000000..e260c946b5
--- /dev/null
+++ b/js/app/packages/service-clients/service-search/generated/models/channelThreadFilters.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * search_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The channel thread filters used to filter down channel-thread entities.
+ */
+export interface ChannelThreadFilters {
+ /** Channel IDs containing the thread. Empty to include threads from all accessible channels. */
+ channel_ids?: string[];
+ /** Sender IDs for the root thread message. Empty to include all root senders. */
+ root_sender_ids?: string[];
+ /** Channel thread parent message IDs to include. Empty to include all accessible threads. */
+ thread_ids?: string[];
+}
diff --git a/js/app/packages/service-clients/service-search/generated/models/entityFilters.ts b/js/app/packages/service-clients/service-search/generated/models/entityFilters.ts
index 039ed259cf..a9ef797e9f 100644
--- a/js/app/packages/service-clients/service-search/generated/models/entityFilters.ts
+++ b/js/app/packages/service-clients/service-search/generated/models/entityFilters.ts
@@ -6,6 +6,7 @@
*/
import type { CallFilters } from './callFilters';
import type { ChannelFilters } from './channelFilters';
+import type { ChannelThreadFilters } from './channelThreadFilters';
import type { ChatFilters } from './chatFilters';
import type { CrmCompanyFilters } from './crmCompanyFilters';
import type { DocumentFilters } from './documentFilters';
@@ -22,6 +23,8 @@ export interface EntityFilters {
call_filters?: CallFilters;
/** the bundled [ChannelFilters] */
channel_filters?: ChannelFilters;
+ /** the bundled [ChannelThreadFilters] */
+ channel_thread_filters?: ChannelThreadFilters;
/** the bundled [ChatFilters] */
chat_filters?: ChatFilters;
/** the bundled [CrmCompanyFilters] */
diff --git a/js/app/packages/service-clients/service-search/generated/models/index.ts b/js/app/packages/service-clients/service-search/generated/models/index.ts
index b0d1b3b03e..1759ce85f6 100644
--- a/js/app/packages/service-clients/service-search/generated/models/index.ts
+++ b/js/app/packages/service-clients/service-search/generated/models/index.ts
@@ -52,6 +52,7 @@ export * from './channelSearchResultSenderId';
export * from './channelSearchResultThreadId';
export * from './channelSearchResultUpdatedAt';
export * from './channelSortTimestamp';
+export * from './channelThreadFilters';
export * from './chatFilters';
export * from './chatFiltersImportance';
export * from './chatMessageSearchResult';
diff --git a/js/app/packages/service-clients/service-search/openapi.json b/js/app/packages/service-clients/service-search/openapi.json
index dd325162e3..3e5f84aeb0 100644
--- a/js/app/packages/service-clients/service-search/openapi.json
+++ b/js/app/packages/service-clients/service-search/openapi.json
@@ -623,6 +623,33 @@
"description": "Sort key for channel content search results.",
"enum": ["message", "thread"]
},
+ "ChannelThreadFilters": {
+ "type": "object",
+ "description": "The channel thread filters used to filter down channel-thread entities.",
+ "properties": {
+ "channel_ids": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Channel IDs containing the thread. Empty to include threads from all accessible channels."
+ },
+ "root_sender_ids": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Sender IDs for the root thread message. Empty to include all root senders."
+ },
+ "thread_ids": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Channel thread parent message IDs to include. Empty to include all accessible threads."
+ }
+ }
+ },
"ChatFilters": {
"type": "object",
"description": "The chat filters used to filter down what chats you search over.",
@@ -1573,6 +1600,10 @@
"$ref": "#/components/schemas/ChannelFilters",
"description": "the bundled [ChannelFilters]"
},
+ "channel_thread_filters": {
+ "$ref": "#/components/schemas/ChannelThreadFilters",
+ "description": "the bundled [ChannelThreadFilters]"
+ },
"chat_filters": {
"$ref": "#/components/schemas/ChatFilters",
"description": "the bundled [ChatFilters]"
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiEntityFilterAst.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiEntityFilterAst.ts
index 72dcd68acc..4c54302182 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/apiEntityFilterAst.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiEntityFilterAst.ts
@@ -18,6 +18,8 @@ Empty/omitted = team's full visible list. */
cf?: unknown;
/** the filters that should be applied to the channel entity */
chanf?: unknown;
+ /** the filters that should be applied to the channel-thread entity */
+ cthf?: unknown;
/** the filters that should be applied to the document entity */
df?: unknown;
/** CRM-scoped address filter (wire key: `eca`). Symmetric counterpart
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/channelThreadFilters.ts b/js/app/packages/service-clients/service-storage/generated/schemas/channelThreadFilters.ts
new file mode 100644
index 0000000000..96f61dd53c
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/channelThreadFilters.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The channel thread filters used to filter down channel-thread entities.
+ */
+export interface ChannelThreadFilters {
+ /** Channel IDs containing the thread. Empty to include threads from all accessible channels. */
+ channel_ids?: string[];
+ /** Sender IDs for the root thread message. Empty to include all root senders. */
+ root_sender_ids?: string[];
+ /** Channel thread parent message IDs to include. Empty to include all accessible threads. */
+ thread_ids?: string[];
+}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/entityFilters.ts b/js/app/packages/service-clients/service-storage/generated/schemas/entityFilters.ts
index 2a16fc0307..fb9942f7cf 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/entityFilters.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/entityFilters.ts
@@ -6,6 +6,7 @@
*/
import type { CallFilters } from './callFilters';
import type { ChannelFilters } from './channelFilters';
+import type { ChannelThreadFilters } from './channelThreadFilters';
import type { ChatFilters } from './chatFilters';
import type { CrmCompanyFilters } from './crmCompanyFilters';
import type { DocumentFilters } from './documentFilters';
@@ -22,6 +23,8 @@ export interface EntityFilters {
call_filters?: CallFilters;
/** the bundled [ChannelFilters] */
channel_filters?: ChannelFilters;
+ /** the bundled [ChannelThreadFilters] */
+ channel_thread_filters?: ChannelThreadFilters;
/** the bundled [ChatFilters] */
chat_filters?: ChatFilters;
/** the bundled [CrmCompanyFilters] */
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.ts
index 4d18f0a426..cc75670d2c 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
@@ -203,6 +203,7 @@ export * from './channelPreviewOneOfSevenAllOf';
export * from './channelPreviewOneOfSevenAllOfType';
export * from './channelSharePermission';
export * from './channelTeamId';
+export * from './channelThreadFilters';
export * from './channelType';
export * from './channelWebhookRequest';
export * from './channelWebhookResponse';
diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.ts
index b5d1927702..445a00202f 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -8074,6 +8074,31 @@ export const postItemsSoupBody = zod
.describe(
'The channel message filters used to filter down what channel messages you search over.'
),
+ channel_thread_filters: zod
+ .object({
+ channel_ids: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'Channel IDs containing the thread. Empty to include threads from all accessible channels.'
+ ),
+ root_sender_ids: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'Sender IDs for the root thread message. Empty to include all root senders.'
+ ),
+ thread_ids: zod
+ .array(zod.string())
+ .optional()
+ .describe(
+ 'Channel thread parent message IDs to include. Empty to include all accessible threads.'
+ ),
+ })
+ .optional()
+ .describe(
+ 'The channel thread filters used to filter down channel-thread entities.'
+ ),
chat_filters: zod
.object({
chat_ids: zod
@@ -10222,6 +10247,12 @@ export const postItemsSoupAstBody = zod
.unknown()
.optional()
.describe('the filters that should be applied to the channel entity'),
+ cthf: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'the filters that should be applied to the channel-thread entity'
+ ),
df: zod
.unknown()
.optional()
@@ -12028,6 +12059,12 @@ export const postItemsSoupAstGroupedBody = zod
.unknown()
.optional()
.describe('the filters that should be applied to the channel entity'),
+ cthf: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'the filters that should be applied to the channel-thread entity'
+ ),
df: zod
.unknown()
.optional()
@@ -12174,6 +12211,12 @@ export const postItemsSoupAstGroupedBody = zod
.unknown()
.optional()
.describe('the filters that should be applied to the channel entity'),
+ cthf: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'the filters that should be applied to the channel-thread entity'
+ ),
df: zod
.unknown()
.optional()
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index ad2c5d8c73..3b07e84e9d 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -9760,6 +9760,9 @@
"chanf": {
"description": "the filters that should be applied to the channel entity"
},
+ "cthf": {
+ "description": "the filters that should be applied to the channel-thread entity"
+ },
"df": {
"description": "the filters that should be applied to the document entity"
},
@@ -11120,6 +11123,33 @@
}
}
},
+ "ChannelThreadFilters": {
+ "type": "object",
+ "description": "The channel thread filters used to filter down channel-thread entities.",
+ "properties": {
+ "channel_ids": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Channel IDs containing the thread. Empty to include threads from all accessible channels."
+ },
+ "root_sender_ids": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Sender IDs for the root thread message. Empty to include all root senders."
+ },
+ "thread_ids": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Channel thread parent message IDs to include. Empty to include all accessible threads."
+ }
+ }
+ },
"ChannelType": {
"type": "string",
"description": "Type of channel.",
@@ -13450,6 +13480,10 @@
"$ref": "#/components/schemas/ChannelFilters",
"description": "the bundled [ChannelFilters]"
},
+ "channel_thread_filters": {
+ "$ref": "#/components/schemas/ChannelThreadFilters",
+ "description": "the bundled [ChannelThreadFilters]"
+ },
"chat_filters": {
"$ref": "#/components/schemas/ChatFilters",
"description": "the bundled [ChatFilters]"
diff --git a/rust/cloud-storage/.sqlx/query-45064c055927af781bc06e3a602a9efbefbd111110b9f0fab5cf029e70208c1e.json b/rust/cloud-storage/.sqlx/query-45064c055927af781bc06e3a602a9efbefbd111110b9f0fab5cf029e70208c1e.json
deleted file mode 100644
index 8e34d4b90f..0000000000
--- a/rust/cloud-storage/.sqlx/query-45064c055927af781bc06e3a602a9efbefbd111110b9f0fab5cf029e70208c1e.json
+++ /dev/null
@@ -1,82 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH user_channels AS (\n SELECT DISTINCT c.*\n FROM comms_channels c\n INNER JOIN comms_channel_participants cp ON cp.channel_id = c.id\n WHERE cp.user_id = $1 AND cp.left_at IS NULL\n ),\n channel_participants_json AS (\n SELECT \n uc.id as channel_id,\n ARRAY_AGG(\n json_build_object(\n 'channel_id', cp.channel_id,\n 'user_id', cp.user_id,\n 'role', cp.role,\n 'joined_at', cp.joined_at,\n 'left_at', cp.left_at\n )\n ) as participants\n FROM user_channels uc\n JOIN comms_channel_participants cp ON cp.channel_id = uc.id\n WHERE cp.left_at IS NULL\n GROUP BY uc.id\n )\n SELECT \n uc.id as \"id!\",\n uc.name as \"name\",\n uc.channel_type as \"channel_type!: ChannelType\",\n uc.team_id,\n uc.org_id,\n uc.created_at as \"created_at!\",\n uc.updated_at as \"updated_at!\",\n uc.owner_id as \"owner_id!\",\n cpj.participants as \"participants_json?\"\n FROM user_channels uc\n LEFT JOIN channel_participants_json cpj ON cpj.channel_id = uc.id\n ORDER BY uc.created_at DESC\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id!",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "name",
- "type_info": "Varchar"
- },
- {
- "ordinal": 2,
- "name": "channel_type!: ChannelType",
- "type_info": {
- "Custom": {
- "name": "comms_channel_type",
- "kind": {
- "Enum": [
- "public",
- "private",
- "direct_message",
- "team"
- ]
- }
- }
- }
- },
- {
- "ordinal": 3,
- "name": "team_id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 4,
- "name": "org_id",
- "type_info": "Int8"
- },
- {
- "ordinal": 5,
- "name": "created_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 6,
- "name": "updated_at!",
- "type_info": "Timestamptz"
- },
- {
- "ordinal": 7,
- "name": "owner_id!",
- "type_info": "Text"
- },
- {
- "ordinal": 8,
- "name": "participants_json?",
- "type_info": "JsonArray"
- }
- ],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": [
- false,
- true,
- false,
- true,
- true,
- false,
- false,
- false,
- null
- ]
- },
- "hash": "45064c055927af781bc06e3a602a9efbefbd111110b9f0fab5cf029e70208c1e"
-}
diff --git a/rust/cloud-storage/.sqlx/query-9afc6f436aedd226ed0d6bf85de64c5ff57853c93ff00f768b49bf79f198590b.json b/rust/cloud-storage/.sqlx/query-9afc6f436aedd226ed0d6bf85de64c5ff57853c93ff00f768b49bf79f198590b.json
deleted file mode 100644
index 154f82bfc7..0000000000
--- a/rust/cloud-storage/.sqlx/query-9afc6f436aedd226ed0d6bf85de64c5ff57853c93ff00f768b49bf79f198590b.json
+++ /dev/null
@@ -1,58 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT \n a.id as \"id!: Uuid\",\n a.user_id as \"user_id!: String\",\n a.channel_id as \"channel_id!: Uuid\",\n a.viewed_at as \"viewed_at?: DateTime<Utc>\",\n a.interacted_at as \"interacted_at?: DateTime<Utc>\",\n a.created_at as \"created_at!: DateTime<Utc>\",\n a.updated_at as \"updated_at!: DateTime<Utc>\"\n FROM comms_activity a\n WHERE a.user_id = $1\n ORDER BY \n GREATEST(\n COALESCE(a.viewed_at, '1970-01-01'::timestamp),\n COALESCE(a.interacted_at, '1970-01-01'::timestamp)\n ) DESC,\n a.created_at DESC\n LIMIT 100\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id!: Uuid",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "user_id!: String",
- "type_info": "Text"
- },
- {
- "ordinal": 2,
- "name": "channel_id!: Uuid",
- "type_info": "Uuid"
- },
- {
- "ordinal": 3,
- "name": "viewed_at?: DateTime<Utc>",
- "type_info": "Timestamp"
- },
- {
- "ordinal": 4,
- "name": "interacted_at?: DateTime<Utc>",
- "type_info": "Timestamp"
- },
- {
- "ordinal": 5,
- "name": "created_at!: DateTime<Utc>",
- "type_info": "Timestamp"
- },
- {
- "ordinal": 6,
- "name": "updated_at!: DateTime<Utc>",
- "type_info": "Timestamp"
- }
- ],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": [
- false,
- false,
- false,
- true,
- true,
- false,
- false
- ]
- },
- "hash": "9afc6f436aedd226ed0d6bf85de64c5ff57853c93ff00f768b49bf79f198590b"
-}
diff --git a/rust/cloud-storage/channels/src/domain/list_service.rs b/rust/cloud-storage/channels/src/domain/list_service.rs
index 442522a2df..da5df22504 100644
--- a/rust/cloud-storage/channels/src/domain/list_service.rs
+++ b/rust/cloud-storage/channels/src/domain/list_service.rs
@@ -9,8 +9,8 @@ use uuid::Uuid;
use crate::domain::{
models::{
- Activity, ChannelType, ChannelWithLatest, GetChannelsRequest, NameLookup, UserName,
- fallback_user_name,
+ Activity, ChannelThreadReplyRows, ChannelType, ChannelWithLatest, GetChannelsRequest,
+ GetThreadReplyRowsRequest, NameLookup, UserName, fallback_user_name,
},
ports::{ChannelListRepo, ChannelListService, ChannelListUserRepo},
};
@@ -150,6 +150,13 @@ where
self.channels.get_channel_list_activities(user)
}
+ fn get_thread_reply_rows(
+ &self,
+ req: GetThreadReplyRowsRequest,
+ ) -> impl Future<Output = Result<Vec<ChannelThreadReplyRows>, rootcause::Report>> + Send {
+ self.channels.get_thread_reply_rows(req.into_params())
+ }
+
fn get_names(
&self,
names: std::collections::HashSet<MacroUserIdStr<'_>>,
diff --git a/rust/cloud-storage/channels/src/domain/models.rs b/rust/cloud-storage/channels/src/domain/models.rs
index 57a1b1a728..fb537fb2b4 100644
--- a/rust/cloud-storage/channels/src/domain/models.rs
+++ b/rust/cloud-storage/channels/src/domain/models.rs
@@ -1,6 +1,9 @@
use chrono::{DateTime, Utc};
#[cfg(feature = "list")]
-use item_filters::ast::{LiteralTree, channel::ChannelLiteral};
+use item_filters::ast::{
+ LiteralTree,
+ channel::{ChannelLiteral, ChannelThreadLiteral},
+};
use macro_user_id::{email::ReadEmailParts, user_id::MacroUserIdStr};
use models_pagination::{CreatedAt, CursorVal, Identify, SortOn};
#[cfg(feature = "list")]
@@ -1192,6 +1195,67 @@ pub struct GetChannelsParams {
query: Query<Uuid, SimpleSortMethod, LiteralTree<ChannelLiteral>>,
}
+/// Channel thread reply rows request.
+#[cfg(feature = "list")]
+#[derive(Debug)]
+pub struct GetThreadReplyRowsRequest {
+ /// Requesting user id.
+ pub macro_id: MacroUserIdStr<'static>,
+ /// Optional result limit.
+ pub limit: Option<u32>,
+ /// Cursor, sort, and channel-thread-level filter.
+ pub query: Query<Uuid, SimpleSortMethod, LiteralTree<ChannelThreadLiteral>>,
+}
+
+#[cfg(feature = "list")]
+impl GetThreadReplyRowsRequest {
+ /// Convert into repository params.
+ pub fn into_params(self) -> GetThreadReplyRowsParams {
+ GetThreadReplyRowsParams {
+ macro_id: self.macro_id,
+ limit: self.limit,
+ query: self.query,
+ }
+ }
+}
+
+/// Channel thread reply rows repository parameters.
+#[cfg(feature = "list")]
+#[derive(Debug)]
+pub struct GetThreadReplyRowsParams {
+ macro_id: MacroUserIdStr<'static>,
+ limit: Option<u32>,
+ query: Query<Uuid, SimpleSortMethod, LiteralTree<ChannelThreadLiteral>>,
+}
+
+#[cfg(feature = "list")]
+impl GetThreadReplyRowsParams {
+ /// Requesting user id.
+ pub fn user(&self) -> &MacroUserIdStr<'static> {
+ &self.macro_id
+ }
+
+ /// Optional result limit.
+ pub fn limit(&self) -> Option<u32> {
+ self.limit
+ }
+
+ /// Cursor, sort, and channel-thread-level filter.
+ pub fn query(&self) -> &Query<Uuid, SimpleSortMethod, LiteralTree<ChannelThreadLiteral>> {
+ &self.query
+ }
+}
+
+/// A top-level channel message plus all reply rows for Soup thread rendering.
+#[cfg(feature = "list")]
+#[derive(Debug, Clone)]
+pub struct ChannelThreadReplyRows {
+ /// Top-level parent message for the thread.
+ pub parent: TopLevelMessageRow,
+ /// Non-deleted replies in oldest-first order.
+ pub replies: Vec<ThreadReplyRow>,
+}
+
#[cfg(feature = "list")]
impl GetChannelsParams {
/// Requesting user id.
diff --git a/rust/cloud-storage/channels/src/domain/ports.rs b/rust/cloud-storage/channels/src/domain/ports.rs
index a884aec158..5215934c91 100644
--- a/rust/cloud-storage/channels/src/domain/ports.rs
+++ b/rust/cloud-storage/channels/src/domain/ports.rs
@@ -15,8 +15,9 @@ use crate::domain::models::{
};
#[cfg(feature = "list")]
use crate::domain::models::{
- ChannelWithLatest, ChannelWithParticipants, GetChannelsParams, GetChannelsRequest,
- LatestMessage, UserName,
+ ChannelThreadReplyRows, ChannelWithLatest, ChannelWithParticipants, GetChannelsParams,
+ GetChannelsRequest, GetThreadReplyRowsParams, GetThreadReplyRowsRequest, LatestMessage,
+ UserName,
};
use crate::domain::side_effects::{
ChannelDocumentMention, ChannelNotificationEffect, ChannelRealtimeEffect,
@@ -48,6 +49,12 @@ pub trait ChannelListRepo: Send + Sync + 'static {
&self,
user_id: MacroUserIdStr<'_>,
) -> impl Future<Output = Result<Vec<Activity>, rootcause::Report>> + Send;
+
+ /// Fetch top-level channel message rows and their reply rows for Soup thread rendering.
+ fn get_thread_reply_rows(
+ &self,
+ req: GetThreadReplyRowsParams,
+ ) -> impl Future<Output = Result<Vec<ChannelThreadReplyRows>, rootcause::Report>> + Send;
}
/// Repository for user display names needed by channel list rendering.
@@ -75,6 +82,12 @@ pub trait ChannelListService: Send + Sync + 'static {
user: MacroUserIdStr<'_>,
) -> impl Future<Output = Result<Vec<Activity>, rootcause::Report>> + Send;
+ /// Fetch top-level channel message rows and their reply rows for Soup thread rendering.
+ fn get_thread_reply_rows(
+ &self,
+ req: GetThreadReplyRowsRequest,
+ ) -> impl Future<Output = Result<Vec<ChannelThreadReplyRows>, rootcause::Report>> + Send;
+
/// Fetch names for user ids.
fn get_names(
&self,
@@ -544,7 +557,19 @@ pub trait ChannelService: Send + Sync + 'static {
limit: u16,
) -> impl Future<Output = Result<ChannelMessagesQueryResult, ChannelMessagesErr>> + Send;
- /// Fetch all replies for the thread identified by `message_id`.
+ /// Fetch raw reply rows 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_reply_rows(
+ &self,
+ channel_id: Uuid,
+ message_id: Uuid,
+ ) -> impl Future<Output = Result<Vec<ThreadReplyRow>, ChannelMessagesErr>> + Send {
+ let _ = channel_id;
+ async move { Err(ChannelMessagesErr::MessageNotFound(message_id)) }
+ }
+
+ /// Fetch all enriched 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(
diff --git a/rust/cloud-storage/channels/src/domain/service.rs b/rust/cloud-storage/channels/src/domain/service.rs
index 8019f6e24b..a1bd2f5cf0 100644
--- a/rust/cloud-storage/channels/src/domain/service.rs
+++ b/rust/cloud-storage/channels/src/domain/service.rs
@@ -10,7 +10,7 @@ use crate::domain::{
PatchChannelRequest, PatchMessageRequest, PostMessageRequest, PostMessageResponse,
PostReactionRequest, PostTypingRequest, ReactionAction, ReferencedShareItem,
RemoveParticipantsRequest, ResolvedChannelMessage, Sender, SimpleMention, ThreadInfo,
- ThreadReply, TopLevelMessageRow, WithChannelId,
+ ThreadReply, ThreadReplyRow, TopLevelMessageRow, WithChannelId,
},
ports::{
ChannelAttachmentsPage, ChannelEventDispatcher, ChannelMessagesErr,
@@ -175,6 +175,42 @@ where
Ok(messages)
}
+ /// Hydrate thread reply rows with reactions, attachments, and bot profiles.
+ async fn hydrate_thread_replies(
+ &self,
+ reply_rows: Vec<ThreadReplyRow>,
+ ) -> Result<Vec<ThreadReply>, ChannelMessagesErr> {
+ 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, bot_profiles) = tokio::join!(
+ self.repo.get_reactions_batch(&reply_ids),
+ self.repo.get_attachments_batch(&reply_ids),
+ self.get_bot_profiles_for_senders(reply_rows.iter().map(|row| row.sender_id.as_str())),
+ );
+
+ let reactions = reactions.map_err(anyhow::Error::from)?;
+ let attachments = attachments.map_err(anyhow::Error::from)?;
+ let bot_profiles = bot_profiles?;
+
+ Ok(reply_rows
+ .into_iter()
+ .map(|row| ThreadReply {
+ id: row.id,
+ bot_profile: bot_profile_for(&bot_profiles, &row.sender_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())
+ }
+
/// Batch-fetch public bot profiles for any bot senders among `sender_ids`.
async fn get_bot_profiles_for_senders(
&self,
@@ -1464,11 +1500,11 @@ where
}
#[tracing::instrument(err, skip(self))]
- async fn get_thread_replies(
+ async fn get_thread_reply_rows(
&self,
channel_id: Uuid,
message_id: Uuid,
- ) -> Result<Vec<ThreadReply>, ChannelMessagesErr> {
+ ) -> Result<Vec<ThreadReplyRow>, ChannelMessagesErr> {
let parent = self
.repo
.resolve_top_level_parent(channel_id, message_id)
@@ -1476,43 +1512,21 @@ where
.map_err(anyhow::Error::from)?
.ok_or(ChannelMessagesErr::MessageNotFound(message_id))?;
- let reply_rows = self
- .repo
+ 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, bot_profiles) = tokio::join!(
- self.repo.get_reactions_batch(&reply_ids),
- self.repo.get_attachments_batch(&reply_ids),
- self.get_bot_profiles_for_senders(reply_rows.iter().map(|row| row.sender_id.as_str())),
- );
-
- let reactions = reactions.map_err(anyhow::Error::from)?;
- let attachments = attachments.map_err(anyhow::Error::from)?;
- let bot_profiles = bot_profiles?;
-
- let replies = reply_rows
- .into_iter()
- .map(|row| ThreadReply {
- id: row.id,
- bot_profile: bot_profile_for(&bot_profiles, &row.sender_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();
+ .map_err(anyhow::Error::from)
+ .map_err(ChannelMessagesErr::Repo)
+ }
- Ok(replies)
+ #[tracing::instrument(err, skip(self))]
+ async fn get_thread_replies(
+ &self,
+ channel_id: Uuid,
+ message_id: Uuid,
+ ) -> Result<Vec<ThreadReply>, ChannelMessagesErr> {
+ let reply_rows = self.get_thread_reply_rows(channel_id, message_id).await?;
+ self.hydrate_thread_replies(reply_rows).await
}
#[tracing::instrument(err, skip(self))]
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 f7883ab08a..9550874c34 100644
--- a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs
+++ b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs
@@ -11,12 +11,13 @@ use crate::domain::{
AttachmentGenericReference, BotId, BotSenderProfile, ChannelAttachment,
ChannelAttachmentType, ChannelContextMessage, ChannelInfo, ChannelListItem,
ChannelMessageFilters, ChannelMessageKind, ChannelMetadata, ChannelParticipant,
- ChannelPreviewRow, ChannelType, ChannelWithParticipants, CountedReaction,
- CreateChannelRequest, CreateEntityMentionOptions, EntityMention, GetChannelsParams,
- LatestMessage, MessageAttachment, MessagePageDirection, MutatedAttachment, MutatedMessage,
- NameLookup, NewChannelAttachment, ParticipantRole, PatchChannelRequest,
- RecentChannelMessage, ResolvedChannelMessage, Sender, SimpleMention, ThreadData,
- ThreadReplyRow, TopLevelMessageRow, UserName, fallback_user_name,
+ ChannelPreviewRow, ChannelThreadReplyRows, ChannelType, ChannelWithParticipants,
+ CountedReaction, CreateChannelRequest, CreateEntityMentionOptions, EntityMention,
+ GetChannelsParams, GetThreadReplyRowsParams, LatestMessage, MessageAttachment,
+ MessagePageDirection, MutatedAttachment, MutatedMessage, NameLookup, NewChannelAttachment,
+ ParticipantRole, PatchChannelRequest, RecentChannelMessage, ResolvedChannelMessage, Sender,
+ SimpleMention, ThreadData, ThreadReplyRow, TopLevelMessageRow, UserName,
+ fallback_user_name,
},
ports::{ChannelRepo, TopLevelMessagesQueryResult},
};
@@ -25,7 +26,10 @@ use chrono::{DateTime, Utc};
#[cfg(feature = "list")]
use filter_ast::Expr;
#[cfg(feature = "list")]
-use item_filters::ast::{LiteralTree, channel::ChannelLiteral};
+use item_filters::ast::{
+ LiteralTree,
+ channel::{ChannelLiteral, ChannelThreadLiteral},
+};
use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use models_pagination::{CreatedAt, Query};
#[cfg(feature = "list")]
@@ -784,6 +788,126 @@ fn build_channel_list_query(
builder
}
+#[cfg(feature = "list")]
+fn push_channel_thread_sort_expr(
+ builder: &mut QueryBuilder<'static, Postgres>,
+ sort_method_str: String,
+) {
+ builder.push("(CASE ");
+ builder.push_bind(sort_method_str);
+ builder.push(
+ " WHEN 'created_at' THEN m.created_at ELSE GREATEST(m.updated_at, COALESCE(thread_stats.latest_reply_updated_at, m.updated_at)) END)",
+ );
+}
+
+#[cfg(feature = "list")]
+fn push_channel_thread_filter_expr(
+ builder: &mut QueryBuilder<'static, Postgres>,
+ expr: &Expr<ChannelThreadLiteral>,
+) {
+ match expr {
+ Expr::And(a, b) => {
+ builder.push("(");
+ push_channel_thread_filter_expr(builder, a);
+ builder.push(" AND ");
+ push_channel_thread_filter_expr(builder, b);
+ builder.push(")");
+ }
+ Expr::Or(a, b) => {
+ builder.push("(");
+ push_channel_thread_filter_expr(builder, a);
+ builder.push(" OR ");
+ push_channel_thread_filter_expr(builder, b);
+ builder.push(")");
+ }
+ Expr::Not(a) => {
+ builder.push("(NOT ");
+ push_channel_thread_filter_expr(builder, a);
+ builder.push(")");
+ }
+ Expr::Literal(ChannelThreadLiteral::ThreadId(id)) => {
+ builder.push("m.id = ");
+ builder.push_bind(*id);
+ }
+ Expr::Literal(ChannelThreadLiteral::ChannelId(channel_id)) => {
+ builder.push("c.id = ");
+ builder.push_bind(*channel_id);
+ }
+ Expr::Literal(ChannelThreadLiteral::RootSender(sender)) => {
+ builder.push("m.sender_id = ");
+ builder.push_bind(sender.as_ref().to_string());
+ }
+ }
+}
+
+#[cfg(feature = "list")]
+fn build_channel_thread_rows_query(
+ params: &GetThreadReplyRowsParams,
+) -> QueryBuilder<'static, Postgres> {
+ // Dynamic QueryBuilder is required because the channel-thread filter is an AST with
+ // arbitrary AND/OR/NOT shape. All runtime values are still passed as bind parameters.
+ let cursor = params.query();
+ let sort_method_str = cursor.sort_method().to_string();
+ let query_limit = params.limit().map(i64::from);
+ let (cursor_id, cursor_timestamp) = cursor.vals();
+ let cursor_id_str = cursor_id.map(|id| id.to_string());
+ let cursor_timestamp = cursor_timestamp.cloned();
+
+ let mut builder = QueryBuilder::new(
+ r#"
+ WITH user_channels AS (
+ SELECT DISTINCT c.*
+ FROM comms_channels c
+ INNER JOIN comms_channel_participants cp ON cp.channel_id = c.id
+ WHERE cp.user_id = "#,
+ );
+ builder.push_bind(params.user().as_ref().to_string());
+ builder.push(
+ r#" AND cp.left_at IS NULL
+ )
+ SELECT
+ m.id AS id,
+ m.channel_id AS channel_id,
+ m.sender_id AS sender_id,
+ m.content AS content,
+ m.created_at AS created_at,
+ m.updated_at AS updated_at,
+ m.edited_at::timestamptz AS edited_at,
+ m.deleted_at::timestamptz AS deleted_at
+ FROM comms_messages m
+ INNER JOIN user_channels c ON c.id = m.channel_id
+ LEFT JOIN LATERAL (
+ SELECT MAX(reply.updated_at) AS latest_reply_updated_at
+ FROM comms_messages reply
+ WHERE reply.thread_id = m.id
+ AND reply.deleted_at IS NULL
+ ) thread_stats ON TRUE
+ WHERE m.thread_id IS NULL
+ AND m.deleted_at IS NULL
+ "#,
+ );
+
+ if let Some(expr) = cursor.filter().as_deref() {
+ builder.push(" AND ");
+ push_channel_thread_filter_expr(&mut builder, expr);
+ }
+
+ builder.push(" AND (");
+ builder.push_bind(cursor_timestamp);
+ builder.push("::timestamptz IS NULL OR (");
+ push_channel_thread_sort_expr(&mut builder, sort_method_str.clone());
+ builder.push(", m.id::text) < (");
+ builder.push_bind(cursor_timestamp);
+ builder.push(", ");
+ builder.push_bind(cursor_id_str);
+ builder.push(")) ORDER BY ");
+ push_channel_thread_sort_expr(&mut builder, sort_method_str);
+ builder.push(" DESC, m.id::text DESC LIMIT ");
+ builder.push_bind(query_limit);
+
+ builder
+}
+
#[cfg(feature = "list")]
struct ChannelListRow {
id: Uuid,
@@ -1060,6 +1184,84 @@ impl ChannelListRepo for PgChannelsRepo {
.fetch_all(&self.pool)
.await?)
}
+
+ async fn get_thread_reply_rows(
+ &self,
+ params: GetThreadReplyRowsParams,
+ ) -> Result<Vec<ChannelThreadReplyRows>, rootcause::Report> {
+ let parents: Vec<TopLevelMessageRow> = build_channel_thread_rows_query(&params)
+ .build()
+ .try_map(|row: PgRow| {
+ Ok(TopLevelMessageRow {
+ id: row.try_get("id")?,
+ channel_id: row.try_get("channel_id")?,
+ sender_id: row.try_get("sender_id")?,
+ content: row.try_get("content")?,
+ created_at: row.try_get("created_at")?,
+ updated_at: row.try_get("updated_at")?,
+ edited_at: row.try_get("edited_at")?,
+ deleted_at: row.try_get("deleted_at")?,
+ })
+ })
+ .fetch_all(&self.pool)
+ .await?;
+
+ let parent_ids: Vec<Uuid> = parents.iter().map(|parent| parent.id).collect();
+ if parent_ids.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ // QueryBuilder keeps this batch fetch independent from SQLx's offline macro cache;
+ // all parent ids are still passed as a single bind parameter.
+ let mut reply_query = QueryBuilder::new(
+ r#"
+ SELECT
+ id,
+ thread_id,
+ sender_id,
+ content,
+ created_at,
+ updated_at,
+ edited_at::timestamptz AS edited_at
+ FROM comms_messages
+ WHERE thread_id = ANY("#,
+ );
+ reply_query.push_bind(parent_ids.clone());
+ reply_query.push(
+ r#")
+ AND deleted_at IS NULL
+ ORDER BY thread_id ASC, created_at ASC, id ASC
+ "#,
+ );
+ let reply_rows = reply_query
+ .build_query_as::<ThreadReplyOnlyRow>()
+ .fetch_all(&self.pool)
+ .await?;
+
+ let mut replies_by_parent: HashMap<Uuid, Vec<ThreadReplyRow>> = HashMap::new();
+ for row in reply_rows {
+ replies_by_parent
+ .entry(row.thread_id)
+ .or_default()
+ .push(ThreadReplyRow {
+ id: row.id,
+ thread_id: row.thread_id,
+ sender_id: row.sender_id,
+ content: row.content,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ edited_at: row.edited_at,
+ });
+ }
+
+ Ok(parents
+ .into_iter()
+ .map(|parent| {
+ let replies = replies_by_parent.remove(&parent.id).unwrap_or_default();
+ ChannelThreadReplyRows { parent, replies }
+ })
+ .collect())
+ }
}
#[cfg(feature = "list")]
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 a8818cde8c..61df8ace37 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,13 +1,17 @@
use crate::domain::models::{
AttachmentEntityReference, BotId, BotSenderProfile, ChannelMessageFilters,
- CreateEntityMentionOptions, MessagePageDirection, NotificationFilters, ParticipantRole,
+ CreateEntityMentionOptions, GetThreadReplyRowsRequest, MessagePageDirection,
+ NotificationFilters, ParticipantRole,
};
-use crate::domain::ports::ChannelRepo;
+use crate::domain::ports::{ChannelListRepo, ChannelRepo};
use crate::outbound::pg_channels_repo::PgChannelsRepo;
+use filter_ast::Expr;
+use item_filters::ast::{LiteralTree, channel::ChannelThreadLiteral};
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use macro_user_id::user_id::MacroUserIdStr;
-use models_pagination::{CreatedAt, Cursor, CursorVal, Query};
+use models_pagination::{CreatedAt, Cursor, CursorVal, Query, SimpleSortMethod};
use sqlx::{Pool, Postgres};
+use std::sync::Arc;
use uuid::Uuid;
const NO_FILTERS: ChannelMessageFilters = ChannelMessageFilters {
@@ -27,9 +31,11 @@ const CH2: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c02);
const MSG1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000001);
const MSG2: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000002);
const MSG3: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000003);
+const MSG31: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000031);
const REPLY1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_00000000b001);
const REPLY2: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_00000000b002);
const REPLY3: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_00000000b003);
+const REPLY4: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_00000000b004);
const REPLY5: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_00000000b005);
const DELETED_MSG_ATTACHMENT: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_00000000a004);
const USER_A: &str = "macro|[email protected]";
@@ -45,6 +51,27 @@ fn macro_user_id(user_id: &str) -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from(user_id.to_owned()).expect("valid macro user id")
}
+fn thread_rows_request(
+ user_id: &str,
+ filter: LiteralTree<ChannelThreadLiteral>,
+ sort: SimpleSortMethod,
+ limit: u32,
+) -> GetThreadReplyRowsRequest {
+ GetThreadReplyRowsRequest {
+ macro_id: macro_user_id(user_id),
+ limit: Some(limit),
+ query: Query::Sort(sort, filter),
+ }
+}
+
+fn thread_filter(literal: ChannelThreadLiteral) -> LiteralTree<ChannelThreadLiteral> {
+ Some(Arc::new(Expr::val(literal)))
+}
+
+fn report_err(e: rootcause::Report) -> anyhow::Error {
+ anyhow::anyhow!("{e:?}")
+}
+
async fn insert_channel_message_notification(
pool: &Pool<Postgres>,
user_id: &str,
@@ -157,6 +184,176 @@ async fn top_level_ordered_newest_first(pool: Pool<Postgres>) -> anyhow::Result<
Ok(())
}
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("channels_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn channel_thread_rows_are_visible_to_channel_members(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = repo(pool);
+ let rows = repo
+ .get_thread_reply_rows(
+ thread_rows_request(USER_A, None, SimpleSortMethod::UpdatedAt, 50).into_params(),
+ )
+ .await
+ .map_err(report_err)?;
+
+ let parent_ids = rows.iter().map(|row| row.parent.id).collect::<Vec<_>>();
+ assert_eq!(parent_ids, vec![MSG3, MSG1, MSG31]);
+
+ let msg1 = rows
+ .iter()
+ .find(|row| row.parent.id == MSG1)
+ .expect("msg1 thread should be returned");
+ let reply_ids = msg1
+ .replies
+ .iter()
+ .map(|reply| reply.id)
+ .collect::<Vec<_>>();
+ assert_eq!(reply_ids, vec![REPLY1, REPLY2, REPLY3, REPLY4]);
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("channels_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn channel_thread_rows_are_scoped_to_active_channel_members(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = repo(pool);
+ let rows = repo
+ .get_thread_reply_rows(
+ thread_rows_request(NON_MEMBER, None, SimpleSortMethod::UpdatedAt, 50).into_params(),
+ )
+ .await
+ .map_err(report_err)?;
+
+ assert!(rows.is_empty());
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("channels_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn channel_thread_rows_filter_by_thread_id(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = repo(pool);
+ let rows = repo
+ .get_thread_reply_rows(
+ thread_rows_request(
+ USER_A,
+ thread_filter(ChannelThreadLiteral::ThreadId(MSG1)),
+ SimpleSortMethod::UpdatedAt,
+ 50,
+ )
+ .into_params(),
+ )
+ .await
+ .map_err(report_err)?;
+
+ assert_eq!(rows.len(), 1);
+ assert_eq!(rows[0].parent.id, MSG1);
+ let reply_ids = rows[0]
+ .replies
+ .iter()
+ .map(|reply| reply.id)
+ .collect::<Vec<_>>();
+ assert_eq!(reply_ids, vec![REPLY1, REPLY2, REPLY3, REPLY4]);
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("channels_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn channel_thread_rows_filter_by_channel_id(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = repo(pool);
+ let rows = repo
+ .get_thread_reply_rows(
+ thread_rows_request(
+ USER_A,
+ thread_filter(ChannelThreadLiteral::ChannelId(CH2)),
+ SimpleSortMethod::UpdatedAt,
+ 50,
+ )
+ .into_params(),
+ )
+ .await
+ .map_err(report_err)?;
+
+ assert!(rows.is_empty());
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("channels_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn channel_thread_rows_filter_by_root_sender(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = repo(pool);
+ let rows = repo
+ .get_thread_reply_rows(
+ thread_rows_request(
+ USER_A,
+ thread_filter(ChannelThreadLiteral::RootSender(macro_user_id(USER_A))),
+ SimpleSortMethod::UpdatedAt,
+ 50,
+ )
+ .into_params(),
+ )
+ .await
+ .map_err(report_err)?;
+
+ let parent_ids = rows.iter().map(|row| row.parent.id).collect::<Vec<_>>();
+ assert_eq!(parent_ids, vec![MSG3, MSG1, MSG31]);
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("channels_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn channel_thread_rows_apply_cursor(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = repo(pool);
+ let first_page = repo
+ .get_thread_reply_rows(
+ thread_rows_request(USER_A, None, SimpleSortMethod::UpdatedAt, 1).into_params(),
+ )
+ .await
+ .map_err(report_err)?;
+ assert_eq!(first_page.len(), 1);
+ assert_eq!(first_page[0].parent.id, MSG3);
+
+ let second_page = repo
+ .get_thread_reply_rows(
+ GetThreadReplyRowsRequest {
+ macro_id: macro_user_id(USER_A),
+ limit: Some(50),
+ query: Query::Cursor(Cursor {
+ id: first_page[0].parent.id,
+ limit: 50,
+ val: CursorVal {
+ sort_type: SimpleSortMethod::UpdatedAt,
+ last_val: first_page[0].parent.updated_at,
+ },
+ filter: None,
+ }),
+ }
+ .into_params(),
+ )
+ .await
+ .map_err(report_err)?;
+
+ let parent_ids = second_page
+ .iter()
+ .map(|row| row.parent.id)
+ .collect::<Vec<_>>();
+ assert_eq!(parent_ids, vec![MSG1, MSG31]);
+ Ok(())
+}
+
#[sqlx::test(
fixtures(path = "../../../fixtures", scripts("channels_repo")),
migrator = "MACRO_DB_MIGRATIONS"
diff --git a/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rs b/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rs
index 4c521c82e4..8ea614ece7 100644
--- a/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rs
+++ b/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rs
@@ -958,6 +958,7 @@ async fn test_dynamic_filter_document_date_created_at_gt(pool: PgPool) {
chat_filter: None,
email_filter: item_filters::ast::EmailFilterAst::default(),
channel_filter: None,
+ channel_thread_filter: None,
call_filter: None,
crm_company_filter: None,
foreign_entity_filter: None,
@@ -1051,6 +1052,7 @@ async fn test_dynamic_filter_document_date_created_at_lt(pool: PgPool) {
chat_filter: None,
email_filter: item_filters::ast::EmailFilterAst::default(),
channel_filter: None,
+ channel_thread_filter: None,
call_filter: None,
crm_company_filter: None,
foreign_entity_filter: None,
@@ -1140,6 +1142,7 @@ async fn test_dynamic_filter_document_date_updated_at_gt(pool: PgPool) {
chat_filter: None,
email_filter: item_filters::ast::EmailFilterAst::default(),
channel_filter: None,
+ channel_thread_filter: None,
call_filter: None,
crm_company_filter: None,
foreign_entity_filter: None,
@@ -1234,6 +1237,7 @@ async fn test_dynamic_filter_document_date_updated_at_lt(pool: PgPool) {
chat_filter: None,
email_filter: item_filters::ast::EmailFilterAst::default(),
channel_filter: None,
+ channel_thread_filter: None,
call_filter: None,
crm_company_filter: None,
foreign_entity_filter: None,
diff --git a/rust/cloud-storage/item_filters/src/ast.rs b/rust/cloud-storage/item_filters/src/ast.rs
index 787e3e2849..8f64627a39 100644
--- a/rust/cloud-storage/item_filters/src/ast.rs
+++ b/rust/cloud-storage/item_filters/src/ast.rs
@@ -2,11 +2,12 @@
//! This is used to construct a strictly typed ast for the input filters, allowing consumers to have a logical represenation of the required operations
use crate::{
- CallFilters, ChannelFilters, ChatFilters, CrmCompanyFilters, DocumentFilters, EmailFilters,
- EntityFilters, ForeignEntityFilters, ProjectFilters, PropertyFilter,
+ CallFilters, ChannelFilters, ChannelThreadFilters, ChatFilters, CrmCompanyFilters,
+ DocumentFilters, EmailFilters, EntityFilters, ForeignEntityFilters, ProjectFilters,
+ PropertyFilter,
ast::{
call::CallLiteral,
- channel::{ChannelLiteral, ChannelTypeFilter},
+ channel::{ChannelLiteral, ChannelThreadLiteral, ChannelTypeFilter},
chat::{ChatLiteral, ChatRole},
crm_company::CrmCompanyLiteral,
email::EmailLiteral,
@@ -195,6 +196,10 @@ pub struct EntityFilterAst {
#[serde(default, rename = "chanf")]
#[cfg_attr(feature = "schema", schema(value_type = serde_json::Value))]
pub channel_filter: LiteralTree<ChannelLiteral>,
+ /// the filters that should be applied to the channel-thread entity
+ #[serde(default, rename = "cthf")]
+ #[cfg_attr(feature = "schema", schema(value_type = serde_json::Value))]
+ pub channel_thread_filter: LiteralTree<ChannelThreadLiteral>,
/// the filters that should be applied to the call entity
#[serde(default, rename = "callf")]
#[cfg_attr(feature = "schema", schema(value_type = serde_json::Value))]
@@ -241,6 +246,10 @@ impl EntityFilterAst {
},
channel_filter: ChannelFilters::expand_ast(entity_filter.channel_filters)?
.map(Arc::new),
+ channel_thread_filter: ChannelThreadFilters::expand_ast(
+ entity_filter.channel_thread_filters,
+ )?
+ .map(Arc::new),
call_filter: CallFilters::expand_ast(entity_filter.call_filters)?.map(Arc::new),
crm_company_filter: CrmCompanyFilters::expand_ast(entity_filter.crm_company_filters)?
.map(Arc::new),
@@ -262,6 +271,7 @@ impl EntityFilterAst {
chat_filter: None,
email_filter: EmailFilterAst::default(),
channel_filter: None,
+ channel_thread_filter: None,
call_filter: None,
crm_company_filter: None,
foreign_entity_filter: None,
@@ -278,6 +288,7 @@ impl IsEmpty for EntityFilterAst {
chat_filter,
email_filter,
channel_filter,
+ channel_thread_filter,
call_filter,
crm_company_filter,
foreign_entity_filter,
@@ -288,6 +299,7 @@ impl IsEmpty for EntityFilterAst {
&& chat_filter.is_none()
&& email_filter.is_empty()
&& channel_filter.is_none()
+ && channel_thread_filter.is_none()
&& call_filter.is_none()
&& crm_company_filter.is_none()
&& foreign_entity_filter.is_none()
diff --git a/rust/cloud-storage/item_filters/src/ast/channel.rs b/rust/cloud-storage/item_filters/src/ast/channel.rs
index d2e0c5c5e6..b5170a4e3a 100644
--- a/rust/cloud-storage/item_filters/src/ast/channel.rs
+++ b/rust/cloud-storage/item_filters/src/ast/channel.rs
@@ -5,7 +5,7 @@ use strum::Display;
use uuid::Uuid;
use crate::{
- ChannelFilters,
+ ChannelFilters, ChannelThreadFilters,
ast::{ExpandErr, ParseFromStr, UnknownValue},
};
@@ -140,3 +140,47 @@ impl ExpandFrame<ChannelLiteral> for ChannelFilters {
.fold_with(Expr::and))
}
}
+
+/// the possible literal values in a channel thread filter ast
+#[derive(Debug, Serialize, Deserialize, Clone)]
+pub enum ChannelThreadLiteral {
+ /// The thread parent message id.
+ ThreadId(Uuid),
+ /// The thread must be in channel with [Uuid].
+ ChannelId(Uuid),
+ /// The sender of the root thread message must be the included user.
+ RootSender(MacroUserIdStr<'static>),
+}
+
+impl ExpandFrame<ChannelThreadLiteral> for ChannelThreadFilters {
+ type Err = ExpandErr;
+
+ fn expand_ast(
+ filter_request: ChannelThreadFilters,
+ ) -> Result<Option<Expr<ChannelThreadLiteral>>, Self::Err> {
+ let ChannelThreadFilters {
+ thread_ids,
+ channel_ids,
+ root_sender_ids,
+ } = filter_request;
+
+ let thread_ids = thread_ids
+ .iter()
+ .map(|s| Uuid::parse_str(s))
+ .try_expand(|r| r.map(ChannelThreadLiteral::ThreadId), Expr::or)?;
+
+ let channel_ids = channel_ids
+ .iter()
+ .map(|s| Uuid::parse_str(s))
+ .try_expand(|r| r.map(ChannelThreadLiteral::ChannelId), Expr::or)?;
+
+ let root_sender_ids = root_sender_ids
+ .iter()
+ .map(|s| MacroUserIdStr::parse_from_str(s).map(CowLike::into_owned))
+ .try_expand(|r| r.map(ChannelThreadLiteral::RootSender), Expr::or)?;
+
+ Ok([thread_ids, channel_ids, root_sender_ids]
+ .into_iter()
+ .fold_with(Expr::and))
+ }
+}
diff --git a/rust/cloud-storage/item_filters/src/ast/tests.rs b/rust/cloud-storage/item_filters/src/ast/tests.rs
index 54f9958d4c..082b4fef93 100644
--- a/rust/cloud-storage/item_filters/src/ast/tests.rs
+++ b/rust/cloud-storage/item_filters/src/ast/tests.rs
@@ -335,6 +335,62 @@ fn it_expands_channel_type_with_channel_id() {
assert!(json.get("&").is_some());
}
+#[test]
+fn it_expands_channel_thread_filters() {
+ let thread_id = Uuid::new_v4();
+ let channel_id = Uuid::new_v4();
+ let f = EntityFilters {
+ channel_thread_filters: crate::ChannelThreadFilters {
+ thread_ids: vec![thread_id.to_string()],
+ channel_ids: vec![channel_id.to_string()],
+ root_sender_ids: vec!["macro|[email protected]".to_string()],
+ },
+ ..Default::default()
+ };
+
+ let ast = Arc::into_inner(
+ EntityFilterAst::new_from_filters(f)
+ .unwrap()
+ .unwrap()
+ .channel_thread_filter
+ .unwrap(),
+ )
+ .unwrap();
+
+ let json = serde_json::to_value(ast).unwrap();
+ assert!(json.get("&").is_some());
+}
+
+#[test]
+fn it_expands_single_channel_thread_id() {
+ let thread_id = Uuid::new_v4();
+ let f = EntityFilters {
+ channel_thread_filters: crate::ChannelThreadFilters {
+ thread_ids: vec![thread_id.to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ };
+
+ let ast = Arc::into_inner(
+ EntityFilterAst::new_from_filters(f)
+ .unwrap()
+ .unwrap()
+ .channel_thread_filter
+ .unwrap(),
+ )
+ .unwrap();
+
+ let json = serde_json::to_value(ast).unwrap();
+ let exp = json!({
+ "l": {
+ "ThreadId": thread_id
+ }
+ });
+
+ assert_eq!(json, exp);
+}
+
#[test]
fn it_expands_document_notification_filters() {
let f = EntityFilters {
diff --git a/rust/cloud-storage/item_filters/src/lib.rs b/rust/cloud-storage/item_filters/src/lib.rs
index 3b13fce10d..2f82f5e601 100644
--- a/rust/cloud-storage/item_filters/src/lib.rs
+++ b/rust/cloud-storage/item_filters/src/lib.rs
@@ -472,6 +472,34 @@ impl IsEmpty for ChannelFilters {
}
}
+/// The channel thread filters used to filter down channel-thread entities.
+#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Clone)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema, schemars::JsonSchema))]
+pub struct ChannelThreadFilters {
+ /// Channel thread parent message IDs to include. Empty to include all accessible threads.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub thread_ids: Vec<String>,
+
+ /// Channel IDs containing the thread. Empty to include threads from all accessible channels.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub channel_ids: Vec<String>,
+
+ /// Sender IDs for the root thread message. Empty to include all root senders.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub root_sender_ids: Vec<String>,
+}
+
+impl IsEmpty for ChannelThreadFilters {
+ fn is_empty(&self) -> bool {
+ let ChannelThreadFilters {
+ thread_ids,
+ channel_ids,
+ root_sender_ids,
+ } = self;
+ thread_ids.is_empty() && channel_ids.is_empty() && root_sender_ids.is_empty()
+ }
+}
+
/// A single property-based filter condition.
///
/// Each filter targets a specific property definition on entities of a given type,
@@ -585,6 +613,9 @@ pub struct EntityFilters {
/// the bundled [ChannelFilters]
#[serde(default)]
pub channel_filters: ChannelFilters,
+ /// the bundled [ChannelThreadFilters]
+ #[serde(default)]
+ pub channel_thread_filters: ChannelThreadFilters,
/// the bundled [CallFilters]
#[serde(default)]
pub call_filters: CallFilters,
@@ -609,6 +640,7 @@ impl IsEmpty for EntityFilters {
document_filters,
chat_filters,
channel_filters,
+ channel_thread_filters,
call_filters,
email_filters,
crm_company_filters,
@@ -619,6 +651,7 @@ impl IsEmpty for EntityFilters {
&& document_filters.is_empty()
&& chat_filters.is_empty()
&& channel_filters.is_empty()
+ && channel_thread_filters.is_empty()
&& call_filters.is_empty()
&& email_filters.is_empty()
&& crm_company_filters.is_empty()
diff --git a/rust/cloud-storage/models_soup/src/comms.rs b/rust/cloud-storage/models_soup/src/comms.rs
index fa6eb751ca..32acff76b9 100644
--- a/rust/cloud-storage/models_soup/src/comms.rs
+++ b/rust/cloud-storage/models_soup/src/comms.rs
@@ -262,6 +262,36 @@ impl ChannelMessage {
mentions: Vec::new(),
}
}
+
+ /// Converts a raw channels-domain top-level message row into a Soup channel message.
+ pub fn new_from_top_level_message_row(
+ row: channels::domain::models::TopLevelMessageRow,
+ ) -> Self {
+ Self {
+ message_id: row.id,
+ thread_id: None,
+ sender_id: row.sender_id,
+ content: row.content,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ deleted_at: row.deleted_at,
+ mentions: Vec::new(),
+ }
+ }
+
+ /// Converts a raw channels-domain thread reply row into a Soup channel message.
+ pub fn new_from_thread_reply_row(row: channels::domain::models::ThreadReplyRow) -> Self {
+ Self {
+ message_id: row.id,
+ thread_id: Some(row.thread_id),
+ sender_id: row.sender_id,
+ content: row.content,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ deleted_at: None,
+ mentions: Vec::new(),
+ }
+ }
}
impl LatestMessage {
@@ -372,4 +402,20 @@ impl SoupChannelThread {
.collect(),
}
}
+
+ /// Converts raw channels-domain parent/reply rows into a Soup thread.
+ pub fn new_from_thread_reply_rows(
+ rows: channels::domain::models::ChannelThreadReplyRows,
+ ) -> Self {
+ let channel_id = rows.parent.channel_id;
+ Self {
+ channel_id: ChannelId(channel_id),
+ root_message: ChannelMessage::new_from_top_level_message_row(rows.parent),
+ messages: rows
+ .replies
+ .into_iter()
+ .map(ChannelMessage::new_from_thread_reply_row)
+ .collect(),
+ }
+ }
}
diff --git a/rust/cloud-storage/soup/src/domain/models.rs b/rust/cloud-storage/soup/src/domain/models.rs
index 99e529b08f..ddadf956d8 100644
--- a/rust/cloud-storage/soup/src/domain/models.rs
+++ b/rust/cloud-storage/soup/src/domain/models.rs
@@ -6,7 +6,7 @@ pub use grouping::{
};
use call::domain::models::GetCallRecordsRequest;
-use channels::domain::models::GetChannelsRequest;
+use channels::domain::models::{GetChannelsRequest, GetThreadReplyRowsRequest};
use crm::domain::auth::CrmTeamReceipt;
use crm::domain::companies_repo::{CrmCompanyListSort, CrmCompanySoupCursor};
use email::domain::models::{GetEmailsRequest, PreviewView};
@@ -475,6 +475,36 @@ impl SoupRequest<Option<EntityFilterAst>> {
})
}
+ pub(crate) fn build_comms_thread_request(&self) -> Option<GetThreadReplyRowsRequest> {
+ let query = match &self.cursor {
+ SoupQuery::Simple(SimpleQueryInner(Query::Sort(t, f))) => Some(Query::Sort(
+ *t,
+ f.as_ref().and_then(|f| f.channel_thread_filter.clone()),
+ )),
+ SoupQuery::Simple(SimpleQueryInner(Query::Cursor(CursorWithValAndFilter {
+ id,
+ limit,
+ val,
+ filter,
+ }))) => Some(Query::Cursor(CursorWithValAndFilter {
+ id: *id,
+ limit: *limit,
+ val: val.clone(),
+ filter: filter
+ .as_ref()
+ .and_then(|f| f.channel_thread_filter.clone()),
+ })),
+ // query by frecency not yet implemented for channel threads
+ SoupQuery::Frecency(_) => None,
+ }?;
+
+ Some(GetThreadReplyRowsRequest {
+ macro_id: self.user.clone(),
+ limit: Some(self.limit as u32),
+ query,
+ })
+ }
+
pub(crate) fn build_foreign_entity_query(&self) -> Option<ForeignEntityListQuery> {
match &self.cursor {
SoupQuery::Simple(SimpleQueryInner(Query::Sort(t, f))) => Some(Query::Sort(
diff --git a/rust/cloud-storage/soup/src/domain/service.rs b/rust/cloud-storage/soup/src/domain/service.rs
index 5165097cf9..c4b6ea46bb 100644
--- a/rust/cloud-storage/soup/src/domain/service.rs
+++ b/rust/cloud-storage/soup/src/domain/service.rs
@@ -7,7 +7,10 @@ use crate::domain::{
ports::{SoupOutput, SoupRepo, SoupService},
};
use call::domain::{models::GetCallRecordsRequest, ports::CallRecordQueryService};
-use channels::domain::{models::GetChannelsRequest, ports::ChannelListService};
+use channels::domain::{
+ models::{GetChannelsRequest, GetThreadReplyRowsRequest},
+ ports::ChannelListService,
+};
use cowlike::CowLike;
use crm::domain::service::CrmService;
use doppleganger::Mirror;
@@ -32,7 +35,7 @@ use models_pagination::{
};
use models_soup::{
call_record::SoupCallRecord,
- comms::SoupChannel,
+ comms::{SoupChannel, SoupChannelThread},
crm_company::SoupCrmCompany,
email_thread::{
SoupAttachment, SoupContact, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreview,
@@ -400,6 +403,30 @@ where
))
}
+ #[tracing::instrument(err, skip(self, req))]
+ async fn handle_comms_thread_request(
+ &self,
+ req: Option<GetThreadReplyRowsRequest>,
+ ) -> Result<impl Iterator<Item = FrecencySoupItem>, SoupErr> {
+ let Some(req) = req else {
+ return Ok(Either::Left(None.into_iter()));
+ };
+
+ Ok(Either::Right(
+ self.comms_service
+ .get_thread_reply_rows(req)
+ .await
+ .map_err(|_| SoupErr::CommsErr)?
+ .into_iter()
+ .map(|rows| FrecencySoupItem {
+ item: SoupItem::ChannelThread(SoupChannelThread::new_from_thread_reply_rows(
+ rows,
+ )),
+ frecency_score: None,
+ }),
+ ))
+ }
+
#[tracing::instrument(err, skip(self, req))]
async fn handle_crm_company_request(
&self,
@@ -524,6 +551,7 @@ where
let foreign_entity_query = req.build_foreign_entity_query();
let email_request = req.build_email_request(team_receipt);
let comms_request = req.build_comms_request();
+ let comms_thread_request = req.build_comms_thread_request();
let call_request = req.build_call_request();
match req.cursor {
@@ -543,6 +571,8 @@ where
let comms_soup_fut = self.handle_comms_request(comms_request);
+ let comms_thread_soup_fut = self.handle_comms_thread_request(comms_thread_request);
+
let call_soup_fut = self.handle_call_request(call_request);
let crm_company_soup_fut = self.handle_crm_company_request(crm_company_request);
@@ -558,6 +588,7 @@ where
main_soup,
email_soup,
comms_soup,
+ comms_thread_soup,
call_soup,
crm_company_soup,
foreign_entity_soup,
@@ -565,6 +596,7 @@ where
main_soup_fut,
email_soup_fut,
comms_soup_fut,
+ comms_thread_soup_fut,
call_soup_fut,
crm_company_soup_fut,
foreign_entity_soup_fut,
@@ -573,6 +605,7 @@ where
let page = main_soup?
.chain(email_soup?)
.chain(comms_soup?)
+ .chain(comms_thread_soup?)
.chain(call_soup?)
.chain(crm_company_soup?)
.chain(foreign_entity_soup?)
diff --git a/rust/cloud-storage/soup/src/domain/service/tests.rs b/rust/cloud-storage/soup/src/domain/service/tests.rs
index 191da8460e..71898444e4 100644
--- a/rust/cloud-storage/soup/src/domain/service/tests.rs
+++ b/rust/cloud-storage/soup/src/domain/service/tests.rs
@@ -1,6 +1,12 @@
use crate::domain::models::FrecencySoupItem;
use crate::domain::ports::MockSoupRepo;
-use channels::domain::{models::GetChannelsRequest, ports::ChannelListService};
+use channels::domain::{
+ models::{
+ ChannelThreadReplyRows, GetChannelsRequest, GetThreadReplyRowsRequest, ThreadReplyRow,
+ TopLevelMessageRow,
+ },
+ ports::ChannelListService,
+};
use chrono::Days;
use chrono::{DateTime, Utc};
use cool_asserts::assert_matches;
@@ -18,7 +24,8 @@ use frecency::domain::ports::MockFrecencyQueryService;
use frecency::domain::services::FrecencyQueryServiceImpl;
use frecency::{domain::models::AggregateFrecency, outbound::mock::MockFrecencyStorage};
use item_filters::{
- EntityFilters, ForeignEntityFilters, ast::foreign_entity::ForeignEntityLiteral,
+ ChannelThreadFilters, EntityFilters, ForeignEntityFilters,
+ ast::foreign_entity::ForeignEntityLiteral,
};
use model_entity::EntityType;
use models_pagination::{
@@ -67,6 +74,83 @@ impl ChannelListService for NoopCommsService {
Ok(Vec::new())
}
+ async fn get_thread_reply_rows(
+ &self,
+ _req: GetThreadReplyRowsRequest,
+ ) -> Result<Vec<ChannelThreadReplyRows>, Report> {
+ Ok(Vec::new())
+ }
+
+ async fn get_names(
+ &self,
+ _names: std::collections::HashSet<MacroUserIdStr<'_>>,
+ ) -> Result<Vec<channels::domain::models::UserName>, Report> {
+ Ok(Vec::new())
+ }
+}
+
+#[derive(Clone)]
+struct RecordingCommsService {
+ rows: Vec<ChannelThreadReplyRows>,
+ channel_calls: Arc<Mutex<u32>>,
+ channel_filters: Arc<Mutex<Vec<String>>>,
+ thread_filters: Arc<Mutex<Vec<String>>>,
+}
+
+impl RecordingCommsService {
+ fn new(rows: Vec<ChannelThreadReplyRows>) -> Self {
+ Self {
+ rows,
+ channel_calls: Arc::new(Mutex::new(0)),
+ channel_filters: Arc::new(Mutex::new(Vec::new())),
+ thread_filters: Arc::new(Mutex::new(Vec::new())),
+ }
+ }
+
+ fn channel_calls(&self) -> u32 {
+ *self.channel_calls.lock().unwrap()
+ }
+
+ fn channel_filters(&self) -> Vec<String> {
+ self.channel_filters.lock().unwrap().clone()
+ }
+
+ fn thread_filters(&self) -> Vec<String> {
+ self.thread_filters.lock().unwrap().clone()
+ }
+}
+
+impl ChannelListService for RecordingCommsService {
+ async fn get_channels(
+ &self,
+ req: GetChannelsRequest,
+ ) -> Result<Vec<channels::domain::models::ChannelWithLatest>, Report> {
+ *self.channel_calls.lock().unwrap() += 1;
+ self.channel_filters
+ .lock()
+ .unwrap()
+ .push(serde_json::to_string(req.query.filter()).unwrap());
+ Ok(Vec::new())
+ }
+
+ async fn get_activities(
+ &self,
+ _user: MacroUserIdStr<'_>,
+ ) -> Result<Vec<channels::domain::models::Activity>, Report> {
+ Ok(Vec::new())
+ }
+
+ async fn get_thread_reply_rows(
+ &self,
+ req: GetThreadReplyRowsRequest,
+ ) -> Result<Vec<ChannelThreadReplyRows>, Report> {
+ self.thread_filters
+ .lock()
+ .unwrap()
+ .push(serde_json::to_string(req.query.filter()).unwrap());
+ Ok(self.rows.clone())
+ }
+
async fn get_names(
&self,
_names: std::collections::HashSet<MacroUserIdStr<'_>>,
@@ -407,6 +491,150 @@ fn foreign_entity_for_source(
}
}
+fn channel_thread_rows(
+ channel_id: Uuid,
+ thread_id: Uuid,
+ reply_id: Uuid,
+ updated_at: DateTime<Utc>,
+) -> ChannelThreadReplyRows {
+ ChannelThreadReplyRows {
+ parent: TopLevelMessageRow {
+ id: thread_id,
+ channel_id,
+ sender_id: "macro|[email protected]".to_string(),
+ content: "thread parent".to_string(),
+ created_at: DateTime::default(),
+ updated_at,
+ edited_at: None,
+ deleted_at: None,
+ },
+ replies: vec![ThreadReplyRow {
+ id: reply_id,
+ thread_id,
+ sender_id: "macro|[email protected]".to_string(),
+ content: "thread reply".to_string(),
+ created_at: DateTime::default() + Days::new(1),
+ updated_at: DateTime::default() + Days::new(1),
+ edited_at: None,
+ }],
+ }
+}
+
+#[tokio::test]
+async fn simple_soup_includes_channel_threads() {
+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let channel_id = Uuid::from_u128(0xaaaa);
+ let thread_id = Uuid::from_u128(0xbbbb);
+ let reply_id = Uuid::from_u128(0xcccc);
+ let comms_service = RecordingCommsService::new(vec![channel_thread_rows(
+ channel_id,
+ thread_id,
+ reply_id,
+ DateTime::default() + Days::new(2),
+ )]);
+
+ let mut soup_mock = MockSoupRepo::new();
+ soup_mock
+ .expect_unexpanded_generic_cursor_soup()
+ .times(1)
+ .returning(|_params| Box::pin(async move { Ok(Vec::new()) }));
+
+ let page = SoupImpl::new(
+ soup_mock,
+ FrecencyQueryServiceImpl::new(MockFrecencyStorage::new()),
+ NoopEmailPreviewService,
+ comms_service.clone(),
+ NoopCallRecordQueryService,
+ NoOpCrmService,
+ NoopForeignEntityService,
+ )
+ .get_user_soup(
+ SoupRequest {
+ email_preview_view: PreviewView::StandardLabel(
+ email::domain::models::PreviewViewStandardLabel::Inbox,
+ ),
+ link_ids: vec![],
+ soup_type: SoupType::UnExpanded,
+ limit: 20,
+ cursor: SoupQuery::new_sort_simple(
+ SimpleSortMethod::UpdatedAt,
+ EntityFilters::default(),
+ ),
+ user,
+ },
+ None,
+ )
+ .await
+ .unwrap()
+ .unwrap_left();
+
+ assert_eq!(page.items.len(), 1);
+ assert_matches!(
+ &page.items[0].item,
+ SoupItem::ChannelThread(thread) => {
+ assert_eq!(thread.channel_id.0, channel_id);
+ assert_eq!(thread.root_message.message_id, thread_id);
+ assert_eq!(thread.messages.len(), 1);
+ assert_eq!(thread.messages[0].message_id, reply_id);
+ }
+ );
+}
+
+#[tokio::test]
+async fn simple_soup_uses_channel_thread_filters_without_touching_channel_filters() {
+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let thread_id = Uuid::from_u128(0xbbbb);
+ let comms_service = RecordingCommsService::new(Vec::new());
+
+ let mut soup_mock = MockSoupRepo::new();
+ soup_mock
+ .expect_unexpanded_generic_cursor_soup()
+ .times(1)
+ .returning(|_params| Box::pin(async move { Ok(Vec::new()) }));
+
+ let _page = SoupImpl::new(
+ soup_mock,
+ FrecencyQueryServiceImpl::new(MockFrecencyStorage::new()),
+ NoopEmailPreviewService,
+ comms_service.clone(),
+ NoopCallRecordQueryService,
+ NoOpCrmService,
+ NoopForeignEntityService,
+ )
+ .get_user_soup(
+ SoupRequest {
+ email_preview_view: PreviewView::StandardLabel(
+ email::domain::models::PreviewViewStandardLabel::Inbox,
+ ),
+ link_ids: vec![],
+ soup_type: SoupType::UnExpanded,
+ limit: 20,
+ cursor: SoupQuery::new_sort_simple(
+ SimpleSortMethod::UpdatedAt,
+ EntityFilters {
+ channel_thread_filters: ChannelThreadFilters {
+ thread_ids: vec![thread_id.to_string()],
+ ..Default::default()
+ },
+ ..Default::default()
+ },
+ ),
+ user,
+ },
+ None,
+ )
+ .await
+ .unwrap()
+ .unwrap_left();
+
+ assert_eq!(comms_service.channel_calls(), 1);
+ assert_eq!(comms_service.channel_filters(), vec!["null".to_string()]);
+ let thread_filters = comms_service.thread_filters();
+ assert_eq!(thread_filters.len(), 1);
+ assert!(thread_filters[0].contains("ThreadId"));
+ assert!(thread_filters[0].contains(&thread_id.to_string()));
+}
+
#[tokio::test]
async fn simple_soup_includes_foreign_entities() {
let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
diff --git a/rust/cloud-storage/soup/src/inbound/axum_router.rs b/rust/cloud-storage/soup/src/inbound/axum_router.rs
index a36e3d7efd..20e24b77fc 100644
--- a/rust/cloud-storage/soup/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/soup/src/inbound/axum_router.rs
@@ -33,7 +33,7 @@ use item_filters::{
ast::{
EntityFilterAst, ExpandErr, LiteralTree,
call::CallLiteral,
- channel::ChannelLiteral,
+ channel::{ChannelLiteral, ChannelThreadLiteral},
chat::ChatLiteral,
crm_company::CrmCompanyLiteral,
document::DocumentLiteral,
@@ -1053,6 +1053,10 @@ pub struct ApiEntityFilterAst {
#[serde(default, rename = "chanf")]
#[schema(value_type = serde_json::Value)]
pub channel_filter: LiteralTree<ChannelLiteral>,
+ /// the filters that should be applied to the channel-thread entity
+ #[serde(default, rename = "cthf")]
+ #[schema(value_type = serde_json::Value)]
+ pub channel_thread_filter: LiteralTree<ChannelThreadLiteral>,
/// the filters that should be applied to foreign entity records
#[serde(default, rename = "fef")]
#[schema(value_type = serde_json::Value)]
@@ -1151,6 +1155,7 @@ impl ApiEntityFilterAst {
chat_filter,
email_filter,
channel_filter,
+ channel_thread_filter,
foreign_entity_filter,
call_filter,
crm_company_filter,
@@ -1217,6 +1222,7 @@ impl ApiEntityFilterAst {
crm_scope,
},
channel_filter,
+ channel_thread_filter,
call_filter,
crm_company_filter,
foreign_entity_filter,
diff --git a/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs b/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs
index a7db085d53..b38eba8e7d 100644
--- a/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs
+++ b/rust/cloud-storage/soup/src/inbound/toolset/list_entities.rs
@@ -11,9 +11,15 @@ use filter_ast::Expr;
use item_filters::{
SharedEmailFilter,
ast::{
- EntityFilterAst, LiteralTree, call::CallLiteral, channel::ChannelLiteral,
- chat::ChatLiteral, crm_company::CrmCompanyLiteral, document::DocumentLiteral,
- email::EmailLiteral, foreign_entity::ForeignEntityLiteral, project::ProjectLiteral,
+ EntityFilterAst, LiteralTree,
+ call::CallLiteral,
+ channel::{ChannelLiteral, ChannelThreadLiteral},
+ chat::ChatLiteral,
+ crm_company::CrmCompanyLiteral,
+ document::DocumentLiteral,
+ email::EmailLiteral,
+ foreign_entity::ForeignEntityLiteral,
+ project::ProjectLiteral,
properties::PropertiesLiteral,
},
};
@@ -86,6 +92,8 @@ pub enum ItemType {
Email,
/// Chat channel.
Channel,
+ /// Chat channel thread.
+ ChannelThread,
/// Call record.
Call,
/// Foreign entity record.
@@ -291,6 +299,14 @@ pub struct ListEntities {
#[serde(default, rename = "chanf")]
pub channel_filter: LiteralTree<ChannelLiteral>,
+ /// Channel thread entity AST filter.
+ #[schemars(
+ description = "Full soup AST channel thread filter (cthf).",
+ with = "Option<serde_json::Value>"
+ )]
+ #[serde(default, rename = "cthf")]
+ pub channel_thread_filter: LiteralTree<ChannelThreadLiteral>,
+
/// Call entity AST filter.
#[schemars(
description = "Full soup AST call filter (callf).",
@@ -349,6 +365,7 @@ impl ListEntities {
crm_scope: None,
},
channel_filter: self.channel_filter.clone(),
+ channel_thread_filter: self.channel_thread_filter.clone(),
call_filter: self.call_filter.clone(),
// CrmCompany not in the tool surface — force-filter so the
// AI never sees one.
@@ -397,6 +414,13 @@ impl ListEntities {
} else {
Some(Arc::new(Expr::val(ChannelLiteral::ChannelId(Uuid::nil()))))
},
+ channel_thread_filter: if include_types.contains(&ItemType::ChannelThread) {
+ ast.channel_thread_filter
+ } else {
+ Some(Arc::new(Expr::val(ChannelThreadLiteral::ThreadId(
+ Uuid::nil(),
+ ))))
+ },
call_filter: if include_types.contains(&ItemType::Call) {
ast.call_filter
} else {
diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs
index 4cc1a62460..8967f952e9 100644
--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs
+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs
@@ -5456,6 +5456,7 @@ fn mock_empty_ast() -> EntityFilterAst {
chat_filter: None,
email_filter: item_filters::ast::EmailFilterAst::default(),
channel_filter: None,
+ channel_thread_filter: None,
call_filter: None,
crm_company_filter: None,
foreign_entity_filter: None,