Skip to content

The open alternative to Salesforce, designed for AI.

feat(messaging): let apps own message channels (#25903)

Félix Malfait3d81d817af3b
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index 0337a035e61..6c97020749b 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -2958,6 +2958,7 @@ enum MessageChannelType {
EMAIL
SMS
EMAIL_GROUP
+ APP
}
enum MessageChannelContactAutoCreationPolicy {
@@ -3712,6 +3713,7 @@ type Query {
messageSuppressions(input: FindMessageSuppressionsInput!): MessageSuppressionList!
unsubscribeTopics: [UnsubscribeTopic!]!
myMessageChannels(connectedAccountId: UUID): [MessageChannel!]!
+ appMessageChannels(filter: ListAppMessageChannelsInput): [MessageChannel!]!
getEmailingDomains: [EmailingDomain!]!
getToolIndex: [ToolIndexEntry!]!
getToolInputSchema(toolName: String!): JSON
@@ -3813,6 +3815,10 @@ input FindMessageSuppressionsInput {
offset: Int! = 0
}
+input ListAppMessageChannelsInput {
+ connectedAccountId: UUID
+}
+
input ListAppConnectionsInput {
providerName: String
userWorkspaceId: String
@@ -4032,6 +4038,9 @@ type Mutation {
createEmailGroupChannel(input: CreateEmailGroupChannelInput!): CreateEmailGroupChannelOutput!
updateEmailGroupChannel(input: UpdateEmailGroupChannelInput!): MessageChannel!
deleteEmailGroupChannel(id: UUID!): MessageChannel!
+ createAppMessageChannel(input: CreateAppMessageChannelInput!): MessageChannel!
+ updateAppMessageChannel(input: UpdateAppMessageChannelInput!): MessageChannel!
+ deleteAppMessageChannel(id: UUID!): MessageChannel!
createEmailingDomain(input: CreateEmailingDomainInput!): EmailingDomain!
deleteEmailingDomain(id: String!): Boolean!
verifyEmailingDomain(id: String!): EmailingDomain!
@@ -5177,6 +5186,20 @@ input UpdateEmailGroupChannelInput {
displayName: String
}
+input CreateAppMessageChannelInput {
+ connectedAccountId: UUID!
+ handle: String!
+ displayName: String
+ visibility: MessageChannelVisibility!
+}
+
+input UpdateAppMessageChannelInput {
+ id: UUID!
+ displayName: String
+ visibility: MessageChannelVisibility
+ isSyncEnabled: Boolean
+}
+
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.ts
index 69398e7b456..a904db27bab 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -2559,7 +2559,7 @@ export interface MessageChannel {
export type MessageChannelVisibility = 'METADATA' | 'SUBJECT' | 'SHARE_EVERYTHING'
-export type MessageChannelType = 'EMAIL' | 'SMS' | 'EMAIL_GROUP'
+export type MessageChannelType = 'EMAIL' | 'SMS' | 'EMAIL_GROUP' | 'APP'
export type MessageChannelContactAutoCreationPolicy = 'SENT_AND_RECEIVED' | 'SENT' | 'NONE'
@@ -3249,6 +3249,7 @@ export interface Query {
messageSuppressions: MessageSuppressionList
unsubscribeTopics: UnsubscribeTopic[]
myMessageChannels: MessageChannel[]
+ appMessageChannels: MessageChannel[]
getEmailingDomains: EmailingDomain[]
getToolIndex: ToolIndexEntry[]
getToolInputSchema?: Scalars['JSON']
@@ -3461,6 +3462,9 @@ export interface Mutation {
createEmailGroupChannel: CreateEmailGroupChannelOutput
updateEmailGroupChannel: MessageChannel
deleteEmailGroupChannel: MessageChannel
+ createAppMessageChannel: MessageChannel
+ updateAppMessageChannel: MessageChannel
+ deleteAppMessageChannel: MessageChannel
createEmailingDomain: EmailingDomain
deleteEmailingDomain: Scalars['Boolean']
verifyEmailingDomain: EmailingDomain
@@ -6956,6 +6960,7 @@ export interface QueryGenqlSelection{
messageSuppressions?: (MessageSuppressionListGenqlSelection & { __args: {input: FindMessageSuppressionsInput} })
unsubscribeTopics?: UnsubscribeTopicGenqlSelection
myMessageChannels?: (MessageChannelGenqlSelection & { __args?: {connectedAccountId?: (Scalars['UUID'] | null)} })
+ appMessageChannels?: (MessageChannelGenqlSelection & { __args?: {filter?: (ListAppMessageChannelsInput | null)} })
getEmailingDomains?: EmailingDomainGenqlSelection
getToolIndex?: ToolIndexEntryGenqlSelection
getToolInputSchema?: { __args: {toolName: Scalars['String']} }
@@ -7022,6 +7027,8 @@ export interface PreviewMessageCampaignAudienceInput {listId: Scalars['String'],
export interface FindMessageSuppressionsInput {reason?: (MessageSuppressionReason | null),searchTerm?: (Scalars['String'] | null),unsubscribeTopicId?: (Scalars['UUID'] | null),limit: Scalars['Int'],offset: Scalars['Int']}
+export interface ListAppMessageChannelsInput {connectedAccountId?: (Scalars['UUID'] | null)}
+
export interface ListAppConnectionsInput {providerName?: (Scalars['String'] | null),userWorkspaceId?: (Scalars['String'] | null),visibility?: (Scalars['String'] | null)}
export interface MetadataTranslationsInput {objectMetadataId?: (Scalars['UUID'] | null),fieldMetadataId?: (Scalars['UUID'] | null),locale?: (Scalars['String'] | null)}
@@ -7203,6 +7210,9 @@ export interface MutationGenqlSelection{
createEmailGroupChannel?: (CreateEmailGroupChannelOutputGenqlSelection & { __args: {input: CreateEmailGroupChannelInput} })
updateEmailGroupChannel?: (MessageChannelGenqlSelection & { __args: {input: UpdateEmailGroupChannelInput} })
deleteEmailGroupChannel?: (MessageChannelGenqlSelection & { __args: {id: Scalars['UUID']} })
+ createAppMessageChannel?: (MessageChannelGenqlSelection & { __args: {input: CreateAppMessageChannelInput} })
+ updateAppMessageChannel?: (MessageChannelGenqlSelection & { __args: {input: UpdateAppMessageChannelInput} })
+ deleteAppMessageChannel?: (MessageChannelGenqlSelection & { __args: {id: Scalars['UUID']} })
createEmailingDomain?: (EmailingDomainGenqlSelection & { __args: {input: CreateEmailingDomainInput} })
deleteEmailingDomain?: { __args: {id: Scalars['String']} }
verifyEmailingDomain?: (EmailingDomainGenqlSelection & { __args: {id: Scalars['String']} })
@@ -7647,6 +7657,10 @@ export interface CreateEmailGroupChannelInput {handle: Scalars['String'],display
export interface UpdateEmailGroupChannelInput {id: Scalars['UUID'],displayName?: (Scalars['String'] | null)}
+export interface CreateAppMessageChannelInput {connectedAccountId: Scalars['UUID'],handle: Scalars['String'],displayName?: (Scalars['String'] | null),visibility: MessageChannelVisibility}
+
+export interface UpdateAppMessageChannelInput {id: Scalars['UUID'],displayName?: (Scalars['String'] | null),visibility?: (MessageChannelVisibility | null),isSyncEnabled?: (Scalars['Boolean'] | null)}
+
export interface CreateEmailingDomainInput {domain: Scalars['String']}
export interface RunAgentInput {agentUniversalIdentifier: Scalars['String'],prompt?: (Scalars['String'] | null),runAsWorkspaceMemberId?: (Scalars['UUID'] | null),messages?: (RunAgentMessageInput[] | null)}
@@ -10802,7 +10816,8 @@ export const enumMessageChannelVisibility = {
export const enumMessageChannelType = {
EMAIL: 'EMAIL' as const,
SMS: 'SMS' as const,
- EMAIL_GROUP: 'EMAIL_GROUP' as const
+ EMAIL_GROUP: 'EMAIL_GROUP' as const,
+ APP: 'APP' as const
}
export const enumMessageChannelContactAutoCreationPolicy = {
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index 17fc4065752..a7085f720d6 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -99,10 +99,10 @@ export default {
387,
389,
394,
- 410,
- 422,
- 540,
- 566
+ 411,
+ 423,
+ 543,
+ 569
],
"types": {
"BillingProductDTO": {
@@ -7691,6 +7691,14 @@ export default {
]
}
],
+ "appMessageChannels": [
+ 317,
+ {
+ "filter": [
+ 407
+ ]
+ }
+ ],
"getEmailingDomains": [
313
],
@@ -7762,7 +7770,7 @@ export default {
228,
{
"filter": [
- 407
+ 408
]
}
],
@@ -7839,7 +7847,7 @@ export default {
388,
{
"input": [
- 408,
+ 409,
"MetadataTranslationsInput!"
]
}
@@ -7905,7 +7913,7 @@ export default {
362,
{
"input": [
- 409,
+ 410,
"EventLogQueryInput!"
]
}
@@ -7914,7 +7922,7 @@ export default {
356,
{
"input": [
- 413,
+ 414,
"PieChartDataInput!"
]
}
@@ -7923,7 +7931,7 @@ export default {
354,
{
"input": [
- 414,
+ 415,
"LineChartDataInput!"
]
}
@@ -7932,7 +7940,7 @@ export default {
351,
{
"input": [
- 415,
+ 416,
"BarChartDataInput!"
]
}
@@ -8139,6 +8147,14 @@ export default {
1
]
},
+ "ListAppMessageChannelsInput": {
+ "connectedAccountId": [
+ 3
+ ],
+ "__typename": [
+ 1
+ ]
+ },
"ListAppConnectionsInput": {
"providerName": [
1
@@ -8169,10 +8185,10 @@ export default {
},
"EventLogQueryInput": {
"table": [
- 410
+ 411
],
"filters": [
- 411
+ 412
],
"first": [
28
@@ -8193,7 +8209,7 @@ export default {
1
],
"dateRange": [
- 412
+ 413
],
"recordId": [
1
@@ -8254,7 +8270,7 @@ export default {
8,
{
"input": [
- 417,
+ 418,
"AddQuerySubscriptionInput!"
]
}
@@ -8263,7 +8279,7 @@ export default {
8,
{
"input": [
- 418,
+ 419,
"RemoveQueryFromEventStreamInput!"
]
}
@@ -8272,7 +8288,7 @@ export default {
154,
{
"inputs": [
- 419,
+ 420,
"[CreateNavigationMenuItemInput!]!"
]
}
@@ -8281,7 +8297,7 @@ export default {
154,
{
"input": [
- 419,
+ 420,
"CreateNavigationMenuItemInput!"
]
}
@@ -8290,7 +8306,7 @@ export default {
154,
{
"inputs": [
- 420,
+ 421,
"[UpdateOneNavigationMenuItemInput!]!"
]
}
@@ -8299,7 +8315,7 @@ export default {
154,
{
"input": [
- 420,
+ 421,
"UpdateOneNavigationMenuItemInput!"
]
}
@@ -8373,7 +8389,7 @@ export default {
151,
{
"file": [
- 422,
+ 423,
"Upload!"
]
}
@@ -8382,7 +8398,7 @@ export default {
151,
{
"file": [
- 422,
+ 423,
"Upload!"
]
}
@@ -8391,7 +8407,7 @@ export default {
151,
{
"file": [
- 422,
+ 423,
"Upload!"
],
"fieldMetadataUniversalIdentifier": [
@@ -8404,7 +8420,7 @@ export default {
183,
{
"input": [
- 423,
+ 424,
"CreateUsageLimitInput!"
]
}
@@ -8413,7 +8429,7 @@ export default {
183,
{
"input": [
- 424,
+ 425,
"UpdateUsageLimitInput!"
]
}
@@ -8431,7 +8447,7 @@ export default {
55,
{
"input": [
- 425,
+ 426,
"CreateViewFilterGroupInput!"
]
}
@@ -8444,7 +8460,7 @@ export default {
"String!"
],
"input": [
- 426,
+ 427,
"UpdateViewFilterGroupInput!"
]
}
@@ -8471,7 +8487,7 @@ export default {
57,
{
"input": [
- 427,
+ 428,
"CreateViewFilterInput!"
]
}
@@ -8480,7 +8496,7 @@ export default {
57,
{
"input": [
- 428,
+ 429,
"UpdateViewFilterInput!"
]
}
@@ -8489,7 +8505,7 @@ export default {
57,
{
"input": [
- 430,
+ 431,
"DeleteViewFilterInput!"
]
}
@@ -8498,7 +8514,7 @@ export default {
57,
{
"input": [
- 431,
+ 432,
"DestroyViewFilterInput!"
]
}
@@ -8507,7 +8523,7 @@ export default {
63,
{
"input": [
- 432,
+ 433,
"CreateViewInput!"
]
}
@@ -8520,7 +8536,7 @@ export default {
"String!"
],
"input": [
- 433,
+ 434,
"UpdateViewInput!"
]
}
@@ -8547,7 +8563,7 @@ export default {
63,
{
"input": [
- 434,
+ 435,
"UpsertViewWidgetInput!"
]
}
@@ -8556,7 +8572,7 @@ export default {
60,
{
"input": [
- 440,
+ 441,
"CreateViewSortInput!"
]
}
@@ -8565,7 +8581,7 @@ export default {
60,
{
"input": [
- 441,
+ 442,
"UpdateViewSortInput!"
]
}
@@ -8574,7 +8590,7 @@ export default {
8,
{
"input": [
- 443,
+ 444,
"DeleteViewSortInput!"
]
}
@@ -8583,7 +8599,7 @@ export default {
8,
{
"input": [
- 444,
+ 445,
"DestroyViewSortInput!"
]
}
@@ -8592,7 +8608,7 @@ export default {
53,
{
"input": [
- 445,
+ 446,
"UpdateViewFieldInput!"
]
}
@@ -8601,7 +8617,7 @@ export default {
53,
{
"input": [
- 447,
+ 448,
"CreateViewFieldInput!"
]
}
@@ -8610,7 +8626,7 @@ export default {
53,
{
"inputs": [
- 447,
+ 448,
"[CreateViewFieldInput!]!"
]
}
@@ -8619,7 +8635,7 @@ export default {
53,
{
"input": [
- 448,
+ 449,
"DeleteViewFieldInput!"
]
}
@@ -8628,7 +8644,7 @@ export default {
53,
{
"input": [
- 449,
+ 450,
"DestroyViewFieldInput!"
]
}
@@ -8637,7 +8653,7 @@ export default {
62,
{
"input": [
- 450,
+ 451,
"UpdateViewFieldGroupInput!"
]
}
@@ -8646,7 +8662,7 @@ export default {
62,
{
"input": [
- 452,
+ 453,
"CreateViewFieldGroupInput!"
]
}
@@ -8655,7 +8671,7 @@ export default {
62,
{
"inputs": [
- 452,
+ 453,
"[CreateViewFieldGroupInput!]!"
]
}
@@ -8664,7 +8680,7 @@ export default {
62,
{
"input": [
- 453,
+ 454,
"DeleteViewFieldGroupInput!"
]
}
@@ -8673,7 +8689,7 @@ export default {
62,
{
"input": [
- 454,
+ 455,
"DestroyViewFieldGroupInput!"
]
}
@@ -8682,7 +8698,7 @@ export default {
63,
{
"input": [
- 455,
+ 456,
"UpsertFieldsWidgetInput!"
]
}
@@ -8691,7 +8707,7 @@ export default {
2,
{
"input": [
- 458,
+ 459,
"CreateApiKeyInput!"
]
}
@@ -8700,7 +8716,7 @@ export default {
2,
{
"input": [
- 459,
+ 460,
"UpdateApiKeyInput!"
]
}
@@ -8709,7 +8725,7 @@ export default {
2,
{
"input": [
- 460,
+ 461,
"RevokeApiKeyInput!"
]
}
@@ -8911,7 +8927,7 @@ export default {
184,
{
"input": [
- 461,
+ 462,
"CreateApprovedAccessDomainInput!"
]
}
@@ -8920,7 +8936,7 @@ export default {
8,
{
"input": [
- 462,
+ 463,
"DeleteApprovedAccessDomainInput!"
]
}
@@ -8929,7 +8945,7 @@ export default {
184,
{
"input": [
- 463,
+ 464,
"ValidateApprovedAccessDomainInput!"
]
}
@@ -8938,7 +8954,7 @@ export default {
125,
{
"input": [
- 464,
+ 465,
"CreatePageLayoutTabInput!"
]
}
@@ -8951,7 +8967,7 @@ export default {
"String!"
],
"input": [
- 465,
+ 466,
"UpdatePageLayoutTabInput!"
]
}
@@ -8969,7 +8985,7 @@ export default {
126,
{
"input": [
- 466,
+ 467,
"CreatePageLayoutInput!"
]
}
@@ -8982,7 +8998,7 @@ export default {
"String!"
],
"input": [
- 467,
+ 468,
"UpdatePageLayoutInput!"
]
}
@@ -9004,7 +9020,7 @@ export default {
"String!"
],
"input": [
- 468,
+ 469,
"UpdatePageLayoutWithTabsInput!"
]
}
@@ -9040,7 +9056,7 @@ export default {
81,
{
"input": [
- 471,
+ 472,
"CreatePageLayoutWidgetInput!"
]
}
@@ -9053,7 +9069,7 @@ export default {
"String!"
],
"input": [
- 472,
+ 473,
"UpdatePageLayoutWidgetInput!"
]
}
@@ -9071,7 +9087,7 @@ export default {
10,
{
"input": [
- 473,
+ 474,
"CreateAgentInput!"
]
}
@@ -9080,7 +9096,7 @@ export default {
10,
{
"input": [
- 474,
+ 475,
"UpdateAgentInput!"
]
}
@@ -9098,7 +9114,7 @@ export default {
23,
{
"input": [
- 475,
+ 476,
"CreateOneObjectInput!"
]
}
@@ -9107,7 +9123,7 @@ export default {
23,
{
"input": [
- 477,
+ 478,
"DeleteOneObjectInput!"
]
}
@@ -9116,7 +9132,7 @@ export default {
23,
{
"input": [
- 478,
+ 479,
"UpdateOneObjectInput!"
]
}
@@ -9125,7 +9141,7 @@ export default {
258,
{
"input": [
- 481,
+ 482,
"CreateOneIndexInput!"
]
}
@@ -9134,7 +9150,7 @@ export default {
258,
{
"input": [
- 484,
+ 485,
"DeleteOneIndexInput!"
]
}
@@ -9152,7 +9168,7 @@ export default {
21,
{
"input": [
- 485,
+ 486,
"CreateLogicFunctionFromSourceInput!"
]
}
@@ -9161,7 +9177,7 @@ export default {
147,
{
"input": [
- 486,
+ 487,
"ExecuteOneLogicFunctionInput!"
]
}
@@ -9170,7 +9186,7 @@ export default {
8,
{
"input": [
- 487,
+ 488,
"UpdateLogicFunctionFromSourceInput!"
]
}
@@ -9179,7 +9195,7 @@ export default {
14,
{
"input": [
- 489,
+ 490,
"CreateCommandMenuItemInput!"
]
}
@@ -9188,7 +9204,7 @@ export default {
14,
{
"input": [
- 490,
+ 491,
"UpdateCommandMenuItemInput!"
]
}
@@ -9215,7 +9231,7 @@ export default {
13,
{
"input": [
- 491,
+ 492,
"CreateFrontComponentInput!"
]
}
@@ -9224,7 +9240,7 @@ export default {
13,
{
"input": [
- 492,
+ 493,
"UpdateFrontComponentInput!"
]
}
@@ -9242,7 +9258,7 @@ export default {
69,
{
"data": [
- 494,
+ 495,
"ActivateWorkspaceInput!"
]
}
@@ -9251,7 +9267,7 @@ export default {
69,
{
"data": [
- 495,
+ 496,
"UpdateWorkspaceInput!"
]
}
@@ -9282,7 +9298,7 @@ export default {
225,
{
"input": [
- 496,
+ 497,
"CreateApplicationRegistrationInput!"
]
}
@@ -9291,7 +9307,7 @@ export default {
76,
{
"input": [
- 497,
+ 498,
"UpdateApplicationRegistrationInput!"
]
}
@@ -9318,7 +9334,7 @@ export default {
198,
{
"input": [
- 499,
+ 500,
"CreateApplicationRegistrationVariableInput!"
]
}
@@ -9327,7 +9343,7 @@ export default {
198,
{
"input": [
- 500,
+ 501,
"UpdateApplicationRegistrationVariableInput!"
]
}
@@ -9345,7 +9361,7 @@ export default {
76,
{
"file": [
- 422,
+ 423,
"Upload!"
],
"universalIdentifier": [
@@ -9403,7 +9419,7 @@ export default {
245,
{
"input": [
- 502,
+ 503,
"TriggerInstallApplicationJobInput!"
]
}
@@ -9412,7 +9428,7 @@ export default {
246,
{
"input": [
- 503,
+ 504,
"TriggerUninstallApplicationJobInput!"
]
}
@@ -9425,7 +9441,7 @@ export default {
"UUID!"
],
"input": [
- 504,
+ 505,
"UpdateApplicationInput!"
]
}
@@ -9446,7 +9462,7 @@ export default {
250,
{
"input": [
- 505,
+ 506,
"CreateOneFieldMetadataInput!"
]
}
@@ -9455,7 +9471,7 @@ export default {
250,
{
"input": [
- 507,
+ 508,
"UpdateOneFieldMetadataInput!"
]
}
@@ -9464,7 +9480,7 @@ export default {
250,
{
"input": [
- 509,
+ 510,
"DeleteOneFieldInput!"
]
}
@@ -9473,7 +9489,7 @@ export default {
59,
{
"input": [
- 510,
+ 511,
"CreateViewGroupInput!"
]
}
@@ -9482,7 +9498,7 @@ export default {
59,
{
"inputs": [
- 510,
+ 511,
"[CreateViewGroupInput!]!"
]
}
@@ -9491,7 +9507,7 @@ export default {
59,
{
"input": [
- 511,
+ 512,
"UpdateViewGroupInput!"
]
}
@@ -9500,7 +9516,7 @@ export default {
59,
{
"inputs": [
- 511,
+ 512,
"[UpdateViewGroupInput!]!"
]
}
@@ -9509,7 +9525,7 @@ export default {
59,
{
"input": [
- 513,
+ 514,
"DeleteViewGroupInput!"
]
}
@@ -9518,7 +9534,7 @@ export default {
59,
{
"input": [
- 514,
+ 515,
"DestroyViewGroupInput!"
]
}
@@ -9540,7 +9556,7 @@ export default {
48,
{
"createRoleInput": [
- 515,
+ 516,
"CreateRoleInput!"
]
}
@@ -9549,7 +9565,7 @@ export default {
48,
{
"updateRoleInput": [
- 516,
+ 517,
"UpdateRoleInput!"
]
}
@@ -9567,7 +9583,7 @@ export default {
45,
{
"upsertObjectPermissionsInput": [
- 518,
+ 519,
"UpsertObjectPermissionsInput!"
]
}
@@ -9576,7 +9592,7 @@ export default {
46,
{
"upsertPermissionFlagsInput": [
- 520,
+ 521,
"UpsertPermissionFlagsInput!"
]
}
@@ -9585,7 +9601,7 @@ export default {
40,
{
"upsertFieldPermissionsInput": [
- 521,
+ 522,
"UpsertFieldPermissionsInput!"
]
}
@@ -9594,7 +9610,7 @@ export default {
271,
{
"input": [
- 523,
+ 524,
"UpsertRowLevelPermissionPredicatesInput!"
]
}
@@ -9625,7 +9641,7 @@ export default {
328,
{
"input": [
- 526,
+ 527,
"SendEmailViaDomainInput!"
]
}
@@ -9634,7 +9650,7 @@ export default {
329,
{
"input": [
- 527,
+ 528,
"SendMessageCampaignInput!"
]
}
@@ -9643,7 +9659,7 @@ export default {
327,
{
"input": [
- 528,
+ 529,
"CancelMessageCampaignInput!"
]
}
@@ -9652,7 +9668,7 @@ export default {
328,
{
"input": [
- 529,
+ 530,
"SendMessageCampaignTestInput!"
]
}
@@ -9670,7 +9686,7 @@ export default {
331,
{
"input": [
- 530,
+ 531,
"CreateMessageSuppressionInput!"
]
}
@@ -9688,7 +9704,7 @@ export default {
335,
{
"input": [
- 531,
+ 532,
"CreateUnsubscribeTopicInput!"
]
}
@@ -9697,7 +9713,7 @@ export default {
335,
{
"input": [
- 532,
+ 533,
"UpdateUnsubscribeTopicInput!"
]
}
@@ -9715,7 +9731,7 @@ export default {
317,
{
"input": [
- 533,
+ 534,
"UpdateMessageChannelInput!"
]
}
@@ -9724,7 +9740,7 @@ export default {
325,
{
"input": [
- 535,
+ 536,
"CreateEmailGroupChannelInput!"
]
}
@@ -9733,7 +9749,7 @@ export default {
317,
{
"input": [
- 536,
+ 537,
"UpdateEmailGroupChannelInput!"
]
}
@@ -9747,11 +9763,38 @@ export default {
]
}
],
+ "createAppMessageChannel": [
+ 317,
+ {
+ "input": [
+ 538,
+ "CreateAppMessageChannelInput!"
+ ]
+ }
+ ],
+ "updateAppMessageChannel": [
+ 317,
+ {
+ "input": [
+ 539,
+ "UpdateAppMessageChannelInput!"
+ ]
+ }
+ ],
+ "deleteAppMessageChannel": [
+ 317,
+ {
+ "id": [
+ 3,
+ "UUID!"
+ ]
+ }
+ ],
"createEmailingDomain": [
313,
{
"input": [
- 537,
+ 540,
"CreateEmailingDomainInput!"
]
}
@@ -9778,7 +9821,7 @@ export default {
347,
{
"input": [
- 538,
+ 541,
"RunAgentInput!"
]
}
@@ -9787,7 +9830,7 @@ export default {
344,
{
"input": [
- 541,
+ 544,
"CreateWebhookInput!"
]
}
@@ -9796,7 +9839,7 @@ export default {
344,
{
"input": [
- 542,
+ 545,
"UpdateWebhookInput!"
]
}
@@ -9814,7 +9857,7 @@ export default {
386,
{
"input": [
- 544,
+ 547,
"UpdateMessageFolderInput!"
]
}
@@ -9823,7 +9866,7 @@ export default {
386,
{
"input": [
- 546,
+ 549,
"UpdateMessageFoldersInput!"
]
}
@@ -9832,7 +9875,7 @@ export default {
381,
{
"input": [
- 547,
+ 550,
"UpdateCalendarChannelInput!"
]
}
@@ -9841,7 +9884,7 @@ export default {
379,
{
"input": [
- 549,
+ 552,
"SetAppKeyValueInput!"
]
}
@@ -9862,7 +9905,7 @@ export default {
377,
{
"input": [
- 550,
+ 553,
"EnqueueJobInput!"
]
}
@@ -9871,7 +9914,7 @@ export default {
378,
{
"input": [
- 551,
+ 554,
"EnqueueJobsInput!"
]
}
@@ -9880,7 +9923,7 @@ export default {
8,
{
"input": [
- 553,
+ 556,
"ReportAppConnectionAuthFailureInput!"
]
}
@@ -9910,7 +9953,7 @@ export default {
1
],
"fileAttachments": [
- 554,
+ 557,
"[FileAttachmentInput!]"
]
}
@@ -9939,14 +9982,14 @@ export default {
"UUID!"
],
"answers": [
- 555,
+ 558,
"[AgentChatQuestionAnswerInput!]!"
],
"modelId": [
1
],
"fileAttachments": [
- 554,
+ 557,
"[FileAttachmentInput!]"
]
}
@@ -10024,7 +10067,7 @@ export default {
363,
{
"input": [
- 556,
+ 559,
"CreateSkillInput!"
]
}
@@ -10033,7 +10076,7 @@ export default {
363,
{
"input": [
- 557,
+ 560,
"UpdateSkillInput!"
]
}
@@ -10091,7 +10134,7 @@ export default {
392,
{
"input": [
- 558,
+ 561,
"UpdateTimelineActivityTypeInput!"
]
}
@@ -10109,7 +10152,7 @@ export default {
280,
{
"input": [
- 559,
+ 562,
"GetAuthorizationUrlForSSOInput!"
]
}
@@ -10275,7 +10318,7 @@ export default {
283,
{
"input": [
- 560
+ 563
]
}
],
@@ -10287,7 +10330,7 @@ export default {
"String!"
],
"file": [
- 422,
+ 423,
"Upload!"
]
}
@@ -10453,7 +10496,7 @@ export default {
8,
{
"input": [
- 561,
+ 564,
"UpdateWorkspaceMemberSettingsInput!"
]
}
@@ -10487,7 +10530,7 @@ export default {
235,
{
"input": [
- 562,
+ 565,
"SetupOIDCSsoInput!"
]
}
@@ -10496,7 +10539,7 @@ export default {
235,
{
"input": [
- 563,
+ 566,
"SetupSAMLSsoInput!"
]
}
@@ -10505,7 +10548,7 @@ export default {
231,
{
"input": [
- 564,
+ 567,
"DeleteSsoInput!"
]
}
@@ -10514,7 +10557,7 @@ export default {
232,
{
"input": [
- 565,
+ 568,
"EditSsoInput!"
]
}
@@ -10543,7 +10586,7 @@ export default {
359,
{
"type": [
- 566,
+ 569,
"AnalyticsType!"
],
"name": [
@@ -10586,7 +10629,7 @@ export default {
349,
{
"input": [
- 567,
+ 570,
"CreateCalendarEventInput!"
]
}
@@ -10595,7 +10638,7 @@ export default {
358,
{
"input": [
- 568,
+ 571,
"SendEmailInput!"
]
}
@@ -10617,7 +10660,7 @@ export default {
"String!"
],
"connectionParameters": [
- 570,
+ 573,
"EmailAccountConnectionParameters!"
],
"id": [
@@ -10629,7 +10672,7 @@ export default {
195,
{
"input": [
- 572,
+ 575,
"UpdateLabPublicFeatureFlagInput!"
]
}
@@ -10697,7 +10740,7 @@ export default {
302,
{
"file": [
- 422,
+ 423,
"Upload!"
],
"applicationUniversalIdentifier": [
@@ -10722,7 +10765,7 @@ export default {
"String!"
],
"files": [
- 573,
+ 576,
"[ApplicationFileUploadRequestInput!]!"
]
}
@@ -10845,7 +10888,7 @@ export default {
3
],
"update": [
- 421
+ 422
],
"__typename": [
1
@@ -10918,7 +10961,7 @@ export default {
3
],
"payload": [
- 423
+ 424
],
"__typename": [
1
@@ -11001,7 +11044,7 @@ export default {
3
],
"update": [
- 429
+ 430
],
"__typename": [
1
@@ -11172,19 +11215,19 @@ export default {
3
],
"view": [
- 435
+ 436
],
"viewFields": [
- 436
+ 437
],
"viewFilters": [
- 437
+ 438
],
"viewFilterGroups": [
- 438
+ 439
],
"viewSorts": [
- 439
+ 440
],
"__typename": [
1
@@ -11333,7 +11376,7 @@ export default {
3
],
"update": [
- 442
+ 443
],
"__typename": [
1
@@ -11371,7 +11414,7 @@ export default {
3
],
"update": [
- 446
+ 447
],
"__typename": [
1
@@ -11447,7 +11490,7 @@ export default {
3
],
"update": [
- 451
+ 452
],
"__typename": [
1
@@ -11511,10 +11554,10 @@ export default {
3
],
"groups": [
- 456
+ 457
],
"fields": [
- 457
+ 458
],
"__typename": [
1
@@ -11534,7 +11577,7 @@ export default {
8
],
"fields": [
- 457
+ 458
],
"__typename": [
1
@@ -11705,7 +11748,7 @@ export default {
8
],
"tabs": [
- 469
+ 470
],
"__typename": [
1
@@ -11728,7 +11771,7 @@ export default {
85
],
"widgets": [
- 470
+ 471
],
"__typename": [
1
@@ -11893,7 +11936,7 @@ export default {
},
"CreateOneObjectInput": {
"object": [
- 476
+ 477
],
"__typename": [
1
@@ -11953,7 +11996,7 @@ export default {
},
"UpdateOneObjectInput": {
"update": [
- 479
+ 480
],
"id": [
3
@@ -12006,7 +12049,7 @@ export default {
24
],
"translations": [
- 480
+ 481
],
"__typename": [
1
@@ -12028,7 +12071,7 @@ export default {
},
"CreateOneIndexInput": {
"index": [
- 482
+ 483
],
"__typename": [
1
@@ -12039,7 +12082,7 @@ export default {
3
],
"fields": [
- 483
+ 484
],
"indexType": [
259
@@ -12124,7 +12167,7 @@ export default {
3
],
"update": [
- 488
+ 489
],
"__typename": [
1
@@ -12293,7 +12336,7 @@ export default {
3
],
"update": [
- 493
+ 494
],
"__typename": [
1
@@ -12420,7 +12463,7 @@ export default {
1
],
"update": [
- 498
+ 499
],
"__typename": [
1
@@ -12474,7 +12517,7 @@ export default {
1
],
"update": [
- 501
+ 502
],
"__typename": [
1
@@ -12520,7 +12563,7 @@ export default {
},
"CreateOneFieldMetadataInput": {
"field": [
- 506
+ 507
],
"__typename": [
1
@@ -12599,7 +12642,7 @@ export default {
3
],
"update": [
- 508
+ 509
],
"__typename": [
1
@@ -12664,7 +12707,7 @@ export default {
9
],
"translations": [
- 480
+ 481
],
"__typename": [
1
@@ -12703,7 +12746,7 @@ export default {
3
],
"update": [
- 512
+ 513
],
"__typename": [
1
@@ -12788,7 +12831,7 @@ export default {
},
"UpdateRoleInput": {
"update": [
- 517
+ 518
],
"id": [
3
@@ -12843,7 +12886,7 @@ export default {
3
],
"objectPermissions": [
- 519
+ 520
],
"__typename": [
1
@@ -12885,7 +12928,7 @@ export default {
3
],
"fieldPermissions": [
- 522
+ 523
],
"__typename": [
1
@@ -12916,10 +12959,10 @@ export default {
3
],
"predicates": [
- 524
+ 525
],
"predicateGroups": [
- 525
+ 526
],
"__typename": [
1
@@ -13095,7 +13138,7 @@ export default {
3
],
"update": [
- 534
+ 535
],
"__typename": [
1
@@ -13149,6 +13192,40 @@ export default {
1
]
},
+ "CreateAppMessageChannelInput": {
+ "connectedAccountId": [
+ 3
+ ],
+ "handle": [
+ 1
+ ],
+ "displayName": [
+ 1
+ ],
+ "visibility": [
+ 318
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UpdateAppMessageChannelInput": {
+ "id": [
+ 3
+ ],
+ "displayName": [
+ 1
+ ],
+ "visibility": [
+ 318
+ ],
+ "isSyncEnabled": [
+ 8
+ ],
+ "__typename": [
+ 1
+ ]
+ },
"CreateEmailingDomainInput": {
"domain": [
1
@@ -13168,7 +13245,7 @@ export default {
3
],
"messages": [
- 539
+ 542
],
"__typename": [
1
@@ -13176,7 +13253,7 @@ export default {
},
"RunAgentMessageInput": {
"role": [
- 540
+ 543
],
"content": [
1
@@ -13211,7 +13288,7 @@ export default {
3
],
"update": [
- 543
+ 546
],
"__typename": [
1
@@ -13239,7 +13316,7 @@ export default {
3
],
"update": [
- 545
+ 548
],
"__typename": [
1
@@ -13258,7 +13335,7 @@ export default {
3
],
"update": [
- 545
+ 548
],
"__typename": [
1
@@ -13269,7 +13346,7 @@ export default {
3
],
"update": [
- 548
+ 551
],
"__typename": [
1
@@ -13334,7 +13411,7 @@ export default {
9
],
"jobs": [
- 552
+ 555
],
"retryLimit": [
28
@@ -13456,7 +13533,7 @@ export default {
8
],
"translations": [
- 480
+ 481
],
"__typename": [
1
@@ -13622,7 +13699,7 @@ export default {
1
],
"files": [
- 569
+ 572
],
"__typename": [
1
@@ -13644,13 +13721,13 @@ export default {
1
],
"IMAP": [
- 571
+ 574
],
"SMTP": [
- 571
+ 574
],
"CALDAV": [
- 571
+ 574
],
"__typename": [
1
@@ -13715,7 +13792,7 @@ export default {
272,
{
"input": [
- 575,
+ 578,
"LogicFunctionLogsInput!"
]
}
@@ -13733,7 +13810,7 @@ export default {
360,
{
"table": [
- 410,
+ 411,
"EventLogTable!"
]
}
diff --git a/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx b/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
index 05cfa3a9db3..a6e8b34a5f0 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
@@ -568,7 +568,7 @@ const asApplication = new RestApiClient({ runAs: 'application' });
Check `context.workspaceMemberId` when a function behaves differently depending on whether someone is behind it, for instance to attribute a record.
</Note>
-The SDK helpers that reach your application's own resources always use its access and ignore `runAs`: the [key-value store](/developers/extend/apps/logic/key-value-store), [connections](/developers/extend/apps/logic/connections), `runAgent`, `getPublicAssetUrl` and [credit charging](/developers/extend/apps/logic/credits).
+The SDK helpers that reach your application's own resources always use its access and ignore `runAs`: the [key-value store](/developers/extend/apps/logic/key-value-store), [connections](/developers/extend/apps/logic/connections), [messaging channels](/developers/extend/apps/logic/messaging-channels), `runAgent`, `getPublicAssetUrl` and [credit charging](/developers/extend/apps/logic/credits).
#### Exposing a function as an AI tool or workflow action
diff --git a/packages/twenty-docs/developers/extend/apps/logic/messaging-channels.mdx b/packages/twenty-docs/developers/extend/apps/logic/messaging-channels.mdx
new file mode 100644
index 00000000000..111ce8c0834
--- /dev/null
+++ b/packages/twenty-docs/developers/extend/apps/logic/messaging-channels.mdx
@@ -0,0 +1,126 @@
+---
+title: Messaging Channels
+description: Bring conversations from any provider into Twenty's Message and Message Thread records.
+icon: "messages"
+---
+
+A **messaging channel** lets your app put conversations from an external provider — LinkedIn, WhatsApp, SMS, an in-app inbox — into the same `Message` and `Message Thread` records Twenty uses for email. Threads you ingest appear on the Person, Company and Opportunity records of the people in them, in the timeline and in search, with no bespoke UI.
+
+Twenty's message model is deliberately channel-neutral: a message has participants, text, a timestamp and a thread; a participant has a `handle` and an optional link to a Person. Nothing in it is email-specific. A channel is what binds a stream of those messages to one account on one provider.
+
+<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
+
+A channel always belongs to one of your app's [connections](/developers/extend/apps/logic/connections) — the credential it speaks through. You need a connection provider before you can create a channel.
+
+## Creating a channel
+
+Create the channel once per connected account, from the connection provider's `onConnect` hook. That way the channel's lifetime matches the credential's.
+
+```ts src/logic-functions/handlers/linkedin-register-connection-handler.ts
+import { createMessageChannel, getConnection } from 'twenty-sdk/logic-function';
+import { MessageChannelVisibility } from 'twenty-shared/types';
+
+export const linkedinRegisterConnectionHandler = async (payload: {
+ connectedAccountId: string;
+}) => {
+ const connection = await getConnection(payload.connectedAccountId);
+ const profile = await fetchLinkedinProfile(connection.accessToken);
+
+ const channel = await createMessageChannel({
+ connectedAccountId: connection.id,
+ handle: profile.memberUrn,
+ displayName: profile.name,
+ // LinkedIn DMs are personal, so other members see participants and dates
+ // but not subjects or bodies.
+ visibility: MessageChannelVisibility.METADATA,
+ });
+
+ return { channelId: channel.id };
+};
+```
+
+### `handle`
+
+The account's identity **as the provider names it** — a LinkedIn member URN, an E.164 phone number, a workspace-scoped user id. Twenty treats it as opaque. It is what you match inbound payloads against, and what decides whether an ingested message is incoming or outgoing.
+
+Pick the most stable identifier the provider offers. A handle that changes when the user renames themselves will split their history across two channels.
+
+### `visibility`
+
+`visibility` is **required**, with no default, because it decides who in the workspace can read these conversations:
+
+| Value | Other members see |
+|---|---|
+| `METADATA` | participants and dates only |
+| `SUBJECT` | the above, plus the subject |
+| `SHARE_EVERYTHING` | the above, plus the message body |
+
+The member who owns the underlying connection always reads their own messages in full, whatever this is set to.
+
+Choose based on how private the provider's messages are, not on what is convenient to display. Personal inboxes (LinkedIn DMs, personal WhatsApp) want `METADATA`; shared ones (a support inbox, a team number) want `SHARE_EVERYTHING`.
+
+<Warning>
+`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>
+
+## Listing and updating channels
+
+```ts
+import {
+ listMessageChannels,
+ updateMessageChannel,
+} from 'twenty-sdk/logic-function';
+
+// Every channel this app owns, across all its connections
+const channels = await listMessageChannels();
+
+// Just the ones on a given connection
+const forConnection = await listMessageChannels({
+ connectedAccountId: connection.id,
+});
+
+// Rename it, re-scope who can read it, or pause ingestion
+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.
+
+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.
+
+## Retiring a channel
+
+Call `deleteMessageChannel(id)` from the connection provider's `onDisconnect` hook so a channel never outlives the credential it speaks through.
+
+```ts src/logic-functions/handlers/linkedin-disconnect-handler.ts
+import {
+ deleteMessageChannel,
+ listMessageChannels,
+} from 'twenty-sdk/logic-function';
+
+export const linkedinDisconnectHandler = async (payload: {
+ connectedAccountId: string;
+}) => {
+ const channels = await listMessageChannels({
+ connectedAccountId: payload.connectedAccountId,
+ });
+
+ await Promise.all(channels.map((channel) => deleteMessageChannel(channel.id)));
+};
+```
+
+Deleting a channel deletes the messages ingested through it, and any thread left with no messages. To stop ingesting while keeping the history, set `isSyncEnabled: false` instead.
+
+## What a channel does not do
+
+- **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.
diff --git a/packages/twenty-docs/developers/extend/apps/logic/overview.mdx b/packages/twenty-docs/developers/extend/apps/logic/overview.mdx
index 428f1ff5b84..2b24f99e429 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/overview.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/overview.mdx
@@ -34,6 +34,9 @@ A Twenty app's **logic layer** is the code that *runs* — server-side TypeScrip
<Card title="Connections" icon="plug" href="/developers/extend/apps/logic/connections">
OAuth 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.
+ </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.
</Card>
diff --git a/packages/twenty-docs/docs.json b/packages/twenty-docs/docs.json
index 0ffd37f717c..da66be85925 100644
--- a/packages/twenty-docs/docs.json
+++ b/packages/twenty-docs/docs.json
@@ -443,6 +443,7 @@
"developers/extend/apps/logic/background-jobs",
"developers/extend/apps/logic/skills-and-agents",
"developers/extend/apps/logic/connections",
+ "developers/extend/apps/logic/messaging-channels",
"developers/extend/apps/logic/credits"
]
},
diff --git a/packages/twenty-docs/navigation/base-structure.json b/packages/twenty-docs/navigation/base-structure.json
index 0ee8ae4fe9f..e5407e8f2a6 100644
--- a/packages/twenty-docs/navigation/base-structure.json
+++ b/packages/twenty-docs/navigation/base-structure.json
@@ -444,6 +444,7 @@
"developers/extend/apps/logic/background-jobs",
"developers/extend/apps/logic/skills-and-agents",
"developers/extend/apps/logic/connections",
+ "developers/extend/apps/logic/messaging-channels",
"developers/extend/apps/logic/credits"
]
},
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index 2a5842f597d..d95228c3d31 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -1225,6 +1225,13 @@ export type CreateApiKeyInput = {
roleId: Scalars['UUID']['input'];
};
+export type CreateAppMessageChannelInput = {
+ connectedAccountId: Scalars['UUID']['input'];
+ displayName?: InputMaybe<Scalars['String']['input']>;
+ handle: Scalars['String']['input'];
+ visibility: MessageChannelVisibility;
+};
+
export type CreateApplicationFileUploadsResult = {
__typename?: 'CreateApplicationFileUploadsResult';
errors: Array<ApplicationFileUploadError>;
@@ -2498,6 +2505,10 @@ export type ListAppConnectionsInput = {
visibility?: InputMaybe<Scalars['String']['input']>;
};
+export type ListAppMessageChannelsInput = {
+ connectedAccountId?: InputMaybe<Scalars['UUID']['input']>;
+};
+
export type Location = {
__typename?: 'Location';
lat?: Maybe<Scalars['Float']['output']>;
@@ -2720,6 +2731,7 @@ export enum MessageChannelSyncStatus {
}
export enum MessageChannelType {
+ APP = 'APP',
EMAIL = 'EMAIL',
EMAIL_GROUP = 'EMAIL_GROUP',
SMS = 'SMS'
@@ -2904,6 +2916,7 @@ export type Mutation = {
completeBookCallOnboardingStep: OnboardingStepSuccess;
completeFileUpload: FileWithSignedUrl;
createApiKey: ApiKey;
+ createAppMessageChannel: MessageChannel;
createApplicationFileUploads: CreateApplicationFileUploadsResult;
createApplicationRegistration: CreateApplicationRegistration;
createApplicationRegistrationVariable: ApplicationRegistrationVariable;
@@ -2950,6 +2963,7 @@ export type Mutation = {
createWebhook: Webhook;
deactivateSkill: Skill;
deleteAppKeyValue: Scalars['Boolean']['output'];
+ deleteAppMessageChannel: MessageChannel;
deleteApplicationRegistration: Scalars['Boolean']['output'];
deleteApplicationRegistrationVariable: Scalars['Boolean']['output'];
deleteApprovedAccessDomain: Scalars['Boolean']['output'];
@@ -3079,6 +3093,7 @@ export type Mutation = {
unarchiveChatThread: AgentChatThread;
uninstallApplication: Scalars['Boolean']['output'];
updateApiKey?: Maybe<ApiKey>;
+ updateAppMessageChannel: MessageChannel;
updateApplication: Application;
updateApplicationRegistration: ApplicationRegistration;
updateApplicationRegistrationVariable: ApplicationRegistrationVariable;
@@ -3237,6 +3252,11 @@ export type MutationCreateApiKeyArgs = {
};
+export type MutationCreateAppMessageChannelArgs = {
+ input: CreateAppMessageChannelInput;
+};
+
+
export type MutationCreateApplicationFileUploadsArgs = {
applicationUniversalIdentifier: Scalars['String']['input'];
files: Array<ApplicationFileUploadRequestInput>;
@@ -3472,6 +3492,11 @@ export type MutationDeleteAppKeyValueArgs = {
};
+export type MutationDeleteAppMessageChannelArgs = {
+ id: Scalars['UUID']['input'];
+};
+
+
export type MutationDeleteApplicationRegistrationArgs = {
id: Scalars['String']['input'];
};
@@ -4083,6 +4108,11 @@ export type MutationUpdateApiKeyArgs = {
};
+export type MutationUpdateAppMessageChannelArgs = {
+ input: UpdateAppMessageChannelInput;
+};
+
+
export type MutationUpdateApplicationArgs = {
id: Scalars['UUID']['input'];
input: UpdateApplicationInput;
@@ -4925,6 +4955,7 @@ export type Query = {
appConnection: AppConnection;
appConnections: Array<AppConnection>;
appKeyValue?: Maybe<AppKeyValue>;
+ appMessageChannels: Array<MessageChannel>;
applicationConnectedAccounts: Array<ApplicationConnectedAccountDto>;
applicationConnectionProviders: Array<ApplicationConnectionProvider>;
applicationRegistrationTarballUrl?: Maybe<Scalars['String']['output']>;
@@ -5076,6 +5107,11 @@ export type QueryAppKeyValueArgs = {
};
+export type QueryAppMessageChannelsArgs = {
+ filter?: InputMaybe<ListAppMessageChannelsInput>;
+};
+
+
export type QueryApplicationConnectedAccountsArgs = {
applicationId: Scalars['UUID']['input'];
};
@@ -6112,6 +6148,13 @@ export type UpdateApiKeyInput = {
revokedAt?: InputMaybe<Scalars['String']['input']>;
};
+export type UpdateAppMessageChannelInput = {
+ displayName?: InputMaybe<Scalars['String']['input']>;
+ id: Scalars['UUID']['input'];
+ isSyncEnabled?: InputMaybe<Scalars['Boolean']['input']>;
+ visibility?: InputMaybe<MessageChannelVisibility>;
+};
+
export type UpdateApplicationInput = {
autoUpgrade?: InputMaybe<Scalars['Boolean']['input']>;
};
diff --git a/packages/twenty-front/src/pages/settings/accounts/SettingsAccountsEmails.tsx b/packages/twenty-front/src/pages/settings/accounts/SettingsAccountsEmails.tsx
index 02754b016bd..c626d13cfd0 100644
--- a/packages/twenty-front/src/pages/settings/accounts/SettingsAccountsEmails.tsx
+++ b/packages/twenty-front/src/pages/settings/accounts/SettingsAccountsEmails.tsx
@@ -27,7 +27,10 @@ export const SettingsAccountsEmails = () => {
(channel) =>
channel.isSyncEnabled &&
channel.syncStage !== MessageChannelSyncStage.PENDING_CONFIGURATION &&
- channel.type !== MessageChannelType.EMAIL_GROUP,
+ // Every setting on this page is a mailbox setting, so it lists
+ // mailboxes only: group inboxes have their own page, and app-owned
+ // channels are configured by the app that created them.
+ channel.type === MessageChannelType.EMAIL,
),
[allMessageChannels],
);
diff --git a/packages/twenty-front/src/pages/settings/accounts/__stories__/SettingsAccountsEmails.stories.tsx b/packages/twenty-front/src/pages/settings/accounts/__stories__/SettingsAccountsEmails.stories.tsx
index 90798df2c84..3b1b659c088 100644
--- a/packages/twenty-front/src/pages/settings/accounts/__stories__/SettingsAccountsEmails.stories.tsx
+++ b/packages/twenty-front/src/pages/settings/accounts/__stories__/SettingsAccountsEmails.stories.tsx
@@ -68,7 +68,7 @@ export const TwoConnectedAccounts: Story = {
id: '20202020-ef5a-4822-9e08-ce6e6a4dcb6f',
handle: '[email protected]',
connectedAccountId: '20202020-954c-4d76-9a87-e5f072d4b7ef',
- type: 'email',
+ type: 'EMAIL',
isSyncEnabled: true,
syncStage: 'MESSAGE_LIST_FETCH_PENDING',
syncStatus: 'COMPLETED',
@@ -84,7 +84,7 @@ export const TwoConnectedAccounts: Story = {
id: '20202020-ef5a-4822-9e08-ce6e6a4dcb6a',
handle: '[email protected]',
connectedAccountId: '20202020-954c-4d76-9a87-e5f072d4b7ef',
- type: 'email',
+ type: 'EMAIL',
isSyncEnabled: true,
syncStage: 'MESSAGE_LIST_FETCH_PENDING',
syncStatus: 'COMPLETED',
diff --git a/packages/twenty-sdk/src/sdk/logic-function/index.ts b/packages/twenty-sdk/src/sdk/logic-function/index.ts
index 06f6274e213..6de8253007f 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/index.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/index.ts
@@ -59,6 +59,15 @@ export { reportConnectionAuthFailure } from '@/sdk/logic-function/connections/re
export { AppConnectionAuthFailedError } from '@/sdk/logic-function/connections/errors/app-connection-auth-failed.error';
export type { AppConnection } from '@/sdk/logic-function/connections/types/app-connection.type';
+export { createMessageChannel } from '@/sdk/logic-function/messaging/create-message-channel';
+export type { CreateMessageChannelInput } from '@/sdk/logic-function/messaging/create-message-channel';
+export { listMessageChannels } from '@/sdk/logic-function/messaging/list-message-channels';
+export type { ListMessageChannelsFilter } from '@/sdk/logic-function/messaging/list-message-channels';
+export { 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 type { AppMessageChannel } from '@/sdk/logic-function/messaging/types/app-message-channel.type';
+
export { runAgent } from '@/sdk/logic-function/agents/run-agent';
export type { RunAgentInput, RunAgentResult } from 'twenty-shared/application';
diff --git a/packages/twenty-sdk/src/sdk/logic-function/messaging/create-message-channel.ts b/packages/twenty-sdk/src/sdk/logic-function/messaging/create-message-channel.ts
new file mode 100644
index 00000000000..aeabf7ef303
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/logic-function/messaging/create-message-channel.ts
@@ -0,0 +1,43 @@
+import { type MessageChannelVisibility } from 'twenty-shared/types';
+
+import { APP_MESSAGE_CHANNEL_SELECTION } from '@/sdk/logic-function/messaging/message-channel-fields.constant';
+import { type AppMessageChannel } from '@/sdk/logic-function/messaging/types/app-message-channel.type';
+import { postGraphqlRequest } from '@/sdk/logic-function/utils/post-graphql-request.util';
+
+const CREATE_APP_MESSAGE_CHANNEL_MUTATION = `
+ mutation CreateAppMessageChannel($input: CreateAppMessageChannelInput!) {
+ createAppMessageChannel(input: $input) {
+ ${APP_MESSAGE_CHANNEL_SELECTION}
+ }
+ }
+`;
+
+export type CreateMessageChannelInput = {
+ // An app connection id, from `getConnection`/`listConnections`. The channel
+ // speaks through this credential and inherits who may see it.
+ connectedAccountId: string;
+ // This account's identity on the provider — whatever the provider calls it.
+ // Inbound participants matching it are treated as the account itself.
+ handle: string;
+ displayName?: string;
+ // Required rather than defaulted: this decides whether one member's
+ // conversations are readable by the whole workspace, and only the app
+ // knows how private its provider's messages are. Prefer 'METADATA' for
+ // personal inboxes and 'SHARE_EVERYTHING' for shared ones.
+ visibility: MessageChannelVisibility;
+};
+
+export const createMessageChannel = async (
+ input: CreateMessageChannelInput,
+): Promise<AppMessageChannel> => {
+ const { createAppMessageChannel } = await postGraphqlRequest<
+ { input: CreateMessageChannelInput },
+ { createAppMessageChannel: AppMessageChannel }
+ >({
+ query: CREATE_APP_MESSAGE_CHANNEL_MUTATION,
+ variables: { input },
+ caller: 'createMessageChannel',
+ });
+
+ return createAppMessageChannel;
+};
diff --git a/packages/twenty-sdk/src/sdk/logic-function/messaging/delete-message-channel.ts b/packages/twenty-sdk/src/sdk/logic-function/messaging/delete-message-channel.ts
new file mode 100644
index 00000000000..773d9696aaf
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/logic-function/messaging/delete-message-channel.ts
@@ -0,0 +1,30 @@
+import { APP_MESSAGE_CHANNEL_SELECTION } from '@/sdk/logic-function/messaging/message-channel-fields.constant';
+import { type AppMessageChannel } from '@/sdk/logic-function/messaging/types/app-message-channel.type';
+import { postGraphqlRequest } from '@/sdk/logic-function/utils/post-graphql-request.util';
+
+const DELETE_APP_MESSAGE_CHANNEL_MUTATION = `
+ mutation DeleteAppMessageChannel($id: UUID!) {
+ deleteAppMessageChannel(id: $id) {
+ ${APP_MESSAGE_CHANNEL_SELECTION}
+ }
+ }
+`;
+
+// Deleting a channel also deletes the messages ingested through it, and any
+// thread left with no messages. Call this from the connection provider's
+// onDisconnect hook to retire a channel along with its credential; to stop
+// ingesting while keeping the history, set `isSyncEnabled` to false instead.
+export const deleteMessageChannel = async (
+ id: string,
+): Promise<AppMessageChannel> => {
+ const { deleteAppMessageChannel } = await postGraphqlRequest<
+ { id: string },
+ { deleteAppMessageChannel: AppMessageChannel }
+ >({
+ query: DELETE_APP_MESSAGE_CHANNEL_MUTATION,
+ variables: { id },
+ caller: 'deleteMessageChannel',
+ });
+
+ return deleteAppMessageChannel;
+};
diff --git a/packages/twenty-sdk/src/sdk/logic-function/messaging/list-message-channels.ts b/packages/twenty-sdk/src/sdk/logic-function/messaging/list-message-channels.ts
new file mode 100644
index 00000000000..6834dbaab2f
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/logic-function/messaging/list-message-channels.ts
@@ -0,0 +1,30 @@
+import { APP_MESSAGE_CHANNEL_SELECTION } from '@/sdk/logic-function/messaging/message-channel-fields.constant';
+import { type AppMessageChannel } from '@/sdk/logic-function/messaging/types/app-message-channel.type';
+import { postGraphqlRequest } from '@/sdk/logic-function/utils/post-graphql-request.util';
+
+const LIST_APP_MESSAGE_CHANNELS_QUERY = `
+ query ListAppMessageChannels($filter: ListAppMessageChannelsInput) {
+ appMessageChannels(filter: $filter) {
+ ${APP_MESSAGE_CHANNEL_SELECTION}
+ }
+ }
+`;
+
+export type ListMessageChannelsFilter = {
+ connectedAccountId?: string;
+};
+
+export const listMessageChannels = async (
+ filter: ListMessageChannelsFilter = {},
+): Promise<AppMessageChannel[]> => {
+ const { appMessageChannels } = await postGraphqlRequest<
+ { filter: ListMessageChannelsFilter },
+ { appMessageChannels: AppMessageChannel[] }
+ >({
+ query: LIST_APP_MESSAGE_CHANNELS_QUERY,
+ variables: { filter },
+ caller: 'listMessageChannels',
+ });
+
+ return appMessageChannels;
+};
diff --git a/packages/twenty-sdk/src/sdk/logic-function/messaging/message-channel-fields.constant.ts b/packages/twenty-sdk/src/sdk/logic-function/messaging/message-channel-fields.constant.ts
new file mode 100644
index 00000000000..d06beed19e1
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/logic-function/messaging/message-channel-fields.constant.ts
@@ -0,0 +1,10 @@
+// Every helper selects the same fields, so an AppMessageChannel returned by
+// one is interchangeable with one returned by another.
+export const APP_MESSAGE_CHANNEL_SELECTION = `
+ id
+ handle
+ displayName
+ visibility
+ connectedAccountId
+ isSyncEnabled
+`;
diff --git a/packages/twenty-sdk/src/sdk/logic-function/messaging/types/app-message-channel.type.ts b/packages/twenty-sdk/src/sdk/logic-function/messaging/types/app-message-channel.type.ts
new file mode 100644
index 00000000000..fc77212d7e6
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/logic-function/messaging/types/app-message-channel.type.ts
@@ -0,0 +1,6 @@
+// One messaging channel the running app owns. Returned from
+// `createMessageChannel` and `listMessageChannels`.
+//
+// The shape lives in twenty-shared so this re-export and the server-side
+// projection always agree — changes propagate to both at once.
+export type { AppMessageChannel } from 'twenty-shared/application';
diff --git a/packages/twenty-sdk/src/sdk/logic-function/messaging/update-message-channel.ts b/packages/twenty-sdk/src/sdk/logic-function/messaging/update-message-channel.ts
new file mode 100644
index 00000000000..79b89b5a63f
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/logic-function/messaging/update-message-channel.ts
@@ -0,0 +1,40 @@
+import { type MessageChannelVisibility } from 'twenty-shared/types';
+
+import { APP_MESSAGE_CHANNEL_SELECTION } from '@/sdk/logic-function/messaging/message-channel-fields.constant';
+import { type AppMessageChannel } from '@/sdk/logic-function/messaging/types/app-message-channel.type';
+import { postGraphqlRequest } from '@/sdk/logic-function/utils/post-graphql-request.util';
+
+const UPDATE_APP_MESSAGE_CHANNEL_MUTATION = `
+ mutation UpdateAppMessageChannel($input: UpdateAppMessageChannelInput!) {
+ updateAppMessageChannel(input: $input) {
+ ${APP_MESSAGE_CHANNEL_SELECTION}
+ }
+ }
+`;
+
+export type UpdateMessageChannelInput = {
+ id: string;
+ // Omitted leaves the current label untouched; null clears it.
+ displayName?: string | null;
+ // Changing this changes who can read every message already ingested into
+ // the channel, not just the ones that follow.
+ visibility?: MessageChannelVisibility;
+ // False pauses ingestion without deleting the history; ingesting into a
+ // paused channel is rejected.
+ isSyncEnabled?: boolean;
+};
+
+export const updateMessageChannel = async (
+ input: UpdateMessageChannelInput,
+): Promise<AppMessageChannel> => {
+ const { updateAppMessageChannel } = await postGraphqlRequest<
+ { input: UpdateMessageChannelInput },
+ { updateAppMessageChannel: AppMessageChannel }
+ >({
+ query: UPDATE_APP_MESSAGE_CHANNEL_MUTATION,
+ variables: { input },
+ caller: 'updateMessageChannel',
+ });
+
+ return updateAppMessageChannel;
+};
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-41/2-41-instance-command-fast-1789395506192-add-app-message-channel-type.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-41/2-41-instance-command-fast-1789395506192-add-app-message-channel-type.ts
new file mode 100644
index 00000000000..f67f015d693
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-41/2-41-instance-command-fast-1789395506192-add-app-message-channel-type.ts
@@ -0,0 +1,25 @@
+import { QueryRunner } from 'typeorm';
+
+import { RegisteredInstanceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-instance-command.decorator';
+import { FastInstanceCommand } from 'src/engine/core-modules/upgrade/interfaces/fast-instance-command.interface';
+
+@RegisteredInstanceCommand('2.41.0', 1789395506192)
+export class AddAppMessageChannelTypeFastInstanceCommand implements FastInstanceCommand {
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query('ALTER TYPE "core"."messageChannel_type_enum" RENAME TO "messageChannel_type_enum_old"');
+ await queryRunner.query('CREATE TYPE "core"."messageChannel_type_enum" AS ENUM(\'EMAIL\', \'SMS\', \'EMAIL_GROUP\', \'APP\')');
+ await queryRunner.query('ALTER TABLE "core"."messageChannel" ALTER COLUMN "type" TYPE "core"."messageChannel_type_enum" USING "type"::"text"::"core"."messageChannel_type_enum"');
+ await queryRunner.query('DROP TYPE "core"."messageChannel_type_enum_old"');
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ // Narrowing the enum casts every existing row into it, so an APP channel
+ // left behind makes the rollback itself fail. Rolling back removes the
+ // code that can read these channels, so the rows are already dead.
+ await queryRunner.query('DELETE FROM "core"."messageChannel" WHERE "type" = \'APP\'');
+ await queryRunner.query('CREATE TYPE "core"."messageChannel_type_enum_old" AS ENUM(\'EMAIL\', \'SMS\', \'EMAIL_GROUP\')');
+ await queryRunner.query('ALTER TABLE "core"."messageChannel" ALTER COLUMN "type" TYPE "core"."messageChannel_type_enum_old" USING "type"::"text"::"core"."messageChannel_type_enum_old"');
+ await queryRunner.query('DROP TYPE "core"."messageChannel_type_enum"');
+ await queryRunner.query('ALTER TYPE "core"."messageChannel_type_enum_old" RENAME TO "messageChannel_type_enum"');
+ }
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-41/2-41-instance-command-fast-1789418882171-add-app-message-channel-unique-handle.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-41/2-41-instance-command-fast-1789418882171-add-app-message-channel-unique-handle.ts
new file mode 100644
index 00000000000..efb414ab405
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-41/2-41-instance-command-fast-1789418882171-add-app-message-channel-unique-handle.ts
@@ -0,0 +1,15 @@
+import { QueryRunner } from 'typeorm';
+
+import { RegisteredInstanceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-instance-command.decorator';
+import { FastInstanceCommand } from 'src/engine/core-modules/upgrade/interfaces/fast-instance-command.interface';
+
+@RegisteredInstanceCommand('2.41.0', 1789418882171)
+export class AddAppMessageChannelUniqueHandleFastInstanceCommand implements FastInstanceCommand {
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query('CREATE UNIQUE INDEX "IDX_MESSAGE_CHANNEL_APP_CONNECTED_ACCOUNT_HANDLE_UNIQUE" ON "core"."messageChannel" ("workspaceId", "connectedAccountId", "handle") WHERE "type" = \'APP\'');
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query('DROP INDEX "core"."IDX_MESSAGE_CHANNEL_APP_CONNECTED_ACCOUNT_HANDLE_UNIQUE"');
+ }
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
index 66486748d31..7878212344e 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
@@ -191,6 +191,8 @@ import { MigrateCanvasTabsToVerticalListSlowInstanceCommand } from 'src/database
import { AddWorkspaceWorkflowIdToWorkflowFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-41/2-41-instance-command-fast-1789350000001-add-workspace-workflow-id-to-workflow';
import { AddCoreVersionPointersFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-41/2-41-instance-command-fast-1789370101008-add-core-version-pointers';
import { AddReadabilityParentFieldsToObjectMetadataFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-41/2-41-instance-command-fast-1789373200000-add-readability-parent-fields-to-object-metadata';
+import { AddAppMessageChannelTypeFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-41/2-41-instance-command-fast-1789395506192-add-app-message-channel-type';
+import { AddAppMessageChannelUniqueHandleFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-41/2-41-instance-command-fast-1789418882171-add-app-message-channel-unique-handle';
export const INSTANCE_COMMANDS = [
AddViewFieldGroupIdIndexOnViewFieldFastInstanceCommand,
@@ -384,4 +386,6 @@ export const INSTANCE_COMMANDS = [
AddWorkspaceWorkflowIdToWorkflowFastInstanceCommand,
AddCoreVersionPointersFastInstanceCommand,
AddReadabilityParentFieldsToObjectMetadataFastInstanceCommand,
+ AddAppMessageChannelTypeFastInstanceCommand,
+ AddAppMessageChannelUniqueHandleFastInstanceCommand,
];
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/create-app-message-channel.input.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/create-app-message-channel.input.ts
new file mode 100644
index 00000000000..a21b209f588
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/create-app-message-channel.input.ts
@@ -0,0 +1,41 @@
+import { Field, InputType } from '@nestjs/graphql';
+
+import {
+ IsEnum,
+ IsNotEmpty,
+ IsOptional,
+ IsString,
+ IsUUID,
+ MaxLength,
+} from 'class-validator';
+import { MessageChannelVisibility } from 'twenty-shared/types';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+
+@InputType('CreateAppMessageChannelInput')
+export class CreateAppMessageChannelInput {
+ @Field(() => UUIDScalarType)
+ @IsUUID()
+ @IsNotEmpty()
+ connectedAccountId: string;
+
+ @Field()
+ @IsString()
+ @IsNotEmpty()
+ @MaxLength(255)
+ handle: string;
+
+ @Field({ nullable: true })
+ @IsOptional()
+ @IsString()
+ @MaxLength(255)
+ displayName?: string;
+
+ // Deliberately required: a default here would decide, silently and for
+ // every app, whether one member's conversations are readable by the whole
+ // workspace. The app author knows which its provider's messages are.
+ @Field(() => MessageChannelVisibility)
+ @IsEnum(MessageChannelVisibility)
+ @IsNotEmpty()
+ visibility: MessageChannelVisibility;
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/list-app-message-channels.input.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/list-app-message-channels.input.ts
new file mode 100644
index 00000000000..8d7b6a0b7e5
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/list-app-message-channels.input.ts
@@ -0,0 +1,13 @@
+import { Field, InputType } from '@nestjs/graphql';
+
+import { IsOptional, IsUUID } from 'class-validator';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+
+@InputType('ListAppMessageChannelsInput')
+export class ListAppMessageChannelsInput {
+ @Field(() => UUIDScalarType, { nullable: true })
+ @IsOptional()
+ @IsUUID()
+ connectedAccountId?: string;
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/update-app-message-channel.input.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/update-app-message-channel.input.ts
new file mode 100644
index 00000000000..cb5733d83e3
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/update-app-message-channel.input.ts
@@ -0,0 +1,39 @@
+import { Field, InputType } from '@nestjs/graphql';
+
+import {
+ IsBoolean,
+ IsEnum,
+ IsNotEmpty,
+ IsOptional,
+ IsString,
+ IsUUID,
+ MaxLength,
+} from 'class-validator';
+import { MessageChannelVisibility } from 'twenty-shared/types';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+
+@InputType('UpdateAppMessageChannelInput')
+export class UpdateAppMessageChannelInput {
+ @Field(() => UUIDScalarType)
+ @IsUUID()
+ @IsNotEmpty()
+ id: string;
+
+ // An omitted displayName leaves the current one untouched; an explicit null clears it
+ @Field(() => String, { nullable: true })
+ @IsOptional()
+ @IsString()
+ @MaxLength(255)
+ displayName?: string | null;
+
+ @Field(() => MessageChannelVisibility, { nullable: true })
+ @IsOptional()
+ @IsEnum(MessageChannelVisibility)
+ visibility?: MessageChannelVisibility;
+
+ @Field({ nullable: true })
+ @IsOptional()
+ @IsBoolean()
+ isSyncEnabled?: boolean;
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/entities/message-channel.entity.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/entities/message-channel.entity.ts
index f3d438ae634..a1323e3695a 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/entities/message-channel.entity.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/entities/message-channel.entity.ts
@@ -59,6 +59,15 @@ registerEnumType(MessageChannelPendingGroupEmailsAction, {
['webhookSubscriptionExternalId'],
{ where: '"webhookSubscriptionExternalId" IS NOT NULL' },
)
+// An app creates its channel from a connect hook, which a provider can retry
+// or run concurrently. The create path reads before it writes, so only the
+// database can actually stop a second row appearing for one handle. Scoped to
+// APP so it makes no claim about the email rows already in this table.
+@Index(
+ 'IDX_MESSAGE_CHANNEL_APP_CONNECTED_ACCOUNT_HANDLE_UNIQUE',
+ ['workspaceId', 'connectedAccountId', 'handle'],
+ { unique: true, where: `"type" = 'APP'` },
+)
export class MessageChannelEntity extends WorkspaceRelatedEntity {
@PrimaryGeneratedColumn('uuid')
id: string;
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.ts
index 236762fc72b..9de9e00607a 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
@@ -3,10 +3,13 @@ import { TypeOrmModule } from '@nestjs/typeorm';
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';
import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
import { 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 { 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 { 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';
@@ -14,7 +17,11 @@ import { MessagingImportManagerModule } from 'src/modules/messaging/message-impo
@Module({
imports: [
- TypeOrmModule.forFeature([MessageChannelEntity, MessageFolderEntity]),
+ TypeOrmModule.forFeature([
+ MessageChannelEntity,
+ MessageFolderEntity,
+ ConnectedAccountEntity,
+ ]),
PermissionsModule,
ConnectedAccountMetadataModule,
MessagingImportManagerModule,
@@ -24,6 +31,8 @@ import { MessagingImportManagerModule } from 'src/modules/messaging/message-impo
providers: [
MessageChannelMetadataService,
MessageChannelResolver,
+ ApplicationMessageChannelsService,
+ ApplicationMessageChannelsResolver,
MessageChannelGraphqlApiExceptionInterceptor,
],
exports: [MessageChannelMetadataService],
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/application-message-channels.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/application-message-channels.resolver.ts
new file mode 100644
index 00000000000..73fe84f8d51
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/application-message-channels.resolver.ts
@@ -0,0 +1,99 @@
+import { UseGuards, UseInterceptors, UsePipes } from '@nestjs/common';
+import { Args, Mutation, Query } 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 { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+import { CreateAppMessageChannelInput } from 'src/engine/metadata-modules/message-channel/dtos/create-app-message-channel.input';
+import { ListAppMessageChannelsInput } from 'src/engine/metadata-modules/message-channel/dtos/list-app-message-channels.input';
+import { MessageChannelDTO } from 'src/engine/metadata-modules/message-channel/dtos/message-channel.dto';
+import { UpdateAppMessageChannelInput } from 'src/engine/metadata-modules/message-channel/dtos/update-app-message-channel.input';
+import { MessageChannelGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules/message-channel/interceptors/message-channel-graphql-api-exception.interceptor';
+import { ApplicationMessageChannelsService } from 'src/engine/metadata-modules/message-channel/services/application-message-channels.service';
+
+@UseGuards(WorkspaceAuthGuard, NoPermissionGuard)
+@UseInterceptors(MessageChannelGraphqlApiExceptionInterceptor)
+@UsePipes(ResolverValidationPipe)
+@MetadataResolver()
+export class ApplicationMessageChannelsResolver {
+ constructor(
+ private readonly applicationMessageChannelsService: ApplicationMessageChannelsService,
+ ) {}
+
+ @Query(() => [MessageChannelDTO])
+ async appMessageChannels(
+ @AuthApplication() application: FlatApplication,
+ @AuthWorkspace() workspace: FlatWorkspace,
+ @AuthUserWorkspaceId({ allowUndefined: true })
+ userWorkspaceId: string | undefined,
+ @Args('filter', { nullable: true }) filter?: ListAppMessageChannelsInput,
+ ): Promise<MessageChannelDTO[]> {
+ return this.applicationMessageChannelsService.list({
+ applicationId: application.id,
+ workspaceId: workspace.id,
+ requestUserWorkspaceId: userWorkspaceId ?? null,
+ connectedAccountId: filter?.connectedAccountId,
+ });
+ }
+
+ @Mutation(() => MessageChannelDTO)
+ async createAppMessageChannel(
+ @AuthApplication() application: FlatApplication,
+ @AuthWorkspace() workspace: FlatWorkspace,
+ @AuthUserWorkspaceId({ allowUndefined: true })
+ userWorkspaceId: string | undefined,
+ @Args('input') input: CreateAppMessageChannelInput,
+ ): Promise<MessageChannelDTO> {
+ return this.applicationMessageChannelsService.create({
+ applicationId: application.id,
+ workspaceId: workspace.id,
+ requestUserWorkspaceId: userWorkspaceId ?? null,
+ connectedAccountId: input.connectedAccountId,
+ handle: input.handle,
+ displayName: input.displayName,
+ visibility: input.visibility,
+ });
+ }
+
+ @Mutation(() => MessageChannelDTO)
+ async updateAppMessageChannel(
+ @AuthApplication() application: FlatApplication,
+ @AuthWorkspace() workspace: FlatWorkspace,
+ @AuthUserWorkspaceId({ allowUndefined: true })
+ userWorkspaceId: string | undefined,
+ @Args('input') input: UpdateAppMessageChannelInput,
+ ): Promise<MessageChannelDTO> {
+ return this.applicationMessageChannelsService.update({
+ applicationId: application.id,
+ workspaceId: workspace.id,
+ requestUserWorkspaceId: userWorkspaceId ?? null,
+ id: input.id,
+ displayName: input.displayName,
+ visibility: input.visibility,
+ isSyncEnabled: input.isSyncEnabled,
+ });
+ }
+
+ @Mutation(() => MessageChannelDTO)
+ async deleteAppMessageChannel(
+ @AuthApplication() application: FlatApplication,
+ @AuthWorkspace() workspace: FlatWorkspace,
+ @AuthUserWorkspaceId({ allowUndefined: true })
+ userWorkspaceId: string | undefined,
+ @Args('id', { type: () => UUIDScalarType }) id: string,
+ ): Promise<MessageChannelDTO> {
+ return this.applicationMessageChannelsService.delete({
+ applicationId: application.id,
+ workspaceId: workspace.id,
+ requestUserWorkspaceId: userWorkspaceId ?? null,
+ id,
+ });
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/message-channel.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/message-channel.resolver.ts
index 4a1ae0ffb9f..c97df4e5a2d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/message-channel.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/message-channel.resolver.ts
@@ -124,6 +124,18 @@ export class MessageChannelResolver {
applicationId: application?.id,
});
+ // An app channel's settings belong to the app that created it: its
+ // visibility is the app's statement about how private its provider's
+ // messages are, and the mailbox fields on this input (folder import
+ // policy, group-email exclusions, contact auto-creation) have no meaning
+ // for it. Mutations go through updateAppMessageChannel instead.
+ if (messageChannel.type === MessageChannelType.APP) {
+ throw new MessageChannelException(
+ `Message channel ${input.id} is owned by an application and cannot be updated through this endpoint`,
+ MessageChannelExceptionCode.MESSAGE_CHANNEL_OWNERSHIP_VIOLATION,
+ );
+ }
+
const isSyncOngoing =
messageChannel.syncStage ===
MessageChannelSyncStage.MESSAGE_LIST_FETCH_ONGOING;
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/services/__tests__/application-message-channels.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/services/__tests__/application-message-channels.service.spec.ts
new file mode 100644
index 00000000000..ea053b7fd79
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/services/__tests__/application-message-channels.service.spec.ts
@@ -0,0 +1,432 @@
+import { Test, type TestingModule } from '@nestjs/testing';
+import { getRepositoryToken } from '@nestjs/typeorm';
+
+import {
+ ConnectedAccountProvider,
+ MessageChannelType,
+ MessageChannelVisibility,
+} from 'twenty-shared/types';
+import { type Repository } from 'typeorm';
+
+import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
+import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
+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 { WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';
+
+const APPLICATION_ID = '11111111-1111-4111-8111-111111111111';
+const OTHER_APPLICATION_ID = '22222222-2222-4222-8222-222222222222';
+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 ALICE_USER_WORKSPACE_ID = '99999999-9999-4999-8999-999999999999';
+const BOB_USER_WORKSPACE_ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+
+describe('ApplicationMessageChannelsService', () => {
+ let service: ApplicationMessageChannelsService;
+ let messageChannelRepository: jest.Mocked<Repository<MessageChannelEntity>>;
+ let connectedAccountRepository: jest.Mocked<
+ Repository<ConnectedAccountEntity>
+ >;
+ let workspaceEventEmitter: jest.Mocked<WorkspaceEventEmitter>;
+
+ // No request user: a cron/webhook run acting as the application itself.
+ const scope = {
+ applicationId: APPLICATION_ID,
+ workspaceId: WORKSPACE_ID,
+ requestUserWorkspaceId: null,
+ };
+
+ beforeEach(async () => {
+ messageChannelRepository = {
+ find: jest.fn().mockResolvedValue([]),
+ findOne: jest.fn().mockResolvedValue(null),
+ findOneOrFail: jest.fn(),
+ create: jest.fn().mockImplementation((data) => data),
+ save: jest.fn().mockImplementation(async (data) => data),
+ update: jest.fn(),
+ delete: jest.fn(),
+ } as unknown as jest.Mocked<Repository<MessageChannelEntity>>;
+
+ connectedAccountRepository = {
+ find: jest.fn().mockResolvedValue([]),
+ findOne: jest.fn().mockResolvedValue(null),
+ } as unknown as jest.Mocked<Repository<ConnectedAccountEntity>>;
+
+ workspaceEventEmitter = {
+ emitCustomBatchEvent: jest.fn(),
+ } as unknown as jest.Mocked<WorkspaceEventEmitter>;
+
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ ApplicationMessageChannelsService,
+ {
+ provide: getRepositoryToken(MessageChannelEntity),
+ useValue: messageChannelRepository,
+ },
+ {
+ provide: getRepositoryToken(ConnectedAccountEntity),
+ useValue: connectedAccountRepository,
+ },
+ { provide: WorkspaceEventEmitter, useValue: workspaceEventEmitter },
+ ],
+ }).compile();
+
+ service = module.get(ApplicationMessageChannelsService);
+ });
+
+ const givenTheAppOwnsTheConnection = () => {
+ connectedAccountRepository.findOne.mockResolvedValue({
+ id: CONNECTED_ACCOUNT_ID,
+ applicationId: APPLICATION_ID,
+ workspaceId: WORKSPACE_ID,
+ provider: ConnectedAccountProvider.APP,
+ visibility: 'workspace',
+ userWorkspaceId: ALICE_USER_WORKSPACE_ID,
+ } as ConnectedAccountEntity);
+ connectedAccountRepository.find.mockResolvedValue([
+ {
+ id: CONNECTED_ACCOUNT_ID,
+ visibility: 'workspace',
+ userWorkspaceId: ALICE_USER_WORKSPACE_ID,
+ },
+ ] as ConnectedAccountEntity[]);
+ };
+
+ describe('create', () => {
+ it('creates an APP channel on a connection the app owns', async () => {
+ givenTheAppOwnsTheConnection();
+
+ const channel = await service.create({
+ ...scope,
+ connectedAccountId: CONNECTED_ACCOUNT_ID,
+ handle: 'urn:li:person:abc',
+ displayName: ' Ada Lovelace ',
+ visibility: MessageChannelVisibility.METADATA,
+ });
+
+ expect(channel).toEqual(
+ expect.objectContaining({
+ workspaceId: WORKSPACE_ID,
+ connectedAccountId: CONNECTED_ACCOUNT_ID,
+ handle: 'urn:li:person:abc',
+ displayName: 'Ada Lovelace',
+ type: MessageChannelType.APP,
+ visibility: MessageChannelVisibility.METADATA,
+ isSyncEnabled: true,
+ }),
+ );
+ });
+
+ it('persists the visibility the app asked for rather than a default', async () => {
+ givenTheAppOwnsTheConnection();
+
+ const channel = await service.create({
+ ...scope,
+ connectedAccountId: CONNECTED_ACCOUNT_ID,
+ handle: 'urn:li:person:abc',
+ visibility: MessageChannelVisibility.SHARE_EVERYTHING,
+ });
+
+ expect(channel.visibility).toBe(
+ MessageChannelVisibility.SHARE_EVERYTHING,
+ );
+ });
+
+ it('refuses a connection belonging to another application', async () => {
+ connectedAccountRepository.findOne.mockResolvedValue(null);
+
+ await expect(
+ service.create({
+ applicationId: OTHER_APPLICATION_ID,
+ workspaceId: WORKSPACE_ID,
+ requestUserWorkspaceId: null,
+ connectedAccountId: CONNECTED_ACCOUNT_ID,
+ handle: 'urn:li:person:abc',
+ visibility: MessageChannelVisibility.METADATA,
+ }),
+ ).rejects.toThrow(MessageChannelException);
+
+ expect(messageChannelRepository.save).not.toHaveBeenCalled();
+ });
+
+ it('refuses a second channel for the same handle on one connection', async () => {
+ givenTheAppOwnsTheConnection();
+ messageChannelRepository.findOne.mockResolvedValue({
+ id: MESSAGE_CHANNEL_ID,
+ } as MessageChannelEntity);
+
+ await expect(
+ service.create({
+ ...scope,
+ connectedAccountId: CONNECTED_ACCOUNT_ID,
+ handle: 'urn:li:person:abc',
+ visibility: MessageChannelVisibility.METADATA,
+ }),
+ ).rejects.toMatchObject({
+ code: MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,
+ });
+ });
+ });
+
+ describe('update', () => {
+ it('refuses a channel owned by another application', async () => {
+ messageChannelRepository.findOne.mockResolvedValue({
+ id: MESSAGE_CHANNEL_ID,
+ connectedAccountId: CONNECTED_ACCOUNT_ID,
+ type: MessageChannelType.APP,
+ } as MessageChannelEntity);
+ connectedAccountRepository.findOne.mockResolvedValue(null);
+
+ await expect(
+ service.update({
+ applicationId: OTHER_APPLICATION_ID,
+ workspaceId: WORKSPACE_ID,
+ requestUserWorkspaceId: null,
+ id: MESSAGE_CHANNEL_ID,
+ displayName: 'stolen',
+ }),
+ ).rejects.toMatchObject({
+ code: MessageChannelExceptionCode.MESSAGE_CHANNEL_NOT_FOUND,
+ });
+
+ expect(messageChannelRepository.update).not.toHaveBeenCalled();
+ });
+
+ it('clears the display name on an explicit null but leaves it on omission', async () => {
+ const existing = {
+ id: MESSAGE_CHANNEL_ID,
+ connectedAccountId: CONNECTED_ACCOUNT_ID,
+ type: MessageChannelType.APP,
+ displayName: 'Ada',
+ } as MessageChannelEntity;
+
+ messageChannelRepository.findOne.mockResolvedValue(existing);
+ messageChannelRepository.findOneOrFail.mockResolvedValue(existing);
+ givenTheAppOwnsTheConnection();
+
+ await service.update({ ...scope, id: MESSAGE_CHANNEL_ID });
+ expect(messageChannelRepository.update).not.toHaveBeenCalled();
+
+ await service.update({
+ ...scope,
+ id: MESSAGE_CHANNEL_ID,
+ displayName: null,
+ });
+ expect(messageChannelRepository.update).toHaveBeenCalledWith(
+ { id: MESSAGE_CHANNEL_ID, workspaceId: WORKSPACE_ID },
+ { displayName: null },
+ );
+ });
+
+ it('does not resolve a channel that is not app-owned', async () => {
+ messageChannelRepository.findOne.mockResolvedValue(null);
+
+ await expect(
+ service.update({
+ ...scope,
+ id: MESSAGE_CHANNEL_ID,
+ isSyncEnabled: false,
+ }),
+ ).rejects.toMatchObject({
+ code: MessageChannelExceptionCode.MESSAGE_CHANNEL_NOT_FOUND,
+ });
+
+ expect(messageChannelRepository.findOne).toHaveBeenCalledWith({
+ where: {
+ id: MESSAGE_CHANNEL_ID,
+ workspaceId: WORKSPACE_ID,
+ type: MessageChannelType.APP,
+ },
+ });
+ });
+ });
+
+ describe('delete', () => {
+ it('emits the channel-deleted event so ingested messages are cleaned up', async () => {
+ messageChannelRepository.findOne.mockResolvedValue({
+ id: MESSAGE_CHANNEL_ID,
+ connectedAccountId: CONNECTED_ACCOUNT_ID,
+ type: MessageChannelType.APP,
+ } as MessageChannelEntity);
+ givenTheAppOwnsTheConnection();
+
+ await service.delete({ ...scope, id: MESSAGE_CHANNEL_ID });
+
+ expect(messageChannelRepository.delete).toHaveBeenCalledWith({
+ id: MESSAGE_CHANNEL_ID,
+ workspaceId: WORKSPACE_ID,
+ });
+ expect(workspaceEventEmitter.emitCustomBatchEvent).toHaveBeenCalledWith(
+ expect.any(String),
+ [{ messageChannelId: MESSAGE_CHANNEL_ID }],
+ WORKSPACE_ID,
+ );
+ });
+ });
+
+ describe('list', () => {
+ it('returns nothing when the app holds no connections', async () => {
+ connectedAccountRepository.find.mockResolvedValue([]);
+
+ await expect(service.list(scope)).resolves.toEqual([]);
+ expect(messageChannelRepository.find).not.toHaveBeenCalled();
+ });
+
+ it('refuses to filter by a connection the app does not own', async () => {
+ connectedAccountRepository.find.mockResolvedValue([
+ {
+ id: CONNECTED_ACCOUNT_ID,
+ visibility: 'workspace',
+ userWorkspaceId: ALICE_USER_WORKSPACE_ID,
+ },
+ ] as ConnectedAccountEntity[]);
+
+ await expect(
+ service.list({ ...scope, connectedAccountId: 'someone-elses' }),
+ ).rejects.toMatchObject({
+ code: MessageChannelExceptionCode.MESSAGE_CHANNEL_OWNERSHIP_VIOLATION,
+ });
+ });
+ });
+ // Owning the app is not permission to administer another person's private
+ // connection. Same application, two users, one private connection.
+ describe("another user's private connection", () => {
+ const givenAlicePrivateConnection = () => {
+ const alicesAccount = {
+ id: CONNECTED_ACCOUNT_ID,
+ applicationId: APPLICATION_ID,
+ workspaceId: WORKSPACE_ID,
+ provider: ConnectedAccountProvider.APP,
+ visibility: 'user',
+ userWorkspaceId: ALICE_USER_WORKSPACE_ID,
+ } as ConnectedAccountEntity;
+
+ connectedAccountRepository.findOne.mockResolvedValue(alicesAccount);
+ connectedAccountRepository.find.mockResolvedValue([alicesAccount]);
+ messageChannelRepository.findOne.mockResolvedValue({
+ id: MESSAGE_CHANNEL_ID,
+ connectedAccountId: CONNECTED_ACCOUNT_ID,
+ type: MessageChannelType.APP,
+ } as MessageChannelEntity);
+ };
+
+ const asBob = {
+ applicationId: APPLICATION_ID,
+ workspaceId: WORKSPACE_ID,
+ requestUserWorkspaceId: BOB_USER_WORKSPACE_ID,
+ };
+ const asAlice = {
+ applicationId: APPLICATION_ID,
+ workspaceId: WORKSPACE_ID,
+ requestUserWorkspaceId: ALICE_USER_WORKSPACE_ID,
+ };
+
+ it("hides Alice's channel from Bob's listing", async () => {
+ givenAlicePrivateConnection();
+
+ await expect(service.list(asBob)).resolves.toEqual([]);
+ expect(messageChannelRepository.find).not.toHaveBeenCalled();
+ });
+
+ it("refuses Bob a visibility change on Alice's channel", async () => {
+ givenAlicePrivateConnection();
+
+ await expect(
+ service.update({
+ ...asBob,
+ id: MESSAGE_CHANNEL_ID,
+ visibility: MessageChannelVisibility.SHARE_EVERYTHING,
+ }),
+ ).rejects.toMatchObject({
+ // Indistinguishable from a channel that does not exist.
+ code: MessageChannelExceptionCode.MESSAGE_CHANNEL_NOT_FOUND,
+ });
+
+ expect(messageChannelRepository.update).not.toHaveBeenCalled();
+ });
+
+ it("refuses Bob deletion of Alice's channel", async () => {
+ givenAlicePrivateConnection();
+
+ await expect(
+ service.delete({ ...asBob, id: MESSAGE_CHANNEL_ID }),
+ ).rejects.toMatchObject({
+ code: MessageChannelExceptionCode.MESSAGE_CHANNEL_NOT_FOUND,
+ });
+
+ expect(messageChannelRepository.delete).not.toHaveBeenCalled();
+ });
+
+ it("refuses Bob a channel on Alice's connection", async () => {
+ givenAlicePrivateConnection();
+
+ await expect(
+ service.create({
+ ...asBob,
+ connectedAccountId: CONNECTED_ACCOUNT_ID,
+ handle: 'urn:li:person:abc',
+ visibility: MessageChannelVisibility.METADATA,
+ }),
+ ).rejects.toMatchObject({
+ code: MessageChannelExceptionCode.MESSAGE_CHANNEL_OWNERSHIP_VIOLATION,
+ });
+
+ expect(messageChannelRepository.save).not.toHaveBeenCalled();
+ });
+
+ it('still lets Alice reach her own channel', async () => {
+ givenAlicePrivateConnection();
+ messageChannelRepository.findOneOrFail.mockResolvedValue({
+ id: MESSAGE_CHANNEL_ID,
+ } as MessageChannelEntity);
+
+ await expect(
+ service.update({
+ ...asAlice,
+ id: MESSAGE_CHANNEL_ID,
+ visibility: MessageChannelVisibility.SHARE_EVERYTHING,
+ }),
+ ).resolves.toBeDefined();
+ expect(messageChannelRepository.update).toHaveBeenCalled();
+ });
+
+ it('still lets a background run with no request user through', async () => {
+ givenAlicePrivateConnection();
+ messageChannelRepository.findOneOrFail.mockResolvedValue({
+ id: MESSAGE_CHANNEL_ID,
+ } as MessageChannelEntity);
+
+ await expect(
+ service.update({
+ ...scope,
+ id: MESSAGE_CHANNEL_ID,
+ isSyncEnabled: false,
+ }),
+ ).resolves.toBeDefined();
+ });
+ });
+ it('never names the connection when refusing a channel it cannot reach', async () => {
+ messageChannelRepository.findOne.mockResolvedValue({
+ id: MESSAGE_CHANNEL_ID,
+ connectedAccountId: CONNECTED_ACCOUNT_ID,
+ type: MessageChannelType.APP,
+ } as MessageChannelEntity);
+ connectedAccountRepository.findOne.mockResolvedValue(null);
+
+ await expect(
+ service.update({
+ applicationId: OTHER_APPLICATION_ID,
+ workspaceId: WORKSPACE_ID,
+ requestUserWorkspaceId: null,
+ id: MESSAGE_CHANNEL_ID,
+ displayName: 'probe',
+ }),
+ ).rejects.toMatchObject({
+ message: expect.not.stringContaining(CONNECTED_ACCOUNT_ID),
+ });
+ });
+});
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.ts
new file mode 100644
index 00000000000..8704d2a2b09
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-channels.service.ts
@@ -0,0 +1,350 @@
+import { Injectable } from '@nestjs/common';
+import { InjectRepository } from '@nestjs/typeorm';
+
+import { isNonEmptyString } from '@sniptt/guards';
+import {
+ ConnectedAccountProvider,
+ MessageChannelContactAutoCreationPolicy,
+ MessageChannelPendingGroupEmailsAction,
+ MessageChannelSyncStage,
+ MessageChannelSyncStatus,
+ MessageChannelType,
+ type MessageChannelVisibility,
+} from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+import { In, Repository } from 'typeorm';
+
+import { MESSAGE_CHANNEL_DELETED_EVENT } from 'src/engine/metadata-modules/message-channel/constants/message-channel-deleted.constant';
+import { isConnectionHiddenFromRequestUser } from 'src/engine/core-modules/application/connection-provider/connections/utils/is-connection-hidden-from-request-user.util';
+import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
+import { type MessageChannelDTO } from 'src/engine/metadata-modules/message-channel/dtos/message-channel.dto';
+import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
+import {
+ MessageChannelException,
+ MessageChannelExceptionCode,
+} from 'src/engine/metadata-modules/message-channel/message-channel.exception';
+import { type MessageChannelDeletedEvent } from 'src/engine/metadata-modules/message-channel/types/message-channel-deleted.type';
+import { WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';
+
+type ApplicationScope = {
+ applicationId: string;
+ workspaceId: string;
+ // The user behind the call, when there is one. An APPLICATION_ACCESS token
+ // carries them whenever a person triggered the run, and owning the app is
+ // not the same as being allowed to administer another person's private
+ // connection — so the channel API has to honour the same boundary the
+ // connection API does. Null for cron, webhooks and install hooks, which act
+ // as the application itself.
+ requestUserWorkspaceId: string | null;
+};
+
+type CreateArgs = ApplicationScope & {
+ connectedAccountId: string;
+ handle: string;
+ displayName?: string;
+ visibility: MessageChannelVisibility;
+};
+
+type UpdateArgs = ApplicationScope & {
+ id: string;
+ displayName?: string | null;
+ visibility?: MessageChannelVisibility;
+ isSyncEnabled?: boolean;
+};
+
+// The scalar subset an app may change. Narrower than Partial<MessageChannelEntity>,
+// which carries the relations TypeORM's update() cannot take.
+type UpdatableChannelFields = Partial<
+ Pick<MessageChannelEntity, 'displayName' | 'visibility' | 'isSyncEnabled'>
+>;
+
+export type OwnedMessageChannel = {
+ messageChannel: MessageChannelEntity;
+ connectedAccount: ConnectedAccountEntity;
+};
+
+// A name that is only whitespace is no name: stored as null so the UI falls
+// back to the handle, rather than rendering a blank row.
+const normalizeDisplayName = (displayName?: string | null): string | null => {
+ const trimmedDisplayName = displayName?.trim();
+
+ return isNonEmptyString(trimmedDisplayName) ? trimmedDisplayName : null;
+};
+
+@Injectable()
+export class ApplicationMessageChannelsService {
+ constructor(
+ @InjectRepository(MessageChannelEntity)
+ private readonly messageChannelRepository: Repository<MessageChannelEntity>,
+ @InjectRepository(ConnectedAccountEntity)
+ private readonly connectedAccountRepository: Repository<ConnectedAccountEntity>,
+ private readonly workspaceEventEmitter: WorkspaceEventEmitter,
+ ) {}
+
+ async list({
+ applicationId,
+ workspaceId,
+ requestUserWorkspaceId,
+ connectedAccountId,
+ }: ApplicationScope & {
+ connectedAccountId?: string;
+ }): Promise<MessageChannelDTO[]> {
+ const ownedAccountIds = await this.findReachableConnectedAccountIds({
+ applicationId,
+ workspaceId,
+ requestUserWorkspaceId,
+ });
+
+ if (ownedAccountIds.length === 0) {
+ return [];
+ }
+
+ if (
+ isDefined(connectedAccountId) &&
+ !ownedAccountIds.includes(connectedAccountId)
+ ) {
+ throw this.ownershipViolation(connectedAccountId);
+ }
+
+ return this.messageChannelRepository.find({
+ where: {
+ connectedAccountId: isDefined(connectedAccountId)
+ ? connectedAccountId
+ : In(ownedAccountIds),
+ workspaceId,
+ type: MessageChannelType.APP,
+ },
+ });
+ }
+
+ async create({
+ applicationId,
+ workspaceId,
+ requestUserWorkspaceId,
+ connectedAccountId,
+ handle,
+ displayName,
+ visibility,
+ }: CreateArgs): Promise<MessageChannelDTO> {
+ await this.assertOwnsConnectedAccount({
+ applicationId,
+ workspaceId,
+ requestUserWorkspaceId,
+ connectedAccountId,
+ });
+
+ const existingChannel = await this.messageChannelRepository.findOne({
+ where: { connectedAccountId, handle, workspaceId },
+ });
+
+ if (isDefined(existingChannel)) {
+ throw new MessageChannelException(
+ `A message channel already exists for handle ${handle} on connection ${connectedAccountId}`,
+ MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,
+ );
+ }
+
+ const entity = this.messageChannelRepository.create({
+ workspaceId,
+ connectedAccountId,
+ handle,
+ displayName: normalizeDisplayName(displayName),
+ type: MessageChannelType.APP,
+ visibility,
+ isSyncEnabled: true,
+ // Inert for an app channel: it is excluded from the polling crons, which
+ // are the only writers of these fields. Mirrors EMAIL_GROUP, the other
+ // push-delivered channel, so the sync-status UI reads it as healthy.
+ syncStage: MessageChannelSyncStage.MESSAGE_LIST_FETCH_PENDING,
+ syncStatus: MessageChannelSyncStatus.ACTIVE,
+ isContactAutoCreationEnabled: false,
+ contactAutoCreationPolicy: MessageChannelContactAutoCreationPolicy.SENT,
+ excludeGroupEmails: false,
+ excludeNonProfessionalEmails: false,
+ pendingGroupEmailsAction: MessageChannelPendingGroupEmailsAction.NONE,
+ });
+
+ return this.messageChannelRepository.save(entity);
+ }
+
+ async update({
+ applicationId,
+ workspaceId,
+ requestUserWorkspaceId,
+ id,
+ displayName,
+ visibility,
+ isSyncEnabled,
+ }: UpdateArgs): Promise<MessageChannelDTO> {
+ const { messageChannel } = await this.findOwnedOrThrow({
+ applicationId,
+ workspaceId,
+ requestUserWorkspaceId,
+ id,
+ });
+
+ const data: UpdatableChannelFields = {};
+
+ if (displayName !== undefined) {
+ data.displayName = normalizeDisplayName(displayName);
+ }
+
+ if (isDefined(visibility)) {
+ data.visibility = visibility;
+ }
+
+ if (isDefined(isSyncEnabled)) {
+ data.isSyncEnabled = isSyncEnabled;
+ }
+
+ if (Object.keys(data).length === 0) {
+ return messageChannel;
+ }
+
+ await this.messageChannelRepository.update({ id, workspaceId }, data);
+
+ return this.messageChannelRepository.findOneOrFail({
+ where: { id, workspaceId },
+ });
+ }
+
+ async delete({
+ applicationId,
+ workspaceId,
+ requestUserWorkspaceId,
+ id,
+ }: ApplicationScope & { id: string }): Promise<MessageChannelDTO> {
+ const { messageChannel } = await this.findOwnedOrThrow({
+ applicationId,
+ workspaceId,
+ requestUserWorkspaceId,
+ id,
+ });
+
+ await this.messageChannelRepository.delete({ id, workspaceId });
+
+ this.workspaceEventEmitter.emitCustomBatchEvent<MessageChannelDeletedEvent>(
+ MESSAGE_CHANNEL_DELETED_EVENT,
+ [{ messageChannelId: id }],
+ workspaceId,
+ );
+
+ return messageChannel;
+ }
+
+ // 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({
+ applicationId,
+ workspaceId,
+ requestUserWorkspaceId,
+ id,
+ }: ApplicationScope & { id: string }): Promise<OwnedMessageChannel> {
+ const messageChannel = await this.messageChannelRepository.findOne({
+ where: { id, workspaceId, type: MessageChannelType.APP },
+ });
+
+ const connectedAccount = isDefined(messageChannel)
+ ? await this.findReachableConnectedAccount({
+ applicationId,
+ workspaceId,
+ requestUserWorkspaceId,
+ connectedAccountId: messageChannel.connectedAccountId,
+ })
+ : null;
+
+ // Missing and not-reachable answer identically, and neither names the
+ // connection. Letting the two differ would tell a caller holding a channel
+ // id that the channel exists and whose connection backs it — the same
+ // probe ownershipViolation() exists to prevent one step earlier.
+ if (!isDefined(messageChannel) || !isDefined(connectedAccount)) {
+ throw new MessageChannelException(
+ `Message channel ${id} not found`,
+ MessageChannelExceptionCode.MESSAGE_CHANNEL_NOT_FOUND,
+ );
+ }
+
+ // The account comes back with the channel because the gate has already
+ // loaded it: ingestion needs the same row, and re-reading it would be a
+ // second round trip for a value we are holding.
+ return { messageChannel, connectedAccount };
+ }
+
+ // Two boundaries, not one: the connection must belong to this application,
+ // AND the caller must be allowed to see it. Checking only the first would
+ // let any user of an app administer another user's private connection —
+ // including flipping its channel to SHARE_EVERYTHING, which publishes that
+ // person's messages to the whole workspace.
+ private async assertOwnsConnectedAccount(
+ args: ApplicationScope & { connectedAccountId: string },
+ ): Promise<void> {
+ if (!isDefined(await this.findReachableConnectedAccount(args))) {
+ throw this.ownershipViolation(args.connectedAccountId);
+ }
+ }
+
+ private async findReachableConnectedAccount({
+ applicationId,
+ workspaceId,
+ requestUserWorkspaceId,
+ connectedAccountId,
+ }: ApplicationScope & {
+ connectedAccountId: string;
+ }): Promise<ConnectedAccountEntity | null> {
+ const connectedAccount = await this.connectedAccountRepository.findOne({
+ where: {
+ id: connectedAccountId,
+ applicationId,
+ workspaceId,
+ provider: ConnectedAccountProvider.APP,
+ },
+ });
+
+ if (
+ !isDefined(connectedAccount) ||
+ isConnectionHiddenFromRequestUser({
+ account: connectedAccount,
+ requestUserWorkspaceId,
+ })
+ ) {
+ return null;
+ }
+
+ return connectedAccount;
+ }
+
+ private async findReachableConnectedAccountIds({
+ applicationId,
+ workspaceId,
+ requestUserWorkspaceId,
+ }: ApplicationScope): Promise<string[]> {
+ const connectedAccounts = await this.connectedAccountRepository.find({
+ where: {
+ applicationId,
+ workspaceId,
+ provider: ConnectedAccountProvider.APP,
+ },
+ select: { id: true, visibility: true, userWorkspaceId: true },
+ });
+
+ return connectedAccounts
+ .filter(
+ (connectedAccount) =>
+ !isConnectionHiddenFromRequestUser({
+ account: connectedAccount,
+ requestUserWorkspaceId,
+ }),
+ )
+ .map((connectedAccount) => connectedAccount.id);
+ }
+
+ // Deliberately indistinguishable from "not found": whether a connection id
+ // exists is not something one app should be able to probe for another.
+ private ownershipViolation(connectedAccountId: string) {
+ return new MessageChannelException(
+ `Connection ${connectedAccountId} not found`,
+ MessageChannelExceptionCode.MESSAGE_CHANNEL_OWNERSHIP_VIOLATION,
+ );
+ }
+}
diff --git a/packages/twenty-server/src/modules/connected-account/channel-sync/services/channel-sync.service.ts b/packages/twenty-server/src/modules/connected-account/channel-sync/services/channel-sync.service.ts
index 1e9df6ffc28..a35c760e128 100644
--- a/packages/twenty-server/src/modules/connected-account/channel-sync/services/channel-sync.service.ts
+++ b/packages/twenty-server/src/modules/connected-account/channel-sync/services/channel-sync.service.ts
@@ -1,14 +1,14 @@
import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
+import { POLLED_MESSAGE_CHANNEL_TYPES } from 'twenty-shared/constants';
import {
CalendarChannelSyncStage,
CalendarChannelSyncStatus,
MessageChannelSyncStage,
- MessageChannelType,
WebhookSubscriptionChannelType,
} from 'twenty-shared/types';
-import { Not, Repository } from 'typeorm';
+import { In, Repository } from 'typeorm';
import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
@@ -76,7 +76,7 @@ export class ChannelSyncService {
where: {
connectedAccountId,
syncStage: MessageChannelSyncStage.PENDING_CONFIGURATION,
- type: Not(MessageChannelType.EMAIL_GROUP),
+ type: In([...POLLED_MESSAGE_CHANNEL_TYPES]),
workspaceId,
},
});
diff --git a/packages/twenty-server/src/modules/messaging/common/query-hooks/message/__tests__/apply-messages-visibility-restrictions.service.spec.ts b/packages/twenty-server/src/modules/messaging/common/query-hooks/message/__tests__/apply-messages-visibility-restrictions.service.spec.ts
new file mode 100644
index 00000000000..5774c80083d
--- /dev/null
+++ b/packages/twenty-server/src/modules/messaging/common/query-hooks/message/__tests__/apply-messages-visibility-restrictions.service.spec.ts
@@ -0,0 +1,133 @@
+import { Test, type TestingModule } from '@nestjs/testing';
+import { getRepositoryToken } from '@nestjs/typeorm';
+
+import { FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED } from 'twenty-shared/constants';
+import { MessageChannelVisibility } from 'twenty-shared/types';
+
+import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
+import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
+import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
+import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
+import { ApplyMessagesVisibilityRestrictionsService } from 'src/modules/messaging/common/query-hooks/message/apply-messages-visibility-restrictions.service';
+import { type MessageWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message.workspace-entity';
+
+const WORKSPACE_ID = '33333333-3333-4333-8333-333333333333';
+const APPLICATION_ID = '44444444-4444-4444-8444-444444444444';
+const MESSAGE_ID = '77777777-7777-4777-8777-777777777777';
+const MESSAGE_CHANNEL_ID = '55555555-5555-4555-8555-555555555555';
+
+describe('ApplyMessagesVisibilityRestrictionsService', () => {
+ let service: ApplyMessagesVisibilityRestrictionsService;
+ let connectedAccountRepository: { find: jest.Mock };
+ let messageChannelRepository: { find: jest.Mock };
+
+ const aMessage = (): MessageWorkspaceEntity =>
+ ({
+ id: MESSAGE_ID,
+ subject: 'Coffee tomorrow?',
+ text: 'Are you free at 3?',
+ }) as unknown as MessageWorkspaceEntity;
+
+ beforeEach(async () => {
+ connectedAccountRepository = { find: jest.fn().mockResolvedValue([]) };
+ messageChannelRepository = {
+ find: jest.fn().mockResolvedValue([
+ {
+ id: MESSAGE_CHANNEL_ID,
+ visibility: MessageChannelVisibility.METADATA,
+ },
+ ]),
+ };
+
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ ApplyMessagesVisibilityRestrictionsService,
+ {
+ provide: WorkspaceOrmManager,
+ useValue: {
+ executeInWorkspaceContext: (callback: () => unknown) => callback(),
+ getRepository: () => ({
+ find: jest.fn().mockResolvedValue([
+ {
+ messageId: MESSAGE_ID,
+ messageChannelId: MESSAGE_CHANNEL_ID,
+ },
+ ]),
+ }),
+ },
+ },
+ {
+ provide: getRepositoryToken(ConnectedAccountEntity),
+ useValue: connectedAccountRepository,
+ },
+ {
+ provide: getRepositoryToken(UserWorkspaceEntity),
+ useValue: { findOne: jest.fn() },
+ },
+ {
+ provide: getRepositoryToken(MessageChannelEntity),
+ useValue: messageChannelRepository,
+ },
+ ],
+ }).compile();
+
+ service = module.get(ApplyMessagesVisibilityRestrictionsService);
+ });
+
+ // An application has no user behind it, so before this bypass existed it fell
+ // straight through to the redaction branches and read back placeholders
+ // instead of the messages it had just written.
+ it('does not redact a channel owned by the calling application', async () => {
+ connectedAccountRepository.find.mockResolvedValue([
+ { id: 'connected-account-id', applicationId: APPLICATION_ID },
+ ]);
+
+ const [message] = await service.applyMessagesVisibilityRestrictions(
+ [aMessage()],
+ WORKSPACE_ID,
+ undefined,
+ APPLICATION_ID,
+ );
+
+ expect(message.subject).toBe('Coffee tomorrow?');
+ expect(message.text).toBe('Are you free at 3?');
+ expect(connectedAccountRepository.find).toHaveBeenCalledWith(
+ expect.objectContaining({
+ where: expect.objectContaining({
+ applicationId: APPLICATION_ID,
+ workspaceId: WORKSPACE_ID,
+ }),
+ }),
+ );
+ });
+
+ // The bypass keys on the connection carrying this application's id, so a
+ // channel belonging to someone else stays redacted.
+ it('still redacts a channel the calling application does not own', async () => {
+ connectedAccountRepository.find.mockResolvedValue([]);
+
+ const [message] = await service.applyMessagesVisibilityRestrictions(
+ [aMessage()],
+ WORKSPACE_ID,
+ undefined,
+ APPLICATION_ID,
+ );
+
+ expect(message.subject).toBe(
+ FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED,
+ );
+ expect(message.text).toBe(FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED);
+ });
+
+ it('leaves the email path alone when no application is calling', async () => {
+ const [message] = await service.applyMessagesVisibilityRestrictions(
+ [aMessage()],
+ WORKSPACE_ID,
+ );
+
+ expect(connectedAccountRepository.find).not.toHaveBeenCalled();
+ expect(message.subject).toBe(
+ FIELD_RESTRICTED_ADDITIONAL_PERMISSIONS_REQUIRED,
+ );
+ });
+});
diff --git a/packages/twenty-server/src/modules/messaging/common/query-hooks/message/apply-messages-visibility-restrictions.service.ts b/packages/twenty-server/src/modules/messaging/common/query-hooks/message/apply-messages-visibility-restrictions.service.ts
index fdeabfdd54f..502de2088eb 100644
--- a/packages/twenty-server/src/modules/messaging/common/query-hooks/message/apply-messages-visibility-restrictions.service.ts
+++ b/packages/twenty-server/src/modules/messaging/common/query-hooks/message/apply-messages-visibility-restrictions.service.ts
@@ -32,6 +32,7 @@ export class ApplyMessagesVisibilityRestrictionsService {
messages: MessageWorkspaceEntity[],
workspaceId: string,
userId?: string,
+ applicationId?: string,
) {
const authContext = buildSystemAuthContext(workspaceId);
@@ -133,6 +134,28 @@ export class ApplyMessagesVisibilityRestrictionsService {
}
}
+ // The same bypass as above, resolved through the application that
+ // owns the connection rather than the user who owns it. An email
+ // connection carries no applicationId, so this can only ever match
+ // a channel the calling application created.
+ if (isDefined(applicationId)) {
+ const connectedAccounts =
+ await this.connectedAccountRepository.find({
+ where: {
+ applicationId,
+ workspaceId,
+ messageChannels: {
+ id: In(messageChannels.map((channel) => channel.id)),
+ },
+ },
+ relations: { messageChannels: true },
+ });
+
+ if (connectedAccounts.length > 0) {
+ continue;
+ }
+ }
+
if (
messageChannelsGroupByVisibility[MessageChannelVisibility.SUBJECT]
) {
diff --git a/packages/twenty-server/src/modules/messaging/common/query-hooks/message/message-find-many.post-query.hook.ts b/packages/twenty-server/src/modules/messaging/common/query-hooks/message/message-find-many.post-query.hook.ts
index 431cbc27eba..430e161219b 100644
--- a/packages/twenty-server/src/modules/messaging/common/query-hooks/message/message-find-many.post-query.hook.ts
+++ b/packages/twenty-server/src/modules/messaging/common/query-hooks/message/message-find-many.post-query.hook.ts
@@ -45,10 +45,18 @@ export class MessageFindManyPostQueryHook implements WorkspacePostQueryHookInsta
? authContext.user.id
: undefined;
+ // An application reading its own channel has no user behind it, so without
+ // this it falls through to the redaction branches and gets back
+ // placeholders instead of the messages it just wrote.
+ const applicationId = isApplicationAuthContext(authContext)
+ ? authContext.application.id
+ : undefined;
+
await this.applyMessagesVisibilityRestrictionsService.applyMessagesVisibilityRestrictions(
payload,
workspace.id,
userId,
+ applicationId,
);
}
}
diff --git a/packages/twenty-server/src/modules/messaging/common/query-hooks/message/message-find-one.post-query.hook.ts b/packages/twenty-server/src/modules/messaging/common/query-hooks/message/message-find-one.post-query.hook.ts
index c194329110f..c02df4d3fcc 100644
--- a/packages/twenty-server/src/modules/messaging/common/query-hooks/message/message-find-one.post-query.hook.ts
+++ b/packages/twenty-server/src/modules/messaging/common/query-hooks/message/message-find-one.post-query.hook.ts
@@ -45,10 +45,18 @@ export class MessageFindOnePostQueryHook implements WorkspacePostQueryHookInstan
? authContext.user.id
: undefined;
+ // An application reading its own channel has no user behind it, so without
+ // this it falls through to the redaction branches and gets back
+ // placeholders instead of the messages it just wrote.
+ const applicationId = isApplicationAuthContext(authContext)
+ ? authContext.application.id
+ : undefined;
+
await this.applyMessagesVisibilityRestrictionsService.applyMessagesVisibilityRestrictions(
payload,
workspace.id,
userId,
+ applicationId,
);
}
}
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/crons/jobs/messaging-message-list-fetch.cron.job.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/crons/jobs/messaging-message-list-fetch.cron.job.ts
index 1ab94f76e3a..f4679da33ed 100644
--- a/packages/twenty-server/src/modules/messaging/message-import-manager/crons/jobs/messaging-message-list-fetch.cron.job.ts
+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/crons/jobs/messaging-message-list-fetch.cron.job.ts
@@ -1,12 +1,12 @@
import { Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
+import { POLLED_MESSAGE_CHANNEL_TYPES } from 'twenty-shared/constants';
import { WorkspaceActivationStatus } from 'twenty-shared/workspace';
-import { In, Not, Repository } from 'typeorm';
+import { In, Repository } from 'typeorm';
import {
MessageChannelSyncStage,
- MessageChannelType,
WebhookSubscriptionStatus,
} from 'twenty-shared/types';
import { SentryCronMonitor } from 'src/engine/core-modules/cron/sentry-cron-monitor.decorator';
@@ -62,7 +62,7 @@ export class MessagingMessageListFetchCronJob {
workspaceId: activeWorkspace.id,
isSyncEnabled: true,
syncStage: MessageChannelSyncStage.MESSAGE_LIST_FETCH_PENDING,
- type: Not(MessageChannelType.EMAIL_GROUP),
+ type: In([...POLLED_MESSAGE_CHANNEL_TYPES]),
},
},
);
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/crons/jobs/messaging-messages-import.cron.job.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/crons/jobs/messaging-messages-import.cron.job.ts
index 3175521b9ff..6861323883a 100644
--- a/packages/twenty-server/src/modules/messaging/message-import-manager/crons/jobs/messaging-messages-import.cron.job.ts
+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/crons/jobs/messaging-messages-import.cron.job.ts
@@ -1,14 +1,12 @@
import { Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
+import { POLLED_MESSAGE_CHANNEL_TYPES } from 'twenty-shared/constants';
import { isDefined } from 'twenty-shared/utils';
import { WorkspaceActivationStatus } from 'twenty-shared/workspace';
-import { In, Not, Repository } from 'typeorm';
+import { In, Repository } from 'typeorm';
-import {
- MessageChannelSyncStage,
- MessageChannelType,
-} from 'twenty-shared/types';
+import { MessageChannelSyncStage } from 'twenty-shared/types';
import { SentryCronMonitor } from 'src/engine/core-modules/cron/sentry-cron-monitor.decorator';
import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';
import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
@@ -61,7 +59,7 @@ export class MessagingMessagesImportCronJob {
workspaceId: activeWorkspace.id,
isSyncEnabled: true,
syncStage: MessageChannelSyncStage.MESSAGES_IMPORT_PENDING,
- type: Not(MessageChannelType.EMAIL_GROUP),
+ type: In([...POLLED_MESSAGE_CHANNEL_TYPES]),
},
},
);
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/crons/jobs/messaging-relaunch-failed-message-channels.cron.job.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/crons/jobs/messaging-relaunch-failed-message-channels.cron.job.ts
index eb2cb2101f5..6d3329f1db4 100644
--- a/packages/twenty-server/src/modules/messaging/message-import-manager/crons/jobs/messaging-relaunch-failed-message-channels.cron.job.ts
+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/crons/jobs/messaging-relaunch-failed-message-channels.cron.job.ts
@@ -1,12 +1,12 @@
import { InjectRepository } from '@nestjs/typeorm';
+import { POLLED_MESSAGE_CHANNEL_TYPES } from 'twenty-shared/constants';
import { WorkspaceActivationStatus } from 'twenty-shared/workspace';
-import { In, Not, Repository } from 'typeorm';
+import { In, Repository } from 'typeorm';
import {
MessageChannelSyncStage,
MessageChannelSyncStatus,
- MessageChannelType,
} from 'twenty-shared/types';
import { SentryCronMonitor } from 'src/engine/core-modules/cron/sentry-cron-monitor.decorator';
import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';
@@ -62,7 +62,7 @@ export class MessagingRelaunchFailedMessageChannelsCronJob {
where: {
syncStage: MessageChannelSyncStage.FAILED,
syncStatus: MessageChannelSyncStatus.FAILED_UNKNOWN,
- type: Not(MessageChannelType.EMAIL_GROUP),
+ type: In([...POLLED_MESSAGE_CHANNEL_TYPES]),
workspaceId: In(activeWorkspaceIds),
},
})
diff --git a/packages/twenty-shared/src/application/appMessageChannelType.ts b/packages/twenty-shared/src/application/appMessageChannelType.ts
new file mode 100644
index 00000000000..6b97cb1f89a
--- /dev/null
+++ b/packages/twenty-shared/src/application/appMessageChannelType.ts
@@ -0,0 +1,29 @@
+import { type MessageChannelVisibility } from '../types/MessageChannelVisibility';
+
+// One messaging channel an app owns, bound to one of its connections.
+// Returned from `listMessageChannels` and `createMessageChannel`.
+//
+// The shape lives in twenty-shared so this and the server-side
+// `MessageChannelDTO` projection always agree.
+export type AppMessageChannel = {
+ id: string;
+ // The account's identity on the provider, as the provider names it (a
+ // LinkedIn member URN, a WhatsApp number). Opaque to Twenty: it is what
+ // the app matches inbound payloads against, and what participant handles
+ // on this channel are compared to when deciding message direction.
+ handle: string;
+ // End-user label for the channel. Falls back to `handle` in the UI when null.
+ displayName: string | null;
+ // How much of a message on this channel other workspace members may read:
+ // 'METADATA' = participants and dates only.
+ // 'SUBJECT' = the above plus the subject.
+ // 'SHARE_EVERYTHING' = the above plus the body.
+ // The owner of the underlying connection always reads their own messages
+ // in full regardless of this value.
+ visibility: MessageChannelVisibility;
+ // The app connection whose credential this channel speaks through.
+ connectedAccountId: string;
+ // False pauses the channel without deleting it: ingestion is rejected
+ // while it is off, and existing messages stay readable.
+ isSyncEnabled: boolean;
+};
diff --git a/packages/twenty-shared/src/application/index.ts b/packages/twenty-shared/src/application/index.ts
index bc2a8988c29..4043e79ee1f 100644
--- a/packages/twenty-shared/src/application/index.ts
+++ b/packages/twenty-shared/src/application/index.ts
@@ -45,6 +45,7 @@ export type {
ApplicationVariables,
} from './applicationVariablesType';
export { APPLICATION_VARIABLE_FIELD_METADATA_TYPES } from './applicationVariablesType';
+export type { AppMessageChannel } from './appMessageChannelType';
export type { AssetManifest } from './assetManifestType';
export type {
BillableOperationManifest,
diff --git a/packages/twenty-shared/src/constants/DocumentationPaths.ts b/packages/twenty-shared/src/constants/DocumentationPaths.ts
index 4a396a173cd..1f953551cb0 100644
--- a/packages/twenty-shared/src/constants/DocumentationPaths.ts
+++ b/packages/twenty-shared/src/constants/DocumentationPaths.ts
@@ -68,6 +68,8 @@ export const DOCUMENTATION_PATHS = {
'/developers/extend/apps/logic/key-value-store',
DEVELOPERS_EXTEND_APPS_LOGIC_LOGIC_FUNCTIONS:
'/developers/extend/apps/logic/logic-functions',
+ DEVELOPERS_EXTEND_APPS_LOGIC_MESSAGING_CHANNELS:
+ '/developers/extend/apps/logic/messaging-channels',
DEVELOPERS_EXTEND_APPS_LOGIC_OVERVIEW:
'/developers/extend/apps/logic/overview',
DEVELOPERS_EXTEND_APPS_LOGIC_SKILLS_AND_AGENTS:
diff --git a/packages/twenty-shared/src/constants/PolledMessageChannelTypes.ts b/packages/twenty-shared/src/constants/PolledMessageChannelTypes.ts
new file mode 100644
index 00000000000..d5957a65730
--- /dev/null
+++ b/packages/twenty-shared/src/constants/PolledMessageChannelTypes.ts
@@ -0,0 +1,10 @@
+import { MessageChannelType } from '../types/MessageChannelType';
+
+// The email import pipeline polls providers on a cron. Only types whose
+// messages are fetched that way belong here: push-delivered channels
+// (EMAIL_GROUP, APP) would be scheduled forever against a driver that
+// cannot list their messages. SMS is declared on the enum but has no
+// driver, so it is left out too — listing the polled types rather than
+// excluding the others keeps a type out of the pipeline until someone
+// deliberately opts it in.
+export const POLLED_MESSAGE_CHANNEL_TYPES = [MessageChannelType.EMAIL] as const;
diff --git a/packages/twenty-shared/src/constants/index.ts b/packages/twenty-shared/src/constants/index.ts
index 2956d236c41..df0d7d9f925 100644
--- a/packages/twenty-shared/src/constants/index.ts
+++ b/packages/twenty-shared/src/constants/index.ts
@@ -57,6 +57,7 @@ export { MUTATION_MAX_MERGE_RECORDS } from './MutationMaxMergeRecords';
export { OBJECTS_WITH_CHANNEL_VISIBILITY_CONSTRAINTS } from './ObjectsWithChannelVisibilityConstraints';
export { PermissionFlagType } from './PermissionFlagType';
export { PermissionsOnAllObjectRecords } from './PermissionsOnAllObjectRecords';
+export { POLLED_MESSAGE_CHANNEL_TYPES } from './PolledMessageChannelTypes';
export { QUERY_DEFAULT_LIMIT_RECORDS } from './QueryDefaultLimitRecords';
export { QUERY_MAX_RECORDS } from './QueryMaxRecords';
export { QUERY_MAX_RECORDS_FROM_RELATION } from './QueryMaxRecordsFromRelation';
diff --git a/packages/twenty-shared/src/types/MessageChannelType.ts b/packages/twenty-shared/src/types/MessageChannelType.ts
index c9b4dfdbe09..a966064fdc3 100644
--- a/packages/twenty-shared/src/types/MessageChannelType.ts
+++ b/packages/twenty-shared/src/types/MessageChannelType.ts
@@ -2,4 +2,5 @@ export enum MessageChannelType {
EMAIL = 'EMAIL',
SMS = 'SMS',
EMAIL_GROUP = 'EMAIL_GROUP',
+ APP = 'APP',
}