The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
feat(messaging): let apps ingest messages into their channels (#25905)
Félix Malfait802c782c6a66
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphqlindex 6c97020749b..ff0d0d176ef 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql@@ -2997,6 +2997,16 @@ enum MessageChannelSyncStage {FAILED}+type IngestedAppMessage {+ externalId: String!+ messageId: UUID!+ messageThreadId: UUID!+}++type IngestAppMessagesOutput {+ messages: [IngestedAppMessage!]!+}+type CreateEmailGroupChannelOutput {messageChannel: MessageChannel!forwardingAddress: String!@@ -4041,6 +4051,7 @@ type Mutation {createAppMessageChannel(input: CreateAppMessageChannelInput!): MessageChannel!updateAppMessageChannel(input: UpdateAppMessageChannelInput!): MessageChannel!deleteAppMessageChannel(id: UUID!): MessageChannel!+ ingestAppMessages(input: IngestAppMessagesInput!): IngestAppMessagesOutput!createEmailingDomain(input: CreateEmailingDomainInput!): EmailingDomain!deleteEmailingDomain(id: String!): Boolean!verifyEmailingDomain(id: String!): EmailingDomain!@@ -5200,6 +5211,34 @@ input UpdateAppMessageChannelInput {isSyncEnabled: Boolean}+input IngestAppMessagesInput {+ messageChannelId: UUID!+ messages: [AppMessageInput!]!+}++input AppMessageInput {+ externalId: String!+ threadExternalId: String!+ subject: String+ text: String!+ receivedAt: DateTime!+ participants: [AppMessageParticipantInput!]!+}++input AppMessageParticipantInput {+ role: MessageParticipantRole!+ handle: String!+ displayName: String+}++enum MessageParticipantRole {+ FROM+ TO+ CC+ BCC+ REPLY_TO+}+input CreateEmailingDomainInput {domain: String!}diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.tsindex a904db27bab..c6b6b76e193 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts@@ -2571,6 +2571,18 @@ export type MessageChannelSyncStatus = 'NOT_SYNCED' | 'ONGOING' | 'ACTIVE' | 'FAexport type MessageChannelSyncStage = 'PENDING_CONFIGURATION' | 'MESSAGE_LIST_FETCH_PENDING' | 'MESSAGE_LIST_FETCH_SCHEDULED' | 'MESSAGE_LIST_FETCH_ONGOING' | 'MESSAGES_IMPORT_PENDING' | 'MESSAGES_IMPORT_SCHEDULED' | 'MESSAGES_IMPORT_ONGOING' | 'FAILED'+export interface IngestedAppMessage {+ externalId: Scalars['String']+ messageId: Scalars['UUID']+ messageThreadId: Scalars['UUID']+ __typename: 'IngestedAppMessage'+}++export interface IngestAppMessagesOutput {+ messages: IngestedAppMessage[]+ __typename: 'IngestAppMessagesOutput'+}+export interface CreateEmailGroupChannelOutput {messageChannel: MessageChannelforwardingAddress: Scalars['String']@@ -3465,6 +3477,7 @@ export interface Mutation {createAppMessageChannel: MessageChannelupdateAppMessageChannel: MessageChanneldeleteAppMessageChannel: MessageChannel+ ingestAppMessages: IngestAppMessagesOutputcreateEmailingDomain: EmailingDomaindeleteEmailingDomain: Scalars['Boolean']verifyEmailingDomain: EmailingDomain@@ -3558,6 +3571,8 @@ export interface Mutation {__typename: 'Mutation'}+export type MessageParticipantRole = 'FROM' | 'TO' | 'CC' | 'BCC' | 'REPLY_TO'+export type RunAgentMessageRole = 'user' | 'assistant'export type AnalyticsType = 'PAGEVIEW' | 'TRACK'@@ -6237,6 +6252,20 @@ export interface MessageChannelGenqlSelection{__scalar?: boolean | number}+export interface IngestedAppMessageGenqlSelection{+ externalId?: boolean | number+ messageId?: boolean | number+ messageThreadId?: boolean | number+ __typename?: boolean | number+ __scalar?: boolean | number+}++export interface IngestAppMessagesOutputGenqlSelection{+ messages?: IngestedAppMessageGenqlSelection+ __typename?: boolean | number+ __scalar?: boolean | number+}+export interface CreateEmailGroupChannelOutputGenqlSelection{messageChannel?: MessageChannelGenqlSelectionforwardingAddress?: boolean | number@@ -7213,6 +7242,7 @@ export interface MutationGenqlSelection{createAppMessageChannel?: (MessageChannelGenqlSelection & { __args: {input: CreateAppMessageChannelInput} })updateAppMessageChannel?: (MessageChannelGenqlSelection & { __args: {input: UpdateAppMessageChannelInput} })deleteAppMessageChannel?: (MessageChannelGenqlSelection & { __args: {id: Scalars['UUID']} })+ ingestAppMessages?: (IngestAppMessagesOutputGenqlSelection & { __args: {input: IngestAppMessagesInput} })createEmailingDomain?: (EmailingDomainGenqlSelection & { __args: {input: CreateEmailingDomainInput} })deleteEmailingDomain?: { __args: {id: Scalars['String']} }verifyEmailingDomain?: (EmailingDomainGenqlSelection & { __args: {id: Scalars['String']} })@@ -7661,6 +7691,12 @@ export interface CreateAppMessageChannelInput {connectedAccountId: Scalars['UUIDexport interface UpdateAppMessageChannelInput {id: Scalars['UUID'],displayName?: (Scalars['String'] | null),visibility?: (MessageChannelVisibility | null),isSyncEnabled?: (Scalars['Boolean'] | null)}+export interface IngestAppMessagesInput {messageChannelId: Scalars['UUID'],messages: AppMessageInput[]}++export interface AppMessageInput {externalId: Scalars['String'],threadExternalId: Scalars['String'],subject?: (Scalars['String'] | null),text: Scalars['String'],receivedAt: Scalars['DateTime'],participants: AppMessageParticipantInput[]}++export interface AppMessageParticipantInput {role: MessageParticipantRole,handle: Scalars['String'],displayName?: (Scalars['String'] | null)}+export interface CreateEmailingDomainInput {domain: Scalars['String']}export interface RunAgentInput {agentUniversalIdentifier: Scalars['String'],prompt?: (Scalars['String'] | null),runAsWorkspaceMemberId?: (Scalars['UUID'] | null),messages?: (RunAgentMessageInput[] | null)}@@ -9611,6 +9647,22 @@ export interface LogicFunctionLogsInput {applicationId?: (Scalars['UUID'] | null+ const IngestedAppMessage_possibleTypes: string[] = ['IngestedAppMessage']+ export const isIngestedAppMessage = (obj?: { __typename?: any } | null): obj is IngestedAppMessage => {+ if (!obj?.__typename) throw new Error('__typename is missing in "isIngestedAppMessage"')+ return IngestedAppMessage_possibleTypes.includes(obj.__typename)+ }++++ const IngestAppMessagesOutput_possibleTypes: string[] = ['IngestAppMessagesOutput']+ export const isIngestAppMessagesOutput = (obj?: { __typename?: any } | null): obj is IngestAppMessagesOutput => {+ if (!obj?.__typename) throw new Error('__typename is missing in "isIngestAppMessagesOutput"')+ return IngestAppMessagesOutput_possibleTypes.includes(obj.__typename)+ }+++const CreateEmailGroupChannelOutput_possibleTypes: string[] = ['CreateEmailGroupChannelOutput']export const isCreateEmailGroupChannelOutput = (obj?: { __typename?: any } | null): obj is CreateEmailGroupChannelOutput => {if (!obj?.__typename) throw new Error('__typename is missing in "isCreateEmailGroupChannelOutput"')@@ -10969,6 +11021,14 @@ export const enumEventLogTable = {APPLICATION_LOG: 'APPLICATION_LOG' as const}+export const enumMessageParticipantRole = {+ FROM: 'FROM' as const,+ TO: 'TO' as const,+ CC: 'CC' as const,+ BCC: 'BCC' as const,+ REPLY_TO: 'REPLY_TO' as const+}+export const enumRunAgentMessageRole = {user: 'user' as const,assistant: 'assistant' as constdiff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.tsindex a7085f720d6..a414219e805 100644--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts@@ -87,22 +87,23 @@ export default {322,323,324,- 332,- 333,- 336,- 373,- 380,+ 334,+ 335,+ 338,+ 375,382,- 383,384,385,+ 386,387,389,- 394,- 411,- 423,- 543,- 569+ 391,+ 396,+ 413,+ 425,+ 545,+ 549,+ 575],"types": {"BillingProductDTO": {@@ -5785,6 +5786,28 @@ export default {"MessageChannelPendingGroupEmailsAction": {},"MessageChannelSyncStatus": {},"MessageChannelSyncStage": {},+ "IngestedAppMessage": {+ "externalId": [+ 1+ ],+ "messageId": [+ 3+ ],+ "messageThreadId": [+ 3+ ],+ "__typename": [+ 1+ ]+ },+ "IngestAppMessagesOutput": {+ "messages": [+ 325+ ],+ "__typename": [+ 1+ ]+ },"CreateEmailGroupChannelOutput": {"messageChannel": [317@@ -5852,7 +5875,7 @@ export default {28],"audience": [- 326+ 328],"__typename": [1@@ -5895,10 +5918,10 @@ export default {1],"reason": [- 332+ 334],"source": [- 333+ 335],"unsubscribeTopicId": [3@@ -5911,7 +5934,7 @@ export default {"MessageSuppressionSource": {},"MessageSuppressionList": {"records": [- 331+ 333],"totalCount": [28@@ -5937,7 +5960,7 @@ export default {1],"visibility": [- 336+ 338],"__typename": [1@@ -5983,7 +6006,7 @@ export default {1],"location": [- 338+ 340],"__typename": [1@@ -6011,13 +6034,13 @@ export default {1],"IMAP": [- 340+ 342],"SMTP": [- 340+ 342],"CALDAV": [- 340+ 342],"__typename": [1@@ -6037,7 +6060,7 @@ export default {3],"connectionParameters": [- 341+ 343],"__typename": [1@@ -6262,7 +6285,7 @@ export default {1],"series": [- 350+ 352],"xAxisLabel": [1@@ -6311,7 +6334,7 @@ export default {1],"data": [- 352+ 354],"__typename": [1@@ -6319,7 +6342,7 @@ export default {},"LineChartData": {"series": [- 353+ 355],"xAxisLabel": [1@@ -6356,7 +6379,7 @@ export default {},"PieChartData": {"data": [- 355+ 357],"showLegend": [8@@ -6461,13 +6484,13 @@ export default {},"EventLogQueryResult": {"records": [- 360+ 362],"totalCount": [28],"pageInfo": [- 361+ 363],"__typename": [1@@ -6534,7 +6557,7 @@ export default {1],"parts": [- 346+ 348],"processedAt": [4@@ -6603,7 +6626,7 @@ export default {},"AiSystemPromptPreview": {"sections": [- 366+ 368],"estimatedTokenCount": [28@@ -6631,7 +6654,7 @@ export default {28],"error": [- 368+ 370],"__typename": [1@@ -6664,10 +6687,10 @@ export default {},"StartWorkspaceSetupChatResult": {"outcome": [- 373+ 375],"thread": [- 365+ 367],"__typename": [1@@ -6705,10 +6728,10 @@ export default {3],"evaluations": [- 374+ 376],"messages": [- 364+ 366],"createdAt": [4@@ -6770,7 +6793,7 @@ export default {9],"scope": [- 380+ 382],"__typename": [1@@ -6785,19 +6808,19 @@ export default {1],"syncStatus": [- 382+ 384],"syncStage": [- 383+ 385],"visibility": [- 384+ 386],"isContactAutoCreationEnabled": [8],"contactAutoCreationPolicy": [- 385+ 387],"isSyncEnabled": [8@@ -6848,7 +6871,7 @@ export default {1],"pendingSyncAction": [- 387+ 389],"messageChannelId": [3@@ -6890,7 +6913,7 @@ export default {1],"provenance": [- 389+ 391],"__typename": [1@@ -6919,7 +6942,7 @@ export default {3],"through": [- 390+ 392],"__typename": [1@@ -6939,7 +6962,7 @@ export default {1],"emit": [- 391+ 393],"action": [1@@ -6974,7 +6997,7 @@ export default {},"CollectionHash": {"collectionName": [- 394+ 396],"hash": [1@@ -7038,13 +7061,13 @@ export default {},"MinimalMetadata": {"objectMetadataItems": [- 395+ 397],"views": [- 396+ 398],"collectionHashes": [- 393+ 395],"__typename": [1@@ -7104,7 +7127,7 @@ export default {175,{"input": [- 399+ 401]}],@@ -7121,7 +7144,7 @@ export default {182,{"input": [- 400,+ 402,"UsageQuotaScopeInput!"]}@@ -7244,7 +7267,7 @@ export default {2,{"input": [- 401,+ 403,"GetApiKeyInput!"]}@@ -7362,7 +7385,7 @@ export default {10,{"input": [- 402,+ 404,"AgentIdInput!"]}@@ -7375,7 +7398,7 @@ export default {"CursorPaging!"],"filter": [- 403,+ 405,"ObjectFilter!"]}@@ -7405,7 +7428,7 @@ export default {21,{"input": [- 404,+ 406,"LogicFunctionIdInput!"]}@@ -7417,7 +7440,7 @@ export default {9,{"input": [- 404,+ 406,"LogicFunctionIdInput!"]}@@ -7426,7 +7449,7 @@ export default {1,{"input": [- 404,+ 406,"LogicFunctionIdInput!"]}@@ -7663,25 +7686,25 @@ export default {48],"previewMessageCampaignAudience": [- 326,+ 328,{"input": [- 405,+ 407,"PreviewMessageCampaignAudienceInput!"]}],"messageSuppressions": [- 334,+ 336,{"input": [- 406,+ 408,"FindMessageSuppressionsInput!"]}],"unsubscribeTopics": [- 335+ 337],"myMessageChannels": [317,@@ -7695,7 +7718,7 @@ export default {317,{"filter": [- 407+ 409]}],@@ -7703,7 +7726,7 @@ export default {313],"getToolIndex": [- 345+ 347],"getToolInputSchema": [9,@@ -7715,10 +7738,10 @@ export default {}],"webhooks": [- 344+ 346],"webhook": [- 344,+ 346,{"id": [3,@@ -7727,7 +7750,7 @@ export default {}],"myMessageFolders": [- 386,+ 388,{"messageChannelId": [3@@ -7735,7 +7758,7 @@ export default {}],"myCalendarChannels": [- 381,+ 383,{"connectedAccountId": [3@@ -7743,17 +7766,17 @@ export default {}],"minimalMetadata": [- 397+ 399],"appKeyValue": [- 379,+ 381,{"key": [1,"String!"],"scope": [- 380+ 382]}],@@ -7770,7 +7793,7 @@ export default {228,{"filter": [- 408+ 410]}],@@ -7784,13 +7807,13 @@ export default {}],"findWorkspaceAiStats": [- 376+ 378],"chatThreads": [- 365+ 367],"chatThread": [- 365,+ 367,{"id": [3,@@ -7799,7 +7822,7 @@ export default {}],"chatMessages": [- 364,+ 366,{"threadId": [3,@@ -7808,7 +7831,7 @@ export default {}],"chatStreamCatchupChunks": [- 369,+ 371,{"threadId": [3,@@ -7817,13 +7840,13 @@ export default {}],"getAiSystemPromptPreview": [- 367+ 369],"skills": [- 363+ 365],"skill": [- 363,+ 365,{"id": [3,@@ -7832,7 +7855,7 @@ export default {}],"agentTurns": [- 375,+ 377,{"agentId": [3,@@ -7841,13 +7864,13 @@ export default {}],"timelineActivityTypes": [- 392+ 394],"metadataTranslations": [- 388,+ 390,{"input": [- 409,+ 411,"MetadataTranslationsInput!"]}@@ -7910,37 +7933,37 @@ export default {234],"eventLogs": [- 362,+ 364,{"input": [- 410,+ 412,"EventLogQueryInput!"]}],"pieChartData": [- 356,+ 358,{"input": [- 414,+ 416,"PieChartDataInput!"]}],"lineChartData": [- 354,+ 356,{"input": [- 415,+ 417,"LineChartDataInput!"]}],"barChartData": [- 351,+ 353,{"input": [- 416,+ 418,"BarChartDataInput!"]}@@ -7955,7 +7978,7 @@ export default {}],"getConnectedImapSmtpCaldavAccount": [- 342,+ 344,{"id": [3,@@ -7964,7 +7987,7 @@ export default {}],"getAutoCompleteAddress": [- 337,+ 339,{"address": [1,@@ -7983,7 +8006,7 @@ export default {}],"getAddressDetails": [- 339,+ 341,{"placeId": [1,@@ -8072,10 +8095,10 @@ export default {},"ObjectFilter": {"and": [- 403+ 405],"or": [- 403+ 405],"id": [31@@ -8129,7 +8152,7 @@ export default {},"FindMessageSuppressionsInput": {"reason": [- 332+ 334],"searchTerm": [1@@ -8185,10 +8208,10 @@ export default {},"EventLogQueryInput": {"table": [- 411+ 413],"filters": [- 412+ 414],"first": [28@@ -8209,7 +8232,7 @@ export default {1],"dateRange": [- 413+ 415],"recordId": [1@@ -8270,7 +8293,7 @@ export default {8,{"input": [- 418,+ 420,"AddQuerySubscriptionInput!"]}@@ -8279,7 +8302,7 @@ export default {8,{"input": [- 419,+ 421,"RemoveQueryFromEventStreamInput!"]}@@ -8288,7 +8311,7 @@ export default {154,{"inputs": [- 420,+ 422,"[CreateNavigationMenuItemInput!]!"]}@@ -8297,7 +8320,7 @@ export default {154,{"input": [- 420,+ 422,"CreateNavigationMenuItemInput!"]}@@ -8306,7 +8329,7 @@ export default {154,{"inputs": [- 421,+ 423,"[UpdateOneNavigationMenuItemInput!]!"]}@@ -8315,7 +8338,7 @@ export default {154,{"input": [- 421,+ 423,"UpdateOneNavigationMenuItemInput!"]}@@ -8389,7 +8412,7 @@ export default {151,{"file": [- 423,+ 425,"Upload!"]}@@ -8398,7 +8421,7 @@ export default {151,{"file": [- 423,+ 425,"Upload!"]}@@ -8407,7 +8430,7 @@ export default {151,{"file": [- 423,+ 425,"Upload!"],"fieldMetadataUniversalIdentifier": [@@ -8420,7 +8443,7 @@ export default {183,{"input": [- 424,+ 426,"CreateUsageLimitInput!"]}@@ -8429,7 +8452,7 @@ export default {183,{"input": [- 425,+ 427,"UpdateUsageLimitInput!"]}@@ -8447,7 +8470,7 @@ export default {55,{"input": [- 426,+ 428,"CreateViewFilterGroupInput!"]}@@ -8460,7 +8483,7 @@ export default {"String!"],"input": [- 427,+ 429,"UpdateViewFilterGroupInput!"]}@@ -8487,7 +8510,7 @@ export default {57,{"input": [- 428,+ 430,"CreateViewFilterInput!"]}@@ -8496,7 +8519,7 @@ export default {57,{"input": [- 429,+ 431,"UpdateViewFilterInput!"]}@@ -8505,7 +8528,7 @@ export default {57,{"input": [- 431,+ 433,"DeleteViewFilterInput!"]}@@ -8514,7 +8537,7 @@ export default {57,{"input": [- 432,+ 434,"DestroyViewFilterInput!"]}@@ -8523,7 +8546,7 @@ export default {63,{"input": [- 433,+ 435,"CreateViewInput!"]}@@ -8536,7 +8559,7 @@ export default {"String!"],"input": [- 434,+ 436,"UpdateViewInput!"]}@@ -8563,7 +8586,7 @@ export default {63,{"input": [- 435,+ 437,"UpsertViewWidgetInput!"]}@@ -8572,7 +8595,7 @@ export default {60,{"input": [- 441,+ 443,"CreateViewSortInput!"]}@@ -8581,7 +8604,7 @@ export default {60,{"input": [- 442,+ 444,"UpdateViewSortInput!"]}@@ -8590,7 +8613,7 @@ export default {8,{"input": [- 444,+ 446,"DeleteViewSortInput!"]}@@ -8599,7 +8622,7 @@ export default {8,{"input": [- 445,+ 447,"DestroyViewSortInput!"]}@@ -8608,7 +8631,7 @@ export default {53,{"input": [- 446,+ 448,"UpdateViewFieldInput!"]}@@ -8617,7 +8640,7 @@ export default {53,{"input": [- 448,+ 450,"CreateViewFieldInput!"]}@@ -8626,7 +8649,7 @@ export default {53,{"inputs": [- 448,+ 450,"[CreateViewFieldInput!]!"]}@@ -8635,7 +8658,7 @@ export default {53,{"input": [- 449,+ 451,"DeleteViewFieldInput!"]}@@ -8644,7 +8667,7 @@ export default {53,{"input": [- 450,+ 452,"DestroyViewFieldInput!"]}@@ -8653,7 +8676,7 @@ export default {62,{"input": [- 451,+ 453,"UpdateViewFieldGroupInput!"]}@@ -8662,7 +8685,7 @@ export default {62,{"input": [- 453,+ 455,"CreateViewFieldGroupInput!"]}@@ -8671,7 +8694,7 @@ export default {62,{"inputs": [- 453,+ 455,"[CreateViewFieldGroupInput!]!"]}@@ -8680,7 +8703,7 @@ export default {62,{"input": [- 454,+ 456,"DeleteViewFieldGroupInput!"]}@@ -8689,7 +8712,7 @@ export default {62,{"input": [- 455,+ 457,"DestroyViewFieldGroupInput!"]}@@ -8698,7 +8721,7 @@ export default {63,{"input": [- 456,+ 458,"UpsertFieldsWidgetInput!"]}@@ -8707,7 +8730,7 @@ export default {2,{"input": [- 459,+ 461,"CreateApiKeyInput!"]}@@ -8716,7 +8739,7 @@ export default {2,{"input": [- 460,+ 462,"UpdateApiKeyInput!"]}@@ -8725,7 +8748,7 @@ export default {2,{"input": [- 461,+ 463,"RevokeApiKeyInput!"]}@@ -8927,7 +8950,7 @@ export default {184,{"input": [- 462,+ 464,"CreateApprovedAccessDomainInput!"]}@@ -8936,7 +8959,7 @@ export default {8,{"input": [- 463,+ 465,"DeleteApprovedAccessDomainInput!"]}@@ -8945,7 +8968,7 @@ export default {184,{"input": [- 464,+ 466,"ValidateApprovedAccessDomainInput!"]}@@ -8954,7 +8977,7 @@ export default {125,{"input": [- 465,+ 467,"CreatePageLayoutTabInput!"]}@@ -8967,7 +8990,7 @@ export default {"String!"],"input": [- 466,+ 468,"UpdatePageLayoutTabInput!"]}@@ -8985,7 +9008,7 @@ export default {126,{"input": [- 467,+ 469,"CreatePageLayoutInput!"]}@@ -8998,7 +9021,7 @@ export default {"String!"],"input": [- 468,+ 470,"UpdatePageLayoutInput!"]}@@ -9020,7 +9043,7 @@ export default {"String!"],"input": [- 469,+ 471,"UpdatePageLayoutWithTabsInput!"]}@@ -9056,7 +9079,7 @@ export default {81,{"input": [- 472,+ 474,"CreatePageLayoutWidgetInput!"]}@@ -9069,7 +9092,7 @@ export default {"String!"],"input": [- 473,+ 475,"UpdatePageLayoutWidgetInput!"]}@@ -9087,7 +9110,7 @@ export default {10,{"input": [- 474,+ 476,"CreateAgentInput!"]}@@ -9096,7 +9119,7 @@ export default {10,{"input": [- 475,+ 477,"UpdateAgentInput!"]}@@ -9105,7 +9128,7 @@ export default {10,{"input": [- 402,+ 404,"AgentIdInput!"]}@@ -9114,7 +9137,7 @@ export default {23,{"input": [- 476,+ 478,"CreateOneObjectInput!"]}@@ -9123,7 +9146,7 @@ export default {23,{"input": [- 478,+ 480,"DeleteOneObjectInput!"]}@@ -9132,7 +9155,7 @@ export default {23,{"input": [- 479,+ 481,"UpdateOneObjectInput!"]}@@ -9141,7 +9164,7 @@ export default {258,{"input": [- 482,+ 484,"CreateOneIndexInput!"]}@@ -9150,7 +9173,7 @@ export default {258,{"input": [- 485,+ 487,"DeleteOneIndexInput!"]}@@ -9159,7 +9182,7 @@ export default {21,{"input": [- 404,+ 406,"LogicFunctionIdInput!"]}@@ -9168,7 +9191,7 @@ export default {21,{"input": [- 486,+ 488,"CreateLogicFunctionFromSourceInput!"]}@@ -9177,7 +9200,7 @@ export default {147,{"input": [- 487,+ 489,"ExecuteOneLogicFunctionInput!"]}@@ -9186,7 +9209,7 @@ export default {8,{"input": [- 488,+ 490,"UpdateLogicFunctionFromSourceInput!"]}@@ -9195,7 +9218,7 @@ export default {14,{"input": [- 490,+ 492,"CreateCommandMenuItemInput!"]}@@ -9204,7 +9227,7 @@ export default {14,{"input": [- 491,+ 493,"UpdateCommandMenuItemInput!"]}@@ -9231,7 +9254,7 @@ export default {13,{"input": [- 492,+ 494,"CreateFrontComponentInput!"]}@@ -9240,7 +9263,7 @@ export default {13,{"input": [- 493,+ 495,"UpdateFrontComponentInput!"]}@@ -9258,7 +9281,7 @@ export default {69,{"data": [- 495,+ 497,"ActivateWorkspaceInput!"]}@@ -9267,7 +9290,7 @@ export default {69,{"data": [- 496,+ 498,"UpdateWorkspaceInput!"]}@@ -9298,7 +9321,7 @@ export default {225,{"input": [- 497,+ 499,"CreateApplicationRegistrationInput!"]}@@ -9307,7 +9330,7 @@ export default {76,{"input": [- 498,+ 500,"UpdateApplicationRegistrationInput!"]}@@ -9334,7 +9357,7 @@ export default {198,{"input": [- 500,+ 502,"CreateApplicationRegistrationVariableInput!"]}@@ -9343,7 +9366,7 @@ export default {198,{"input": [- 501,+ 503,"UpdateApplicationRegistrationVariableInput!"]}@@ -9361,7 +9384,7 @@ export default {76,{"file": [- 423,+ 425,"Upload!"],"universalIdentifier": [@@ -9419,7 +9442,7 @@ export default {245,{"input": [- 503,+ 505,"TriggerInstallApplicationJobInput!"]}@@ -9428,7 +9451,7 @@ export default {246,{"input": [- 504,+ 506,"TriggerUninstallApplicationJobInput!"]}@@ -9441,7 +9464,7 @@ export default {"UUID!"],"input": [- 505,+ 507,"UpdateApplicationInput!"]}@@ -9462,7 +9485,7 @@ export default {250,{"input": [- 506,+ 508,"CreateOneFieldMetadataInput!"]}@@ -9471,7 +9494,7 @@ export default {250,{"input": [- 508,+ 510,"UpdateOneFieldMetadataInput!"]}@@ -9480,7 +9503,7 @@ export default {250,{"input": [- 510,+ 512,"DeleteOneFieldInput!"]}@@ -9489,7 +9512,7 @@ export default {59,{"input": [- 511,+ 513,"CreateViewGroupInput!"]}@@ -9498,7 +9521,7 @@ export default {59,{"inputs": [- 511,+ 513,"[CreateViewGroupInput!]!"]}@@ -9507,7 +9530,7 @@ export default {59,{"input": [- 512,+ 514,"UpdateViewGroupInput!"]}@@ -9516,7 +9539,7 @@ export default {59,{"inputs": [- 512,+ 514,"[UpdateViewGroupInput!]!"]}@@ -9525,7 +9548,7 @@ export default {59,{"input": [- 514,+ 516,"DeleteViewGroupInput!"]}@@ -9534,7 +9557,7 @@ export default {59,{"input": [- 515,+ 517,"DestroyViewGroupInput!"]}@@ -9556,7 +9579,7 @@ export default {48,{"createRoleInput": [- 516,+ 518,"CreateRoleInput!"]}@@ -9565,7 +9588,7 @@ export default {48,{"updateRoleInput": [- 517,+ 519,"UpdateRoleInput!"]}@@ -9583,7 +9606,7 @@ export default {45,{"upsertObjectPermissionsInput": [- 519,+ 521,"UpsertObjectPermissionsInput!"]}@@ -9592,7 +9615,7 @@ export default {46,{"upsertPermissionFlagsInput": [- 521,+ 523,"UpsertPermissionFlagsInput!"]}@@ -9601,7 +9624,7 @@ export default {40,{"upsertFieldPermissionsInput": [- 522,+ 524,"UpsertFieldPermissionsInput!"]}@@ -9610,7 +9633,7 @@ export default {271,{"input": [- 524,+ 526,"UpsertRowLevelPermissionPredicatesInput!"]}@@ -9638,43 +9661,43 @@ export default {}],"sendEmailViaEmailingDomain": [- 328,+ 330,{"input": [- 527,+ 529,"SendEmailViaDomainInput!"]}],"sendMessageCampaign": [- 329,+ 331,{"input": [- 528,+ 530,"SendMessageCampaignInput!"]}],"cancelMessageCampaign": [- 327,+ 329,{"input": [- 529,+ 531,"CancelMessageCampaignInput!"]}],"sendMessageCampaignTest": [- 328,+ 330,{"input": [- 530,+ 532,"SendMessageCampaignTestInput!"]}],"duplicateMessageList": [- 330,+ 332,{"id": [3,@@ -9683,10 +9706,10 @@ export default {}],"createMessageSuppression": [- 331,+ 333,{"input": [- 531,+ 533,"CreateMessageSuppressionInput!"]}@@ -9701,19 +9724,19 @@ export default {}],"createUnsubscribeTopic": [- 335,+ 337,{"input": [- 532,+ 534,"CreateUnsubscribeTopicInput!"]}],"updateUnsubscribeTopic": [- 335,+ 337,{"input": [- 533,+ 535,"UpdateUnsubscribeTopicInput!"]}@@ -9731,16 +9754,16 @@ export default {317,{"input": [- 534,+ 536,"UpdateMessageChannelInput!"]}],"createEmailGroupChannel": [- 325,+ 327,{"input": [- 536,+ 538,"CreateEmailGroupChannelInput!"]}@@ -9749,7 +9772,7 @@ export default {317,{"input": [- 537,+ 539,"UpdateEmailGroupChannelInput!"]}@@ -9767,7 +9790,7 @@ export default {317,{"input": [- 538,+ 540,"CreateAppMessageChannelInput!"]}@@ -9776,7 +9799,7 @@ export default {317,{"input": [- 539,+ 541,"UpdateAppMessageChannelInput!"]}@@ -9790,11 +9813,20 @@ export default {]}],+ "ingestAppMessages": [+ 326,+ {+ "input": [+ 542,+ "IngestAppMessagesInput!"+ ]+ }+ ],"createEmailingDomain": [313,{"input": [- 540,+ 546,"CreateEmailingDomainInput!"]}@@ -9818,34 +9850,34 @@ export default {}],"runAgent": [- 347,+ 349,{"input": [- 541,+ 547,"RunAgentInput!"]}],"createWebhook": [- 344,+ 346,{"input": [- 544,+ 550,"CreateWebhookInput!"]}],"updateWebhook": [- 344,+ 346,{"input": [- 545,+ 551,"UpdateWebhookInput!"]}],"deleteWebhook": [- 344,+ 346,{"id": [3,@@ -9854,37 +9886,37 @@ export default {}],"updateMessageFolder": [- 386,+ 388,{"input": [- 547,+ 553,"UpdateMessageFolderInput!"]}],"updateMessageFolders": [- 386,+ 388,{"input": [- 549,+ 555,"UpdateMessageFoldersInput!"]}],"updateCalendarChannel": [- 381,+ 383,{"input": [- 550,+ 556,"UpdateCalendarChannelInput!"]}],"setAppKeyValue": [- 379,+ 381,{"input": [- 552,+ 558,"SetAppKeyValueInput!"]}@@ -9897,24 +9929,24 @@ export default {"String!"],"scope": [- 380+ 382]}],"enqueueJob": [- 377,+ 379,{"input": [- 553,+ 559,"EnqueueJobInput!"]}],"enqueueJobs": [- 378,+ 380,{"input": [- 554,+ 560,"EnqueueJobsInput!"]}@@ -9923,16 +9955,16 @@ export default {8,{"input": [- 556,+ 562,"ReportAppConnectionAuthFailureInput!"]}],"createChatThread": [- 365+ 367],"sendChatMessage": [- 370,+ 372,{"threadId": [3,@@ -9953,13 +9985,13 @@ export default {1],"fileAttachments": [- 557,+ 563,"[FileAttachmentInput!]"]}],"retryChatMessage": [- 370,+ 372,{"threadId": [3,@@ -9971,7 +10003,7 @@ export default {}],"answerAgentChatQuestion": [- 370,+ 372,{"threadId": [3,@@ -9982,14 +10014,14 @@ export default {"UUID!"],"answers": [- 558,+ 564,"[AgentChatQuestionAnswerInput!]!"],"modelId": [1],"fileAttachments": [- 557,+ 563,"[FileAttachmentInput!]"]}@@ -10004,7 +10036,7 @@ export default {}],"renameChatThread": [- 365,+ 367,{"id": [3,@@ -10017,7 +10049,7 @@ export default {}],"archiveChatThread": [- 365,+ 367,{"id": [3,@@ -10026,7 +10058,7 @@ export default {}],"unarchiveChatThread": [- 365,+ 367,{"id": [3,@@ -10053,7 +10085,7 @@ export default {}],"startWorkspaceSetupChat": [- 372,+ 374,{"companyContext": [9@@ -10064,25 +10096,25 @@ export default {}],"createSkill": [- 363,+ 365,{"input": [- 559,+ 565,"CreateSkillInput!"]}],"updateSkill": [- 363,+ 365,{"input": [- 560,+ 566,"UpdateSkillInput!"]}],"deleteSkill": [- 363,+ 365,{"id": [3,@@ -10091,7 +10123,7 @@ export default {}],"activateSkill": [- 363,+ 365,{"id": [3,@@ -10100,7 +10132,7 @@ export default {}],"deactivateSkill": [- 363,+ 365,{"id": [3,@@ -10109,7 +10141,7 @@ export default {}],"evaluateAgentTurn": [- 374,+ 376,{"turnId": [3,@@ -10118,7 +10150,7 @@ export default {}],"runEvaluationInput": [- 375,+ 377,{"agentId": [3,@@ -10131,16 +10163,16 @@ export default {}],"updateTimelineActivityType": [- 392,+ 394,{"input": [- 561,+ 567,"UpdateTimelineActivityTypeInput!"]}],"resetTimelineActivityType": [- 392,+ 394,{"id": [3,@@ -10152,7 +10184,7 @@ export default {280,{"input": [- 562,+ 568,"GetAuthorizationUrlForSSOInput!"]}@@ -10318,7 +10350,7 @@ export default {283,{"input": [- 563+ 569]}],@@ -10330,7 +10362,7 @@ export default {"String!"],"file": [- 423,+ 425,"Upload!"]}@@ -10496,7 +10528,7 @@ export default {8,{"input": [- 564,+ 570,"UpdateWorkspaceMemberSettingsInput!"]}@@ -10530,7 +10562,7 @@ export default {235,{"input": [- 565,+ 571,"SetupOIDCSsoInput!"]}@@ -10539,7 +10571,7 @@ export default {235,{"input": [- 566,+ 572,"SetupSAMLSsoInput!"]}@@ -10548,7 +10580,7 @@ export default {231,{"input": [- 567,+ 573,"DeleteSsoInput!"]}@@ -10557,13 +10589,13 @@ export default {232,{"input": [- 568,+ 574,"EditSsoInput!"]}],"createObjectEvent": [- 359,+ 361,{"event": [1,@@ -10583,10 +10615,10 @@ export default {}],"trackAnalytics": [- 359,+ 361,{"type": [- 569,+ 575,"AnalyticsType!"],"name": [@@ -10601,7 +10633,7 @@ export default {}],"duplicateDashboard": [- 357,+ 359,{"id": [3,@@ -10626,25 +10658,25 @@ export default {295],"createCalendarEvent": [- 349,+ 351,{"input": [- 570,+ 576,"CreateCalendarEventInput!"]}],"sendEmail": [- 358,+ 360,{"input": [- 571,+ 577,"SendEmailInput!"]}],"startChannelSync": [- 348,+ 350,{"connectedAccountId": [3,@@ -10653,14 +10685,14 @@ export default {}],"saveImapSmtpCaldavAccount": [- 343,+ 345,{"handle": [1,"String!"],"connectionParameters": [- 573,+ 579,"EmailAccountConnectionParameters!"],"id": [@@ -10672,7 +10704,7 @@ export default {195,{"input": [- 575,+ 581,"UpdateLabPublicFeatureFlagInput!"]}@@ -10740,7 +10772,7 @@ export default {302,{"file": [- 423,+ 425,"Upload!"],"applicationUniversalIdentifier": [@@ -10765,7 +10797,7 @@ export default {"String!"],"files": [- 576,+ 582,"[ApplicationFileUploadRequestInput!]!"]}@@ -10888,7 +10920,7 @@ export default {3],"update": [- 422+ 424],"__typename": [1@@ -10961,7 +10993,7 @@ export default {3],"payload": [- 424+ 426],"__typename": [1@@ -11044,7 +11076,7 @@ export default {3],"update": [- 430+ 432],"__typename": [1@@ -11215,19 +11247,19 @@ export default {3],"view": [- 436+ 438],"viewFields": [- 437+ 439],"viewFilters": [- 438+ 440],"viewFilterGroups": [- 439+ 441],"viewSorts": [- 440+ 442],"__typename": [1@@ -11376,7 +11408,7 @@ export default {3],"update": [- 443+ 445],"__typename": [1@@ -11414,7 +11446,7 @@ export default {3],"update": [- 447+ 449],"__typename": [1@@ -11490,7 +11522,7 @@ export default {3],"update": [- 452+ 454],"__typename": [1@@ -11554,10 +11586,10 @@ export default {3],"groups": [- 457+ 459],"fields": [- 458+ 460],"__typename": [1@@ -11577,7 +11609,7 @@ export default {8],"fields": [- 458+ 460],"__typename": [1@@ -11748,7 +11780,7 @@ export default {8],"tabs": [- 470+ 472],"__typename": [1@@ -11771,7 +11803,7 @@ export default {85],"widgets": [- 471+ 473],"__typename": [1@@ -11936,7 +11968,7 @@ export default {},"CreateOneObjectInput": {"object": [- 477+ 479],"__typename": [1@@ -11996,7 +12028,7 @@ export default {},"UpdateOneObjectInput": {"update": [- 480+ 482],"id": [3@@ -12049,7 +12081,7 @@ export default {24],"translations": [- 481+ 483],"__typename": [1@@ -12071,7 +12103,7 @@ export default {},"CreateOneIndexInput": {"index": [- 483+ 485],"__typename": [1@@ -12082,7 +12114,7 @@ export default {3],"fields": [- 484+ 486],"indexType": [259@@ -12167,7 +12199,7 @@ export default {3],"update": [- 489+ 491],"__typename": [1@@ -12336,7 +12368,7 @@ export default {3],"update": [- 494+ 496],"__typename": [1@@ -12463,7 +12495,7 @@ export default {1],"update": [- 499+ 501],"__typename": [1@@ -12517,7 +12549,7 @@ export default {1],"update": [- 502+ 504],"__typename": [1@@ -12563,7 +12595,7 @@ export default {},"CreateOneFieldMetadataInput": {"field": [- 507+ 509],"__typename": [1@@ -12642,7 +12674,7 @@ export default {3],"update": [- 509+ 511],"__typename": [1@@ -12707,7 +12739,7 @@ export default {9],"translations": [- 481+ 483],"__typename": [1@@ -12746,7 +12778,7 @@ export default {3],"update": [- 513+ 515],"__typename": [1@@ -12831,7 +12863,7 @@ export default {},"UpdateRoleInput": {"update": [- 518+ 520],"id": [3@@ -12886,7 +12918,7 @@ export default {3],"objectPermissions": [- 520+ 522],"__typename": [1@@ -12928,7 +12960,7 @@ export default {3],"fieldPermissions": [- 523+ 525],"__typename": [1@@ -12959,10 +12991,10 @@ export default {3],"predicates": [- 525+ 527],"predicateGroups": [- 526+ 528],"__typename": [1@@ -13110,7 +13142,7 @@ export default {1],"visibility": [- 336+ 338],"__typename": [1@@ -13127,7 +13159,7 @@ export default {1],"visibility": [- 336+ 338],"__typename": [1@@ -13138,7 +13170,7 @@ export default {3],"update": [- 535+ 537],"__typename": [1@@ -13226,6 +13258,55 @@ export default {1]},+ "IngestAppMessagesInput": {+ "messageChannelId": [+ 3+ ],+ "messages": [+ 543+ ],+ "__typename": [+ 1+ ]+ },+ "AppMessageInput": {+ "externalId": [+ 1+ ],+ "threadExternalId": [+ 1+ ],+ "subject": [+ 1+ ],+ "text": [+ 1+ ],+ "receivedAt": [+ 4+ ],+ "participants": [+ 544+ ],+ "__typename": [+ 1+ ]+ },+ "AppMessageParticipantInput": {+ "role": [+ 545+ ],+ "handle": [+ 1+ ],+ "displayName": [+ 1+ ],+ "__typename": [+ 1+ ]+ },+ "MessageParticipantRole": {},"CreateEmailingDomainInput": {"domain": [1@@ -13245,7 +13326,7 @@ export default {3],"messages": [- 542+ 548],"__typename": [1@@ -13253,7 +13334,7 @@ export default {},"RunAgentMessageInput": {"role": [- 543+ 549],"content": [1@@ -13288,7 +13369,7 @@ export default {3],"update": [- 546+ 552],"__typename": [1@@ -13316,7 +13397,7 @@ export default {3],"update": [- 548+ 554],"__typename": [1@@ -13335,7 +13416,7 @@ export default {3],"update": [- 548+ 554],"__typename": [1@@ -13346,7 +13427,7 @@ export default {3],"update": [- 551+ 557],"__typename": [1@@ -13354,13 +13435,13 @@ export default {},"UpdateCalendarChannelInputUpdates": {"visibility": [- 384+ 386],"isContactAutoCreationEnabled": [8],"contactAutoCreationPolicy": [- 385+ 387],"isSyncEnabled": [8@@ -13377,7 +13458,7 @@ export default {9],"scope": [- 380+ 382],"__typename": [1@@ -13411,7 +13492,7 @@ export default {9],"jobs": [- 555+ 561],"retryLimit": [28@@ -13533,7 +13614,7 @@ export default {8],"translations": [- 481+ 483],"__typename": [1@@ -13699,7 +13780,7 @@ export default {1],"files": [- 572+ 578],"__typename": [1@@ -13721,13 +13802,13 @@ export default {1],"IMAP": [- 574+ 580],"SMTP": [- 574+ 580],"CALDAV": [- 574+ 580],"__typename": [1@@ -13792,13 +13873,13 @@ export default {272,{"input": [- 578,+ 584,"LogicFunctionLogsInput!"]}],"onAgentChatEvent": [- 371,+ 373,{"threadId": [3,@@ -13807,10 +13888,10 @@ export default {}],"eventLogsLive": [- 360,+ 362,{"table": [- 411,+ 413,"EventLogTable!"]}diff --git a/packages/twenty-docs/developers/extend/apps/logic/messaging-channels.mdx b/packages/twenty-docs/developers/extend/apps/logic/messaging-channels.mdxindex 111ce8c0834..7efd1e725d8 100644--- a/packages/twenty-docs/developers/extend/apps/logic/messaging-channels.mdx+++ b/packages/twenty-docs/developers/extend/apps/logic/messaging-channels.mdx@@ -10,8 +10,6 @@ Twenty's message model is deliberately channel-neutral: a message has participan<Note>**Beta — and possibly not live on your instance yet.** App-owned message channels are new; the API described here may change, and it may not be available on the version of Twenty you are running. Check that `createMessageChannel` exists in your SDK before building on it.--This page covers **declaring and owning a channel**. Writing messages into it is a separate step, documented alongside the ingestion API.</Note>## Prerequisites@@ -69,6 +67,71 @@ Choose based on how private the provider's messages are, not on what is convenie`visibility` is the only thing standing between one member's private conversations and the rest of the workspace. Twenty deliberately makes you state it rather than inheriting a default that might over-share.</Warning>+## Ingesting messages++Once the channel exists, `ingestMessages` writes conversations into it. Threading, de-duplication, channel association and per-message privacy are handled server-side — the same path Twenty's own email import uses.++```ts src/logic-functions/handlers/linkedin-inbound-handler.ts+import { ingestMessages } from 'twenty-sdk/logic-function';+import { MessageParticipantRole } from 'twenty-shared/types';++export const linkedinInboundHandler = async (payload: LinkedinWebhookPayload) => {+ const ingested = await ingestMessages({+ messageChannelId: payload.channelId,+ messages: payload.events.map((event) => ({+ externalId: event.messageUrn,+ threadExternalId: event.conversationUrn,+ text: event.body,+ receivedAt: new Date(event.createdAt),+ participants: [+ {+ role: MessageParticipantRole.FROM,+ handle: event.sender.memberUrn,+ displayName: event.sender.name,+ },+ ...event.recipients.map((recipient) => ({+ role: MessageParticipantRole.TO,+ handle: recipient.memberUrn,+ displayName: recipient.name,+ })),+ ],+ })),+ });++ return { ingested: ingested.length };+};+```++### What the server does for you++**De-duplication.** `externalId` is the key. Ingesting the same one twice creates nothing and changes nothing, so a redelivered webhook is safe to replay and a backfill may overlap a live stream. The returned `messageId` is stable across replays. Calls against one channel are serialised, so a redelivery arriving while its original is still being written waits rather than racing it.++**Threading.** Messages sharing a `threadExternalId` land in one Message Thread, which then appears on the Person, Company and Opportunity records of its participants.++**Direction.** Derived, not declared: the message is outgoing when the `FROM` participant's handle equals the channel's handle, incoming otherwise. Exactly one participant must carry `FROM` — direction, the thread's sender column and the timeline preview all read it, so a message without one is rejected rather than rendering as an empty conversation.++**De-duplication is scoped to the channel.** `externalId` only has to be unique within one channel, which is what most providers actually guarantee — plenty number messages per conversation or per account. The consequence is that two members in the same provider conversation each get their own Message rather than a shared one. That is deliberate: merging them would require every app to guarantee a global namespace it does not control, and getting it wrong would attach one member's body to another member's channel.++**Privacy.** Each message inherits its channel's `visibility`. Nothing you ingest is more visible than the channel you ingest it into.++### Batching++One call is one transaction inside one logic-function timeout, capped at **100 messages**. Page a provider backfill rather than sending it whole:++```ts+for (const page of chunk(allHistoricalMessages, 100)) {+ await ingestMessages({ messageChannelId, messages: page });+}+```++A batch is all-or-nothing, and repeating one `externalId` inside a single batch is rejected — de-duplicate before you send. A message body is capped at 256KB.++### Linking participants to People++Twenty matches email participants to People by email address. That will not match a LinkedIn URN or a phone number, so ingested participants start unlinked, and an unlinked thread does not appear on anyone's record page.++Until app-supplied identity linking lands, resolve contacts yourself: look the participant up by whatever field your provider's identity lives in (`Person.linkedinLink`, a custom field your app added), then attach the thread to that record. See [Extending objects](/developers/extend/apps/data/extending-objects) for adding an identity field of your own.+## Listing and updating channels```ts@@ -90,11 +153,11 @@ await updateMessageChannel({ id: channel.id, displayName: 'Ada (LinkedIn)' });await updateMessageChannel({ id: channel.id, isSyncEnabled: false });```-Changing `visibility` through `updateMessageChannel` re-scopes every message already ingested into the channel, not only the ones that follow.+Changing `visibility` through `updateMessageChannel` re-scopes every message already ingested into the channel, not only the ones that follow. Ingesting into a channel with `isSyncEnabled: false` is rejected, so pausing a channel stops the stream without deleting anything.Your app only ever sees channels created against its own connections. Channels belonging to other apps, and Twenty's own email channels, are invisible to it.-A channel is also only reachable by the person whose connection it speaks through, when that connection is private to them. A run triggered by another member of the workspace cannot see it or change it; a run with nobody behind it — a cron, a webhook, an install hook — acts as the application and reaches every channel the app owns.+A channel is also only reachable by the person whose connection it speaks through, when that connection is private to them. A run triggered by another member of the workspace cannot see it, change it or ingest into it; a run with nobody behind it — a cron, a webhook, an install hook — acts as the application and reaches every channel the app owns.## Retiring a channel@@ -124,3 +187,4 @@ Deleting a channel deletes the messages ingested through it, and any thread left- **It is not polled.** Twenty's import pipeline polls mailbox providers on a cron. App channels are push-only: nothing fetches on your behalf, so your app is responsible for getting messages in, via a webhook route or a cron logic function.- **It does not send.** Outbound delivery is not yet routed to apps; a reply composed in Twenty cannot reach your provider. Until it is, link out to the provider's own UI for replies.- **It does not resolve contacts.** Twenty matches email participants to People by email address, which will not match a LinkedIn URN. Link participants to People explicitly when you ingest them.+- **It does not create contacts.** Twenty's auto-creation derives people and companies from email domains, which is meaningless for most providers, so it is off for app channels.diff --git a/packages/twenty-docs/developers/extend/apps/logic/overview.mdx b/packages/twenty-docs/developers/extend/apps/logic/overview.mdxindex 2b24f99e429..89cd3fba3d9 100644--- a/packages/twenty-docs/developers/extend/apps/logic/overview.mdx+++ b/packages/twenty-docs/developers/extend/apps/logic/overview.mdx@@ -35,7 +35,7 @@ A Twenty app's **logic layer** is the code that *runs* — server-side TypeScripOAuth credentials your app holds for third-party services — Linear, GitHub, Slack, and more.</Card><Card title="Messaging Channels" icon="messages" href="/developers/extend/apps/logic/messaging-channels">- Bring conversations from any provider into Twenty's Message and Message Thread records.+ Bring conversations from any provider into Twenty's Message and Message Thread records — threading and de-duplication included.</Card><Card title="Key-Value Store" icon="database" href="/developers/extend/apps/logic/key-value-store">Persist state between logic function runs — caches, cursors, and cross-workspace claims.diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.tsindex d95228c3d31..dee5350988d 100644--- a/packages/twenty-front/src/generated-metadata/graphql.ts+++ b/packages/twenty-front/src/generated-metadata/graphql.ts@@ -304,6 +304,21 @@ export enum AppKeyValueScope {WORKSPACE = 'WORKSPACE'}+export type AppMessageInput = {+ externalId: Scalars['String']['input'];+ participants: Array<AppMessageParticipantInput>;+ receivedAt: Scalars['DateTime']['input'];+ subject?: InputMaybe<Scalars['String']['input']>;+ text: Scalars['String']['input'];+ threadExternalId: Scalars['String']['input'];+};++export type AppMessageParticipantInput = {+ displayName?: InputMaybe<Scalars['String']['input']>;+ handle: Scalars['String']['input'];+ role: MessageParticipantRole;+};+export type Application = {__typename?: 'Application';agents: Array<Agent>;@@ -2399,6 +2414,23 @@ export enum IndexType {GIN = 'GIN'}+export type IngestAppMessagesInput = {+ messageChannelId: Scalars['UUID']['input'];+ messages: Array<AppMessageInput>;+};++export type IngestAppMessagesOutput = {+ __typename?: 'IngestAppMessagesOutput';+ messages: Array<IngestedAppMessage>;+};++export type IngestedAppMessage = {+ __typename?: 'IngestedAppMessage';+ externalId: Scalars['String']['output'];+ messageId: Scalars['UUID']['output'];+ messageThreadId: Scalars['UUID']['output'];+};+export type InitiateTwoFactorAuthenticationProvisioning = {__typename?: 'InitiateTwoFactorAuthenticationProvisioning';uri: Scalars['String']['output'];@@ -2768,6 +2800,14 @@ export enum MessageFolderPendingSyncAction {NONE = 'NONE'}+export enum MessageParticipantRole {+ BCC = 'BCC',+ CC = 'CC',+ FROM = 'FROM',+ REPLY_TO = 'REPLY_TO',+ TO = 'TO'+}+export type MessageSuppression = {__typename?: 'MessageSuppression';createdAt: Scalars['DateTime']['output'];@@ -3033,6 +3073,7 @@ export type Mutation = {getLoginTokenFromCredentials: LoginToken;goBackToPreviousOnboardingStep: OnboardingStepNavigation;impersonate: Impersonate;+ ingestAppMessages: IngestAppMessagesOutput;initiateOTPProvisioning: InitiateTwoFactorAuthenticationProvisioning;initiateOTPProvisioningForAuthenticatedUser: InitiateTwoFactorAuthenticationProvisioning;installApplication: Application;@@ -3815,6 +3856,11 @@ export type MutationImpersonateArgs = {};+export type MutationIngestAppMessagesArgs = {+ input: IngestAppMessagesInput;+};++export type MutationInitiateOtpProvisioningArgs = {loginToken: Scalars['String']['input'];origin: Scalars['String']['input'];diff --git a/packages/twenty-sdk/src/sdk/logic-function/index.ts b/packages/twenty-sdk/src/sdk/logic-function/index.tsindex 6de8253007f..119542d97d3 100644--- a/packages/twenty-sdk/src/sdk/logic-function/index.ts+++ b/packages/twenty-sdk/src/sdk/logic-function/index.ts@@ -66,6 +66,12 @@ export type { ListMessageChannelsFilter } from '@/sdk/logic-function/messaging/lexport { updateMessageChannel } from '@/sdk/logic-function/messaging/update-message-channel';export type { UpdateMessageChannelInput } from '@/sdk/logic-function/messaging/update-message-channel';export { deleteMessageChannel } from '@/sdk/logic-function/messaging/delete-message-channel';+export { ingestMessages } from '@/sdk/logic-function/messaging/ingest-messages';+export type {+ IngestedMessage,+ IngestMessage,+ IngestMessageParticipant,+} from '@/sdk/logic-function/messaging/types/ingest-message.type';export type { AppMessageChannel } from '@/sdk/logic-function/messaging/types/app-message-channel.type';export { runAgent } from '@/sdk/logic-function/agents/run-agent';diff --git a/packages/twenty-sdk/src/sdk/logic-function/messaging/ingest-messages.ts b/packages/twenty-sdk/src/sdk/logic-function/messaging/ingest-messages.tsnew file mode 100644index 00000000000..4862b196765--- /dev/null+++ b/packages/twenty-sdk/src/sdk/logic-function/messaging/ingest-messages.ts@@ -0,0 +1,43 @@+import {+ type IngestMessage,+ type IngestedMessage,+} from '@/sdk/logic-function/messaging/types/ingest-message.type';+import { postGraphqlRequest } from '@/sdk/logic-function/utils/post-graphql-request.util';++const INGEST_APP_MESSAGES_MUTATION = `+ mutation IngestAppMessages($input: IngestAppMessagesInput!) {+ ingestAppMessages(input: $input) {+ messages {+ externalId+ messageId+ messageThreadId+ }+ }+ }+`;++// Writes messages into Twenty's Message/Message Thread records. Threading,+// de-duplication, channel association and per-message privacy are handled+// server-side; the whole batch lands in one transaction.+//+// At most 100 messages per call: one call is one transaction inside one+// logic-function timeout, so page a provider backfill rather than sending it+// whole.+export const ingestMessages = async ({+ messageChannelId,+ messages,+}: {+ messageChannelId: string;+ messages: IngestMessage[];+}): Promise<IngestedMessage[]> => {+ const { ingestAppMessages } = await postGraphqlRequest<+ { input: { messageChannelId: string; messages: IngestMessage[] } },+ { ingestAppMessages: { messages: IngestedMessage[] } }+ >({+ query: INGEST_APP_MESSAGES_MUTATION,+ variables: { input: { messageChannelId, messages } },+ caller: 'ingestMessages',+ });++ return ingestAppMessages.messages;+};diff --git a/packages/twenty-sdk/src/sdk/logic-function/messaging/types/ingest-message.type.ts b/packages/twenty-sdk/src/sdk/logic-function/messaging/types/ingest-message.type.tsnew file mode 100644index 00000000000..75d7ed1a317--- /dev/null+++ b/packages/twenty-sdk/src/sdk/logic-function/messaging/types/ingest-message.type.ts@@ -0,0 +1,34 @@+import { type MessageParticipantRole } from 'twenty-shared/types';++export type IngestMessageParticipant = {+ // 'FROM' marks the sender; exactly one participant must carry it. When its+ // handle equals the channel's, the message is recorded as outgoing.+ role: MessageParticipantRole;+ // The participant's identity on the provider, in the same namespace as the+ // channel's own handle.+ handle: string;+ displayName?: string;+};++export type IngestMessage = {+ // The provider's id for this message. Ingesting it twice is a no-op, so+ // redelivered webhooks are safe to replay.+ externalId: string;+ // The provider's id for the conversation. Messages sharing one land in the+ // same Message Thread.+ threadExternalId: string;+ // Most non-email providers have none; the thread falls back to its+ // participants for a title.+ subject?: string;+ text: string;+ receivedAt: Date;+ participants: IngestMessageParticipant[];+};++export type IngestedMessage = {+ externalId: string;+ // Stable across re-ingestion, so it is safe to hang timeline activities or+ // your own records off it.+ messageId: string;+ messageThreadId: string;+};diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/__tests__/ingest-app-messages.input.spec.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/__tests__/ingest-app-messages.input.spec.tsnew file mode 100644index 00000000000..4ef99a16073--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/__tests__/ingest-app-messages.input.spec.ts@@ -0,0 +1,50 @@+import { GraphQLISODateTime } from '@nestjs/graphql';++import { plainToInstance } from 'class-transformer';+import { validate } from 'class-validator';+import { MessageParticipantRole } from 'twenty-shared/types';++import { IngestAppMessagesInput } from 'src/engine/metadata-modules/message-channel/dtos/ingest-app-messages.input';++const MESSAGE_CHANNEL_ID = '55555555-5555-4555-8555-555555555555';++const anInput = (receivedAt: unknown) => ({+ messageChannelId: MESSAGE_CHANNEL_ID,+ messages: [+ {+ externalId: 'urn:li:message:1',+ threadExternalId: 'urn:li:conversation:1',+ text: 'Are you free at 3?',+ receivedAt,+ participants: [+ {+ role: MessageParticipantRole.FROM,+ handle: 'urn:li:person:ada',+ },+ ],+ },+ ],+});++const validationErrors = (receivedAt: unknown) =>+ validate(plainToInstance(IngestAppMessagesInput, anInput(receivedAt)));++// `receivedAt` is the one field whose wire representation is not the type the+// validator checks, so it is the one that can silently reject every call.+describe('IngestAppMessagesInput receivedAt', () => {+ it('accepts what the GraphQL DateTime scalar produces', async () => {+ const fromTheScalar = GraphQLISODateTime.parseValue(+ '2026-09-14T10:00:00.000Z',+ );++ expect(await validationErrors(fromTheScalar)).toHaveLength(0);+ });++ it('accepts a raw ISO string, so the contract does not rely on the scalar', async () => {+ expect(await validationErrors('2026-09-14T10:00:00.000Z')).toHaveLength(0);+ });++ it('rejects a value that is not a date at all', async () => {+ expect(await validationErrors('not a date')).not.toHaveLength(0);+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/ingest-app-messages.input.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/ingest-app-messages.input.tsnew file mode 100644index 00000000000..5c3d2210f1b--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/ingest-app-messages.input.ts@@ -0,0 +1,117 @@+import { Field, InputType, registerEnumType } from '@nestjs/graphql';++import { Type } from 'class-transformer';+import {+ ArrayMaxSize,+ ArrayMinSize,+ IsArray,+ IsDate,+ IsEnum,+ IsNotEmpty,+ IsOptional,+ IsString,+ IsUUID,+ MaxLength,+ ValidateNested,+} from 'class-validator';+import { MessageParticipantRole } from 'twenty-shared/types';++import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';++// Only registered here: the role is stored as a SELECT on messageParticipant,+// so app ingestion is the first surface to expose it as a GraphQL enum.+registerEnumType(MessageParticipantRole, { name: 'MessageParticipantRole' });++// One request stays inside a single transaction and one logic-function+// timeout, so a provider backfill has to page rather than send everything.+export const INGEST_APP_MESSAGES_MAX_BATCH_SIZE = 100;++// Comfortably above a long plain-text conversation message, well below what+// would threaten the row or the transaction at full batch size.+export const MAX_APP_MESSAGE_TEXT_LENGTH = 262_144;++@InputType('AppMessageParticipantInput')+export class AppMessageParticipantInput {+ @Field(() => MessageParticipantRole)+ @IsEnum(MessageParticipantRole)+ @IsNotEmpty()+ role: MessageParticipantRole;++ @Field()+ @IsString()+ @IsNotEmpty()+ @MaxLength(512)+ handle: string;++ @Field({ nullable: true })+ @IsOptional()+ @IsString()+ @MaxLength(255)+ displayName?: string;+}++@InputType('AppMessageInput')+export class AppMessageInput {+ // The provider's own id for this message. Re-ingesting the same externalId+ // updates nothing and creates nothing, so redelivered webhooks are safe.+ @Field()+ @IsString()+ @IsNotEmpty()+ @MaxLength(512)+ externalId: string;++ // The provider's own id for the conversation. Messages sharing one land in+ // the same Message Thread.+ @Field()+ @IsString()+ @IsNotEmpty()+ @MaxLength(512)+ threadExternalId: string;++ @Field({ nullable: true })+ @IsOptional()+ @IsString()+ @MaxLength(998)+ subject?: string;++ // Bounded like every other string here. One call is already 100 messages in+ // a single workspace transaction, and unlike email import nothing upstream+ // caps this, so an unbounded body would make the batch limit meaningless.+ @Field()+ @IsString()+ @MaxLength(MAX_APP_MESSAGE_TEXT_LENGTH)+ text: string;++ // GraphQL's DateTime scalar already hands the pipe a Date, so `@IsDate`+ // passes without this. It is here so the contract does not depend on that:+ // a timestamp scalar mode, or any non-GraphQL caller, would otherwise fail+ // validation on a value the field is meant to accept.+ @Field(() => Date)+ @Type(() => Date)+ @IsDate()+ receivedAt: Date;++ @Field(() => [AppMessageParticipantInput])+ @IsArray()+ @ArrayMinSize(1)+ @ArrayMaxSize(256)+ @ValidateNested({ each: true })+ @Type(() => AppMessageParticipantInput)+ participants: AppMessageParticipantInput[];+}++@InputType('IngestAppMessagesInput')+export class IngestAppMessagesInput {+ @Field(() => UUIDScalarType)+ @IsUUID()+ @IsNotEmpty()+ messageChannelId: string;++ @Field(() => [AppMessageInput])+ @IsArray()+ @ArrayMinSize(1)+ @ArrayMaxSize(INGEST_APP_MESSAGES_MAX_BATCH_SIZE)+ @ValidateNested({ each: true })+ @Type(() => AppMessageInput)+ messages: AppMessageInput[];+}diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/ingest-app-messages.output.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/ingest-app-messages.output.tsnew file mode 100644index 00000000000..6dd74a1e702--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/ingest-app-messages.output.ts@@ -0,0 +1,23 @@+import { Field, ObjectType } from '@nestjs/graphql';++import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';++@ObjectType('IngestedAppMessage')+export class IngestedAppMessageDTO {+ @Field()+ externalId: string;++ // Stable across re-ingestion of the same externalId, so it is safe to hang+ // timeline activities or app records off it.+ @Field(() => UUIDScalarType)+ messageId: string;++ @Field(() => UUIDScalarType)+ messageThreadId: string;+}++@ObjectType('IngestAppMessagesOutput')+export class IngestAppMessagesOutput {+ @Field(() => [IngestedAppMessageDTO])+ messages: IngestedAppMessageDTO[];+}diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/message-channel-metadata.module.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/message-channel-metadata.module.tsindex 9de9e00607a..2cb02cc075f 100644--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/message-channel-metadata.module.ts+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/message-channel-metadata.module.ts@@ -1,6 +1,7 @@import { Module } from '@nestjs/common';import { TypeOrmModule } from '@nestjs/typeorm';+import { CacheLockModule } from 'src/engine/core-modules/cache-lock/cache-lock.module';import { EmailingDomainModule } from 'src/engine/core-modules/emailing-domain/emailing-domain.module';import { ConnectedAccountMetadataModule } from 'src/engine/metadata-modules/connected-account/connected-account-metadata.module';import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';@@ -8,8 +9,10 @@ import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channeimport { MessageChannelGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules/message-channel/interceptors/message-channel-graphql-api-exception.interceptor';import { MessageChannelMetadataService } from 'src/engine/metadata-modules/message-channel/message-channel-metadata.service';import { ApplicationMessageChannelsResolver } from 'src/engine/metadata-modules/message-channel/resolvers/application-message-channels.resolver';+import { ApplicationMessageIngestionResolver } from 'src/engine/metadata-modules/message-channel/resolvers/application-message-ingestion.resolver';import { MessageChannelResolver } from 'src/engine/metadata-modules/message-channel/resolvers/message-channel.resolver';import { ApplicationMessageChannelsService } from 'src/engine/metadata-modules/message-channel/services/application-message-channels.service';+import { ApplicationMessageIngestionService } from 'src/engine/metadata-modules/message-channel/services/application-message-ingestion.service';import { MessageFolderEntity } from 'src/engine/metadata-modules/message-folder/entities/message-folder.entity';import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permissions.module';import { WorkspaceEventEmitterModule } from 'src/engine/workspace-event-emitter/workspace-event-emitter.module';@@ -22,6 +25,7 @@ import { MessagingImportManagerModule } from 'src/modules/messaging/message-impoMessageFolderEntity,ConnectedAccountEntity,]),+ CacheLockModule,PermissionsModule,ConnectedAccountMetadataModule,MessagingImportManagerModule,@@ -33,6 +37,8 @@ import { MessagingImportManagerModule } from 'src/modules/messaging/message-impoMessageChannelResolver,ApplicationMessageChannelsService,ApplicationMessageChannelsResolver,+ ApplicationMessageIngestionService,+ ApplicationMessageIngestionResolver,MessageChannelGraphqlApiExceptionInterceptor,],exports: [MessageChannelMetadataService],diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/application-message-ingestion.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/application-message-ingestion.resolver.tsnew file mode 100644index 00000000000..56615fb4391--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/application-message-ingestion.resolver.ts@@ -0,0 +1,43 @@+import { UseGuards, UseInterceptors, UsePipes } from '@nestjs/common';+import { Args, Mutation } from '@nestjs/graphql';++import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorators/metadata-resolver.decorator';+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';+import { ResolverValidationPipe } from 'src/engine/core-modules/graphql/pipes/resolver-validation.pipe';+import { type FlatWorkspace } from 'src/engine/core-modules/workspace/types/flat-workspace.type';+import { AuthApplication } from 'src/engine/decorators/auth/auth-application.decorator';+import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';+import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';+import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';+import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';+import { IngestAppMessagesInput } from 'src/engine/metadata-modules/message-channel/dtos/ingest-app-messages.input';+import { IngestAppMessagesOutput } from 'src/engine/metadata-modules/message-channel/dtos/ingest-app-messages.output';+import { MessageChannelGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules/message-channel/interceptors/message-channel-graphql-api-exception.interceptor';+import { ApplicationMessageIngestionService } from 'src/engine/metadata-modules/message-channel/services/application-message-ingestion.service';++@UseGuards(WorkspaceAuthGuard, NoPermissionGuard)+@UseInterceptors(MessageChannelGraphqlApiExceptionInterceptor)+@UsePipes(ResolverValidationPipe)+@MetadataResolver()+export class ApplicationMessageIngestionResolver {+ constructor(+ private readonly applicationMessageIngestionService: ApplicationMessageIngestionService,+ ) {}++ @Mutation(() => IngestAppMessagesOutput)+ async ingestAppMessages(+ @AuthApplication() application: FlatApplication,+ @AuthWorkspace() workspace: FlatWorkspace,+ @AuthUserWorkspaceId({ allowUndefined: true })+ userWorkspaceId: string | undefined,+ @Args('input') input: IngestAppMessagesInput,+ ): Promise<IngestAppMessagesOutput> {+ return this.applicationMessageIngestionService.ingest({+ applicationId: application.id,+ workspaceId: workspace.id,+ requestUserWorkspaceId: userWorkspaceId ?? null,+ messageChannelId: input.messageChannelId,+ messages: input.messages,+ });+ }+}diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/services/__tests__/application-message-ingestion.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/services/__tests__/application-message-ingestion.service.spec.tsnew file mode 100644index 00000000000..a4d0c853135--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/services/__tests__/application-message-ingestion.service.spec.ts@@ -0,0 +1,338 @@+import { Test, type TestingModule } from '@nestjs/testing';++import {+ MessageChannelType,+ MessageParticipantRole,+} from 'twenty-shared/types';++import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';+import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';+import { type AppMessageInput } from 'src/engine/metadata-modules/message-channel/dtos/ingest-app-messages.input';+import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';+import { MessageChannelExceptionCode } from 'src/engine/metadata-modules/message-channel/message-channel.exception';+import { ApplicationMessageChannelsService } from 'src/engine/metadata-modules/message-channel/services/application-message-channels.service';+import { ApplicationMessageIngestionService } from 'src/engine/metadata-modules/message-channel/services/application-message-ingestion.service';+import { MessageDirection } from 'src/modules/messaging/common/enums/message-direction.enum';+import { MessagingSaveMessagesAndEnqueueContactCreationService } from 'src/modules/messaging/message-import-manager/services/messaging-save-messages-and-enqueue-contact-creation.service';++const APPLICATION_ID = '11111111-1111-4111-8111-111111111111';+const WORKSPACE_ID = '33333333-3333-4333-8333-333333333333';+const CONNECTED_ACCOUNT_ID = '44444444-4444-4444-8444-444444444444';+const MESSAGE_CHANNEL_ID = '55555555-5555-4555-8555-555555555555';+const CHANNEL_HANDLE = 'urn:li:person:self';++describe('ApplicationMessageIngestionService', () => {+ let service: ApplicationMessageIngestionService;+ let channelsService: jest.Mocked<ApplicationMessageChannelsService>;+ let saveMessagesService: jest.Mocked<MessagingSaveMessagesAndEnqueueContactCreationService>;+ let cacheLockService: { withLock: jest.Mock };++ const scope = {+ applicationId: APPLICATION_ID,+ workspaceId: WORKSPACE_ID,+ requestUserWorkspaceId: null,+ messageChannelId: MESSAGE_CHANNEL_ID,+ };++ const aMessage = (overrides: Partial<AppMessageInput> = {}) =>+ ({+ externalId: 'msg-1',+ threadExternalId: 'thread-1',+ text: 'hello',+ receivedAt: new Date('2026-01-01T00:00:00Z'),+ participants: [+ {+ role: MessageParticipantRole.FROM,+ handle: 'urn:li:person:ada',+ displayName: 'Ada',+ },+ { role: MessageParticipantRole.TO, handle: CHANNEL_HANDLE },+ ],+ ...overrides,+ }) as AppMessageInput;++ beforeEach(async () => {+ cacheLockService = { withLock: jest.fn((fn: () => unknown) => fn()) };++ channelsService = {+ findOwnedOrThrow: jest.fn().mockResolvedValue({+ messageChannel: {+ id: MESSAGE_CHANNEL_ID,+ connectedAccountId: CONNECTED_ACCOUNT_ID,+ handle: CHANNEL_HANDLE,+ type: MessageChannelType.APP,+ isSyncEnabled: true,+ } as MessageChannelEntity,+ connectedAccount: {+ id: CONNECTED_ACCOUNT_ID,+ handle: CHANNEL_HANDLE,+ handleAliases: [],+ } as unknown as ConnectedAccountEntity,+ }),+ } as unknown as jest.Mocked<ApplicationMessageChannelsService>;++ saveMessagesService = {+ saveMessagesAndEnqueueContactCreation: jest.fn().mockResolvedValue({+ messageExternalIdsAndIdsMap: new Map([['msg-1', 'message-uuid']]),+ messageExternalIdToMessageThreadIdMap: new Map([+ ['msg-1', 'thread-uuid'],+ ]),+ }),+ } as unknown as jest.Mocked<MessagingSaveMessagesAndEnqueueContactCreationService>;++ const module: TestingModule = await Test.createTestingModule({+ providers: [+ ApplicationMessageIngestionService,+ { provide: CacheLockService, useValue: cacheLockService },+ {+ provide: ApplicationMessageChannelsService,+ useValue: channelsService,+ },+ {+ provide: MessagingSaveMessagesAndEnqueueContactCreationService,+ useValue: saveMessagesService,+ },+ ],+ }).compile();++ service = module.get(ApplicationMessageIngestionService);+ });++ const savedMessages = () =>+ saveMessagesService.saveMessagesAndEnqueueContactCreation.mock.calls[0][0];++ it('routes through the shared save path rather than writing records directly', async () => {+ await service.ingest({ ...scope, messages: [aMessage()] });++ expect(+ saveMessagesService.saveMessagesAndEnqueueContactCreation,+ ).toHaveBeenCalledTimes(1);+ expect(savedMessages()[0]).toEqual(+ expect.objectContaining({+ externalId: 'msg-1',+ messageThreadExternalId: 'thread-1',+ text: 'hello',+ isDraft: false,+ }),+ );+ });++ it('namespaces the dedup key by application and channel', async () => {+ await service.ingest({ ...scope, messages: [aMessage()] });++ expect(savedMessages()[0].headerMessageId).toBe(+ `app:${APPLICATION_ID}:${MESSAGE_CHANNEL_ID}:msg-1`,+ );+ });++ it('derives direction from the sender rather than trusting the app', async () => {+ await service.ingest({ ...scope, messages: [aMessage()] });+ expect(savedMessages()[0].direction).toBe(MessageDirection.INCOMING);++ saveMessagesService.saveMessagesAndEnqueueContactCreation.mockClear();++ await service.ingest({+ ...scope,+ messages: [+ aMessage({+ participants: [+ { role: MessageParticipantRole.FROM, handle: CHANNEL_HANDLE },+ { role: MessageParticipantRole.TO, handle: 'urn:li:person:ada' },+ ],+ }),+ ],+ });+ expect(savedMessages()[0].direction).toBe(MessageDirection.OUTGOING);+ });++ it('defaults a missing subject to null rather than an empty string', async () => {+ await service.ingest({ ...scope, messages: [aMessage()] });++ expect(savedMessages()[0].subject).toBeNull();+ });++ it('rejects a message with no sender', async () => {+ await expect(+ service.ingest({+ ...scope,+ messages: [+ aMessage({+ participants: [+ { role: MessageParticipantRole.TO, handle: CHANNEL_HANDLE },+ ],+ }),+ ],+ }),+ ).rejects.toMatchObject({+ code: MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,+ });++ expect(+ saveMessagesService.saveMessagesAndEnqueueContactCreation,+ ).not.toHaveBeenCalled();+ });++ it('rejects a message with two senders', async () => {+ await expect(+ service.ingest({+ ...scope,+ messages: [+ aMessage({+ participants: [+ { role: MessageParticipantRole.FROM, handle: 'a' },+ { role: MessageParticipantRole.FROM, handle: 'b' },+ ],+ }),+ ],+ }),+ ).rejects.toMatchObject({+ code: MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,+ });+ });++ it('rejects a batch repeating one external id', async () => {+ await expect(+ service.ingest({+ ...scope,+ messages: [aMessage(), aMessage()],+ }),+ ).rejects.toMatchObject({+ code: MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,+ });++ expect(+ saveMessagesService.saveMessagesAndEnqueueContactCreation,+ ).not.toHaveBeenCalled();+ });++ it('refuses to ingest into a paused channel', async () => {+ channelsService.findOwnedOrThrow.mockResolvedValue({+ messageChannel: {+ id: MESSAGE_CHANNEL_ID,+ connectedAccountId: CONNECTED_ACCOUNT_ID,+ handle: CHANNEL_HANDLE,+ type: MessageChannelType.APP,+ isSyncEnabled: false,+ } as MessageChannelEntity,+ connectedAccount: {+ id: CONNECTED_ACCOUNT_ID,+ handle: CHANNEL_HANDLE,+ handleAliases: [],+ } as unknown as ConnectedAccountEntity,+ });++ await expect(+ service.ingest({ ...scope, messages: [aMessage()] }),+ ).rejects.toMatchObject({+ code: MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,+ });++ expect(+ saveMessagesService.saveMessagesAndEnqueueContactCreation,+ ).not.toHaveBeenCalled();+ });++ it('gates on channel ownership before touching anything else', async () => {+ channelsService.findOwnedOrThrow.mockRejectedValue(new Error('not yours'));++ await expect(+ service.ingest({ ...scope, messages: [aMessage()] }),+ ).rejects.toThrow('not yours');+ });++ it('returns the ids the app needs to link its own records', async () => {+ const result = await service.ingest({ ...scope, messages: [aMessage()] });++ expect(result.messages).toEqual([+ {+ externalId: 'msg-1',+ messageId: 'message-uuid',+ messageThreadId: 'thread-uuid',+ },+ ]);+ });+ it("refuses to ingest into another member's private channel", async () => {+ channelsService.findOwnedOrThrow.mockRejectedValue(+ new Error('ownership violation'),+ );++ await expect(+ service.ingest({+ ...scope,+ requestUserWorkspaceId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',+ messages: [aMessage()],+ }),+ ).rejects.toThrow('ownership violation');++ expect(+ saveMessagesService.saveMessagesAndEnqueueContactCreation,+ ).not.toHaveBeenCalled();+ });++ it('passes the request user to the ownership gate', async () => {+ await service.ingest({+ ...scope,+ requestUserWorkspaceId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb',+ messages: [aMessage()],+ });++ expect(channelsService.findOwnedOrThrow).toHaveBeenCalledWith(+ expect.objectContaining({+ requestUserWorkspaceId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb',+ }),+ );+ });+ it('serialises the save per channel so a redelivery cannot race its original', async () => {+ await service.ingest({ ...scope, messages: [aMessage()] });++ expect(cacheLockService.withLock).toHaveBeenCalledWith(+ expect.any(Function),+ `app-message-ingestion:${WORKSPACE_ID}:${MESSAGE_CHANNEL_ID}`,+ expect.objectContaining({ ttl: expect.any(Number) }),+ );+ });++ it('holds the lock around the save rather than after it', async () => {+ const order: string[] = [];++ cacheLockService.withLock.mockImplementation(async (fn: () => unknown) => {+ order.push('lock-acquired');+ const result = await fn();++ order.push('lock-released');++ return result;+ });+ saveMessagesService.saveMessagesAndEnqueueContactCreation.mockImplementation(+ async () => {+ order.push('saved');++ return {+ messageExternalIdsAndIdsMap: new Map([['msg-1', 'message-uuid']]),+ messageExternalIdToMessageThreadIdMap: new Map([+ ['msg-1', 'thread-uuid'],+ ]),+ };+ },+ );++ await service.ingest({ ...scope, messages: [aMessage()] });++ expect(order).toEqual(['lock-acquired', 'saved', 'lock-released']);+ });++ it('fails loudly rather than returning fewer messages than were sent', async () => {+ saveMessagesService.saveMessagesAndEnqueueContactCreation.mockResolvedValue(+ {+ messageExternalIdsAndIdsMap: new Map(),+ messageExternalIdToMessageThreadIdMap: new Map(),+ } as never,+ );++ await expect(+ service.ingest({ ...scope, messages: [aMessage()] }),+ ).rejects.toMatchObject({+ code: MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,+ });+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-channels.service.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-channels.service.tsindex 8704d2a2b09..96f444cb44b 100644--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-channels.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-channels.service.ts@@ -234,8 +234,9 @@ export class ApplicationMessageChannelsService {// Resolving the channel through the app's own connections is what stops one// app from reading or mutating another app's channels: the connected account- // carries the applicationId, the channel does not.- private async findOwnedOrThrow({+ // carries the applicationId, the channel does not. Public because ingestion+ // gates on the same check, and there must be exactly one of it.+ async findOwnedOrThrow({applicationId,workspaceId,requestUserWorkspaceId,diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-ingestion.service.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-ingestion.service.tsnew file mode 100644index 00000000000..5606cd2602e--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-ingestion.service.ts@@ -0,0 +1,223 @@+import { Injectable } from '@nestjs/common';++import { MessageParticipantRole } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';++import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';+import { type MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';+import { type AppMessageInput } from 'src/engine/metadata-modules/message-channel/dtos/ingest-app-messages.input';+import { type IngestAppMessagesOutput } from 'src/engine/metadata-modules/message-channel/dtos/ingest-app-messages.output';+import {+ MessageChannelException,+ MessageChannelExceptionCode,+} from 'src/engine/metadata-modules/message-channel/message-channel.exception';+import { ApplicationMessageChannelsService } from 'src/engine/metadata-modules/message-channel/services/application-message-channels.service';+import { buildAppIngestionLockKey } from 'src/engine/metadata-modules/message-channel/utils/build-app-ingestion-lock-key.util';+import { buildAppMessageHeaderMessageId } from 'src/engine/metadata-modules/message-channel/utils/build-app-message-header-message-id.util';+import { resolveAppMessageDirection } from 'src/engine/metadata-modules/message-channel/utils/resolve-app-message-direction.util';+import { MessagingSaveMessagesAndEnqueueContactCreationService } from 'src/modules/messaging/message-import-manager/services/messaging-save-messages-and-enqueue-contact-creation.service';+import { type MessageWithParticipants } from 'src/modules/messaging/message-import-manager/types/message';++// A full batch is 100 messages in one transaction, so the hold has to outlast+// that comfortably: a lease that expires mid-save would let the next delivery+// in and reintroduce exactly the duplicate this prevents. Waiting up to the+// same order of time is better than failing a webhook that would have+// succeeded a second later.+//+// The wait deliberately outlasts the lease. `withLock` does not renew, so a+// holder that dies leaves the key behind until Redis expires it; a window+// shorter than the lease would make every waiter give up just before the+// lock became free, turning one crash into a batch of avoidable failures.+const INGESTION_LOCK_TTL_MS = 60_000;+const INGESTION_LOCK_RETRY_INTERVAL_MS = 500;++const INGESTION_LOCK_OPTIONS = {+ ttl: INGESTION_LOCK_TTL_MS,+ ms: INGESTION_LOCK_RETRY_INTERVAL_MS,+ maxRetries:+ Math.ceil(INGESTION_LOCK_TTL_MS / INGESTION_LOCK_RETRY_INTERVAL_MS) + 10,+};++type IngestArgs = {+ applicationId: string;+ workspaceId: string;+ // Ingestion resolves the channel through the same gate the channel API+ // uses, so a run triggered by one member cannot write into another+ // member's private channel.+ requestUserWorkspaceId: string | null;+ messageChannelId: string;+ messages: AppMessageInput[];+};++@Injectable()+export class ApplicationMessageIngestionService {+ constructor(+ private readonly applicationMessageChannelsService: ApplicationMessageChannelsService,+ private readonly saveMessagesService: MessagingSaveMessagesAndEnqueueContactCreationService,+ private readonly cacheLockService: CacheLockService,+ ) {}++ async ingest({+ applicationId,+ workspaceId,+ requestUserWorkspaceId,+ messageChannelId,+ messages,+ }: IngestArgs): Promise<IngestAppMessagesOutput> {+ const { messageChannel, connectedAccount } =+ await this.applicationMessageChannelsService.findOwnedOrThrow({+ applicationId,+ workspaceId,+ requestUserWorkspaceId,+ id: messageChannelId,+ });++ if (!messageChannel.isSyncEnabled) {+ throw new MessageChannelException(+ `Message channel ${messageChannelId} has sync disabled`,+ MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,+ );+ }++ this.assertEachMessageHasOneSender(messages);+ this.assertExternalIdsAreUnique(messages);++ const messagesToSave = messages.map((message) =>+ this.toMessageWithParticipants({+ message,+ applicationId,+ messageChannel,+ }),+ );++ // The save path decides what to insert by reading first and writing after,+ // and no unique index backs headerMessageId — so two deliveries of the same+ // provider message, arriving together, would both see nothing and both+ // insert, handing the app two different Twenty ids for one message. A+ // provider redelivers constantly, so this is the common case, not the edge.+ // Serialising per channel is the narrowest scope that closes it: dedup+ // never spans channels, and one channel's deliveries are naturally+ // sequential, so contention is a redelivery racing its original.+ const savedMessages = await this.cacheLockService.withLock(+ () =>+ this.saveMessagesService.saveMessagesAndEnqueueContactCreation(+ messagesToSave,+ // The save path only reads folder and contact-creation settings off+ // the channel, both inert here, plus its id.+ messageChannel,+ connectedAccount,+ workspaceId,+ ),+ buildAppIngestionLockKey({ workspaceId, messageChannelId }),+ INGESTION_LOCK_OPTIONS,+ );++ if (!isDefined(savedMessages)) {+ throw new MessageChannelException(+ `Ingestion into message channel ${messageChannelId} did not persist`,+ MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,+ );+ }++ const {+ messageExternalIdsAndIdsMap,+ messageExternalIdToMessageThreadIdMap,+ } = savedMessages;++ // Dropping a row here would report success while returning fewer messages+ // than were sent, leaving the app with nothing to retry against — the+ // silent version of the "did not persist" failure above.+ return {+ messages: messagesToSave.map((message) => {+ const messageId = messageExternalIdsAndIdsMap.get(message.externalId);+ const messageThreadId = messageExternalIdToMessageThreadIdMap.get(+ message.externalId,+ );++ if (!isDefined(messageId) || !isDefined(messageThreadId)) {+ throw new MessageChannelException(+ `Message ${message.externalId} was not persisted by the save path`,+ MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,+ );+ }++ return {+ externalId: message.externalId,+ messageId,+ messageThreadId,+ };+ }),+ };+ }++ private toMessageWithParticipants({+ message,+ applicationId,+ messageChannel,+ }: {+ message: AppMessageInput;+ applicationId: string;+ messageChannel: MessageChannelEntity;+ }): MessageWithParticipants {+ return {+ headerMessageId: buildAppMessageHeaderMessageId({+ applicationId,+ messageChannelId: messageChannel.id,+ externalId: message.externalId,+ }),+ subject: message.subject ?? null,+ text: message.text,+ receivedAt: message.receivedAt,+ // Apps ingest what the provider already delivered; there is no+ // provider-side draft to mirror.+ isDraft: false,+ externalId: message.externalId,+ messageThreadExternalId: message.threadExternalId,+ direction: resolveAppMessageDirection({+ participants: message.participants,+ channelHandle: messageChannel.handle,+ }),+ attachments: [],+ participants: message.participants.map((participant) => ({+ role: participant.role,+ handle: participant.handle,+ displayName: participant.displayName ?? '',+ })),+ };+ }++ // Direction, the thread's sender column and the timeline preview all read+ // the FROM participant, so a message without exactly one is rejected rather+ // than silently rendering as an empty conversation.+ private assertEachMessageHasOneSender(messages: AppMessageInput[]): void {+ for (const message of messages) {+ const senderCount = message.participants.filter(+ (participant) => participant.role === MessageParticipantRole.FROM,+ ).length;++ if (senderCount !== 1) {+ throw new MessageChannelException(+ `Message ${message.externalId} must have exactly one FROM participant, got ${senderCount}`,+ MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,+ );+ }+ }+ }++ // Two entries sharing an externalId would race each other inside the save+ // transaction, which keys its accumulator on exactly that value.+ private assertExternalIdsAreUnique(messages: AppMessageInput[]): void {+ const externalIds = new Set<string>();++ for (const message of messages) {+ if (externalIds.has(message.externalId)) {+ throw new MessageChannelException(+ `Message externalId ${message.externalId} appears more than once in the same batch`,+ MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,+ );+ }++ externalIds.add(message.externalId);+ }+ }+}diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/__tests__/build-app-message-header-message-id.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/__tests__/build-app-message-header-message-id.util.spec.tsnew file mode 100644index 00000000000..ff6e20117ae--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/__tests__/build-app-message-header-message-id.util.spec.ts@@ -0,0 +1,70 @@+import { buildAppMessageHeaderMessageId } from 'src/engine/metadata-modules/message-channel/utils/build-app-message-header-message-id.util';++const APPLICATION_ID = '11111111-1111-4111-8111-111111111111';+const OTHER_APPLICATION_ID = '22222222-2222-4222-8222-222222222222';+const ALICE_CHANNEL_ID = '55555555-5555-4555-8555-555555555555';+const BOB_CHANNEL_ID = '66666666-6666-4666-8666-666666666666';++describe('buildAppMessageHeaderMessageId', () => {+ it('is stable for the same channel and external id, so re-ingestion dedupes', () => {+ expect(+ buildAppMessageHeaderMessageId({+ applicationId: APPLICATION_ID,+ messageChannelId: ALICE_CHANNEL_ID,+ externalId: 'msg-1',+ }),+ ).toBe(+ buildAppMessageHeaderMessageId({+ applicationId: APPLICATION_ID,+ messageChannelId: ALICE_CHANNEL_ID,+ externalId: 'msg-1',+ }),+ );+ });++ // The collision that matters: providers commonly scope message ids per+ // conversation or per account, so two members can legitimately both send+ // "1". Merging those would discard one body and attach the other member's+ // channel to it.+ it('separates two members whose provider reuses the same external id', () => {+ expect(+ buildAppMessageHeaderMessageId({+ applicationId: APPLICATION_ID,+ messageChannelId: ALICE_CHANNEL_ID,+ externalId: '1',+ }),+ ).not.toBe(+ buildAppMessageHeaderMessageId({+ applicationId: APPLICATION_ID,+ messageChannelId: BOB_CHANNEL_ID,+ externalId: '1',+ }),+ );+ });++ it('separates two apps that happen to use the same external id', () => {+ expect(+ buildAppMessageHeaderMessageId({+ applicationId: APPLICATION_ID,+ messageChannelId: ALICE_CHANNEL_ID,+ externalId: 'msg-1',+ }),+ ).not.toBe(+ buildAppMessageHeaderMessageId({+ applicationId: OTHER_APPLICATION_ID,+ messageChannelId: ALICE_CHANNEL_ID,+ externalId: 'msg-1',+ }),+ );+ });++ it('cannot collide with an RFC822 header message id', () => {+ expect(+ buildAppMessageHeaderMessageId({+ applicationId: APPLICATION_ID,+ messageChannelId: ALICE_CHANNEL_ID,+ externalId: 'msg-1',+ }),+ ).toMatch(/^app:/);+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/__tests__/resolve-app-message-direction.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/__tests__/resolve-app-message-direction.util.spec.tsnew file mode 100644index 00000000000..1422b8f58d8--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/__tests__/resolve-app-message-direction.util.spec.ts@@ -0,0 +1,72 @@+import { MessageParticipantRole } from 'twenty-shared/types';++import { MessageDirection } from 'src/modules/messaging/common/enums/message-direction.enum';+import { resolveAppMessageDirection } from 'src/engine/metadata-modules/message-channel/utils/resolve-app-message-direction.util';++const CHANNEL_HANDLE = 'urn:li:person:self';++describe('resolveAppMessageDirection', () => {+ it('is outgoing when the sender is the channel itself', () => {+ expect(+ resolveAppMessageDirection({+ channelHandle: CHANNEL_HANDLE,+ participants: [+ { role: MessageParticipantRole.FROM, handle: CHANNEL_HANDLE },+ { role: MessageParticipantRole.TO, handle: 'urn:li:person:ada' },+ ],+ }),+ ).toBe(MessageDirection.OUTGOING);+ });++ it('is incoming when someone else sent it', () => {+ expect(+ resolveAppMessageDirection({+ channelHandle: CHANNEL_HANDLE,+ participants: [+ { role: MessageParticipantRole.FROM, handle: 'urn:li:person:ada' },+ { role: MessageParticipantRole.TO, handle: CHANNEL_HANDLE },+ ],+ }),+ ).toBe(MessageDirection.INCOMING);+ });++ it('does not read direction off a recipient that matches the channel', () => {+ expect(+ resolveAppMessageDirection({+ channelHandle: CHANNEL_HANDLE,+ participants: [+ { role: MessageParticipantRole.TO, handle: CHANNEL_HANDLE },+ { role: MessageParticipantRole.FROM, handle: 'urn:li:person:ada' },+ ],+ }),+ ).toBe(MessageDirection.INCOMING);+ });++ // A provider that spells one account differently across its profile and+ // message payloads would otherwise mark everything the owner sent as+ // incoming — the same reason the email path normalises its handles.+ it('still recognises the channel owner when the casing differs', () => {+ expect(+ resolveAppMessageDirection({+ channelHandle: CHANNEL_HANDLE,+ participants: [+ {+ role: MessageParticipantRole.FROM,+ handle: CHANNEL_HANDLE.toUpperCase(),+ },+ ],+ }),+ ).toBe(MessageDirection.OUTGOING);+ });++ it('is unaffected by the casing of the stored channel handle', () => {+ expect(+ resolveAppMessageDirection({+ channelHandle: CHANNEL_HANDLE.toUpperCase(),+ participants: [+ { role: MessageParticipantRole.FROM, handle: CHANNEL_HANDLE },+ ],+ }),+ ).toBe(MessageDirection.OUTGOING);+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/build-app-ingestion-lock-key.util.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/build-app-ingestion-lock-key.util.tsnew file mode 100644index 00000000000..f9e155e9e28--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/build-app-ingestion-lock-key.util.ts@@ -0,0 +1,11 @@+// Scoped to the channel because that is the scope dedup works at: two channels+// never share a headerMessageId, so serialising them against each other would+// only add contention. Workspace-qualified so one workspace's ingestion cannot+// stall another's.+export const buildAppIngestionLockKey = ({+ workspaceId,+ messageChannelId,+}: {+ workspaceId: string;+ messageChannelId: string;+}): string => `app-message-ingestion:${workspaceId}:${messageChannelId}`;diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/build-app-message-header-message-id.util.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/build-app-message-header-message-id.util.tsnew file mode 100644index 00000000000..1a0475f81b8--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/build-app-message-header-message-id.util.ts@@ -0,0 +1,24 @@+// The save path dedupes on headerMessageId across every channel in the+// workspace, which is what makes one email addressed to two synced mailboxes a+// single Message with two channel associations. That is only sound when the id+// is globally unique, as an RFC822 Message-ID is.+//+// A provider's own message id usually is not: plenty scope it per conversation+// or per account, so Alice's message "1" and Bob's unrelated message "1" would+// dedupe onto one row — discarding one body and attaching the other member's+// channel to it. Scoping to the channel makes a collision impossible without+// asking apps to guarantee a namespace they do not control.+//+// The cost is that two members in the same provider conversation get one+// Message each rather than a shared one. Deliberate: convergence is a nicety,+// and the alternative failure is one member's content surfacing under+// another's sharing policy.+export const buildAppMessageHeaderMessageId = ({+ applicationId,+ messageChannelId,+ externalId,+}: {+ applicationId: string;+ messageChannelId: string;+ externalId: string;+}): string => `app:${applicationId}:${messageChannelId}:${externalId}`;diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/resolve-app-message-direction.util.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/resolve-app-message-direction.util.tsnew file mode 100644index 00000000000..6ac7cd39a92--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/resolve-app-message-direction.util.ts@@ -0,0 +1,28 @@+import { MessageParticipantRole } from 'twenty-shared/types';++import { MessageDirection } from 'src/modules/messaging/common/enums/message-direction.enum';++// Derived rather than taken from the app: direction is a property of who sent+// the message relative to this channel, which the server already knows, and+// an app that got it backwards would mislabel every thread it ingests.+export const resolveAppMessageDirection = ({+ participants,+ channelHandle,+}: {+ participants: { role: MessageParticipantRole; handle: string }[];+ channelHandle: string;+}): MessageDirection => {+ const sender = participants.find(+ (participant) => participant.role === MessageParticipantRole.FROM,+ );++ // Compared case-insensitively, as the email path already normalises its+ // handles. A provider that spells the same account differently in its+ // profile API and its message payloads would otherwise mark every message+ // the channel owner sent as incoming. Two distinct handles differing only+ // in case would collide here, but one of them would have to be the+ // channel's own, which is the far smaller risk of the two.+ return sender?.handle.toLowerCase() === channelHandle.toLowerCase()+ ? MessageDirection.OUTGOING+ : MessageDirection.INCOMING;+};