Skip to content

The open alternative to Salesforce, designed for AI.

Let apps connect accounts through their own authorization flow (#28672)

Félix Malfaita81ca558f32a
diff --git a/packages/twenty-agent-skills/references/develop-app/logic.md b/packages/twenty-agent-skills/references/develop-app/logic.md
index c5051ce18ef..cd5d2d04348 100644
--- a/packages/twenty-agent-skills/references/develop-app/logic.md
+++ b/packages/twenty-agent-skills/references/develop-app/logic.md
@@ -101,6 +101,15 @@ For third-party connections:
- Verify failure states for expired or missing credentials.
- When the provider can say which account a token belongs to (team, organization, user), declare `identifyAccountLogicFunction` so a reconnect that authorizes a different account is refused instead of overwriting the connection. Write the handler as one request to the provider's "who am I" endpoint, return the id as a string, and return `{ externalAccountId: null }` when there is no stable id.
- Set `scope` on `defineConnectionProvider`: `'WORKSPACE'` (default) when the app uses one connection shared with the workspace, `'USER'` when each member connects their own account. One scope per provider; declare two providers when the app needs both. A provider's scope cannot change in a later version: declare a new provider with a new `universalIdentifier` instead, which deletes the old provider's connections on upgrade, and deletes existing `'USER'` connected accounts left on a `'WORKSPACE'` provider. Members cannot add `USER` connections from settings yet (they will from App preferences). Requires `"engines": { "twenty": ">=2.49.0" }`.
+- For services that connect accounts through their own hosted flow instead of OAuth (Unipile, Plaid, Merge), declare `type: 'custom'` with `custom.authorizeLogicFunction` (return `{ authorizationUrl }` built with the given `callbackUrl`) and `custom.callbackLogicFunction` (receives each `GET` return and `POST` notification to that URL with its query, headers, body and `rawBody`; verify a signed notification over `rawBody`, confirm the account with the service, then return `{ externalAccountId, handle?, accessToken? }`, or `null` when the request carries no account). Both run within 10 seconds. Connections carry `providerType`: an `'oauth'` connection always has an `accessToken`, a `'custom'` one has `null` unless the callback returned one, so call the service with the app's own key and `externalAccountId`. Release upstream state in `onDisconnectLogicFunction`; Twenty does not refresh or revoke custom connections. The `type` cannot change after the first sync; declare a new provider with a new `universalIdentifier` instead. Requires `"engines": { "twenty": ">=2.52.0" }`.
+
+## Messaging Providers
+
+To let members reply to an app's message channels, declare `defineMessagingProvider` with a kebab-case `name`, a `displayName`, the `connectionProvider` it sends through, and a `sendMessageLogicFunction`:
+
+- Bind each channel to it with `messagingProvider: { universalIdentifier }` on `createMessageChannel` or `updateMessageChannel` (`null` unbinds). The provider must use the channel account's connection provider. A channel without one, or whose provider or function is gone, only ingests.
+- The send function receives `{ messagingProviderName, connectedAccountId, messageChannelId, threadExternalId, text, idempotencyKey, recipients }` (type `SendAppMessagePayload`; `recipients` are the latest message's participants), must deliver the reply and return `{ externalId, sentAt? }`. Twenty then records it in the thread, and a later ingestion of the same `externalId` is a no-op. Throw on failure so nothing is recorded. A `sendAppChannelMessage` retry with the same `idempotencyKey` records the delivered reply without calling the function again; forward the key to the provider when it supports idempotent sends.
+- Declare one messaging provider per kind of messaging (LinkedIn, WhatsApp) even when they share a connection provider. Its connection provider cannot change after the first sync; declare a new one with a new `universalIdentifier` instead. Requires `"engines": { "twenty": ">=2.52.0" }`.
## Post-Install Hooks
diff --git a/packages/twenty-cli/src/app/manifest/__tests__/__snapshots__/manifest-fixtures.spec.ts.snap b/packages/twenty-cli/src/app/manifest/__tests__/__snapshots__/manifest-fixtures.spec.ts.snap
index 17c93b4c0ec..09dcd4c5c29 100644
--- a/packages/twenty-cli/src/app/manifest/__tests__/__snapshots__/manifest-fixtures.spec.ts.snap
+++ b/packages/twenty-cli/src/app/manifest/__tests__/__snapshots__/manifest-fixtures.spec.ts.snap
@@ -15,6 +15,7 @@ exports[`CLI manifest fixtures and worker transport > matches the manifest, file
"logicFunctions": [
"src/logic-functions/add-numbers.function.ts",
],
+ "messagingProviders": [],
"navigationMenuItems": [],
"objects": [],
"pageLayoutTabs": [],
@@ -77,6 +78,7 @@ The scripts invoke that local build directly, so the SDK binary cannot shadow it
"universalIdentifier": "f9e5589c-e951-4d99-85db-0a305ab53502",
},
],
+ "messagingProviders": [],
"navigationMenuItems": [],
"objects": [],
"pageLayoutTabs": [],
@@ -146,6 +148,7 @@ exports[`CLI manifest fixtures and worker transport > matches the manifest, file
"logicFunctions": [
"my.function.ts",
],
+ "messagingProviders": [],
"navigationMenuItems": [],
"objects": [
"my.object.ts",
@@ -209,6 +212,7 @@ exports[`CLI manifest fixtures and worker transport > matches the manifest, file
"universalIdentifier": "e1e2e3e4-e5e6-4000-8000-000000000010",
},
],
+ "messagingProviders": [],
"navigationMenuItems": [],
"objects": [
{
@@ -318,6 +322,7 @@ exports[`CLI manifest fixtures and worker transport > matches the manifest, file
"src/logic-functions/test-function.function.ts",
"src/root.function.ts",
],
+ "messagingProviders": [],
"navigationMenuItems": [
"src/navigation-menu-items/post-card-recipients.navigation-menu-item.ts",
"src/navigation-menu-items/post-cards.navigation-menu-item.ts",
@@ -875,6 +880,7 @@ exports[`CLI manifest fixtures and worker transport > matches the manifest, file
"universalIdentifier": "f0f1f2f3-f4f5-4000-8000-000000000001",
},
],
+ "messagingProviders": [],
"navigationMenuItems": [
{
"position": 1,
@@ -1418,6 +1424,7 @@ exports[`CLI manifest fixtures and worker transport > matches the manifest, file
],
"indexes": [],
"logicFunctions": [],
+ "messagingProviders": [],
"navigationMenuItems": [],
"objects": [],
"pageLayoutTabs": [],
@@ -1473,6 +1480,7 @@ exports[`CLI manifest fixtures and worker transport > matches the manifest, file
],
"indexes": [],
"logicFunctions": [],
+ "messagingProviders": [],
"navigationMenuItems": [],
"objects": [],
"pageLayoutTabs": [],
diff --git a/packages/twenty-cli/src/app/manifest/__tests__/manifest-validate.spec.ts b/packages/twenty-cli/src/app/manifest/__tests__/manifest-validate.spec.ts
index 4ca6743fef3..e1ea158f1ed 100644
--- a/packages/twenty-cli/src/app/manifest/__tests__/manifest-validate.spec.ts
+++ b/packages/twenty-cli/src/app/manifest/__tests__/manifest-validate.spec.ts
@@ -374,6 +374,98 @@ describe('manifestValidate', () => {
},
);
+ it('should not flag a messaging provider referencing its connection provider and send logic function as duplicates', () => {
+ const connectionProviderId = '550e8400-e29b-41d4-a716-446655440045';
+ const sendMessageLogicFunctionId = '550e8400-e29b-41d4-a716-446655440046';
+
+ const result = manifestValidate({
+ ...validManifest,
+ logicFunctions: [
+ {
+ universalIdentifier: sendMessageLogicFunctionId,
+ name: 'send-message',
+ sourceHandlerPath: 'src/logic-functions/send-message.ts',
+ builtHandlerPath: 'dist/send-message.js',
+ builtHandlerChecksum: '00000000-0000-4000-8000-000000000000',
+ handlerName: 'handler',
+ },
+ ],
+ connectionProviders: [
+ {
+ universalIdentifier: connectionProviderId,
+ name: 'unipile',
+ displayName: 'Unipile',
+ type: 'custom',
+ custom: {
+ authorizeLogicFunction: {
+ universalIdentifier: sendMessageLogicFunctionId,
+ },
+ callbackLogicFunction: {
+ universalIdentifier: sendMessageLogicFunctionId,
+ },
+ },
+ },
+ ],
+ messagingProviders: [
+ {
+ universalIdentifier: '550e8400-e29b-41d4-a716-446655440047',
+ name: 'linkedin-messaging',
+ displayName: 'LinkedIn Messages',
+ connectionProvider: { universalIdentifier: connectionProviderId },
+ sendMessageLogicFunction: {
+ universalIdentifier: sendMessageLogicFunctionId,
+ },
+ },
+ ],
+ });
+
+ expect(result.isValid).toBe(true);
+ expect(result.errors).toHaveLength(0);
+ });
+
+ it('should not flag a custom connection provider referencing its authorize and callback logic functions as duplicates', () => {
+ const authorizeLogicFunctionId = '550e8400-e29b-41d4-a716-446655440042';
+ const callbackLogicFunctionId = '550e8400-e29b-41d4-a716-446655440043';
+
+ const logicFunctions: Manifest['logicFunctions'] = [
+ authorizeLogicFunctionId,
+ callbackLogicFunctionId,
+ ].map((universalIdentifier) => ({
+ universalIdentifier,
+ name: universalIdentifier,
+ sourceHandlerPath: `src/logic-functions/${universalIdentifier}.ts`,
+ builtHandlerPath: `dist/${universalIdentifier}.js`,
+ builtHandlerChecksum: '00000000-0000-4000-8000-000000000000',
+ handlerName: 'handler',
+ }));
+
+ const connectionProvider: NonNullable<
+ Manifest['connectionProviders']
+ >[number] = {
+ universalIdentifier: '550e8400-e29b-41d4-a716-446655440044',
+ name: 'linkedin',
+ displayName: 'LinkedIn',
+ type: 'custom',
+ custom: {
+ authorizeLogicFunction: {
+ universalIdentifier: authorizeLogicFunctionId,
+ },
+ callbackLogicFunction: {
+ universalIdentifier: callbackLogicFunctionId,
+ },
+ },
+ };
+
+ const result = manifestValidate({
+ ...validManifest,
+ logicFunctions,
+ connectionProviders: [connectionProvider],
+ });
+
+ expect(result.isValid).toBe(true);
+ expect(result.errors).toHaveLength(0);
+ });
+
it('should not flag a front component referenced via settingsFrontComponent as a duplicate', () => {
const frontComponentId = '550e8400-e29b-41d4-a716-446655440050';
diff --git a/packages/twenty-cli/src/app/manifest/manifest-build.ts b/packages/twenty-cli/src/app/manifest/manifest-build.ts
index fae70113660..b9a2bce8e45 100644
--- a/packages/twenty-cli/src/app/manifest/manifest-build.ts
+++ b/packages/twenty-cli/src/app/manifest/manifest-build.ts
@@ -39,6 +39,7 @@ import {
ASSETS_DIR,
type CommandMenuItemManifest,
type ConnectionProviderManifest,
+ type MessagingProviderManifest,
type FieldManifest,
type FrontComponentManifest,
type IndexManifest,
@@ -112,6 +113,7 @@ export const buildManifest = async (
const agents: AgentManifest[] = [];
const workflows: WorkflowManifest[] = [];
const connectionProviders: ConnectionProviderManifest[] = [];
+ const messagingProviders: MessagingProviderManifest[] = [];
const logicFunctions: LogicFunctionManifest[] = [];
const frontComponents: FrontComponentManifest[] = [];
const publicAssets: AssetManifest[] = [];
@@ -144,6 +146,7 @@ export const buildManifest = async (
const agentsFilePaths: string[] = [];
const workflowsFilePaths: string[] = [];
const connectionProvidersFilePaths: string[] = [];
+ const messagingProvidersFilePaths: string[] = [];
const logicFunctionsFilePaths: string[] = [];
const frontComponentsFilePaths: string[] = [];
const publicAssetsFilePaths: string[] = [];
@@ -285,6 +288,18 @@ export const buildManifest = async (
connectionProvidersFilePaths.push(relativePath);
break;
}
+ case 'messagingProviders': {
+ const extract =
+ await extractManifestFromFile<MessagingProviderManifest>({
+ appPath,
+ filePath,
+ });
+ messagingProviders.push(extract.config);
+ errors.push(...extract.errors);
+ warnings.push(...(extract.warnings ?? []));
+ messagingProvidersFilePaths.push(relativePath);
+ break;
+ }
case 'logicFunctions': {
const extract = await extractManifestFromFile<LogicFunctionConfig>({
appPath,
@@ -705,6 +720,7 @@ export const buildManifest = async (
agents: agents.sort(byId),
workflows: workflows.sort(byId),
connectionProviders: connectionProviders.sort(byId),
+ messagingProviders: messagingProviders.sort(byId),
logicFunctions: logicFunctions.sort(byId),
frontComponents: frontComponents.sort(byId),
publicAssets: publicAssets.sort(byPath),
@@ -730,6 +746,7 @@ export const buildManifest = async (
agents: agentsFilePaths,
workflows: workflowsFilePaths,
connectionProviders: connectionProvidersFilePaths,
+ messagingProviders: messagingProvidersFilePaths,
logicFunctions: logicFunctionsFilePaths,
frontComponents: frontComponentsFilePaths,
publicAssets: publicAssetsFilePaths,
diff --git a/packages/twenty-cli/src/app/manifest/manifest-validate.ts b/packages/twenty-cli/src/app/manifest/manifest-validate.ts
index 3bd170019f0..dfede4a42d3 100644
--- a/packages/twenty-cli/src/app/manifest/manifest-validate.ts
+++ b/packages/twenty-cli/src/app/manifest/manifest-validate.ts
@@ -67,8 +67,12 @@ const findUniversalIdentifiers = (obj: object): string[] => {
key === 'uninstallLogicFunction' ||
key === 'healthCheckLogicFunction' ||
key === 'identifyAccountLogicFunction' ||
+ key === 'authorizeLogicFunction' ||
+ key === 'callbackLogicFunction' ||
key === 'onConnectLogicFunction' ||
key === 'onDisconnectLogicFunction' ||
+ key === 'sendMessageLogicFunction' ||
+ key === 'connectionProvider' ||
key === 'settingsFrontComponent' ||
key === 'input' ||
key === 'expectedBody' ||
diff --git a/packages/twenty-cli/src/app/source/extract-define-entity.ts b/packages/twenty-cli/src/app/source/extract-define-entity.ts
index 80f0451442e..64edd3cbecb 100644
--- a/packages/twenty-cli/src/app/source/extract-define-entity.ts
+++ b/packages/twenty-cli/src/app/source/extract-define-entity.ts
@@ -17,6 +17,7 @@ export const DEFINE_ENTITY_KEYS = {
defineAgent: 'agents',
defineWorkflow: 'workflows',
defineConnectionProvider: 'connectionProviders',
+ defineMessagingProvider: 'messagingProviders',
defineFrontComponent: 'frontComponents',
defineSettingsFrontComponent: 'frontComponents',
defineView: 'views',
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index aa4af2bf6fa..b4ea8025a80 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -280,6 +280,7 @@ enum AllMetadataName {
frontComponent
index
logicFunction
+ messagingProvider
navigationMenuItem
objectMetadata
objectPermission
@@ -345,7 +346,7 @@ type ApiKeyToken {
}
type AppConnection {
- accessToken: String!
+ accessToken: String
authFailedAt: String
authFailedReason: String
externalAccountId: String
@@ -353,6 +354,7 @@ type AppConnection {
id: ID!
name: String!
providerName: String!
+ providerType: String!
scope: ConnectedAccountScope!
scopes: [String!]!
userWorkspaceId: String!
@@ -1435,6 +1437,7 @@ input CreateAppMessageChannelInput {
connectedAccountId: UUID!
displayName: String
handle: String!
+ messagingProviderUniversalIdentifier: UUID
participantHandleFieldUniversalIdentifier: UUID
visibility: MessageChannelVisibility!
}
@@ -2938,6 +2941,7 @@ type MessageChannel {
isContactAutoCreationEnabled: Boolean!
isSyncEnabled: Boolean!
messageFolderImportPolicy: MessageFolderImportPolicy!
+ messagingProviderUniversalIdentifier: UUID
participantHandleFieldUniversalIdentifier: UUID
pendingGroupEmailsAction: MessageChannelPendingGroupEmailsAction!
syncStage: MessageChannelSyncStage!
@@ -3329,6 +3333,7 @@ type Mutation {
runAgent(input: RunAgentInput!): RunAgentResult!
runApplicationHealthCheck(applicationId: UUID!): ApplicationHealthCheckResult
saveImapSmtpCaldavAccount(connectionParameters: EmailAccountConnectionParameters!, handle: String!, id: UUID): ImapSmtpCaldavConnectionSuccess!
+ sendAppChannelMessage(input: SendAppChannelMessageInput!): SendAppChannelMessageOutput!
sendChatMessage(browsingContext: JSON, channelId: UUID, fileAttachments: [FileAttachmentInput!], mentionedWorkspaceMemberIds: [UUID!], messageId: UUID!, modelId: String, shouldAssistantReply: Boolean, text: String!, threadId: UUID!): SendChatMessageResult!
sendEmail(input: SendEmailInput!): SendEmailOutput!
sendInboxMessage(input: SendInboxMessageInput!): SendInboxMessageResult!
@@ -4442,6 +4447,18 @@ type SearchField {
updatedAt: DateTime!
}
+input SendAppChannelMessageInput {
+ idempotencyKey: UUID!
+ messageChannelId: UUID!
+ messageThreadId: UUID!
+ text: String!
+}
+
+type SendAppChannelMessageOutput {
+ messageId: UUID!
+ messageThreadId: UUID!
+}
+
type SendChatMessageResult {
mentionedParticipantWorkspaceMemberIds: [UUID!]
messageId: String
@@ -4857,6 +4874,7 @@ input UpdateAppMessageChannelInput {
displayName: String
id: UUID!
isSyncEnabled: Boolean
+ messagingProviderUniversalIdentifier: UUID
visibility: MessageChannelVisibility
}
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index 461c001a607..34bba92a1fa 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -243,7 +243,7 @@ export interface AiSystemPromptSection {
__typename: 'AiSystemPromptSection'
}
-export type AllMetadataName = 'agent' | 'agentChatChannel' | 'agentChatChannelRole' | 'applicationVariable' | 'commandMenuItem' | 'connectionProvider' | 'fieldMetadata' | 'fieldPermission' | 'frontComponent' | 'index' | 'logicFunction' | 'navigationMenuItem' | 'objectMetadata' | 'objectPermission' | 'pageLayout' | 'pageLayoutTab' | 'pageLayoutWidget' | 'permissionFlag' | 'role' | 'rolePermissionFlag' | 'roleTarget' | 'rowLevelPermissionPredicate' | 'rowLevelPermissionPredicateGroup' | 'searchFieldMetadata' | 'settingsMenuItem' | 'skill' | 'timelineActivityType' | 'validationRule' | 'view' | 'viewField' | 'viewFieldGroup' | 'viewFilter' | 'viewFilterGroup' | 'viewGroup' | 'viewSort' | 'webhook' | 'workflow' | 'workflowVersion'
+export type AllMetadataName = 'agent' | 'agentChatChannel' | 'agentChatChannelRole' | 'applicationVariable' | 'commandMenuItem' | 'connectionProvider' | 'fieldMetadata' | 'fieldPermission' | 'frontComponent' | 'index' | 'logicFunction' | 'messagingProvider' | 'navigationMenuItem' | 'objectMetadata' | 'objectPermission' | 'pageLayout' | 'pageLayoutTab' | 'pageLayoutWidget' | 'permissionFlag' | 'role' | 'rolePermissionFlag' | 'roleTarget' | 'rowLevelPermissionPredicate' | 'rowLevelPermissionPredicateGroup' | 'searchFieldMetadata' | 'settingsMenuItem' | 'skill' | 'timelineActivityType' | 'validationRule' | 'view' | 'viewField' | 'viewFieldGroup' | 'viewFilter' | 'viewFilterGroup' | 'viewGroup' | 'viewSort' | 'webhook' | 'workflow' | 'workflowVersion'
export interface Analytics {
/** Boolean that confirms query was dispatched */
@@ -283,7 +283,7 @@ export interface ApiKeyToken {
}
export interface AppConnection {
- accessToken: Scalars['String']
+ accessToken?: Scalars['String']
authFailedAt?: Scalars['String']
authFailedReason?: Scalars['String']
externalAccountId?: Scalars['String']
@@ -291,6 +291,7 @@ export interface AppConnection {
id: Scalars['ID']
name: Scalars['String']
providerName: Scalars['String']
+ providerType: Scalars['String']
scope: ConnectedAccountScope
scopes: Scalars['String'][]
userWorkspaceId: Scalars['String']
@@ -2054,6 +2055,7 @@ export interface MessageChannel {
isContactAutoCreationEnabled: Scalars['Boolean']
isSyncEnabled: Scalars['Boolean']
messageFolderImportPolicy: MessageFolderImportPolicy
+ messagingProviderUniversalIdentifier?: Scalars['UUID']
participantHandleFieldUniversalIdentifier?: Scalars['UUID']
pendingGroupEmailsAction: MessageChannelPendingGroupEmailsAction
syncStage: MessageChannelSyncStage
@@ -2367,6 +2369,7 @@ export interface Mutation {
runAgent: RunAgentResult
runApplicationHealthCheck?: ApplicationHealthCheckResult
saveImapSmtpCaldavAccount: ImapSmtpCaldavConnectionSuccess
+ sendAppChannelMessage: SendAppChannelMessageOutput
sendChatMessage: SendChatMessageResult
sendEmail: SendEmailOutput
sendInboxMessage: SendInboxMessageResult
@@ -3284,6 +3287,12 @@ export interface SearchField {
__typename: 'SearchField'
}
+export interface SendAppChannelMessageOutput {
+ messageId: Scalars['UUID']
+ messageThreadId: Scalars['UUID']
+ __typename: 'SendAppChannelMessageOutput'
+}
+
export interface SendChatMessageResult {
mentionedParticipantWorkspaceMemberIds?: Scalars['UUID'][]
messageId?: Scalars['String']
@@ -4451,6 +4460,7 @@ export interface AppConnectionGenqlSelection{
id?: boolean | number
name?: boolean | number
providerName?: boolean | number
+ providerType?: boolean | number
scope?: boolean | number
scopes?: boolean | number
userWorkspaceId?: boolean | number
@@ -5502,7 +5512,7 @@ export interface CreateAgentInput {description?: (Scalars['String'] | null),icon
export interface CreateApiKeyInput {expiresAt: Scalars['String'],name: Scalars['String'],revokedAt?: (Scalars['String'] | null),roleId: Scalars['UUID']}
-export interface CreateAppMessageChannelInput {connectedAccountId: Scalars['UUID'],displayName?: (Scalars['String'] | null),handle: Scalars['String'],participantHandleFieldUniversalIdentifier?: (Scalars['UUID'] | null),visibility: MessageChannelVisibility}
+export interface CreateAppMessageChannelInput {connectedAccountId: Scalars['UUID'],displayName?: (Scalars['String'] | null),handle: Scalars['String'],messagingProviderUniversalIdentifier?: (Scalars['UUID'] | null),participantHandleFieldUniversalIdentifier?: (Scalars['UUID'] | null),visibility: MessageChannelVisibility}
export interface CreateApplicationFileUploadsResultGenqlSelection{
errors?: ApplicationFileUploadErrorGenqlSelection
@@ -6507,6 +6517,7 @@ export interface MessageChannelGenqlSelection{
isContactAutoCreationEnabled?: boolean | number
isSyncEnabled?: boolean | number
messageFolderImportPolicy?: boolean | number
+ messagingProviderUniversalIdentifier?: boolean | number
participantHandleFieldUniversalIdentifier?: boolean | number
pendingGroupEmailsAction?: boolean | number
syncStage?: boolean | number
@@ -6797,6 +6808,7 @@ export interface MutationGenqlSelection{
runAgent?: (RunAgentResultGenqlSelection & { __args: {input: RunAgentInput} })
runApplicationHealthCheck?: (ApplicationHealthCheckResultGenqlSelection & { __args: {applicationId: Scalars['UUID']} })
saveImapSmtpCaldavAccount?: (ImapSmtpCaldavConnectionSuccessGenqlSelection & { __args: {connectionParameters: EmailAccountConnectionParameters, handle: Scalars['String'], id?: (Scalars['UUID'] | null)} })
+ sendAppChannelMessage?: (SendAppChannelMessageOutputGenqlSelection & { __args: {input: SendAppChannelMessageInput} })
sendChatMessage?: (SendChatMessageResultGenqlSelection & { __args: {browsingContext?: (Scalars['JSON'] | null), channelId?: (Scalars['UUID'] | null), fileAttachments?: (FileAttachmentInput[] | null), mentionedWorkspaceMemberIds?: (Scalars['UUID'][] | null), messageId: Scalars['UUID'], modelId?: (Scalars['String'] | null), shouldAssistantReply?: (Scalars['Boolean'] | null), text: Scalars['String'], threadId: Scalars['UUID']} })
sendEmail?: (SendEmailOutputGenqlSelection & { __args: {input: SendEmailInput} })
sendInboxMessage?: (SendInboxMessageResultGenqlSelection & { __args: {input: SendInboxMessageInput} })
@@ -7787,6 +7799,15 @@ export interface SearchFieldGenqlSelection{
__scalar?: boolean | number
}
+export interface SendAppChannelMessageInput {idempotencyKey: Scalars['UUID'],messageChannelId: Scalars['UUID'],messageThreadId: Scalars['UUID'],text: Scalars['String']}
+
+export interface SendAppChannelMessageOutputGenqlSelection{
+ messageId?: boolean | number
+ messageThreadId?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
export interface SendChatMessageResultGenqlSelection{
mentionedParticipantWorkspaceMemberIds?: boolean | number
messageId?: boolean | number
@@ -8123,7 +8144,7 @@ export interface UpdateAgentInput {description?: (Scalars['String'] | null),icon
export interface UpdateApiKeyInput {expiresAt?: (Scalars['String'] | null),id: Scalars['UUID'],name?: (Scalars['String'] | null),revokedAt?: (Scalars['String'] | null)}
-export interface UpdateAppMessageChannelInput {displayName?: (Scalars['String'] | null),id: Scalars['UUID'],isSyncEnabled?: (Scalars['Boolean'] | null),visibility?: (MessageChannelVisibility | null)}
+export interface UpdateAppMessageChannelInput {displayName?: (Scalars['String'] | null),id: Scalars['UUID'],isSyncEnabled?: (Scalars['Boolean'] | null),messagingProviderUniversalIdentifier?: (Scalars['UUID'] | null),visibility?: (MessageChannelVisibility | null)}
export interface UpdateApplicationInput {autoUpgrade?: (Scalars['Boolean'] | null)}
@@ -11093,6 +11114,14 @@ export interface WorkspaceUrlsAndIdGenqlSelection{
+ const SendAppChannelMessageOutput_possibleTypes: string[] = ['SendAppChannelMessageOutput']
+ export const isSendAppChannelMessageOutput = (obj?: { __typename?: any } | null): obj is SendAppChannelMessageOutput => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isSendAppChannelMessageOutput"')
+ return SendAppChannelMessageOutput_possibleTypes.includes(obj.__typename)
+ }
+
+
+
const SendChatMessageResult_possibleTypes: string[] = ['SendChatMessageResult']
export const isSendChatMessageResult = (obj?: { __typename?: any } | null): obj is SendChatMessageResult => {
if (!obj?.__typename) throw new Error('__typename is missing in "isSendChatMessageResult"')
@@ -11813,6 +11842,7 @@ export const enumAllMetadataName = {
frontComponent: 'frontComponent' as const,
index: 'index' as const,
logicFunction: 'logicFunction' as const,
+ messagingProvider: 'messagingProvider' as const,
navigationMenuItem: 'navigationMenuItem' as const,
objectMetadata: 'objectMetadata' as const,
objectPermission: 'objectPermission' as const,
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index 232e2bfc49b..b5596f86e7c 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -92,36 +92,36 @@ export default {
451,
455,
460,
- 478,
- 490,
- 491,
+ 480,
+ 492,
493,
- 517,
+ 495,
519,
521,
- 582,
- 602,
- 609,
+ 523,
+ 584,
+ 604,
611,
- 615,
- 626,
- 632,
- 633,
+ 613,
+ 617,
+ 628,
+ 634,
635,
- 636,
+ 637,
638,
- 639,
640,
- 643,
- 644,
- 649,
+ 641,
+ 642,
+ 645,
+ 646,
651,
- 654,
- 659,
- 660,
+ 653,
+ 656,
661,
- 664,
- 665
+ 662,
+ 663,
+ 666,
+ 667
],
"types": {
"ActivateWorkspaceInput": {
@@ -149,7 +149,7 @@ export default {
},
"Agent": {
"applicationId": [
- 517
+ 519
],
"createdAt": [
207
@@ -161,7 +161,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isCustom": [
4
@@ -188,7 +188,7 @@ export default {
309
],
"roleId": [
- 517
+ 519
],
"triggers": [
309
@@ -209,7 +209,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isAccessible": [
4
@@ -224,7 +224,7 @@ export default {
6
],
"roleIds": [
- 517
+ 519
],
"__typename": [
1
@@ -240,7 +240,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"label": [
1
@@ -251,7 +251,7 @@ export default {
},
"AgentChatChannelSummary": {
"channelId": [
- 517
+ 519
],
"hasUnreadOpen": [
4
@@ -272,7 +272,7 @@ export default {
4
],
"threadIds": [
- 517
+ 519
],
"__typename": [
1
@@ -358,7 +358,7 @@ export default {
207
],
"id": [
- 517
+ 519
],
"isSubscribed": [
4
@@ -373,7 +373,7 @@ export default {
207
],
"threadId": [
- 517
+ 519
],
"updatedAt": [
207
@@ -384,7 +384,7 @@ export default {
},
"AgentIdInput": {
"id": [
- 517
+ 519
],
"__typename": [
1
@@ -392,13 +392,13 @@ export default {
},
"AgentMessage": {
"agentId": [
- 517
+ 519
],
"createdAt": [
207
],
"id": [
- 517
+ 519
],
"parts": [
21
@@ -413,19 +413,19 @@ export default {
1
],
"senderUserWorkspaceId": [
- 517
+ 519
],
"senderWorkspaceMemberId": [
- 517
+ 519
],
"status": [
1
],
"threadId": [
- 517
+ 519
],
"turnId": [
- 517
+ 519
],
"__typename": [
1
@@ -442,7 +442,7 @@ export default {
1
],
"fileId": [
- 517
+ 519
],
"fileMediaType": [
1
@@ -451,10 +451,10 @@ export default {
1
],
"id": [
- 517
+ 519
],
"messageId": [
- 517
+ 519
],
"orderIndex": [
10
@@ -516,7 +516,7 @@ export default {
},
"AgentMessageReactionSummary": {
"agentIds": [
- 517
+ 519
],
"emoji": [
1
@@ -525,7 +525,7 @@ export default {
4
],
"workspaceMemberIds": [
- 517
+ 519
],
"__typename": [
1
@@ -551,7 +551,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"input": [
1
@@ -575,7 +575,7 @@ export default {
24
],
"threadId": [
- 517
+ 519
],
"threadTitle": [
1
@@ -590,13 +590,13 @@ export default {
"AgentTurnStatus": {},
"AggregateChartConfiguration": {
"aggregateFieldMetadataId": [
- 517
+ 519
],
"aggregateOperation": [
26
],
"configurationType": [
- 643
+ 645
],
"description": [
1
@@ -716,7 +716,7 @@ export default {
207
],
"id": [
- 517
+ 519
],
"name": [
1
@@ -739,7 +739,7 @@ export default {
207
],
"id": [
- 517
+ 519
],
"name": [
1
@@ -784,6 +784,9 @@ export default {
"providerName": [
1
],
+ "providerType": [
+ 1
+ ],
"scope": [
157
],
@@ -849,13 +852,13 @@ export default {
1
],
"personId": [
- 517
+ 519
],
"role": [
348
],
"workspaceMemberId": [
- 517
+ 519
],
"__typename": [
1
@@ -869,7 +872,7 @@ export default {
73
],
"applicationRegistrationId": [
- 517
+ 519
],
"applicationVariables": [
76
@@ -902,10 +905,10 @@ export default {
282
],
"healthCheckLogicFunctionId": [
- 517
+ 519
],
"id": [
- 517
+ 519
],
"isUninstallBlockedByOtherWorkspaceInstallations": [
4
@@ -914,7 +917,7 @@ export default {
321
],
"logoFileId": [
- 517
+ 519
],
"logoUrl": [
1
@@ -929,13 +932,13 @@ export default {
1
],
"packageJsonFileId": [
- 517
+ 519
],
"settingsCustomTabFrontComponentId": [
- 517
+ 519
],
"settingsMenuItems": [
- 477
+ 479
],
"universalIdentifier": [
1
@@ -947,7 +950,7 @@ export default {
1
],
"yarnLockFileId": [
- 517
+ 519
],
"__typename": [
1
@@ -955,7 +958,7 @@ export default {
},
"ApplicationAuthorization": {
"applicationId": [
- 517
+ 519
],
"applicationName": [
1
@@ -967,7 +970,7 @@ export default {
207
],
"id": [
- 517
+ 519
],
"lastAuthorizedAt": [
207
@@ -979,7 +982,7 @@ export default {
1
],
"workspaceId": [
- 517
+ 519
],
"__typename": [
1
@@ -990,7 +993,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"__typename": [
1
@@ -998,7 +1001,7 @@ export default {
},
"ApplicationConnectedAccountDTO": {
"applicationId": [
- 517
+ 519
],
"archivedAt": [
207
@@ -1013,7 +1016,7 @@ export default {
417
],
"connectionProviderId": [
- 517
+ 519
],
"createdAt": [
207
@@ -1025,7 +1028,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isOwnedByCurrentUser": [
4
@@ -1052,7 +1055,7 @@ export default {
207
],
"userWorkspaceId": [
- 517
+ 519
],
"visibility": [
1
@@ -1069,7 +1072,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"logoUrl": [
1
@@ -1166,7 +1169,7 @@ export default {
},
"ApplicationFileCompletionError": {
"fileId": [
- 517
+ 519
],
"message": [
1
@@ -1214,7 +1217,7 @@ export default {
275
],
"fileId": [
- 517
+ 519
],
"filePath": [
1
@@ -1421,13 +1424,13 @@ export default {
},
"ApplicationPreferences": {
"applicationId": [
- 517
+ 519
],
"settingsMenuItems": [
- 477
+ 479
],
"variables": [
- 614
+ 616
],
"__typename": [
1
@@ -1441,7 +1444,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isConfigured": [
4
@@ -1474,7 +1477,7 @@ export default {
1
],
"ownerWorkspaceId": [
- 517
+ 519
],
"sourcePackage": [
1
@@ -1513,7 +1516,7 @@ export default {
6
],
"versionDistribution": [
- 624
+ 626
],
"__typename": [
1
@@ -1521,7 +1524,7 @@ export default {
},
"ApplicationRegistrationSummary": {
"id": [
- 517
+ 519
],
"latestAvailableVersion": [
1
@@ -1544,7 +1547,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isDeprecated": [
4
@@ -1593,7 +1596,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isDeprecated": [
4
@@ -1635,7 +1638,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isValidated": [
4
@@ -1732,7 +1735,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"inviteHash": [
1
@@ -1750,7 +1753,7 @@ export default {
458
],
"workspaceUrls": [
- 666
+ 668
],
"__typename": [
1
@@ -1781,7 +1784,7 @@ export default {
"AxisNameDisplay": {},
"BarChartConfiguration": {
"aggregateFieldMetadataId": [
- 517
+ 519
],
"aggregateOperation": [
26
@@ -1793,7 +1796,7 @@ export default {
1
],
"configurationType": [
- 643
+ 645
],
"description": [
1
@@ -1829,7 +1832,7 @@ export default {
384
],
"primaryAxisGroupByFieldMetadataId": [
- 517
+ 519
],
"primaryAxisGroupBySubFieldName": [
1
@@ -1850,7 +1853,7 @@ export default {
384
],
"secondaryAxisGroupByFieldMetadataId": [
- 517
+ 519
],
"secondaryAxisGroupBySubFieldName": [
1
@@ -1917,7 +1920,7 @@ export default {
309
],
"objectMetadataId": [
- 517
+ 519
],
"__typename": [
1
@@ -1959,10 +1962,10 @@ export default {
4
],
"id": [
- 517
+ 519
],
"userCreditsFallback": [
- 615
+ 617
],
"__typename": [
1
@@ -1982,7 +1985,7 @@ export default {
4
],
"status": [
- 491
+ 493
],
"__typename": [
1
@@ -2092,7 +2095,7 @@ export default {
123
],
"recurringInterval": [
- 490
+ 492
],
"stripePriceId": [
1
@@ -2109,7 +2112,7 @@ export default {
123
],
"recurringInterval": [
- 490
+ 492
],
"stripePriceId": [
1
@@ -2256,10 +2259,10 @@ export default {
4
],
"id": [
- 517
+ 519
],
"interval": [
- 490
+ 492
],
"metadata": [
309
@@ -2268,7 +2271,7 @@ export default {
119
],
"status": [
- 491
+ 493
],
"__typename": [
1
@@ -2286,7 +2289,7 @@ export default {
4
],
"id": [
- 517
+ 519
],
"quantity": [
6
@@ -2362,7 +2365,7 @@ export default {
},
"CalendarChannel": {
"connectedAccountId": [
- 517
+ 519
],
"contactAutoCreationPolicy": [
126
@@ -2377,7 +2380,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isContactAutoCreationEnabled": [
4
@@ -2416,7 +2419,7 @@ export default {
"CalendarChannelVisibility": {},
"CalendarConfiguration": {
"configurationType": [
- 643
+ 645
],
"__typename": [
1
@@ -2424,7 +2427,7 @@ export default {
},
"CallRecordingSummaryConfiguration": {
"configurationType": [
- 643
+ 645
],
"__typename": [
1
@@ -2432,7 +2435,7 @@ export default {
},
"CallRecordingTranscriptConfiguration": {
"configurationType": [
- 643
+ 645
],
"__typename": [
1
@@ -2509,7 +2512,7 @@ export default {
"ChartNumberFormat": {},
"ChatConfiguration": {
"configurationType": [
- 643
+ 645
],
"__typename": [
1
@@ -2542,7 +2545,7 @@ export default {
},
"ChatThreadsConfiguration": {
"configurationType": [
- 643
+ 645
],
"__typename": [
1
@@ -2815,7 +2818,7 @@ export default {
1
],
"sentry": [
- 475
+ 477
],
"serverUrl": [
1
@@ -2824,7 +2827,7 @@ export default {
4
],
"support": [
- 492
+ 494
],
"__typename": [
1
@@ -2857,10 +2860,10 @@ export default {
},
"CommandMenuItem": {
"applicationId": [
- 517
+ 519
],
"availabilityObjectMetadataId": [
- 517
+ 519
],
"availabilityType": [
153
@@ -2872,7 +2875,7 @@ export default {
1
],
"coreWorkflowVersionId": [
- 517
+ 519
],
"createdAt": [
207
@@ -2884,7 +2887,7 @@ export default {
282
],
"frontComponentId": [
- 517
+ 519
],
"hotKeys": [
1
@@ -2893,7 +2896,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isActive": [
4
@@ -2905,10 +2908,10 @@ export default {
1
],
"navigationTargetObjectMetadataId": [
- 517
+ 519
],
"pageLayoutId": [
- 517
+ 519
],
"payload": [
154
@@ -2920,13 +2923,13 @@ export default {
1
],
"universalIdentifier": [
- 517
+ 519
],
"updatedAt": [
207
],
"workflowVersionId": [
- 517
+ 519
],
"__typename": [
1
@@ -2957,7 +2960,7 @@ export default {
},
"ConnectedAccountPublicDTO": {
"applicationId": [
- 517
+ 519
],
"archivedAt": [
207
@@ -2972,7 +2975,7 @@ export default {
417
],
"connectionProviderId": [
- 517
+ 519
],
"createdAt": [
207
@@ -2984,7 +2987,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"lastCredentialsRefreshedAt": [
207
@@ -3008,7 +3011,7 @@ export default {
207
],
"userWorkspaceId": [
- 517
+ 519
],
"visibility": [
1
@@ -3026,13 +3029,13 @@ export default {
1
],
"id": [
- 517
+ 519
],
"provider": [
1
],
"userWorkspaceId": [
- 517
+ 519
],
"__typename": [
1
@@ -3071,7 +3074,7 @@ export default {
1
],
"roleIds": [
- 517
+ 519
],
"__typename": [
1
@@ -3103,7 +3106,7 @@ export default {
309
],
"roleId": [
- 517
+ 519
],
"triggers": [
309
@@ -3123,7 +3126,7 @@ export default {
1
],
"roleId": [
- 517
+ 519
],
"__typename": [
1
@@ -3131,7 +3134,7 @@ export default {
},
"CreateAppMessageChannelInput": {
"connectedAccountId": [
- 517
+ 519
],
"displayName": [
1
@@ -3139,8 +3142,11 @@ export default {
"handle": [
1
],
+ "messagingProviderUniversalIdentifier": [
+ 519
+ ],
"participantHandleFieldUniversalIdentifier": [
- 517
+ 519
],
"visibility": [
344
@@ -3259,7 +3265,7 @@ export default {
},
"CreateCommandMenuItemInput": {
"availabilityObjectMetadataId": [
- 517
+ 519
],
"availabilityType": [
153
@@ -3271,13 +3277,13 @@ export default {
1
],
"coreWorkflowVersionId": [
- 517
+ 519
],
"engineComponentKey": [
241
],
"frontComponentId": [
- 517
+ 519
],
"hotKeys": [
1
@@ -3292,10 +3298,10 @@ export default {
1
],
"navigationTargetObjectMetadataId": [
- 517
+ 519
],
"pageLayoutId": [
- 517
+ 519
],
"payload": [
309
@@ -3307,7 +3313,7 @@ export default {
1
],
"workflowVersionId": [
- 517
+ 519
],
"__typename": [
1
@@ -3393,7 +3399,7 @@ export default {
1
],
"objectMetadataId": [
- 517
+ 519
],
"options": [
309
@@ -3425,7 +3431,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"name": [
1
@@ -3439,7 +3445,7 @@ export default {
},
"CreateIndexFieldInput": {
"fieldMetadataId": [
- 517
+ 519
],
"subFieldName": [
1
@@ -3456,7 +3462,7 @@ export default {
302
],
"objectMetadataId": [
- 517
+ 519
],
"__typename": [
1
@@ -3476,7 +3482,7 @@ export default {
309
],
"id": [
- 517
+ 519
],
"name": [
1
@@ -3494,7 +3500,7 @@ export default {
309
],
"universalIdentifier": [
- 517
+ 519
],
"workflowActionTriggerSettings": [
309
@@ -3508,7 +3514,7 @@ export default {
1
],
"unsubscribeTopicId": [
- 517
+ 519
],
"__typename": [
1
@@ -3516,19 +3522,19 @@ export default {
},
"CreateNavigationMenuItemInput": {
"agentChatChannelId": [
- 517
+ 519
],
"color": [
1
],
"folderId": [
- 517
+ 519
],
"icon": [
1
],
"id": [
- 517
+ 519
],
"link": [
1
@@ -3537,25 +3543,25 @@ export default {
1
],
"pageLayoutId": [
- 517
+ 519
],
"position": [
6
],
"targetObjectMetadataId": [
- 517
+ 519
],
"targetRecordId": [
- 517
+ 519
],
"type": [
368
],
"userWorkspaceId": [
- 517
+ 519
],
"viewId": [
- 517
+ 519
],
"__typename": [
1
@@ -3634,7 +3640,7 @@ export default {
1
],
"objectMetadataId": [
- 517
+ 519
],
"type": [
394
@@ -3648,7 +3654,7 @@ export default {
393
],
"pageLayoutId": [
- 517
+ 519
],
"position": [
6
@@ -3665,10 +3671,10 @@ export default {
309
],
"objectMetadataId": [
- 517
+ 519
],
"pageLayoutTabId": [
- 517
+ 519
],
"position": [
309
@@ -3677,7 +3683,7 @@ export default {
1
],
"type": [
- 644
+ 646
],
"__typename": [
1
@@ -3685,13 +3691,13 @@ export default {
},
"CreateRecordExportInput": {
"fieldMetadataIds": [
- 517
+ 519
],
"filter": [
309
],
"objectMetadataId": [
- 517
+ 519
],
"orderBy": [
309
@@ -3758,7 +3764,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"label": [
1
@@ -3778,7 +3784,7 @@ export default {
1
],
"visibility": [
- 521
+ 523
],
"__typename": [
1
@@ -3795,7 +3801,7 @@ export default {
96
],
"operationType": [
- 602
+ 604
],
"periodCount": [
10
@@ -3804,7 +3810,7 @@ export default {
1
],
"resourceType": [
- 609
+ 611
],
"spenderId": [
1
@@ -3813,7 +3819,7 @@ export default {
1
],
"unit": [
- 611
+ 613
],
"__typename": [
1
@@ -3824,7 +3830,7 @@ export default {
1
],
"errorFieldMetadataId": [
- 517
+ 519
],
"expression": [
1
@@ -3842,7 +3848,7 @@ export default {
1
],
"objectMetadataId": [
- 517
+ 519
],
"__typename": [
1
@@ -3850,7 +3856,7 @@ export default {
},
"CreateViewFieldGroupInput": {
"id": [
- 517
+ 519
],
"isVisible": [
4
@@ -3862,7 +3868,7 @@ export default {
6
],
"viewId": [
- 517
+ 519
],
"__typename": [
1
@@ -3873,10 +3879,10 @@ export default {
26
],
"fieldMetadataId": [
- 517
+ 519
],
"id": [
- 517
+ 519
],
"isVisible": [
4
@@ -3888,10 +3894,10 @@ export default {
6
],
"viewFieldGroupId": [
- 517
+ 519
],
"viewId": [
- 517
+ 519
],
"__typename": [
1
@@ -3899,19 +3905,19 @@ export default {
},
"CreateViewFilterGroupInput": {
"id": [
- 517
+ 519
],
"logicalOperator": [
- 632
+ 634
],
"parentViewFilterGroupId": [
- 517
+ 519
],
"positionInViewFilterGroup": [
6
],
"viewId": [
- 517
+ 519
],
"__typename": [
1
@@ -3919,19 +3925,19 @@ export default {
},
"CreateViewFilterInput": {
"fieldMetadataId": [
- 517
+ 519
],
"id": [
- 517
+ 519
],
"operand": [
- 633
+ 635
],
"positionInViewFilterGroup": [
6
],
"relationTargetFieldMetadataId": [
- 517
+ 519
],
"subFieldName": [
1
@@ -3940,10 +3946,10 @@ export default {
309
],
"viewFilterGroupId": [
- 517
+ 519
],
"viewId": [
- 517
+ 519
],
"__typename": [
1
@@ -3954,7 +3960,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isVisible": [
4
@@ -3963,7 +3969,7 @@ export default {
6
],
"viewId": [
- 517
+ 519
],
"__typename": [
1
@@ -3974,13 +3980,13 @@ export default {
1
],
"calendarEndFieldMetadataId": [
- 517
+ 519
],
"calendarFieldMetadataId": [
- 517
+ 519
],
"calendarLayout": [
- 626
+ 628
],
"groupLoadLimit": [
10
@@ -3989,7 +3995,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isCompact": [
4
@@ -3998,25 +4004,25 @@ export default {
26
],
"kanbanAggregateOperationFieldMetadataId": [
- 517
+ 519
],
"kanbanColumnWidth": [
10
],
"key": [
- 635
+ 637
],
"mainGroupByFieldMetadataId": [
- 517
+ 519
],
"name": [
1
],
"objectMetadataId": [
- 517
+ 519
],
"openRecordIn": [
- 636
+ 638
],
"position": [
6
@@ -4025,10 +4031,10 @@ export default {
4
],
"type": [
- 639
+ 641
],
"visibility": [
- 640
+ 642
],
"__typename": [
1
@@ -4036,19 +4042,19 @@ export default {
},
"CreateViewSortInput": {
"direction": [
- 638
+ 640
],
"fieldMetadataId": [
- 517
+ 519
],
"id": [
- 517
+ 519
],
"subFieldName": [
1
],
"viewId": [
- 517
+ 519
],
"__typename": [
1
@@ -4059,7 +4065,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"operations": [
1
@@ -4082,10 +4088,10 @@ export default {
1
],
"operation": [
- 602
+ 604
],
"resource": [
- 609
+ 611
],
"__typename": [
1
@@ -4112,7 +4118,7 @@ export default {
"DateTime": {},
"DeleteApprovedAccessDomainInput": {
"id": [
- 517
+ 519
],
"__typename": [
1
@@ -4120,7 +4126,7 @@ export default {
},
"DeleteOneFieldInput": {
"id": [
- 517
+ 519
],
"__typename": [
1
@@ -4128,7 +4134,7 @@ export default {
},
"DeleteOneIndexInput": {
"id": [
- 517
+ 519
],
"__typename": [
1
@@ -4136,7 +4142,7 @@ export default {
},
"DeleteOneObjectInput": {
"id": [
- 517
+ 519
],
"__typename": [
1
@@ -4144,7 +4150,7 @@ export default {
},
"DeleteSso": {
"identityProviderId": [
- 517
+ 519
],
"__typename": [
1
@@ -4152,7 +4158,7 @@ export default {
},
"DeleteSsoInput": {
"identityProviderId": [
- 517
+ 519
],
"__typename": [
1
@@ -4168,7 +4174,7 @@ export default {
},
"DeleteViewFieldGroupInput": {
"id": [
- 517
+ 519
],
"__typename": [
1
@@ -4176,7 +4182,7 @@ export default {
},
"DeleteViewFieldInput": {
"id": [
- 517
+ 519
],
"__typename": [
1
@@ -4184,7 +4190,7 @@ export default {
},
"DeleteViewFilterInput": {
"id": [
- 517
+ 519
],
"__typename": [
1
@@ -4192,7 +4198,7 @@ export default {
},
"DeleteViewGroupInput": {
"id": [
- 517
+ 519
],
"__typename": [
1
@@ -4200,7 +4206,7 @@ export default {
},
"DeleteViewSortInput": {
"id": [
- 517
+ 519
],
"__typename": [
1
@@ -4211,7 +4217,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"name": [
285
@@ -4220,7 +4226,7 @@ export default {
1
],
"userWorkspaceId": [
- 517
+ 519
],
"__typename": [
1
@@ -4228,7 +4234,7 @@ export default {
},
"DestroyViewFieldGroupInput": {
"id": [
- 517
+ 519
],
"__typename": [
1
@@ -4236,7 +4242,7 @@ export default {
},
"DestroyViewFieldInput": {
"id": [
- 517
+ 519
],
"__typename": [
1
@@ -4244,7 +4250,7 @@ export default {
},
"DestroyViewFilterInput": {
"id": [
- 517
+ 519
],
"__typename": [
1
@@ -4252,7 +4258,7 @@ export default {
},
"DestroyViewGroupInput": {
"id": [
- 517
+ 519
],
"__typename": [
1
@@ -4260,7 +4266,7 @@ export default {
},
"DestroyViewSortInput": {
"id": [
- 517
+ 519
],
"__typename": [
1
@@ -4302,7 +4308,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isCustomDomainEnabled": [
4
@@ -4319,10 +4325,10 @@ export default {
1
],
"id": [
- 517
+ 519
],
"pageLayoutId": [
- 517
+ 519
],
"position": [
6
@@ -4345,7 +4351,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"memberCount": [
6
@@ -4365,7 +4371,7 @@ export default {
},
"EditSso": {
"id": [
- 517
+ 519
],
"issuer": [
1
@@ -4385,7 +4391,7 @@ export default {
},
"EditSsoInput": {
"id": [
- 517
+ 519
],
"status": [
460
@@ -4422,7 +4428,7 @@ export default {
},
"EmailThreadConfiguration": {
"configurationType": [
- 643
+ 645
],
"__typename": [
1
@@ -4436,7 +4442,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"status": [
238
@@ -4445,13 +4451,13 @@ export default {
239
],
"unsubscribeHostnameStatus": [
- 519
+ 521
],
"updatedAt": [
207
],
"verificationRecords": [
- 621
+ 623
],
"verifiedAt": [
207
@@ -4464,7 +4470,7 @@ export default {
"EmailingDomainTenantStatus": {},
"EmailsConfiguration": {
"configurationType": [
- 643
+ 645
],
"__typename": [
1
@@ -4730,7 +4736,7 @@ export default {
},
"ExecuteOneLogicFunctionInput": {
"id": [
- 517
+ 519
],
"payload": [
309
@@ -4753,7 +4759,7 @@ export default {
"FeatureFlagKey": {},
"Field": {
"applicationId": [
- 517
+ 519
],
"createdAt": [
207
@@ -4768,7 +4774,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isActive": [
4
@@ -4801,7 +4807,7 @@ export default {
1
],
"morphId": [
- 517
+ 519
],
"morphRelations": [
436
@@ -4813,7 +4819,7 @@ export default {
370
],
"objectMetadataId": [
- 517
+ 519
],
"options": [
309
@@ -4842,7 +4848,7 @@ export default {
},
"FieldConfiguration": {
"configurationType": [
- 643
+ 645
],
"fieldDisplayMode": [
265
@@ -4891,7 +4897,7 @@ export default {
267
],
"id": [
- 518
+ 520
],
"isActive": [
124
@@ -4906,7 +4912,7 @@ export default {
124
],
"objectMetadataId": [
- 518
+ 520
],
"or": [
267
@@ -4924,16 +4930,16 @@ export default {
4
],
"fieldMetadataId": [
- 517
+ 519
],
"id": [
- 517
+ 519
],
"objectMetadataId": [
- 517
+ 519
],
"roleId": [
- 517
+ 519
],
"__typename": [
1
@@ -4947,10 +4953,10 @@ export default {
4
],
"fieldMetadataId": [
- 517
+ 519
],
"objectMetadataId": [
- 517
+ 519
],
"__typename": [
1
@@ -4958,7 +4964,7 @@ export default {
},
"FieldRichTextConfiguration": {
"configurationType": [
- 643
+ 645
],
"__typename": [
1
@@ -4966,7 +4972,7 @@ export default {
},
"FieldsConfiguration": {
"configurationType": [
- 643
+ 645
],
"newFieldDefaultVisibility": [
4
@@ -4986,7 +4992,7 @@ export default {
207
],
"id": [
- 517
+ 519
],
"path": [
1
@@ -5003,7 +5009,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"__typename": [
1
@@ -5018,7 +5024,7 @@ export default {
207
],
"fileId": [
- 517
+ 519
],
"uploadUrl": [
1
@@ -5032,7 +5038,7 @@ export default {
207
],
"id": [
- 517
+ 519
],
"path": [
1
@@ -5049,7 +5055,7 @@ export default {
},
"FilesConfiguration": {
"configurationType": [
- 643
+ 645
],
"__typename": [
1
@@ -5057,7 +5063,7 @@ export default {
},
"FindAvailableSSOIDP": {
"id": [
- 517
+ 519
],
"issuer": [
1
@@ -5072,7 +5078,7 @@ export default {
292
],
"workspace": [
- 663
+ 665
],
"__typename": [
1
@@ -5092,7 +5098,7 @@ export default {
1
],
"unsubscribeTopicId": [
- 517
+ 519
],
"__typename": [
1
@@ -5100,7 +5106,7 @@ export default {
},
"FormFieldConfiguration": {
"configurationType": [
- 643
+ 645
],
"fieldMetadataId": [
1
@@ -5114,7 +5120,7 @@ export default {
1
],
"applicationId": [
- 517
+ 519
],
"applicationName": [
1
@@ -5144,7 +5150,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isHeadless": [
4
@@ -5156,7 +5162,7 @@ export default {
1
],
"universalIdentifier": [
- 517
+ 519
],
"updatedAt": [
207
@@ -5173,13 +5179,13 @@ export default {
},
"FrontComponentConfiguration": {
"configurationType": [
- 643
+ 645
],
"frontComponentId": [
- 517
+ 519
],
"headerCommandMenuItemUniversalIdentifiers": [
- 517
+ 519
],
"__typename": [
1
@@ -5187,7 +5193,7 @@ export default {
},
"FrontComponentWidgetAvailability": {
"objectMetadataId": [
- 517
+ 519
],
"pageLayoutType": [
394
@@ -5209,7 +5215,7 @@ export default {
},
"GetApiKeyInput": {
"id": [
- 517
+ 519
],
"__typename": [
1
@@ -5220,7 +5226,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"type": [
1
@@ -5231,7 +5237,7 @@ export default {
},
"GetAuthorizationUrlForSSOInput": {
"identityProviderId": [
- 517
+ 519
],
"workspaceInviteHash": [
1
@@ -5242,7 +5248,7 @@ export default {
},
"GrantApplicationCapabilitiesInput": {
"applicationId": [
- 517
+ 519
],
"capabilities": [
1
@@ -5272,7 +5278,7 @@ export default {
"IdentityProviderType": {},
"IframeConfiguration": {
"configurationType": [
- 643
+ 645
],
"url": [
1
@@ -5331,7 +5337,7 @@ export default {
81
],
"workspace": [
- 667
+ 669
],
"__typename": [
1
@@ -5342,7 +5348,7 @@ export default {
207
],
"id": [
- 517
+ 519
],
"indexFieldMetadataList": [
300
@@ -5385,10 +5391,10 @@ export default {
207
],
"fieldMetadataId": [
- 517
+ 519
],
"id": [
- 517
+ 519
],
"order": [
6
@@ -5408,7 +5414,7 @@ export default {
301
],
"id": [
- 518
+ 520
],
"isCustom": [
124
@@ -5423,7 +5429,7 @@ export default {
"IndexType": {},
"IngestAppMessagesInput": {
"messageChannelId": [
- 517
+ 519
],
"messages": [
42
@@ -5445,10 +5451,10 @@ export default {
1
],
"messageId": [
- 517
+ 519
],
"messageThreadId": [
- 517
+ 519
],
"__typename": [
1
@@ -5515,7 +5521,7 @@ export default {
},
"LineChartConfiguration": {
"aggregateFieldMetadataId": [
- 517
+ 519
],
"aggregateOperation": [
26
@@ -5527,7 +5533,7 @@ export default {
1
],
"configurationType": [
- 643
+ 645
],
"description": [
1
@@ -5560,7 +5566,7 @@ export default {
384
],
"primaryAxisGroupByFieldMetadataId": [
- 517
+ 519
],
"primaryAxisGroupBySubFieldName": [
1
@@ -5581,7 +5587,7 @@ export default {
384
],
"secondaryAxisGroupByFieldMetadataId": [
- 517
+ 519
],
"secondaryAxisGroupBySubFieldName": [
1
@@ -5633,7 +5639,7 @@ export default {
309
],
"objectMetadataId": [
- 517
+ 519
],
"__typename": [
1
@@ -5683,7 +5689,7 @@ export default {
},
"ListAppMessageChannelsInput": {
"connectedAccountId": [
- 517
+ 519
],
"__typename": [
1
@@ -5702,7 +5708,7 @@ export default {
},
"LogicFunction": {
"applicationId": [
- 517
+ 519
],
"canRunOnDemand": [
4
@@ -5729,7 +5735,7 @@ export default {
309
],
"id": [
- 517
+ 519
],
"name": [
1
@@ -5747,7 +5753,7 @@ export default {
309
],
"universalIdentifier": [
- 517
+ 519
],
"updatedAt": [
207
@@ -5797,7 +5803,7 @@ export default {
1
],
"universalIdentifier": [
- 517
+ 519
],
"__typename": [
1
@@ -5805,19 +5811,19 @@ export default {
},
"LogicFunctionLogsInput": {
"applicationId": [
- 517
+ 519
],
"applicationUniversalIdentifier": [
- 517
+ 519
],
"id": [
- 517
+ 519
],
"name": [
1
],
"universalIdentifier": [
- 517
+ 519
],
"__typename": [
1
@@ -6049,7 +6055,7 @@ export default {
},
"MessageCampaignBodyConfiguration": {
"configurationType": [
- 643
+ 645
],
"__typename": [
1
@@ -6057,7 +6063,7 @@ export default {
},
"MessageCampaignDetailsConfiguration": {
"configurationType": [
- 643
+ 645
],
"__typename": [
1
@@ -6079,7 +6085,7 @@ export default {
156
],
"connectedAccountId": [
- 517
+ 519
],
"contactAutoCreationPolicy": [
339
@@ -6100,7 +6106,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"importProgress": [
10
@@ -6114,8 +6120,11 @@ export default {
"messageFolderImportPolicy": [
346
],
+ "messagingProviderUniversalIdentifier": [
+ 519
+ ],
"participantHandleFieldUniversalIdentifier": [
- 517
+ 519
],
"pendingGroupEmailsAction": [
340
@@ -6165,7 +6174,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isSentFolder": [
4
@@ -6174,7 +6183,7 @@ export default {
4
],
"messageChannelId": [
- 517
+ 519
],
"name": [
1
@@ -6203,7 +6212,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"reason": [
351
@@ -6212,7 +6221,7 @@ export default {
352
],
"unsubscribeTopicId": [
- 517
+ 519
],
"__typename": [
1
@@ -6264,7 +6273,7 @@ export default {
1
],
"objectMetadataId": [
- 517
+ 519
],
"property": [
1
@@ -6273,7 +6282,7 @@ export default {
358
],
"recordId": [
- 517
+ 519
],
"sourceValue": [
1
@@ -6302,13 +6311,13 @@ export default {
"MetadataTranslationProvenance": {},
"MetadataTranslationsInput": {
"fieldMetadataId": [
- 517
+ 519
],
"locale": [
1
],
"objectMetadataId": [
- 517
+ 519
],
"__typename": [
1
@@ -6337,7 +6346,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isActive": [
4
@@ -6366,16 +6375,16 @@ export default {
},
"MinimalView": {
"id": [
- 517
+ 519
],
"key": [
- 635
+ 637
],
"objectMetadataId": [
- 517
+ 519
],
"type": [
- 639
+ 641
],
"__typename": [
1
@@ -6384,16 +6393,16 @@ export default {
"ModelFamily": {},
"Mutation": {
"activateSkill": [
- 484,
+ 486,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
],
"activateWorkspace": [
- 648,
+ 650,
{
"data": [
0,
@@ -6409,7 +6418,7 @@ export default {
"String!"
],
"messageId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -6427,10 +6436,10 @@ export default {
4,
{
"assigneeWorkspaceMemberId": [
- 517
+ 519
],
"threadId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -6439,11 +6448,11 @@ export default {
4,
{
"agentId": [
- 517,
+ 519,
"UUID!"
],
"roleId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -6452,11 +6461,11 @@ export default {
4,
{
"apiKeyId": [
- 517,
+ 519,
"UUID!"
],
"roleId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -6524,7 +6533,7 @@ export default {
"BillingPlanKey!"
],
"recurringInterval": [
- 490,
+ 492,
"SubscriptionInterval!"
],
"requirePaymentMethod": [
@@ -6549,7 +6558,7 @@ export default {
70,
{
"fileId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -6562,7 +6571,7 @@ export default {
"String!"
],
"fileIds": [
- 517,
+ 519,
"[UUID!]!"
]
}
@@ -6694,7 +6703,7 @@ export default {
16,
{
"channelId": [
- 517
+ 519
]
}
],
@@ -6780,7 +6789,7 @@ export default {
}
],
"createManyViewFieldGroups": [
- 629,
+ 631,
{
"inputs": [
196,
@@ -6789,7 +6798,7 @@ export default {
}
],
"createManyViewFields": [
- 628,
+ 630,
{
"inputs": [
197,
@@ -6798,7 +6807,7 @@ export default {
}
],
"createManyViewGroups": [
- 634,
+ 636,
{
"inputs": [
200,
@@ -6842,10 +6851,10 @@ export default {
}
],
"createOIDCIdentityProvider": [
- 481,
+ 483,
{
"input": [
- 479,
+ 481,
"SetupOIDCSsoInput!"
]
}
@@ -6858,14 +6867,14 @@ export default {
"String!"
],
"objectMetadataId": [
- 517,
+ 519,
"UUID!"
],
"properties": [
309
],
"recordId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -6965,16 +6974,16 @@ export default {
}
],
"createSAMLIdentityProvider": [
- 481,
+ 483,
{
"input": [
- 480,
+ 482,
"SetupSAMLSsoInput!"
]
}
],
"createSkill": [
- 484,
+ 486,
{
"input": [
192,
@@ -6994,7 +7003,7 @@ export default {
"BillingPlanKey!"
],
"recurringInterval": [
- 490,
+ 492,
"SubscriptionInterval!"
],
"requirePaymentMethod": [
@@ -7007,7 +7016,7 @@ export default {
}
],
"createUnsubscribeTopic": [
- 520,
+ 522,
{
"input": [
193,
@@ -7016,7 +7025,7 @@ export default {
}
],
"createUsageLimit": [
- 600,
+ 602,
{
"input": [
194,
@@ -7025,7 +7034,7 @@ export default {
}
],
"createValidationRule": [
- 620,
+ 622,
{
"input": [
195,
@@ -7034,7 +7043,7 @@ export default {
}
],
"createView": [
- 625,
+ 627,
{
"input": [
201,
@@ -7043,7 +7052,7 @@ export default {
}
],
"createViewField": [
- 628,
+ 630,
{
"input": [
197,
@@ -7052,7 +7061,7 @@ export default {
}
],
"createViewFieldGroup": [
- 629,
+ 631,
{
"input": [
196,
@@ -7061,7 +7070,7 @@ export default {
}
],
"createViewFilter": [
- 630,
+ 632,
{
"input": [
199,
@@ -7070,7 +7079,7 @@ export default {
}
],
"createViewFilterGroup": [
- 631,
+ 633,
{
"input": [
198,
@@ -7079,7 +7088,7 @@ export default {
}
],
"createViewGroup": [
- 634,
+ 636,
{
"input": [
200,
@@ -7088,7 +7097,7 @@ export default {
}
],
"createViewSort": [
- 637,
+ 639,
{
"input": [
202,
@@ -7097,7 +7106,7 @@ export default {
}
],
"createWebhook": [
- 641,
+ 643,
{
"input": [
203,
@@ -7106,10 +7115,10 @@ export default {
}
],
"deactivateSkill": [
- 484,
+ 486,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
@@ -7118,11 +7127,11 @@ export default {
4,
{
"channelId": [
- 517,
+ 519,
"UUID!"
],
"destinationChannelId": [
- 517
+ 519
]
}
],
@@ -7142,7 +7151,7 @@ export default {
338,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
@@ -7169,7 +7178,7 @@ export default {
152,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
@@ -7178,19 +7187,19 @@ export default {
156,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
],
"deleteCurrentWorkspace": [
- 648
+ 650
],
"deleteEmailGroupChannel": [
338,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
@@ -7208,7 +7217,7 @@ export default {
282,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
@@ -7217,7 +7226,7 @@ export default {
367,
{
"ids": [
- 517,
+ 519,
"[UUID!]!"
]
}
@@ -7226,7 +7235,7 @@ export default {
4,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
@@ -7235,7 +7244,7 @@ export default {
367,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
@@ -7289,7 +7298,7 @@ export default {
1,
{
"roleId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -7307,7 +7316,7 @@ export default {
4,
{
"messageId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -7322,10 +7331,10 @@ export default {
}
],
"deleteSkill": [
- 484,
+ 486,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
@@ -7334,7 +7343,7 @@ export default {
214,
{
"twoFactorAuthenticationMethodId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -7352,16 +7361,16 @@ export default {
4,
{
"usageLimitId": [
- 517,
+ 519,
"UUID!"
]
}
],
"deleteUser": [
- 613
+ 615
],
"deleteUserFromWorkspace": [
- 617,
+ 619,
{
"workspaceMemberIdToDelete": [
1,
@@ -7370,10 +7379,10 @@ export default {
}
],
"deleteValidationRule": [
- 620,
+ 622,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
@@ -7388,7 +7397,7 @@ export default {
}
],
"deleteViewField": [
- 628,
+ 630,
{
"input": [
216,
@@ -7397,7 +7406,7 @@ export default {
}
],
"deleteViewFieldGroup": [
- 629,
+ 631,
{
"input": [
215,
@@ -7406,7 +7415,7 @@ export default {
}
],
"deleteViewFilter": [
- 630,
+ 632,
{
"input": [
217,
@@ -7424,7 +7433,7 @@ export default {
}
],
"deleteViewGroup": [
- 634,
+ 636,
{
"input": [
218,
@@ -7442,10 +7451,10 @@ export default {
}
],
"deleteWebhook": [
- 641,
+ 643,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
@@ -7496,7 +7505,7 @@ export default {
}
],
"destroyViewField": [
- 628,
+ 630,
{
"input": [
222,
@@ -7505,7 +7514,7 @@ export default {
}
],
"destroyViewFieldGroup": [
- 629,
+ 631,
{
"input": [
221,
@@ -7514,7 +7523,7 @@ export default {
}
],
"destroyViewFilter": [
- 630,
+ 632,
{
"input": [
223,
@@ -7532,7 +7541,7 @@ export default {
}
],
"destroyViewGroup": [
- 634,
+ 636,
{
"input": [
224,
@@ -7553,7 +7562,7 @@ export default {
156,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
@@ -7562,7 +7571,7 @@ export default {
229,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
@@ -7571,7 +7580,7 @@ export default {
230,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
@@ -7596,7 +7605,7 @@ export default {
"String!"
],
"workspaceId": [
- 517
+ 519
]
}
],
@@ -7622,7 +7631,7 @@ export default {
}
],
"enrichWorkspaceCompany": [
- 652
+ 654
],
"executeOneLogicFunction": [
323,
@@ -7637,7 +7646,7 @@ export default {
38,
{
"apiKeyId": [
- 517,
+ 519,
"UUID!"
],
"expiresAt": [
@@ -7650,7 +7659,7 @@ export default {
75,
{
"applicationId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -7659,16 +7668,16 @@ export default {
81
],
"generateTransientToken": [
- 500
+ 502
],
"generateTwoFactorAuthenticationRecoveryCode": [
- 514,
+ 516,
{
"otp": [
1
],
"userId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -7716,7 +7725,7 @@ export default {
}
],
"getAuthTokensFromTwoFactorAuthenticationRecoveryCode": [
- 515,
+ 517,
{
"captchaToken": [
1
@@ -7786,11 +7795,11 @@ export default {
297,
{
"userId": [
- 517,
+ 519,
"UUID!"
],
"workspaceId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -7848,7 +7857,7 @@ export default {
4,
{
"threadId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -7857,10 +7866,10 @@ export default {
4,
{
"channelId": [
- 517
+ 519
],
"threadId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -7879,7 +7888,7 @@ export default {
"String!"
],
"messageId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -7910,7 +7919,7 @@ export default {
4,
{
"agentId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -7937,7 +7946,7 @@ export default {
4,
{
"threadId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -7965,7 +7974,7 @@ export default {
}
],
"resendWorkspaceInvitation": [
- 471,
+ 473,
{
"appTokenId": [
1,
@@ -7977,7 +7986,7 @@ export default {
152,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
@@ -8010,22 +8019,22 @@ export default {
}
],
"resetTimelineActivityType": [
- 495,
+ 497,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
],
"retryChatMessage": [
- 463,
+ 465,
{
"modelId": [
1
],
"threadId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -8046,7 +8055,7 @@ export default {
4,
{
"applicationAuthorizationId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -8055,7 +8064,7 @@ export default {
4,
{
"userId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -8064,7 +8073,7 @@ export default {
4,
{
"userSessionId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -8091,7 +8100,7 @@ export default {
60,
{
"applicationId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -8108,29 +8117,38 @@ export default {
"String!"
],
"id": [
- 517
+ 519
+ ]
+ }
+ ],
+ "sendAppChannelMessage": [
+ 464,
+ {
+ "input": [
+ 463,
+ "SendAppChannelMessageInput!"
]
}
],
"sendChatMessage": [
- 463,
+ 465,
{
"browsingContext": [
309
],
"channelId": [
- 517
+ 519
],
"fileAttachments": [
274,
"[FileAttachmentInput!]"
],
"mentionedWorkspaceMemberIds": [
- 517,
+ 519,
"[UUID!]"
],
"messageId": [
- 517,
+ 519,
"UUID!"
],
"modelId": [
@@ -8144,55 +8162,55 @@ export default {
"String!"
],
"threadId": [
- 517,
+ 519,
"UUID!"
]
}
],
"sendEmail": [
- 466,
+ 468,
{
"input": [
- 465,
+ 467,
"SendEmailInput!"
]
}
],
"sendInboxMessage": [
- 470,
+ 472,
{
"input": [
- 469,
+ 471,
"SendInboxMessageInput!"
]
}
],
"sendInvitations": [
- 471,
+ 473,
{
"emails": [
1,
"[String!]!"
],
"roleId": [
- 517
+ 519
]
}
],
"sendMessageCampaign": [
- 473,
+ 475,
{
"input": [
- 472,
+ 474,
"SendMessageCampaignInput!"
]
}
],
"sendMessageCampaignTest": [
- 468,
+ 470,
{
"input": [
- 474,
+ 476,
"SendMessageCampaignTestInput!"
]
}
@@ -8201,7 +8219,7 @@ export default {
40,
{
"input": [
- 476,
+ 478,
"SetAppKeyValueInput!"
]
}
@@ -8307,15 +8325,15 @@ export default {
}
],
"signUpInNewWorkspace": [
- 482,
+ 484,
{
"input": [
- 483
+ 485
]
}
],
"signUpInWorkspace": [
- 482,
+ 484,
{
"captchaToken": [
1
@@ -8335,7 +8353,7 @@ export default {
1
],
"workspaceId": [
- 517
+ 519
],
"workspaceInviteHash": [
1
@@ -8362,7 +8380,7 @@ export default {
"DateTime!"
],
"threadId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -8371,13 +8389,13 @@ export default {
138,
{
"connectedAccountId": [
- 517,
+ 519,
"UUID!"
]
}
],
"startWorkspaceSetupChat": [
- 486,
+ 488,
{
"companyContext": [
309
@@ -8391,13 +8409,13 @@ export default {
4,
{
"threadId": [
- 517,
+ 519,
"UUID!"
]
}
],
"stopImpersonation": [
- 487
+ 489
],
"switchBillingPlan": [
122,
@@ -8411,7 +8429,7 @@ export default {
122
],
"syncApplication": [
- 662,
+ 664,
{
"dryRun": [
4
@@ -8460,55 +8478,55 @@ export default {
}
],
"triggerAddPeopleToMessageListJob": [
- 502,
+ 504,
{
"input": [
- 501,
+ 503,
"TriggerAddPeopleToMessageListJobInput!"
]
}
],
"triggerInstallApplication": [
- 506,
+ 508,
{
"input": [
- 503,
+ 505,
"TriggerInstallApplicationInput!"
]
}
],
"triggerInstallApplicationJob": [
- 505,
+ 507,
{
"input": [
- 504,
+ 506,
"TriggerInstallApplicationJobInput!"
]
}
],
"triggerUninstallApplication": [
- 510,
+ 512,
{
"input": [
- 507,
+ 509,
"TriggerUninstallApplicationInput!"
]
}
],
"triggerUninstallApplicationJob": [
- 509,
+ 511,
{
"input": [
- 508,
+ 510,
"TriggerUninstallApplicationJobInput!"
]
}
],
"triggerUpgradeApplication": [
- 512,
+ 514,
{
"input": [
- 511,
+ 513,
"TriggerUpgradeApplicationInput!"
]
}
@@ -8526,11 +8544,11 @@ export default {
5,
{
"channelId": [
- 517,
+ 519,
"UUID!"
],
"input": [
- 522,
+ 524,
"UpdateAgentChatChannelInput!"
]
}
@@ -8546,7 +8564,7 @@ export default {
207
],
"threadIds": [
- 517,
+ 519,
"[UUID!]!"
]
}
@@ -8555,7 +8573,7 @@ export default {
36,
{
"input": [
- 524,
+ 526,
"UpdateApiKeyInput!"
]
}
@@ -8564,7 +8582,7 @@ export default {
338,
{
"input": [
- 525,
+ 527,
"UpdateAppMessageChannelInput!"
]
}
@@ -8573,11 +8591,11 @@ export default {
44,
{
"id": [
- 517,
+ 519,
"UUID!"
],
"input": [
- 526,
+ 528,
"UpdateApplicationInput!"
]
}
@@ -8586,7 +8604,7 @@ export default {
70,
{
"input": [
- 527,
+ 529,
"UpdateApplicationRegistrationInput!"
]
}
@@ -8595,7 +8613,7 @@ export default {
74,
{
"input": [
- 529,
+ 531,
"UpdateApplicationRegistrationVariableInput!"
]
}
@@ -8604,7 +8622,7 @@ export default {
125,
{
"input": [
- 531,
+ 533,
"UpdateCalendarChannelInput!"
]
}
@@ -8613,7 +8631,7 @@ export default {
152,
{
"input": [
- 533,
+ 535,
"UpdateCommandMenuItemInput!"
]
}
@@ -8622,7 +8640,7 @@ export default {
338,
{
"input": [
- 534,
+ 536,
"UpdateEmailGroupChannelInput!"
]
}
@@ -8631,7 +8649,7 @@ export default {
282,
{
"input": [
- 536,
+ 538,
"UpdateFrontComponentInput!"
]
}
@@ -8640,7 +8658,7 @@ export default {
260,
{
"input": [
- 538,
+ 540,
"UpdateLabPublicFeatureFlagInput!"
]
}
@@ -8649,7 +8667,7 @@ export default {
367,
{
"inputs": [
- 549,
+ 551,
"[UpdateOneNavigationMenuItemInput!]!"
]
}
@@ -8658,16 +8676,16 @@ export default {
370,
{
"inputs": [
- 550,
+ 552,
"[UpdateOneObjectInput!]!"
]
}
],
"updateManyViewGroups": [
- 634,
+ 636,
{
"inputs": [
- 572,
+ 574,
"[UpdateViewGroupInput!]!"
]
}
@@ -8676,7 +8694,7 @@ export default {
338,
{
"input": [
- 541,
+ 543,
"UpdateMessageChannelInput!"
]
}
@@ -8685,7 +8703,7 @@ export default {
345,
{
"input": [
- 543,
+ 545,
"UpdateMessageFolderInput!"
]
}
@@ -8694,7 +8712,7 @@ export default {
345,
{
"input": [
- 545,
+ 547,
"UpdateMessageFoldersInput!"
]
}
@@ -8720,7 +8738,7 @@ export default {
367,
{
"input": [
- 549,
+ 551,
"UpdateOneNavigationMenuItemInput!"
]
}
@@ -8729,7 +8747,7 @@ export default {
3,
{
"input": [
- 523,
+ 525,
"UpdateAgentInput!"
]
}
@@ -8738,7 +8756,7 @@ export default {
4,
{
"applicationId": [
- 517
+ 519
],
"key": [
1,
@@ -8754,7 +8772,7 @@ export default {
262,
{
"input": [
- 548,
+ 550,
"UpdateOneFieldMetadataInput!"
]
}
@@ -8763,7 +8781,7 @@ export default {
4,
{
"input": [
- 539,
+ 541,
"UpdateLogicFunctionFromSourceInput!"
]
}
@@ -8772,7 +8790,7 @@ export default {
370,
{
"input": [
- 550,
+ 552,
"UpdateOneObjectInput!"
]
}
@@ -8781,7 +8799,7 @@ export default {
443,
{
"updateRoleInput": [
- 557,
+ 559,
"UpdateRoleInput!"
]
}
@@ -8794,7 +8812,7 @@ export default {
"String!"
],
"input": [
- 551,
+ 553,
"UpdatePageLayoutInput!"
]
}
@@ -8807,7 +8825,7 @@ export default {
"String!"
],
"input": [
- 552,
+ 554,
"UpdatePageLayoutTabInput!"
]
}
@@ -8820,7 +8838,7 @@ export default {
"String!"
],
"input": [
- 554,
+ 556,
"UpdatePageLayoutWidgetInput!"
]
}
@@ -8833,7 +8851,7 @@ export default {
"String!"
],
"input": [
- 556,
+ 558,
"UpdatePageLayoutWithTabsInput!"
]
}
@@ -8852,37 +8870,37 @@ export default {
}
],
"updateSkill": [
- 484,
+ 486,
{
"input": [
- 559,
+ 561,
"UpdateSkillInput!"
]
}
],
"updateTimelineActivityType": [
- 495,
+ 497,
{
"input": [
- 560,
+ 562,
"UpdateTimelineActivityTypeInput!"
]
}
],
"updateUnsubscribeTopic": [
- 520,
+ 522,
{
"input": [
- 561,
+ 563,
"UpdateUnsubscribeTopicInput!"
]
}
],
"updateUsageLimit": [
- 600,
+ 602,
{
"input": [
- 562,
+ 564,
"UpdateUsageLimitInput!"
]
}
@@ -8891,7 +8909,7 @@ export default {
98,
{
"userCreditsFallback": [
- 615,
+ 617,
"UserCreditsFallback!"
]
}
@@ -8909,121 +8927,121 @@ export default {
}
],
"updateValidationRule": [
- 620,
+ 622,
{
"input": [
- 563,
+ 565,
"UpdateValidationRuleInput!"
]
}
],
"updateView": [
- 625,
+ 627,
{
"id": [
1,
"String!"
],
"input": [
- 574,
+ 576,
"UpdateViewInput!"
]
}
],
"updateViewField": [
- 628,
+ 630,
{
"input": [
- 567,
+ 569,
"UpdateViewFieldInput!"
]
}
],
"updateViewFieldGroup": [
- 629,
+ 631,
{
"input": [
- 565,
+ 567,
"UpdateViewFieldGroupInput!"
]
}
],
"updateViewFilter": [
- 630,
+ 632,
{
"input": [
- 570,
+ 572,
"UpdateViewFilterInput!"
]
}
],
"updateViewFilterGroup": [
- 631,
+ 633,
{
"id": [
1,
"String!"
],
"input": [
- 569,
+ 571,
"UpdateViewFilterGroupInput!"
]
}
],
"updateViewGroup": [
- 634,
+ 636,
{
"input": [
- 572,
+ 574,
"UpdateViewGroupInput!"
]
}
],
"updateViewSort": [
- 637,
+ 639,
{
"input": [
- 575,
+ 577,
"UpdateViewSortInput!"
]
}
],
"updateWebhook": [
- 641,
+ 643,
{
"input": [
- 577,
+ 579,
"UpdateWebhookInput!"
]
}
],
"updateWorkspace": [
- 648,
+ 650,
{
"data": [
- 580,
+ 582,
"UpdateWorkspaceInput!"
]
}
],
"updateWorkspaceAllowedIframeOrigins": [
- 648,
+ 650,
{
"data": [
- 579,
+ 581,
"UpdateWorkspaceAllowedIframeOriginsInput!"
]
}
],
"updateWorkspaceMemberRole": [
- 657,
+ 659,
{
"roleId": [
- 517,
+ 519,
"UUID!"
],
"workspaceMemberId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -9032,7 +9050,7 @@ export default {
4,
{
"input": [
- 581,
+ 583,
"UpdateWorkspaceMemberSettingsInput!"
]
}
@@ -9054,7 +9072,7 @@ export default {
70,
{
"file": [
- 582,
+ 584,
"Upload!"
],
"universalIdentifier": [
@@ -9070,7 +9088,7 @@ export default {
"String!"
],
"file": [
- 582,
+ 584,
"Upload!"
],
"fileFolder": [
@@ -9091,7 +9109,7 @@ export default {
"String!"
],
"file": [
- 582,
+ 584,
"Upload!"
]
}
@@ -9100,7 +9118,7 @@ export default {
277,
{
"file": [
- 582,
+ 584,
"Upload!"
],
"workspaceId": [
@@ -9113,7 +9131,7 @@ export default {
277,
{
"file": [
- 582,
+ 584,
"Upload!"
]
}
@@ -9122,7 +9140,7 @@ export default {
277,
{
"file": [
- 582,
+ 584,
"Upload!"
]
}
@@ -9131,16 +9149,16 @@ export default {
269,
{
"upsertFieldPermissionsInput": [
- 583,
+ 585,
"UpsertFieldPermissionsInput!"
]
}
],
"upsertFieldsWidget": [
- 625,
+ 627,
{
"input": [
- 586,
+ 588,
"UpsertFieldsWidgetInput!"
]
}
@@ -9149,7 +9167,7 @@ export default {
378,
{
"upsertObjectPermissionsInput": [
- 587,
+ 589,
"UpsertObjectPermissionsInput!"
]
}
@@ -9158,25 +9176,25 @@ export default {
444,
{
"upsertPermissionFlagsInput": [
- 588,
+ 590,
"UpsertPermissionFlagsInput!"
]
}
],
"upsertRowLevelPermissionPredicates": [
- 590,
+ 592,
{
"input": [
- 589,
+ 591,
"UpsertRowLevelPermissionPredicatesInput!"
]
}
],
"upsertViewWidget": [
- 625,
+ 627,
{
"input": [
- 591,
+ 593,
"UpsertViewWidgetInput!"
]
}
@@ -9185,13 +9203,13 @@ export default {
78,
{
"input": [
- 618,
+ 620,
"ValidateApprovedAccessDomainInput!"
]
}
],
"verifyEmailAndGetLoginToken": [
- 622,
+ 624,
{
"captchaToken": [
1
@@ -9236,7 +9254,7 @@ export default {
}
],
"verifyTwoFactorAuthenticationMethodForAuthenticatedUser": [
- 623,
+ 625,
{
"otp": [
1,
@@ -9261,10 +9279,10 @@ export default {
},
"NavigationMenuItem": {
"agentChatChannelId": [
- 517
+ 519
],
"applicationId": [
- 517
+ 519
],
"color": [
1
@@ -9273,13 +9291,13 @@ export default {
207
],
"folderId": [
- 517
+ 519
],
"icon": [
1
],
"id": [
- 517
+ 519
],
"link": [
1
@@ -9288,16 +9306,16 @@ export default {
1
],
"pageLayoutId": [
- 517
+ 519
],
"position": [
6
],
"targetObjectMetadataId": [
- 517
+ 519
],
"targetRecordId": [
- 517
+ 519
],
"targetRecordIdentifier": [
423
@@ -9309,10 +9327,10 @@ export default {
207
],
"userWorkspaceId": [
- 517
+ 519
],
"viewId": [
- 517
+ 519
],
"__typename": [
1
@@ -9321,7 +9339,7 @@ export default {
"NavigationMenuItemType": {},
"NotesConfiguration": {
"configurationType": [
- 643
+ 645
],
"__typename": [
1
@@ -9329,7 +9347,7 @@ export default {
},
"Object": {
"applicationId": [
- 517
+ 519
],
"color": [
1
@@ -9363,10 +9381,10 @@ export default {
1
],
"id": [
- 517
+ 519
],
"imageIdentifierFieldMetadataId": [
- 517
+ 519
],
"indexMetadataList": [
298
@@ -9409,7 +9427,7 @@ export default {
4
],
"labelIdentifierFieldMetadataId": [
- 517
+ 519
],
"labelPlural": [
1
@@ -9430,7 +9448,7 @@ export default {
355
],
"readabilityParentFieldUniversalIdentifiers": [
- 517
+ 519
],
"searchFieldMetadataList": [
462
@@ -9492,7 +9510,7 @@ export default {
374
],
"id": [
- 518
+ 520
],
"isActive": [
124
@@ -9519,7 +9537,7 @@ export default {
374
],
"universalIdentifier": [
- 518
+ 520
],
"__typename": [
1
@@ -9538,7 +9556,7 @@ export default {
},
"ObjectMetadataCommandMenuItemPayload": {
"objectMetadataItemId": [
- 517
+ 519
],
"__typename": [
1
@@ -9559,7 +9577,7 @@ export default {
4
],
"objectMetadataId": [
- 517
+ 519
],
"restrictedFields": [
309
@@ -9588,7 +9606,7 @@ export default {
4
],
"objectMetadataId": [
- 517
+ 519
],
"__typename": [
1
@@ -9698,19 +9716,19 @@ export default {
},
"PageLayout": {
"applicationId": [
- 517
+ 519
],
"createdAt": [
207
],
"defaultTabToFocusOnMobileAndSidePanelId": [
- 517
+ 519
],
"deletedAt": [
207
],
"id": [
- 517
+ 519
],
"isFirstTabPinned": [
4
@@ -9722,7 +9740,7 @@ export default {
1
],
"objectMetadataId": [
- 517
+ 519
],
"tabs": [
392
@@ -9731,7 +9749,7 @@ export default {
394
],
"universalIdentifier": [
- 517
+ 519
],
"updatedAt": [
207
@@ -9742,7 +9760,7 @@ export default {
},
"PageLayoutTab": {
"applicationId": [
- 517
+ 519
],
"createdAt": [
207
@@ -9754,7 +9772,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isActive": [
4
@@ -9769,7 +9787,7 @@ export default {
393
],
"pageLayoutId": [
- 517
+ 519
],
"position": [
6
@@ -9778,7 +9796,7 @@ export default {
1
],
"universalIdentifier": [
- 517
+ 519
],
"updatedAt": [
207
@@ -9794,7 +9812,7 @@ export default {
"PageLayoutType": {},
"PageLayoutWidget": {
"applicationId": [
- 517
+ 519
],
"conditionalAvailabilityExpression": [
1
@@ -9803,7 +9821,7 @@ export default {
309
],
"configuration": [
- 642
+ 644
],
"createdAt": [
207
@@ -9815,7 +9833,7 @@ export default {
291
],
"id": [
- 517
+ 519
],
"isActive": [
4
@@ -9827,10 +9845,10 @@ export default {
4
],
"objectMetadataId": [
- 517
+ 519
],
"pageLayoutTabId": [
- 517
+ 519
],
"position": [
398
@@ -9839,10 +9857,10 @@ export default {
1
],
"type": [
- 644
+ 646
],
"universalIdentifier": [
- 517
+ 519
],
"updatedAt": [
207
@@ -9918,7 +9936,7 @@ export default {
},
"PermissionFlag": {
"applicationId": [
- 517
+ 519
],
"createdAt": [
207
@@ -9930,7 +9948,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"key": [
1
@@ -9942,7 +9960,7 @@ export default {
1
],
"universalIdentifier": [
- 517
+ 519
],
"updatedAt": [
207
@@ -9954,7 +9972,7 @@ export default {
"PermissionFlagType": {},
"PieChartConfiguration": {
"aggregateFieldMetadataId": [
- 517
+ 519
],
"aggregateOperation": [
26
@@ -9963,7 +9981,7 @@ export default {
1
],
"configurationType": [
- 643
+ 645
],
"dateGranularity": [
384
@@ -9984,7 +10002,7 @@ export default {
10
],
"groupByFieldMetadataId": [
- 517
+ 519
],
"groupBySubFieldName": [
1
@@ -10042,7 +10060,7 @@ export default {
309
],
"objectMetadataId": [
- 517
+ 519
],
"__typename": [
1
@@ -10117,7 +10135,7 @@ export default {
},
"PublicApplicationRegistration": {
"id": [
- 517
+ 519
],
"logoUrl": [
1
@@ -10154,7 +10172,7 @@ export default {
},
"PublicDomain": {
"applicationId": [
- 517
+ 519
],
"createdAt": [
207
@@ -10163,7 +10181,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isValidated": [
4
@@ -10225,13 +10243,13 @@ export default {
1
],
"id": [
- 517
+ 519
],
"logo": [
1
],
"workspaceUrls": [
- 666
+ 668
],
"__typename": [
1
@@ -10242,7 +10260,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"logo": [
1
@@ -10268,7 +10286,7 @@ export default {
7
],
"channelId": [
- 517,
+ 519,
"UUID!"
],
"first": [
@@ -10289,7 +10307,7 @@ export default {
23,
{
"agentId": [
- 517,
+ 519,
"UUID!"
],
"limit": [
@@ -10357,7 +10375,7 @@ export default {
47,
{
"applicationId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -10366,7 +10384,7 @@ export default {
48,
{
"applicationId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -10393,7 +10411,7 @@ export default {
461,
{
"applicationId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -10419,10 +10437,10 @@ export default {
}
],
"callRecordingIdForCalendarEvent": [
- 517,
+ 519,
{
"calendarEventId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -10431,7 +10449,7 @@ export default {
20,
{
"threadId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -10440,7 +10458,7 @@ export default {
141,
{
"threadId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -10449,7 +10467,7 @@ export default {
16,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
@@ -10467,7 +10485,7 @@ export default {
}
],
"checkWorkspaceInviteHashIsValid": [
- 656,
+ 658,
{
"inviteHash": [
1,
@@ -10476,7 +10494,7 @@ export default {
}
],
"checkWorkspaceSubdomainAvailability": [
- 488,
+ 490,
{
"subdomain": [
1,
@@ -10488,7 +10506,7 @@ export default {
152,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
@@ -10497,16 +10515,16 @@ export default {
152
],
"currentUser": [
- 613
+ 615
],
"currentUserApplicationAuthorizations": [
45
],
"currentUserSessions": [
- 616
+ 618
],
"currentWorkspace": [
- 648
+ 650
],
"enterpriseCheckoutSession": [
1,
@@ -10540,7 +10558,7 @@ export default {
50,
{
"universalIdentifier": [
- 517,
+ 519,
"UUID!"
]
}
@@ -10549,7 +10567,7 @@ export default {
262,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
@@ -10693,10 +10711,10 @@ export default {
44,
{
"id": [
- 517
+ 519
],
"universalIdentifier": [
- 517
+ 519
]
}
],
@@ -10743,10 +10761,10 @@ export default {
}
],
"findWorkspaceAiStats": [
- 650
+ 652
],
"findWorkspaceFromInviteHash": [
- 648,
+ 650,
{
"inviteHash": [
1,
@@ -10755,13 +10773,13 @@ export default {
}
],
"findWorkspaceInvitations": [
- 655
+ 657
],
"frontComponent": [
282,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
@@ -10823,7 +10841,7 @@ export default {
158,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
@@ -10923,7 +10941,7 @@ export default {
419,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
@@ -10935,7 +10953,7 @@ export default {
443,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
@@ -10947,7 +10965,7 @@ export default {
279
],
"getToolIndex": [
- 499
+ 501
],
"getToolInputSchema": [
309,
@@ -10959,15 +10977,15 @@ export default {
}
],
"getUsageAnalytics": [
- 597,
+ 599,
{
"input": [
- 598
+ 600
]
}
],
"getView": [
- 625,
+ 627,
{
"id": [
1,
@@ -10976,7 +10994,7 @@ export default {
}
],
"getViewField": [
- 628,
+ 630,
{
"id": [
1,
@@ -10985,7 +11003,7 @@ export default {
}
],
"getViewFieldGroup": [
- 629,
+ 631,
{
"id": [
1,
@@ -10994,7 +11012,7 @@ export default {
}
],
"getViewFieldGroups": [
- 629,
+ 631,
{
"viewId": [
1,
@@ -11003,7 +11021,7 @@ export default {
}
],
"getViewFields": [
- 628,
+ 630,
{
"viewId": [
1,
@@ -11012,7 +11030,7 @@ export default {
}
],
"getViewFilter": [
- 630,
+ 632,
{
"id": [
1,
@@ -11021,7 +11039,7 @@ export default {
}
],
"getViewFilterGroup": [
- 631,
+ 633,
{
"id": [
1,
@@ -11030,7 +11048,7 @@ export default {
}
],
"getViewFilterGroups": [
- 631,
+ 633,
{
"viewId": [
1
@@ -11038,7 +11056,7 @@ export default {
}
],
"getViewFilters": [
- 630,
+ 632,
{
"viewId": [
1
@@ -11046,7 +11064,7 @@ export default {
}
],
"getViewGroup": [
- 634,
+ 636,
{
"id": [
1,
@@ -11055,7 +11073,7 @@ export default {
}
],
"getViewGroups": [
- 634,
+ 636,
{
"viewId": [
1
@@ -11063,7 +11081,7 @@ export default {
}
],
"getViewSort": [
- 637,
+ 639,
{
"id": [
1,
@@ -11072,7 +11090,7 @@ export default {
}
],
"getViewSorts": [
- 637,
+ 639,
{
"viewId": [
1
@@ -11080,19 +11098,19 @@ export default {
}
],
"getViews": [
- 625,
+ 627,
{
"objectMetadataId": [
1
],
"viewTypes": [
- 639,
+ 641,
"[ViewType!]"
]
}
],
"getWorkspaceCreationDefaults": [
- 653
+ 655
],
"githubClaimAuthorizationUrl": [
1,
@@ -11146,10 +11164,10 @@ export default {
361
],
"mostlyEmptyFieldMetadataIds": [
- 517,
+ 519,
{
"objectMetadataId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -11161,7 +11179,7 @@ export default {
125,
{
"connectedAccountId": [
- 517
+ 519
]
}
],
@@ -11172,7 +11190,7 @@ export default {
338,
{
"connectedAccountId": [
- 517
+ 519
]
}
],
@@ -11180,18 +11198,18 @@ export default {
345,
{
"messageChannelId": [
- 517
+ 519
]
}
],
"myUserApplicationVariables": [
- 658
+ 660
],
"navigationMenuItem": [
367,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
@@ -11203,7 +11221,7 @@ export default {
370,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
@@ -11288,52 +11306,52 @@ export default {
}
],
"skill": [
- 484,
+ 486,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
],
"skills": [
- 484
+ 486
],
"timelineActivityTypes": [
- 495
+ 497
],
"twoFactorAuthenticationRecoveryStatus": [
- 516,
+ 518,
{
"userId": [
- 517,
+ 519,
"UUID!"
]
}
],
"unsubscribeTopics": [
- 520
+ 522
],
"usageLimits": [
- 600
+ 602
],
"usageQuotaDefinitions": [
- 604
+ 606
],
"usageQuotaScopeConsumption": [
- 606,
+ 608,
{
"input": [
- 607,
+ 609,
"UsageQuotaScopeInput!"
]
}
],
"usageQuotasWithConsumption": [
- 608
+ 610
],
"validatePasswordResetToken": [
- 619,
+ 621,
{
"passwordResetToken": [
1,
@@ -11342,25 +11360,25 @@ export default {
}
],
"validationRules": [
- 620,
+ 622,
{
"objectMetadataId": [
- 517,
+ 519,
"UUID!"
]
}
],
"webhook": [
- 641,
+ 643,
{
"id": [
- 517,
+ 519,
"UUID!"
]
}
],
"webhooks": [
- 641
+ 643
],
"__typename": [
1
@@ -11368,7 +11386,7 @@ export default {
},
"RatioAggregateConfig": {
"fieldMetadataId": [
- 517
+ 519
],
"optionValue": [
1
@@ -11388,7 +11406,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"progress": [
10
@@ -11399,7 +11417,7 @@ export default {
},
"RecordIdentifier": {
"id": [
- 517
+ 519
],
"imageIdentifier": [
1
@@ -11430,13 +11448,13 @@ export default {
},
"RecordPermissionsResult": {
"objectMetadataId": [
- 517
+ 519
],
"permissions": [
424
],
"recordId": [
- 517
+ 519
],
"__typename": [
1
@@ -11445,10 +11463,10 @@ export default {
"RecordShareAccessLevel": {},
"RecordSharePrincipalInput": {
"roleId": [
- 517
+ 519
],
"workspaceMemberId": [
- 517
+ 519
],
"__typename": [
1
@@ -11493,10 +11511,10 @@ export default {
17
],
"principalId": [
- 517
+ 519
],
"principalRoleId": [
- 517
+ 519
],
"principalType": [
428
@@ -11517,7 +11535,7 @@ export default {
4
],
"id": [
- 517
+ 519
],
"label": [
1
@@ -11528,7 +11546,7 @@ export default {
},
"RecordTableConfiguration": {
"configurationType": [
- 643
+ 645
],
"isUIEditable": [
4
@@ -11545,10 +11563,10 @@ export default {
},
"RecordTargetInput": {
"objectMetadataId": [
- 517
+ 519
],
"recordId": [
- 517
+ 519
],
"__typename": [
1
@@ -11607,7 +11625,7 @@ export default {
},
"RevokeApiKeyInput": {
"id": [
- 517
+ 519
],
"__typename": [
1
@@ -11635,7 +11653,7 @@ export default {
37
],
"applicationId": [
- 517
+ 519
],
"canAccessAllAgentChatChannels": [
4
@@ -11677,7 +11695,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isEditable": [
4
@@ -11698,10 +11716,10 @@ export default {
446
],
"universalIdentifier": [
- 517
+ 519
],
"workspaceMembers": [
- 657
+ 659
],
"__typename": [
1
@@ -11712,10 +11730,10 @@ export default {
1
],
"id": [
- 517
+ 519
],
"roleId": [
- 517
+ 519
],
"__typename": [
1
@@ -11792,16 +11810,16 @@ export default {
},
"RowLevelPermissionPredicateGroupInput": {
"id": [
- 517
+ 519
],
"logicalOperator": [
449
],
"objectMetadataId": [
- 517
+ 519
],
"parentRowLevelPermissionPredicateGroupId": [
- 517
+ 519
],
"positionInRowLevelPermissionPredicateGroup": [
6
@@ -11813,10 +11831,10 @@ export default {
"RowLevelPermissionPredicateGroupLogicalOperator": {},
"RowLevelPermissionPredicateInput": {
"fieldMetadataId": [
- 517
+ 519
],
"id": [
- 517
+ 519
],
"operand": [
451
@@ -11825,7 +11843,7 @@ export default {
6
],
"rowLevelPermissionPredicateGroupId": [
- 517
+ 519
],
"subFieldName": [
1
@@ -11864,7 +11882,7 @@ export default {
309
],
"runAsWorkspaceMemberId": [
- 517
+ 519
],
"thread": [
457
@@ -11878,7 +11896,7 @@ export default {
},
"RunAgentMessageAttachmentInput": {
"fileId": [
- 517
+ 519
],
"filename": [
1
@@ -11916,7 +11934,7 @@ export default {
4
],
"threadId": [
- 517
+ 519
],
"__typename": [
1
@@ -11935,7 +11953,7 @@ export default {
},
"SSOConnection": {
"id": [
- 517
+ 519
],
"issuer": [
1
@@ -11955,7 +11973,7 @@ export default {
},
"SSOIdentityProvider": {
"id": [
- 517
+ 519
],
"issuer": [
1
@@ -11990,16 +12008,16 @@ export default {
207
],
"fieldMetadataId": [
- 517
+ 519
],
"id": [
- 517
+ 519
],
"position": [
6
],
"tsVectorFieldMetadataId": [
- 517
+ 519
],
"updatedAt": [
207
@@ -12008,9 +12026,37 @@ export default {
1
]
},
+ "SendAppChannelMessageInput": {
+ "idempotencyKey": [
+ 519
+ ],
+ "messageChannelId": [
+ 519
+ ],
+ "messageThreadId": [
+ 519
+ ],
+ "text": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "SendAppChannelMessageOutput": {
+ "messageId": [
+ 519
+ ],
+ "messageThreadId": [
+ 519
+ ],
+ "__typename": [
+ 1
+ ]
+ },
"SendChatMessageResult": {
"mentionedParticipantWorkspaceMemberIds": [
- 517
+ 519
],
"messageId": [
1
@@ -12053,7 +12099,7 @@ export default {
1
],
"files": [
- 464
+ 466
],
"fromHandle": [
1
@@ -12065,7 +12111,7 @@ export default {
1
],
"targetRecord": [
- 467
+ 469
],
"to": [
1
@@ -12093,7 +12139,7 @@ export default {
1
],
"recordId": [
- 517
+ 519
],
"__typename": [
1
@@ -12124,7 +12170,7 @@ export default {
309
],
"workspaceMemberIds": [
- 517
+ 519
],
"__typename": [
1
@@ -12132,7 +12178,7 @@ export default {
},
"SendInboxMessageResult": {
"threadId": [
- 517
+ 519
],
"__typename": [
1
@@ -12143,7 +12189,7 @@ export default {
1
],
"result": [
- 655
+ 657
],
"success": [
4
@@ -12230,31 +12276,31 @@ export default {
},
"SettingsMenuItem": {
"applicationId": [
- 517
+ 519
],
"createdAt": [
207
],
"frontComponentId": [
- 517
+ 519
],
"icon": [
1
],
"id": [
- 517
+ 519
],
"position": [
6
],
"scope": [
- 478
+ 480
],
"title": [
1
],
"universalIdentifier": [
- 517
+ 519
],
"updatedAt": [
207
@@ -12289,7 +12335,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"issuer": [
1
@@ -12306,7 +12352,7 @@ export default {
},
"SetupSso": {
"id": [
- 517
+ 519
],
"issuer": [
1
@@ -12329,7 +12375,7 @@ export default {
81
],
"workspace": [
- 667
+ 669
],
"__typename": [
1
@@ -12351,7 +12397,7 @@ export default {
},
"Skill": {
"applicationId": [
- 517
+ 519
],
"content": [
1
@@ -12366,7 +12412,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isActive": [
4
@@ -12395,7 +12441,7 @@ export default {
442
],
"configurationType": [
- 643
+ 645
],
"__typename": [
1
@@ -12403,7 +12449,7 @@ export default {
},
"StartWorkspaceSetupChatResult": {
"outcome": [
- 665
+ 667
],
"thread": [
16
@@ -12473,7 +12519,7 @@ export default {
13,
{
"threadId": [
- 517,
+ 519,
"UUID!"
]
}
@@ -12495,7 +12541,7 @@ export default {
"SubscriptionStatus": {},
"Support": {
"supportDriver": [
- 493
+ 495
],
"supportFrontChatId": [
1
@@ -12507,7 +12553,7 @@ export default {
"SupportDriver": {},
"TasksConfiguration": {
"configurationType": [
- 643
+ 645
],
"__typename": [
1
@@ -12518,22 +12564,22 @@ export default {
1
],
"applicationId": [
- 517
+ 519
],
"createdAt": [
207
],
"emit": [
- 496
+ 498
],
"frontComponentUniversalIdentifier": [
- 517
+ 519
],
"icon": [
1
],
"id": [
- 517
+ 519
],
"isActive": [
4
@@ -12545,13 +12591,13 @@ export default {
1
],
"objectUniversalIdentifier": [
- 517
+ 519
],
"replacesTimelineActivityTypeUniversalIdentifier": [
- 517
+ 519
],
"universalIdentifier": [
- 517
+ 519
],
"updatedAt": [
207
@@ -12562,13 +12608,13 @@ export default {
},
"TimelineActivityTypeEmit": {
"objectUniversalIdentifier": [
- 517
+ 519
],
"on": [
1
],
"through": [
- 497
+ 499
],
"__typename": [
1
@@ -12576,13 +12622,13 @@ export default {
},
"TimelineActivityTypeEmitThrough": {
"happensAtFieldUniversalIdentifier": [
- 517
+ 519
],
"relationFieldUniversalIdentifier": [
- 517
+ 519
],
"triggerFieldUniversalIdentifiers": [
- 517
+ 519
],
"__typename": [
1
@@ -12590,7 +12636,7 @@ export default {
},
"TimelineConfiguration": {
"configurationType": [
- 643
+ 645
],
"__typename": [
1
@@ -12638,7 +12684,7 @@ export default {
},
"TriggerAddPeopleToMessageListJobInput": {
"messageListId": [
- 517
+ 519
],
"personFilter": [
309
@@ -12746,7 +12792,7 @@ export default {
1
],
"twoFactorAuthenticationMethodId": [
- 517
+ 519
],
"__typename": [
1
@@ -12791,19 +12837,19 @@ export default {
"UUID": {},
"UUIDFilterComparison": {
"eq": [
- 517
+ 519
],
"gt": [
- 517
+ 519
],
"gte": [
- 517
+ 519
],
"iLike": [
- 517
+ 519
],
"in": [
- 517
+ 519
],
"is": [
4
@@ -12812,25 +12858,25 @@ export default {
4
],
"like": [
- 517
+ 519
],
"lt": [
- 517
+ 519
],
"lte": [
- 517
+ 519
],
"neq": [
- 517
+ 519
],
"notILike": [
- 517
+ 519
],
"notIn": [
- 517
+ 519
],
"notLike": [
- 517
+ 519
],
"__typename": [
1
@@ -12845,7 +12891,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"name": [
1
@@ -12854,7 +12900,7 @@ export default {
207
],
"visibility": [
- 521
+ 523
],
"__typename": [
1
@@ -12875,7 +12921,7 @@ export default {
6
],
"roleIds": [
- 517
+ 519
],
"__typename": [
1
@@ -12889,7 +12935,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"label": [
1
@@ -12910,7 +12956,7 @@ export default {
309
],
"roleId": [
- 517
+ 519
],
"triggers": [
309
@@ -12924,7 +12970,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"name": [
1
@@ -12941,11 +12987,14 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isSyncEnabled": [
4
],
+ "messagingProviderUniversalIdentifier": [
+ 519
+ ],
"visibility": [
344
],
@@ -12966,7 +13015,7 @@ export default {
1
],
"update": [
- 528
+ 530
],
"__typename": [
1
@@ -12991,7 +13040,7 @@ export default {
1
],
"update": [
- 530
+ 532
],
"__typename": [
1
@@ -13013,10 +13062,10 @@ export default {
},
"UpdateCalendarChannelInput": {
"id": [
- 517
+ 519
],
"update": [
- 532
+ 534
],
"__typename": [
1
@@ -13044,7 +13093,7 @@ export default {
},
"UpdateCommandMenuItemInput": {
"availabilityObjectMetadataId": [
- 517
+ 519
],
"availabilityType": [
153
@@ -13059,7 +13108,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isPinned": [
4
@@ -13068,7 +13117,7 @@ export default {
1
],
"pageLayoutId": [
- 517
+ 519
],
"position": [
6
@@ -13085,7 +13134,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"__typename": [
1
@@ -13138,7 +13187,7 @@ export default {
1
],
"objectMetadataId": [
- 517
+ 519
],
"options": [
309
@@ -13158,10 +13207,10 @@ export default {
},
"UpdateFrontComponentInput": {
"id": [
- 517
+ 519
],
"update": [
- 537
+ 539
],
"__typename": [
1
@@ -13191,10 +13240,10 @@ export default {
},
"UpdateLogicFunctionFromSourceInput": {
"id": [
- 517
+ 519
],
"update": [
- 540
+ 542
],
"__typename": [
1
@@ -13240,10 +13289,10 @@ export default {
},
"UpdateMessageChannelInput": {
"id": [
- 517
+ 519
],
"update": [
- 542
+ 544
],
"__typename": [
1
@@ -13277,10 +13326,10 @@ export default {
},
"UpdateMessageFolderInput": {
"id": [
- 517
+ 519
],
"update": [
- 544
+ 546
],
"__typename": [
1
@@ -13296,10 +13345,10 @@ export default {
},
"UpdateMessageFoldersInput": {
"ids": [
- 517
+ 519
],
"update": [
- 544
+ 546
],
"__typename": [
1
@@ -13310,7 +13359,7 @@ export default {
1
],
"folderId": [
- 517
+ 519
],
"icon": [
1
@@ -13322,7 +13371,7 @@ export default {
1
],
"pageLayoutId": [
- 517
+ 519
],
"position": [
6
@@ -13342,7 +13391,7 @@ export default {
1
],
"imageIdentifierFieldMetadataId": [
- 517
+ 519
],
"isActive": [
4
@@ -13354,7 +13403,7 @@ export default {
4
],
"labelIdentifierFieldMetadataId": [
- 517
+ 519
],
"labelPlural": [
1
@@ -13389,10 +13438,10 @@ export default {
},
"UpdateOneFieldMetadataInput": {
"id": [
- 517
+ 519
],
"update": [
- 535
+ 537
],
"__typename": [
1
@@ -13400,10 +13449,10 @@ export default {
},
"UpdateOneNavigationMenuItemInput": {
"id": [
- 517
+ 519
],
"update": [
- 546
+ 548
],
"__typename": [
1
@@ -13411,10 +13460,10 @@ export default {
},
"UpdateOneObjectInput": {
"id": [
- 517
+ 519
],
"update": [
- 547
+ 549
],
"__typename": [
1
@@ -13425,7 +13474,7 @@ export default {
1
],
"objectMetadataId": [
- 517
+ 519
],
"type": [
394
@@ -13456,7 +13505,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"layoutMode": [
393
@@ -13468,7 +13517,7 @@ export default {
1
],
"widgets": [
- 555
+ 557
],
"__typename": [
1
@@ -13488,10 +13537,10 @@ export default {
4
],
"objectMetadataId": [
- 517
+ 519
],
"pageLayoutTabId": [
- 517
+ 519
],
"position": [
309
@@ -13500,7 +13549,7 @@ export default {
1
],
"type": [
- 644
+ 646
],
"__typename": [
1
@@ -13517,13 +13566,13 @@ export default {
309
],
"id": [
- 517
+ 519
],
"objectMetadataId": [
- 517
+ 519
],
"pageLayoutTabId": [
- 517
+ 519
],
"position": [
309
@@ -13532,7 +13581,7 @@ export default {
1
],
"type": [
- 644
+ 646
],
"__typename": [
1
@@ -13546,10 +13595,10 @@ export default {
1
],
"objectMetadataId": [
- 517
+ 519
],
"tabs": [
- 553
+ 555
],
"type": [
394
@@ -13560,10 +13609,10 @@ export default {
},
"UpdateRoleInput": {
"id": [
- 517
+ 519
],
"update": [
- 558
+ 560
],
"__typename": [
1
@@ -13624,7 +13673,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isActive": [
4
@@ -13644,7 +13693,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isActive": [
4
@@ -13670,7 +13719,7 @@ export default {
1
],
"visibility": [
- 521
+ 523
],
"__typename": [
1
@@ -13678,7 +13727,7 @@ export default {
},
"UpdateUsageLimitInput": {
"id": [
- 517
+ 519
],
"payload": [
194
@@ -13689,10 +13738,10 @@ export default {
},
"UpdateValidationRuleInput": {
"id": [
- 517
+ 519
],
"update": [
- 564
+ 566
],
"__typename": [
1
@@ -13703,7 +13752,7 @@ export default {
1
],
"errorFieldMetadataId": [
- 517
+ 519
],
"expression": [
1
@@ -13726,10 +13775,10 @@ export default {
},
"UpdateViewFieldGroupInput": {
"id": [
- 517
+ 519
],
"update": [
- 566
+ 568
],
"__typename": [
1
@@ -13754,10 +13803,10 @@ export default {
},
"UpdateViewFieldInput": {
"id": [
- 517
+ 519
],
"update": [
- 568
+ 570
],
"__typename": [
1
@@ -13777,7 +13826,7 @@ export default {
6
],
"viewFieldGroupId": [
- 517
+ 519
],
"__typename": [
1
@@ -13785,19 +13834,19 @@ export default {
},
"UpdateViewFilterGroupInput": {
"id": [
- 517
+ 519
],
"logicalOperator": [
- 632
+ 634
],
"parentViewFilterGroupId": [
- 517
+ 519
],
"positionInViewFilterGroup": [
6
],
"viewId": [
- 517
+ 519
],
"__typename": [
1
@@ -13805,10 +13854,10 @@ export default {
},
"UpdateViewFilterInput": {
"id": [
- 517
+ 519
],
"update": [
- 571
+ 573
],
"__typename": [
1
@@ -13816,16 +13865,16 @@ export default {
},
"UpdateViewFilterInputUpdates": {
"fieldMetadataId": [
- 517
+ 519
],
"operand": [
- 633
+ 635
],
"positionInViewFilterGroup": [
6
],
"relationTargetFieldMetadataId": [
- 517
+ 519
],
"subFieldName": [
1
@@ -13834,7 +13883,7 @@ export default {
309
],
"viewFilterGroupId": [
- 517
+ 519
],
"__typename": [
1
@@ -13842,10 +13891,10 @@ export default {
},
"UpdateViewGroupInput": {
"id": [
- 517
+ 519
],
"update": [
- 573
+ 575
],
"__typename": [
1
@@ -13853,7 +13902,7 @@ export default {
},
"UpdateViewGroupInputUpdates": {
"fieldMetadataId": [
- 517
+ 519
],
"fieldValue": [
1
@@ -13873,13 +13922,13 @@ export default {
1
],
"calendarEndFieldMetadataId": [
- 517
+ 519
],
"calendarFieldMetadataId": [
- 517
+ 519
],
"calendarLayout": [
- 626
+ 628
],
"groupLoadLimit": [
10
@@ -13888,7 +13937,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isCompact": [
4
@@ -13897,19 +13946,19 @@ export default {
26
],
"kanbanAggregateOperationFieldMetadataId": [
- 517
+ 519
],
"kanbanColumnWidth": [
10
],
"mainGroupByFieldMetadataId": [
- 517
+ 519
],
"name": [
1
],
"openRecordIn": [
- 636
+ 638
],
"position": [
6
@@ -13918,10 +13967,10 @@ export default {
4
],
"type": [
- 639
+ 641
],
"visibility": [
- 640
+ 642
],
"__typename": [
1
@@ -13929,10 +13978,10 @@ export default {
},
"UpdateViewSortInput": {
"id": [
- 517
+ 519
],
"update": [
- 576
+ 578
],
"__typename": [
1
@@ -13940,7 +13989,7 @@ export default {
},
"UpdateViewSortInputUpdates": {
"direction": [
- 638
+ 640
],
"subFieldName": [
1
@@ -13951,10 +14000,10 @@ export default {
},
"UpdateWebhookInput": {
"id": [
- 517
+ 519
],
"update": [
- 578
+ 580
],
"__typename": [
1
@@ -14011,7 +14060,7 @@ export default {
1
],
"defaultRoleId": [
- 517
+ 519
],
"displayName": [
1
@@ -14071,7 +14120,7 @@ export default {
6
],
"workspaceDiscoverability": [
- 654
+ 656
],
"__typename": [
1
@@ -14082,7 +14131,7 @@ export default {
309
],
"workspaceMemberId": [
- 517
+ 519
],
"__typename": [
1
@@ -14094,7 +14143,7 @@ export default {
270
],
"roleId": [
- 517
+ 519
],
"__typename": [
1
@@ -14102,7 +14151,7 @@ export default {
},
"UpsertFieldsWidgetFieldInput": {
"fieldMetadataId": [
- 517
+ 519
],
"isVisible": [
4
@@ -14111,7 +14160,7 @@ export default {
6
],
"viewFieldId": [
- 517
+ 519
],
"__typename": [
1
@@ -14119,10 +14168,10 @@ export default {
},
"UpsertFieldsWidgetGroupInput": {
"fields": [
- 584
+ 586
],
"id": [
- 517
+ 519
],
"isVisible": [
4
@@ -14139,13 +14188,13 @@ export default {
},
"UpsertFieldsWidgetInput": {
"fields": [
- 584
+ 586
],
"groups": [
- 585
+ 587
],
"widgetId": [
- 517
+ 519
],
"__typename": [
1
@@ -14156,7 +14205,7 @@ export default {
379
],
"roleId": [
- 517
+ 519
],
"__typename": [
1
@@ -14167,7 +14216,7 @@ export default {
1
],
"roleId": [
- 517
+ 519
],
"__typename": [
1
@@ -14175,7 +14224,7 @@ export default {
},
"UpsertRowLevelPermissionPredicatesInput": {
"objectMetadataId": [
- 517
+ 519
],
"predicateGroups": [
448
@@ -14184,7 +14233,7 @@ export default {
450
],
"roleId": [
- 517
+ 519
],
"__typename": [
1
@@ -14203,22 +14252,22 @@ export default {
},
"UpsertViewWidgetInput": {
"view": [
- 595
+ 597
],
"viewFields": [
- 592
+ 594
],
"viewFilterGroups": [
- 593
+ 595
],
"viewFilters": [
- 594
+ 596
],
"viewSorts": [
- 596
+ 598
],
"widgetId": [
- 517
+ 519
],
"__typename": [
1
@@ -14229,7 +14278,7 @@ export default {
26
],
"fieldMetadataId": [
- 517
+ 519
],
"isVisible": [
4
@@ -14241,7 +14290,7 @@ export default {
6
],
"viewFieldId": [
- 517
+ 519
],
"__typename": [
1
@@ -14249,13 +14298,13 @@ export default {
},
"UpsertViewWidgetViewFilterGroupInput": {
"id": [
- 517
+ 519
],
"logicalOperator": [
- 632
+ 634
],
"parentViewFilterGroupId": [
- 517
+ 519
],
"positionInViewFilterGroup": [
6
@@ -14266,19 +14315,19 @@ export default {
},
"UpsertViewWidgetViewFilterInput": {
"fieldMetadataId": [
- 517
+ 519
],
"id": [
- 517
+ 519
],
"operand": [
- 633
+ 635
],
"positionInViewFilterGroup": [
6
],
"relationTargetFieldMetadataId": [
- 517
+ 519
],
"subFieldName": [
1
@@ -14287,7 +14336,7 @@ export default {
309
],
"viewFilterGroupId": [
- 517
+ 519
],
"__typename": [
1
@@ -14295,34 +14344,34 @@ export default {
},
"UpsertViewWidgetViewSettingsInput": {
"calendarEndFieldMetadataId": [
- 517
+ 519
],
"calendarFieldMetadataId": [
- 517
+ 519
],
"calendarLayout": [
- 626
+ 628
],
"kanbanAggregateOperation": [
26
],
"kanbanAggregateOperationFieldMetadataId": [
- 517
+ 519
],
"kanbanColumnWidth": [
10
],
"mainGroupByFieldMetadataId": [
- 517
+ 519
],
"openRecordIn": [
- 636
+ 638
],
"shouldHideEmptyGroups": [
4
],
"type": [
- 639
+ 641
],
"__typename": [
1
@@ -14330,13 +14379,13 @@ export default {
},
"UpsertViewWidgetViewSortInput": {
"direction": [
- 638
+ 640
],
"fieldMetadataId": [
- 517
+ 519
],
"id": [
- 517
+ 519
],
"__typename": [
1
@@ -14350,22 +14399,22 @@ export default {
207
],
"timeSeries": [
- 610
+ 612
],
"usageByApplication": [
- 599
+ 601
],
"usageByModel": [
- 599
+ 601
],
"usageByOperationType": [
- 599
+ 601
],
"usageByUser": [
- 599
+ 601
],
"userDailyUsage": [
- 612
+ 614
],
"__typename": [
1
@@ -14373,7 +14422,7 @@ export default {
},
"UsageAnalyticsInput": {
"operationTypes": [
- 602
+ 604
],
"periodEnd": [
207
@@ -14416,7 +14465,7 @@ export default {
207
],
"id": [
- 517
+ 519
],
"limitKind": [
1
@@ -14425,7 +14474,7 @@ export default {
96
],
"operationType": [
- 602
+ 604
],
"periodCount": [
10
@@ -14434,7 +14483,7 @@ export default {
1
],
"resourceType": [
- 609
+ 611
],
"spenderId": [
1
@@ -14443,7 +14492,7 @@ export default {
1
],
"unit": [
- 611
+ 613
],
"updatedAt": [
207
@@ -14454,10 +14503,10 @@ export default {
},
"UsageLimitOperationDefinition": {
"allowedUnits": [
- 611
+ 613
],
"operationType": [
- 602
+ 604
],
"__typename": [
1
@@ -14466,7 +14515,7 @@ export default {
"UsageOperationType": {},
"UsageQuotaDefinition": {
"allowedOperations": [
- 601
+ 603
],
"allowedSpenderTypes": [
1
@@ -14475,10 +14524,10 @@ export default {
1
],
"operatorOnlyScopes": [
- 605
+ 607
],
"resourceType": [
- 609
+ 611
],
"__typename": [
1
@@ -14486,7 +14535,7 @@ export default {
},
"UsageQuotaDefinitions": {
"definitions": [
- 603
+ 605
],
"hasAllowancePeriod": [
4
@@ -14500,7 +14549,7 @@ export default {
},
"UsageQuotaOperatorOnlyScope": {
"operationType": [
- 602
+ 604
],
"periodUnit": [
1
@@ -14509,7 +14558,7 @@ export default {
1
],
"unit": [
- 611
+ 613
],
"__typename": [
1
@@ -14531,13 +14580,13 @@ export default {
},
"UsageQuotaScopeInput": {
"operationType": [
- 602
+ 604
],
"periodUnit": [
1
],
"resourceType": [
- 609
+ 611
],
"spenderId": [
1
@@ -14546,7 +14595,7 @@ export default {
1
],
"unit": [
- 611
+ 613
],
"__typename": [
1
@@ -14557,7 +14606,7 @@ export default {
96
],
"id": [
- 517
+ 519
],
"isEnforced": [
4
@@ -14566,7 +14615,7 @@ export default {
96
],
"operationType": [
- 602
+ 604
],
"periodEnd": [
207
@@ -14581,7 +14630,7 @@ export default {
96
],
"resourceType": [
- 609
+ 611
],
"spenderId": [
1
@@ -14593,7 +14642,7 @@ export default {
1
],
"unit": [
- 611
+ 613
],
"__typename": [
1
@@ -14617,7 +14666,7 @@ export default {
"UsageUnit": {},
"UsageUserDaily": {
"dailyUsage": [
- 610
+ 612
],
"userWorkspaceId": [
1
@@ -14640,10 +14689,10 @@ export default {
207
],
"currentUserWorkspace": [
- 617
+ 619
],
"currentWorkspace": [
- 648
+ 650
],
"deletedAt": [
207
@@ -14664,7 +14713,7 @@ export default {
4
],
"id": [
- 517
+ 519
],
"isEmailVerified": [
4
@@ -14694,16 +14743,16 @@ export default {
310
],
"userWorkspaces": [
- 617
+ 619
],
"workspaceMember": [
- 657
+ 659
],
"workspaceMembers": [
- 657
+ 659
],
"workspaces": [
- 617
+ 619
],
"__typename": [
1
@@ -14753,7 +14802,7 @@ export default {
207
],
"id": [
- 517
+ 519
],
"ipAddress": [
1
@@ -14771,7 +14820,7 @@ export default {
1
],
"workspaceId": [
- 517
+ 519
],
"__typename": [
1
@@ -14785,7 +14834,7 @@ export default {
207
],
"id": [
- 517
+ 519
],
"isImpersonating": [
4
@@ -14803,16 +14852,16 @@ export default {
403
],
"twoFactorAuthenticationMethodSummary": [
- 513
+ 515
],
"updatedAt": [
207
],
"user": [
- 613
+ 615
],
"userId": [
- 517
+ 519
],
"__typename": [
1
@@ -14820,7 +14869,7 @@ export default {
},
"ValidateApprovedAccessDomainInput": {
"approvedAccessDomainId": [
- 517
+ 519
],
"validationToken": [
1
@@ -14837,7 +14886,7 @@ export default {
4
],
"id": [
- 517
+ 519
],
"__typename": [
1
@@ -14848,7 +14897,7 @@ export default {
1
],
"errorFieldMetadataId": [
- 517
+ 519
],
"expression": [
1
@@ -14857,7 +14906,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isActive": [
4
@@ -14869,7 +14918,7 @@ export default {
1
],
"objectMetadataId": [
- 517
+ 519
],
"__typename": [
1
@@ -14900,7 +14949,7 @@ export default {
81
],
"workspaceUrls": [
- 666
+ 668
],
"__typename": [
1
@@ -14930,22 +14979,22 @@ export default {
1
],
"applicationId": [
- 517
+ 519
],
"calendarEndFieldMetadataId": [
- 517
+ 519
],
"calendarFieldMetadataId": [
- 517
+ 519
],
"calendarLayout": [
- 626
+ 628
],
"createdAt": [
207
],
"createdByUserWorkspaceId": [
- 517
+ 519
],
"deletedAt": [
207
@@ -14957,7 +15006,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isActive": [
4
@@ -14975,25 +15024,25 @@ export default {
26
],
"kanbanAggregateOperationFieldMetadataId": [
- 517
+ 519
],
"kanbanColumnWidth": [
10
],
"key": [
- 635
+ 637
],
"mainGroupByFieldMetadataId": [
- 517
+ 519
],
"name": [
1
],
"objectMetadataId": [
- 517
+ 519
],
"openRecordIn": [
- 636
+ 638
],
"position": [
6
@@ -15002,37 +15051,37 @@ export default {
4
],
"type": [
- 639
+ 641
],
"universalIdentifier": [
- 517
+ 519
],
"updatedAt": [
207
],
"viewFieldGroups": [
- 629
+ 631
],
"viewFields": [
- 628
+ 630
],
"viewFilterGroups": [
- 631
+ 633
],
"viewFilters": [
- 630
+ 632
],
"viewGroups": [
- 634
+ 636
],
"viewSorts": [
- 637
+ 639
],
"visibility": [
- 640
+ 642
],
"workspaceId": [
- 517
+ 519
],
"__typename": [
1
@@ -15041,7 +15090,7 @@ export default {
"ViewCalendarLayout": {},
"ViewConfiguration": {
"configurationType": [
- 643
+ 645
],
"__typename": [
1
@@ -15052,7 +15101,7 @@ export default {
26
],
"applicationId": [
- 517
+ 519
],
"createdAt": [
207
@@ -15061,10 +15110,10 @@ export default {
207
],
"fieldMetadataId": [
- 517
+ 519
],
"id": [
- 517
+ 519
],
"isActive": [
4
@@ -15085,19 +15134,19 @@ export default {
6
],
"universalIdentifier": [
- 517
+ 519
],
"updatedAt": [
207
],
"viewFieldGroupId": [
- 517
+ 519
],
"viewId": [
- 517
+ 519
],
"workspaceId": [
- 517
+ 519
],
"__typename": [
1
@@ -15111,7 +15160,7 @@ export default {
207
],
"id": [
- 517
+ 519
],
"isActive": [
4
@@ -15132,13 +15181,13 @@ export default {
207
],
"viewFields": [
- 628
+ 630
],
"viewId": [
- 517
+ 519
],
"workspaceId": [
- 517
+ 519
],
"__typename": [
1
@@ -15152,19 +15201,19 @@ export default {
207
],
"fieldMetadataId": [
- 517
+ 519
],
"id": [
- 517
+ 519
],
"operand": [
- 633
+ 635
],
"positionInViewFilterGroup": [
6
],
"relationTargetFieldMetadataId": [
- 517
+ 519
],
"subFieldName": [
1
@@ -15176,13 +15225,13 @@ export default {
309
],
"viewFilterGroupId": [
- 517
+ 519
],
"viewId": [
- 517
+ 519
],
"workspaceId": [
- 517
+ 519
],
"__typename": [
1
@@ -15196,13 +15245,13 @@ export default {
207
],
"id": [
- 517
+ 519
],
"logicalOperator": [
- 632
+ 634
],
"parentViewFilterGroupId": [
- 517
+ 519
],
"positionInViewFilterGroup": [
6
@@ -15211,10 +15260,10 @@ export default {
207
],
"viewId": [
- 517
+ 519
],
"workspaceId": [
- 517
+ 519
],
"__typename": [
1
@@ -15233,7 +15282,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"isVisible": [
4
@@ -15245,10 +15294,10 @@ export default {
207
],
"viewId": [
- 517
+ 519
],
"workspaceId": [
- 517
+ 519
],
"__typename": [
1
@@ -15264,13 +15313,13 @@ export default {
207
],
"direction": [
- 638
+ 640
],
"fieldMetadataId": [
- 517
+ 519
],
"id": [
- 517
+ 519
],
"subFieldName": [
1
@@ -15279,10 +15328,10 @@ export default {
207
],
"viewId": [
- 517
+ 519
],
"workspaceId": [
- 517
+ 519
],
"__typename": [
1
@@ -15293,7 +15342,7 @@ export default {
"ViewVisibility": {},
"Webhook": {
"applicationId": [
- 517
+ 519
],
"createdAt": [
207
@@ -15305,7 +15354,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"operations": [
1
@@ -15391,25 +15440,25 @@ export default {
434
],
"on_StandaloneRichTextConfiguration": [
- 485
+ 487
],
"on_TasksConfiguration": [
- 494
+ 496
],
"on_TimelineConfiguration": [
- 498
+ 500
],
"on_ViewConfiguration": [
- 627
+ 629
],
"on_WorkflowConfiguration": [
- 645
+ 647
],
"on_WorkflowRunConfiguration": [
- 646
+ 648
],
"on_WorkflowVersionConfiguration": [
- 647
+ 649
],
"__typename": [
1
@@ -15419,7 +15468,7 @@ export default {
"WidgetType": {},
"WorkflowConfiguration": {
"configurationType": [
- 643
+ 645
],
"__typename": [
1
@@ -15427,7 +15476,7 @@ export default {
},
"WorkflowRunConfiguration": {
"configurationType": [
- 643
+ 645
],
"__typename": [
1
@@ -15435,7 +15484,7 @@ export default {
},
"WorkflowVersionConfiguration": {
"configurationType": [
- 643
+ 645
],
"__typename": [
1
@@ -15443,7 +15492,7 @@ export default {
},
"Workspace": {
"activationStatus": [
- 649
+ 651
],
"aiAdditionalInstructions": [
1
@@ -15512,7 +15561,7 @@ export default {
4
],
"id": [
- 517
+ 519
],
"installedApplications": [
44
@@ -15566,7 +15615,7 @@ export default {
1
],
"logoFileId": [
- 517
+ 519
],
"metadataVersion": [
6
@@ -15581,22 +15630,22 @@ export default {
207
],
"viewFields": [
- 628
+ 630
],
"viewFilterGroups": [
- 631
+ 633
],
"viewFilters": [
- 630
+ 632
],
"viewGroups": [
- 634
+ 636
],
"viewSorts": [
- 637
+ 639
],
"views": [
- 625
+ 627
],
"workspaceCustomApplication": [
44
@@ -15605,13 +15654,13 @@ export default {
1
],
"workspaceDiscoverability": [
- 654
+ 656
],
"workspaceMembersCount": [
6
],
"workspaceUrls": [
- 666
+ 668
],
"__typename": [
1
@@ -15641,13 +15690,13 @@ export default {
4
],
"outcome": [
- 651
+ 653
],
"personEnrichment": [
309
],
"personOutcome": [
- 664
+ 666
],
"__typename": [
1
@@ -15673,10 +15722,10 @@ export default {
207
],
"id": [
- 517
+ 519
],
"roleId": [
- 517
+ 519
],
"__typename": [
1
@@ -15701,10 +15750,10 @@ export default {
1
],
"dateFormat": [
- 659
+ 661
],
"id": [
- 517
+ 519
],
"locale": [
1
@@ -15713,7 +15762,7 @@ export default {
285
],
"numberFormat": [
- 660
+ 662
],
"openRecordIn": [
389
@@ -15722,7 +15771,7 @@ export default {
443
],
"timeFormat": [
- 661
+ 663
],
"timeZone": [
1
@@ -15734,10 +15783,10 @@ export default {
1
],
"userId": [
- 517
+ 519
],
"userWorkspaceId": [
- 517
+ 519
],
"__typename": [
1
@@ -15745,13 +15794,13 @@ export default {
},
"WorkspaceMemberApplicationVariables": {
"userWorkspaceId": [
- 517
+ 519
],
"variables": [
- 614
+ 616
],
"workspaceMemberId": [
- 517
+ 519
],
"__typename": [
1
@@ -15776,7 +15825,7 @@ export default {
1
],
"id": [
- 517
+ 519
],
"__typename": [
1
@@ -15797,10 +15846,10 @@ export default {
},
"WorkspaceUrlsAndId": {
"id": [
- 517
+ 519
],
"workspaceUrls": [
- 666
+ 668
],
"__typename": [
1
diff --git a/packages/twenty-docs/developers/extend/apps/getting-started/concepts.mdx b/packages/twenty-docs/developers/extend/apps/getting-started/concepts.mdx
index f1507c0377d..0f702dc79c5 100644
--- a/packages/twenty-docs/developers/extend/apps/getting-started/concepts.mdx
+++ b/packages/twenty-docs/developers/extend/apps/getting-started/concepts.mdx
@@ -49,7 +49,8 @@ your-app/
| **Skill** | Reusable AI agent instructions | [Skills & Agents](/developers/extend/apps/logic/skills-and-agents) |
| **Agent** | AI assistants with custom prompts | [Skills & Agents](/developers/extend/apps/logic/skills-and-agents) |
| **Workflow** | Ready-made workflows with a trigger and steps | [Workflows](/developers/extend/apps/logic/workflows) |
-| **Connection Provider** | OAuth credentials for third-party APIs | [Connections](/developers/extend/apps/logic/connections) |
+| **Connection Provider** | OAuth or custom sign-in for third-party accounts | [Connections](/developers/extend/apps/logic/connections) |
+| **Messaging Provider** | Sends replies from an app's message channels through a connection | [Messaging Channels](/developers/extend/apps/logic/messaging-channels#sending-replies) |
| **View** | Pre-configured record list views | [Views](/developers/extend/apps/layout/views) |
| **Navigation Menu Item** | Custom sidebar entries | [Navigation Menu Items](/developers/extend/apps/layout/navigation-menu-items) |
| **Page Layout** | Tabs and widgets on a record's detail page | [Page Layouts](/developers/extend/apps/layout/page-layouts) |
@@ -100,7 +101,7 @@ your-app/
</Card>
<Card href="/developers/extend/apps/logic/overview" img="/images/documentation/section-overview-icons-v1/apps-logic.svg">
<CardTitle>Logic</CardTitle>
- Logic functions, skills, agents, and OAuth connections.
+ Logic functions, skills, agents, connections, and messaging channels.
</Card>
<Card href="/developers/extend/apps/layout/overview" img="/images/user-guide/halftone/layout-window-v1.svg">
<CardTitle>Layout</CardTitle>
diff --git a/packages/twenty-docs/developers/extend/apps/getting-started/quick-start.mdx b/packages/twenty-docs/developers/extend/apps/getting-started/quick-start.mdx
index 6e8d4f612a5..718edae9c7b 100644
--- a/packages/twenty-docs/developers/extend/apps/getting-started/quick-start.mdx
+++ b/packages/twenty-docs/developers/extend/apps/getting-started/quick-start.mdx
@@ -99,7 +99,7 @@ Each skill installs with its own reference docs. The `agent-skills` branch becom
</Card>
<Card href="/developers/extend/apps/logic/overview" img="/images/documentation/section-overview-icons-v1/apps-logic.svg">
<CardTitle>Logic</CardTitle>
- Logic functions, skills, agents, and OAuth connections.
+ Logic functions, skills, agents, connections, and messaging channels.
</Card>
<Card href="/developers/extend/apps/layout/overview" img="/images/user-guide/halftone/layout-window-v1.svg">
<CardTitle>Layout</CardTitle>
diff --git a/packages/twenty-docs/developers/extend/apps/logic/connections.mdx b/packages/twenty-docs/developers/extend/apps/logic/connections.mdx
index 1f820286fb0..66f6f798f57 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/connections.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/connections.mdx
@@ -9,7 +9,7 @@ import { PageBanner } from "/snippets/page-banner.mdx"
Connections are credentials a user holds for an external service (Linear, GitHub, Slack, ...). Your app declares **how** those credentials are obtained — a **connection provider** — and consumes them at runtime to make authenticated calls to the third-party API.
-Today only OAuth 2.0 is supported. Future credential types (personal access tokens, API keys, basic auth) will plug into the same surface — apps already using `defineConnectionProvider({ type: 'oauth', ... })` won't need to migrate.
+OAuth 2.0 is built in. Services with their own connection flow — a hosted login page, an account id delivered by webhook — use a `custom` provider, where your app drives the flow and Twenty keeps the user, the workspace and the saved connection. Future credential types (personal access tokens, API keys, basic auth) will plug into the same surface — apps already using `defineConnectionProvider({ type: 'oauth', ... })` won't need to migrate.
<AccordionGroup>
@@ -96,7 +96,7 @@ Key points:
- `clientIdVariable` / `clientSecretVariable` are **names**, not values — they must match keys declared in `defineApplication.serverVariables`. The actual `client_id` and `client_secret` are entered by the server admin through the app registration UI, never committed to your repo.
- Use `serverVariables` (not `applicationVariables`) — OAuth credentials are server-wide and one OAuth app per Twenty server.
- Until both `serverVariables` are filled in, the app's General tab shows a "needs server admin" hint and the "Add connection" button is disabled.
-- `type: 'oauth'` is the only supported value today. The discriminator is forward-compatible: future types (`'pat'`, `'api-key'`, ...) will add new sub-config blocks alongside `oauth`.
+- `type` is `'oauth'` (with an `oauth` block) or `'custom'` (with a `custom` block, see "Custom connection flows"). The discriminator is forward-compatible: future types (`'pat'`, `'api-key'`, ...) will add new sub-config blocks alongside these.
The OAuth callback URL your provider needs to whitelist is:
@@ -106,6 +106,139 @@ https://<your-twenty-server>/auth/apps/callback
</Accordion>
+<Accordion title="Custom connection flows" description="Connect services that are not OAuth providers">
+
+Some services connect accounts through their own flow rather than OAuth: Unipile, Plaid or Merge send the user to a hosted page and then report the connected account to a URL you gave them, sometimes from their servers rather than the browser. Declare these with `type: 'custom'` and two logic functions:
+
+```ts src/connection-providers/linkedin-connection.ts
+import { defineConnectionProvider } from 'twenty-sdk/define';
+
+export default defineConnectionProvider({
+ universalIdentifier: '5b0e6f3a-2c4d-4e8f-9a1b-7c6d5e4f3a2b',
+ name: 'linkedin',
+ displayName: 'LinkedIn',
+ type: 'custom',
+ scope: 'USER',
+ custom: {
+ authorizeLogicFunction: {
+ universalIdentifier: 'c4a1e2b3-6d5f-4a7b-8c9d-0e1f2a3b4c5d',
+ },
+ callbackLogicFunction: {
+ universalIdentifier: 'd5b2f3c4-7e6a-4b8c-9d0e-1f2a3b4c5d6e',
+ },
+ },
+ onConnectLogicFunction: {
+ universalIdentifier: 'e6c3a4d5-8f7b-4c9d-0e1f-2a3b4c5d6e7f',
+ },
+});
+```
+
+**Add connection** and **Reconnect** work as for OAuth. Twenty checks the member may connect, signs a short-lived state for the attempt, and runs `authorizeLogicFunction` with a `callbackUrl` that carries it. Return where to send the user:
+
+```ts src/logic-functions/handlers/linkedin-authorize-handler.ts
+import { type AuthorizeConnectionPayload } from 'twenty-sdk/logic-function';
+
+export const linkedinAuthorizeHandler = async ({
+ callbackUrl,
+}: AuthorizeConnectionPayload) => {
+ const response = await fetch(
+ `${process.env.UNIPILE_DSN}/api/v1/hosted/accounts/link`,
+ {
+ method: 'POST',
+ headers: {
+ 'X-API-KEY': process.env.UNIPILE_API_KEY ?? '',
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ type: 'create',
+ providers: ['LINKEDIN'],
+ api_url: process.env.UNIPILE_DSN,
+ expiresOn: new Date(Date.now() + 10 * 60 * 1000).toISOString(),
+ // The browser comes back here, and the account id is posted here.
+ success_redirect_url: callbackUrl,
+ failure_redirect_url: callbackUrl,
+ notify_url: callbackUrl,
+ }),
+ },
+ );
+
+ const { url } = await response.json();
+
+ return { authorizationUrl: url };
+};
+```
+
+Hand `callbackUrl` to the service unchanged. Twenty accepts it as a browser redirect (`GET`) and as a server notification (`POST`), and runs `callbackLogicFunction` for each request with its method, query parameters (without `state`), headers, parsed body and `rawBody` (the exact request bytes, `null` on `GET`). Return the account the request proves, or `null` when it carries none — typically the browser coming back while the account id travels by notification:
+
+```ts src/logic-functions/handlers/linkedin-callback-handler.ts
+import { type ConnectionCallbackPayload } from 'twenty-sdk/logic-function';
+
+export const linkedinCallbackHandler = async ({
+ httpMethod,
+ body,
+}: ConnectionCallbackPayload) => {
+ if (httpMethod !== 'POST') {
+ return null;
+ }
+
+ const { account_id: accountId } = body as { account_id: string };
+
+ // Never trust the payload alone: confirm the account with the service.
+ const account = await fetchUnipileAccount(accountId);
+
+ return { externalAccountId: account.id, handle: account.name };
+};
+```
+
+The signed state in `callbackUrl` only proves the request carries that URL, not that the service sent it. When the service signs its notifications, verify the signature over `rawBody` before trusting the body. Headers are lowercased, and `cookie`, `authorization` and `proxy-authorization` are never passed on:
+
+```ts src/logic-functions/handlers/hosted-callback-handler.ts
+import { createHmac, timingSafeEqual } from 'node:crypto';
+
+import { type ConnectionCallbackPayload } from 'twenty-sdk/logic-function';
+
+export const hostedCallbackHandler = async ({
+ httpMethod,
+ headers,
+ rawBody,
+}: ConnectionCallbackPayload) => {
+ if (httpMethod !== 'POST' || rawBody === null) {
+ return null;
+ }
+
+ const expected = createHmac('sha256', process.env.WEBHOOK_SECRET ?? '')
+ .update(rawBody)
+ .digest();
+ const received = Buffer.from(headers['x-signature'] ?? '', 'hex');
+
+ if (received.length !== expected.length || !timingSafeEqual(received, expected)) {
+ throw new Error('Invalid notification signature');
+ }
+
+ const { account_id: accountId } = JSON.parse(rawBody) as { account_id: string };
+
+ return { externalAccountId: accountId };
+};
+```
+
+The callback returns:
+
+| Field | Description |
+| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
+| `externalAccountId` | The service's id for the account. A later callback for the same id and member updates that connection instead of adding a second one. |
+| `handle` | Optional label shown for the connection. Defaults to the member's email. |
+| `accessToken` | Optional per-account token, stored encrypted and returned by `getConnection`. Leave it out when your app calls the service with its own key. |
+
+Both functions run while the member waits on a redirect, so their timeout is capped at 10 seconds. A failure or an invalid return aborts the connection: nothing is saved and `onConnectLogicFunction` does not run. `onConnectLogicFunction` runs when a connection is created, reconnected or restored, not again when the service reports an account that is already connected. The state expires after an hour, so a notification arriving later is refused. Services commonly retry notifications: a repeat for an account already connected updates that connection, so returning the same account again is safe.
+
+Twenty does not refresh or revoke custom connections. Release what the service holds for the account in `onDisconnectLogicFunction`.
+
+A provider's `type`, like its `scope`, cannot change once it is synced: to move a service between `oauth` and `custom`, declare a new provider with a new `universalIdentifier`.
+
+Custom providers ship with Twenty 2.52.0.
+
+</Accordion>
+
<Accordion title="Identify the connected account" description="Stop a reconnect from silently switching upstream accounts">
When a user clicks **Reconnect**, nothing stops them from authorizing a different upstream account than the one the connection was made with: Slack workspace B instead of workspace A, another GitHub organization, another Google account. Without a way to tell the two apart, Twenty would overwrite A's tokens with B's and everything your app built on that connection would quietly start talking to B.
@@ -327,7 +460,8 @@ Each connection has:
| `scopes` | OAuth permissions granted by the upstream provider (distinct from `scope` — those are unrelated) |
| `userWorkspaceId` | The owner's userWorkspace id — useful for picking "the request user's connection" in HTTP-route triggers |
| `workspaceMemberId` | The owner's workspace member id, or `null` if they've since left the workspace |
-| `accessToken` | Fresh OAuth access token (refreshed automatically if expired) |
+| `providerType` | `'oauth'` or `'custom'`, the type of the connection provider. Check it to narrow `accessToken` |
+| `accessToken` | Fresh OAuth access token (refreshed automatically if expired), always set when `providerType` is `'oauth'`. For `'custom'`, `null` unless the callback returned one |
| `name` | The connection's display name (auto-derived at OAuth callback, user-renameable) |
| `handle` | The connected upstream account's label, refreshed on each reconnect: the `handle` returned by the identify function when there is one, otherwise the email from the OIDC `id_token` returned at token exchange, falling back to the connecting Twenty user's email |
| `externalAccountId` | Stable id of the upstream account returned by the identify function, or `null` when the provider declares none or the connection predates it. Not unique: use it to deduplicate connections yourself |
diff --git a/packages/twenty-docs/developers/extend/apps/logic/messaging-channels.mdx b/packages/twenty-docs/developers/extend/apps/logic/messaging-channels.mdx
index 07d25303ccb..74aff1eaa0a 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/messaging-channels.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/messaging-channels.mdx
@@ -188,6 +188,71 @@ There is no way to *clear* an identity yet: a null is treated as "leave it alone
Participants you leave unlinked are still stored and still render in the thread — they simply do not pull the conversation onto a record.
+## Sending replies
+
+A messaging provider declares how an app sends on a channel. It names the connection provider whose accounts it speaks through and the logic function that delivers a reply, so one connection (a Unipile account, say) can back several kinds of messaging, each with its own handler:
+
+```ts src/messaging-providers/linkedin-messaging.ts
+import { defineMessagingProvider } from 'twenty-sdk/define';
+
+export default defineMessagingProvider({
+ universalIdentifier: '8a9b0c1d-2e3f-4a5b-8c6d-7e8f9a0b1c2d',
+ name: 'linkedin-messaging',
+ displayName: 'LinkedIn Messages',
+ connectionProvider: {
+ universalIdentifier: '5b0e6f3a-2c4d-4e8f-9a1b-7c6d5e4f3a2b',
+ },
+ sendMessageLogicFunction: {
+ universalIdentifier: 'f7d4b5e6-9a8c-4d0e-1f2a-3b4c5d6e7f80',
+ },
+});
+```
+
+Bind a channel to it when you create the channel, or later with `updateMessageChannel` (passing `null` unbinds it):
+
+```ts
+await createMessageChannel({
+ connectedAccountId: connection.id,
+ handle: profile.memberUrn,
+ visibility: 'METADATA',
+ messagingProvider: {
+ universalIdentifier: '8a9b0c1d-2e3f-4a5b-8c6d-7e8f9a0b1c2d',
+ },
+});
+```
+
+The messaging provider must belong to your app and use the connection provider of the channel's account; its connection provider cannot change after the first sync. Changing the send function in a later version applies to every channel bound to the provider.
+
+Replies are sent with the `sendAppChannelMessage` mutation, which takes the channel, the thread, the text and an `idempotencyKey` (a UUID the client generates per reply and reuses when retrying it), and runs the provider's function:
+
+```ts src/logic-functions/handlers/linkedin-send-message-handler.ts
+import { type SendAppMessagePayload } from 'twenty-sdk/logic-function';
+
+export const linkedinSendMessageHandler = async ({
+ connectedAccountId,
+ threadExternalId,
+ text,
+ idempotencyKey,
+}: SendAppMessagePayload) => {
+ const sent = await sendLinkedinMessage({
+ connectedAccountId,
+ conversationUrn: threadExternalId,
+ text,
+ idempotencyKey,
+ });
+
+ return { externalId: sent.messageUrn, sentAt: sent.createdAt };
+};
+```
+
+The payload carries the `messagingProviderName`, the conversation's `threadExternalId` as you ingested it, the `text`, the `idempotencyKey`, and the `recipients`: the participants of the thread's latest message other than the channel's own handle, so someone who only took part in an earlier exchange is not messaged. Prefer the provider's own conversation over `recipients` when its API sends to a conversation id. Return the provider's id for the sent message as `externalId`.
+
+Twenty then records the reply in the thread as an outgoing message from the channel, with the same recipients, so it shows immediately. When your webhook later delivers the same message, ingesting it with that `externalId` changes nothing.
+
+The function runs inside the `sendAppChannelMessage` request. If it throws or returns no `externalId`, the mutation fails and nothing is recorded.
+
+Once your function returns, Twenty keeps the delivery for 24 hours under the member, the channel, the thread and the `idempotencyKey`. If recording the reply then fails, the mutation fails, and retrying it with the same key records the delivered reply without calling your function again; a retry of a reply already recorded returns it. A retry while the first call is still sending waits for it. A new key is a new reply. Your function can still be called twice for one reply if the client retries with a new key or after those 24 hours, or if your function itself fails after the provider accepted the message, so forward `idempotencyKey` to the provider when its API supports idempotent sends. A channel with `isSyncEnabled: false` refuses replies without calling your function. A channel with no messaging provider, or whose provider has no `sendMessageLogicFunction` or no longer exists, cannot send; its conversations stay as they are. Requires `"engines": { "twenty": ">=2.52.0" }`.
+
## Listing and updating channels
```ts
@@ -241,7 +306,7 @@ Deleting a channel deletes the messages ingested through it, and any thread left
## 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 start conversations.** Replies go to an existing thread through a [messaging provider](#sending-replies); a first message to someone new has to be started from your app.
- **It only resolves contacts through a declared field.** Without one, Twenty cannot tell who a LinkedIn URN belongs to, so app channels [link participants explicitly at ingestion](#resolve-the-person-yourself).
- **It does not create contacts.** Twenty's auto-creation derives people and companies from email domains, which is meaningless for most providers, so it is off for app channels. Create the Person yourself, then pass its `personId`.
diff --git a/packages/twenty-docs/developers/extend/apps/logic/overview.mdx b/packages/twenty-docs/developers/extend/apps/logic/overview.mdx
index fb280820261..cc261c05770 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/overview.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/overview.mdx
@@ -8,7 +8,7 @@ import { CardTitle } from "/snippets/card-title.mdx"
## What the logic layer covers
-A Twenty app's **logic layer** is the code that *runs* — server-side TypeScript handlers reacting to HTTP requests, cron schedules, and record changes; AI skills and agents that live inside the workspace; and OAuth connections that let your functions act on a user's behalf in third-party services.
+A Twenty app's **logic layer** is the code that *runs* — server-side TypeScript handlers reacting to HTTP requests, cron schedules, and record changes; AI skills and agents that live inside the workspace; connections (OAuth or a custom sign-in flow) that let your functions act on a user's behalf in third-party services; and messaging channels that bring an external inbox into Twenty.
```text
┌─ HTTP route ──┐
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index a7db9d1ccee..be855885823 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -320,6 +320,7 @@ export enum AllMetadataName {
frontComponent = 'frontComponent',
index = 'index',
logicFunction = 'logicFunction',
+ messagingProvider = 'messagingProvider',
navigationMenuItem = 'navigationMenuItem',
objectMetadata = 'objectMetadata',
objectPermission = 'objectPermission',
@@ -391,7 +392,7 @@ export type ApiKeyToken = {
export type AppConnection = {
__typename?: 'AppConnection';
- accessToken: Scalars['String']['output'];
+ accessToken?: Maybe<Scalars['String']['output']>;
authFailedAt?: Maybe<Scalars['String']['output']>;
authFailedReason?: Maybe<Scalars['String']['output']>;
externalAccountId?: Maybe<Scalars['String']['output']>;
@@ -399,6 +400,7 @@ export type AppConnection = {
id: Scalars['ID']['output'];
name: Scalars['String']['output'];
providerName: Scalars['String']['output'];
+ providerType: Scalars['String']['output'];
scope: ConnectedAccountScope;
scopes: Array<Scalars['String']['output']>;
userWorkspaceId: Scalars['String']['output'];
@@ -1557,6 +1559,7 @@ export type CreateAppMessageChannelInput = {
connectedAccountId: Scalars['UUID']['input'];
displayName?: InputMaybe<Scalars['String']['input']>;
handle: Scalars['String']['input'];
+ messagingProviderUniversalIdentifier?: InputMaybe<Scalars['UUID']['input']>;
participantHandleFieldUniversalIdentifier?: InputMaybe<Scalars['UUID']['input']>;
visibility: MessageChannelVisibility;
};
@@ -3112,6 +3115,7 @@ export type MessageChannel = {
isContactAutoCreationEnabled: Scalars['Boolean']['output'];
isSyncEnabled: Scalars['Boolean']['output'];
messageFolderImportPolicy: MessageFolderImportPolicy;
+ messagingProviderUniversalIdentifier?: Maybe<Scalars['UUID']['output']>;
participantHandleFieldUniversalIdentifier?: Maybe<Scalars['UUID']['output']>;
pendingGroupEmailsAction: MessageChannelPendingGroupEmailsAction;
syncStage: MessageChannelSyncStage;
@@ -3512,6 +3516,7 @@ export type Mutation = {
runAgent: RunAgentResult;
runApplicationHealthCheck?: Maybe<ApplicationHealthCheckResult>;
saveImapSmtpCaldavAccount: ImapSmtpCaldavConnectionSuccess;
+ sendAppChannelMessage: SendAppChannelMessageOutput;
sendChatMessage: SendChatMessageResult;
sendEmail: SendEmailOutput;
sendInboxMessage: SendInboxMessageResult;
@@ -4501,6 +4506,11 @@ export type MutationSaveImapSmtpCaldavAccountArgs = {
};
+export type MutationSendAppChannelMessageArgs = {
+ input: SendAppChannelMessageInput;
+};
+
+
export type MutationSendChatMessageArgs = {
browsingContext?: InputMaybe<Scalars['JSON']['input']>;
channelId?: InputMaybe<Scalars['UUID']['input']>;
@@ -6637,6 +6647,19 @@ export type SearchField = {
updatedAt: Scalars['DateTime']['output'];
};
+export type SendAppChannelMessageInput = {
+ idempotencyKey: Scalars['UUID']['input'];
+ messageChannelId: Scalars['UUID']['input'];
+ messageThreadId: Scalars['UUID']['input'];
+ text: Scalars['String']['input'];
+};
+
+export type SendAppChannelMessageOutput = {
+ __typename?: 'SendAppChannelMessageOutput';
+ messageId: Scalars['UUID']['output'];
+ messageThreadId: Scalars['UUID']['output'];
+};
+
export type SendChatMessageResult = {
__typename?: 'SendChatMessageResult';
mentionedParticipantWorkspaceMemberIds?: Maybe<Array<Scalars['UUID']['output']>>;
@@ -7111,6 +7134,7 @@ export type UpdateAppMessageChannelInput = {
displayName?: InputMaybe<Scalars['String']['input']>;
id: Scalars['UUID']['input'];
isSyncEnabled?: InputMaybe<Scalars['Boolean']['input']>;
+ messagingProviderUniversalIdentifier?: InputMaybe<Scalars['UUID']['input']>;
visibility?: InputMaybe<MessageChannelVisibility>;
};
diff --git a/packages/twenty-front/src/modules/metadata-error-handler/hooks/useMetadataErrorHandler.ts b/packages/twenty-front/src/modules/metadata-error-handler/hooks/useMetadataErrorHandler.ts
index 16797a9c079..ca84b117978 100644
--- a/packages/twenty-front/src/modules/metadata-error-handler/hooks/useMetadataErrorHandler.ts
+++ b/packages/twenty-front/src/modules/metadata-error-handler/hooks/useMetadataErrorHandler.ts
@@ -52,6 +52,7 @@ export const useMetadataErrorHandler = () => {
viewSort: t`view sort`,
applicationVariable: t`application variable`,
connectionProvider: t`connection provider`,
+ messagingProvider: t`messaging provider`,
searchFieldMetadata: t`search field metadata`,
timelineActivityType: t`timeline activity type`,
settingsMenuItem: t`settings menu item`,
diff --git a/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationConnectionsSection.tsx b/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationConnectionsSection.tsx
index 503ad37fd42..5f870ed30d2 100644
--- a/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationConnectionsSection.tsx
+++ b/packages/twenty-front/src/pages/settings/applications/tabs/SettingsApplicationConnectionsSection.tsx
@@ -56,6 +56,7 @@ export const SettingsApplicationConnectionsSection = ({
const isOAuth = provider.type === 'oauth';
const isClientCredentialsConfigured =
provider.oauth?.isClientCredentialsConfigured ?? false;
+ const canStartAuthorization = !isOAuth || isClientCredentialsConfigured;
const canAddConnection = provider.scope === 'WORKSPACE';
const providerConnections = connectedAccounts.filter(
@@ -159,7 +160,7 @@ export const SettingsApplicationConnectionsSection = ({
</StyledTableRowsContainer>
</Table>
)}
- {canAddConnection && isClientCredentialsConfigured && (
+ {canAddConnection && canStartAuthorization && (
<StyledFooter>
<Button
startIcon={<IconPlus />}
diff --git a/packages/twenty-front/src/pages/settings/applications/tabs/__tests__/SettingsApplicationConnectionsSection.test.tsx b/packages/twenty-front/src/pages/settings/applications/tabs/__tests__/SettingsApplicationConnectionsSection.test.tsx
index 3c0f3cb3a8f..a4414effbbc 100644
--- a/packages/twenty-front/src/pages/settings/applications/tabs/__tests__/SettingsApplicationConnectionsSection.test.tsx
+++ b/packages/twenty-front/src/pages/settings/applications/tabs/__tests__/SettingsApplicationConnectionsSection.test.tsx
@@ -158,6 +158,48 @@ describe('SettingsApplicationConnectionsSection', () => {
});
});
+ it('adds a connection to a custom provider without OAuth credentials', async () => {
+ mockedUseFindApplicationConnectionProviders.mockReturnValue({
+ connectionProviders: [
+ {
+ id: 'provider-1',
+ applicationId: 'app-1',
+ type: 'custom',
+ name: 'linkedin',
+ displayName: 'LinkedIn',
+ scope: 'WORKSPACE',
+ logoUrl: null,
+ oauth: null,
+ },
+ ],
+ loading: false,
+ refetch: jest.fn(),
+ });
+
+ mockedUseApplicationConnectedAccounts.mockReturnValue({
+ accounts: [],
+ loading: false,
+ refetch: jest.fn(),
+ });
+
+ render(
+ <I18nProvider i18n={i18n}>
+ <MemoryRouter>
+ <SettingsApplicationConnectionsSection applicationId="app-1" />
+ </MemoryRouter>
+ </I18nProvider>,
+ );
+
+ await userEvent.click(
+ screen.getByRole('button', { name: /Add connection/i }),
+ );
+
+ expect(mockTriggerAppOAuth).toHaveBeenCalledWith({
+ applicationId: 'app-1',
+ providerName: 'linkedin',
+ });
+ });
+
it('hides a provider scoped to each member when the caller sees none of its connections', () => {
mockedUseFindApplicationConnectionProviders.mockReturnValue({
connectionProviders: [
diff --git a/packages/twenty-sdk/src/sdk/define/common/constants/provider-name-pattern.constant.ts b/packages/twenty-sdk/src/sdk/define/common/constants/provider-name-pattern.constant.ts
new file mode 100644
index 00000000000..0fb19b2afda
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/define/common/constants/provider-name-pattern.constant.ts
@@ -0,0 +1 @@
+export const PROVIDER_NAME_PATTERN = /^[a-z][a-z0-9-]*$/;
diff --git a/packages/twenty-sdk/src/sdk/define/common/types/define-entity.type.ts b/packages/twenty-sdk/src/sdk/define/common/types/define-entity.type.ts
index f0ed971cbfd..ff285222ce3 100644
--- a/packages/twenty-sdk/src/sdk/define/common/types/define-entity.type.ts
+++ b/packages/twenty-sdk/src/sdk/define/common/types/define-entity.type.ts
@@ -18,6 +18,7 @@ import {
type AgentManifest,
type ConnectionProviderManifest,
type FieldManifest,
+ type MessagingProviderManifest,
type NavigationMenuItemManifest,
type SkillManifest,
type StandalonePageLayoutWidgetManifest,
@@ -44,6 +45,7 @@ export type DefinableEntity =
| UninstallLogicFunctionConfig
| AgentManifest
| ConnectionProviderManifest
+ | MessagingProviderManifest
| RoleConfig
| SkillManifest
| ViewConfig
diff --git a/packages/twenty-sdk/src/sdk/define/connection-providers/__tests__/define-connection-provider.spec.ts b/packages/twenty-sdk/src/sdk/define/connection-providers/__tests__/define-connection-provider.spec.ts
index 83fea8f0627..6607235272a 100644
--- a/packages/twenty-sdk/src/sdk/define/connection-providers/__tests__/define-connection-provider.spec.ts
+++ b/packages/twenty-sdk/src/sdk/define/connection-providers/__tests__/define-connection-provider.spec.ts
@@ -131,4 +131,75 @@ describe('defineConnectionProvider', () => {
).toBe(true);
},
);
+
+ describe('custom type', () => {
+ const baseCustomConfig = {
+ universalIdentifier: '99fcd8e8-fbb1-4d2c-bc16-7c61ef3ebbbb',
+ name: 'linkedin',
+ displayName: 'LinkedIn',
+ type: 'custom' as const,
+ custom: {
+ authorizeLogicFunction: {
+ universalIdentifier: 'b648f87b-1d26-4961-b974-0908fd991061',
+ },
+ callbackLogicFunction: {
+ universalIdentifier: 'b648f87b-1d26-4961-b974-0908fd991062',
+ },
+ },
+ };
+
+ it('returns success for a valid config', () => {
+ const result = defineConnectionProvider(baseCustomConfig);
+
+ expect(result.success).toBe(true);
+ expect(result.errors).toEqual([]);
+ });
+
+ it('reports a missing custom config block', () => {
+ const result = defineConnectionProvider({
+ ...baseCustomConfig,
+ custom: undefined as never,
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.errors).toContain(
+ "Connection provider with type 'custom' must declare a `custom` config block",
+ );
+ });
+
+ it.each(['authorizeLogicFunction', 'callbackLogicFunction'] as const)(
+ 'reports a missing custom.%s',
+ (logicFunctionKey) => {
+ const result = defineConnectionProvider({
+ ...baseCustomConfig,
+ custom: {
+ ...baseCustomConfig.custom,
+ [logicFunctionKey]: undefined as never,
+ },
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.errors).toContain(
+ `Custom connection provider must declare custom.${logicFunctionKey}`,
+ );
+ },
+ );
+
+ it('rejects a non-UUID logic function reference', () => {
+ const result = defineConnectionProvider({
+ ...baseCustomConfig,
+ custom: {
+ ...baseCustomConfig.custom,
+ callbackLogicFunction: { universalIdentifier: 'linkedin-callback' },
+ },
+ });
+
+ expect(result.success).toBe(false);
+ expect(
+ result.errors.some((error) =>
+ error.includes('custom.callbackLogicFunction.universalIdentifier'),
+ ),
+ ).toBe(true);
+ });
+ });
});
diff --git a/packages/twenty-sdk/src/sdk/define/connection-providers/define-connection-provider.ts b/packages/twenty-sdk/src/sdk/define/connection-providers/define-connection-provider.ts
index 89cb30fc37a..b42ffff9007 100644
--- a/packages/twenty-sdk/src/sdk/define/connection-providers/define-connection-provider.ts
+++ b/packages/twenty-sdk/src/sdk/define/connection-providers/define-connection-provider.ts
@@ -1,14 +1,15 @@
import { type DefineEntity } from '@/sdk/define/common/types/define-entity.type';
+import { PROVIDER_NAME_PATTERN } from '@/sdk/define/common/constants/provider-name-pattern.constant';
import { createValidationResult } from '@/sdk/define/common/utils/create-validation-result';
import { isValidPostgresUuid } from '@/sdk/define/common/utils/is-valid-postgres-uuid';
import {
CONNECTION_PROVIDER_SCOPES,
type ConnectionProviderManifest,
+ type CustomConnectionProviderConfig,
} from 'twenty-shared/application';
import { isDefined } from 'twenty-shared/utils';
-const PROVIDER_NAME_PATTERN = /^[a-z][a-z0-9-]*$/;
-const SUPPORTED_TYPES = ['oauth'] as const;
+const SUPPORTED_TYPES = ['oauth', 'custom'] as const;
type ConnectionProviderLogicFunctionKey = Extract<
keyof ConnectionProviderManifest,
@@ -21,6 +22,49 @@ const LOGIC_FUNCTION_KEYS = [
'onDisconnectLogicFunction',
] as const satisfies readonly ConnectionProviderLogicFunctionKey[];
+const CUSTOM_LOGIC_FUNCTION_KEYS = [
+ 'authorizeLogicFunction',
+ 'callbackLogicFunction',
+] as const;
+
+const getInvalidLogicFunctionReferenceError = ({
+ path,
+ universalIdentifier,
+}: {
+ path: string;
+ universalIdentifier: string;
+}): string | null =>
+ isValidPostgresUuid(universalIdentifier)
+ ? null
+ : `Connection provider ${path}.universalIdentifier "${universalIdentifier}" must be the UUID universalIdentifier of a logic function in this app.`;
+
+const getCustomConfigErrors = (
+ custom: CustomConnectionProviderConfig | undefined,
+): string[] => {
+ if (!isDefined(custom)) {
+ return [
+ "Connection provider with type 'custom' must declare a `custom` config block",
+ ];
+ }
+
+ return CUSTOM_LOGIC_FUNCTION_KEYS.flatMap((logicFunctionKey) => {
+ const logicFunction = custom[logicFunctionKey];
+
+ if (!isDefined(logicFunction)) {
+ return [
+ `Custom connection provider must declare custom.${logicFunctionKey}`,
+ ];
+ }
+
+ const referenceError = getInvalidLogicFunctionReferenceError({
+ path: `custom.${logicFunctionKey}`,
+ universalIdentifier: logicFunction.universalIdentifier,
+ });
+
+ return isDefined(referenceError) ? [referenceError] : [];
+ });
+};
+
export const defineConnectionProvider: DefineEntity<
ConnectionProviderManifest
> = (config) => {
@@ -48,14 +92,15 @@ export const defineConnectionProvider: DefineEntity<
for (const logicFunctionKey of LOGIC_FUNCTION_KEYS) {
const logicFunction = config[logicFunctionKey];
+ const referenceError = isDefined(logicFunction)
+ ? getInvalidLogicFunctionReferenceError({
+ path: logicFunctionKey,
+ universalIdentifier: logicFunction.universalIdentifier,
+ })
+ : null;
- if (
- isDefined(logicFunction) &&
- !isValidPostgresUuid(logicFunction.universalIdentifier)
- ) {
- errors.push(
- `Connection provider ${logicFunctionKey}.universalIdentifier "${logicFunction.universalIdentifier}" must be the UUID universalIdentifier of a logic function in this app.`,
- );
+ if (isDefined(referenceError)) {
+ errors.push(referenceError);
}
}
@@ -108,5 +153,9 @@ export const defineConnectionProvider: DefineEntity<
}
}
+ if (config.type === 'custom') {
+ errors.push(...getCustomConfigErrors(config.custom));
+ }
+
return createValidationResult({ config, errors });
};
diff --git a/packages/twenty-sdk/src/sdk/define/index.ts b/packages/twenty-sdk/src/sdk/define/index.ts
index 19ddf7908fe..06ef1f33adb 100644
--- a/packages/twenty-sdk/src/sdk/define/index.ts
+++ b/packages/twenty-sdk/src/sdk/define/index.ts
@@ -143,6 +143,7 @@ export type { InputJsonSchema } from 'twenty-shared/logic-function';
export { defineConnectionProvider } from '@/sdk/define/connection-providers/define-connection-provider';
export type { ConnectionProviderScope } from 'twenty-shared/application';
+export { defineMessagingProvider } from '@/sdk/define/messaging-providers/define-messaging-provider';
export { defineNavigationMenuItem } from '@/sdk/define/navigation-menu-items/define-navigation-menu-item';
diff --git a/packages/twenty-sdk/src/sdk/define/messaging-providers/__tests__/define-messaging-provider.spec.ts b/packages/twenty-sdk/src/sdk/define/messaging-providers/__tests__/define-messaging-provider.spec.ts
new file mode 100644
index 00000000000..ce6a57788bd
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/define/messaging-providers/__tests__/define-messaging-provider.spec.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from 'vitest';
+
+import { defineMessagingProvider } from '@/sdk/define';
+
+const baseValidConfig = {
+ universalIdentifier: '6b1f0a52-4d8e-4c4e-9b0a-2f5d8a7c1e01',
+ name: 'linkedin-messaging',
+ displayName: 'LinkedIn Messages',
+ connectionProvider: {
+ universalIdentifier: '6b1f0a52-4d8e-4c4e-9b0a-2f5d8a7c1e02',
+ },
+ sendMessageLogicFunction: {
+ universalIdentifier: '6b1f0a52-4d8e-4c4e-9b0a-2f5d8a7c1e03',
+ },
+};
+
+describe('defineMessagingProvider', () => {
+ it('returns success for a valid config', () => {
+ const result = defineMessagingProvider(baseValidConfig);
+
+ expect(result.success).toBe(true);
+ expect(result.errors).toEqual([]);
+ });
+
+ it('accepts a provider that only ingests', () => {
+ const { sendMessageLogicFunction: _, ...ingestOnlyConfig } =
+ baseValidConfig;
+
+ expect(defineMessagingProvider(ingestOnlyConfig).success).toBe(true);
+ });
+
+ it('rejects a name that is not a slug', () => {
+ const result = defineMessagingProvider({
+ ...baseValidConfig,
+ name: 'LinkedIn Messaging',
+ });
+
+ expect(result.success).toBe(false);
+ });
+
+ it('rejects references that are not UUIDs', () => {
+ const result = defineMessagingProvider({
+ ...baseValidConfig,
+ connectionProvider: { universalIdentifier: 'unipile' },
+ sendMessageLogicFunction: { universalIdentifier: 'send-message' },
+ });
+
+ expect(result.errors).toHaveLength(2);
+ });
+});
diff --git a/packages/twenty-sdk/src/sdk/define/messaging-providers/define-messaging-provider.ts b/packages/twenty-sdk/src/sdk/define/messaging-providers/define-messaging-provider.ts
new file mode 100644
index 00000000000..eb9f884fef4
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/define/messaging-providers/define-messaging-provider.ts
@@ -0,0 +1,55 @@
+import { type DefineEntity } from '@/sdk/define/common/types/define-entity.type';
+import { PROVIDER_NAME_PATTERN } from '@/sdk/define/common/constants/provider-name-pattern.constant';
+import { createValidationResult } from '@/sdk/define/common/utils/create-validation-result';
+import { isValidPostgresUuid } from '@/sdk/define/common/utils/is-valid-postgres-uuid';
+import { type MessagingProviderManifest } from 'twenty-shared/application';
+import { isDefined, isNonEmptyString } from 'twenty-shared/utils';
+
+export const defineMessagingProvider: DefineEntity<
+ MessagingProviderManifest
+> = (config) => {
+ const errors: string[] = [];
+
+ if (!isNonEmptyString(config.universalIdentifier)) {
+ errors.push('Messaging provider must have a universalIdentifier');
+ } else if (!isValidPostgresUuid(config.universalIdentifier)) {
+ errors.push(
+ `Messaging provider universalIdentifier "${config.universalIdentifier}" must be a UUID. Generate one with \`uuidgen\` or any UUID v4 tool.`,
+ );
+ }
+
+ if (!isNonEmptyString(config.name)) {
+ errors.push('Messaging provider must have a name');
+ } else if (!PROVIDER_NAME_PATTERN.test(config.name)) {
+ errors.push(
+ `Messaging provider name "${config.name}" must match ${PROVIDER_NAME_PATTERN}`,
+ );
+ }
+
+ if (!isNonEmptyString(config.displayName)) {
+ errors.push('Messaging provider must have a displayName');
+ }
+
+ if (!isDefined(config.connectionProvider)) {
+ errors.push(
+ 'Messaging provider must declare the connectionProvider it uses',
+ );
+ } else if (
+ !isValidPostgresUuid(config.connectionProvider.universalIdentifier)
+ ) {
+ errors.push(
+ `Messaging provider connectionProvider.universalIdentifier "${config.connectionProvider.universalIdentifier}" must be the UUID universalIdentifier of a connection provider in this app.`,
+ );
+ }
+
+ if (
+ isDefined(config.sendMessageLogicFunction) &&
+ !isValidPostgresUuid(config.sendMessageLogicFunction.universalIdentifier)
+ ) {
+ errors.push(
+ `Messaging provider sendMessageLogicFunction.universalIdentifier "${config.sendMessageLogicFunction.universalIdentifier}" must be the UUID universalIdentifier of a logic function in this app.`,
+ );
+ }
+
+ return createValidationResult({ config, errors });
+};
diff --git a/packages/twenty-sdk/src/sdk/logic-function/connections/__tests__/find-connection-for-request.spec.ts b/packages/twenty-sdk/src/sdk/logic-function/connections/__tests__/find-connection-for-request.spec.ts
index 0f99ff03476..25832d2c92d 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/connections/__tests__/find-connection-for-request.spec.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/connections/__tests__/find-connection-for-request.spec.ts
@@ -5,7 +5,9 @@ import { type AppConnection } from '@/sdk/logic-function/connections/types/app-c
import { withLegacyConnectionVisibility } from '@/sdk/logic-function/connections/utils/with-legacy-connection-visibility.util';
const buildConnection = (
- overrides: Partial<Omit<AppConnection, 'visibility'>> = {},
+ overrides: Partial<
+ Omit<AppConnection, 'visibility' | 'providerType' | 'accessToken'>
+ > = {},
): AppConnection =>
withLegacyConnectionVisibility({
id: 'c-1',
@@ -16,6 +18,7 @@ const buildConnection = (
scope: 'USER',
userWorkspaceId: 'uws-me',
workspaceMemberId: 'wm-me',
+ providerType: 'oauth',
accessToken: 'token-fresh',
scopes: ['read'],
authFailedAt: null,
diff --git a/packages/twenty-sdk/src/sdk/logic-function/connections/__tests__/get-connection.spec.ts b/packages/twenty-sdk/src/sdk/logic-function/connections/__tests__/get-connection.spec.ts
index 5bde416c1ce..4435c9991a1 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/connections/__tests__/get-connection.spec.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/connections/__tests__/get-connection.spec.ts
@@ -3,6 +3,7 @@ import {
beforeEach,
describe,
expect,
+ expectTypeOf,
it,
vi,
type MockInstance,
@@ -11,10 +12,13 @@ import {
import { AppConnectionAuthFailedError } from '@/sdk/logic-function/connections/errors/app-connection-auth-failed.error';
import { getConnection } from '@/sdk/logic-function/connections/get-connection';
import { type AppConnection } from '@/sdk/logic-function/connections/types/app-connection.type';
+import { type AppConnectionWithoutVisibility } from '@/sdk/logic-function/connections/utils/with-legacy-connection-visibility.util';
const buildConnection = (
- overrides: Partial<Omit<AppConnection, 'visibility'>> = {},
-): Omit<AppConnection, 'visibility'> => ({
+ overrides: Partial<
+ Omit<AppConnection, 'visibility' | 'providerType' | 'accessToken'>
+ > = {},
+): AppConnectionWithoutVisibility => ({
id: 'c-1',
providerName: 'linear',
name: 'Linear #1',
@@ -23,6 +27,7 @@ const buildConnection = (
scope: 'USER',
userWorkspaceId: 'uws-me',
workspaceMemberId: 'wm-me',
+ providerType: 'oauth',
accessToken: 'fresh',
scopes: ['read'],
authFailedAt: null,
@@ -45,6 +50,36 @@ describe('getConnection', () => {
fetchSpy.mockRestore();
});
+ it('narrows the token by provider type', async () => {
+ fetchSpy.mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ data: {
+ appConnection: {
+ ...buildConnection(),
+ providerType: 'custom',
+ accessToken: null,
+ },
+ },
+ }),
+ { status: 200 },
+ ),
+ );
+
+ const connection = await getConnection('c-1');
+
+ if (connection.providerType === 'oauth') {
+ expectTypeOf(connection.accessToken).toEqualTypeOf<string>();
+ } else {
+ expectTypeOf(connection.accessToken).toEqualTypeOf<string | null>();
+ }
+
+ expect(connection).toMatchObject({
+ providerType: 'custom',
+ accessToken: null,
+ });
+ });
+
it('queries appConnection by id over GraphQL and derives the deprecated visibility', async () => {
const connection = buildConnection({ id: 'persisted' });
diff --git a/packages/twenty-sdk/src/sdk/logic-function/connections/__tests__/list-connections.spec.ts b/packages/twenty-sdk/src/sdk/logic-function/connections/__tests__/list-connections.spec.ts
index 3b35c250614..e4108dbf097 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/connections/__tests__/list-connections.spec.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/connections/__tests__/list-connections.spec.ts
@@ -9,9 +9,9 @@ import {
} from 'vitest';
import { listConnections } from '@/sdk/logic-function/connections/list-connections';
-import { type AppConnection } from '@/sdk/logic-function/connections/types/app-connection.type';
+import { type AppConnectionWithoutVisibility } from '@/sdk/logic-function/connections/utils/with-legacy-connection-visibility.util';
-const sharedConnection: Omit<AppConnection, 'visibility'> = {
+const sharedConnection: AppConnectionWithoutVisibility = {
id: 'shared',
providerName: 'linear',
name: 'Linear #1',
@@ -20,6 +20,7 @@ const sharedConnection: Omit<AppConnection, 'visibility'> = {
scope: 'WORKSPACE',
userWorkspaceId: 'uws-me',
workspaceMemberId: 'wm-me',
+ providerType: 'oauth',
accessToken: 'fresh',
scopes: ['read'],
authFailedAt: null,
diff --git a/packages/twenty-sdk/src/sdk/logic-function/connections/get-connection.ts b/packages/twenty-sdk/src/sdk/logic-function/connections/get-connection.ts
index a4f2fc80824..8902d1e4662 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/connections/get-connection.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/connections/get-connection.ts
@@ -1,6 +1,9 @@
import { AppConnectionAuthFailedError } from '@/sdk/logic-function/connections/errors/app-connection-auth-failed.error';
import { type AppConnection } from '@/sdk/logic-function/connections/types/app-connection.type';
-import { withLegacyConnectionVisibility } from '@/sdk/logic-function/connections/utils/with-legacy-connection-visibility.util';
+import {
+ type AppConnectionWithoutVisibility,
+ withLegacyConnectionVisibility,
+} from '@/sdk/logic-function/connections/utils/with-legacy-connection-visibility.util';
import { postGraphqlRequest } from '@/sdk/logic-function/utils/post-graphql-request.util';
const GET_APP_CONNECTION_QUERY = `
@@ -14,6 +17,7 @@ const GET_APP_CONNECTION_QUERY = `
scope
userWorkspaceId
workspaceMemberId
+ providerType
accessToken
scopes
authFailedAt
@@ -25,7 +29,7 @@ const GET_APP_CONNECTION_QUERY = `
export const getConnection = async (id: string): Promise<AppConnection> => {
const { appConnection } = await postGraphqlRequest<
{ id: string },
- { appConnection: Omit<AppConnection, 'visibility'> }
+ { appConnection: AppConnectionWithoutVisibility }
>({
query: GET_APP_CONNECTION_QUERY,
variables: { id },
diff --git a/packages/twenty-sdk/src/sdk/logic-function/connections/list-connections.ts b/packages/twenty-sdk/src/sdk/logic-function/connections/list-connections.ts
index ab3e9e7e93f..3dff09f9a58 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/connections/list-connections.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/connections/list-connections.ts
@@ -2,7 +2,10 @@ import { CONNECTION_SCOPE_BY_LEGACY_VISIBILITY } from 'twenty-shared/application
import { isDefined } from 'twenty-shared/utils';
import { type AppConnection } from '@/sdk/logic-function/connections/types/app-connection.type';
-import { withLegacyConnectionVisibility } from '@/sdk/logic-function/connections/utils/with-legacy-connection-visibility.util';
+import {
+ type AppConnectionWithoutVisibility,
+ withLegacyConnectionVisibility,
+} from '@/sdk/logic-function/connections/utils/with-legacy-connection-visibility.util';
import { postGraphqlRequest } from '@/sdk/logic-function/utils/post-graphql-request.util';
const LIST_APP_CONNECTIONS_QUERY = `
@@ -16,6 +19,7 @@ const LIST_APP_CONNECTIONS_QUERY = `
scope
userWorkspaceId
workspaceMemberId
+ providerType
accessToken
scopes
authFailedAt
@@ -38,7 +42,7 @@ export const listConnections = async ({
}: ListConnectionsFilter = {}): Promise<AppConnection[]> => {
const { appConnections } = await postGraphqlRequest<
{ filter: Omit<ListConnectionsFilter, 'visibility'> },
- { appConnections: Omit<AppConnection, 'visibility'>[] }
+ { appConnections: AppConnectionWithoutVisibility[] }
>({
query: LIST_APP_CONNECTIONS_QUERY,
variables: {
diff --git a/packages/twenty-sdk/src/sdk/logic-function/connections/utils/with-legacy-connection-visibility.util.ts b/packages/twenty-sdk/src/sdk/logic-function/connections/utils/with-legacy-connection-visibility.util.ts
index 205b87e5a85..9d5bfab06ab 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/connections/utils/with-legacy-connection-visibility.util.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/connections/utils/with-legacy-connection-visibility.util.ts
@@ -2,8 +2,14 @@ import { LEGACY_CONNECTION_VISIBILITY_BY_SCOPE } from 'twenty-shared/application
import { type AppConnection } from '@/sdk/logic-function/connections/types/app-connection.type';
+type WithoutVisibility<TConnection> = TConnection extends unknown
+ ? Omit<TConnection, 'visibility'>
+ : never;
+
+export type AppConnectionWithoutVisibility = WithoutVisibility<AppConnection>;
+
export const withLegacyConnectionVisibility = (
- connection: Omit<AppConnection, 'visibility'>,
+ connection: AppConnectionWithoutVisibility,
): AppConnection => ({
...connection,
visibility: LEGACY_CONNECTION_VISIBILITY_BY_SCOPE[connection.scope],
diff --git a/packages/twenty-sdk/src/sdk/logic-function/index.ts b/packages/twenty-sdk/src/sdk/logic-function/index.ts
index c27cf6f21f9..270810f3603 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/index.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/index.ts
@@ -50,8 +50,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 type {
+ AuthorizeConnectionPayload,
+ AuthorizeConnectionResult,
+ ConnectionCallbackPayload,
+ ConnectionCallbackResult,
IdentifyAccountPayload,
IdentifyAccountResult,
+ SendAppMessagePayload,
+ SendAppMessageRecipient,
+ SendAppMessageResult,
} from 'twenty-shared/application';
export { createMessageChannel } from '@/sdk/logic-function/messaging/create-message-channel';
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
index 91abe1e618f..9108590248c 100644
--- 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
@@ -22,17 +22,29 @@ export type CreateMessageChannelInput = {
visibility: MessageChannelVisibility;
// Person field to match participant handles against (handles are then stored in its canonical form); set once
participantHandleFieldUniversalIdentifier?: string;
+ messagingProvider?: { universalIdentifier: string };
};
-export const createMessageChannel = async (
- input: CreateMessageChannelInput,
-): Promise<AppMessageChannel> => {
+export const createMessageChannel = async ({
+ messagingProvider,
+ ...input
+}: CreateMessageChannelInput): Promise<AppMessageChannel> => {
const { createAppMessageChannel } = await postGraphqlRequest<
- { input: CreateMessageChannelInput },
+ {
+ input: Omit<CreateMessageChannelInput, 'messagingProvider'> & {
+ messagingProviderUniversalIdentifier?: string;
+ };
+ },
{ createAppMessageChannel: AppMessageChannel }
>({
query: CREATE_APP_MESSAGE_CHANNEL_MUTATION,
- variables: { input },
+ variables: {
+ input: {
+ ...input,
+ messagingProviderUniversalIdentifier:
+ messagingProvider?.universalIdentifier,
+ },
+ },
caller: 'createMessageChannel',
});
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
index 876b16a1f3e..b04317e5619 100644
--- 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
@@ -7,4 +7,5 @@ export const APP_MESSAGE_CHANNEL_SELECTION = `
connectedAccountId
isSyncEnabled
participantHandleFieldUniversalIdentifier
+ messagingProviderUniversalIdentifier
`;
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
index fe3b45fd5db..f315993e507 100644
--- 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
@@ -19,17 +19,31 @@ export type UpdateMessageChannelInput = {
visibility?: MessageChannelVisibility;
// False pauses ingestion (further ingests are rejected) without deleting the history
isSyncEnabled?: boolean;
+ messagingProvider?: { universalIdentifier: string } | null;
};
-export const updateMessageChannel = async (
- input: UpdateMessageChannelInput,
-): Promise<AppMessageChannel> => {
+export const updateMessageChannel = async ({
+ messagingProvider,
+ ...input
+}: UpdateMessageChannelInput): Promise<AppMessageChannel> => {
const { updateAppMessageChannel } = await postGraphqlRequest<
- { input: UpdateMessageChannelInput },
+ {
+ input: Omit<UpdateMessageChannelInput, 'messagingProvider'> & {
+ messagingProviderUniversalIdentifier?: string | null;
+ };
+ },
{ updateAppMessageChannel: AppMessageChannel }
>({
query: UPDATE_APP_MESSAGE_CHANNEL_MUTATION,
- variables: { input },
+ variables: {
+ input: {
+ ...input,
+ messagingProviderUniversalIdentifier:
+ messagingProvider === undefined
+ ? undefined
+ : (messagingProvider?.universalIdentifier ?? null),
+ },
+ },
caller: 'updateMessageChannel',
});
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-52/2-52-instance-command-fast-1793032438836-add-custom-config-to-connection-provider.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-52/2-52-instance-command-fast-1793032438836-add-custom-config-to-connection-provider.ts
new file mode 100644
index 00000000000..89d6bc66ebc
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-52/2-52-instance-command-fast-1793032438836-add-custom-config-to-connection-provider.ts
@@ -0,0 +1,19 @@
+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.52.0', 1793032438836)
+export class AddCustomConfigToConnectionProviderFastInstanceCommand implements FastInstanceCommand {
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ 'ALTER TABLE "core"."connectionProvider" ADD "customConfig" jsonb',
+ );
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ 'ALTER TABLE "core"."connectionProvider" DROP COLUMN "customConfig"',
+ );
+ }
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-52/2-52-instance-command-fast-1793032438837-add-messaging-provider.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-52/2-52-instance-command-fast-1793032438837-add-messaging-provider.ts
new file mode 100644
index 00000000000..57914a59202
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-52/2-52-instance-command-fast-1793032438837-add-messaging-provider.ts
@@ -0,0 +1,41 @@
+import { type QueryRunner } from 'typeorm';
+
+import { RegisteredInstanceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-instance-command.decorator';
+import { type FastInstanceCommand } from 'src/engine/core-modules/upgrade/interfaces/fast-instance-command.interface';
+
+@RegisteredInstanceCommand('2.52.0', 1793032438837)
+export class AddMessagingProviderFastInstanceCommand implements FastInstanceCommand {
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ 'CREATE TABLE "core"."messagingProvider" ("workspaceId" uuid NOT NULL, "universalIdentifier" uuid NOT NULL, "applicationId" uuid NOT NULL, "id" uuid NOT NULL DEFAULT uuid_generate_v4(), "name" character varying NOT NULL, "displayName" character varying NOT NULL, "connectionProviderUniversalIdentifier" uuid NOT NULL, "sendMessageLogicFunctionUniversalIdentifier" uuid, "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), CONSTRAINT "IDX_MESSAGING_PROVIDER_NAME_APPLICATION_UNIQUE" UNIQUE ("name", "applicationId"), CONSTRAINT "PK_cf0b52a057bbef9c4975ab083e0" PRIMARY KEY ("id"))',
+ );
+ await queryRunner.query(
+ 'CREATE UNIQUE INDEX "IDX_cc6e86ea81701c6d48ae239ea0" ON "core"."messagingProvider" ("workspaceId", "universalIdentifier") ',
+ );
+ await queryRunner.query(
+ 'CREATE INDEX "IDX_MESSAGING_PROVIDER_APPLICATION_ID" ON "core"."messagingProvider" ("applicationId") ',
+ );
+ await queryRunner.query(
+ 'ALTER TABLE "core"."messagingProvider" ADD CONSTRAINT "FK_877a5039c291fe9b340d79c84fa" FOREIGN KEY ("workspaceId") REFERENCES "core"."workspace"("id") ON DELETE CASCADE ON UPDATE NO ACTION',
+ );
+ await queryRunner.query(
+ 'ALTER TABLE "core"."messagingProvider" ADD CONSTRAINT "FK_6a936124386fc95f14ba5959ff0" FOREIGN KEY ("applicationId") REFERENCES "core"."application"("id") ON DELETE CASCADE ON UPDATE NO ACTION',
+ );
+ await queryRunner.query(
+ 'ALTER TABLE "core"."messageChannel" ADD "messagingProviderUniversalIdentifier" uuid',
+ );
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ 'ALTER TABLE "core"."messageChannel" DROP COLUMN "messagingProviderUniversalIdentifier"',
+ );
+ await queryRunner.query(
+ 'ALTER TABLE "core"."messagingProvider" DROP CONSTRAINT "FK_6a936124386fc95f14ba5959ff0"',
+ );
+ await queryRunner.query(
+ 'ALTER TABLE "core"."messagingProvider" DROP CONSTRAINT "FK_877a5039c291fe9b340d79c84fa"',
+ );
+ await queryRunner.query('DROP TABLE "core"."messagingProvider"');
+ }
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-52/add-messaging-provider-upgrade-command-name.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-52/add-messaging-provider-upgrade-command-name.constant.ts
new file mode 100644
index 00000000000..fe0d2658062
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-52/add-messaging-provider-upgrade-command-name.constant.ts
@@ -0,0 +1,2 @@
+export const ADD_MESSAGING_PROVIDER_UPGRADE_COMMAND_NAME =
+ '2.52.0_AddMessagingProviderFastInstanceCommand_1793032438837';
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 221a8ba61a1..d09e639aaff 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
@@ -257,6 +257,8 @@ import { AddAgentChatChannelFastInstanceCommand } from 'src/database/commands/up
import { BackfillRoleAgentChatChannelAccessSlowInstanceCommand } from 'src/database/commands/upgrade-version-command/2-51/2-51-instance-command-slow-1792686689823-backfill-role-agent-chat-channel-access';
import { AddAgentChatChannelNavigationMenuItemFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-51/2-51-instance-command-fast-1792686749823-add-agent-chat-channel-navigation-menu-item';
import { AddParticipantHandleFieldToMessageChannelFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-52/2-52-instance-command-fast-1792907887530-add-participant-handle-field-to-message-channel';
+import { AddCustomConfigToConnectionProviderFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-52/2-52-instance-command-fast-1793032438836-add-custom-config-to-connection-provider';
+import { AddMessagingProviderFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-52/2-52-instance-command-fast-1793032438837-add-messaging-provider';
export const INSTANCE_COMMANDS = [
AddViewFieldGroupIdIndexOnViewFieldFastInstanceCommand,
@@ -516,4 +518,6 @@ export const INSTANCE_COMMANDS = [
BackfillRoleAgentChatChannelAccessSlowInstanceCommand,
AddAgentChatChannelNavigationMenuItemFastInstanceCommand,
AddParticipantHandleFieldToMessageChannelFastInstanceCommand,
+ AddCustomConfigToConnectionProviderFastInstanceCommand,
+ AddMessagingProviderFastInstanceCommand,
];
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-connection-provider-manifest-to-universal-flat-connection-provider.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-connection-provider-manifest-to-universal-flat-connection-provider.util.spec.ts
index 55fe43b79f2..e3b1edf43b6 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-connection-provider-manifest-to-universal-flat-connection-provider.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-connection-provider-manifest-to-universal-flat-connection-provider.util.spec.ts
@@ -52,6 +52,7 @@ describe('fromConnectionProviderManifestToUniversalFlatConnectionProvider', () =
tokenRequestContentType: 'json',
usePkce: true,
},
+ customConfig: null,
identifyAccountLogicFunctionUniversalIdentifier: null,
onConnectLogicFunctionUniversalIdentifier: null,
onDisconnectLogicFunctionUniversalIdentifier: null,
@@ -84,6 +85,37 @@ describe('fromConnectionProviderManifestToUniversalFlatConnectionProvider', () =
expect(result.logo).toBe('public/linear-logomark.svg');
});
+ it('moves the custom flow logic functions into the customConfig blob', () => {
+ const result =
+ fromConnectionProviderManifestToUniversalFlatConnectionProvider({
+ connectionProviderManifest: {
+ universalIdentifier: PROVIDER_UID,
+ name: 'linkedin',
+ displayName: 'LinkedIn',
+ type: 'custom',
+ custom: {
+ authorizeLogicFunction: {
+ universalIdentifier: 'f1f1f1f1-f1f1-4f1f-f1f1-f1f1f1f1f1f1',
+ },
+ callbackLogicFunction: {
+ universalIdentifier: 'f2f2f2f2-f2f2-4f2f-f2f2-f2f2f2f2f2f2',
+ },
+ },
+ },
+ applicationUniversalIdentifier: APP_UID,
+ now: NOW,
+ });
+
+ expect(result.type).toBe('custom');
+ expect(result.oauthConfig).toBeNull();
+ expect(result.customConfig).toEqual({
+ authorizeLogicFunctionUniversalIdentifier:
+ 'f1f1f1f1-f1f1-4f1f-f1f1-f1f1f1f1f1f1',
+ callbackLogicFunctionUniversalIdentifier:
+ 'f2f2f2f2-f2f2-4f2f-f2f2-f2f2f2f2f2f2',
+ });
+ });
+
it('resolves the identifyAccountLogicFunction universalIdentifier into the flat field when provided', () => {
const identifyAccountLogicFunctionUniversalIdentifier =
'e3e3e3e3-e3e3-4e3e-e3e3-e3e3e3e3e3e3';
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-logic-function-manifest-to-universal-flat-logic-function.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-logic-function-manifest-to-universal-flat-logic-function.util.spec.ts
index 8eb84bef243..7ae59724dbd 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-logic-function-manifest-to-universal-flat-logic-function.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-logic-function-manifest-to-universal-flat-logic-function.util.spec.ts
@@ -2,7 +2,7 @@ import { type LogicFunctionManifest } from 'twenty-shared/application';
import { fromLogicFunctionManifestToUniversalFlatLogicFunction } from 'src/engine/core-modules/application/application-manifest/converters/from-logic-function-manifest-to-universal-flat-logic-function.util';
import { ApplicationRegistrationSourceType } from 'src/engine/core-modules/application/application-registration/enums/application-registration-source-type.enum';
-import { IDENTIFY_ACCOUNT_TIMEOUT_SECONDS } from 'src/engine/core-modules/application/connection-provider/constants/identify-account-timeout-seconds.constant';
+import { CONNECTION_FLOW_LOGIC_FUNCTION_TIMEOUT_SECONDS } from 'src/engine/core-modules/application/connection-provider/constants/connection-flow-logic-function-timeout-seconds.constant';
import { createEmptyFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/constant/create-empty-flat-entity-maps.constant';
import { type AllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/all-flat-entity-maps.type';
import { LogicFunctionExecutionMode } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
@@ -45,44 +45,46 @@ describe('fromLogicFunctionManifestToUniversalFlatLogicFunction', () => {
logicFunctionManifest = buildLogicFunctionManifest(),
applicationSourceType,
existingFlatLogicFunctionMaps = emptyFlatLogicFunctionMaps,
- identifyAccountLogicFunctionUniversalIdentifiers = new Set<string>(),
+ connectionFlowLogicFunctionUniversalIdentifiers = new Set<string>(),
}: {
logicFunctionManifest?: LogicFunctionManifest;
applicationSourceType: ApplicationRegistrationSourceType;
existingFlatLogicFunctionMaps?: AllFlatEntityMaps['flatLogicFunctionMaps'];
- identifyAccountLogicFunctionUniversalIdentifiers?: Set<string>;
+ connectionFlowLogicFunctionUniversalIdentifiers?: Set<string>;
}) =>
fromLogicFunctionManifestToUniversalFlatLogicFunction({
logicFunctionManifest,
applicationUniversalIdentifier,
applicationSourceType,
existingFlatLogicFunctionMaps,
- identifyAccountLogicFunctionUniversalIdentifiers,
+ connectionFlowLogicFunctionUniversalIdentifiers,
now,
});
- it('caps the timeout of a function a connection provider uses to identify accounts', () => {
+ it('caps the timeout of a function a connection provider runs during the connection flow', () => {
const result = convert({
logicFunctionManifest: buildLogicFunctionManifest({
timeoutSeconds: 120,
}),
applicationSourceType: ApplicationRegistrationSourceType.LOCAL,
- identifyAccountLogicFunctionUniversalIdentifiers: new Set([
+ connectionFlowLogicFunctionUniversalIdentifiers: new Set([
logicFunctionUniversalIdentifier,
]),
});
- expect(result.timeoutSeconds).toBe(IDENTIFY_ACCOUNT_TIMEOUT_SECONDS);
+ expect(result.timeoutSeconds).toBe(
+ CONNECTION_FLOW_LOGIC_FUNCTION_TIMEOUT_SECONDS,
+ );
});
- it('keeps a shorter timeout on an identify function and the declared one elsewhere', () => {
+ it('keeps a shorter timeout on a connection flow function and the declared one elsewhere', () => {
expect(
convert({
logicFunctionManifest: buildLogicFunctionManifest({
timeoutSeconds: 5,
}),
applicationSourceType: ApplicationRegistrationSourceType.LOCAL,
- identifyAccountLogicFunctionUniversalIdentifiers: new Set([
+ connectionFlowLogicFunctionUniversalIdentifiers: new Set([
logicFunctionUniversalIdentifier,
]),
}).timeoutSeconds,
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-connection-provider-manifest-to-universal-flat-connection-provider.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-connection-provider-manifest-to-universal-flat-connection-provider.util.ts
index 1f82a9c6c48..88ca1b9c698 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-connection-provider-manifest-to-universal-flat-connection-provider.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-connection-provider-manifest-to-universal-flat-connection-provider.util.ts
@@ -1,11 +1,30 @@
import {
type ConnectionProviderManifest,
DEFAULT_CONNECTION_PROVIDER_SCOPE,
+ type StoredCustomConnectionProviderConfig,
type StoredOAuthConnectionProviderConfig,
} from 'twenty-shared/application';
import { type UniversalFlatConnectionProvider } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-connection-provider.type';
+const toStoredCustomConfig = (
+ connectionProviderManifest: ConnectionProviderManifest,
+): StoredCustomConnectionProviderConfig | null => {
+ if (connectionProviderManifest.type !== 'custom') {
+ return null;
+ }
+
+ const { authorizeLogicFunction, callbackLogicFunction } =
+ connectionProviderManifest.custom;
+
+ return {
+ authorizeLogicFunctionUniversalIdentifier:
+ authorizeLogicFunction.universalIdentifier,
+ callbackLogicFunctionUniversalIdentifier:
+ callbackLogicFunction.universalIdentifier,
+ };
+};
+
export const fromConnectionProviderManifestToUniversalFlatConnectionProvider =
({
connectionProviderManifest,
@@ -47,6 +66,7 @@ export const fromConnectionProviderManifestToUniversalFlatConnectionProvider =
scope:
connectionProviderManifest.scope ?? DEFAULT_CONNECTION_PROVIDER_SCOPE,
oauthConfig,
+ customConfig: toStoredCustomConfig(connectionProviderManifest),
identifyAccountLogicFunctionUniversalIdentifier:
connectionProviderManifest.identifyAccountLogicFunction
?.universalIdentifier ?? null,
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-logic-function-manifest-to-universal-flat-logic-function.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-logic-function-manifest-to-universal-flat-logic-function.util.ts
index 13bb1203e70..be9e062dcbe 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-logic-function-manifest-to-universal-flat-logic-function.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-logic-function-manifest-to-universal-flat-logic-function.util.ts
@@ -5,7 +5,7 @@ import { type LogicFunctionManifest } from 'twenty-shared/application';
import { isDefined } from 'twenty-shared/utils';
import { ApplicationRegistrationSourceType } from 'src/engine/core-modules/application/application-registration/enums/application-registration-source-type.enum';
-import { IDENTIFY_ACCOUNT_TIMEOUT_SECONDS } from 'src/engine/core-modules/application/connection-provider/constants/identify-account-timeout-seconds.constant';
+import { CONNECTION_FLOW_LOGIC_FUNCTION_TIMEOUT_SECONDS } from 'src/engine/core-modules/application/connection-provider/constants/connection-flow-logic-function-timeout-seconds.constant';
import { isPackagedApplicationSource } from 'src/engine/core-modules/application/application-registration/utils/is-packaged-application-source.util';
import { type AllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/all-flat-entity-maps.type';
import { findFlatEntityByUniversalIdentifier } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-universal-identifier.util';
@@ -56,14 +56,14 @@ export const fromLogicFunctionManifestToUniversalFlatLogicFunction = ({
applicationUniversalIdentifier,
applicationSourceType,
existingFlatLogicFunctionMaps,
- identifyAccountLogicFunctionUniversalIdentifiers,
+ connectionFlowLogicFunctionUniversalIdentifiers,
now,
}: {
logicFunctionManifest: LogicFunctionManifest;
applicationUniversalIdentifier: string;
applicationSourceType: ApplicationRegistrationSourceType;
existingFlatLogicFunctionMaps: AllFlatEntityMaps['flatLogicFunctionMaps'];
- identifyAccountLogicFunctionUniversalIdentifiers: Set<string>;
+ connectionFlowLogicFunctionUniversalIdentifiers: Set<string>;
now: string;
}): UniversalFlatLogicFunction => {
const name =
@@ -77,10 +77,10 @@ export const fromLogicFunctionManifestToUniversalFlatLogicFunction = ({
name,
description: logicFunctionManifest.description ?? null,
runtime: LogicFunctionRuntime.NODE22,
- timeoutSeconds: identifyAccountLogicFunctionUniversalIdentifiers.has(
+ timeoutSeconds: connectionFlowLogicFunctionUniversalIdentifiers.has(
logicFunctionManifest.universalIdentifier,
)
- ? Math.min(timeoutSeconds, IDENTIFY_ACCOUNT_TIMEOUT_SECONDS)
+ ? Math.min(timeoutSeconds, CONNECTION_FLOW_LOGIC_FUNCTION_TIMEOUT_SECONDS)
: timeoutSeconds,
sourceHandlerPath: logicFunctionManifest.sourceHandlerPath,
builtHandlerPath: logicFunctionManifest.builtHandlerPath,
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-messaging-provider-manifest-to-universal-flat-messaging-provider.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-messaging-provider-manifest-to-universal-flat-messaging-provider.util.ts
new file mode 100644
index 00000000000..07e2d531919
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-messaging-provider-manifest-to-universal-flat-messaging-provider.util.ts
@@ -0,0 +1,25 @@
+import { type MessagingProviderManifest } from 'twenty-shared/application';
+
+import { type UniversalFlatMessagingProvider } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-messaging-provider.type';
+
+export const fromMessagingProviderManifestToUniversalFlatMessagingProvider = ({
+ messagingProviderManifest,
+ applicationUniversalIdentifier,
+ now,
+}: {
+ messagingProviderManifest: MessagingProviderManifest;
+ applicationUniversalIdentifier: string;
+ now: string;
+}): UniversalFlatMessagingProvider => ({
+ universalIdentifier: messagingProviderManifest.universalIdentifier,
+ applicationUniversalIdentifier,
+ name: messagingProviderManifest.name,
+ displayName: messagingProviderManifest.displayName,
+ connectionProviderUniversalIdentifier:
+ messagingProviderManifest.connectionProvider.universalIdentifier,
+ sendMessageLogicFunctionUniversalIdentifier:
+ messagingProviderManifest.sendMessageLogicFunction?.universalIdentifier ??
+ null,
+ createdAt: now,
+ updatedAt: now,
+});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/services/compute-application-manifest-all-universal-flat-entity-maps.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/services/compute-application-manifest-all-universal-flat-entity-maps.service.ts
index bd6f47ada67..6973e57b403 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/services/compute-application-manifest-all-universal-flat-entity-maps.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/services/compute-application-manifest-all-universal-flat-entity-maps.service.ts
@@ -14,7 +14,9 @@ import { isDefined } from 'twenty-shared/utils';
import { fromAgentManifestToUniversalFlatRoleTarget } from 'src/engine/core-modules/application/application-manifest/converters/from-agent-manifest-to-universal-flat-role-target.util';
import { fromApplicationVariableManifestToUniversalFlatApplicationVariable } from 'src/engine/core-modules/application/application-manifest/converters/from-application-variable-manifest-to-universal-flat-application-variable.util';
import { fromCommandMenuItemManifestToUniversalFlatCommandMenuItem } from 'src/engine/core-modules/application/application-manifest/converters/from-command-menu-item-manifest-to-universal-flat-command-menu-item.util';
+import { getConnectionProviderManifestLogicFunctionReferences } from 'src/engine/core-modules/application/application-manifest/utils/get-connection-provider-manifest-logic-function-references.util';
import { fromConnectionProviderManifestToUniversalFlatConnectionProvider } from 'src/engine/core-modules/application/application-manifest/converters/from-connection-provider-manifest-to-universal-flat-connection-provider.util';
+import { fromMessagingProviderManifestToUniversalFlatMessagingProvider } from 'src/engine/core-modules/application/application-manifest/converters/from-messaging-provider-manifest-to-universal-flat-messaging-provider.util';
import { fromFieldManifestToUniversalFlatFieldMetadata } from 'src/engine/core-modules/application/application-manifest/converters/from-field-manifest-to-universal-flat-field-metadata.util';
import { fromFieldPermissionManifestToUniversalFlatFieldPermission } from 'src/engine/core-modules/application/application-manifest/converters/from-field-permission-manifest-to-universal-flat-field-permission.util';
import { fromFrontComponentManifestToUniversalFlatFrontComponent } from 'src/engine/core-modules/application/application-manifest/converters/from-front-component-manifest-to-universal-flat-front-component.util';
@@ -53,6 +55,12 @@ import { type AllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/
import { type UniversalFlatFieldMetadata } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-field-metadata.type';
import { addUniversalFlatEntityToUniversalFlatEntityMapsThroughMutationOrThrow } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/utils/add-universal-flat-entity-to-universal-flat-entity-maps-through-mutation-or-throw.util';
+const CONNECTION_FLOW_HOOKS = new Set([
+ 'identifyAccount',
+ 'authorize',
+ 'callback',
+]);
+
@Injectable()
export class ComputeApplicationManifestAllUniversalFlatEntityMapsService {
compute({
@@ -204,14 +212,12 @@ export class ComputeApplicationManifestAllUniversalFlatEntityMapsService {
});
}
- const identifyAccountLogicFunctionUniversalIdentifiers = new Set(
- (manifest.connectionProviders ?? [])
- .map(
- (connectionProviderManifest) =>
- connectionProviderManifest.identifyAccountLogicFunction
- ?.universalIdentifier,
- )
- .filter(isDefined),
+ const connectionFlowLogicFunctionUniversalIdentifiers = new Set(
+ (manifest.connectionProviders ?? []).flatMap((connectionProvider) =>
+ getConnectionProviderManifestLogicFunctionReferences(connectionProvider)
+ .filter(({ hook }) => CONNECTION_FLOW_HOOKS.has(hook))
+ .map(({ universalIdentifier }) => universalIdentifier),
+ ),
);
for (const logicFunctionManifest of manifest.logicFunctions) {
@@ -223,7 +229,7 @@ export class ComputeApplicationManifestAllUniversalFlatEntityMapsService {
applicationSourceType,
existingFlatLogicFunctionMaps:
fromAllFlatEntityMaps.flatLogicFunctionMaps,
- identifyAccountLogicFunctionUniversalIdentifiers,
+ connectionFlowLogicFunctionUniversalIdentifiers,
now,
}),
universalFlatEntityMapsToMutate:
@@ -272,6 +278,19 @@ export class ComputeApplicationManifestAllUniversalFlatEntityMapsService {
});
}
+ for (const messagingProviderManifest of manifest.messagingProviders ?? []) {
+ addUniversalFlatEntityToUniversalFlatEntityMapsThroughMutationOrThrow({
+ universalFlatEntity:
+ fromMessagingProviderManifestToUniversalFlatMessagingProvider({
+ messagingProviderManifest,
+ applicationUniversalIdentifier,
+ now,
+ }),
+ universalFlatEntityMapsToMutate:
+ allUniversalFlatEntityMaps.flatMessagingProviderMaps,
+ });
+ }
+
for (const permissionFlagManifest of manifest.permissionFlags ?? []) {
addUniversalFlatEntityToUniversalFlatEntityMapsThroughMutationOrThrow({
universalFlatEntity:
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/assert-connection-provider-logic-functions-are-own.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/assert-connection-provider-logic-functions-are-own.util.spec.ts
index 20728b73d74..4790f62f9b7 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/assert-connection-provider-logic-functions-are-own.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/assert-connection-provider-logic-functions-are-own.util.spec.ts
@@ -97,6 +97,46 @@ describe('assertConnectionProviderLogicFunctionsAreOwn', () => {
},
);
+ it.each(['authorizeLogicFunction', 'callbackLogicFunction'] as const)(
+ 'rejects a custom provider whose %s references a logic function outside the application',
+ (logicFunctionKey) => {
+ const custom = {
+ authorizeLogicFunction: {
+ universalIdentifier: MANIFEST_LOGIC_FUNCTION_IDENTIFIER,
+ },
+ callbackLogicFunction: {
+ universalIdentifier: MANIFEST_LOGIC_FUNCTION_IDENTIFIER,
+ },
+ [logicFunctionKey]: {
+ universalIdentifier: UNKNOWN_LOGIC_FUNCTION_IDENTIFIER,
+ },
+ };
+
+ expect(() =>
+ assertConnectionProviderLogicFunctionsAreOwn({
+ manifest: {
+ connectionProviders: [
+ {
+ universalIdentifier: 'connection-provider',
+ name: 'provider',
+ displayName: 'Provider',
+ type: 'custom',
+ custom,
+ },
+ ],
+ },
+ fromFlatLogicFunctionMaps: buildFlatLogicFunctionMaps(
+ EXISTING_LOGIC_FUNCTION_IDENTIFIER,
+ ),
+ toFlatLogicFunctionMaps: buildFlatLogicFunctionMaps(
+ MANIFEST_LOGIC_FUNCTION_IDENTIFIER,
+ ),
+ inferDeletionFromMissingEntities: true,
+ }),
+ ).toThrow(ApplicationException);
+ },
+ );
+
it('accepts an existing logic function of the application on a partial sync', () => {
expect(() =>
assertHooks({
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/assert-connection-provider-logic-functions-are-own.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/assert-connection-provider-logic-functions-are-own.util.ts
index 92e6b2b95c3..aa43c034a59 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/assert-connection-provider-logic-functions-are-own.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/assert-connection-provider-logic-functions-are-own.util.ts
@@ -6,6 +6,7 @@ import {
ApplicationExceptionCode,
} from 'src/engine/core-modules/application/application.exception';
import { type SyncableFlatEntity } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-from.type';
+import { getConnectionProviderManifestLogicFunctionReferences } from 'src/engine/core-modules/application/application-manifest/utils/get-connection-provider-manifest-logic-function-references.util';
import { findFlatEntityByUniversalIdentifier } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-universal-identifier.util';
import { type UniversalFlatEntityMaps } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-entity-maps.type';
@@ -21,17 +22,12 @@ export const assertConnectionProviderLogicFunctionsAreOwn = ({
inferDeletionFromMissingEntities: boolean;
}): void => {
for (const connectionProvider of manifest.connectionProviders ?? []) {
- for (const [hook, logicFunctionReference] of Object.entries({
- identifyAccount: connectionProvider.identifyAccountLogicFunction,
- onConnect: connectionProvider.onConnectLogicFunction,
- onDisconnect: connectionProvider.onDisconnectLogicFunction,
- })) {
- if (!isDefined(logicFunctionReference)) {
- continue;
- }
-
- const { universalIdentifier } = logicFunctionReference;
-
+ for (const {
+ hook,
+ universalIdentifier,
+ } of getConnectionProviderManifestLogicFunctionReferences(
+ connectionProvider,
+ )) {
// fromFlatLogicFunctionMaps only holds this application's functions, which a partial sync keeps.
const isOwnLogicFunction =
isDefined(
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/find-manifest-entity-descriptor-by-universal-identifier.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/find-manifest-entity-descriptor-by-universal-identifier.util.ts
index b84baaa0b4c..4b37d9ad60a 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/find-manifest-entity-descriptor-by-universal-identifier.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/find-manifest-entity-descriptor-by-universal-identifier.util.ts
@@ -84,6 +84,14 @@ export const MANIFEST_ENTITY_REGISTRY: Record<
(connectionProvider) => connectionProvider.displayName,
),
},
+ messagingProvider: {
+ entityKind: 'messaging provider',
+ getCandidates: (manifest) =>
+ toCandidates(
+ manifest.messagingProviders,
+ (messagingProvider) => messagingProvider.displayName,
+ ),
+ },
timelineActivityType: {
entityKind: 'timeline activity type',
getCandidates: (manifest) =>
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/get-connection-provider-manifest-logic-function-references.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/get-connection-provider-manifest-logic-function-references.util.ts
new file mode 100644
index 00000000000..70ee09c10a1
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/get-connection-provider-manifest-logic-function-references.util.ts
@@ -0,0 +1,47 @@
+import {
+ type ConnectionProviderManifest,
+ type SyncableEntityOptions,
+} from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+type ConnectionProviderLogicFunctionHook =
+ | 'identifyAccount'
+ | 'onConnect'
+ | 'onDisconnect'
+ | 'authorize'
+ | 'callback';
+
+export const getConnectionProviderManifestLogicFunctionReferences = (
+ connectionProvider: ConnectionProviderManifest,
+): {
+ hook: ConnectionProviderLogicFunctionHook;
+ universalIdentifier: string;
+}[] => {
+ const custom =
+ connectionProvider.type === 'custom'
+ ? connectionProvider.custom
+ : undefined;
+
+ const references: {
+ hook: ConnectionProviderLogicFunctionHook;
+ reference: SyncableEntityOptions | undefined;
+ }[] = [
+ {
+ hook: 'identifyAccount',
+ reference: connectionProvider.identifyAccountLogicFunction,
+ },
+ { hook: 'onConnect', reference: connectionProvider.onConnectLogicFunction },
+ {
+ hook: 'onDisconnect',
+ reference: connectionProvider.onDisconnectLogicFunction,
+ },
+ { hook: 'authorize', reference: custom?.authorizeLogicFunction },
+ { hook: 'callback', reference: custom?.callbackLogicFunction },
+ ];
+
+ return references.flatMap(({ hook, reference }) =>
+ isDefined(reference)
+ ? [{ hook, universalIdentifier: reference.universalIdentifier }]
+ : [],
+ );
+};
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-authorization-state.service.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-authorization-state.service.ts
new file mode 100644
index 00000000000..fe501314d16
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-authorization-state.service.ts
@@ -0,0 +1,87 @@
+import { Injectable, Logger } from '@nestjs/common';
+
+import { ConnectionProviderExceptionCode } from 'src/engine/core-modules/application/connection-provider/connection-provider-exception-code.enum';
+import { ConnectionProviderException } from 'src/engine/core-modules/application/connection-provider/connection-provider.exception';
+import { type ConnectionAuthorizationArgs } from 'src/engine/core-modules/application/connection-provider/types/connection-authorization-args.type';
+import { type AppOAuthStateJwtPayload } from 'src/engine/core-modules/auth/types/app-oauth-state-jwt-payload.type';
+import { JwtTokenTypeEnum } from 'src/engine/core-modules/auth/types/jwt-token-type.enum';
+import { JwtWrapperService } from 'src/engine/core-modules/jwt/services/jwt-wrapper.service';
+
+@Injectable()
+export class ConnectionProviderAuthorizationStateService {
+ private readonly logger = new Logger(
+ ConnectionProviderAuthorizationStateService.name,
+ );
+
+ constructor(private readonly jwtWrapperService: JwtWrapperService) {}
+
+ async sign({
+ connectionProvider,
+ workspaceId,
+ userId,
+ userWorkspaceId,
+ reconnectingConnectedAccountId,
+ redirectLocation,
+ codeVerifier,
+ expiresIn,
+ }: ConnectionAuthorizationArgs & {
+ codeVerifier: string | null;
+ expiresIn: string;
+ }): Promise<string> {
+ const payload: AppOAuthStateJwtPayload = {
+ sub: connectionProvider.id,
+ type: JwtTokenTypeEnum.APP_OAUTH_STATE,
+ connectionProviderId: connectionProvider.id,
+ workspaceId,
+ userId,
+ userWorkspaceId,
+ scope: connectionProvider.scope,
+ reconnectingConnectedAccountId,
+ redirectLocation,
+ codeVerifier,
+ };
+
+ return this.jwtWrapperService.signAsyncOrThrow(payload, { expiresIn });
+ }
+
+ async verifyOrThrow(state: string): Promise<AppOAuthStateJwtPayload> {
+ const verified: AppOAuthStateJwtPayload = await this.jwtWrapperService
+ .verifyJwtToken(state)
+ .catch((error: unknown) => {
+ this.logger.warn(
+ `Rejected OAuth state: ${error instanceof Error ? error.message : String(error)}`,
+ );
+
+ throw new ConnectionProviderException(
+ 'OAuth state signature invalid or expired',
+ ConnectionProviderExceptionCode.INVALID_STATE,
+ );
+ });
+
+ if (verified.type !== JwtTokenTypeEnum.APP_OAUTH_STATE) {
+ throw new ConnectionProviderException(
+ 'Wrong JWT type for OAuth state',
+ ConnectionProviderExceptionCode.INVALID_STATE,
+ );
+ }
+
+ return verified;
+ }
+
+ async findErrorRedirectTarget(state: string): Promise<{
+ workspaceId: string;
+ redirectLocation: string | null;
+ } | null> {
+ try {
+ const { workspaceId, redirectLocation } = await this.verifyOrThrow(state);
+
+ return { workspaceId, redirectLocation };
+ } catch (error) {
+ this.logger.warn(
+ `Could not read the OAuth state for the error redirect: ${error instanceof Error ? error.message : String(error)}`,
+ );
+
+ return null;
+ }
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-connected-account.service.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-connected-account.service.ts
new file mode 100644
index 00000000000..7f56e34dfad
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-connected-account.service.ts
@@ -0,0 +1,265 @@
+import { Injectable } from '@nestjs/common';
+import { InjectRepository } from '@nestjs/typeorm';
+
+import { type IdentifiedAccount } from 'twenty-shared/application';
+import { ConnectedAccountProvider } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+import { IsNull, Repository } from 'typeorm';
+
+import { AppConnectionAccessService } from 'src/engine/core-modules/application/connection-provider/app-connection-access.service';
+import { ConnectionProviderExceptionCode } from 'src/engine/core-modules/application/connection-provider/connection-provider-exception-code.enum';
+import { type ConnectionProviderEntity } from 'src/engine/core-modules/application/connection-provider/connection-provider.entity';
+import { ConnectionProviderException } from 'src/engine/core-modules/application/connection-provider/connection-provider.exception';
+import { type TokenExchangeResponse } from 'src/engine/core-modules/application/connection-provider/types/token-exchange-response.type';
+import { extractEmailFromIdTokenClaims } from 'src/engine/core-modules/application/connection-provider/utils/extract-email-from-id-token-claims.util';
+import { type PlaintextString } from 'src/engine/core-modules/secret-encryption/branded-strings/plaintext-string.type';
+import { UserEntity } from 'src/engine/core-modules/user/user.entity';
+import {
+ ConnectedAccountEntity,
+ type ConnectedAccountScope,
+} from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
+import { ConnectedAccountTokenEncryptionService } from 'src/engine/metadata-modules/connected-account/services/connected-account-token-encryption.service';
+import { buildConnectedAccountUsableByCallerWhere } from 'src/engine/metadata-modules/connected-account/utils/build-connected-account-usable-by-caller-where.util';
+
+type ConnectedAccountCredentials = {
+ accessToken: PlaintextString | null;
+ refreshToken: PlaintextString | null;
+ scopes: string[] | null;
+};
+
+@Injectable()
+export class ConnectionProviderConnectedAccountService {
+ constructor(
+ private readonly connectedAccountTokenEncryptionService: ConnectedAccountTokenEncryptionService,
+ private readonly appConnectionAccessService: AppConnectionAccessService,
+ @InjectRepository(ConnectedAccountEntity)
+ private readonly connectedAccountRepository: Repository<ConnectedAccountEntity>,
+ @InjectRepository(UserEntity)
+ private readonly userRepository: Repository<UserEntity>,
+ ) {}
+
+ async assertCallerCanConnectOrThrow({
+ connectionProviderId,
+ workspaceId,
+ userWorkspaceId,
+ scope,
+ reconnectingConnectedAccountId,
+ }: {
+ connectionProviderId: string;
+ workspaceId: string;
+ userWorkspaceId: string;
+ scope: ConnectedAccountScope;
+ reconnectingConnectedAccountId: string | null;
+ }): Promise<void> {
+ await this.assertReconnectTargetUsableByCallerOrThrow({
+ connectionProviderId,
+ workspaceId,
+ userWorkspaceId,
+ reconnectingConnectedAccountId,
+ });
+
+ await this.appConnectionAccessService.validateCallerCanManageConnection({
+ isWorkspaceShared: scope === 'WORKSPACE',
+ workspaceId,
+ userWorkspaceId,
+ });
+ }
+
+ async resolveHandle({
+ idToken,
+ userId,
+ }: {
+ idToken: TokenExchangeResponse['idToken'];
+ userId: string;
+ }): Promise<string> {
+ const idTokenEmail = isDefined(idToken)
+ ? extractEmailFromIdTokenClaims(idToken)
+ : null;
+
+ if (isDefined(idTokenEmail)) {
+ return idTokenEmail;
+ }
+
+ const user = await this.userRepository.findOneBy({ id: userId });
+
+ if (!isDefined(user)) {
+ throw new ConnectionProviderException(
+ 'User not found',
+ ConnectionProviderExceptionCode.INVALID_STATE,
+ );
+ }
+
+ return user.email;
+ }
+
+ async persist({
+ provider,
+ credentials,
+ handle,
+ identifiedAccount,
+ workspaceId,
+ userId,
+ userWorkspaceId,
+ scope,
+ reconnectingConnectedAccountId,
+ }: {
+ provider: Pick<
+ ConnectionProviderEntity,
+ 'id' | 'displayName' | 'applicationId'
+ >;
+ credentials: ConnectedAccountCredentials | undefined;
+ handle: string | undefined;
+ identifiedAccount: IdentifiedAccount | null;
+ workspaceId: string;
+ userId: string;
+ userWorkspaceId: string;
+ scope: ConnectedAccountScope;
+ reconnectingConnectedAccountId: string | null;
+ }): Promise<ConnectedAccountEntity> {
+ const sharedFields = {
+ ...(isDefined(credentials) && {
+ accessToken:
+ this.connectedAccountTokenEncryptionService.encryptNullable({
+ plaintext: credentials.accessToken,
+ workspaceId,
+ }),
+ refreshToken:
+ this.connectedAccountTokenEncryptionService.encryptNullable({
+ plaintext: credentials.refreshToken,
+ workspaceId,
+ }),
+ scopes: credentials.scopes,
+ lastCredentialsRefreshedAt: new Date(),
+ }),
+ ...(isDefined(handle) && { handle }),
+ authFailedAt: null,
+ authFailedReason: null,
+ archivedAt: null,
+ scope,
+ externalAccountId: identifiedAccount?.externalAccountId ?? null,
+ };
+
+ if (isDefined(reconnectingConnectedAccountId)) {
+ const reconnectTarget = {
+ id: reconnectingConnectedAccountId,
+ workspaceId,
+ };
+
+ // Compared and written in one statement so overlapping reconnects cannot pin different accounts.
+ const updateResult = await this.connectedAccountRepository.update(
+ isDefined(identifiedAccount)
+ ? [
+ { ...reconnectTarget, externalAccountId: IsNull() },
+ {
+ ...reconnectTarget,
+ externalAccountId: identifiedAccount.externalAccountId,
+ },
+ ]
+ : reconnectTarget,
+ { ...sharedFields, userWorkspaceId },
+ );
+
+ const connectedAccount =
+ await this.connectedAccountRepository.findOneByOrFail(reconnectTarget);
+
+ if (updateResult.affected === 0 && isDefined(identifiedAccount)) {
+ const authorizedAccountHandle =
+ identifiedAccount.handle ?? identifiedAccount.externalAccountId;
+
+ throw new ConnectionProviderException(
+ `You authorized ${authorizedAccountHandle}, but this connection belongs to ${connectedAccount.handle}. Reconnect with ${connectedAccount.handle}, or add a new connection for ${authorizedAccountHandle}.`,
+ ConnectionProviderExceptionCode.RECONNECT_ACCOUNT_MISMATCH,
+ );
+ }
+
+ return connectedAccount;
+ }
+
+ const existingCount = await this.connectedAccountRepository.count({
+ where: { connectionProviderId: provider.id, workspaceId },
+ });
+
+ const name = `${provider.displayName} #${existingCount + 1}`;
+
+ const created = this.connectedAccountRepository.create({
+ ...sharedFields,
+ handle: handle ?? (await this.resolveHandle({ idToken: null, userId })),
+ name,
+ scope,
+ provider: ConnectedAccountProvider.APP,
+ workspaceId,
+ applicationId: provider.applicationId,
+ connectionProviderId: provider.id,
+ userWorkspaceId,
+ });
+
+ return this.connectedAccountRepository.save(created);
+ }
+
+ async findConnectedAccountForReport({
+ provider,
+ workspaceId,
+ userWorkspaceId,
+ externalAccountId,
+ reconnectingConnectedAccountId,
+ }: {
+ provider: Pick<ConnectionProviderEntity, 'id'>;
+ workspaceId: string;
+ userWorkspaceId: string;
+ externalAccountId: string;
+ reconnectingConnectedAccountId: string | null;
+ }): Promise<Pick<
+ ConnectedAccountEntity,
+ 'id' | 'archivedAt' | 'authFailedAt'
+ > | null> {
+ return this.connectedAccountRepository.findOne({
+ where: isDefined(reconnectingConnectedAccountId)
+ ? {
+ id: reconnectingConnectedAccountId,
+ workspaceId,
+ connectionProviderId: provider.id,
+ }
+ : {
+ workspaceId,
+ connectionProviderId: provider.id,
+ userWorkspaceId,
+ externalAccountId,
+ },
+ select: { id: true, archivedAt: true, authFailedAt: true },
+ });
+ }
+
+ private async assertReconnectTargetUsableByCallerOrThrow({
+ connectionProviderId,
+ workspaceId,
+ userWorkspaceId,
+ reconnectingConnectedAccountId,
+ }: {
+ connectionProviderId: string;
+ workspaceId: string;
+ userWorkspaceId: string;
+ reconnectingConnectedAccountId: string | null;
+ }): Promise<void> {
+ if (!isDefined(reconnectingConnectedAccountId)) {
+ return;
+ }
+
+ const reconnectTarget = await this.connectedAccountRepository.findOne({
+ where: buildConnectedAccountUsableByCallerWhere({
+ baseWhere: {
+ id: reconnectingConnectedAccountId,
+ workspaceId,
+ connectionProviderId,
+ },
+ userWorkspaceId,
+ }),
+ });
+
+ if (!isDefined(reconnectTarget)) {
+ throw new ConnectionProviderException(
+ `Cannot reconnect connectedAccount ${reconnectingConnectedAccountId}: not found in this workspace for the requested provider, or not usable by this member.`,
+ ConnectionProviderExceptionCode.FORBIDDEN,
+ );
+ }
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-custom-flow.service.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-custom-flow.service.ts
new file mode 100644
index 00000000000..e5122e1c096
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-custom-flow.service.ts
@@ -0,0 +1,185 @@
+import { Injectable } from '@nestjs/common';
+
+import { type ConnectionCallbackPayload } from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+import { ConnectionProviderAuthorizationStateService } from 'src/engine/core-modules/application/connection-provider/connection-provider-authorization-state.service';
+import { ConnectionProviderConnectedAccountService } from 'src/engine/core-modules/application/connection-provider/connection-provider-connected-account.service';
+import { ConnectionProviderLifecycleHookService } from 'src/engine/core-modules/application/connection-provider/connection-provider-lifecycle-hook.service';
+import { ConnectionProviderService } from 'src/engine/core-modules/application/connection-provider/connection-provider.service';
+import { type ConnectionAuthorizationArgs } from 'src/engine/core-modules/application/connection-provider/types/connection-authorization-args.type';
+import { assertCustomProvider } from 'src/engine/core-modules/application/connection-provider/utils/assert-custom-provider.util';
+import { wasStateIssuedBeforeAccountChange } from 'src/engine/core-modules/application/connection-provider/utils/was-state-issued-before-account-change.util';
+import { buildAppCustomConnectionCallbackUrl } from 'src/engine/core-modules/application/connection-provider/utils/build-custom-connection-callback-url.util';
+import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+
+const STATE_JWT_EXPIRES_IN = '1h';
+
+type CallbackArgs = {
+ state: string;
+ request: Pick<
+ ConnectionCallbackPayload,
+ 'httpMethod' | 'queryStringParameters' | 'headers' | 'body' | 'rawBody'
+ >;
+};
+
+type CallbackResult = {
+ connectedAccountId: string | null;
+ workspaceId: string;
+ applicationId: string;
+ redirectLocation: string | null;
+};
+
+@Injectable()
+export class ConnectionProviderCustomFlowService {
+ constructor(
+ private readonly connectionProviderService: ConnectionProviderService,
+ private readonly authorizationStateService: ConnectionProviderAuthorizationStateService,
+ private readonly connectedAccountService: ConnectionProviderConnectedAccountService,
+ private readonly connectionProviderLifecycleHookService: ConnectionProviderLifecycleHookService,
+ private readonly cacheLockService: CacheLockService,
+ private readonly twentyConfigService: TwentyConfigService,
+ ) {}
+
+ async startAuthorizationFlow(
+ authorizationArgs: ConnectionAuthorizationArgs,
+ ): Promise<{ authorizationUrl: string }> {
+ const { connectionProvider, workspaceId, userWorkspaceId } =
+ authorizationArgs;
+
+ assertCustomProvider(connectionProvider);
+
+ await this.connectedAccountService.assertCallerCanConnectOrThrow({
+ connectionProviderId: connectionProvider.id,
+ workspaceId,
+ userWorkspaceId,
+ scope: connectionProvider.scope,
+ reconnectingConnectedAccountId:
+ authorizationArgs.reconnectingConnectedAccountId,
+ });
+
+ const state = await this.authorizationStateService.sign({
+ ...authorizationArgs,
+ codeVerifier: null,
+ expiresIn: STATE_JWT_EXPIRES_IN,
+ });
+
+ const authorizationUrl =
+ await this.connectionProviderLifecycleHookService.runAuthorize({
+ provider: connectionProvider,
+ workspaceId,
+ callbackUrl: buildAppCustomConnectionCallbackUrl({
+ serverUrl: this.twentyConfigService.get('SERVER_URL'),
+ state,
+ }),
+ });
+
+ return { authorizationUrl };
+ }
+
+ async completeAuthorizationFlow(
+ callbackArgs: CallbackArgs,
+ ): Promise<CallbackResult> {
+ const statePayload = await this.authorizationStateService.verifyOrThrow(
+ callbackArgs.state,
+ );
+
+ const provider = await this.connectionProviderService.findOneByIdOrThrow({
+ id: statePayload.connectionProviderId,
+ workspaceId: statePayload.workspaceId,
+ });
+
+ assertCustomProvider(provider);
+
+ await this.connectedAccountService.assertCallerCanConnectOrThrow({
+ connectionProviderId: provider.id,
+ workspaceId: statePayload.workspaceId,
+ userWorkspaceId: statePayload.userWorkspaceId,
+ scope: statePayload.scope,
+ reconnectingConnectedAccountId:
+ statePayload.reconnectingConnectedAccountId,
+ });
+
+ const callbackResult = {
+ workspaceId: statePayload.workspaceId,
+ applicationId: provider.applicationId,
+ redirectLocation: statePayload.redirectLocation,
+ };
+
+ const connectedAccountFromCallback =
+ await this.connectionProviderLifecycleHookService.runCallback({
+ provider,
+ workspaceId: statePayload.workspaceId,
+ request: callbackArgs.request,
+ });
+
+ if (!isDefined(connectedAccountFromCallback)) {
+ return { ...callbackResult, connectedAccountId: null };
+ }
+
+ const { externalAccountId, handle, accessToken } =
+ connectedAccountFromCallback;
+
+ const { connectedAccount, isRepeatReport } =
+ await this.cacheLockService.withLock(async () => {
+ const existingConnectedAccount =
+ await this.connectedAccountService.findConnectedAccountForReport({
+ provider,
+ workspaceId: statePayload.workspaceId,
+ userWorkspaceId: statePayload.userWorkspaceId,
+ externalAccountId,
+ reconnectingConnectedAccountId:
+ statePayload.reconnectingConnectedAccountId,
+ });
+
+ if (
+ isDefined(existingConnectedAccount) &&
+ wasStateIssuedBeforeAccountChange({
+ stateIssuedAtSeconds: statePayload.iat,
+ connectedAccount: existingConnectedAccount,
+ })
+ ) {
+ return { connectedAccount: null, isRepeatReport: true };
+ }
+
+ return {
+ isRepeatReport:
+ !isDefined(statePayload.reconnectingConnectedAccountId) &&
+ isDefined(existingConnectedAccount) &&
+ !isDefined(existingConnectedAccount.archivedAt) &&
+ !isDefined(existingConnectedAccount.authFailedAt),
+ connectedAccount: await this.connectedAccountService.persist({
+ provider,
+ credentials: isDefined(accessToken)
+ ? { accessToken, refreshToken: null, scopes: null }
+ : undefined,
+ handle,
+ identifiedAccount: { externalAccountId },
+ workspaceId: statePayload.workspaceId,
+ userId: statePayload.userId,
+ userWorkspaceId: statePayload.userWorkspaceId,
+ scope: statePayload.scope,
+ reconnectingConnectedAccountId:
+ statePayload.reconnectingConnectedAccountId ??
+ existingConnectedAccount?.id ??
+ null,
+ }),
+ };
+ }, `app-custom-connection:${statePayload.workspaceId}:${provider.id}:${statePayload.userWorkspaceId}:${externalAccountId}`);
+
+ if (!isDefined(connectedAccount)) {
+ return { ...callbackResult, connectedAccountId: null };
+ }
+
+ if (!isRepeatReport) {
+ await this.connectionProviderLifecycleHookService.dispatchOnConnect({
+ provider,
+ workspaceId: statePayload.workspaceId,
+ connectedAccountId: connectedAccount.id,
+ });
+ }
+
+ return { ...callbackResult, connectedAccountId: connectedAccount.id };
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-custom.controller.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-custom.controller.ts
new file mode 100644
index 00000000000..591c12ae6ee
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-custom.controller.ts
@@ -0,0 +1,131 @@
+import {
+ Controller,
+ Get,
+ HttpCode,
+ Post,
+ Req,
+ Res,
+ UseFilters,
+ UseGuards,
+} from '@nestjs/common';
+
+import { isNonEmptyString } from '@sniptt/guards';
+import { type Request, type Response } from 'express';
+import { ApiPath } from 'twenty-shared/types';
+
+import { ConnectionProviderCustomFlowService } from 'src/engine/core-modules/application/connection-provider/connection-provider-custom-flow.service';
+import { ConnectionProviderExceptionCode } from 'src/engine/core-modules/application/connection-provider/connection-provider-exception-code.enum';
+import { ConnectionProviderFlowRedirectService } from 'src/engine/core-modules/application/connection-provider/connection-provider-flow-redirect.service';
+import { ConnectionProviderException } from 'src/engine/core-modules/application/connection-provider/connection-provider.exception';
+import { ConnectionProviderRestApiExceptionFilter } from 'src/engine/core-modules/application/connection-provider/filters/connection-provider-rest-api-exception.filter';
+import { BillingRestApiExceptionFilter } from 'src/engine/core-modules/billing/filters/billing-api-exception.filter';
+import { LogicFunctionExecutionRestApiExceptionFilter } from 'src/engine/core-modules/logic-function/logic-function-executor/filters/logic-function-execution-rest-api-exception.filter';
+import {
+ extractBody,
+ extractRawBody,
+ filterRequestHeaders,
+ normalizeQueryStringParameters,
+} from 'src/engine/core-modules/logic-function/logic-function-trigger/triggers/route/utils/build-logic-function-event.util';
+import { UsageLimitRestApiExceptionFilter } from 'src/engine/core-modules/usage-limit/filters/usage-limit-rest-api-exception.filter';
+import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';
+import { PublicEndpointGuard } from 'src/engine/guards/public-endpoint.guard';
+import { PermissionsRestApiExceptionFilter } from 'src/engine/metadata-modules/permissions/utils/permissions-rest-api-exception.filter';
+
+@Controller(`${ApiPath.Auth}/apps/custom`)
+@UseGuards(PublicEndpointGuard, NoPermissionGuard)
+export class ConnectionProviderCustomController {
+ constructor(
+ private readonly customFlowService: ConnectionProviderCustomFlowService,
+ private readonly flowRedirectService: ConnectionProviderFlowRedirectService,
+ ) {}
+
+ @Get('callback')
+ async callback(@Req() req: Request, @Res() res: Response) {
+ let state: string | undefined;
+
+ try {
+ const callbackRequest = this.readCallbackRequestOrThrow(req);
+
+ state = callbackRequest.state;
+
+ const { workspaceId, applicationId, redirectLocation } =
+ await this.customFlowService.completeAuthorizationFlow({
+ state,
+ request: {
+ httpMethod: 'GET',
+ queryStringParameters: callbackRequest.queryStringParameters,
+ headers: callbackRequest.headers,
+ body: null,
+ rawBody: null,
+ },
+ });
+
+ return await this.flowRedirectService.redirectToConnectedApplication({
+ res,
+ workspaceId,
+ applicationId,
+ redirectLocation,
+ });
+ } catch (error) {
+ return this.flowRedirectService.redirectToErrorFromState({
+ res,
+ state,
+ error,
+ });
+ }
+ }
+
+ @Post('callback')
+ @HttpCode(200)
+ @UseFilters(
+ ConnectionProviderRestApiExceptionFilter,
+ PermissionsRestApiExceptionFilter,
+ LogicFunctionExecutionRestApiExceptionFilter,
+ UsageLimitRestApiExceptionFilter,
+ BillingRestApiExceptionFilter,
+ )
+ async callbackNotification(@Req() req: Request): Promise<{ success: true }> {
+ const { state, queryStringParameters, headers } =
+ this.readCallbackRequestOrThrow(req);
+
+ await this.customFlowService.completeAuthorizationFlow({
+ state,
+ request: {
+ httpMethod: 'POST',
+ queryStringParameters,
+ headers,
+ body: extractBody(req),
+ rawBody: extractRawBody(req) ?? null,
+ },
+ });
+
+ return { success: true };
+ }
+
+ private readCallbackRequestOrThrow(req: Request): {
+ state: string;
+ queryStringParameters: Record<string, string | undefined>;
+ headers: Record<string, string | undefined>;
+ } {
+ const { state, ...queryStringParameters } = normalizeQueryStringParameters(
+ req.query,
+ );
+
+ if (!isNonEmptyString(state)) {
+ throw new ConnectionProviderException(
+ 'Custom connection callback is missing the `state` query parameter',
+ ConnectionProviderExceptionCode.INVALID_REQUEST,
+ );
+ }
+
+ return {
+ state,
+ queryStringParameters,
+ headers: filterRequestHeaders({
+ requestHeaders: req.headers,
+ forwardedRequestHeaders: [],
+ forwardAllHeaders: true,
+ }),
+ };
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-exception-code.enum.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-exception-code.enum.ts
index 5c73924bd8f..25cf6993562 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-exception-code.enum.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-exception-code.enum.ts
@@ -16,4 +16,8 @@ export enum ConnectionProviderExceptionCode {
IDENTIFY_ACCOUNT_LOGIC_FUNCTION_NOT_FOUND = 'IDENTIFY_ACCOUNT_LOGIC_FUNCTION_NOT_FOUND',
IDENTIFY_ACCOUNT_LOGIC_FUNCTION_FAILED = 'IDENTIFY_ACCOUNT_LOGIC_FUNCTION_FAILED',
RECONNECT_ACCOUNT_MISMATCH = 'RECONNECT_ACCOUNT_MISMATCH',
+ AUTHORIZE_LOGIC_FUNCTION_NOT_FOUND = 'AUTHORIZE_LOGIC_FUNCTION_NOT_FOUND',
+ AUTHORIZE_LOGIC_FUNCTION_FAILED = 'AUTHORIZE_LOGIC_FUNCTION_FAILED',
+ CALLBACK_LOGIC_FUNCTION_NOT_FOUND = 'CALLBACK_LOGIC_FUNCTION_NOT_FOUND',
+ CALLBACK_LOGIC_FUNCTION_FAILED = 'CALLBACK_LOGIC_FUNCTION_FAILED',
}
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-flow-redirect.service.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-flow-redirect.service.ts
new file mode 100644
index 00000000000..e8ec937df62
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-flow-redirect.service.ts
@@ -0,0 +1,174 @@
+import { Injectable } from '@nestjs/common';
+import { InjectRepository } from '@nestjs/typeorm';
+
+import { isNonEmptyString } from '@sniptt/guards';
+import { type Response } from 'express';
+import { SOURCE_LOCALE } from 'twenty-shared/translations';
+import { SettingsPath } from 'twenty-shared/types';
+import {
+ getSettingsPath,
+ isDefined,
+ isSafeInternalPath,
+} from 'twenty-shared/utils';
+import { Repository } from 'typeorm';
+
+import { ConnectionProviderAuthorizationStateService } from 'src/engine/core-modules/application/connection-provider/connection-provider-authorization-state.service';
+import { ConnectionProviderExceptionCode } from 'src/engine/core-modules/application/connection-provider/connection-provider-exception-code.enum';
+import { ConnectionProviderException } from 'src/engine/core-modules/application/connection-provider/connection-provider.exception';
+import { parseRelativeUrl } from 'src/engine/core-modules/domain/domain-server-config/utils/parse-relative-url.util';
+import { WorkspaceDomainsService } from 'src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service';
+import { GuardRedirectService } from 'src/engine/core-modules/guard-redirect/services/guard-redirect.service';
+import { I18nService } from 'src/engine/core-modules/i18n/i18n.service';
+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+
+@Injectable()
+export class ConnectionProviderFlowRedirectService {
+ constructor(
+ private readonly authorizationStateService: ConnectionProviderAuthorizationStateService,
+ private readonly workspaceDomainsService: WorkspaceDomainsService,
+ private readonly guardRedirectService: GuardRedirectService,
+ private readonly twentyConfigService: TwentyConfigService,
+ private readonly i18nService: I18nService,
+ @InjectRepository(WorkspaceEntity)
+ private readonly workspaceRepository: Repository<WorkspaceEntity>,
+ ) {}
+
+ async redirectToConnectedApplication({
+ res,
+ workspaceId,
+ applicationId,
+ redirectLocation,
+ }: {
+ res: Response;
+ workspaceId: string;
+ applicationId: string;
+ redirectLocation: string | null;
+ }) {
+ const workspace = await this.workspaceRepository.findOneBy({
+ id: workspaceId,
+ });
+
+ if (!isDefined(workspace)) {
+ throw new ConnectionProviderException(
+ `Workspace ${workspaceId} not found after OAuth callback`,
+ ConnectionProviderExceptionCode.PROVIDER_NOT_FOUND,
+ );
+ }
+
+ const hasRedirectLocation = isNonEmptyString(redirectLocation);
+
+ const { pathname, searchParams, hash } = this.parseRedirectLocation({
+ redirectLocation,
+ fallbackPathname: getSettingsPath(SettingsPath.ApplicationDetail, {
+ applicationId,
+ }),
+ });
+
+ const url = this.workspaceDomainsService.buildWorkspaceURL({
+ workspace,
+ pathname,
+ searchParams,
+ hash,
+ });
+
+ // Frontend tab list reads the URL hash to pick the active tab.
+ if (!hasRedirectLocation) {
+ url.hash = 'settings';
+ }
+
+ return res.redirect(url.toString());
+ }
+
+ async redirectToErrorFromState({
+ res,
+ state,
+ error,
+ }: {
+ res: Response;
+ state: string | undefined;
+ error: unknown;
+ }) {
+ const errorRedirectTarget = isNonEmptyString(state)
+ ? await this.authorizationStateService.findErrorRedirectTarget(state)
+ : null;
+
+ const workspace = isDefined(errorRedirectTarget)
+ ? await this.workspaceRepository.findOneBy({
+ id: errorRedirectTarget.workspaceId,
+ })
+ : null;
+
+ return this.redirectToError({
+ res,
+ error,
+ workspace,
+ redirectLocation: errorRedirectTarget?.redirectLocation ?? null,
+ });
+ }
+
+ redirectToError({
+ res,
+ error,
+ workspace,
+ redirectLocation,
+ }: {
+ res: Response;
+ error: unknown;
+ workspace: Pick<
+ WorkspaceEntity,
+ 'id' | 'subdomain' | 'customDomain' | 'isCustomDomainEnabled'
+ > | null;
+ redirectLocation: string | null;
+ }) {
+ const { pathname, searchParams, hash } = this.parseRedirectLocation({
+ redirectLocation,
+ fallbackPathname: getSettingsPath(SettingsPath.Accounts),
+ });
+
+ return res.redirect(
+ this.guardRedirectService.getRedirectErrorUrlAndCaptureExceptions({
+ error: error instanceof Error ? error : new Error(String(error)),
+ workspace: {
+ id: workspace?.id,
+ subdomain:
+ workspace?.subdomain ??
+ this.twentyConfigService.get('DEFAULT_SUBDOMAIN'),
+ customDomain: workspace?.customDomain ?? null,
+ isCustomDomainEnabled: workspace?.isCustomDomainEnabled ?? false,
+ },
+ pathname,
+ searchParams,
+ hash,
+ errorMessage: this.getTokenExchangeFailureMessage(error),
+ }),
+ );
+ }
+
+ private parseRedirectLocation({
+ redirectLocation,
+ fallbackPathname,
+ }: {
+ redirectLocation: string | null | undefined;
+ fallbackPathname: string;
+ }) {
+ return parseRelativeUrl(
+ isDefined(redirectLocation) && isSafeInternalPath(redirectLocation)
+ ? redirectLocation
+ : fallbackPathname,
+ );
+ }
+
+ private getTokenExchangeFailureMessage(error: unknown): string | undefined {
+ if (
+ !(error instanceof ConnectionProviderException) ||
+ error.code !== ConnectionProviderExceptionCode.TOKEN_EXCHANGE_FAILED
+ ) {
+ return undefined;
+ }
+
+ return this.i18nService
+ .getI18nInstance(SOURCE_LOCALE)
+ ._(error.userFriendlyMessage);
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-lifecycle-hook.service.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-lifecycle-hook.service.ts
index 4d2d4782aff..efeb53d7655 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-lifecycle-hook.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-lifecycle-hook.service.ts
@@ -1,6 +1,8 @@
import { Injectable } from '@nestjs/common';
import {
+ type AuthorizeConnectionPayload,
+ type ConnectionCallbackPayload,
type IdentifiedAccount,
type IdentifyAccountPayload,
} from 'twenty-shared/application';
@@ -10,6 +12,12 @@ import { ConnectionProviderExceptionCode } from 'src/engine/core-modules/applica
import { type ConnectionProviderEntity } from 'src/engine/core-modules/application/connection-provider/connection-provider.entity';
import { ConnectionProviderException } from 'src/engine/core-modules/application/connection-provider/connection-provider.exception';
import { ConnectionProviderService } from 'src/engine/core-modules/application/connection-provider/connection-provider.service';
+import { type CustomConnectionProvider } from 'src/engine/core-modules/application/connection-provider/utils/assert-custom-provider.util';
+import { parseAuthorizeConnectionResult } from 'src/engine/core-modules/application/connection-provider/utils/parse-authorize-connection-result.util';
+import {
+ parseConnectionCallbackResult,
+ type ParsedConnectedAccountFromCallback,
+} from 'src/engine/core-modules/application/connection-provider/utils/parse-connection-callback-result.util';
import { parseIdentifyAccountResult } from 'src/engine/core-modules/application/connection-provider/utils/parse-identify-account-result.util';
import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';
import { type LogicFunctionExecuteResult } from 'src/engine/core-modules/logic-function/logic-function-drivers/interfaces/logic-function-driver.interface';
@@ -22,10 +30,20 @@ import {
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';
import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
+import { findApplicationFlatLogicFunction } from 'src/engine/metadata-modules/logic-function/utils/find-application-flat-logic-function.util';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
-import { CustomException } from 'src/utils/custom-exception';
-type ConnectionLifecycleHook = 'identifyAccount' | 'onConnect' | 'onDisconnect';
+type ConnectionLifecycleHook =
+ | 'identifyAccount'
+ | 'authorize'
+ | 'callback'
+ | 'onConnect'
+ | 'onDisconnect';
+
+type ConnectionFlowHook = Extract<
+ ConnectionLifecycleHook,
+ 'identifyAccount' | 'authorize' | 'callback'
+>;
type ConnectionLifecycleHookProvider = Pick<
ConnectionProviderEntity,
@@ -38,12 +56,38 @@ const MISSING_LOGIC_FUNCTION_EXCEPTION_CODE_BY_HOOK: Record<
> = {
identifyAccount:
ConnectionProviderExceptionCode.IDENTIFY_ACCOUNT_LOGIC_FUNCTION_NOT_FOUND,
+ authorize: ConnectionProviderExceptionCode.AUTHORIZE_LOGIC_FUNCTION_NOT_FOUND,
+ callback: ConnectionProviderExceptionCode.CALLBACK_LOGIC_FUNCTION_NOT_FOUND,
onConnect:
ConnectionProviderExceptionCode.ON_CONNECT_LOGIC_FUNCTION_NOT_FOUND,
onDisconnect:
ConnectionProviderExceptionCode.ON_DISCONNECT_LOGIC_FUNCTION_NOT_FOUND,
};
+const FAILED_LOGIC_FUNCTION_EXCEPTION_CODE_BY_CONNECTION_FLOW_HOOK: Record<
+ ConnectionFlowHook,
+ ConnectionProviderExceptionCode
+> = {
+ identifyAccount:
+ ConnectionProviderExceptionCode.IDENTIFY_ACCOUNT_LOGIC_FUNCTION_FAILED,
+ authorize: ConnectionProviderExceptionCode.AUTHORIZE_LOGIC_FUNCTION_FAILED,
+ callback: ConnectionProviderExceptionCode.CALLBACK_LOGIC_FUNCTION_FAILED,
+};
+
+const buildConnectionFlowHookFailedException = ({
+ hook,
+ provider,
+ reason,
+}: {
+ hook: ConnectionFlowHook;
+ provider: Pick<ConnectionLifecycleHookProvider, 'id'>;
+ reason: string;
+}): ConnectionProviderException =>
+ new ConnectionProviderException(
+ `${hook} logic function of connection provider ${provider.id} ${reason}`,
+ FAILED_LOGIC_FUNCTION_EXCEPTION_CODE_BY_CONNECTION_FLOW_HOOK[hook],
+ );
+
@Injectable()
export class ConnectionProviderLifecycleHookService {
constructor(
@@ -132,30 +176,122 @@ export class ConnectionProviderLifecycleHookService {
accessToken,
};
- const executionResult = await this.executeIdentifyAccount({
+ const data = await this.executeConnectionFlowHook({
+ hook: 'identifyAccount',
provider,
logicFunctionId,
workspaceId,
payload,
});
- if (isDefined(executionResult.error)) {
- throw new ConnectionProviderException(
- `identifyAccount logic function of connection provider ${provider.id} failed: ${executionResult.error.errorMessage}`,
- ConnectionProviderExceptionCode.IDENTIFY_ACCOUNT_LOGIC_FUNCTION_FAILED,
- );
+ const parsedResult = parseIdentifyAccountResult(data);
+
+ if (!parsedResult.isValid) {
+ throw buildConnectionFlowHookFailedException({
+ hook: 'identifyAccount',
+ provider,
+ reason: `returned an invalid result: ${parsedResult.reason}`,
+ });
}
- const parsedResult = parseIdentifyAccountResult(executionResult.data);
+ return parsedResult.identifiedAccount;
+ }
+
+ async runAuthorize({
+ provider,
+ workspaceId,
+ callbackUrl,
+ }: {
+ provider: Pick<
+ CustomConnectionProvider,
+ 'id' | 'name' | 'applicationId' | 'customConfig'
+ >;
+ workspaceId: string;
+ callbackUrl: string;
+ }): Promise<string> {
+ const logicFunctionId = await this.resolveLogicFunctionIdOrThrow({
+ hook: 'authorize',
+ logicFunctionUniversalIdentifier:
+ provider.customConfig.authorizeLogicFunctionUniversalIdentifier,
+ provider,
+ workspaceId,
+ });
+
+ const payload: AuthorizeConnectionPayload = {
+ connectionProviderId: provider.id,
+ connectionProviderName: provider.name,
+ callbackUrl,
+ };
+
+ const data = await this.executeConnectionFlowHook({
+ hook: 'authorize',
+ provider,
+ logicFunctionId,
+ workspaceId,
+ payload,
+ });
+
+ const parsedResult = parseAuthorizeConnectionResult(data);
if (!parsedResult.isValid) {
- throw new ConnectionProviderException(
- `identifyAccount logic function of connection provider ${provider.id} returned an invalid result: ${parsedResult.reason}`,
- ConnectionProviderExceptionCode.IDENTIFY_ACCOUNT_LOGIC_FUNCTION_FAILED,
- );
+ throw buildConnectionFlowHookFailedException({
+ hook: 'authorize',
+ provider,
+ reason: `returned an invalid result: ${parsedResult.reason}`,
+ });
}
- return parsedResult.identifiedAccount;
+ return parsedResult.authorizationUrl;
+ }
+
+ async runCallback({
+ provider,
+ workspaceId,
+ request,
+ }: {
+ provider: Pick<
+ CustomConnectionProvider,
+ 'id' | 'name' | 'applicationId' | 'customConfig'
+ >;
+ workspaceId: string;
+ request: Pick<
+ ConnectionCallbackPayload,
+ 'httpMethod' | 'queryStringParameters' | 'headers' | 'body' | 'rawBody'
+ >;
+ }): Promise<ParsedConnectedAccountFromCallback | null> {
+ const logicFunctionId = await this.resolveLogicFunctionIdOrThrow({
+ hook: 'callback',
+ logicFunctionUniversalIdentifier:
+ provider.customConfig.callbackLogicFunctionUniversalIdentifier,
+ provider,
+ workspaceId,
+ });
+
+ const payload: ConnectionCallbackPayload = {
+ connectionProviderId: provider.id,
+ connectionProviderName: provider.name,
+ ...request,
+ };
+
+ const data = await this.executeConnectionFlowHook({
+ hook: 'callback',
+ provider,
+ logicFunctionId,
+ workspaceId,
+ payload,
+ });
+
+ const parsedResult = parseConnectionCallbackResult(data);
+
+ if (!parsedResult.isValid) {
+ throw buildConnectionFlowHookFailedException({
+ hook: 'callback',
+ provider,
+ reason: `returned an invalid result: ${parsedResult.reason}`,
+ });
+ }
+
+ return parsedResult.connectedAccount;
}
// Runs inline, before the connected account and its token are deleted, so the
@@ -202,34 +338,30 @@ export class ConnectionProviderLifecycleHookService {
});
}
- private async executeIdentifyAccount({
+ private async executeConnectionFlowHook({
+ hook,
provider,
logicFunctionId,
workspaceId,
payload,
}: {
+ hook: ConnectionFlowHook;
provider: ConnectionLifecycleHookProvider;
logicFunctionId: string;
workspaceId: string;
- payload: IdentifyAccountPayload;
- }): Promise<LogicFunctionExecuteResult> {
- try {
- return await this.logicFunctionExecutorService.execute({
- logicFunctionId,
- workspaceId,
- payload,
- shouldEnforceUsageLimits: true,
- });
- } catch (error) {
- if (error instanceof CustomException) {
- throw error;
- }
-
- throw new ConnectionProviderException(
- `identifyAccount logic function of connection provider ${provider.id} could not be executed: ${error instanceof Error ? error.message : String(error)}`,
- ConnectionProviderExceptionCode.IDENTIFY_ACCOUNT_LOGIC_FUNCTION_FAILED,
- );
- }
+ payload:
+ | IdentifyAccountPayload
+ | AuthorizeConnectionPayload
+ | ConnectionCallbackPayload;
+ }): Promise<LogicFunctionExecuteResult['data']> {
+ return this.logicFunctionExecutorService.executeOrThrow({
+ logicFunctionId,
+ workspaceId,
+ payload,
+ shouldEnforceUsageLimits: true,
+ toException: (reason) =>
+ buildConnectionFlowHookFailedException({ hook, provider, reason }),
+ });
}
// Lifecycle hooks are best effort: a failing hook must never surface to the
@@ -262,10 +394,8 @@ export class ConnectionProviderLifecycleHookService {
}
private async resolveLogicFunctionId({
- hook,
logicFunctionUniversalIdentifier,
- provider,
- workspaceId,
+ ...logicFunctionLookup
}: {
hook: ConnectionLifecycleHook;
logicFunctionUniversalIdentifier: string | null;
@@ -276,21 +406,35 @@ export class ConnectionProviderLifecycleHookService {
return undefined;
}
+ return this.resolveLogicFunctionIdOrThrow({
+ ...logicFunctionLookup,
+ logicFunctionUniversalIdentifier,
+ });
+ }
+
+ private async resolveLogicFunctionIdOrThrow({
+ hook,
+ logicFunctionUniversalIdentifier,
+ provider,
+ workspaceId,
+ }: {
+ hook: ConnectionLifecycleHook;
+ logicFunctionUniversalIdentifier: string;
+ provider: Pick<ConnectionLifecycleHookProvider, 'id' | 'applicationId'>;
+ workspaceId: string;
+ }): Promise<string> {
const { flatLogicFunctionMaps } =
await this.workspaceCacheService.getOrRecompute(workspaceId, [
'flatLogicFunctionMaps',
]);
- const flatLogicFunction =
- flatLogicFunctionMaps.byUniversalIdentifier[
- logicFunctionUniversalIdentifier
- ];
+ const flatLogicFunction = findApplicationFlatLogicFunction({
+ flatLogicFunctionMaps,
+ universalIdentifier: logicFunctionUniversalIdentifier,
+ applicationId: provider.applicationId,
+ });
- if (
- !isDefined(flatLogicFunction) ||
- isDefined(flatLogicFunction.deletedAt) ||
- flatLogicFunction.applicationId !== provider.applicationId
- ) {
+ if (!isDefined(flatLogicFunction)) {
throw new ConnectionProviderException(
`Connection provider ${provider.id} references ${hook} logic function ${logicFunctionUniversalIdentifier}, which was not found in its application.`,
MISSING_LOGIC_FUNCTION_EXCEPTION_CODE_BY_HOOK[hook],
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth-flow.service.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth-flow.service.ts
index 5b97ed2bd7c..1917e65a3c2 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth-flow.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth-flow.service.ts
@@ -1,52 +1,23 @@
import { Injectable, Logger } from '@nestjs/common';
-import { InjectRepository } from '@nestjs/typeorm';
-import { IsNull, Repository } from 'typeorm';
-
-import { type IdentifiedAccount } from 'twenty-shared/application';
-import { ConnectedAccountProvider } from 'twenty-shared/types';
-import { isDefined } from 'twenty-shared/utils';
-
-import { AppConnectionAccessService } from 'src/engine/core-modules/application/connection-provider/app-connection-access.service';
+import { ConnectionProviderAuthorizationStateService } from 'src/engine/core-modules/application/connection-provider/connection-provider-authorization-state.service';
+import { ConnectionProviderConnectedAccountService } from 'src/engine/core-modules/application/connection-provider/connection-provider-connected-account.service';
import { ConnectionProviderExceptionCode } from 'src/engine/core-modules/application/connection-provider/connection-provider-exception-code.enum';
import { ConnectionProviderLifecycleHookService } from 'src/engine/core-modules/application/connection-provider/connection-provider-lifecycle-hook.service';
-import { type ConnectionProviderEntity } from 'src/engine/core-modules/application/connection-provider/connection-provider.entity';
import { ConnectionProviderException } from 'src/engine/core-modules/application/connection-provider/connection-provider.exception';
import { ConnectionProviderService } from 'src/engine/core-modules/application/connection-provider/connection-provider.service';
+import { type ConnectionAuthorizationArgs } from 'src/engine/core-modules/application/connection-provider/types/connection-authorization-args.type';
import { type TokenExchangeResponse } from 'src/engine/core-modules/application/connection-provider/types/token-exchange-response.type';
-import {
- assertOAuthProvider,
- type OAuthConnectionProvider,
-} from 'src/engine/core-modules/application/connection-provider/utils/assert-oauth-provider.util';
+import { assertOAuthProvider } from 'src/engine/core-modules/application/connection-provider/utils/assert-oauth-provider.util';
import { buildAppOAuthCallbackUrl } from 'src/engine/core-modules/application/connection-provider/utils/build-callback-url.util';
import { computePkceChallenge } from 'src/engine/core-modules/application/connection-provider/utils/compute-pkce-challenge.util';
import { exchangeCodeForToken } from 'src/engine/core-modules/application/connection-provider/utils/exchange-code-for-token.util';
-import { extractEmailFromIdTokenClaims } from 'src/engine/core-modules/application/connection-provider/utils/extract-email-from-id-token-claims.util';
import { generatePkceVerifier } from 'src/engine/core-modules/application/connection-provider/utils/generate-pkce-verifier.util';
-import { type AppOAuthStateJwtPayload } from 'src/engine/core-modules/auth/types/app-oauth-state-jwt-payload.type';
-import { JwtTokenTypeEnum } from 'src/engine/core-modules/auth/types/jwt-token-type.enum';
-import { JwtWrapperService } from 'src/engine/core-modules/jwt/services/jwt-wrapper.service';
import { SecureHttpClientService } from 'src/engine/core-modules/secure-http-client/secure-http-client.service';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
-import { UserEntity } from 'src/engine/core-modules/user/user.entity';
-import {
- ConnectedAccountEntity,
- type ConnectedAccountScope,
-} from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
-import { ConnectedAccountTokenEncryptionService } from 'src/engine/metadata-modules/connected-account/services/connected-account-token-encryption.service';
-import { buildConnectedAccountUsableByCallerWhere } from 'src/engine/metadata-modules/connected-account/utils/build-connected-account-usable-by-caller-where.util';
const STATE_JWT_EXPIRES_IN = '10m';
-type AuthorizeArgs = {
- connectionProvider: ConnectionProviderEntity;
- workspaceId: string;
- userId: string;
- userWorkspaceId: string;
- reconnectingConnectedAccountId: string | null;
- redirectLocation: string | null;
-};
-
type CallbackArgs = {
code: string;
state: string;
@@ -65,36 +36,28 @@ export class ConnectionProviderOAuthFlowService {
constructor(
private readonly oauthProviderService: ConnectionProviderService,
- private readonly jwtWrapperService: JwtWrapperService,
+ private readonly authorizationStateService: ConnectionProviderAuthorizationStateService,
+ private readonly connectedAccountService: ConnectionProviderConnectedAccountService,
private readonly secureHttpClientService: SecureHttpClientService,
private readonly twentyConfigService: TwentyConfigService,
- private readonly connectedAccountTokenEncryptionService: ConnectedAccountTokenEncryptionService,
private readonly connectionProviderLifecycleHookService: ConnectionProviderLifecycleHookService,
- private readonly appConnectionAccessService: AppConnectionAccessService,
- @InjectRepository(ConnectedAccountEntity)
- private readonly connectedAccountRepository: Repository<ConnectedAccountEntity>,
- @InjectRepository(UserEntity)
- private readonly userRepository: Repository<UserEntity>,
) {}
async startAuthorizationFlow(
- args: AuthorizeArgs,
+ authorizationArgs: ConnectionAuthorizationArgs,
): Promise<{ authorizationUrl: string }> {
- const { connectionProvider, workspaceId, userId, userWorkspaceId } = args;
+ const { connectionProvider, workspaceId, userWorkspaceId } =
+ authorizationArgs;
assertOAuthProvider(connectionProvider);
- await this.assertReconnectTargetUsableByCallerOrThrow({
+ await this.connectedAccountService.assertCallerCanConnectOrThrow({
connectionProviderId: connectionProvider.id,
- workspaceId,
- userWorkspaceId,
- reconnectingConnectedAccountId: args.reconnectingConnectedAccountId,
- });
-
- await this.validateCallerCanManageConnection({
workspaceId,
userWorkspaceId,
scope: connectionProvider.scope,
+ reconnectingConnectedAccountId:
+ authorizationArgs.reconnectingConnectedAccountId,
});
const { clientId } =
@@ -105,17 +68,10 @@ export class ConnectionProviderOAuthFlowService {
const codeVerifier = usePkce ? generatePkceVerifier() : null;
- const state = await this.signState({
- sub: connectionProvider.id,
- type: JwtTokenTypeEnum.APP_OAUTH_STATE,
- connectionProviderId: connectionProvider.id,
- workspaceId,
- userId,
- userWorkspaceId,
- scope: connectionProvider.scope,
- reconnectingConnectedAccountId: args.reconnectingConnectedAccountId,
- redirectLocation: args.redirectLocation,
+ const state = await this.authorizationStateService.sign({
+ ...authorizationArgs,
codeVerifier,
+ expiresIn: STATE_JWT_EXPIRES_IN,
});
const callbackUrl = buildAppOAuthCallbackUrl(this.getServerUrl());
@@ -143,8 +99,12 @@ export class ConnectionProviderOAuthFlowService {
return { authorizationUrl: authorizationUrl.toString() };
}
- async completeAuthorizationFlow(args: CallbackArgs): Promise<CallbackResult> {
- const statePayload = await this.verifyState(args.state);
+ async completeAuthorizationFlow(
+ callbackArgs: CallbackArgs,
+ ): Promise<CallbackResult> {
+ const statePayload = await this.authorizationStateService.verifyOrThrow(
+ callbackArgs.state,
+ );
const provider = await this.oauthProviderService.findOneByIdOrThrow({
id: statePayload.connectionProviderId,
@@ -153,20 +113,15 @@ export class ConnectionProviderOAuthFlowService {
assertOAuthProvider(provider);
- await this.assertReconnectTargetUsableByCallerOrThrow({
+ await this.connectedAccountService.assertCallerCanConnectOrThrow({
connectionProviderId: provider.id,
workspaceId: statePayload.workspaceId,
userWorkspaceId: statePayload.userWorkspaceId,
+ scope: statePayload.scope,
reconnectingConnectedAccountId:
statePayload.reconnectingConnectedAccountId,
});
- await this.validateCallerCanManageConnection({
- workspaceId: statePayload.workspaceId,
- userWorkspaceId: statePayload.userWorkspaceId,
- scope: statePayload.scope,
- });
-
const { clientId, clientSecret } =
await this.oauthProviderService.getClientCredentials(provider);
@@ -180,7 +135,7 @@ export class ConnectionProviderOAuthFlowService {
tokenEndpoint: provider.oauthConfig.tokenEndpoint,
clientId,
clientSecret,
- code: args.code,
+ code: callbackArgs.code,
redirectUri: callbackUrl,
codeVerifier: statePayload.codeVerifier,
contentType: provider.oauthConfig.tokenRequestContentType,
@@ -203,9 +158,21 @@ export class ConnectionProviderOAuthFlowService {
accessToken: tokenResponse.accessToken,
});
- const connectedAccount = await this.persistConnectedAccount({
+ const handle =
+ identifiedAccount?.handle ??
+ (await this.connectedAccountService.resolveHandle({
+ idToken: tokenResponse.idToken,
+ userId: statePayload.userId,
+ }));
+
+ const connectedAccount = await this.connectedAccountService.persist({
provider,
- tokenResponse,
+ credentials: {
+ accessToken: tokenResponse.accessToken,
+ refreshToken: tokenResponse.refreshToken,
+ scopes: tokenResponse.scopes ?? provider.oauthConfig.scopes,
+ },
+ handle,
identifiedAccount,
workspaceId: statePayload.workspaceId,
userId: statePayload.userId,
@@ -229,234 +196,7 @@ export class ConnectionProviderOAuthFlowService {
};
}
- private async validateCallerCanManageConnection({
- workspaceId,
- userWorkspaceId,
- scope,
- }: {
- workspaceId: string;
- userWorkspaceId: string;
- scope: ConnectedAccountScope;
- }): Promise<void> {
- await this.appConnectionAccessService.validateCallerCanManageConnection({
- isWorkspaceShared: scope === 'WORKSPACE',
- workspaceId,
- userWorkspaceId,
- });
- }
-
- private async assertReconnectTargetUsableByCallerOrThrow({
- connectionProviderId,
- workspaceId,
- userWorkspaceId,
- reconnectingConnectedAccountId,
- }: {
- connectionProviderId: string;
- workspaceId: string;
- userWorkspaceId: string;
- reconnectingConnectedAccountId: string | null;
- }): Promise<void> {
- if (!isDefined(reconnectingConnectedAccountId)) {
- return;
- }
-
- const reconnectTarget = await this.connectedAccountRepository.findOne({
- where: buildConnectedAccountUsableByCallerWhere({
- baseWhere: {
- id: reconnectingConnectedAccountId,
- workspaceId,
- connectionProviderId,
- },
- userWorkspaceId,
- }),
- });
-
- if (!isDefined(reconnectTarget)) {
- throw new ConnectionProviderException(
- `Cannot reconnect connectedAccount ${reconnectingConnectedAccountId}: not found in this workspace for the requested provider, or not usable by this member.`,
- ConnectionProviderExceptionCode.FORBIDDEN,
- );
- }
- }
-
- private async signState(payload: AppOAuthStateJwtPayload): Promise<string> {
- return this.jwtWrapperService.signAsyncOrThrow(payload, {
- expiresIn: STATE_JWT_EXPIRES_IN,
- });
- }
-
- async findErrorRedirectTargetFromState(state: string): Promise<{
- workspaceId: string;
- redirectLocation: string | null;
- } | null> {
- try {
- const { workspaceId, redirectLocation } = await this.verifyState(state);
-
- return { workspaceId, redirectLocation };
- } catch (error) {
- this.logger.warn(
- `Could not read the OAuth state for the error redirect: ${error instanceof Error ? error.message : String(error)}`,
- );
-
- return null;
- }
- }
-
- private async verifyState(state: string): Promise<AppOAuthStateJwtPayload> {
- try {
- const verified = (await this.jwtWrapperService.verifyJwtToken(
- state,
- )) as AppOAuthStateJwtPayload;
-
- if (verified.type !== JwtTokenTypeEnum.APP_OAUTH_STATE) {
- throw new Error('Wrong JWT type for OAuth state');
- }
-
- return verified;
- } catch (error) {
- this.logger.warn(
- `Rejected OAuth state: ${(error as Error).message ?? 'unknown reason'}`,
- );
-
- throw new ConnectionProviderException(
- 'OAuth state signature invalid or expired',
- ConnectionProviderExceptionCode.INVALID_STATE,
- );
- }
- }
-
private getServerUrl(): string {
return this.twentyConfigService.get('SERVER_URL');
}
-
- private async resolveConnectedAccountHandle({
- tokenResponse,
- userId,
- }: {
- tokenResponse: TokenExchangeResponse;
- userId: string;
- }): Promise<string> {
- const idTokenEmail = isDefined(tokenResponse.idToken)
- ? extractEmailFromIdTokenClaims(tokenResponse.idToken)
- : null;
-
- if (isDefined(idTokenEmail)) {
- return idTokenEmail;
- }
-
- const user = await this.userRepository.findOneBy({ id: userId });
-
- if (!isDefined(user)) {
- throw new ConnectionProviderException(
- 'User not found',
- ConnectionProviderExceptionCode.INVALID_STATE,
- );
- }
-
- return user.email;
- }
-
- private async persistConnectedAccount({
- provider,
- tokenResponse,
- identifiedAccount,
- workspaceId,
- userId,
- userWorkspaceId,
- scope,
- reconnectingConnectedAccountId,
- }: {
- provider: OAuthConnectionProvider;
- tokenResponse: TokenExchangeResponse;
- identifiedAccount: IdentifiedAccount | null;
- workspaceId: string;
- userId: string;
- userWorkspaceId: string;
- scope: ConnectedAccountScope;
- reconnectingConnectedAccountId: string | null;
- }): Promise<ConnectedAccountEntity> {
- const { encryptedAccessToken, encryptedRefreshToken } =
- this.connectedAccountTokenEncryptionService.encryptTokenPair({
- accessToken: tokenResponse.accessToken,
- refreshToken: isDefined(tokenResponse.refreshToken)
- ? tokenResponse.refreshToken
- : null,
- workspaceId,
- });
-
- const handle =
- identifiedAccount?.handle ??
- (await this.resolveConnectedAccountHandle({
- tokenResponse,
- userId,
- }));
-
- const sharedFields = {
- accessToken: encryptedAccessToken,
- refreshToken: encryptedRefreshToken,
- scopes: tokenResponse.scopes ?? provider.oauthConfig.scopes,
- lastCredentialsRefreshedAt: new Date(),
- authFailedAt: null,
- authFailedReason: null,
- archivedAt: null,
- scope,
- handle,
- externalAccountId: identifiedAccount?.externalAccountId ?? null,
- };
-
- if (isDefined(reconnectingConnectedAccountId)) {
- const reconnectTarget = {
- id: reconnectingConnectedAccountId,
- workspaceId,
- };
-
- // Compared and written in one statement so overlapping reconnects cannot pin different accounts.
- const updateResult = await this.connectedAccountRepository.update(
- isDefined(identifiedAccount)
- ? [
- { ...reconnectTarget, externalAccountId: IsNull() },
- {
- ...reconnectTarget,
- externalAccountId: identifiedAccount.externalAccountId,
- },
- ]
- : reconnectTarget,
- { ...sharedFields, userWorkspaceId },
- );
-
- const connectedAccount =
- await this.connectedAccountRepository.findOneByOrFail(reconnectTarget);
-
- if (updateResult.affected === 0 && isDefined(identifiedAccount)) {
- const authorizedAccountHandle =
- identifiedAccount.handle ?? identifiedAccount.externalAccountId;
-
- throw new ConnectionProviderException(
- `You authorized ${authorizedAccountHandle}, but this connection belongs to ${connectedAccount.handle}. Reconnect with ${connectedAccount.handle}, or add a new connection for ${authorizedAccountHandle}.`,
- ConnectionProviderExceptionCode.RECONNECT_ACCOUNT_MISMATCH,
- );
- }
-
- return connectedAccount;
- }
-
- const existingCount = await this.connectedAccountRepository.count({
- where: { connectionProviderId: provider.id, workspaceId },
- });
-
- const name = `${provider.displayName} #${existingCount + 1}`;
-
- const created = this.connectedAccountRepository.create({
- ...sharedFields,
- name,
- scope,
- provider: ConnectedAccountProvider.APP,
- workspaceId,
- applicationId: provider.applicationId,
- connectionProviderId: provider.id,
- userWorkspaceId,
- });
-
- return this.connectedAccountRepository.save(created);
- }
}
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth.controller.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth.controller.ts
index a0f1bcce156..1178bbbdf61 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth.controller.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth.controller.ts
@@ -1,19 +1,15 @@
import { Controller, Get, Logger, Query, Res, UseGuards } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
-import { isNonEmptyString } from '@sniptt/guards';
import { type Response } from 'express';
-import { SOURCE_LOCALE } from 'twenty-shared/translations';
-import { ApiPath, SettingsPath } from 'twenty-shared/types';
-import {
- getSettingsPath,
- isDefined,
- isSafeInternalPath,
-} from 'twenty-shared/utils';
+import { ApiPath } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
import { Repository } from 'typeorm';
-import { ConnectionProviderOAuthFlowService } from 'src/engine/core-modules/application/connection-provider/connection-provider-oauth-flow.service';
+import { ConnectionProviderCustomFlowService } from 'src/engine/core-modules/application/connection-provider/connection-provider-custom-flow.service';
import { ConnectionProviderExceptionCode } from 'src/engine/core-modules/application/connection-provider/connection-provider-exception-code.enum';
+import { ConnectionProviderFlowRedirectService } from 'src/engine/core-modules/application/connection-provider/connection-provider-flow-redirect.service';
+import { ConnectionProviderOAuthFlowService } from 'src/engine/core-modules/application/connection-provider/connection-provider-oauth-flow.service';
import { ConnectionProviderException } from 'src/engine/core-modules/application/connection-provider/connection-provider.exception';
import { ConnectionProviderService } from 'src/engine/core-modules/application/connection-provider/connection-provider.service';
import {
@@ -21,11 +17,6 @@ import {
AuthExceptionCode,
} from 'src/engine/core-modules/auth/auth.exception';
import { TransientTokenService } from 'src/engine/core-modules/auth/token/services/transient-token.service';
-import { parseRelativeUrl } from 'src/engine/core-modules/domain/domain-server-config/utils/parse-relative-url.util';
-import { WorkspaceDomainsService } from 'src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service';
-import { GuardRedirectService } from 'src/engine/core-modules/guard-redirect/services/guard-redirect.service';
-import { I18nService } from 'src/engine/core-modules/i18n/i18n.service';
-import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';
@@ -39,11 +30,9 @@ export class ConnectionProviderOAuthController {
constructor(
private readonly oauthProviderService: ConnectionProviderService,
private readonly oauthProviderFlowService: ConnectionProviderOAuthFlowService,
+ private readonly customFlowService: ConnectionProviderCustomFlowService,
+ private readonly flowRedirectService: ConnectionProviderFlowRedirectService,
private readonly transientTokenService: TransientTokenService,
- private readonly workspaceDomainsService: WorkspaceDomainsService,
- private readonly guardRedirectService: GuardRedirectService,
- private readonly twentyConfigService: TwentyConfigService,
- private readonly i18nService: I18nService,
@InjectRepository(WorkspaceEntity)
private readonly workspaceRepository: Repository<WorkspaceEntity>,
@InjectRepository(UserWorkspaceEntity)
@@ -118,16 +107,28 @@ export class ConnectionProviderOAuthController {
);
}
+ const authorizationArgs = {
+ connectionProvider: provider,
+ workspaceId,
+ userId,
+ userWorkspaceId: userWorkspace.id,
+ reconnectingConnectedAccountId: reconnectingConnectedAccountId ?? null,
+ redirectLocation: redirectLocation ?? null,
+ };
+
+ if (provider.type === 'custom') {
+ const { authorizationUrl } =
+ await this.customFlowService.startAuthorizationFlow(
+ authorizationArgs,
+ );
+
+ return res.redirect(authorizationUrl);
+ }
+
const { authorizationUrl } =
- await this.oauthProviderFlowService.startAuthorizationFlow({
- connectionProvider: provider,
- workspaceId,
- userId,
- userWorkspaceId: userWorkspace.id,
- reconnectingConnectedAccountId:
- reconnectingConnectedAccountId ?? null,
- redirectLocation: redirectLocation ?? null,
- });
+ await this.oauthProviderFlowService.startAuthorizationFlow(
+ authorizationArgs,
+ );
return res.redirect(authorizationUrl);
} catch (error) {
@@ -137,7 +138,7 @@ export class ConnectionProviderOAuthController {
error instanceof Error ? error.stack : undefined,
);
- return this.redirectToError({
+ return this.flowRedirectService.redirectToError({
res,
error,
workspace,
@@ -155,7 +156,7 @@ export class ConnectionProviderOAuthController {
@Res() res: Response,
) {
if (errorParam) {
- return this.redirectToErrorFromState({
+ return this.flowRedirectService.redirectToErrorFromState({
res,
state,
error: new Error(
@@ -165,7 +166,7 @@ export class ConnectionProviderOAuthController {
}
if (!code || !state) {
- return this.redirectToErrorFromState({
+ return this.flowRedirectService.redirectToErrorFromState({
res,
state,
error: new Error(
@@ -181,132 +182,18 @@ export class ConnectionProviderOAuthController {
state,
});
- const workspace = await this.workspaceRepository.findOneBy({
- id: workspaceId,
- });
-
- if (!workspace) {
- throw new ConnectionProviderException(
- `Workspace ${workspaceId} not found after OAuth callback`,
- ConnectionProviderExceptionCode.PROVIDER_NOT_FOUND,
- );
- }
-
- const hasRedirectLocation = isNonEmptyString(redirectLocation);
-
- const { pathname, searchParams, hash } = this.parseRedirectLocation({
+ return await this.flowRedirectService.redirectToConnectedApplication({
+ res,
+ workspaceId,
+ applicationId,
redirectLocation,
- fallbackPathname: getSettingsPath(SettingsPath.ApplicationDetail, {
- applicationId,
- }),
});
-
- const url = this.workspaceDomainsService.buildWorkspaceURL({
- workspace,
- pathname,
- searchParams,
- hash,
- });
-
- // Frontend tab list reads the URL hash to pick the active tab.
- if (!hasRedirectLocation) {
- url.hash = 'settings';
- }
-
- return res.redirect(url.toString());
} catch (error) {
- return this.redirectToErrorFromState({ res, state, error });
- }
- }
-
- private async redirectToErrorFromState({
- res,
- state,
- error,
- }: {
- res: Response;
- state: string | undefined;
- error: unknown;
- }) {
- const errorRedirectTarget = isNonEmptyString(state)
- ? await this.oauthProviderFlowService.findErrorRedirectTargetFromState(
- state,
- )
- : null;
-
- const workspace = isDefined(errorRedirectTarget)
- ? await this.workspaceRepository.findOneBy({
- id: errorRedirectTarget.workspaceId,
- })
- : null;
-
- return this.redirectToError({
- res,
- error,
- workspace,
- redirectLocation: errorRedirectTarget?.redirectLocation ?? null,
- });
- }
-
- private parseRedirectLocation({
- redirectLocation,
- fallbackPathname,
- }: {
- redirectLocation: string | null | undefined;
- fallbackPathname: string;
- }) {
- return parseRelativeUrl(
- isDefined(redirectLocation) && isSafeInternalPath(redirectLocation)
- ? redirectLocation
- : fallbackPathname,
- );
- }
-
- private redirectToError({
- res,
- error,
- workspace,
- redirectLocation,
- }: {
- res: Response;
- error: unknown;
- workspace: WorkspaceEntity | null;
- redirectLocation: string | null;
- }) {
- const { pathname, searchParams, hash } = this.parseRedirectLocation({
- redirectLocation,
- fallbackPathname: getSettingsPath(SettingsPath.Accounts),
- });
-
- return res.redirect(
- this.guardRedirectService.getRedirectErrorUrlAndCaptureExceptions({
- error: error instanceof Error ? error : new Error(String(error)),
- workspace: {
- id: workspace?.id,
- subdomain:
- workspace?.subdomain ??
- this.twentyConfigService.get('DEFAULT_SUBDOMAIN'),
- customDomain: workspace?.customDomain ?? null,
- isCustomDomainEnabled: workspace?.isCustomDomainEnabled ?? false,
- },
- pathname,
- searchParams,
- hash,
- errorMessage: this.getTokenExchangeFailureMessage(error),
- }),
- );
- }
-
- private getTokenExchangeFailureMessage(error: unknown): string | undefined {
- if (
- !(error instanceof ConnectionProviderException) ||
- error.code !== ConnectionProviderExceptionCode.TOKEN_EXCHANGE_FAILED
- ) {
- return undefined;
+ return this.flowRedirectService.redirectToErrorFromState({
+ res,
+ state,
+ error,
+ });
}
-
- return this.i18nService
- .getI18nInstance(SOURCE_LOCALE)
- ._(error.userFriendlyMessage);
}
}
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider.entity.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider.entity.ts
index 063e89a5217..f795691593a 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider.entity.ts
@@ -3,6 +3,7 @@ import {
type ConnectionProviderScope,
type ConnectionProviderType,
DEFAULT_CONNECTION_PROVIDER_SCOPE,
+ type StoredCustomConnectionProviderConfig,
type StoredOAuthConnectionProviderConfig,
} from 'twenty-shared/application';
import {
@@ -62,6 +63,13 @@ export class ConnectionProviderEntity
@Column({ nullable: true, type: 'jsonb' })
oauthConfig: StoredOAuthConnectionProviderConfig | null;
+ @Column({ nullable: true, type: 'jsonb' })
+ @WasIntroducedInUpgrade({
+ upgradeCommandName:
+ '2.52.0_AddCustomConfigToConnectionProviderFastInstanceCommand_1793032438836',
+ })
+ customConfig: StoredCustomConnectionProviderConfig | null;
+
@Column({ nullable: true, type: 'uuid' })
@WasIntroducedInUpgrade({
upgradeCommandName:
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider.exception.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider.exception.ts
index 5de4e49f566..2ef0426fa0a 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider.exception.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider.exception.ts
@@ -43,6 +43,14 @@ const getConnectionProviderExceptionUserFriendlyMessage = (
return msg`We could not identify the account you authorized. Please try again.`;
case ConnectionProviderExceptionCode.RECONNECT_ACCOUNT_MISMATCH:
return msg`You authorized a different account than the one this connection belongs to.`;
+ case ConnectionProviderExceptionCode.AUTHORIZE_LOGIC_FUNCTION_NOT_FOUND:
+ return msg`The logic function that starts the connection was not found.`;
+ case ConnectionProviderExceptionCode.AUTHORIZE_LOGIC_FUNCTION_FAILED:
+ return msg`We could not start the connection. Please try again.`;
+ case ConnectionProviderExceptionCode.CALLBACK_LOGIC_FUNCTION_NOT_FOUND:
+ return msg`The logic function that completes the connection was not found.`;
+ case ConnectionProviderExceptionCode.CALLBACK_LOGIC_FUNCTION_FAILED:
+ return msg`We could not complete the connection. Please try again.`;
default:
assertUnreachable(code);
}
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider.module.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider.module.ts
index 10e5ca6ec05..dae4e4c9bcf 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider.module.ts
@@ -3,6 +3,9 @@ import { TypeOrmModule } from '@nestjs/typeorm';
import { AppConnectionAccessService } from 'src/engine/core-modules/application/connection-provider/app-connection-access.service';
import { ApplicationConnectionProviderResolver } from 'src/engine/core-modules/application/connection-provider/application-connection-provider.resolver';
+import { ConnectionProviderAuthorizationStateService } from 'src/engine/core-modules/application/connection-provider/connection-provider-authorization-state.service';
+import { ConnectionProviderConnectedAccountService } from 'src/engine/core-modules/application/connection-provider/connection-provider-connected-account.service';
+import { ConnectionProviderCustomFlowService } from 'src/engine/core-modules/application/connection-provider/connection-provider-custom-flow.service';
import { ConnectionProviderEntity } from 'src/engine/core-modules/application/connection-provider/connection-provider.entity';
import { ConnectionProviderLifecycleHookService } from 'src/engine/core-modules/application/connection-provider/connection-provider-lifecycle-hook.service';
import { ConnectionProviderOAuthFlowService } from 'src/engine/core-modules/application/connection-provider/connection-provider-oauth-flow.service';
@@ -20,6 +23,7 @@ import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permi
import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
import { WorkspaceManyOrAllFlatEntityMapsCacheModule } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.module';
+import { CacheLockModule } from 'src/engine/core-modules/cache-lock/cache-lock.module';
import { ApplicationLookupModule } from 'src/engine/core-modules/application/application-lookup/application-lookup.module';
import { ApplicationRegistrationLookupModule } from 'src/engine/core-modules/application/application-registration/application-registration-lookup/application-registration-lookup.module';
@@ -35,6 +39,7 @@ import { ApplicationRegistrationLookupModule } from 'src/engine/core-modules/app
ConnectedAccountEntity,
UserEntity,
]),
+ CacheLockModule,
JwtModule,
SecretEncryptionModule,
SecureHttpClientModule,
@@ -47,14 +52,19 @@ import { ApplicationRegistrationLookupModule } from 'src/engine/core-modules/app
provideWorkspaceScopedRepository(ConnectionProviderEntity),
AppConnectionAccessService,
ConnectionProviderService,
+ ConnectionProviderAuthorizationStateService,
+ ConnectionProviderConnectedAccountService,
ConnectionProviderOAuthFlowService,
+ ConnectionProviderCustomFlowService,
ConnectionProviderLifecycleHookService,
ApplicationConnectionProviderResolver,
provideWorkspaceScopedRepository(ApplicationEntity),
],
exports: [
ConnectionProviderService,
+ ConnectionProviderAuthorizationStateService,
ConnectionProviderOAuthFlowService,
+ ConnectionProviderCustomFlowService,
ConnectionProviderLifecycleHookService,
],
})
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/dtos/app-connection.object.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/dtos/app-connection.object.ts
index f1aa890ca56..d25e0ef868d 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/dtos/app-connection.object.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/dtos/app-connection.object.ts
@@ -1,12 +1,18 @@
import { Field, ID, ObjectType } from '@nestjs/graphql';
-import { type AppConnection } from 'twenty-shared/application';
+import {
+ type AppConnection,
+ type ConnectionProviderType,
+} from 'twenty-shared/application';
import { type ConnectedAccountScope } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
import { ConnectedAccountScopeEnum } from 'src/engine/metadata-modules/connected-account/enums/connected-account-scope.enum';
@ObjectType('AppConnection')
-export class AppConnectionObjectDto implements AppConnection {
+export class AppConnectionObjectDto implements Omit<
+ AppConnection,
+ 'providerType' | 'accessToken'
+> {
@Field(() => ID)
id: string;
@@ -34,8 +40,11 @@ export class AppConnectionObjectDto implements AppConnection {
@Field(() => String, { nullable: true })
workspaceMemberId: string | null;
- @Field()
- accessToken: string;
+ @Field(() => String)
+ providerType: ConnectionProviderType;
+
+ @Field(() => String, { nullable: true })
+ accessToken: string | null;
@Field(() => [String])
scopes: string[];
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/services/application-connection-auth-failure.service.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/services/application-connection-auth-failure.service.ts
index bc2f8e4ee84..7eca520ff70 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/services/application-connection-auth-failure.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/services/application-connection-auth-failure.service.ts
@@ -67,7 +67,10 @@ export class ApplicationConnectionAuthFailureService {
? account.lastCredentialsRefreshedAt
: IsNull(),
},
- { authFailedAt: new Date(), authFailedReason: reason },
+ {
+ authFailedAt: () => 'COALESCE("authFailedAt", NOW())',
+ authFailedReason: reason,
+ },
);
if (updateResult.affected === 0) {
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/services/application-connections-list.service.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/services/application-connections-list.service.ts
index da771e10608..4a20377653c 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/services/application-connections-list.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/services/application-connections-list.service.ts
@@ -249,12 +249,7 @@ export class ApplicationConnectionsListService {
}
try {
- const encryptedTokens = await this.refreshTokensService.resolveTokens(
- account,
- workspaceId,
- );
-
- return {
+ const connectionFields = {
id: account.id,
providerName: provider.name,
name: account.name ?? account.handle,
@@ -264,14 +259,26 @@ export class ApplicationConnectionsListService {
visibility: LEGACY_CONNECTION_VISIBILITY_BY_SCOPE[account.scope],
userWorkspaceId: account.userWorkspaceId,
workspaceMemberId,
- accessToken: this.connectedAccountTokenEncryptionService.decrypt({
- ciphertext: encryptedTokens.accessToken,
- workspaceId,
- }),
scopes: account.scopes ?? provider.oauthConfig?.scopes ?? [],
authFailedAt: account.authFailedAt?.toISOString() ?? null,
authFailedReason: account.authFailedReason,
};
+
+ if (provider.type === 'custom') {
+ return {
+ ...connectionFields,
+ providerType: 'custom',
+ accessToken: isDefined(account.accessToken)
+ ? await this.decryptAccessToken({ account, workspaceId })
+ : null,
+ };
+ }
+
+ return {
+ ...connectionFields,
+ providerType: 'oauth',
+ accessToken: await this.decryptAccessToken({ account, workspaceId }),
+ };
} catch (error) {
this.logger.warn(
`Failed to refresh tokens for connection ${account.id}: ${(error as Error).message}`,
@@ -280,4 +287,22 @@ export class ApplicationConnectionsListService {
return null;
}
}
+
+ private async decryptAccessToken({
+ account,
+ workspaceId,
+ }: {
+ account: ConnectedAccountEntity;
+ workspaceId: string;
+ }): Promise<string> {
+ const encryptedTokens = await this.refreshTokensService.resolveTokens(
+ account,
+ workspaceId,
+ );
+
+ return this.connectedAccountTokenEncryptionService.decrypt({
+ ciphertext: encryptedTokens.accessToken,
+ workspaceId,
+ });
+ }
}
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/constants/connection-flow-logic-function-timeout-seconds.constant.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/constants/connection-flow-logic-function-timeout-seconds.constant.ts
new file mode 100644
index 00000000000..8f3a21c1136
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/constants/connection-flow-logic-function-timeout-seconds.constant.ts
@@ -0,0 +1 @@
+export const CONNECTION_FLOW_LOGIC_FUNCTION_TIMEOUT_SECONDS = 10;
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/constants/identify-account-timeout-seconds.constant.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/constants/identify-account-timeout-seconds.constant.ts
deleted file mode 100644
index 175deaf7e37..00000000000
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/constants/identify-account-timeout-seconds.constant.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-// identifyAccount runs inside the OAuth callback while the user waits on the redirect.
-export const IDENTIFY_ACCOUNT_TIMEOUT_SECONDS = 10;
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/filters/connection-provider-rest-api-exception.filter.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/filters/connection-provider-rest-api-exception.filter.ts
index a66df97b568..8af9587120e 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/filters/connection-provider-rest-api-exception.filter.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/filters/connection-provider-rest-api-exception.filter.ts
@@ -23,6 +23,8 @@ const connectionProviderExceptionCodeToHttpStatus = (
case ConnectionProviderExceptionCode.ON_CONNECT_LOGIC_FUNCTION_NOT_FOUND:
case ConnectionProviderExceptionCode.ON_DISCONNECT_LOGIC_FUNCTION_NOT_FOUND:
case ConnectionProviderExceptionCode.IDENTIFY_ACCOUNT_LOGIC_FUNCTION_NOT_FOUND:
+ case ConnectionProviderExceptionCode.AUTHORIZE_LOGIC_FUNCTION_NOT_FOUND:
+ case ConnectionProviderExceptionCode.CALLBACK_LOGIC_FUNCTION_NOT_FOUND:
return 404;
case ConnectionProviderExceptionCode.FORBIDDEN:
return 403;
@@ -37,6 +39,8 @@ const connectionProviderExceptionCodeToHttpStatus = (
case ConnectionProviderExceptionCode.REFRESH_FAILED:
case ConnectionProviderExceptionCode.ON_DISCONNECT_LOGIC_FUNCTION_FAILED:
case ConnectionProviderExceptionCode.IDENTIFY_ACCOUNT_LOGIC_FUNCTION_FAILED:
+ case ConnectionProviderExceptionCode.AUTHORIZE_LOGIC_FUNCTION_FAILED:
+ case ConnectionProviderExceptionCode.CALLBACK_LOGIC_FUNCTION_FAILED:
return 500;
default:
return assertUnreachable(code);
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/types/connection-authorization-args.type.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/types/connection-authorization-args.type.ts
new file mode 100644
index 00000000000..d76b256cc43
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/types/connection-authorization-args.type.ts
@@ -0,0 +1,10 @@
+import { type ConnectionProviderEntity } from 'src/engine/core-modules/application/connection-provider/connection-provider.entity';
+
+export type ConnectionAuthorizationArgs = {
+ connectionProvider: ConnectionProviderEntity;
+ workspaceId: string;
+ userId: string;
+ userWorkspaceId: string;
+ reconnectingConnectedAccountId: string | null;
+ redirectLocation: string | null;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/__tests__/parse-authorize-connection-result.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/__tests__/parse-authorize-connection-result.util.spec.ts
new file mode 100644
index 00000000000..2ab10dd89a2
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/__tests__/parse-authorize-connection-result.util.spec.ts
@@ -0,0 +1,27 @@
+import { parseAuthorizeConnectionResult } from 'src/engine/core-modules/application/connection-provider/utils/parse-authorize-connection-result.util';
+
+describe('parseAuthorizeConnectionResult', () => {
+ it('returns the trimmed authorization URL', () => {
+ expect(
+ parseAuthorizeConnectionResult({
+ authorizationUrl: ' https://account.example.com/connect?link=abc ',
+ }),
+ ).toEqual({
+ isValid: true,
+ authorizationUrl: 'https://account.example.com/connect?link=abc',
+ });
+ });
+
+ it.each([
+ ['a missing result', undefined],
+ ['a null result', null],
+ ['a missing URL', {}],
+ ['a relative URL', { authorizationUrl: '/connect' }],
+ ['a non-http URL', { authorizationUrl: 'javascript:alert(1)' }],
+ ])('rejects %s', (_label, data) => {
+ expect(parseAuthorizeConnectionResult(data)).toEqual({
+ isValid: false,
+ reason: expect.any(String),
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/__tests__/parse-connection-callback-result.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/__tests__/parse-connection-callback-result.util.spec.ts
new file mode 100644
index 00000000000..3dfa636361f
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/__tests__/parse-connection-callback-result.util.spec.ts
@@ -0,0 +1,59 @@
+import { parseConnectionCallbackResult } from 'src/engine/core-modules/application/connection-provider/utils/parse-connection-callback-result.util';
+import { EXTERNAL_ACCOUNT_ID_MAX_LENGTH } from 'src/engine/metadata-modules/connected-account/constants/external-account-id-max-length.constant';
+
+describe('parseConnectionCallbackResult', () => {
+ it('returns the trimmed id and handle with the access token', () => {
+ expect(
+ parseConnectionCallbackResult({
+ externalAccountId: ' account-a ',
+ handle: ' Jane Doe ',
+ accessToken: 'token-a',
+ }),
+ ).toEqual({
+ isValid: true,
+ connectedAccount: {
+ externalAccountId: 'account-a',
+ handle: 'Jane Doe',
+ accessToken: 'token-a',
+ },
+ });
+ });
+
+ it('leaves out the handle and access token when they are absent or null', () => {
+ expect(
+ parseConnectionCallbackResult({
+ externalAccountId: 'account-a',
+ handle: null,
+ }),
+ ).toEqual({
+ isValid: true,
+ connectedAccount: { externalAccountId: 'account-a' },
+ });
+ });
+
+ it.each([null, undefined])(
+ 'treats %s as a request without an account to save',
+ (data) => {
+ expect(parseConnectionCallbackResult(data)).toEqual({
+ isValid: true,
+ connectedAccount: null,
+ });
+ },
+ );
+
+ it.each([
+ ['a missing id', { handle: 'Jane Doe' }],
+ ['a null id', { externalAccountId: null }],
+ ['a blank id', { externalAccountId: ' ' }],
+ [
+ 'an id over the maximum length',
+ { externalAccountId: 'a'.repeat(EXTERNAL_ACCOUNT_ID_MAX_LENGTH + 1) },
+ ],
+ ['an empty access token', { externalAccountId: 'a', accessToken: '' }],
+ ])('rejects %s', (_label, data) => {
+ expect(parseConnectionCallbackResult(data)).toEqual({
+ isValid: false,
+ reason: expect.any(String),
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/__tests__/was-state-issued-before-account-change.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/__tests__/was-state-issued-before-account-change.util.spec.ts
new file mode 100644
index 00000000000..55a220af306
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/__tests__/was-state-issued-before-account-change.util.spec.ts
@@ -0,0 +1,59 @@
+import { wasStateIssuedBeforeAccountChange } from 'src/engine/core-modules/application/connection-provider/utils/was-state-issued-before-account-change.util';
+
+const ISSUED_AT_SECONDS = 1_800_000_000;
+
+describe('wasStateIssuedBeforeAccountChange', () => {
+ it('is true when the connection was archived after the state was issued', () => {
+ expect(
+ wasStateIssuedBeforeAccountChange({
+ stateIssuedAtSeconds: ISSUED_AT_SECONDS,
+ connectedAccount: {
+ archivedAt: new Date((ISSUED_AT_SECONDS + 60) * 1000),
+ authFailedAt: null,
+ },
+ }),
+ ).toBe(true);
+ });
+
+ it('is true when the connection failed after the state was issued', () => {
+ expect(
+ wasStateIssuedBeforeAccountChange({
+ stateIssuedAtSeconds: ISSUED_AT_SECONDS,
+ connectedAccount: {
+ archivedAt: null,
+ authFailedAt: new Date((ISSUED_AT_SECONDS + 60) * 1000),
+ },
+ }),
+ ).toBe(true);
+ });
+
+ it('is false for a state issued after the change, or in the same second', () => {
+ expect(
+ wasStateIssuedBeforeAccountChange({
+ stateIssuedAtSeconds: ISSUED_AT_SECONDS,
+ connectedAccount: {
+ archivedAt: new Date((ISSUED_AT_SECONDS - 60) * 1000),
+ authFailedAt: new Date(ISSUED_AT_SECONDS * 1000 + 500),
+ },
+ }),
+ ).toBe(false);
+ });
+
+ it('is false for a healthy connection or a state without iat', () => {
+ expect(
+ wasStateIssuedBeforeAccountChange({
+ stateIssuedAtSeconds: ISSUED_AT_SECONDS,
+ connectedAccount: { archivedAt: null, authFailedAt: null },
+ }),
+ ).toBe(false);
+ expect(
+ wasStateIssuedBeforeAccountChange({
+ stateIssuedAtSeconds: undefined,
+ connectedAccount: {
+ archivedAt: new Date((ISSUED_AT_SECONDS + 60) * 1000),
+ authFailedAt: null,
+ },
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/assert-custom-provider.util.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/assert-custom-provider.util.ts
new file mode 100644
index 00000000000..e87bd867ca2
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/assert-custom-provider.util.ts
@@ -0,0 +1,22 @@
+import { type StoredCustomConnectionProviderConfig } from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type ConnectionProviderEntity } from 'src/engine/core-modules/application/connection-provider/connection-provider.entity';
+import { ConnectionProviderExceptionCode } from 'src/engine/core-modules/application/connection-provider/connection-provider-exception-code.enum';
+import { ConnectionProviderException } from 'src/engine/core-modules/application/connection-provider/connection-provider.exception';
+
+export type CustomConnectionProvider = ConnectionProviderEntity & {
+ type: 'custom';
+ customConfig: StoredCustomConnectionProviderConfig;
+};
+
+export function assertCustomProvider(
+ provider: ConnectionProviderEntity,
+): asserts provider is CustomConnectionProvider {
+ if (provider.type !== 'custom' || !isDefined(provider.customConfig)) {
+ throw new ConnectionProviderException(
+ `Connection provider "${provider.name}" (id ${provider.id}) is not custom-typed or has no customConfig`,
+ ConnectionProviderExceptionCode.INVALID_REQUEST,
+ );
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/build-custom-connection-callback-url.util.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/build-custom-connection-callback-url.util.ts
new file mode 100644
index 00000000000..781202b415e
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/build-custom-connection-callback-url.util.ts
@@ -0,0 +1,18 @@
+import { ApiPath } from 'twenty-shared/types';
+
+export const buildAppCustomConnectionCallbackUrl = ({
+ serverUrl,
+ state,
+}: {
+ serverUrl: string;
+ state: string;
+}): string => {
+ const callbackUrl = new URL(
+ `/${ApiPath.Auth}/apps/custom/callback`,
+ serverUrl,
+ );
+
+ callbackUrl.searchParams.set('state', state);
+
+ return callbackUrl.toString();
+};
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/connection-provider-graphql-api-exception-handler.util.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/connection-provider-graphql-api-exception-handler.util.ts
index ddc5be95088..c251bac4324 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/connection-provider-graphql-api-exception-handler.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/connection-provider-graphql-api-exception-handler.util.ts
@@ -18,6 +18,8 @@ export const connectionProviderGraphqlApiExceptionHandler = (error: Error) => {
case ConnectionProviderExceptionCode.ON_CONNECT_LOGIC_FUNCTION_NOT_FOUND:
case ConnectionProviderExceptionCode.ON_DISCONNECT_LOGIC_FUNCTION_NOT_FOUND:
case ConnectionProviderExceptionCode.IDENTIFY_ACCOUNT_LOGIC_FUNCTION_NOT_FOUND:
+ case ConnectionProviderExceptionCode.AUTHORIZE_LOGIC_FUNCTION_NOT_FOUND:
+ case ConnectionProviderExceptionCode.CALLBACK_LOGIC_FUNCTION_NOT_FOUND:
throw new NotFoundError(error);
case ConnectionProviderExceptionCode.FORBIDDEN:
throw new ForbiddenError(error);
@@ -32,6 +34,8 @@ export const connectionProviderGraphqlApiExceptionHandler = (error: Error) => {
case ConnectionProviderExceptionCode.REFRESH_FAILED:
case ConnectionProviderExceptionCode.ON_DISCONNECT_LOGIC_FUNCTION_FAILED:
case ConnectionProviderExceptionCode.IDENTIFY_ACCOUNT_LOGIC_FUNCTION_FAILED:
+ case ConnectionProviderExceptionCode.AUTHORIZE_LOGIC_FUNCTION_FAILED:
+ case ConnectionProviderExceptionCode.CALLBACK_LOGIC_FUNCTION_FAILED:
throw new InternalServerError(error);
default: {
return assertUnreachable(error.code);
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/parse-authorize-connection-result.util.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/parse-authorize-connection-result.util.ts
new file mode 100644
index 00000000000..b0e0192c1e5
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/parse-authorize-connection-result.util.ts
@@ -0,0 +1,32 @@
+import { z } from 'zod';
+
+import { formatLogicFunctionResultIssues } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/format-logic-function-result-issues.util';
+
+const authorizeConnectionResultSchema = z.object({
+ authorizationUrl: z
+ .string()
+ .trim()
+ .url()
+ .refine((value) => /^https?:\/\//i.test(value), {
+ message: 'must be an http(s) URL',
+ }),
+});
+
+type ParseAuthorizeConnectionResultOutcome =
+ | { isValid: true; authorizationUrl: string }
+ | { isValid: false; reason: string };
+
+export const parseAuthorizeConnectionResult = (
+ data: unknown,
+): ParseAuthorizeConnectionResultOutcome => {
+ const parsed = authorizeConnectionResultSchema.safeParse(data);
+
+ if (!parsed.success) {
+ return {
+ isValid: false,
+ reason: formatLogicFunctionResultIssues(parsed.error),
+ };
+ }
+
+ return { isValid: true, authorizationUrl: parsed.data.authorizationUrl };
+};
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/parse-connection-callback-result.util.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/parse-connection-callback-result.util.ts
new file mode 100644
index 00000000000..26d40312144
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/parse-connection-callback-result.util.ts
@@ -0,0 +1,60 @@
+import { type ConnectedAccountFromCallback } from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+import { z } from 'zod';
+
+import {
+ type PlaintextString,
+ plaintextStringSchema,
+} from 'src/engine/core-modules/secret-encryption/branded-strings/plaintext-string.type';
+import { formatLogicFunctionResultIssues } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/format-logic-function-result-issues.util';
+import { EXTERNAL_ACCOUNT_ID_MAX_LENGTH } from 'src/engine/metadata-modules/connected-account/constants/external-account-id-max-length.constant';
+
+export type ParsedConnectedAccountFromCallback = Omit<
+ ConnectedAccountFromCallback,
+ 'accessToken'
+> & { accessToken?: PlaintextString };
+
+const connectedAccountFromCallbackSchema = z.object({
+ externalAccountId: z
+ .string()
+ .trim()
+ .min(1)
+ .max(EXTERNAL_ACCOUNT_ID_MAX_LENGTH),
+ handle: z.string().trim().min(1).nullish(),
+ accessToken: z.string().min(1).pipe(plaintextStringSchema).nullish(),
+});
+
+type ParseConnectionCallbackResultOutcome =
+ | {
+ isValid: true;
+ connectedAccount: ParsedConnectedAccountFromCallback | null;
+ }
+ | { isValid: false; reason: string };
+
+export const parseConnectionCallbackResult = (
+ data: unknown,
+): ParseConnectionCallbackResultOutcome => {
+ if (!isDefined(data)) {
+ return { isValid: true, connectedAccount: null };
+ }
+
+ const parsed = connectedAccountFromCallbackSchema.safeParse(data);
+
+ if (!parsed.success) {
+ return {
+ isValid: false,
+ reason: formatLogicFunctionResultIssues(parsed.error),
+ };
+ }
+
+ const { externalAccountId, handle, accessToken } = parsed.data;
+
+ return {
+ isValid: true,
+ connectedAccount: {
+ externalAccountId,
+ ...(isDefined(handle) ? { handle } : {}),
+ ...(isDefined(accessToken) ? { accessToken } : {}),
+ },
+ };
+};
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/parse-identify-account-result.util.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/parse-identify-account-result.util.ts
index e1a8a9f191f..44434291571 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/parse-identify-account-result.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/parse-identify-account-result.util.ts
@@ -2,6 +2,7 @@ import { type IdentifiedAccount } from 'twenty-shared/application';
import { isDefined } from 'twenty-shared/utils';
import { z } from 'zod';
+import { formatLogicFunctionResultIssues } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/format-logic-function-result-issues.util';
import { EXTERNAL_ACCOUNT_ID_MAX_LENGTH } from 'src/engine/metadata-modules/connected-account/constants/external-account-id-max-length.constant';
const identifyAccountResultSchema = z.object({
@@ -26,9 +27,7 @@ export const parseIdentifyAccountResult = (
if (!parsed.success) {
return {
isValid: false,
- reason: parsed.error.issues
- .map((issue) => `${issue.path.join('.') || 'result'}: ${issue.message}`)
- .join('; '),
+ reason: formatLogicFunctionResultIssues(parsed.error),
};
}
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/was-state-issued-before-account-change.util.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/was-state-issued-before-account-change.util.ts
new file mode 100644
index 00000000000..bf6ec5f403b
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/was-state-issued-before-account-change.util.ts
@@ -0,0 +1,23 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
+
+export const wasStateIssuedBeforeAccountChange = ({
+ stateIssuedAtSeconds,
+ connectedAccount,
+}: {
+ stateIssuedAtSeconds: number | undefined;
+ connectedAccount: Pick<ConnectedAccountEntity, 'archivedAt' | 'authFailedAt'>;
+}): boolean => {
+ if (!isDefined(stateIssuedAtSeconds)) {
+ return false;
+ }
+
+ const firstMillisecondAfterIssuance = (stateIssuedAtSeconds + 1) * 1000;
+
+ return [connectedAccount.archivedAt, connectedAccount.authFailedAt].some(
+ (changedAt) =>
+ isDefined(changedAt) &&
+ new Date(changedAt).getTime() >= firstMillisecondAfterIssuance,
+ );
+};
diff --git a/packages/twenty-server/src/engine/core-modules/auth/auth.module.ts b/packages/twenty-server/src/engine/core-modules/auth/auth.module.ts
index 3edafc7b455..630c4b3eb7a 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/auth.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/auth.module.ts
@@ -5,6 +5,8 @@ import { ApiKeyModule } from 'src/engine/core-modules/api-key/api-key.module';
import { AppTokenEntity } from 'src/engine/core-modules/app-token/app-token.entity';
import { ApplicationRegistrationModule } from 'src/engine/core-modules/application/application-registration/application-registration.module';
import { ApplicationModule } from 'src/engine/core-modules/application/application.module';
+import { ConnectionProviderCustomController } from 'src/engine/core-modules/application/connection-provider/connection-provider-custom.controller';
+import { ConnectionProviderFlowRedirectService } from 'src/engine/core-modules/application/connection-provider/connection-provider-flow-redirect.service';
import { ConnectionProviderOAuthController } from 'src/engine/core-modules/application/connection-provider/connection-provider-oauth.controller';
import { ConnectionProviderModule } from 'src/engine/core-modules/application/connection-provider/connection-provider.module';
import { ApplicationConnectionsModule } from 'src/engine/core-modules/application/connection-provider/connections/application-connections.module';
@@ -131,9 +133,11 @@ import { AuthService } from './services/auth.service';
OAuthPropagatorController,
SsoAuthController,
ConnectionProviderOAuthController,
+ ConnectionProviderCustomController,
],
providers: [
SignInUpService,
+ ConnectionProviderFlowRedirectService,
AuthService,
SamlAuthStrategy,
AuthResolver,
diff --git a/packages/twenty-server/src/engine/core-modules/auth/types/app-oauth-state-jwt-payload.type.ts b/packages/twenty-server/src/engine/core-modules/auth/types/app-oauth-state-jwt-payload.type.ts
index 403199b595a..6b8df5c5a92 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/types/app-oauth-state-jwt-payload.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/types/app-oauth-state-jwt-payload.type.ts
@@ -14,4 +14,5 @@ export type AppOAuthStateJwtPayload = CommonPropertiesJwtPayload & {
reconnectingConnectedAccountId: string | null;
redirectLocation: string | null;
codeVerifier: string | null;
+ iat?: number;
};
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/filters/logic-function-execution-rest-api-exception.filter.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/filters/logic-function-execution-rest-api-exception.filter.ts
new file mode 100644
index 00000000000..993cba55c73
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/filters/logic-function-execution-rest-api-exception.filter.ts
@@ -0,0 +1,34 @@
+import {
+ type ArgumentsHost,
+ Catch,
+ type ExceptionFilter,
+ Injectable,
+} from '@nestjs/common';
+
+import { type Response } from 'express';
+
+import { HttpExceptionHandlerService } from 'src/engine/core-modules/exception-handler/http-exception-handler.service';
+import { LogicFunctionExecutionException } from 'src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service';
+import { getLogicFunctionExceptionHttpStatus } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/get-logic-function-exception-http-status.util';
+import { LogicFunctionException } from 'src/engine/metadata-modules/logic-function/logic-function.exception';
+
+@Injectable()
+@Catch(LogicFunctionException, LogicFunctionExecutionException)
+export class LogicFunctionExecutionRestApiExceptionFilter implements ExceptionFilter {
+ constructor(
+ private readonly httpExceptionHandlerService: HttpExceptionHandlerService,
+ ) {}
+
+ catch(
+ exception: LogicFunctionException | LogicFunctionExecutionException,
+ host: ArgumentsHost,
+ ) {
+ const response = host.switchToHttp().getResponse<Response>();
+
+ return this.httpExceptionHandlerService.handleError(
+ exception,
+ response,
+ getLogicFunctionExceptionHttpStatus(exception),
+ );
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
index 86498773266..a25abd29d64 100644
--- a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service.ts
@@ -123,6 +123,31 @@ export class LogicFunctionExecutorService {
private readonly applicationRegistrationVariableRepository: Repository<ApplicationRegistrationVariableEntity>,
) {}
+ async executeOrThrow({
+ toException,
+ ...executeArgs
+ }: Parameters<LogicFunctionExecutorService['execute']>[0] & {
+ toException: (reason: string) => CustomException;
+ }): Promise<LogicFunctionExecuteResult['data']> {
+ const executionResult = await this.execute(executeArgs).catch(
+ (error: unknown) => {
+ if (error instanceof CustomException) {
+ throw error;
+ }
+
+ throw toException(
+ `could not be executed: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ },
+ );
+
+ if (isDefined(executionResult.error)) {
+ throw toException(`failed: ${executionResult.error.errorMessage}`);
+ }
+
+ return executionResult.data;
+ }
+
async execute({
logicFunctionId,
workspaceId,
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/__tests__/get-logic-function-exception-http-status.util.spec.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/__tests__/get-logic-function-exception-http-status.util.spec.ts
new file mode 100644
index 00000000000..1baeceaf096
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/__tests__/get-logic-function-exception-http-status.util.spec.ts
@@ -0,0 +1,44 @@
+import {
+ LogicFunctionExecutionException,
+ LogicFunctionExecutionExceptionCode,
+} from 'src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service';
+import { getLogicFunctionExceptionHttpStatus } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/get-logic-function-exception-http-status.util';
+import {
+ LogicFunctionException,
+ LogicFunctionExceptionCode,
+} from 'src/engine/metadata-modules/logic-function/logic-function.exception';
+
+describe('getLogicFunctionExceptionHttpStatus', () => {
+ it.each([
+ [
+ new LogicFunctionExecutionException(
+ 'rate limited',
+ LogicFunctionExecutionExceptionCode.RATE_LIMIT_EXCEEDED,
+ ),
+ 429,
+ ],
+ [
+ new LogicFunctionExecutionException(
+ 'missing',
+ LogicFunctionExecutionExceptionCode.LOGIC_FUNCTION_NOT_FOUND,
+ ),
+ 404,
+ ],
+ [
+ new LogicFunctionException(
+ 'stopped',
+ LogicFunctionExceptionCode.LOGIC_FUNCTION_DISABLED,
+ ),
+ 403,
+ ],
+ [
+ new LogicFunctionException(
+ 'platform',
+ LogicFunctionExceptionCode.LOGIC_FUNCTION_PLATFORM_EXECUTION_ERROR,
+ ),
+ 500,
+ ],
+ ])('maps %s to %i', (exception, expectedStatus) => {
+ expect(getLogicFunctionExceptionHttpStatus(exception)).toBe(expectedStatus);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/format-logic-function-result-issues.util.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/format-logic-function-result-issues.util.ts
new file mode 100644
index 00000000000..15dc54a70b2
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/format-logic-function-result-issues.util.ts
@@ -0,0 +1,6 @@
+import { type z } from 'zod';
+
+export const formatLogicFunctionResultIssues = (error: z.ZodError): string =>
+ error.issues
+ .map((issue) => `${issue.path.join('.') || 'result'}: ${issue.message}`)
+ .join('; ');
diff --git a/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/get-logic-function-exception-http-status.util.ts b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/get-logic-function-exception-http-status.util.ts
new file mode 100644
index 00000000000..3ef9a3060b2
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/logic-function/logic-function-executor/utils/get-logic-function-exception-http-status.util.ts
@@ -0,0 +1,36 @@
+import { assertUnreachable } from 'twenty-shared/utils';
+
+import {
+ LogicFunctionExecutionException,
+ LogicFunctionExecutionExceptionCode,
+} from 'src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service';
+import {
+ type LogicFunctionException,
+ LogicFunctionExceptionCode,
+} from 'src/engine/metadata-modules/logic-function/logic-function.exception';
+
+export const getLogicFunctionExceptionHttpStatus = (
+ exception: LogicFunctionException | LogicFunctionExecutionException,
+): number => {
+ if (exception instanceof LogicFunctionExecutionException) {
+ const { code } = exception;
+
+ switch (code) {
+ case LogicFunctionExecutionExceptionCode.LOGIC_FUNCTION_NOT_FOUND:
+ return 404;
+ case LogicFunctionExecutionExceptionCode.RATE_LIMIT_EXCEEDED:
+ return 429;
+ default:
+ return assertUnreachable(code);
+ }
+ }
+
+ switch (exception.code) {
+ case LogicFunctionExceptionCode.LOGIC_FUNCTION_NOT_FOUND:
+ return 404;
+ case LogicFunctionExceptionCode.LOGIC_FUNCTION_DISABLED:
+ return 403;
+ default:
+ return 500;
+ }
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/__tests__/__snapshots__/all-universal-flat-entity-properties-to-compare-and-stringify.constant.spec.ts.snap b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/__tests__/__snapshots__/all-universal-flat-entity-properties-to-compare-and-stringify.constant.spec.ts.snap
index 5e6ab98900a..8198853c7dd 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/__tests__/__snapshots__/all-universal-flat-entity-properties-to-compare-and-stringify.constant.spec.ts.snap
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/__tests__/__snapshots__/all-universal-flat-entity-properties-to-compare-and-stringify.constant.spec.ts.snap
@@ -85,12 +85,14 @@ exports[`ALL_UNIVERSAL_FLAT_ENTITY_PROPERTIES_TO_COMPARE_AND_STRINGIFY should ma
"type",
"scope",
"oauthConfig",
+ "customConfig",
"identifyAccountLogicFunctionUniversalIdentifier",
"onConnectLogicFunctionUniversalIdentifier",
"onDisconnectLogicFunctionUniversalIdentifier",
],
"propertiesToStringify": [
"oauthConfig",
+ "customConfig",
],
},
"fieldMetadata": {
@@ -185,6 +187,15 @@ exports[`ALL_UNIVERSAL_FLAT_ENTITY_PROPERTIES_TO_COMPARE_AND_STRINGIFY should ma
"workflowActionTriggerSettings",
],
},
+ "messagingProvider": {
+ "propertiesToCompare": [
+ "name",
+ "displayName",
+ "connectionProviderUniversalIdentifier",
+ "sendMessageLogicFunctionUniversalIdentifier",
+ ],
+ "propertiesToStringify": [],
+ },
"navigationMenuItem": {
"propertiesToCompare": [
"type",
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/__tests__/__snapshots__/overridable-and-translatable-properties.constant.spec.ts.snap b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/__tests__/__snapshots__/overridable-and-translatable-properties.constant.spec.ts.snap
index 7856b575d90..8c92c040522 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/__tests__/__snapshots__/overridable-and-translatable-properties.constant.spec.ts.snap
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/__tests__/__snapshots__/overridable-and-translatable-properties.constant.spec.ts.snap
@@ -30,6 +30,7 @@ exports[`registry-derived override property maps derives the overridable propert
"frontComponent": [],
"index": [],
"logicFunction": [],
+ "messagingProvider": [],
"navigationMenuItem": [],
"objectMetadata": [
"openRecordIn",
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-entity-properties-configuration-by-metadata-name.constant.ts b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-entity-properties-configuration-by-metadata-name.constant.ts
index 6f42a61a19a..f59fa7b1b30 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-entity-properties-configuration-by-metadata-name.constant.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-entity-properties-configuration-by-metadata-name.constant.ts
@@ -1932,6 +1932,11 @@ export const ALL_ENTITY_PROPERTIES_CONFIGURATION_BY_METADATA_NAME = {
toStringify: true,
universalProperty: undefined,
},
+ customConfig: {
+ toCompare: true,
+ toStringify: true,
+ universalProperty: undefined,
+ },
identifyAccountLogicFunctionUniversalIdentifier: {
toCompare: true,
toStringify: false,
@@ -1958,6 +1963,34 @@ export const ALL_ENTITY_PROPERTIES_CONFIGURATION_BY_METADATA_NAME = {
universalProperty: undefined,
},
},
+ messagingProvider: {
+ name: { toCompare: true, toStringify: false, universalProperty: undefined },
+ displayName: {
+ toCompare: true,
+ toStringify: false,
+ universalProperty: undefined,
+ },
+ connectionProviderUniversalIdentifier: {
+ toCompare: true,
+ toStringify: false,
+ universalProperty: undefined,
+ },
+ sendMessageLogicFunctionUniversalIdentifier: {
+ toCompare: true,
+ toStringify: false,
+ universalProperty: undefined,
+ },
+ createdAt: {
+ toCompare: false,
+ toStringify: false,
+ universalProperty: undefined,
+ },
+ updatedAt: {
+ toCompare: false,
+ toStringify: false,
+ universalProperty: undefined,
+ },
+ },
searchFieldMetadata: {
isSystemSideEffect: {
toCompare: false,
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-many-to-one-metadata-foreign-key.constant.ts b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-many-to-one-metadata-foreign-key.constant.ts
index ecfb77cbb1e..9e9d575fa21 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-many-to-one-metadata-foreign-key.constant.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-many-to-one-metadata-foreign-key.constant.ts
@@ -317,6 +317,10 @@ export const ALL_MANY_TO_ONE_METADATA_FOREIGN_KEY = {
workspace: null,
application: null,
},
+ messagingProvider: {
+ workspace: null,
+ application: null,
+ },
timelineActivityType: {
workspace: null,
application: null,
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-many-to-one-metadata-relations.constant.ts b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-many-to-one-metadata-relations.constant.ts
index 4ed5da1e4ef..a2eb8e40567 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-many-to-one-metadata-relations.constant.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-many-to-one-metadata-relations.constant.ts
@@ -561,6 +561,10 @@ export const ALL_MANY_TO_ONE_METADATA_RELATIONS = {
workspace: null,
application: null,
},
+ messagingProvider: {
+ workspace: null,
+ application: null,
+ },
timelineActivityType: {
workspace: null,
application: null,
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-metadata-entity-by-metadata-name.constant.ts b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-metadata-entity-by-metadata-name.constant.ts
index ed8b92c5476..cdd4692ffe4 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-metadata-entity-by-metadata-name.constant.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-metadata-entity-by-metadata-name.constant.ts
@@ -6,6 +6,7 @@ import { type AllMetadataName } from 'twenty-shared/metadata';
import { type EntityTarget, type ObjectLiteral } from 'typeorm';
import { ConnectionProviderEntity } from 'src/engine/core-modules/application/connection-provider/connection-provider.entity';
+import { MessagingProviderEntity } from 'src/engine/metadata-modules/messaging-provider/entities/messaging-provider.entity';
import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';
import { ApplicationVariableEntity } from 'src/engine/core-modules/application/application-variable/application-variable.entity';
import { CommandMenuItemEntity } from 'src/engine/metadata-modules/command-menu-item/entities/command-menu-item.entity';
@@ -71,6 +72,7 @@ export const ALL_METADATA_ENTITY_BY_METADATA_NAME = {
applicationVariable: ApplicationVariableEntity,
viewSort: ViewSortEntity,
connectionProvider: ConnectionProviderEntity,
+ messagingProvider: MessagingProviderEntity,
searchFieldMetadata: SearchFieldMetadataEntity,
timelineActivityType: TimelineActivityTypeEntity,
settingsMenuItem: SettingsMenuItemEntity,
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-metadata-required-metadata-for-validation.constant.ts b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-metadata-required-metadata-for-validation.constant.ts
index aa458f64237..8ff4861245f 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-metadata-required-metadata-for-validation.constant.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-metadata-required-metadata-for-validation.constant.ts
@@ -123,6 +123,10 @@ export const ALL_METADATA_REQUIRED_METADATA_FOR_VALIDATION = {
webhook: {},
applicationVariable: {},
connectionProvider: {},
+ messagingProvider: {
+ connectionProvider: true,
+ logicFunction: true,
+ },
searchFieldMetadata: {
objectMetadata: true,
fieldMetadata: true,
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-metadata-serialized-relation.constant.ts b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-metadata-serialized-relation.constant.ts
index f57fae2680f..d7c3c345089 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-metadata-serialized-relation.constant.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-metadata-serialized-relation.constant.ts
@@ -55,6 +55,7 @@ export const ALL_METADATA_SERIALIZED_RELATION = {
webhook: {},
applicationVariable: {},
connectionProvider: {},
+ messagingProvider: {},
timelineActivityType: {},
validationRule: {},
searchFieldMetadata: {},
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-one-to-many-metadata-relations.constant.ts b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-one-to-many-metadata-relations.constant.ts
index 60d1430f838..d99c58cd0d5 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-one-to-many-metadata-relations.constant.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-one-to-many-metadata-relations.constant.ts
@@ -309,6 +309,7 @@ export const ALL_ONE_TO_MANY_METADATA_RELATIONS = {
applicationVariable: {},
viewSort: {},
connectionProvider: {},
+ messagingProvider: {},
searchFieldMetadata: {},
timelineActivityType: {},
settingsMenuItem: {},
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-entity/types/all-flat-entity-types-by-metadata-name.type.ts b/packages/twenty-server/src/engine/metadata-modules/flat-entity/types/all-flat-entity-types-by-metadata-name.type.ts
index 4bf370067d5..fd283b6265d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-entity/types/all-flat-entity-types-by-metadata-name.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-entity/types/all-flat-entity-types-by-metadata-name.type.ts
@@ -26,6 +26,8 @@ import { type FlatAgent } from 'src/engine/metadata-modules/flat-agent/types/fla
import { type FlatCommandMenuItemMaps } from 'src/engine/metadata-modules/flat-command-menu-item/types/flat-command-menu-item-maps.type';
import { type FlatConnectionProviderMaps } from 'src/engine/metadata-modules/flat-connection-provider/types/flat-connection-provider-maps.type';
import { type FlatConnectionProvider } from 'src/engine/metadata-modules/flat-connection-provider/types/flat-connection-provider.type';
+import { type FlatMessagingProviderMaps } from 'src/engine/metadata-modules/flat-messaging-provider/types/flat-messaging-provider-maps.type';
+import { type FlatMessagingProvider } from 'src/engine/metadata-modules/flat-messaging-provider/types/flat-messaging-provider.type';
import { type FlatTimelineActivityTypeMaps } from 'src/engine/metadata-modules/flat-timeline-activity-type/types/flat-timeline-activity-type-maps.type';
import { type FlatTimelineActivityType } from 'src/engine/metadata-modules/flat-timeline-activity-type/types/flat-timeline-activity-type.type';
import { type FlatValidationRuleMaps } from 'src/engine/metadata-modules/flat-validation-rule/types/flat-validation-rule-maps.type';
@@ -92,6 +94,7 @@ import { type FlatRowLevelPermissionPredicate } from 'src/engine/metadata-module
import { type UniversalFlatAgent } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-agent.type';
import { type UniversalFlatCommandMenuItem } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-command-menu-item.type';
import { type UniversalFlatConnectionProvider } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-connection-provider.type';
+import { type UniversalFlatMessagingProvider } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-messaging-provider.type';
import { type UniversalFlatTimelineActivityType } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-timeline-activity-type.type';
import { type UniversalFlatValidationRule } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-validation-rule.type';
import { type UniversalFlatEntityFrom } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-entity-from.type';
@@ -146,6 +149,14 @@ import {
type UniversalDeleteConnectionProviderAction,
type UniversalUpdateConnectionProviderAction,
} from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/connection-provider/types/workspace-migration-connection-provider-action.type';
+import {
+ type FlatCreateMessagingProviderAction,
+ type FlatDeleteMessagingProviderAction,
+ type FlatUpdateMessagingProviderAction,
+ type UniversalCreateMessagingProviderAction,
+ type UniversalDeleteMessagingProviderAction,
+ type UniversalUpdateMessagingProviderAction,
+} from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/messaging-provider/types/workspace-migration-messaging-provider-action.type';
import {
type FlatCreateTimelineActivityTypeAction,
type FlatDeleteTimelineActivityTypeAction,
@@ -904,6 +915,22 @@ export type AllFlatEntityTypesByMetadataName = {
universalFlatEntity: UniversalFlatConnectionProvider;
entity: MetadataEntity<'connectionProvider'>;
};
+ messagingProvider: {
+ flatEntityMaps: FlatMessagingProviderMaps;
+ universalActions: {
+ create: UniversalCreateMessagingProviderAction;
+ update: UniversalUpdateMessagingProviderAction;
+ delete: UniversalDeleteMessagingProviderAction;
+ };
+ flatActions: {
+ create: FlatCreateMessagingProviderAction;
+ update: FlatUpdateMessagingProviderAction;
+ delete: FlatDeleteMessagingProviderAction;
+ };
+ flatEntity: FlatMessagingProvider;
+ universalFlatEntity: UniversalFlatMessagingProvider;
+ entity: MetadataEntity<'messagingProvider'>;
+ };
searchFieldMetadata: {
flatEntityMaps: FlatSearchFieldMetadataMaps;
universalActions: {
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-entity/utils/__tests__/__snapshots__/get-metadata-related-metadata-names.util.spec.ts.snap b/packages/twenty-server/src/engine/metadata-modules/flat-entity/utils/__tests__/__snapshots__/get-metadata-related-metadata-names.util.spec.ts.snap
index 587571dcbaf..9a9f2c5b9f6 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-entity/utils/__tests__/__snapshots__/get-metadata-related-metadata-names.util.spec.ts.snap
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-entity/utils/__tests__/__snapshots__/get-metadata-related-metadata-names.util.spec.ts.snap
@@ -59,6 +59,8 @@ exports[`getMetadataRelatedMetadataNames should return related metadata names fo
exports[`getMetadataRelatedMetadataNames should return related metadata names for logicFunction 1`] = `[]`;
+exports[`getMetadataRelatedMetadataNames should return related metadata names for messagingProvider 1`] = `[]`;
+
exports[`getMetadataRelatedMetadataNames should return related metadata names for navigationMenuItem 1`] = `
[
"objectMetadata",
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-entity/utils/__tests__/__snapshots__/sort-metadata-names-children-first.util.spec.ts.snap b/packages/twenty-server/src/engine/metadata-modules/flat-entity/utils/__tests__/__snapshots__/sort-metadata-names-children-first.util.spec.ts.snap
index 83d7225c986..7e297d4c3f2 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-entity/utils/__tests__/__snapshots__/sort-metadata-names-children-first.util.spec.ts.snap
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-entity/utils/__tests__/__snapshots__/sort-metadata-names-children-first.util.spec.ts.snap
@@ -25,6 +25,7 @@ exports[`sortMetadataNamesChildrenFirst should return metadata names sorted with
"connectionProvider",
"frontComponent",
"logicFunction",
+ "messagingProvider",
"pageLayout",
"pageLayoutTab",
"skill",
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-messaging-provider/flat-messaging-provider.module.ts b/packages/twenty-server/src/engine/metadata-modules/flat-messaging-provider/flat-messaging-provider.module.ts
new file mode 100644
index 00000000000..8f86a84f28f
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-messaging-provider/flat-messaging-provider.module.ts
@@ -0,0 +1,8 @@
+import { Module } from '@nestjs/common';
+
+import { WorkspaceFlatMessagingProviderMapCacheService } from 'src/engine/metadata-modules/flat-messaging-provider/services/workspace-flat-messaging-provider-map-cache.service';
+
+@Module({
+ providers: [WorkspaceFlatMessagingProviderMapCacheService],
+})
+export class FlatMessagingProviderModule {}
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-messaging-provider/services/workspace-flat-messaging-provider-map-cache.service.ts b/packages/twenty-server/src/engine/metadata-modules/flat-messaging-provider/services/workspace-flat-messaging-provider-map-cache.service.ts
new file mode 100644
index 00000000000..fdcc52a4e35
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-messaging-provider/services/workspace-flat-messaging-provider-map-cache.service.ts
@@ -0,0 +1,55 @@
+import { Injectable } from '@nestjs/common';
+
+import { isDefined } from 'twenty-shared/utils';
+
+import { MetadataFlatEntityMapsCacheProvider } from 'src/engine/workspace-cache/interfaces/metadata-flat-entity-maps-cache-provider.service';
+
+import { createEmptyFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/constant/create-empty-flat-entity-maps.constant';
+import { type FlatMessagingProviderMaps } from 'src/engine/metadata-modules/flat-messaging-provider/types/flat-messaging-provider-maps.type';
+import { fromMessagingProviderEntityToFlatMessagingProvider } from 'src/engine/metadata-modules/flat-messaging-provider/utils/from-messaging-provider-entity-to-flat-messaging-provider.util';
+import { WorkspaceCache } from 'src/engine/workspace-cache/decorators/workspace-cache.decorator';
+import { type WorkspaceCacheProviderContext } from 'src/engine/workspace-cache/types/workspace-cache-provider-context.type';
+import { createIdToUniversalIdentifierMap } from 'src/engine/workspace-cache/utils/create-id-to-universal-identifier-map.util';
+import { addFlatEntityToFlatEntityMapsThroughMutationOrThrow } from 'src/engine/workspace-manager/workspace-migration/utils/add-flat-entity-to-flat-entity-maps-through-mutation-or-throw.util';
+
+const FLAT_MESSAGING_PROVIDER_ROWS_REQUIREMENT = {
+ messagingProvider: true,
+ application: ['id', 'universalIdentifier', 'deletedAt'],
+} as const;
+
+@Injectable()
+@WorkspaceCache('flatMessagingProviderMaps', { packingPonderation: 1 })
+export class WorkspaceFlatMessagingProviderMapCacheService extends MetadataFlatEntityMapsCacheProvider<'messagingProvider'> {
+ override readonly rowsRequirement = FLAT_MESSAGING_PROVIDER_ROWS_REQUIREMENT;
+
+ computeForCache({
+ rows,
+ }: WorkspaceCacheProviderContext<
+ typeof FLAT_MESSAGING_PROVIDER_ROWS_REQUIREMENT
+ >): FlatMessagingProviderMaps {
+ const { messagingProvider: messagingProviders, application: applications } =
+ rows;
+
+ const applicationIdToUniversalIdentifierMap =
+ createIdToUniversalIdentifierMap(
+ applications.filter((application) => !isDefined(application.deletedAt)),
+ );
+
+ const flatMessagingProviderMaps = createEmptyFlatEntityMaps();
+
+ for (const messagingProviderEntity of messagingProviders) {
+ const flatMessagingProvider =
+ fromMessagingProviderEntityToFlatMessagingProvider({
+ entity: messagingProviderEntity,
+ applicationIdToUniversalIdentifierMap,
+ });
+
+ addFlatEntityToFlatEntityMapsThroughMutationOrThrow({
+ flatEntity: flatMessagingProvider,
+ flatEntityMapsToMutate: flatMessagingProviderMaps,
+ });
+ }
+
+ return flatMessagingProviderMaps;
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-messaging-provider/types/flat-messaging-provider-maps.type.ts b/packages/twenty-server/src/engine/metadata-modules/flat-messaging-provider/types/flat-messaging-provider-maps.type.ts
new file mode 100644
index 00000000000..4a6d290afbe
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-messaging-provider/types/flat-messaging-provider-maps.type.ts
@@ -0,0 +1,4 @@
+import { type FlatMessagingProvider } from 'src/engine/metadata-modules/flat-messaging-provider/types/flat-messaging-provider.type';
+import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
+
+export type FlatMessagingProviderMaps = FlatEntityMaps<FlatMessagingProvider>;
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-messaging-provider/types/flat-messaging-provider.type.ts b/packages/twenty-server/src/engine/metadata-modules/flat-messaging-provider/types/flat-messaging-provider.type.ts
new file mode 100644
index 00000000000..dedf088e01e
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-messaging-provider/types/flat-messaging-provider.type.ts
@@ -0,0 +1,4 @@
+import { type MessagingProviderEntity } from 'src/engine/metadata-modules/messaging-provider/entities/messaging-provider.entity';
+import { type FlatEntityFrom } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-from.type';
+
+export type FlatMessagingProvider = FlatEntityFrom<MessagingProviderEntity>;
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-messaging-provider/utils/from-messaging-provider-entity-to-flat-messaging-provider.util.ts b/packages/twenty-server/src/engine/metadata-modules/flat-messaging-provider/utils/from-messaging-provider-entity-to-flat-messaging-provider.util.ts
new file mode 100644
index 00000000000..6dff468850d
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-messaging-provider/utils/from-messaging-provider-entity-to-flat-messaging-provider.util.ts
@@ -0,0 +1,26 @@
+import { fromEntityToScalarEntity } from 'src/engine/metadata-modules/flat-entity/utils/from-entity-to-scalar-entity.util';
+import { type FlatMessagingProvider } from 'src/engine/metadata-modules/flat-messaging-provider/types/flat-messaging-provider.type';
+import { type FromEntityToFlatEntityArgs } from 'src/engine/workspace-cache/types/from-entity-to-flat-entity-args.type';
+import { resolveManyToOneRelationIdsToUniversalIdentifiers } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/utils/resolve-many-to-one-relation-ids-to-universal-identifiers.util';
+
+export const fromMessagingProviderEntityToFlatMessagingProvider = (
+ args: FromEntityToFlatEntityArgs<'messagingProvider'>,
+): FlatMessagingProvider => {
+ const { entity: messagingProviderEntity } = args;
+
+ const messagingProviderScalarEntity = fromEntityToScalarEntity({
+ metadataName: 'messagingProvider',
+ entity: messagingProviderEntity,
+ });
+
+ const relationUniversalIdentifiers =
+ resolveManyToOneRelationIdsToUniversalIdentifiers({
+ metadataName: 'messagingProvider',
+ ...args,
+ });
+
+ return {
+ ...messagingProviderScalarEntity,
+ ...relationUniversalIdentifiers,
+ };
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/logic-function/utils/find-application-flat-logic-function.util.ts b/packages/twenty-server/src/engine/metadata-modules/logic-function/utils/find-application-flat-logic-function.util.ts
new file mode 100644
index 00000000000..fd29a9bd42b
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/logic-function/utils/find-application-flat-logic-function.util.ts
@@ -0,0 +1,31 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type FlatLogicFunctionMaps } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function-maps.type';
+import { type FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
+
+export const findApplicationFlatLogicFunction = ({
+ flatLogicFunctionMaps,
+ universalIdentifier,
+ applicationId,
+}: {
+ flatLogicFunctionMaps: Pick<FlatLogicFunctionMaps, 'byUniversalIdentifier'>;
+ universalIdentifier: string | null;
+ applicationId: string;
+}): FlatLogicFunction | undefined => {
+ if (!isDefined(universalIdentifier)) {
+ return undefined;
+ }
+
+ const flatLogicFunction =
+ flatLogicFunctionMaps.byUniversalIdentifier[universalIdentifier];
+
+ if (
+ !isDefined(flatLogicFunction) ||
+ isDefined(flatLogicFunction.deletedAt) ||
+ flatLogicFunction.applicationId !== applicationId
+ ) {
+ return undefined;
+ }
+
+ return flatLogicFunction;
+};
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
index c53e32434dc..524dd39553b 100644
--- 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
@@ -42,4 +42,9 @@ export class CreateAppMessageChannelInput {
@IsOptional()
@IsUUID()
participantHandleFieldUniversalIdentifier?: string;
+
+ @Field(() => UUIDScalarType, { nullable: true })
+ @IsOptional()
+ @IsUUID()
+ messagingProviderUniversalIdentifier?: string;
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/message-channel.dto.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/message-channel.dto.ts
index 38b3cf6bc9a..1c58414cb19 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/message-channel.dto.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/message-channel.dto.ts
@@ -122,6 +122,11 @@ export class MessageChannelDTO {
@Field(() => UUIDScalarType)
connectedAccountId: string;
+ @IsUUID()
+ @IsOptional()
+ @Field(() => UUIDScalarType, { nullable: true })
+ messagingProviderUniversalIdentifier: string | null;
+
@HideField()
workspaceId: string;
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/send-app-channel-message.input.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/send-app-channel-message.input.ts
new file mode 100644
index 00000000000..37b580a5bf4
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/send-app-channel-message.input.ts
@@ -0,0 +1,27 @@
+import { Field, InputType } from '@nestjs/graphql';
+
+import { IsNotEmpty, IsString, IsUUID, MaxLength } from 'class-validator';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+import { MAX_APP_MESSAGE_TEXT_LENGTH } from 'src/engine/metadata-modules/message-channel/dtos/ingest-app-messages.input';
+
+@InputType('SendAppChannelMessageInput')
+export class SendAppChannelMessageInput {
+ @Field(() => UUIDScalarType)
+ @IsUUID()
+ messageChannelId: string;
+
+ @Field(() => UUIDScalarType)
+ @IsUUID()
+ messageThreadId: string;
+
+ @Field()
+ @IsString()
+ @IsNotEmpty()
+ @MaxLength(MAX_APP_MESSAGE_TEXT_LENGTH)
+ text: string;
+
+ @Field(() => UUIDScalarType)
+ @IsUUID()
+ idempotencyKey: string;
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/send-app-channel-message.output.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/send-app-channel-message.output.ts
new file mode 100644
index 00000000000..3ba66111ad8
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/dtos/send-app-channel-message.output.ts
@@ -0,0 +1,12 @@
+import { Field, ObjectType } from '@nestjs/graphql';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+
+@ObjectType('SendAppChannelMessageOutput')
+export class SendAppChannelMessageOutput {
+ @Field(() => UUIDScalarType)
+ messageId: string;
+
+ @Field(() => UUIDScalarType)
+ messageThreadId: 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
index cb5733d83e3..91895332632 100644
--- 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
@@ -36,4 +36,9 @@ export class UpdateAppMessageChannelInput {
@IsOptional()
@IsBoolean()
isSyncEnabled?: boolean;
+
+ @Field(() => UUIDScalarType, { nullable: true })
+ @IsOptional()
+ @IsUUID()
+ messagingProviderUniversalIdentifier?: string | null;
}
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 b8c61e8f87b..3e685860961 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
@@ -24,6 +24,7 @@ import {
WebhookSubscriptionStatus,
} from 'twenty-shared/types';
+import { ADD_MESSAGING_PROVIDER_UPGRADE_COMMAND_NAME } from 'src/database/commands/upgrade-version-command/2-52/add-messaging-provider-upgrade-command-name.constant';
import { WasIntroducedInUpgrade } from 'src/engine/core-modules/upgrade/decorators/was-introduced-in-upgrade.decorator';
import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
import { type MessageFolderEntity } from 'src/engine/metadata-modules/message-folder/entities/message-folder.entity';
@@ -179,6 +180,12 @@ export class MessageChannelEntity extends WorkspaceRelatedEntity {
})
participantHandleFieldUniversalIdentifier: string | null;
+ @Column({ type: 'uuid', nullable: true })
+ @WasIntroducedInUpgrade({
+ upgradeCommandName: ADD_MESSAGING_PROVIDER_UPGRADE_COMMAND_NAME,
+ })
+ messagingProviderUniversalIdentifier: string | null;
+
@Column({ type: 'uuid', nullable: false })
connectedAccountId: 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 c84a35272a4..a0cb6ce7ad1 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
@@ -9,15 +9,19 @@ import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channe
import { MessageChannelMetadataService } from 'src/engine/metadata-modules/message-channel/message-channel-metadata.service';
import { ApplicationMessageChannelsResolver } from 'src/engine/metadata-modules/message-channel/resolvers/application-message-channels.resolver';
import { ApplicationMessageIngestionResolver } from 'src/engine/metadata-modules/message-channel/resolvers/application-message-ingestion.resolver';
+import { ApplicationMessageSendResolver } from 'src/engine/metadata-modules/message-channel/resolvers/application-message-send.resolver';
import { MessageChannelResolver } from 'src/engine/metadata-modules/message-channel/resolvers/message-channel.resolver';
import { ApplicationMessageChannelsService } from 'src/engine/metadata-modules/message-channel/services/application-message-channels.service';
import { ApplicationMessageIngestionService } from 'src/engine/metadata-modules/message-channel/services/application-message-ingestion.service';
+import { ApplicationMessageSendService } from 'src/engine/metadata-modules/message-channel/services/application-message-send.service';
import { MessageFolderEntity } from 'src/engine/metadata-modules/message-folder/entities/message-folder.entity';
+import { MessagingProviderModule } from 'src/engine/metadata-modules/messaging-provider/messaging-provider.module';
import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permissions.module';
import { MatchParticipantModule } from 'src/modules/match-participant/match-participant.module';
import { MessagingCommonModule } from 'src/modules/messaging/common/messaging-common.module';
import { MessagingImportManagerModule } from 'src/modules/messaging/message-import-manager/messaging-import-manager.module';
import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';
+import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
@Module({
imports: [
@@ -33,6 +37,8 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspac
MessagingCommonModule,
MatchParticipantModule,
EmailingDomainModule,
+ WorkspaceCacheModule,
+ MessagingProviderModule,
],
providers: [
MessageChannelMetadataService,
@@ -41,6 +47,8 @@ import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspac
ApplicationMessageChannelsResolver,
ApplicationMessageIngestionService,
ApplicationMessageIngestionResolver,
+ ApplicationMessageSendService,
+ ApplicationMessageSendResolver,
provideWorkspaceScopedRepository(MessageFolderEntity),
],
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
index c4f75366070..d2bf6959a49 100644
--- 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
@@ -76,6 +76,8 @@ export class ApplicationMessageChannelsResolver {
visibility: input.visibility,
participantHandleFieldUniversalIdentifier:
input.participantHandleFieldUniversalIdentifier,
+ messagingProviderUniversalIdentifier:
+ input.messagingProviderUniversalIdentifier,
});
}
@@ -95,6 +97,8 @@ export class ApplicationMessageChannelsResolver {
displayName: input.displayName,
visibility: input.visibility,
isSyncEnabled: input.isSyncEnabled,
+ messagingProviderUniversalIdentifier:
+ input.messagingProviderUniversalIdentifier,
});
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/application-message-send.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/application-message-send.resolver.ts
new file mode 100644
index 00000000000..7012e1a1927
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/resolvers/application-message-send.resolver.ts
@@ -0,0 +1,69 @@
+import {
+ UseFilters,
+ UseGuards,
+ UseInterceptors,
+ UsePipes,
+} from '@nestjs/common';
+import { Args, Mutation } from '@nestjs/graphql';
+
+import { PermissionFlagType } from 'twenty-shared/constants';
+
+import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorators/metadata-resolver.decorator';
+import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filters/auth-graphql-api-exception.filter';
+import { ResolverValidationPipe } from 'src/engine/core-modules/graphql/pipes/resolver-validation.pipe';
+import { UsageLimitGraphqlApiExceptionFilter } from 'src/engine/core-modules/usage-limit/filters/usage-limit-graphql-api-exception.filter';
+import { type FlatWorkspace } from 'src/engine/core-modules/workspace/types/flat-workspace.type';
+import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';
+import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
+import { AuthPrincipalGuard } from 'src/engine/guards/auth-principal.guard';
+import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';
+import { ConnectedAccountGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules/connected-account/interceptors/connected-account-graphql-api-exception.interceptor';
+import { SendAppChannelMessageInput } from 'src/engine/metadata-modules/message-channel/dtos/send-app-channel-message.input';
+import { SendAppChannelMessageOutput } from 'src/engine/metadata-modules/message-channel/dtos/send-app-channel-message.output';
+import { MessageChannelGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules/message-channel/interceptors/message-channel-graphql-api-exception.interceptor';
+import { ApplicationMessageSendService } from 'src/engine/metadata-modules/message-channel/services/application-message-send.service';
+import { MessagingProviderGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules/messaging-provider/interceptors/messaging-provider-graphql-api-exception.interceptor';
+
+@UseGuards(
+ AuthPrincipalGuard({
+ userSession: {
+ standard: true,
+ impersonated: true,
+ playground: false,
+ workspaceAgnostic: false,
+ },
+ apiKey: false,
+ oauthClient: false,
+ application: false,
+ }),
+ SettingsPermissionGuard(PermissionFlagType.SEND_EMAIL_TOOL),
+)
+@UseInterceptors(
+ MessageChannelGraphqlApiExceptionInterceptor,
+ ConnectedAccountGraphqlApiExceptionInterceptor,
+ MessagingProviderGraphqlApiExceptionInterceptor,
+)
+@UsePipes(ResolverValidationPipe)
+@MetadataResolver()
+@UseFilters(AuthGraphqlApiExceptionFilter, UsageLimitGraphqlApiExceptionFilter)
+export class ApplicationMessageSendResolver {
+ constructor(
+ private readonly applicationMessageSendService: ApplicationMessageSendService,
+ ) {}
+
+ @Mutation(() => SendAppChannelMessageOutput)
+ async sendAppChannelMessage(
+ @AuthWorkspace() workspace: FlatWorkspace,
+ @AuthUserWorkspaceId() userWorkspaceId: string,
+ @Args('input') input: SendAppChannelMessageInput,
+ ): Promise<SendAppChannelMessageOutput> {
+ return this.applicationMessageSendService.send({
+ workspaceId: workspace.id,
+ userWorkspaceId,
+ messageChannelId: input.messageChannelId,
+ messageThreadId: input.messageThreadId,
+ text: input.text,
+ idempotencyKey: input.idempotencyKey,
+ });
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/services/__tests__/application-message-send.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/services/__tests__/application-message-send.service.spec.ts
new file mode 100644
index 00000000000..2f742070426
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/services/__tests__/application-message-send.service.spec.ts
@@ -0,0 +1,144 @@
+import { MessageParticipantRole } from 'twenty-shared/types';
+import { type Repository } from 'typeorm';
+
+import { type CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
+import { type CacheStorageService } from 'src/engine/core-modules/cache-storage/services/cache-storage.service';
+import { type ConnectedAccountMetadataService } from 'src/engine/metadata-modules/connected-account/connected-account-metadata.service';
+import { type MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
+import { type ApplicationMessageIngestionService } from 'src/engine/metadata-modules/message-channel/services/application-message-ingestion.service';
+import { ApplicationMessageSendService } from 'src/engine/metadata-modules/message-channel/services/application-message-send.service';
+import { type MessagingProviderMessageSenderService } from 'src/engine/metadata-modules/messaging-provider/services/messaging-provider-message-sender.service';
+import { type WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
+import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+
+const SEND_ARGS = {
+ workspaceId: 'workspace-id',
+ userWorkspaceId: 'user-workspace-id',
+ messageChannelId: 'message-channel-id',
+ messageThreadId: 'message-thread-id',
+ text: 'Tuesday works',
+ idempotencyKey: 'idempotency-key',
+};
+
+describe('ApplicationMessageSendService', () => {
+ const sendOrThrow = jest.fn();
+ const ingest = jest.fn();
+ let service: ApplicationMessageSendService;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+
+ const cache = new Map<string, unknown>();
+
+ const rowsByObjectName: Record<string, object[]> = {
+ message: [{ id: 'message-1' }],
+ messageChannelMessageAssociation: [
+ { messageId: 'message-1', messageThreadExternalId: 'thread-1' },
+ ],
+ messageParticipant: [
+ {
+ messageId: 'message-1',
+ handle: 'urn:li:person:ada',
+ displayName: 'Ada Lovelace',
+ personId: null,
+ workspaceMemberId: null,
+ role: MessageParticipantRole.FROM,
+ },
+ ],
+ };
+
+ sendOrThrow.mockResolvedValue({
+ externalId: 'sent-1',
+ sentAt: '2026-10-21T10:00:00.000Z',
+ });
+
+ service = new ApplicationMessageSendService(
+ {
+ findOne: jest.fn().mockResolvedValue({
+ id: SEND_ARGS.messageChannelId,
+ isSyncEnabled: true,
+ connectedAccountId: 'connected-account-id',
+ handle: 'urn:li:person:jane',
+ displayName: 'Jane Doe',
+ messagingProviderUniversalIdentifier: 'messaging-provider',
+ }),
+ } as unknown as Repository<MessageChannelEntity>,
+ {
+ verifyUsableByCaller: jest.fn().mockResolvedValue({
+ id: 'connected-account-id',
+ applicationId: 'application-id',
+ connectionProviderId: 'connection-provider-id',
+ }),
+ } as unknown as ConnectedAccountMetadataService,
+ {
+ resolveSenderOrThrow: jest.fn().mockResolvedValue({}),
+ sendOrThrow,
+ } as unknown as MessagingProviderMessageSenderService,
+ { ingest } as unknown as ApplicationMessageIngestionService,
+ {
+ executeInWorkspaceContext: jest.fn((callback) => callback()),
+ getRepository: jest.fn((objectName: string) => ({
+ find: jest.fn().mockResolvedValue(rowsByObjectName[objectName] ?? []),
+ })),
+ } as unknown as WorkspaceOrmManager,
+ {
+ getOrRecompute: jest.fn().mockResolvedValue({
+ flatWorkspaceMemberMaps: { idByUserWorkspaceId: {} },
+ }),
+ } as unknown as WorkspaceCacheService,
+ {
+ withLock: jest.fn((callback) => callback()),
+ } as unknown as CacheLockService,
+ {
+ get: jest.fn(async (key: string) => cache.get(key)),
+ set: jest.fn(async (key: string, value: unknown) => {
+ cache.set(key, value);
+ }),
+ } as unknown as CacheStorageService,
+ );
+ });
+
+ it('records a delivered reply on retry without sending it again', async () => {
+ ingest
+ .mockRejectedValueOnce(new Error('recording failed'))
+ .mockResolvedValueOnce({
+ messages: [{ messageId: 'message-2', messageThreadId: 'thread-id' }],
+ });
+
+ await expect(service.send(SEND_ARGS)).rejects.toThrow('recording failed');
+
+ await expect(service.send(SEND_ARGS)).resolves.toEqual({
+ messageId: 'message-2',
+ messageThreadId: 'thread-id',
+ });
+
+ expect(sendOrThrow).toHaveBeenCalledTimes(1);
+ expect(sendOrThrow).toHaveBeenCalledWith(
+ expect.objectContaining({
+ payload: expect.objectContaining({ idempotencyKey: 'idempotency-key' }),
+ }),
+ );
+ expect(ingest).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ messages: [
+ expect.objectContaining({
+ externalId: 'sent-1',
+ threadExternalId: 'thread-1',
+ receivedAt: new Date('2026-10-21T10:00:00.000Z'),
+ }),
+ ],
+ }),
+ );
+ });
+
+ it('sends again under a new idempotency key', async () => {
+ ingest.mockResolvedValue({
+ messages: [{ messageId: 'message-2', messageThreadId: 'thread-id' }],
+ });
+
+ await service.send(SEND_ARGS);
+ await service.send({ ...SEND_ARGS, idempotencyKey: 'another-key' });
+
+ expect(sendOrThrow).toHaveBeenCalledTimes(2);
+ });
+});
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
index b0e9194951e..0a18558a9b4 100644
--- a/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-channels.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-channels.service.ts
@@ -24,6 +24,8 @@ import {
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 { findMessagingProviderOnConnectionProvider } from 'src/engine/metadata-modules/messaging-provider/utils/find-messaging-provider-on-connection-provider.util';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
import { WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';
import { PersonHandleFieldService } from 'src/modules/match-participant/person-handle-field/person-handle-field.service';
import { canonicalizePersonHandle } from 'src/modules/match-participant/person-handle-field/utils/canonicalize-person-handle.util';
@@ -42,6 +44,7 @@ type CreateArgs = ApplicationScope & {
displayName?: string;
visibility: MessageChannelVisibility;
participantHandleFieldUniversalIdentifier?: string;
+ messagingProviderUniversalIdentifier?: string;
};
type UpdateArgs = ApplicationScope & {
@@ -49,11 +52,18 @@ type UpdateArgs = ApplicationScope & {
displayName?: string | null;
visibility?: MessageChannelVisibility;
isSyncEnabled?: boolean;
+ messagingProviderUniversalIdentifier?: string | null;
};
// TypeORM's update() cannot take the relations Partial<MessageChannelEntity> carries
type UpdatableChannelFields = Partial<
- Pick<MessageChannelEntity, 'displayName' | 'visibility' | 'isSyncEnabled'>
+ Pick<
+ MessageChannelEntity,
+ | 'displayName'
+ | 'visibility'
+ | 'isSyncEnabled'
+ | 'messagingProviderUniversalIdentifier'
+ >
>;
export type OwnedMessageChannel = {
@@ -77,6 +87,7 @@ export class ApplicationMessageChannelsService {
private readonly connectedAccountRepository: Repository<ConnectedAccountEntity>,
private readonly workspaceEventEmitter: WorkspaceEventEmitter,
private readonly personHandleFieldService: PersonHandleFieldService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
) {}
async list({
@@ -124,8 +135,9 @@ export class ApplicationMessageChannelsService {
displayName,
visibility,
participantHandleFieldUniversalIdentifier,
+ messagingProviderUniversalIdentifier,
}: CreateArgs): Promise<MessageChannelDTO> {
- await this.assertOwnsConnectedAccount({
+ const connectedAccount = await this.findOwnedConnectedAccountOrThrow({
applicationId,
workspaceId,
requestUserWorkspaceId,
@@ -138,6 +150,15 @@ export class ApplicationMessageChannelsService {
participantHandleFieldUniversalIdentifier,
});
+ if (isDefined(messagingProviderUniversalIdentifier)) {
+ await this.assertMessagingProviderFitsConnectionOrThrow({
+ applicationId,
+ workspaceId,
+ connectedAccount,
+ messagingProviderUniversalIdentifier,
+ });
+ }
+
const existingChannel = await this.messageChannelRepository.findOne({
where: { connectedAccountId, handle, workspaceId },
});
@@ -158,6 +179,8 @@ export class ApplicationMessageChannelsService {
visibility,
participantHandleFieldUniversalIdentifier:
participantHandleFieldUniversalIdentifier ?? null,
+ messagingProviderUniversalIdentifier:
+ messagingProviderUniversalIdentifier ?? null,
isSyncEnabled: true,
// inert since app channels skip the polling crons; mirrors EMAIL_GROUP so the UI reads healthy
syncStage: MessageChannelSyncStage.MESSAGE_LIST_FETCH_PENDING,
@@ -221,8 +244,9 @@ export class ApplicationMessageChannelsService {
displayName,
visibility,
isSyncEnabled,
+ messagingProviderUniversalIdentifier,
}: UpdateArgs): Promise<MessageChannelDTO> {
- const { messageChannel } = await this.findOwnedOrThrow({
+ const { messageChannel, connectedAccount } = await this.findOwnedOrThrow({
applicationId,
workspaceId,
requestUserWorkspaceId,
@@ -243,6 +267,20 @@ export class ApplicationMessageChannelsService {
data.isSyncEnabled = isSyncEnabled;
}
+ if (isDefined(messagingProviderUniversalIdentifier)) {
+ await this.assertMessagingProviderFitsConnectionOrThrow({
+ applicationId,
+ workspaceId,
+ connectedAccount,
+ messagingProviderUniversalIdentifier,
+ });
+ }
+
+ if (messagingProviderUniversalIdentifier !== undefined) {
+ data.messagingProviderUniversalIdentifier =
+ messagingProviderUniversalIdentifier;
+ }
+
if (Object.keys(data).length === 0) {
return messageChannel;
}
@@ -310,12 +348,49 @@ export class ApplicationMessageChannelsService {
}
// ownership alone would let any app user flip another member's private channel to SHARE_EVERYTHING
- private async assertOwnsConnectedAccount(
+ private async findOwnedConnectedAccountOrThrow(
args: ApplicationScope & { connectedAccountId: string },
- ): Promise<void> {
- if (!isDefined(await this.findReachableConnectedAccount(args))) {
+ ): Promise<ConnectedAccountEntity> {
+ const connectedAccount = await this.findReachableConnectedAccount(args);
+
+ if (!isDefined(connectedAccount)) {
throw this.ownershipViolation(args.connectedAccountId);
}
+
+ return connectedAccount;
+ }
+
+ private async assertMessagingProviderFitsConnectionOrThrow({
+ applicationId,
+ workspaceId,
+ connectedAccount,
+ messagingProviderUniversalIdentifier,
+ }: Pick<ApplicationScope, 'applicationId' | 'workspaceId'> & {
+ connectedAccount: Pick<ConnectedAccountEntity, 'connectionProviderId'>;
+ messagingProviderUniversalIdentifier: string;
+ }): Promise<void> {
+ const { flatMessagingProviderMaps, flatConnectionProviderMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatMessagingProviderMaps',
+ 'flatConnectionProviderMaps',
+ ]);
+
+ const messagingProvider = findMessagingProviderOnConnectionProvider({
+ flatMessagingProviderMaps,
+ flatConnectionProviderMaps,
+ messagingProviderUniversalIdentifier,
+ connectionProviderId: connectedAccount.connectionProviderId,
+ });
+
+ if (
+ !isDefined(messagingProvider) ||
+ messagingProvider.applicationId !== applicationId
+ ) {
+ throw new MessageChannelException(
+ `Messaging provider ${messagingProviderUniversalIdentifier} is not one of this application's providers on this connection's provider`,
+ MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,
+ );
+ }
}
// public so MessageChannelResolver shares the single reachability rule
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-send.service.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-send.service.ts
new file mode 100644
index 00000000000..3be7f4edabf
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/services/application-message-send.service.ts
@@ -0,0 +1,430 @@
+import { Injectable } from '@nestjs/common';
+import { InjectRepository } from '@nestjs/typeorm';
+
+import {
+ MessageChannelType,
+ MessageParticipantRole,
+} from 'twenty-shared/types';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+import { In, Repository } from 'typeorm';
+
+import { CacheLockService } from 'src/engine/core-modules/cache-lock/cache-lock.service';
+import { InjectCacheStorage } from 'src/engine/core-modules/cache-storage/decorators/cache-storage.decorator';
+import { CacheStorageService } from 'src/engine/core-modules/cache-storage/services/cache-storage.service';
+import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';
+import { ConnectedAccountMetadataService } from 'src/engine/metadata-modules/connected-account/connected-account-metadata.service';
+import { type SendAppChannelMessageOutput } from 'src/engine/metadata-modules/message-channel/dtos/send-app-channel-message.output';
+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 { ApplicationMessageIngestionService } from 'src/engine/metadata-modules/message-channel/services/application-message-ingestion.service';
+import {
+ type AppMessageReplyRecipient,
+ buildAppMessageReplyRecipients,
+} from 'src/engine/metadata-modules/message-channel/utils/build-app-message-reply-recipients.util';
+import { MessagingProviderMessageSenderService } from 'src/engine/metadata-modules/messaging-provider/services/messaging-provider-message-sender.service';
+import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
+import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { type MessageChannelMessageAssociationWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-channel-message-association.workspace-entity';
+import { type MessageParticipantWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-participant.workspace-entity';
+import { type MessageWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message.workspace-entity';
+
+const CONVERSATION_LOOKUP_MESSAGE_LIMIT = 50;
+
+const APP_MESSAGE_DELIVERY_TTL_MS = 24 * 60 * 60 * 1000;
+
+const APP_MESSAGE_DELIVERY_LOCK_OPTIONS = { ms: 500, maxRetries: 60 };
+
+type SendArgs = {
+ workspaceId: string;
+ userWorkspaceId: string;
+ messageChannelId: string;
+ messageThreadId: string;
+ text: string;
+ idempotencyKey: string;
+};
+
+type Conversation = {
+ threadExternalId: string;
+ recipients: AppMessageReplyRecipient[];
+};
+
+type AppMessageDelivery = Conversation & {
+ externalId: string;
+ text: string;
+ sentAt: string;
+};
+
+@Injectable()
+export class ApplicationMessageSendService {
+ constructor(
+ @InjectRepository(MessageChannelEntity)
+ private readonly messageChannelRepository: Repository<MessageChannelEntity>,
+ private readonly connectedAccountMetadataService: ConnectedAccountMetadataService,
+ private readonly messagingProviderMessageSenderService: MessagingProviderMessageSenderService,
+ private readonly applicationMessageIngestionService: ApplicationMessageIngestionService,
+ private readonly workspaceOrmManager: WorkspaceOrmManager,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ private readonly cacheLockService: CacheLockService,
+ @InjectCacheStorage(CacheStorageNamespace.ModuleMessaging)
+ private readonly cacheStorageService: CacheStorageService,
+ ) {}
+
+ async send({
+ workspaceId,
+ userWorkspaceId,
+ messageChannelId,
+ messageThreadId,
+ text,
+ idempotencyKey,
+ }: SendArgs): Promise<SendAppChannelMessageOutput> {
+ const messageChannel = await this.messageChannelRepository.findOne({
+ where: {
+ id: messageChannelId,
+ workspaceId,
+ type: MessageChannelType.APP,
+ },
+ });
+
+ if (!isDefined(messageChannel)) {
+ throw new MessageChannelException(
+ `Message channel ${messageChannelId} not found`,
+ MessageChannelExceptionCode.MESSAGE_CHANNEL_NOT_FOUND,
+ );
+ }
+
+ if (!messageChannel.isSyncEnabled) {
+ throw new MessageChannelException(
+ `Message channel ${messageChannelId} has sync disabled`,
+ MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,
+ );
+ }
+
+ const connectedAccount =
+ await this.connectedAccountMetadataService.verifyUsableByCaller({
+ id: messageChannel.connectedAccountId,
+ userWorkspaceId,
+ workspaceId,
+ });
+
+ if (
+ !isDefined(connectedAccount.applicationId) ||
+ !isDefined(connectedAccount.connectionProviderId)
+ ) {
+ throw new MessageChannelException(
+ `Message channel ${messageChannelId} is not backed by an application connection`,
+ MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,
+ );
+ }
+
+ const { applicationId, connectionProviderId } = connectedAccount;
+
+ const { flatWorkspaceMemberMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatWorkspaceMemberMaps',
+ ]);
+
+ const deliveryKey = `app-message-delivery:${workspaceId}:${userWorkspaceId}:${messageChannelId}:${messageThreadId}:${idempotencyKey}`;
+
+ return this.cacheLockService.withLock(
+ async () => {
+ const delivery =
+ (await this.cacheStorageService.get<AppMessageDelivery>(
+ deliveryKey,
+ )) ??
+ (await this.deliver({
+ workspaceId,
+ messageChannel,
+ connectionProviderId,
+ connectedAccountId: connectedAccount.id,
+ messageThreadId,
+ idempotencyKey,
+ text,
+ deliveryKey,
+ }));
+
+ const {
+ messages: [ingestedMessage],
+ } = await this.applicationMessageIngestionService.ingest({
+ applicationId,
+ workspaceId,
+ requestUserWorkspaceId: userWorkspaceId,
+ messageChannelId,
+ messages: [
+ {
+ externalId: delivery.externalId,
+ threadExternalId: delivery.threadExternalId,
+ text: delivery.text,
+ receivedAt: new Date(delivery.sentAt),
+ participants: [
+ {
+ role: MessageParticipantRole.FROM,
+ handle: messageChannel.handle,
+ displayName: messageChannel.displayName ?? undefined,
+ workspaceMemberId:
+ flatWorkspaceMemberMaps.idByUserWorkspaceId[
+ userWorkspaceId
+ ],
+ },
+ ...delivery.recipients.map((recipient) => ({
+ role: MessageParticipantRole.TO,
+ ...recipient,
+ })),
+ ],
+ },
+ ],
+ });
+
+ return {
+ messageId: ingestedMessage.messageId,
+ messageThreadId: ingestedMessage.messageThreadId,
+ };
+ },
+ deliveryKey,
+ APP_MESSAGE_DELIVERY_LOCK_OPTIONS,
+ );
+ }
+
+ private async deliver({
+ workspaceId,
+ messageChannel,
+ connectionProviderId,
+ connectedAccountId,
+ messageThreadId,
+ idempotencyKey,
+ text,
+ deliveryKey,
+ }: {
+ workspaceId: string;
+ messageChannel: MessageChannelEntity;
+ connectionProviderId: string;
+ connectedAccountId: string;
+ messageThreadId: string;
+ idempotencyKey: string;
+ text: string;
+ deliveryKey: string;
+ }): Promise<AppMessageDelivery> {
+ const sender =
+ await this.messagingProviderMessageSenderService.resolveSenderOrThrow({
+ messagingProviderUniversalIdentifier:
+ messageChannel.messagingProviderUniversalIdentifier,
+ connectionProviderId,
+ messageChannelId: messageChannel.id,
+ workspaceId,
+ });
+
+ const conversation = await this.findConversation({
+ workspaceId,
+ messageChannel,
+ messageThreadId,
+ });
+
+ const sentMessage =
+ await this.messagingProviderMessageSenderService.sendOrThrow({
+ sender,
+ workspaceId,
+ payload: {
+ connectedAccountId,
+ messageChannelId: messageChannel.id,
+ threadExternalId: conversation.threadExternalId,
+ text,
+ idempotencyKey,
+ recipients: conversation.recipients.map(
+ ({ handle, displayName }) => ({
+ handle,
+ displayName: displayName ?? null,
+ }),
+ ),
+ },
+ });
+
+ const delivery: AppMessageDelivery = {
+ externalId: sentMessage.externalId,
+ threadExternalId: conversation.threadExternalId,
+ text,
+ sentAt: sentMessage.sentAt ?? new Date().toISOString(),
+ recipients: conversation.recipients,
+ };
+
+ await this.cacheStorageService.set(
+ deliveryKey,
+ delivery,
+ APP_MESSAGE_DELIVERY_TTL_MS,
+ );
+
+ return delivery;
+ }
+
+ private async findConversation({
+ workspaceId,
+ messageChannel,
+ messageThreadId,
+ }: {
+ workspaceId: string;
+ messageChannel: Pick<MessageChannelEntity, 'id' | 'handle'>;
+ messageThreadId: string;
+ }): Promise<Conversation> {
+ const conversation =
+ await this.workspaceOrmManager.executeInWorkspaceContext(
+ async () => {
+ const threadMessages = await this.workspaceOrmManager
+ .getRepository<MessageWorkspaceEntity>('message', {
+ shouldBypassPermissionChecks: true,
+ })
+ .find({ where: { messageThreadId }, select: { id: true } });
+
+ const threadMessageIds = threadMessages.map((message) => message.id);
+
+ if (!isNonEmptyArray(threadMessageIds)) {
+ return null;
+ }
+
+ const associations = await this.workspaceOrmManager
+ .getRepository<MessageChannelMessageAssociationWorkspaceEntity>(
+ 'messageChannelMessageAssociation',
+ { shouldBypassPermissionChecks: true },
+ )
+ .find({
+ where: {
+ messageChannelId: messageChannel.id,
+ messageId: In(threadMessageIds),
+ },
+ select: { messageId: true, messageThreadExternalId: true },
+ });
+
+ if (!isNonEmptyArray(associations)) {
+ return null;
+ }
+
+ const latestMessages = await this.workspaceOrmManager
+ .getRepository<MessageWorkspaceEntity>('message', {
+ shouldBypassPermissionChecks: true,
+ })
+ .find({
+ where: {
+ id: In(
+ associations.map((association) => association.messageId),
+ ),
+ },
+ select: { id: true },
+ order: { receivedAt: 'DESC' },
+ take: CONVERSATION_LOOKUP_MESSAGE_LIMIT,
+ });
+
+ const messageIds = latestMessages.map((message) => message.id);
+
+ const participants = await this.workspaceOrmManager
+ .getRepository<MessageParticipantWorkspaceEntity>(
+ 'messageParticipant',
+ { shouldBypassPermissionChecks: true },
+ )
+ .find({
+ where: { messageId: In(messageIds) },
+ select: {
+ messageId: true,
+ handle: true,
+ displayName: true,
+ personId: true,
+ workspaceMemberId: true,
+ role: true,
+ },
+ });
+
+ const byRecency = <TRow extends { messageId: string }>(
+ rows: TRow[],
+ ): TRow[] =>
+ messageIds.flatMap((messageId) =>
+ rows.filter((row) => row.messageId === messageId),
+ );
+
+ const threadExternalId = byRecency(associations).find((association) =>
+ isDefined(association.messageThreadExternalId),
+ )?.messageThreadExternalId;
+
+ if (!isDefined(threadExternalId)) {
+ return null;
+ }
+
+ return {
+ threadExternalId,
+ recipients: await this.dropLinksToDeletedRecords(
+ buildAppMessageReplyRecipients({
+ participants: byRecency(participants),
+ channelHandle: messageChannel.handle,
+ }),
+ ),
+ };
+ },
+ buildSystemAuthContext(workspaceId),
+ { lite: true },
+ );
+
+ if (!isDefined(conversation)) {
+ throw new MessageChannelException(
+ `Message thread ${messageThreadId} has no messages in message channel ${messageChannel.id}`,
+ MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,
+ );
+ }
+
+ if (conversation.recipients.length === 0) {
+ throw new MessageChannelException(
+ `Message thread ${messageThreadId} has no participant to reply to`,
+ MessageChannelExceptionCode.INVALID_MESSAGE_CHANNEL_INPUT,
+ );
+ }
+
+ return conversation;
+ }
+
+ private async dropLinksToDeletedRecords(
+ recipients: Conversation['recipients'],
+ ): Promise<Conversation['recipients']> {
+ const [existingPersonIds, existingWorkspaceMemberIds] = await Promise.all([
+ this.findExistingRecordIds({
+ objectMetadataName: 'person',
+ ids: recipients.map((recipient) => recipient.personId),
+ }),
+ this.findExistingRecordIds({
+ objectMetadataName: 'workspaceMember',
+ ids: recipients.map((recipient) => recipient.workspaceMemberId),
+ }),
+ ]);
+
+ return recipients.map((recipient) => ({
+ ...recipient,
+ personId:
+ isDefined(recipient.personId) &&
+ existingPersonIds.has(recipient.personId)
+ ? recipient.personId
+ : undefined,
+ workspaceMemberId:
+ isDefined(recipient.workspaceMemberId) &&
+ existingWorkspaceMemberIds.has(recipient.workspaceMemberId)
+ ? recipient.workspaceMemberId
+ : undefined,
+ }));
+ }
+
+ private async findExistingRecordIds({
+ objectMetadataName,
+ ids,
+ }: {
+ objectMetadataName: 'person' | 'workspaceMember';
+ ids: (string | undefined)[];
+ }): Promise<Set<string>> {
+ const definedIds = [...new Set(ids.filter(isDefined))];
+
+ if (definedIds.length === 0) {
+ return new Set();
+ }
+
+ const records = await this.workspaceOrmManager
+ .getRepository(objectMetadataName, { shouldBypassPermissionChecks: true })
+ .find({ where: { id: In(definedIds) }, select: { id: true } });
+
+ return new Set(records.map((record) => record.id));
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/__tests__/build-app-message-reply-recipients.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/__tests__/build-app-message-reply-recipients.util.spec.ts
new file mode 100644
index 00000000000..23e82560cbc
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/__tests__/build-app-message-reply-recipients.util.spec.ts
@@ -0,0 +1,166 @@
+import { MessageParticipantRole } from 'twenty-shared/types';
+
+import { buildAppMessageReplyRecipients } from 'src/engine/metadata-modules/message-channel/utils/build-app-message-reply-recipients.util';
+
+const buildParticipant = (
+ overrides: Partial<
+ Parameters<typeof buildAppMessageReplyRecipients>[0]['participants'][0]
+ > = {},
+) => ({
+ messageId: 'message-latest',
+ handle: 'urn:li:person:ada',
+ displayName: 'Ada Lovelace',
+ personId: null,
+ workspaceMemberId: null,
+ role: MessageParticipantRole.FROM,
+ ...overrides,
+});
+
+describe('buildAppMessageReplyRecipients', () => {
+ it('leaves out the channel handle, whatever its case', () => {
+ expect(
+ buildAppMessageReplyRecipients({
+ participants: [
+ buildParticipant({ handle: 'URN:LI:PERSON:JANE' }),
+ buildParticipant(),
+ ],
+ channelHandle: 'urn:li:person:jane',
+ }),
+ ).toEqual([
+ {
+ handle: 'urn:li:person:ada',
+ displayName: 'Ada Lovelace',
+ personId: undefined,
+ workspaceMemberId: undefined,
+ },
+ ]);
+ });
+
+ it('leaves out blind copied participants', () => {
+ expect(
+ buildAppMessageReplyRecipients({
+ participants: [
+ buildParticipant({
+ handle: 'urn:li:person:grace',
+ role: MessageParticipantRole.BCC,
+ }),
+ buildParticipant({ role: MessageParticipantRole.CC }),
+ ],
+ channelHandle: 'urn:li:person:jane',
+ }),
+ ).toEqual([
+ {
+ handle: 'urn:li:person:ada',
+ displayName: 'Ada Lovelace',
+ personId: undefined,
+ workspaceMemberId: undefined,
+ },
+ ]);
+ });
+
+ it('keeps one recipient per handle with the newest values first', () => {
+ expect(
+ buildAppMessageReplyRecipients({
+ participants: [
+ buildParticipant({ displayName: 'Ada L.', personId: 'person-new' }),
+ buildParticipant({
+ messageId: 'message-older',
+ personId: 'person-old',
+ }),
+ ],
+ channelHandle: 'urn:li:person:jane',
+ }),
+ ).toEqual([
+ {
+ handle: 'urn:li:person:ada',
+ displayName: 'Ada L.',
+ personId: 'person-new',
+ workspaceMemberId: undefined,
+ },
+ ]);
+ });
+
+ it('fills a name or link the newest row omits from an older one', () => {
+ expect(
+ buildAppMessageReplyRecipients({
+ participants: [
+ buildParticipant({ displayName: '' }),
+ buildParticipant({
+ messageId: 'message-older',
+ personId: 'person-a',
+ workspaceMemberId: 'member-a',
+ }),
+ ],
+ channelHandle: 'urn:li:person:jane',
+ }),
+ ).toEqual([
+ {
+ handle: 'urn:li:person:ada',
+ displayName: 'Ada Lovelace',
+ personId: 'person-a',
+ workspaceMemberId: 'member-a',
+ },
+ ]);
+ });
+
+ it('skips participants without a handle', () => {
+ expect(
+ buildAppMessageReplyRecipients({
+ participants: [buildParticipant({ handle: null })],
+ channelHandle: 'urn:li:person:jane',
+ }),
+ ).toEqual([]);
+ });
+
+ it('replies only to the latest message participants, not to someone who left the conversation', () => {
+ expect(
+ buildAppMessageReplyRecipients({
+ participants: [
+ buildParticipant({ role: MessageParticipantRole.FROM }),
+ buildParticipant({
+ handle: 'urn:li:person:jane',
+ role: MessageParticipantRole.TO,
+ }),
+ buildParticipant({
+ messageId: 'message-older',
+ handle: 'urn:li:person:grace',
+ displayName: 'Grace Hopper',
+ role: MessageParticipantRole.TO,
+ }),
+ buildParticipant({
+ messageId: 'message-older',
+ personId: 'person-a',
+ role: MessageParticipantRole.TO,
+ }),
+ ],
+ channelHandle: 'urn:li:person:jane',
+ }),
+ ).toEqual([
+ {
+ handle: 'urn:li:person:ada',
+ displayName: 'Ada Lovelace',
+ personId: 'person-a',
+ workspaceMemberId: undefined,
+ },
+ ]);
+ });
+
+ it('takes recipients from an older message when the latest has only the channel itself', () => {
+ expect(
+ buildAppMessageReplyRecipients({
+ participants: [
+ buildParticipant({ handle: 'urn:li:person:jane' }),
+ buildParticipant({ messageId: 'message-older' }),
+ ],
+ channelHandle: 'urn:li:person:jane',
+ }),
+ ).toEqual([
+ {
+ handle: 'urn:li:person:ada',
+ displayName: 'Ada Lovelace',
+ personId: undefined,
+ workspaceMemberId: undefined,
+ },
+ ]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/build-app-message-reply-recipients.util.ts b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/build-app-message-reply-recipients.util.ts
new file mode 100644
index 00000000000..84048b692f4
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/message-channel/utils/build-app-message-reply-recipients.util.ts
@@ -0,0 +1,71 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { MessageParticipantRole } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type AppMessageParticipantInput } from 'src/engine/metadata-modules/message-channel/dtos/ingest-app-messages.input';
+import { type MessageParticipantWorkspaceEntity } from 'src/modules/messaging/common/standard-objects/message-participant.workspace-entity';
+
+export type AppMessageReplyRecipient = Omit<AppMessageParticipantInput, 'role'>;
+
+type ReplyParticipant = Pick<
+ MessageParticipantWorkspaceEntity,
+ | 'messageId'
+ | 'handle'
+ | 'displayName'
+ | 'personId'
+ | 'workspaceMemberId'
+ | 'role'
+>;
+
+export const buildAppMessageReplyRecipients = ({
+ participants,
+ channelHandle,
+}: {
+ participants: ReplyParticipant[];
+ channelHandle: string;
+}): AppMessageReplyRecipient[] => {
+ const isReplyable = (
+ participant: ReplyParticipant,
+ ): participant is ReplyParticipant & { handle: string } =>
+ isNonEmptyString(participant.handle) &&
+ participant.role !== MessageParticipantRole.BCC &&
+ participant.handle.toLowerCase() !== channelHandle.toLowerCase();
+
+ const replyableParticipants = participants.filter(isReplyable);
+
+ const latestMessageId = replyableParticipants[0]?.messageId;
+
+ const recipientsByHandle = new Map<string, AppMessageReplyRecipient>(
+ replyableParticipants
+ .filter((participant) => participant.messageId === latestMessageId)
+ .map((participant) => [
+ participant.handle.toLowerCase(),
+ { handle: participant.handle },
+ ]),
+ );
+
+ for (const participant of replyableParticipants) {
+ const handleKey = participant.handle.toLowerCase();
+ const newerRecipient = recipientsByHandle.get(handleKey);
+
+ if (!isDefined(newerRecipient)) {
+ continue;
+ }
+
+ recipientsByHandle.set(handleKey, {
+ handle: newerRecipient.handle,
+ displayName:
+ newerRecipient.displayName ??
+ (isNonEmptyString(participant.displayName)
+ ? participant.displayName
+ : undefined),
+ personId: newerRecipient.personId ?? participant.personId ?? undefined,
+ workspaceMemberId:
+ newerRecipient.workspaceMemberId ??
+ participant.workspaceMemberId ??
+ undefined,
+ });
+ }
+
+ return [...recipientsByHandle.values()];
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/messaging-provider/entities/messaging-provider.entity.ts b/packages/twenty-server/src/engine/metadata-modules/messaging-provider/entities/messaging-provider.entity.ts
new file mode 100644
index 00000000000..ca2448c47d9
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/messaging-provider/entities/messaging-provider.entity.ts
@@ -0,0 +1,48 @@
+import {
+ Column,
+ CreateDateColumn,
+ Entity,
+ Index,
+ PrimaryGeneratedColumn,
+ Unique,
+ UpdateDateColumn,
+} from 'typeorm';
+
+import { ADD_MESSAGING_PROVIDER_UPGRADE_COMMAND_NAME } from 'src/database/commands/upgrade-version-command/2-52/add-messaging-provider-upgrade-command-name.constant';
+import { WasIntroducedInUpgrade } from 'src/engine/core-modules/upgrade/decorators/was-introduced-in-upgrade.decorator';
+import { SyncableEntity } from 'src/engine/workspace-manager/types/syncable-entity.interface';
+
+@Entity({ name: 'messagingProvider', schema: 'core' })
+@WasIntroducedInUpgrade({
+ upgradeCommandName: ADD_MESSAGING_PROVIDER_UPGRADE_COMMAND_NAME,
+})
+@Unique('IDX_MESSAGING_PROVIDER_NAME_APPLICATION_UNIQUE', [
+ 'name',
+ 'applicationId',
+])
+@Index('IDX_MESSAGING_PROVIDER_APPLICATION_ID', ['applicationId'])
+export class MessagingProviderEntity
+ extends SyncableEntity
+ implements Required<MessagingProviderEntity>
+{
+ @PrimaryGeneratedColumn('uuid')
+ id: string;
+
+ @Column({ nullable: false, type: 'varchar' })
+ name: string;
+
+ @Column({ nullable: false, type: 'varchar' })
+ displayName: string;
+
+ @Column({ nullable: false, type: 'uuid' })
+ connectionProviderUniversalIdentifier: string;
+
+ @Column({ nullable: true, type: 'uuid' })
+ sendMessageLogicFunctionUniversalIdentifier: string | null;
+
+ @CreateDateColumn({ type: 'timestamptz' })
+ createdAt: Date;
+
+ @UpdateDateColumn({ type: 'timestamptz' })
+ updatedAt: Date;
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/messaging-provider/interceptors/messaging-provider-graphql-api-exception.interceptor.ts b/packages/twenty-server/src/engine/metadata-modules/messaging-provider/interceptors/messaging-provider-graphql-api-exception.interceptor.ts
new file mode 100644
index 00000000000..e85d5eb3726
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/messaging-provider/interceptors/messaging-provider-graphql-api-exception.interceptor.ts
@@ -0,0 +1,22 @@
+import {
+ type CallHandler,
+ type ExecutionContext,
+ Injectable,
+ type NestInterceptor,
+} from '@nestjs/common';
+
+import { type Observable, catchError } from 'rxjs';
+
+import { messagingProviderGraphqlApiExceptionHandler } from 'src/engine/metadata-modules/messaging-provider/utils/messaging-provider-graphql-api-exception-handler.util';
+
+@Injectable()
+export class MessagingProviderGraphqlApiExceptionInterceptor implements NestInterceptor {
+ intercept(
+ _context: ExecutionContext,
+ next: CallHandler,
+ ): Observable<unknown> {
+ return next
+ .handle()
+ .pipe(catchError(messagingProviderGraphqlApiExceptionHandler));
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/messaging-provider/messaging-provider.exception.ts b/packages/twenty-server/src/engine/metadata-modules/messaging-provider/messaging-provider.exception.ts
new file mode 100644
index 00000000000..30de302a02b
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/messaging-provider/messaging-provider.exception.ts
@@ -0,0 +1,46 @@
+import { type MessageDescriptor } from '@lingui/core';
+import { msg } from '@lingui/core/macro';
+import { assertUnreachable } from 'twenty-shared/utils';
+
+import { CustomException } from 'src/utils/custom-exception';
+
+export enum MessagingProviderExceptionCode {
+ MESSAGING_PROVIDER_NOT_FOUND = 'MESSAGING_PROVIDER_NOT_FOUND',
+ INVALID_MESSAGING_PROVIDER_INPUT = 'INVALID_MESSAGING_PROVIDER_INPUT',
+ MESSAGING_PROVIDER_NAME_ALREADY_EXISTS = 'MESSAGING_PROVIDER_NAME_ALREADY_EXISTS',
+ SEND_MESSAGE_NOT_AVAILABLE = 'SEND_MESSAGE_NOT_AVAILABLE',
+ SEND_MESSAGE_FAILED = 'SEND_MESSAGE_FAILED',
+}
+
+const getMessagingProviderExceptionUserFriendlyMessage = (
+ code: MessagingProviderExceptionCode,
+) => {
+ switch (code) {
+ case MessagingProviderExceptionCode.MESSAGING_PROVIDER_NOT_FOUND:
+ return msg`Messaging provider not found.`;
+ case MessagingProviderExceptionCode.INVALID_MESSAGING_PROVIDER_INPUT:
+ return msg`Invalid messaging provider input.`;
+ case MessagingProviderExceptionCode.MESSAGING_PROVIDER_NAME_ALREADY_EXISTS:
+ return msg`A messaging provider with this name already exists for this application.`;
+ case MessagingProviderExceptionCode.SEND_MESSAGE_NOT_AVAILABLE:
+ return msg`This message channel cannot send messages.`;
+ case MessagingProviderExceptionCode.SEND_MESSAGE_FAILED:
+ return msg`We could not send your message. Please try again.`;
+ default:
+ assertUnreachable(code);
+ }
+};
+
+export class MessagingProviderException extends CustomException<MessagingProviderExceptionCode> {
+ constructor(
+ message: string,
+ code: MessagingProviderExceptionCode,
+ { userFriendlyMessage }: { userFriendlyMessage?: MessageDescriptor } = {},
+ ) {
+ super(message, code, {
+ userFriendlyMessage:
+ userFriendlyMessage ??
+ getMessagingProviderExceptionUserFriendlyMessage(code),
+ });
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/messaging-provider/messaging-provider.module.ts b/packages/twenty-server/src/engine/metadata-modules/messaging-provider/messaging-provider.module.ts
new file mode 100644
index 00000000000..b4f6986f050
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/messaging-provider/messaging-provider.module.ts
@@ -0,0 +1,12 @@
+import { Module } from '@nestjs/common';
+
+import { FlatMessagingProviderModule } from 'src/engine/metadata-modules/flat-messaging-provider/flat-messaging-provider.module';
+import { MessagingProviderMessageSenderService } from 'src/engine/metadata-modules/messaging-provider/services/messaging-provider-message-sender.service';
+import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
+
+@Module({
+ imports: [FlatMessagingProviderModule, WorkspaceCacheModule],
+ providers: [MessagingProviderMessageSenderService],
+ exports: [MessagingProviderMessageSenderService],
+})
+export class MessagingProviderModule {}
diff --git a/packages/twenty-server/src/engine/metadata-modules/messaging-provider/services/messaging-provider-message-sender.service.ts b/packages/twenty-server/src/engine/metadata-modules/messaging-provider/services/messaging-provider-message-sender.service.ts
new file mode 100644
index 00000000000..41f075e198d
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/messaging-provider/services/messaging-provider-message-sender.service.ts
@@ -0,0 +1,114 @@
+import { Injectable } from '@nestjs/common';
+
+import {
+ type SendAppMessagePayload,
+ type SendAppMessageResult,
+} from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+import { LogicFunctionExecutorService } from 'src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service';
+import { findApplicationFlatLogicFunction } from 'src/engine/metadata-modules/logic-function/utils/find-application-flat-logic-function.util';
+import {
+ MessagingProviderException,
+ MessagingProviderExceptionCode,
+} from 'src/engine/metadata-modules/messaging-provider/messaging-provider.exception';
+import { type MessagingProviderSender } from 'src/engine/metadata-modules/messaging-provider/types/messaging-provider-sender.type';
+import { findMessagingProviderOnConnectionProvider } from 'src/engine/metadata-modules/messaging-provider/utils/find-messaging-provider-on-connection-provider.util';
+import { parseSendAppMessageResult } from 'src/engine/metadata-modules/messaging-provider/utils/parse-send-app-message-result.util';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+
+@Injectable()
+export class MessagingProviderMessageSenderService {
+ constructor(
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ private readonly logicFunctionExecutorService: LogicFunctionExecutorService,
+ ) {}
+
+ async resolveSenderOrThrow({
+ messagingProviderUniversalIdentifier,
+ connectionProviderId,
+ messageChannelId,
+ workspaceId,
+ }: {
+ messagingProviderUniversalIdentifier: string | null;
+ connectionProviderId: string;
+ messageChannelId: string;
+ workspaceId: string;
+ }): Promise<MessagingProviderSender> {
+ const {
+ flatMessagingProviderMaps,
+ flatConnectionProviderMaps,
+ flatLogicFunctionMaps,
+ } = await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatMessagingProviderMaps',
+ 'flatConnectionProviderMaps',
+ 'flatLogicFunctionMaps',
+ ]);
+
+ const messagingProvider = findMessagingProviderOnConnectionProvider({
+ flatMessagingProviderMaps,
+ flatConnectionProviderMaps,
+ messagingProviderUniversalIdentifier,
+ connectionProviderId,
+ });
+
+ if (!isDefined(messagingProvider)) {
+ throw new MessagingProviderException(
+ `Message channel ${messageChannelId} has no messaging provider on its connection provider`,
+ MessagingProviderExceptionCode.SEND_MESSAGE_NOT_AVAILABLE,
+ );
+ }
+
+ const sendMessageLogicFunction = findApplicationFlatLogicFunction({
+ flatLogicFunctionMaps,
+ universalIdentifier:
+ messagingProvider.sendMessageLogicFunctionUniversalIdentifier,
+ applicationId: messagingProvider.applicationId,
+ });
+
+ if (!isDefined(sendMessageLogicFunction)) {
+ throw new MessagingProviderException(
+ `Messaging provider ${messagingProvider.id} has no sendMessage logic function in its application`,
+ MessagingProviderExceptionCode.SEND_MESSAGE_NOT_AVAILABLE,
+ );
+ }
+
+ return {
+ messagingProvider,
+ sendMessageLogicFunctionId: sendMessageLogicFunction.id,
+ };
+ }
+
+ async sendOrThrow({
+ sender: { messagingProvider, sendMessageLogicFunctionId },
+ workspaceId,
+ payload,
+ }: {
+ sender: MessagingProviderSender;
+ workspaceId: string;
+ payload: Omit<SendAppMessagePayload, 'messagingProviderName'>;
+ }): Promise<SendAppMessageResult> {
+ const data = await this.logicFunctionExecutorService.executeOrThrow({
+ logicFunctionId: sendMessageLogicFunctionId,
+ workspaceId,
+ payload: { messagingProviderName: messagingProvider.name, ...payload },
+ shouldEnforceUsageLimits: true,
+ toException: (reason) =>
+ new MessagingProviderException(
+ `sendMessage logic function of messaging provider ${messagingProvider.id} ${reason}`,
+ MessagingProviderExceptionCode.SEND_MESSAGE_FAILED,
+ ),
+ });
+
+ const parsedResult = parseSendAppMessageResult(data);
+
+ if (!parsedResult.isValid) {
+ throw new MessagingProviderException(
+ `sendMessage logic function of messaging provider ${messagingProvider.id} returned an invalid result: ${parsedResult.reason}`,
+ MessagingProviderExceptionCode.SEND_MESSAGE_FAILED,
+ );
+ }
+
+ return parsedResult.sentMessage;
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/messaging-provider/types/messaging-provider-sender.type.ts b/packages/twenty-server/src/engine/metadata-modules/messaging-provider/types/messaging-provider-sender.type.ts
new file mode 100644
index 00000000000..cf25e301d6e
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/messaging-provider/types/messaging-provider-sender.type.ts
@@ -0,0 +1,6 @@
+import { type FlatMessagingProvider } from 'src/engine/metadata-modules/flat-messaging-provider/types/flat-messaging-provider.type';
+
+export type MessagingProviderSender = {
+ messagingProvider: Pick<FlatMessagingProvider, 'id' | 'name'>;
+ sendMessageLogicFunctionId: string;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/messaging-provider/utils/__tests__/parse-send-app-message-result.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/messaging-provider/utils/__tests__/parse-send-app-message-result.util.spec.ts
new file mode 100644
index 00000000000..f0d24dca7dd
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/messaging-provider/utils/__tests__/parse-send-app-message-result.util.spec.ts
@@ -0,0 +1,70 @@
+import { parseSendAppMessageResult } from 'src/engine/metadata-modules/messaging-provider/utils/parse-send-app-message-result.util';
+
+describe('parseSendAppMessageResult', () => {
+ it('returns the trimmed external id with the send time', () => {
+ expect(
+ parseSendAppMessageResult({
+ externalId: ' message-a ',
+ sentAt: '2026-10-23T09:30:00.000Z',
+ }),
+ ).toEqual({
+ isValid: true,
+ sentMessage: {
+ externalId: 'message-a',
+ sentAt: '2026-10-23T09:30:00.000Z',
+ },
+ });
+ });
+
+ it.each([
+ ['an ISO time without offset', '2026-10-23T09:30:00', true],
+ ['an epoch in milliseconds', 1792747800000, true],
+ ['an epoch in seconds', 1792747800, true],
+ ['a time that is not a date', 'today', false],
+ ])(
+ 'accepts %s as the send time, or leaves it out',
+ (_label, sentAt, isKept) => {
+ const result = parseSendAppMessageResult({
+ externalId: 'message-a',
+ sentAt,
+ });
+
+ expect(result.isValid).toBe(true);
+ expect(result.isValid && 'sentAt' in result.sentMessage).toBe(isKept);
+ },
+ );
+
+ it('reads an epoch in seconds as seconds', () => {
+ expect(
+ parseSendAppMessageResult({
+ externalId: 'message-a',
+ sentAt: 1792747800,
+ }),
+ ).toEqual({
+ isValid: true,
+ sentMessage: {
+ externalId: 'message-a',
+ sentAt: new Date(1792747800000).toISOString(),
+ },
+ });
+ });
+
+ it('leaves the send time out when it is absent or null', () => {
+ expect(
+ parseSendAppMessageResult({ externalId: 'message-a', sentAt: null }),
+ ).toEqual({ isValid: true, sentMessage: { externalId: 'message-a' } });
+ });
+
+ it.each([
+ ['a missing result', undefined],
+ ['a null result', null],
+ ['a missing id', {}],
+ ['a blank id', { externalId: ' ' }],
+ ['an id over 512 characters', { externalId: 'a'.repeat(513) }],
+ ])('rejects %s', (_label, data) => {
+ expect(parseSendAppMessageResult(data)).toEqual({
+ isValid: false,
+ reason: expect.any(String),
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/messaging-provider/utils/find-messaging-provider-on-connection-provider.util.ts b/packages/twenty-server/src/engine/metadata-modules/messaging-provider/utils/find-messaging-provider-on-connection-provider.util.ts
new file mode 100644
index 00000000000..14d7516a089
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/messaging-provider/utils/find-messaging-provider-on-connection-provider.util.ts
@@ -0,0 +1,43 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type FlatConnectionProviderMaps } from 'src/engine/metadata-modules/flat-connection-provider/types/flat-connection-provider-maps.type';
+import { type FlatMessagingProviderMaps } from 'src/engine/metadata-modules/flat-messaging-provider/types/flat-messaging-provider-maps.type';
+import { type FlatMessagingProvider } from 'src/engine/metadata-modules/flat-messaging-provider/types/flat-messaging-provider.type';
+
+export const findMessagingProviderOnConnectionProvider = ({
+ flatMessagingProviderMaps,
+ flatConnectionProviderMaps,
+ messagingProviderUniversalIdentifier,
+ connectionProviderId,
+}: {
+ flatMessagingProviderMaps: Pick<
+ FlatMessagingProviderMaps,
+ 'byUniversalIdentifier'
+ >;
+ flatConnectionProviderMaps: Pick<
+ FlatConnectionProviderMaps,
+ 'byUniversalIdentifier'
+ >;
+ messagingProviderUniversalIdentifier: string | null;
+ connectionProviderId: string | null;
+}): FlatMessagingProvider | undefined => {
+ const messagingProvider = isDefined(messagingProviderUniversalIdentifier)
+ ? flatMessagingProviderMaps.byUniversalIdentifier[
+ messagingProviderUniversalIdentifier
+ ]
+ : undefined;
+
+ if (!isDefined(messagingProvider)) {
+ return undefined;
+ }
+
+ const connectionProvider =
+ flatConnectionProviderMaps.byUniversalIdentifier[
+ messagingProvider.connectionProviderUniversalIdentifier
+ ];
+
+ return isDefined(connectionProvider) &&
+ connectionProvider.id === connectionProviderId
+ ? messagingProvider
+ : undefined;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/messaging-provider/utils/messaging-provider-graphql-api-exception-handler.util.ts b/packages/twenty-server/src/engine/metadata-modules/messaging-provider/utils/messaging-provider-graphql-api-exception-handler.util.ts
new file mode 100644
index 00000000000..86511827b8e
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/messaging-provider/utils/messaging-provider-graphql-api-exception-handler.util.ts
@@ -0,0 +1,39 @@
+import { assertUnreachable } from 'twenty-shared/utils';
+
+import {
+ ConflictError,
+ InternalServerError,
+ NotFoundError,
+ UserInputError,
+} from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
+import { LogicFunctionException } from 'src/engine/metadata-modules/logic-function/logic-function.exception';
+import { logicFunctionGraphQLApiExceptionHandler } from 'src/engine/metadata-modules/logic-function/utils/logic-function-graphql-api-exception-handler.utils';
+import {
+ MessagingProviderException,
+ MessagingProviderExceptionCode,
+} from 'src/engine/metadata-modules/messaging-provider/messaging-provider.exception';
+
+export const messagingProviderGraphqlApiExceptionHandler = (error: Error) => {
+ if (error instanceof MessagingProviderException) {
+ switch (error.code) {
+ case MessagingProviderExceptionCode.MESSAGING_PROVIDER_NOT_FOUND:
+ case MessagingProviderExceptionCode.SEND_MESSAGE_NOT_AVAILABLE:
+ throw new NotFoundError(error);
+ case MessagingProviderExceptionCode.INVALID_MESSAGING_PROVIDER_INPUT:
+ throw new UserInputError(error);
+ case MessagingProviderExceptionCode.MESSAGING_PROVIDER_NAME_ALREADY_EXISTS:
+ throw new ConflictError(error);
+ case MessagingProviderExceptionCode.SEND_MESSAGE_FAILED:
+ throw new InternalServerError(error);
+ default: {
+ return assertUnreachable(error.code);
+ }
+ }
+ }
+
+ if (error instanceof LogicFunctionException) {
+ return logicFunctionGraphQLApiExceptionHandler(error);
+ }
+
+ throw error;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/messaging-provider/utils/parse-send-app-message-result.util.ts b/packages/twenty-server/src/engine/metadata-modules/messaging-provider/utils/parse-send-app-message-result.util.ts
new file mode 100644
index 00000000000..dea4d5571a0
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/messaging-provider/utils/parse-send-app-message-result.util.ts
@@ -0,0 +1,54 @@
+import { type SendAppMessageResult } from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+import { z } from 'zod';
+
+import { formatLogicFunctionResultIssues } from 'src/engine/core-modules/logic-function/logic-function-executor/utils/format-logic-function-result-issues.util';
+import { isValidDate } from 'src/utils/date/isValidDate';
+
+const sendAppMessageResultSchema = z.object({
+ externalId: z.string().trim().min(1).max(512),
+ sentAt: z.union([z.string(), z.number()]).nullish(),
+});
+
+const EPOCH_MILLISECONDS_THRESHOLD = 1e11;
+
+type ParseSendAppMessageResultOutcome =
+ | { isValid: true; sentMessage: SendAppMessageResult }
+ | { isValid: false; reason: string };
+
+const toIsoDateOrUndefined = (
+ value: string | number | null | undefined,
+): string | undefined => {
+ if (!isDefined(value)) {
+ return undefined;
+ }
+
+ const date = new Date(
+ typeof value === 'number' && value < EPOCH_MILLISECONDS_THRESHOLD
+ ? value * 1000
+ : value,
+ );
+
+ return isValidDate(date) ? date.toISOString() : undefined;
+};
+
+export const parseSendAppMessageResult = (
+ data: unknown,
+): ParseSendAppMessageResultOutcome => {
+ const parsed = sendAppMessageResultSchema.safeParse(data);
+
+ if (!parsed.success) {
+ return {
+ isValid: false,
+ reason: formatLogicFunctionResultIssues(parsed.error),
+ };
+ }
+
+ const { externalId } = parsed.data;
+ const sentAt = toIsoDateOrUndefined(parsed.data.sentAt);
+
+ return {
+ isValid: true,
+ sentMessage: isDefined(sentAt) ? { externalId, sentAt } : { externalId },
+ };
+};
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/services/workspace-migration-build-orchestrator.service.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/services/workspace-migration-build-orchestrator.service.ts
index 352dc557a10..dfcf9427b27 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/services/workspace-migration-build-orchestrator.service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/services/workspace-migration-build-orchestrator.service.ts
@@ -33,6 +33,7 @@ import { WorkspaceMigrationAgentActionsBuilderService } from 'src/engine/workspa
import { WorkspaceMigrationApplicationVariableActionsBuilderService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/application-variable/workspace-migration-application-variable-actions-builder.service';
import { WorkspaceMigrationCommandMenuItemActionsBuilderService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/command-menu-item/workspace-migration-command-menu-item-actions-builder.service';
import { WorkspaceMigrationConnectionProviderActionsBuilderService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/connection-provider/workspace-migration-connection-provider-actions-builder.service';
+import { WorkspaceMigrationMessagingProviderActionsBuilderService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/messaging-provider/workspace-migration-messaging-provider-actions-builder.service';
import { WorkspaceMigrationTimelineActivityTypeActionsBuilderService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/timeline-activity-type/workspace-migration-timeline-activity-type-actions-builder.service';
import { WorkspaceMigrationValidationRuleActionsBuilderService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/validation-rule/workspace-migration-validation-rule-actions-builder.service';
import { WorkspaceMigrationFieldPermissionActionsBuilderService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/field-permission/workspace-migration-field-permission-actions-builder.service';
@@ -161,6 +162,7 @@ export class WorkspaceMigrationBuildOrchestratorService {
workspaceMigrationWebhookActionsBuilderService: WorkspaceMigrationWebhookActionsBuilderService,
workspaceMigrationApplicationVariableActionsBuilderService: WorkspaceMigrationApplicationVariableActionsBuilderService,
workspaceMigrationConnectionProviderActionsBuilderService: WorkspaceMigrationConnectionProviderActionsBuilderService,
+ workspaceMigrationMessagingProviderActionsBuilderService: WorkspaceMigrationMessagingProviderActionsBuilderService,
workspaceMigrationTimelineActivityTypeActionsBuilderService: WorkspaceMigrationTimelineActivityTypeActionsBuilderService,
workspaceMigrationValidationRuleActionsBuilderService: WorkspaceMigrationValidationRuleActionsBuilderService,
workspaceMigrationSearchFieldMetadataActionsBuilderService: WorkspaceMigrationSearchFieldMetadataActionsBuilderService,
@@ -296,6 +298,10 @@ export class WorkspaceMigrationBuildOrchestratorService {
ALL_METADATA_NAME.connectionProvider,
workspaceMigrationConnectionProviderActionsBuilderService,
),
+ createEntityActionsBuilderTask(
+ ALL_METADATA_NAME.messagingProvider,
+ workspaceMigrationMessagingProviderActionsBuilderService,
+ ),
createEntityActionsBuilderTask(
ALL_METADATA_NAME.timelineActivityType,
workspaceMigrationTimelineActivityTypeActionsBuilderService,
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/universal-flat-entity/constants/__tests__/__snapshots__/all-universal-flat-entity-foreign-key-aggregator-properties.constant.spec.ts.snap b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/universal-flat-entity/constants/__tests__/__snapshots__/all-universal-flat-entity-foreign-key-aggregator-properties.constant.spec.ts.snap
index 5b7697a66ec..9dc68953e90 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/universal-flat-entity/constants/__tests__/__snapshots__/all-universal-flat-entity-foreign-key-aggregator-properties.constant.spec.ts.snap
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/universal-flat-entity/constants/__tests__/__snapshots__/all-universal-flat-entity-foreign-key-aggregator-properties.constant.spec.ts.snap
@@ -26,6 +26,7 @@ exports[`ALL_UNIVERSAL_FLAT_ENTITY_FOREIGN_KEY_AGGREGATOR_PROPERTIES should matc
"frontComponent": [],
"index": [],
"logicFunction": [],
+ "messagingProvider": [],
"navigationMenuItem": [],
"objectMetadata": [
"fieldUniversalIdentifiers",
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/universal-flat-entity/constants/all-jsonb-properties-with-serialized-relation-by-metadata-name.constant.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/universal-flat-entity/constants/all-jsonb-properties-with-serialized-relation-by-metadata-name.constant.ts
index c4df264dbab..706f197ab62 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/universal-flat-entity/constants/all-jsonb-properties-with-serialized-relation-by-metadata-name.constant.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/universal-flat-entity/constants/all-jsonb-properties-with-serialized-relation-by-metadata-name.constant.ts
@@ -48,6 +48,7 @@ export const ALL_JSONB_PROPERTIES_WITH_SERIALIZED_RELATION_BY_METADATA_NAME = {
},
applicationVariable: {},
connectionProvider: {},
+ messagingProvider: {},
timelineActivityType: {},
validationRule: {},
searchFieldMetadata: {},
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-messaging-provider.type.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-messaging-provider.type.ts
new file mode 100644
index 00000000000..60b63cb9d51
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-messaging-provider.type.ts
@@ -0,0 +1,7 @@
+import { type MessagingProviderEntity } from 'src/engine/metadata-modules/messaging-provider/entities/messaging-provider.entity';
+import { type UniversalFlatEntityFrom } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-entity-from.type';
+
+export type UniversalFlatMessagingProvider = UniversalFlatEntityFrom<
+ MessagingProviderEntity,
+ 'messagingProvider'
+>;
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/utils/compute-ordered-migration-actions.util.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/utils/compute-ordered-migration-actions.util.ts
index 22612f956ca..a712b0d32bd 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/utils/compute-ordered-migration-actions.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/utils/compute-ordered-migration-actions.util.ts
@@ -154,6 +154,9 @@ export const computeOrderedMigrationActions = (
...aggregatedOrchestratorActionsReport.connectionProvider.delete,
...aggregatedOrchestratorActionsReport.connectionProvider.create,
...aggregatedOrchestratorActionsReport.connectionProvider.update,
+ ...aggregatedOrchestratorActionsReport.messagingProvider.delete,
+ ...aggregatedOrchestratorActionsReport.messagingProvider.create,
+ ...aggregatedOrchestratorActionsReport.messagingProvider.update,
...aggregatedOrchestratorActionsReport.timelineActivityType.delete,
...aggregatedOrchestratorActionsReport.timelineActivityType.create,
...aggregatedOrchestratorActionsReport.timelineActivityType.update,
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/messaging-provider/types/workspace-migration-messaging-provider-action.type.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/messaging-provider/types/workspace-migration-messaging-provider-action.type.ts
new file mode 100644
index 00000000000..7590854b191
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/messaging-provider/types/workspace-migration-messaging-provider-action.type.ts
@@ -0,0 +1,24 @@
+import { type BaseFlatCreateWorkspaceMigrationAction } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/types/base-flat-create-workspace-migration-action.type';
+import { type BaseFlatDeleteWorkspaceMigrationAction } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/types/base-flat-delete-workspace-migration-action.type';
+import { type BaseFlatUpdateWorkspaceMigrationAction } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/types/base-flat-update-workspace-migration-action.type';
+import { type BaseUniversalCreateWorkspaceMigrationAction } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/types/base-universal-create-workspace-migration-action.type';
+import { type BaseUniversalDeleteWorkspaceMigrationAction } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/types/base-universal-delete-workspace-migration-action.type';
+import { type BaseUniversalUpdateWorkspaceMigrationAction } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/types/base-universal-update-workspace-migration-action.type';
+
+export type FlatCreateMessagingProviderAction =
+ BaseFlatCreateWorkspaceMigrationAction<'messagingProvider'>;
+
+export type UniversalCreateMessagingProviderAction =
+ BaseUniversalCreateWorkspaceMigrationAction<'messagingProvider'>;
+
+export type FlatUpdateMessagingProviderAction =
+ BaseFlatUpdateWorkspaceMigrationAction<'messagingProvider'>;
+
+export type UniversalUpdateMessagingProviderAction =
+ BaseUniversalUpdateWorkspaceMigrationAction<'messagingProvider'>;
+
+export type UniversalDeleteMessagingProviderAction =
+ BaseUniversalDeleteWorkspaceMigrationAction<'messagingProvider'>;
+
+export type FlatDeleteMessagingProviderAction =
+ BaseFlatDeleteWorkspaceMigrationAction<'messagingProvider'>;
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/messaging-provider/workspace-migration-messaging-provider-actions-builder.service.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/messaging-provider/workspace-migration-messaging-provider-actions-builder.service.ts
new file mode 100644
index 00000000000..11dd2a2dca6
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/messaging-provider/workspace-migration-messaging-provider-actions-builder.service.ts
@@ -0,0 +1,122 @@
+import { Injectable } from '@nestjs/common';
+
+import { ALL_METADATA_NAME } from 'twenty-shared/metadata';
+
+import { UniversalUpdateMessagingProviderAction } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/messaging-provider/types/workspace-migration-messaging-provider-action.type';
+import { WorkspaceEntityMigrationBuilderService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/services/workspace-entity-migration-builder.service';
+import { FlatEntityUpdateValidationArgs } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/types/universal-flat-entity-update-validation-args.type';
+import { UniversalFlatEntityValidationArgs } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/types/universal-flat-entity-validation-args.type';
+import { UniversalFlatEntityValidationReturnType } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/types/universal-flat-entity-validation-result.type';
+import { FlatMessagingProviderValidatorService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-messaging-provider-validator.service';
+
+@Injectable()
+export class WorkspaceMigrationMessagingProviderActionsBuilderService extends WorkspaceEntityMigrationBuilderService<
+ typeof ALL_METADATA_NAME.messagingProvider
+> {
+ constructor(
+ private readonly flatMessagingProviderValidatorService: FlatMessagingProviderValidatorService,
+ ) {
+ super(ALL_METADATA_NAME.messagingProvider);
+ }
+
+ protected validateFlatEntityCreation(
+ args: UniversalFlatEntityValidationArgs<
+ typeof ALL_METADATA_NAME.messagingProvider
+ >,
+ ): UniversalFlatEntityValidationReturnType<
+ typeof ALL_METADATA_NAME.messagingProvider,
+ 'create'
+ > {
+ const validationResult =
+ this.flatMessagingProviderValidatorService.validateFlatMessagingProviderCreation(
+ args,
+ );
+
+ if (validationResult.errors.length > 0) {
+ return {
+ status: 'fail',
+ ...validationResult,
+ };
+ }
+
+ const { flatEntityToValidate: flatMessagingProviderToValidate } = args;
+
+ return {
+ status: 'success',
+ action: {
+ type: 'create',
+ metadataName: 'messagingProvider',
+ flatEntity: flatMessagingProviderToValidate,
+ },
+ };
+ }
+
+ protected validateFlatEntityDeletion(
+ args: UniversalFlatEntityValidationArgs<
+ typeof ALL_METADATA_NAME.messagingProvider
+ >,
+ ): UniversalFlatEntityValidationReturnType<
+ typeof ALL_METADATA_NAME.messagingProvider,
+ 'delete'
+ > {
+ const validationResult =
+ this.flatMessagingProviderValidatorService.validateFlatMessagingProviderDeletion(
+ args,
+ );
+
+ if (validationResult.errors.length > 0) {
+ return {
+ status: 'fail',
+ ...validationResult,
+ };
+ }
+
+ const { flatEntityToValidate: flatMessagingProviderToValidate } = args;
+
+ return {
+ status: 'success',
+ action: {
+ type: 'delete',
+ metadataName: 'messagingProvider',
+ universalIdentifier:
+ flatMessagingProviderToValidate.universalIdentifier,
+ },
+ };
+ }
+
+ protected validateFlatEntityUpdate(
+ args: FlatEntityUpdateValidationArgs<
+ typeof ALL_METADATA_NAME.messagingProvider
+ >,
+ ): UniversalFlatEntityValidationReturnType<
+ typeof ALL_METADATA_NAME.messagingProvider,
+ 'update'
+ > {
+ const validationResult =
+ this.flatMessagingProviderValidatorService.validateFlatMessagingProviderUpdate(
+ args,
+ );
+
+ if (validationResult.errors.length > 0) {
+ return {
+ status: 'fail',
+ ...validationResult,
+ };
+ }
+
+ const { universalIdentifier, flatEntityUpdate } = args;
+
+ const updateMessagingProviderAction: UniversalUpdateMessagingProviderAction =
+ {
+ type: 'update',
+ metadataName: 'messagingProvider',
+ universalIdentifier,
+ update: flatEntityUpdate,
+ };
+
+ return {
+ status: 'success',
+ action: updateMessagingProviderAction,
+ };
+ }
+}
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-connection-provider-validator.service.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-connection-provider-validator.service.ts
index 4cc431855d5..700b9aa12df 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-connection-provider-validator.service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-connection-provider-validator.service.ts
@@ -84,6 +84,24 @@ export class FlatConnectionProviderValidatorService {
}
}
+ if (flatConnectionProvider.type === 'custom') {
+ const customConfig = flatConnectionProvider.customConfig;
+
+ if (
+ !isDefined(customConfig) ||
+ !isNonEmptyString(
+ customConfig.authorizeLogicFunctionUniversalIdentifier,
+ ) ||
+ !isNonEmptyString(customConfig.callbackLogicFunctionUniversalIdentifier)
+ ) {
+ validationResult.errors.push({
+ code: ConnectionProviderExceptionCode.INVALID_CONNECTION_PROVIDER_INPUT,
+ message: t`Connection provider with type 'custom' must reference an authorize and a callback logic function`,
+ userFriendlyMessage: msg`Custom connection provider is missing its authorize or callback logic function`,
+ });
+ }
+ }
+
const existingByName = Object.values(
optimisticFlatConnectionProviderMaps.byUniversalIdentifier,
).find(
@@ -185,6 +203,17 @@ export class FlatConnectionProviderValidatorService {
});
}
+ if (
+ isDefined(flatEntityUpdate.type) &&
+ flatEntityUpdate.type !== fromFlatConnectionProvider.type
+ ) {
+ validationResult.errors.push({
+ code: ConnectionProviderExceptionCode.INVALID_CONNECTION_PROVIDER_INPUT,
+ message: t`Connection provider type cannot be changed after creation: declare a new connection provider with a new universalIdentifier`,
+ userFriendlyMessage: msg`Connection provider type cannot be changed`,
+ });
+ }
+
return validationResult;
}
}
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-messaging-provider-validator.service.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-messaging-provider-validator.service.ts
new file mode 100644
index 00000000000..d369c2835a2
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-messaging-provider-validator.service.ts
@@ -0,0 +1,293 @@
+import { Injectable } from '@nestjs/common';
+
+import { msg, t } from '@lingui/core/macro';
+import { isNonEmptyString } from '@sniptt/guards';
+import { ALL_METADATA_NAME } from 'twenty-shared/metadata';
+import { isDefined } from 'twenty-shared/utils';
+
+import { findFlatEntityByUniversalIdentifier } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-universal-identifier.util';
+import { MessagingProviderExceptionCode } from 'src/engine/metadata-modules/messaging-provider/messaging-provider.exception';
+import { type UniversalSyncableFlatEntity } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-entity-from.type';
+import { type UniversalFlatEntityMaps } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-entity-maps.type';
+import { type MetadataUniversalFlatEntityMaps } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/metadata-universal-flat-entity-maps.type';
+import { type UniversalFlatMessagingProvider } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-messaging-provider.type';
+import {
+ type FailedFlatEntityValidation,
+ type FlatEntityValidationError,
+} from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/types/failed-flat-entity-validation.type';
+import { getEmptyFlatEntityValidationError } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/utils/get-flat-entity-validation-error.util';
+import { type FlatEntityUpdateValidationArgs } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/types/universal-flat-entity-update-validation-args.type';
+import { type UniversalFlatEntityValidationArgs } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/types/universal-flat-entity-validation-args.type';
+
+const isInApplication = <TFlatEntity extends UniversalSyncableFlatEntity>({
+ flatEntityMaps,
+ universalIdentifier,
+ applicationUniversalIdentifier,
+}: {
+ flatEntityMaps: UniversalFlatEntityMaps<TFlatEntity>;
+ universalIdentifier: string;
+ applicationUniversalIdentifier: string;
+}): boolean =>
+ findFlatEntityByUniversalIdentifier({ flatEntityMaps, universalIdentifier })
+ ?.applicationUniversalIdentifier === applicationUniversalIdentifier;
+
+const validateMessagingProviderReferences = ({
+ flatMessagingProvider,
+ flatConnectionProviderMaps,
+ flatLogicFunctionMaps,
+}: {
+ flatMessagingProvider: Pick<
+ UniversalFlatMessagingProvider,
+ | 'applicationUniversalIdentifier'
+ | 'connectionProviderUniversalIdentifier'
+ | 'sendMessageLogicFunctionUniversalIdentifier'
+ >;
+ flatConnectionProviderMaps: MetadataUniversalFlatEntityMaps<'connectionProvider'>;
+ flatLogicFunctionMaps: MetadataUniversalFlatEntityMaps<'logicFunction'>;
+}): FlatEntityValidationError[] => {
+ const errors: FlatEntityValidationError[] = [];
+
+ if (
+ !isInApplication({
+ flatEntityMaps: flatConnectionProviderMaps,
+ universalIdentifier:
+ flatMessagingProvider.connectionProviderUniversalIdentifier,
+ applicationUniversalIdentifier:
+ flatMessagingProvider.applicationUniversalIdentifier,
+ })
+ ) {
+ errors.push({
+ code: MessagingProviderExceptionCode.INVALID_MESSAGING_PROVIDER_INPUT,
+ message: t`Connection provider "${flatMessagingProvider.connectionProviderUniversalIdentifier}" was not found in this application`,
+ userFriendlyMessage: msg`The connection provider this messaging provider uses was not found in its application.`,
+ });
+ }
+
+ const sendMessageLogicFunctionUniversalIdentifier =
+ flatMessagingProvider.sendMessageLogicFunctionUniversalIdentifier;
+
+ if (
+ isDefined(sendMessageLogicFunctionUniversalIdentifier) &&
+ !isInApplication({
+ flatEntityMaps: flatLogicFunctionMaps,
+ universalIdentifier: sendMessageLogicFunctionUniversalIdentifier,
+ applicationUniversalIdentifier:
+ flatMessagingProvider.applicationUniversalIdentifier,
+ })
+ ) {
+ errors.push({
+ code: MessagingProviderExceptionCode.INVALID_MESSAGING_PROVIDER_INPUT,
+ message: t`Send message logic function "${sendMessageLogicFunctionUniversalIdentifier}" was not found in this application`,
+ userFriendlyMessage: msg`The logic function this messaging provider sends with was not found in its application.`,
+ });
+ }
+
+ return errors;
+};
+
+const findOtherMessagingProviderWithName = ({
+ flatMessagingProviderMaps,
+ name,
+ applicationUniversalIdentifier,
+ universalIdentifier,
+}: {
+ flatMessagingProviderMaps: Pick<
+ MetadataUniversalFlatEntityMaps<'messagingProvider'>,
+ 'byUniversalIdentifier'
+ >;
+ name: string;
+ applicationUniversalIdentifier: string;
+ universalIdentifier: string;
+}) =>
+ Object.values(flatMessagingProviderMaps.byUniversalIdentifier).find(
+ (existing) =>
+ isDefined(existing) &&
+ existing.name === name &&
+ existing.applicationUniversalIdentifier ===
+ applicationUniversalIdentifier &&
+ existing.universalIdentifier !== universalIdentifier,
+ );
+
+const getNameAlreadyExistsError = (
+ name: string,
+): FlatEntityValidationError => ({
+ code: MessagingProviderExceptionCode.MESSAGING_PROVIDER_NAME_ALREADY_EXISTS,
+ message: t`Messaging provider with name ${name} already exists for this application`,
+ userFriendlyMessage: msg`A messaging provider with this name already exists for this application`,
+});
+
+@Injectable()
+export class FlatMessagingProviderValidatorService {
+ public validateFlatMessagingProviderCreation({
+ flatEntityToValidate: flatMessagingProvider,
+ optimisticFlatEntityMapsAndRelatedFlatEntityMaps: {
+ flatMessagingProviderMaps: optimisticFlatMessagingProviderMaps,
+ flatConnectionProviderMaps,
+ flatLogicFunctionMaps,
+ },
+ }: UniversalFlatEntityValidationArgs<
+ typeof ALL_METADATA_NAME.messagingProvider
+ >): FailedFlatEntityValidation<'messagingProvider', 'create'> {
+ const validationResult = getEmptyFlatEntityValidationError({
+ flatEntityMinimalInformation: {
+ universalIdentifier: flatMessagingProvider.universalIdentifier,
+ name: flatMessagingProvider.name,
+ },
+ metadataName: 'messagingProvider',
+ type: 'create',
+ });
+
+ if (!isNonEmptyString(flatMessagingProvider.name)) {
+ validationResult.errors.push({
+ code: MessagingProviderExceptionCode.INVALID_MESSAGING_PROVIDER_INPUT,
+ message: t`Messaging provider name is required`,
+ userFriendlyMessage: msg`Messaging provider name is required`,
+ });
+ }
+
+ if (!isNonEmptyString(flatMessagingProvider.displayName)) {
+ validationResult.errors.push({
+ code: MessagingProviderExceptionCode.INVALID_MESSAGING_PROVIDER_INPUT,
+ message: t`Messaging provider displayName is required`,
+ userFriendlyMessage: msg`Messaging provider display name is required`,
+ });
+ }
+
+ validationResult.errors.push(
+ ...validateMessagingProviderReferences({
+ flatMessagingProvider,
+ flatConnectionProviderMaps,
+ flatLogicFunctionMaps,
+ }),
+ );
+
+ if (
+ isDefined(
+ findOtherMessagingProviderWithName({
+ flatMessagingProviderMaps: optimisticFlatMessagingProviderMaps,
+ name: flatMessagingProvider.name,
+ applicationUniversalIdentifier:
+ flatMessagingProvider.applicationUniversalIdentifier,
+ universalIdentifier: flatMessagingProvider.universalIdentifier,
+ }),
+ )
+ ) {
+ validationResult.errors.push(
+ getNameAlreadyExistsError(flatMessagingProvider.name),
+ );
+ }
+
+ return validationResult;
+ }
+
+ public validateFlatMessagingProviderDeletion({
+ flatEntityToValidate,
+ optimisticFlatEntityMapsAndRelatedFlatEntityMaps: {
+ flatMessagingProviderMaps: optimisticFlatMessagingProviderMaps,
+ },
+ }: UniversalFlatEntityValidationArgs<
+ typeof ALL_METADATA_NAME.messagingProvider
+ >): FailedFlatEntityValidation<'messagingProvider', 'delete'> {
+ const validationResult = getEmptyFlatEntityValidationError({
+ flatEntityMinimalInformation: {
+ universalIdentifier: flatEntityToValidate.universalIdentifier,
+ name: flatEntityToValidate.name,
+ },
+ metadataName: 'messagingProvider',
+ type: 'delete',
+ });
+
+ const existingMessagingProvider = findFlatEntityByUniversalIdentifier({
+ universalIdentifier: flatEntityToValidate.universalIdentifier,
+ flatEntityMaps: optimisticFlatMessagingProviderMaps,
+ });
+
+ if (!isDefined(existingMessagingProvider)) {
+ validationResult.errors.push({
+ code: MessagingProviderExceptionCode.MESSAGING_PROVIDER_NOT_FOUND,
+ message: t`Messaging provider not found`,
+ userFriendlyMessage: msg`Messaging provider not found`,
+ });
+ }
+
+ return validationResult;
+ }
+
+ public validateFlatMessagingProviderUpdate({
+ universalIdentifier,
+ flatEntityUpdate,
+ optimisticFlatEntityMapsAndRelatedFlatEntityMaps: {
+ flatMessagingProviderMaps: optimisticFlatMessagingProviderMaps,
+ flatConnectionProviderMaps,
+ flatLogicFunctionMaps,
+ },
+ }: FlatEntityUpdateValidationArgs<
+ typeof ALL_METADATA_NAME.messagingProvider
+ >): FailedFlatEntityValidation<'messagingProvider', 'update'> {
+ const validationResult = getEmptyFlatEntityValidationError({
+ flatEntityMinimalInformation: {
+ universalIdentifier,
+ },
+ metadataName: 'messagingProvider',
+ type: 'update',
+ });
+
+ const fromFlatMessagingProvider = findFlatEntityByUniversalIdentifier({
+ universalIdentifier,
+ flatEntityMaps: optimisticFlatMessagingProviderMaps,
+ });
+
+ if (!isDefined(fromFlatMessagingProvider)) {
+ validationResult.errors.push({
+ code: MessagingProviderExceptionCode.MESSAGING_PROVIDER_NOT_FOUND,
+ message: t`Messaging provider not found`,
+ userFriendlyMessage: msg`Messaging provider not found`,
+ });
+
+ return validationResult;
+ }
+
+ if (
+ isDefined(flatEntityUpdate.name) &&
+ flatEntityUpdate.name !== fromFlatMessagingProvider.name &&
+ isDefined(
+ findOtherMessagingProviderWithName({
+ flatMessagingProviderMaps: optimisticFlatMessagingProviderMaps,
+ name: flatEntityUpdate.name,
+ applicationUniversalIdentifier:
+ fromFlatMessagingProvider.applicationUniversalIdentifier,
+ universalIdentifier,
+ }),
+ )
+ ) {
+ validationResult.errors.push(
+ getNameAlreadyExistsError(flatEntityUpdate.name),
+ );
+ }
+
+ if (
+ isDefined(flatEntityUpdate.connectionProviderUniversalIdentifier) &&
+ flatEntityUpdate.connectionProviderUniversalIdentifier !==
+ fromFlatMessagingProvider.connectionProviderUniversalIdentifier
+ ) {
+ validationResult.errors.push({
+ code: MessagingProviderExceptionCode.INVALID_MESSAGING_PROVIDER_INPUT,
+ message: t`Messaging provider connection provider cannot be changed after creation: declare a new messaging provider with a new universalIdentifier`,
+ userFriendlyMessage: msg`Messaging provider connection provider cannot be changed`,
+ });
+ }
+
+ validationResult.errors.push(
+ ...validateMessagingProviderReferences({
+ flatMessagingProvider: {
+ ...fromFlatMessagingProvider,
+ ...flatEntityUpdate,
+ },
+ flatConnectionProviderMaps,
+ flatLogicFunctionMaps,
+ }),
+ );
+
+ return validationResult;
+ }
+}
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/workspace-migration-builder-validators.module.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/workspace-migration-builder-validators.module.ts
index 23b513fedf5..01c6a7446e9 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/workspace-migration-builder-validators.module.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/workspace-migration-builder-validators.module.ts
@@ -31,6 +31,7 @@ import { FlatViewSortValidatorService } from 'src/engine/workspace-manager/works
import { FlatApplicationVariableValidatorService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-application-variable-validator.service';
import { FlatWebhookValidatorService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-webhook-validator.service';
import { FlatConnectionProviderValidatorService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-connection-provider-validator.service';
+import { FlatMessagingProviderValidatorService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-messaging-provider-validator.service';
import { FlatTimelineActivityTypeValidatorService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-timeline-activity-type-validator.service';
import { FlatAgentChatChannelRoleValidatorService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-agent-chat-channel-role-validator.service';
import { FlatAgentChatChannelValidatorService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-agent-chat-channel-validator.service';
@@ -71,6 +72,7 @@ import { FlatSearchFieldMetadataValidatorService } from 'src/engine/workspace-ma
FlatWebhookValidatorService,
FlatApplicationVariableValidatorService,
FlatConnectionProviderValidatorService,
+ FlatMessagingProviderValidatorService,
FlatTimelineActivityTypeValidatorService,
FlatSettingsMenuItemValidatorService,
FlatAgentChatChannelValidatorService,
@@ -108,6 +110,7 @@ import { FlatSearchFieldMetadataValidatorService } from 'src/engine/workspace-ma
FlatWebhookValidatorService,
FlatApplicationVariableValidatorService,
FlatConnectionProviderValidatorService,
+ FlatMessagingProviderValidatorService,
FlatTimelineActivityTypeValidatorService,
FlatSettingsMenuItemValidatorService,
FlatAgentChatChannelValidatorService,
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/workspace-migration-builder.module.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/workspace-migration-builder.module.ts
index c77f264eada..b70f3c6839f 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/workspace-migration-builder.module.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/workspace-migration-builder.module.ts
@@ -34,6 +34,7 @@ import { WorkspaceMigrationViewActionsBuilderService } from 'src/engine/workspac
import { WorkspaceMigrationApplicationVariableActionsBuilderService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/application-variable/workspace-migration-application-variable-actions-builder.service';
import { WorkspaceMigrationWebhookActionsBuilderService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/webhook/workspace-migration-webhook-actions-builder.service';
import { WorkspaceMigrationConnectionProviderActionsBuilderService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/connection-provider/workspace-migration-connection-provider-actions-builder.service';
+import { WorkspaceMigrationMessagingProviderActionsBuilderService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/messaging-provider/workspace-migration-messaging-provider-actions-builder.service';
import { WorkspaceMigrationTimelineActivityTypeActionsBuilderService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/timeline-activity-type/workspace-migration-timeline-activity-type-actions-builder.service';
import { WorkspaceMigrationAgentChatChannelActionsBuilderService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/agent-chat-channel/workspace-migration-agent-chat-channel-actions-builder.service';
import { WorkspaceMigrationAgentChatChannelRoleActionsBuilderService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/agent-chat-channel-role/workspace-migration-agent-chat-channel-role-actions-builder.service';
@@ -78,6 +79,7 @@ import { WorkspaceMigrationBuilderValidatorsModule } from 'src/engine/workspace-
WorkspaceMigrationWebhookActionsBuilderService,
WorkspaceMigrationApplicationVariableActionsBuilderService,
WorkspaceMigrationConnectionProviderActionsBuilderService,
+ WorkspaceMigrationMessagingProviderActionsBuilderService,
WorkspaceMigrationTimelineActivityTypeActionsBuilderService,
WorkspaceMigrationSettingsMenuItemActionsBuilderService,
WorkspaceMigrationAgentChatChannelActionsBuilderService,
@@ -118,6 +120,7 @@ import { WorkspaceMigrationBuilderValidatorsModule } from 'src/engine/workspace-
WorkspaceMigrationWebhookActionsBuilderService,
WorkspaceMigrationApplicationVariableActionsBuilderService,
WorkspaceMigrationConnectionProviderActionsBuilderService,
+ WorkspaceMigrationMessagingProviderActionsBuilderService,
WorkspaceMigrationTimelineActivityTypeActionsBuilderService,
WorkspaceMigrationSettingsMenuItemActionsBuilderService,
WorkspaceMigrationAgentChatChannelActionsBuilderService,
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/messaging-provider/services/create-messaging-provider-action-handler.service.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/messaging-provider/services/create-messaging-provider-action-handler.service.ts
new file mode 100644
index 00000000000..77f54a95930
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/messaging-provider/services/create-messaging-provider-action-handler.service.ts
@@ -0,0 +1,65 @@
+import { Injectable } from '@nestjs/common';
+
+import { v4 } from 'uuid';
+
+import { WorkspaceMigrationRunnerActionHandler } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/interfaces/workspace-migration-runner-action-handler-service.interface';
+
+import { getUniversalFlatEntityEmptyForeignKeyAggregators } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/utils/reset-universal-flat-entity-foreign-key-aggregators.util';
+import {
+ FlatCreateMessagingProviderAction,
+ UniversalCreateMessagingProviderAction,
+} from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/messaging-provider/types/workspace-migration-messaging-provider-action.type';
+import {
+ WorkspaceMigrationActionRunnerArgs,
+ WorkspaceMigrationActionRunnerContext,
+} from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/workspace-migration-action-runner-args.type';
+
+@Injectable()
+export class CreateMessagingProviderActionHandlerService extends WorkspaceMigrationRunnerActionHandler(
+ 'create',
+ 'messagingProvider',
+) {
+ constructor() {
+ super();
+ }
+
+ override async transpileUniversalActionToFlatAction({
+ action,
+ flatApplication,
+ workspaceId,
+ }: WorkspaceMigrationActionRunnerArgs<UniversalCreateMessagingProviderAction>): Promise<FlatCreateMessagingProviderAction> {
+ const emptyUniversalForeignKeyAggregators =
+ getUniversalFlatEntityEmptyForeignKeyAggregators({
+ metadataName: 'messagingProvider',
+ });
+
+ return {
+ ...action,
+ flatEntity: {
+ ...action.flatEntity,
+ applicationId: flatApplication.id,
+ id: action.id ?? v4(),
+ workspaceId,
+ ...emptyUniversalForeignKeyAggregators,
+ },
+ };
+ }
+
+ async executeForMetadata(
+ context: WorkspaceMigrationActionRunnerContext<FlatCreateMessagingProviderAction>,
+ ): Promise<void> {
+ const { flatAction, queryRunner } = context;
+ const { flatEntity } = flatAction;
+
+ await this.insertFlatEntitiesInRepository({
+ queryRunner,
+ flatEntities: [flatEntity],
+ });
+ }
+
+ async executeForWorkspaceSchema(
+ _context: WorkspaceMigrationActionRunnerContext<FlatCreateMessagingProviderAction>,
+ ): Promise<void> {
+ return;
+ }
+}
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/messaging-provider/services/delete-messaging-provider-action-handler.service.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/messaging-provider/services/delete-messaging-provider-action-handler.service.ts
new file mode 100644
index 00000000000..684c547b8a3
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/messaging-provider/services/delete-messaging-provider-action-handler.service.ts
@@ -0,0 +1,51 @@
+import { Injectable } from '@nestjs/common';
+
+import { WorkspaceMigrationRunnerActionHandler } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/interfaces/workspace-migration-runner-action-handler-service.interface';
+
+import { MessagingProviderEntity } from 'src/engine/metadata-modules/messaging-provider/entities/messaging-provider.entity';
+import {
+ FlatDeleteMessagingProviderAction,
+ UniversalDeleteMessagingProviderAction,
+} from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/messaging-provider/types/workspace-migration-messaging-provider-action.type';
+import {
+ WorkspaceMigrationActionRunnerArgs,
+ WorkspaceMigrationActionRunnerContext,
+} from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/workspace-migration-action-runner-args.type';
+
+@Injectable()
+export class DeleteMessagingProviderActionHandlerService extends WorkspaceMigrationRunnerActionHandler(
+ 'delete',
+ 'messagingProvider',
+) {
+ constructor() {
+ super();
+ }
+
+ override async transpileUniversalActionToFlatAction(
+ context: WorkspaceMigrationActionRunnerArgs<UniversalDeleteMessagingProviderAction>,
+ ): Promise<FlatDeleteMessagingProviderAction> {
+ return this.transpileUniversalDeleteActionToFlatDeleteAction(context);
+ }
+
+ async executeForMetadata(
+ context: WorkspaceMigrationActionRunnerContext<FlatDeleteMessagingProviderAction>,
+ ): Promise<void> {
+ const { flatAction, queryRunner, workspaceId } = context;
+
+ const messagingProviderRepository =
+ queryRunner.manager.getRepository<MessagingProviderEntity>(
+ MessagingProviderEntity,
+ );
+
+ await messagingProviderRepository.delete({
+ id: flatAction.entityId,
+ workspaceId,
+ });
+ }
+
+ async executeForWorkspaceSchema(
+ _context: WorkspaceMigrationActionRunnerContext<FlatDeleteMessagingProviderAction>,
+ ): Promise<void> {
+ return;
+ }
+}
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/messaging-provider/services/update-messaging-provider-action-handler.service.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/messaging-provider/services/update-messaging-provider-action-handler.service.ts
new file mode 100644
index 00000000000..9d46f688966
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/messaging-provider/services/update-messaging-provider-action-handler.service.ts
@@ -0,0 +1,68 @@
+import { Injectable } from '@nestjs/common';
+
+import { WorkspaceMigrationRunnerActionHandler } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/interfaces/workspace-migration-runner-action-handler-service.interface';
+
+import { MessagingProviderEntity } from 'src/engine/metadata-modules/messaging-provider/entities/messaging-provider.entity';
+import { findFlatEntityByUniversalIdentifierOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-universal-identifier-or-throw.util';
+import { resolveUniversalUpdateRelationIdentifiersToIds } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/utils/resolve-universal-update-relation-identifiers-to-ids.util';
+import {
+ FlatUpdateMessagingProviderAction,
+ UniversalUpdateMessagingProviderAction,
+} from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/builders/messaging-provider/types/workspace-migration-messaging-provider-action.type';
+import {
+ WorkspaceMigrationActionRunnerArgs,
+ WorkspaceMigrationActionRunnerContext,
+} from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/types/workspace-migration-action-runner-args.type';
+
+@Injectable()
+export class UpdateMessagingProviderActionHandlerService extends WorkspaceMigrationRunnerActionHandler(
+ 'update',
+ 'messagingProvider',
+) {
+ override async transpileUniversalActionToFlatAction(
+ context: WorkspaceMigrationActionRunnerArgs<UniversalUpdateMessagingProviderAction>,
+ ): Promise<FlatUpdateMessagingProviderAction> {
+ const { action, allFlatEntityMaps } = context;
+
+ const flatMessagingProvider = findFlatEntityByUniversalIdentifierOrThrow({
+ flatEntityMaps: allFlatEntityMaps.flatMessagingProviderMaps,
+ universalIdentifier: action.universalIdentifier,
+ });
+
+ const update = resolveUniversalUpdateRelationIdentifiersToIds({
+ metadataName: 'messagingProvider',
+ universalUpdate: action.update,
+ allFlatEntityMaps,
+ });
+
+ return {
+ type: 'update',
+ metadataName: 'messagingProvider',
+ entityId: flatMessagingProvider.id,
+ update,
+ };
+ }
+
+ async executeForMetadata(
+ context: WorkspaceMigrationActionRunnerContext<FlatUpdateMessagingProviderAction>,
+ ): Promise<void> {
+ const { flatAction, queryRunner, workspaceId } = context;
+ const { entityId, update } = flatAction;
+
+ const messagingProviderRepository =
+ queryRunner.manager.getRepository<MessagingProviderEntity>(
+ MessagingProviderEntity,
+ );
+
+ await messagingProviderRepository.update(
+ { id: entityId, workspaceId },
+ update,
+ );
+ }
+
+ async executeForWorkspaceSchema(
+ _context: WorkspaceMigrationActionRunnerContext<FlatUpdateMessagingProviderAction>,
+ ): Promise<void> {
+ return;
+ }
+}
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/workspace-schema-migration-runner-action-handlers.module.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/workspace-schema-migration-runner-action-handlers.module.ts
index ad37fbe497d..32c6e231f42 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/workspace-schema-migration-runner-action-handlers.module.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/workspace-schema-migration-runner-action-handlers.module.ts
@@ -98,6 +98,9 @@ import { UpdateWebhookActionHandlerService } from 'src/engine/workspace-manager/
import { CreateConnectionProviderActionHandlerService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/connection-provider/services/create-connection-provider-action-handler.service';
import { DeleteConnectionProviderActionHandlerService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/connection-provider/services/delete-connection-provider-action-handler.service';
import { UpdateConnectionProviderActionHandlerService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/connection-provider/services/update-connection-provider-action-handler.service';
+import { CreateMessagingProviderActionHandlerService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/messaging-provider/services/create-messaging-provider-action-handler.service';
+import { DeleteMessagingProviderActionHandlerService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/messaging-provider/services/delete-messaging-provider-action-handler.service';
+import { UpdateMessagingProviderActionHandlerService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/messaging-provider/services/update-messaging-provider-action-handler.service';
import { CreateTimelineActivityTypeActionHandlerService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/timeline-activity-type/services/create-timeline-activity-type-action-handler.service';
import { DeleteTimelineActivityTypeActionHandlerService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/timeline-activity-type/services/delete-timeline-activity-type-action-handler.service';
import { UpdateTimelineActivityTypeActionHandlerService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/action-handlers/timeline-activity-type/services/update-timeline-activity-type-action-handler.service';
@@ -259,6 +262,9 @@ import { WorkflowDeletionModule } from 'src/modules/workflow/workflow-deletion/w
CreateConnectionProviderActionHandlerService,
UpdateConnectionProviderActionHandlerService,
DeleteConnectionProviderActionHandlerService,
+ CreateMessagingProviderActionHandlerService,
+ UpdateMessagingProviderActionHandlerService,
+ DeleteMessagingProviderActionHandlerService,
CreateTimelineActivityTypeActionHandlerService,
UpdateTimelineActivityTypeActionHandlerService,
DeleteTimelineActivityTypeActionHandlerService,
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/constants/metadata-event-to-emit.constant.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/constants/metadata-event-to-emit.constant.ts
index 5b1bf905d11..c75ede4c226 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/constants/metadata-event-to-emit.constant.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/constants/metadata-event-to-emit.constant.ts
@@ -31,6 +31,7 @@ export const METADATA_EVENTS_TO_EMIT = {
webhook: false,
applicationVariable: false,
connectionProvider: true,
+ messagingProvider: true,
timelineActivityType: true,
validationRule: true,
searchFieldMetadata: true,
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/derive-metadata-events-from-create-action.util.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/derive-metadata-events-from-create-action.util.ts
index d9b222c8f9d..c8b6e312fb9 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/derive-metadata-events-from-create-action.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/derive-metadata-events-from-create-action.util.ts
@@ -101,6 +101,7 @@ const deriveAllMetadataEventsFromCreateAction = (
case 'workflow':
case 'workflowVersion':
case 'connectionProvider':
+ case 'messagingProvider':
case 'timelineActivityType':
case 'agentChatChannel':
case 'agentChatChannelRole':
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/derive-metadata-events-from-delete-action.util.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/derive-metadata-events-from-delete-action.util.ts
index c1eb2b423f3..6b21698c6a9 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/derive-metadata-events-from-delete-action.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/derive-metadata-events-from-delete-action.util.ts
@@ -65,6 +65,7 @@ const deriveAllMetadataEventsFromDeleteAction = ({
case 'workflow':
case 'workflowVersion':
case 'connectionProvider':
+ case 'messagingProvider':
case 'timelineActivityType':
case 'agentChatChannel':
case 'agentChatChannelRole':
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/derive-metadata-events-from-update-action.util.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/derive-metadata-events-from-update-action.util.ts
index 2a783d17bb1..9906294c103 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/derive-metadata-events-from-update-action.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/derive-metadata-events-from-update-action.util.ts
@@ -143,6 +143,7 @@ const deriveAllMetadataEventsFromUpdateAction = ({
case 'workflow':
case 'workflowVersion':
case 'connectionProvider':
+ case 'messagingProvider':
case 'timelineActivityType':
case 'agentChatChannel':
case 'agentChatChannelRole':
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/optimistically-apply-create-action-on-all-flat-entity-maps.util.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/optimistically-apply-create-action-on-all-flat-entity-maps.util.ts
index bbc248cbddb..aa5289a1214 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/optimistically-apply-create-action-on-all-flat-entity-maps.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/optimistically-apply-create-action-on-all-flat-entity-maps.util.ts
@@ -88,6 +88,7 @@ export const optimisticallyApplyCreateActionOnAllFlatEntityMaps = ({
case 'workflow':
case 'workflowVersion':
case 'connectionProvider':
+ case 'messagingProvider':
case 'timelineActivityType':
case 'agentChatChannel':
case 'agentChatChannelRole':
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/optimistically-apply-delete-action-on-all-flat-entity-maps.util.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/optimistically-apply-delete-action-on-all-flat-entity-maps.util.ts
index e6c5d485e35..0bc49d36f15 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/optimistically-apply-delete-action-on-all-flat-entity-maps.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/optimistically-apply-delete-action-on-all-flat-entity-maps.util.ts
@@ -49,6 +49,7 @@ export const optimisticallyApplyDeleteActionOnAllFlatEntityMaps = ({
case 'workflow':
case 'workflowVersion':
case 'connectionProvider':
+ case 'messagingProvider':
case 'timelineActivityType':
case 'agentChatChannel':
case 'agentChatChannelRole':
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/optimistically-apply-update-action-on-all-flat-entity-maps.util.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/optimistically-apply-update-action-on-all-flat-entity-maps.util.ts
index a64e804e644..8d8ee64b949 100644
--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/optimistically-apply-update-action-on-all-flat-entity-maps.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-runner/utils/optimistically-apply-update-action-on-all-flat-entity-maps.util.ts
@@ -70,6 +70,7 @@ export const optimisticallyApplyUpdateActionOnAllFlatEntityMaps = ({
case 'workflow':
case 'workflowVersion':
case 'connectionProvider':
+ case 'messagingProvider':
case 'timelineActivityType':
case 'agentChatChannel':
case 'agentChatChannelRole':
diff --git a/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-save-messages-and-enqueue-contact-creation.service.ts b/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-save-messages-and-enqueue-contact-creation.service.ts
index b2a4f6cae4e..6ad379ee539 100644
--- a/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-save-messages-and-enqueue-contact-creation.service.ts
+++ b/packages/twenty-server/src/modules/messaging/message-import-manager/services/messaging-save-messages-and-enqueue-contact-creation.service.ts
@@ -140,6 +140,10 @@ export class MessagingSaveMessagesAndEnqueueContactCreationService {
participantsWithMessageId,
workspaceId,
transactionScope,
+ {
+ shouldMatchOnDisplayName:
+ messageChannel.type !== MessageChannelType.APP,
+ },
);
const folderAssociations: MessageChannelMessageAssociationFolderAssociation[] =
diff --git a/packages/twenty-server/src/modules/messaging/message-participant-manager/services/messaging-message-participant.service.ts b/packages/twenty-server/src/modules/messaging/message-participant-manager/services/messaging-message-participant.service.ts
index fd3eb7c131b..c25ee21407f 100644
--- a/packages/twenty-server/src/modules/messaging/message-participant-manager/services/messaging-message-participant.service.ts
+++ b/packages/twenty-server/src/modules/messaging/message-participant-manager/services/messaging-message-participant.service.ts
@@ -27,6 +27,9 @@ export class MessagingMessageParticipantService {
participants: ParticipantWithMessageId[],
workspaceId: string,
transactionScope: WorkspaceTransactionScope,
+ { shouldMatchOnDisplayName }: { shouldMatchOnDisplayName: boolean } = {
+ shouldMatchOnDisplayName: true,
+ },
): Promise<MessageParticipantWorkspaceEntity[]> {
const authContext = buildSystemAuthContext(workspaceId);
@@ -51,14 +54,14 @@ export class MessagingMessageParticipantService {
isDefined(participant.personId) ||
isDefined(participant.workspaceMemberId);
- // Caller-identified rows match on message, handle and role only: displayName can drift between deliveries
const findExisting = (participant: ParticipantWithMessageId) =>
existingParticipantsBasedOnMessageIds.find(
(existingParticipant) =>
existingParticipant.messageId === participant.messageId &&
existingParticipant.handle === participant.handle &&
existingParticipant.role === participant.role &&
- (suppliesIdentity(participant) ||
+ (!shouldMatchOnDisplayName ||
+ suppliesIdentity(participant) ||
existingParticipant.displayName === participant.displayName),
);
@@ -92,9 +95,14 @@ export class MessagingMessageParticipantService {
// Without this a re-ingested participant would keep its original unlinked row forever
const identityUpdates = participantsWithExisting.flatMap(
({ participant, existingParticipant }) => {
+ const shouldFillMissingDisplayName =
+ !shouldMatchOnDisplayName &&
+ !isNonEmptyString(existingParticipant?.displayName) &&
+ isNonEmptyString(participant.displayName);
+
if (
!isDefined(existingParticipant) ||
- !suppliesIdentity(participant)
+ (!suppliesIdentity(participant) && !shouldFillMissingDisplayName)
) {
return [];
}
diff --git a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
index fd58becb17f..392dddbc475 100644
--- a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
+++ b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
@@ -155,6 +155,7 @@ exports[`endpoint permission declarations should match the auth principals, perm
"ApplicationMessageChannelsResolver.deleteAppMessageChannel {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":false,"playground":false,"standard":false,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":[]}",
"ApplicationMessageChannelsResolver.updateAppMessageChannel {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":false,"playground":false,"standard":false,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":[]}",
"ApplicationMessageIngestionResolver.ingestAppMessages {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":false,"playground":false,"standard":false,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":[]}",
+ "ApplicationMessageSendResolver.sendAppChannelMessage {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":true,"playground":false,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["SEND_EMAIL_TOOL"]}",
"ApplicationMonitoringResolver.findApplicationRegistrationMonitoring {"applicationTarget":{"argName":"id","kind":"applicationRegistrationId","requireApplicationRegistrationOwnership":true,"source":"graphqlArg"},"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["API_KEYS_AND_WEBHOOKS"]}",
"ApplicationOAuthResolver.renewApplicationToken {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}},{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":true,"playground":false,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":[]}",
"ApplicationPreferencesResolver.myApplicationPreferences {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["CONNECTED_ACCOUNTS"]}",
@@ -257,6 +258,8 @@ exports[`endpoint permission declarations should match the auth principals, perm
"ConnectedAccountSyncWebhooksController.handleGoogleMessaging {"applicationTarget":null,"authPrincipalGuards":[],"requiredFeatureFlags":[],"requiredPermissionFlags":[]}",
"ConnectedAccountSyncWebhooksController.handleMicrosoftCalendar {"applicationTarget":null,"authPrincipalGuards":[],"requiredFeatureFlags":[],"requiredPermissionFlags":[]}",
"ConnectedAccountSyncWebhooksController.handleMicrosoftMessaging {"applicationTarget":null,"authPrincipalGuards":[],"requiredFeatureFlags":[],"requiredPermissionFlags":[]}",
+ "ConnectionProviderCustomController.callback {"applicationTarget":null,"authPrincipalGuards":[],"requiredFeatureFlags":[],"requiredPermissionFlags":[]}",
+ "ConnectionProviderCustomController.callbackNotification {"applicationTarget":null,"authPrincipalGuards":[],"requiredFeatureFlags":[],"requiredPermissionFlags":[]}",
"ConnectionProviderOAuthController.authorize {"applicationTarget":null,"authPrincipalGuards":[],"requiredFeatureFlags":[],"requiredPermissionFlags":[]}",
"ConnectionProviderOAuthController.callback {"applicationTarget":null,"authPrincipalGuards":[],"requiredFeatureFlags":[],"requiredPermissionFlags":[]}",
"CoreWorkflowResolver.coreWorkflow {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["WORKFLOWS"]}",
diff --git a/packages/twenty-server/test/integration/graphql/suites/ai-chat-inbox-message.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/ai-chat-inbox-message.integration-spec.ts
index a517e99cc49..6724dacdf6c 100644
--- a/packages/twenty-server/test/integration/graphql/suites/ai-chat-inbox-message.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/ai-chat-inbox-message.integration-spec.ts
@@ -1,5 +1,8 @@
import { parse } from 'graphql';
import { answerToolCall } from 'test/integration/graphql/suites/workflow/utils/answer-tool-call.util';
+import { createOneOperationFactory } from 'test/integration/graphql/utils/create-one-operation-factory.util';
+import { destroyOneOperationFactory } from 'test/integration/graphql/utils/destroy-one-operation-factory.util';
+import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
import {
type ApplicationWithResources,
@@ -410,8 +413,17 @@ describe('Proposing a record call as an application', () => {
let application: ApplicationWithResources;
let applicationToken: string;
let threadId: string | undefined;
+ const opportunityId = uuidv4();
beforeAll(async () => {
+ await makeGraphqlApiRequest(
+ createOneOperationFactory({
+ objectMetadataSingularName: 'opportunity',
+ gqlFields: 'id',
+ data: { id: opportunityId, name: 'Inbox proposal deal' },
+ }),
+ );
+
application = await setupApplicationWithResources({
name: 'Inbox Record Application',
permissionFlagUniversalIdentifiers: [SystemPermissionFlag.AI],
@@ -428,6 +440,14 @@ describe('Proposing a record call as an application', () => {
});
afterAll(async () => {
+ await makeGraphqlApiRequest(
+ destroyOneOperationFactory({
+ objectMetadataSingularName: 'opportunity',
+ gqlFields: 'id',
+ recordId: opportunityId,
+ }),
+ );
+
if (threadId !== undefined) {
await destroyAgentChatThread({ threadId });
}
@@ -452,7 +472,7 @@ describe('Proposing a record call as an application', () => {
toolName: 'propose_tool_call',
input: {
toolName: 'update_one_opportunity',
- arguments: { id: OPPORTUNITY_DATA_SEED_IDS.ID_1, stage: 'WON' },
+ arguments: { id: opportunityId, stage: 'WON' },
summary: 'Mark the deal as won',
},
},
@@ -474,7 +494,7 @@ describe('Proposing a record call as an application', () => {
const [opportunity] = await global.testDataSource.query(
`SELECT stage FROM "${schema}"."opportunity" WHERE id = $1`,
- [OPPORTUNITY_DATA_SEED_IDS.ID_1],
+ [opportunityId],
);
expect(part.toolOutput.result).toMatchObject({
@@ -483,7 +503,7 @@ describe('Proposing a record call as an application', () => {
toolName: 'update_one_opportunity',
template: 'recordUpdate',
objectNameSingular: 'opportunity',
- recordId: OPPORTUNITY_DATA_SEED_IDS.ID_1,
+ recordId: opportunityId,
currentValues: { stage: opportunity.stage },
},
});
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/find-records-relation-traversal-workflow.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/find-records-relation-traversal-workflow.integration-spec.ts
index 92554454de8..4cef6450042 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/find-records-relation-traversal-workflow.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/find-records-relation-traversal-workflow.integration-spec.ts
@@ -16,7 +16,6 @@ import {
waitForWorkflowCompletion,
} from 'test/integration/graphql/suites/workflow/utils/workflow-run-test.util';
import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
-import { isDefined } from 'twenty-shared/utils';
import { v4 as uuidv4 } from 'uuid';
const TEST_COMPANY_AIRBNB_ID = '20202020-eeee-4000-8000-000000000001';
@@ -259,7 +258,7 @@ describe('FindRecords workflow action with relation-traversal filter (e2e)', ()
const result = workflowRun?.state?.stepInfos?.[findRecordsStepId!]
?.result as
| {
- all?: Array<{ id: string; companyId: string | null }>;
+ all?: Array<{ id: string }>;
totalCount?: number | string;
}
| undefined;
@@ -269,12 +268,11 @@ describe('FindRecords workflow action with relation-traversal filter (e2e)', ()
expect(Array.isArray(returnedRecords)).toBe(true);
expect(Number.isFinite(Number(result?.totalCount))).toBe(true);
- // An empty filter value can only match people with no company, and other
- // specs sharing the database seed those, so assert the shape rather than []
- const returnedCompanyIds = (returnedRecords ?? []).map(
- (record) => record.companyId,
- );
+ // other specs sharing the database leave people on unnamed companies, which an empty company name also matches
+ const returnedIds = (returnedRecords ?? []).map((record) => record.id);
- expect(returnedCompanyIds.filter(isDefined)).toEqual([]);
+ expect(
+ returnedIds.filter((id) => ALL_TEST_PERSON_IDS.includes(id)),
+ ).toEqual([]);
});
});
diff --git a/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-custom-flow.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-custom-flow.integration-spec.ts
new file mode 100644
index 00000000000..1ab6416c5fb
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-custom-flow.integration-spec.ts
@@ -0,0 +1,574 @@
+import { createHash, createHmac } from 'crypto';
+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import request from 'supertest';
+import { buildBaseManifest } from 'test/integration/metadata/suites/application/utils/build-base-manifest.util';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import { setupApplicationForSync } from 'test/integration/metadata/suites/application/utils/setup-application-for-sync.util';
+import { syncApplication } from 'test/integration/metadata/suites/application/utils/sync-application.util';
+import { uploadApplicationFile } from 'test/integration/metadata/suites/application/utils/upload-application-file.util';
+import { generateTransientTokenResponse } from 'test/integration/utils/generate-transient-token.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { waitForAllJobsToFinish } from 'test/integration/utils/wait-for-all-jobs-to-finish.util';
+import { type Manifest } from 'twenty-shared/application';
+import { assertIsDefinedOrThrow } from 'twenty-shared/utils';
+import { v4 } from 'uuid';
+
+import { type ConnectionProviderEntity } from 'src/engine/core-modules/application/connection-provider/connection-provider.entity';
+import { type ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
+import { type ConnectedAccountTokenEncryptionService } from 'src/engine/metadata-modules/connected-account/services/connected-account-token-encryption.service';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+
+const APPLICATION_IDENTIFIER = v4();
+const ROLE_IDENTIFIER = v4();
+const PROVIDER_IDENTIFIER = v4();
+const AUTHORIZE_IDENTIFIER = v4();
+const CALLBACK_IDENTIFIER = v4();
+const ON_CONNECT_IDENTIFIER = v4();
+const HOSTED_AUTH_ORIGIN = 'https://hosted-auth.example.com';
+const WEBHOOK_SECRET = 'webhook-secret';
+
+const AUTHORIZE_SOURCE = `export const handler = ({ callbackUrl }) => ({
+ authorizationUrl: ${JSON.stringify(HOSTED_AUTH_ORIGIN)} + '/connect?notify=' + encodeURIComponent(callbackUrl),
+});`;
+
+const CALLBACK_SOURCE = `import { createHmac } from 'node:crypto';
+export const handler = ({ httpMethod, headers, body, rawBody }) => {
+ if (httpMethod === 'GET') return null;
+ if (headers.cookie !== undefined) throw new Error('cookie header reached the app');
+ if (headers['x-signature'] !== undefined && headers['x-signature'] !== createHmac('sha256', ${JSON.stringify(WEBHOOK_SECRET)}).update(rawBody).digest('hex')) {
+ throw new Error('invalid signature');
+ }
+ if (body.account_id === 'broken') throw new Error('upstream account lookup failed');
+ return {
+ externalAccountId: body.account_id,
+ handle: 'Handle ' + body.account_id,
+ ...(body.token ? { accessToken: body.token } : {}),
+ };
+};`;
+
+describe('app connection custom flow', () => {
+ let provider: ConnectionProviderEntity;
+ let logicFunctionManifests: Manifest['logicFunctions'];
+ let fixtureDirectory: string;
+ let onConnectExecutionsPath: string;
+
+ const readOnConnectExecutions = (): string[] =>
+ existsSync(onConnectExecutionsPath)
+ ? readFileSync(onConnectExecutionsPath, 'utf8').trim().split('\n')
+ : [];
+
+ const readAccounts = (): Promise<ConnectedAccountEntity[]> =>
+ globalThis.testDataSource.query(
+ 'SELECT * FROM core."connectedAccount" WHERE "connectionProviderId" = $1 ORDER BY "createdAt", id',
+ [provider.id],
+ );
+
+ const authorize = async ({
+ reconnectingConnectedAccountId,
+ }: { reconnectingConnectedAccountId?: string } = {}): Promise<URL> => {
+ const transient = await generateTransientTokenResponse({
+ token: APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ });
+
+ expect(transient.errors).toBeUndefined();
+
+ const response = await request(`http://localhost:${APP_PORT}`)
+ .get('/auth/apps/authorize')
+ .query({
+ applicationId: provider.applicationId,
+ providerName: provider.name,
+ transientToken:
+ transient.data.generateTransientToken.transientToken.token,
+ reconnectingConnectedAccountId,
+ });
+
+ expect(response.status).toBe(302);
+
+ const authorizationUrl = new URL(response.headers.location);
+
+ expect(authorizationUrl.origin).toBe(HOSTED_AUTH_ORIGIN);
+
+ const callbackUrl = authorizationUrl.searchParams.get('notify');
+
+ assertIsDefinedOrThrow(callbackUrl);
+
+ return new URL(callbackUrl);
+ };
+
+ const notify = async ({
+ callbackUrl,
+ body,
+ headers = {},
+ }: {
+ callbackUrl: URL;
+ body: Record<string, string> | string;
+ headers?: Record<string, string>;
+ }) => {
+ const response = await request(`http://localhost:${APP_PORT}`)
+ .post(`${callbackUrl.pathname}${callbackUrl.search}`)
+ .set({ 'content-type': 'application/json', ...headers })
+ .send(body);
+
+ await waitForAllJobsToFinish();
+
+ return response;
+ };
+
+ const returnInBrowser = async (callbackUrl: URL): Promise<URL> => {
+ const response = await request(`http://localhost:${APP_PORT}`).get(
+ `${callbackUrl.pathname}${callbackUrl.search}`,
+ );
+
+ expect(response.status).toBe(302);
+ await waitForAllJobsToFinish();
+
+ return new URL(response.headers.location);
+ };
+
+ beforeAll(async () => {
+ fixtureDirectory = mkdtempSync(join(tmpdir(), 'app-connection-custom-'));
+ onConnectExecutionsPath = join(fixtureDirectory, 'on-connect-executions');
+
+ await setupApplicationForSync({
+ applicationUniversalIdentifier: APPLICATION_IDENTIFIER,
+ name: 'Custom flow integration',
+ description: 'Custom connection flow authorize and callback',
+ sourcePath: 'custom-flow-integration',
+ });
+ jest.useRealTimers();
+
+ const functions = [
+ {
+ universalIdentifier: AUTHORIZE_IDENTIFIER,
+ name: 'authorize',
+ source: AUTHORIZE_SOURCE,
+ },
+ {
+ universalIdentifier: CALLBACK_IDENTIFIER,
+ name: 'callback',
+ source: CALLBACK_SOURCE,
+ },
+ {
+ universalIdentifier: ON_CONNECT_IDENTIFIER,
+ name: 'on-connect',
+ source: `import { appendFileSync } from 'node:fs';
+export const handler = ({ connectedAccountId }) => {
+ appendFileSync(${JSON.stringify(onConnectExecutionsPath)}, connectedAccountId + '\\n');
+};`,
+ },
+ ];
+
+ for (const logicFunction of functions) {
+ const uploaded = await uploadApplicationFile({
+ applicationUniversalIdentifier: APPLICATION_IDENTIFIER,
+ fileFolder: 'BuiltLogicFunction',
+ filePath: `dist/${logicFunction.name}.mjs`,
+ filename: `${logicFunction.name}.mjs`,
+ contentType: 'application/javascript',
+ fileBuffer: Buffer.from(logicFunction.source),
+ });
+
+ expect(uploaded.errors).toBeUndefined();
+ }
+
+ logicFunctionManifests = functions.map((logicFunction) => ({
+ universalIdentifier: logicFunction.universalIdentifier,
+ name: logicFunction.name,
+ handlerName: 'handler',
+ sourceHandlerPath: `src/${logicFunction.name}.ts`,
+ builtHandlerPath: `dist/${logicFunction.name}.mjs`,
+ builtHandlerChecksum: createHash('sha256')
+ .update(logicFunction.source)
+ .digest('hex'),
+ timeoutSeconds: 10,
+ }));
+
+ const { errors } = await syncApplication({
+ manifest: buildBaseManifest({
+ appId: APPLICATION_IDENTIFIER,
+ roleId: ROLE_IDENTIFIER,
+ overrides: {
+ logicFunctions: logicFunctionManifests,
+ connectionProviders: [
+ {
+ universalIdentifier: PROVIDER_IDENTIFIER,
+ name: 'hosted-provider',
+ displayName: 'Hosted provider',
+ type: 'custom',
+ custom: {
+ authorizeLogicFunction: {
+ universalIdentifier: AUTHORIZE_IDENTIFIER,
+ },
+ callbackLogicFunction: {
+ universalIdentifier: CALLBACK_IDENTIFIER,
+ },
+ },
+ onConnectLogicFunction: {
+ universalIdentifier: ON_CONNECT_IDENTIFIER,
+ },
+ },
+ ],
+ },
+ }),
+ });
+
+ expect(errors).toBeUndefined();
+ jest.useRealTimers();
+ [provider] = await globalThis.testDataSource.query(
+ 'SELECT * FROM core."connectionProvider" WHERE "universalIdentifier" = $1',
+ [PROVIDER_IDENTIFIER],
+ );
+ }, 120000);
+
+ beforeEach(() => {
+ rmSync(onConnectExecutionsPath, { force: true });
+ });
+
+ afterEach(async () => {
+ await globalThis.testDataSource.query(
+ 'DELETE FROM core."connectedAccount" WHERE "applicationId" = $1',
+ [provider.applicationId],
+ );
+ });
+
+ afterAll(async () => {
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: APPLICATION_IDENTIFIER,
+ });
+ rmSync(fixtureDirectory, { recursive: true, force: true });
+ });
+
+ it('stores the provider and sends the member to the URL the authorize function returns', async () => {
+ expect(provider).toMatchObject({
+ type: 'custom',
+ oauthConfig: null,
+ customConfig: {
+ authorizeLogicFunctionUniversalIdentifier: AUTHORIZE_IDENTIFIER,
+ callbackLogicFunctionUniversalIdentifier: CALLBACK_IDENTIFIER,
+ },
+ });
+
+ const callbackUrl = await authorize();
+
+ expect(callbackUrl.pathname).toBe('/auth/apps/custom/callback');
+ expect(callbackUrl.searchParams.get('state')).toEqual(expect.any(String));
+ });
+
+ it('saves the account the notification reports and runs onConnect for it', async () => {
+ const response = await notify({
+ callbackUrl: await authorize(),
+ body: {
+ account_id: 'account-a',
+ },
+ });
+ const [connection] = await readAccounts();
+
+ expect(response.status).toBe(200);
+ expect(connection).toMatchObject({
+ provider: 'app',
+ externalAccountId: 'account-a',
+ handle: 'Handle account-a',
+ accessToken: null,
+ refreshToken: null,
+ scope: 'WORKSPACE',
+ });
+ expect(readOnConnectExecutions()).toEqual([connection.id]);
+ });
+
+ it('gives the callback the headers and exact bytes to verify a signed notification, without cookies', async () => {
+ const rawBody = '{"account_id": "account-signed"}';
+
+ const response = await notify({
+ callbackUrl: await authorize(),
+ body: rawBody,
+ headers: {
+ 'x-signature': createHmac('sha256', WEBHOOK_SECRET)
+ .update(rawBody)
+ .digest('hex'),
+ cookie: 'tokenPair=member-session',
+ },
+ });
+
+ expect(response.status).toBe(200);
+ expect(await readAccounts()).toEqual([
+ expect.objectContaining({ externalAccountId: 'account-signed' }),
+ ]);
+ });
+
+ it('saves nothing when the callback rejects the notification signature', async () => {
+ const response = await notify({
+ callbackUrl: await authorize(),
+ body: { account_id: 'account-forged' },
+ headers: { 'x-signature': 'forged' },
+ });
+
+ expect(response.status).toBe(500);
+ expect(await readAccounts()).toHaveLength(0);
+ });
+
+ it('returns the browser to the app settings without saving anything itself', async () => {
+ const redirect = await returnInBrowser(await authorize());
+
+ expect(redirect.searchParams.has('errorMessage')).toBe(false);
+ expect(redirect.pathname).toBe(
+ `/settings/applications/${provider.applicationId}`,
+ );
+ expect(await readAccounts()).toHaveLength(0);
+ expect(readOnConnectExecutions()).toEqual([]);
+ });
+
+ it('stores an access token the callback returns, encrypted', async () => {
+ await notify({
+ callbackUrl: await authorize(),
+ body: {
+ account_id: 'account-a',
+ token: 'token-a',
+ },
+ });
+ const [connection] = await readAccounts();
+
+ assertIsDefinedOrThrow(connection.accessToken);
+ expect(connection.accessToken).not.toBe('token-a');
+ expect(
+ getAppProviderByClassName<ConnectedAccountTokenEncryptionService>(
+ 'ConnectedAccountTokenEncryptionService',
+ ).decrypt({
+ ciphertext: connection.accessToken,
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ }),
+ ).toBe('token-a');
+ });
+
+ it('updates the existing connection and runs onConnect once when the same account is reported again', async () => {
+ const callbackUrl = await authorize();
+
+ await notify({ callbackUrl, body: { account_id: 'account-a' } });
+ await notify({
+ callbackUrl,
+ body: { account_id: 'account-a', token: 'token-a' },
+ });
+ await notify({
+ callbackUrl: await authorize(),
+ body: { account_id: 'account-a' },
+ });
+
+ const connections = await readAccounts();
+
+ expect(connections).toHaveLength(1);
+ expect(readOnConnectExecutions()).toEqual([connections[0].id]);
+ });
+
+ it('ignores a replayed report for a connection archived after its state was issued', async () => {
+ const callbackUrl = await authorize();
+
+ await notify({ callbackUrl, body: { account_id: 'account-a' } });
+ const [connection] = await readAccounts();
+
+ await globalThis.testDataSource.query(
+ `UPDATE core."connectedAccount" SET "archivedAt" = NOW() + INTERVAL '5 seconds' WHERE id = $1`,
+ [connection.id],
+ );
+
+ await notify({ callbackUrl, body: { account_id: 'account-a' } });
+
+ const [replayed] = await readAccounts();
+
+ expect(replayed.archivedAt).not.toBeNull();
+ expect(readOnConnectExecutions()).toEqual([connection.id]);
+ });
+
+ it('ignores a replayed reconnect report for a connection archived after its state was issued', async () => {
+ await notify({
+ callbackUrl: await authorize(),
+ body: { account_id: 'account-a' },
+ });
+ const [connection] = await readAccounts();
+
+ const reconnectCallbackUrl = await authorize({
+ reconnectingConnectedAccountId: connection.id,
+ });
+
+ await globalThis.testDataSource.query(
+ `UPDATE core."connectedAccount" SET "archivedAt" = NOW() + INTERVAL '5 seconds' WHERE id = $1`,
+ [connection.id],
+ );
+
+ await notify({
+ callbackUrl: reconnectCallbackUrl,
+ body: { account_id: 'account-a' },
+ });
+
+ const [replayed] = await readAccounts();
+
+ expect(replayed.archivedAt).not.toBeNull();
+ expect(readOnConnectExecutions()).toEqual([connection.id]);
+ });
+
+ it('restores an archived connection when a new authorization reports it', async () => {
+ await notify({
+ callbackUrl: await authorize(),
+ body: { account_id: 'account-a' },
+ });
+ const [connection] = await readAccounts();
+
+ await globalThis.testDataSource.query(
+ `UPDATE core."connectedAccount" SET "archivedAt" = NOW() - INTERVAL '5 seconds' WHERE id = $1`,
+ [connection.id],
+ );
+
+ await notify({
+ callbackUrl: await authorize(),
+ body: { account_id: 'account-a' },
+ });
+
+ const connections = await readAccounts();
+
+ expect(connections).toHaveLength(1);
+ expect(connections[0].archivedAt).toBeNull();
+ });
+
+ it('runs onConnect again when an explicit reconnect reports the same account', async () => {
+ await notify({
+ callbackUrl: await authorize(),
+ body: { account_id: 'account-a' },
+ });
+ const [original] = await readAccounts();
+
+ await notify({
+ callbackUrl: await authorize({
+ reconnectingConnectedAccountId: original.id,
+ }),
+ body: { account_id: 'account-a' },
+ });
+
+ expect(readOnConnectExecutions()).toEqual([original.id, original.id]);
+ });
+
+ it('keeps the stored token when a later report of the account omits it', async () => {
+ await notify({
+ callbackUrl: await authorize(),
+ body: {
+ account_id: 'account-a',
+ token: 'token-a',
+ },
+ });
+ const [original] = await readAccounts();
+
+ await notify({
+ callbackUrl: await authorize(),
+ body: { account_id: 'account-a' },
+ });
+
+ const connections = await readAccounts();
+
+ expect(connections).toHaveLength(1);
+ expect(connections[0].accessToken).toBe(original.accessToken);
+ });
+
+ it('serialises simultaneous reports of one account into one connection', async () => {
+ const callbackUrl = await authorize();
+
+ await Promise.all([
+ notify({ callbackUrl, body: { account_id: 'account-a' } }),
+ notify({ callbackUrl, body: { account_id: 'account-a' } }),
+ ]);
+
+ expect(await readAccounts()).toHaveLength(1);
+ });
+
+ it('refuses a reconnect that reports a different account and leaves the connection untouched', async () => {
+ await notify({
+ callbackUrl: await authorize(),
+ body: { account_id: 'account-a' },
+ });
+ const [original] = await readAccounts();
+
+ const response = await notify({
+ callbackUrl: await authorize({
+ reconnectingConnectedAccountId: original.id,
+ }),
+ body: { account_id: 'account-b' },
+ });
+ const connections = await readAccounts();
+
+ expect(response.status).toBe(400);
+ expect(connections).toHaveLength(1);
+ expect(connections[0]).toMatchObject({
+ id: original.id,
+ externalAccountId: 'account-a',
+ });
+ });
+
+ it('saves nothing and skips onConnect when the callback function fails', async () => {
+ const response = await notify({
+ callbackUrl: await authorize(),
+ body: {
+ account_id: 'broken',
+ },
+ });
+
+ expect(response.status).toBe(500);
+ expect(await readAccounts()).toHaveLength(0);
+ expect(readOnConnectExecutions()).toEqual([]);
+ });
+
+ it('refuses turning the provider into an OAuth one and keeps it custom', async () => {
+ const { errors } = await syncApplication({
+ manifest: buildBaseManifest({
+ appId: APPLICATION_IDENTIFIER,
+ roleId: ROLE_IDENTIFIER,
+ overrides: {
+ logicFunctions: logicFunctionManifests,
+ connectionProviders: [
+ {
+ universalIdentifier: PROVIDER_IDENTIFIER,
+ name: 'hosted-provider',
+ displayName: 'Hosted provider',
+ type: 'oauth',
+ oauth: {
+ authorizationEndpoint:
+ 'https://hosted-auth.example.com/authorize',
+ tokenEndpoint: 'https://hosted-auth.example.com/token',
+ scopes: [],
+ clientIdVariable: 'CLIENT_ID',
+ clientSecretVariable: 'CLIENT_SECRET',
+ },
+ },
+ ],
+ },
+ }),
+ expectToFail: true,
+ });
+
+ expect(JSON.stringify(errors)).toContain(
+ 'Connection provider type cannot be changed after creation',
+ );
+
+ const [storedProvider] = await globalThis.testDataSource.query(
+ 'SELECT type FROM core."connectionProvider" WHERE "universalIdentifier" = $1',
+ [PROVIDER_IDENTIFIER],
+ );
+
+ expect(storedProvider.type).toBe('custom');
+ });
+
+ it('rejects a notification with a tampered state', async () => {
+ const callbackUrl = await authorize();
+
+ callbackUrl.searchParams.set(
+ 'state',
+ `${callbackUrl.searchParams.get('state')}tampered`,
+ );
+
+ const response = await notify({
+ callbackUrl,
+ body: { account_id: 'account-a' },
+ });
+
+ expect(response.status).toBe(400);
+ expect(await readAccounts()).toHaveLength(0);
+ });
+});
diff --git a/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connections.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connections.integration-spec.ts
index 56b22b6c165..d3a0be89e24 100644
--- a/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connections.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connections.integration-spec.ts
@@ -21,6 +21,7 @@ const APP_CONNECTION_FIELDS = gql`
scope
visibility
userWorkspaceId
+ providerType
accessToken
}
`;
@@ -77,6 +78,7 @@ describe('app connections API (e2e)', () => {
scope: 'WORKSPACE',
visibility: 'workspace',
userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JANE,
+ providerType: 'oauth',
accessToken: application.connectedAccountAccessToken,
});
diff --git a/packages/twenty-server/test/integration/metadata/suites/connection-provider/report-app-connection-auth-failure.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/connection-provider/report-app-connection-auth-failure.integration-spec.ts
index 8745268f5cc..dc6031bafa4 100644
--- a/packages/twenty-server/test/integration/metadata/suites/connection-provider/report-app-connection-auth-failure.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/connection-provider/report-app-connection-auth-failure.integration-spec.ts
@@ -242,6 +242,27 @@ describe('reportAppConnectionAuthFailure resolver (e2e)', () => {
);
});
+ it('keeps the first failure time and the latest reason when the failure is reported again', async () => {
+ const connectedAccountId = uuidv4();
+
+ await insertAppConnection({
+ id: connectedAccountId,
+ applicationId: owningApplicationDbId,
+ connectionProviderId: owningProviderDbId,
+ scope: 'WORKSPACE',
+ userWorkspaceId: adminUserWorkspaceId,
+ });
+
+ await reportAuthFailure({ id: connectedAccountId, reason: 'first' });
+ const firstReport = await findAuthFailure(connectedAccountId);
+
+ await reportAuthFailure({ id: connectedAccountId, reason: 'second' });
+ const secondReport = await findAuthFailure(connectedAccountId);
+
+ expect(secondReport.authFailedAt).toEqual(firstReport.authFailedAt);
+ expect(secondReport.authFailedReason).toBe('second');
+ });
+
it('leaves the reason empty when the caller gives none', async () => {
const connectedAccountId = uuidv4();
diff --git a/packages/twenty-server/test/integration/metadata/suites/message-channel/app-channel-message-send.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/message-channel/app-channel-message-send.integration-spec.ts
new file mode 100644
index 00000000000..160173ba6d0
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/message-channel/app-channel-message-send.integration-spec.ts
@@ -0,0 +1,730 @@
+import { createHash } from 'crypto';
+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import { gql } from 'graphql-tag';
+import { buildBaseManifest } from 'test/integration/metadata/suites/application/utils/build-base-manifest.util';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import { setupApplicationForSync } from 'test/integration/metadata/suites/application/utils/setup-application-for-sync.util';
+import { syncApplication } from 'test/integration/metadata/suites/application/utils/sync-application.util';
+import { uploadApplicationFile } from 'test/integration/metadata/suites/application/utils/upload-application-file.util';
+import { findConnectionProvidersByApplication } from 'test/integration/metadata/suites/connection-provider/utils/find-connection-providers-by-application.util';
+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { generateAppleAdminApplicationTokenPair } from 'test/integration/utils/generate-apple-admin-application-token-pair.util';
+import { type SendAppMessagePayload } from 'twenty-shared/application';
+import {
+ ConnectedAccountProvider,
+ MessageChannelVisibility,
+ MessageParticipantRole,
+} from 'twenty-shared/types';
+import { assertIsDefinedOrThrow, isDefined } from 'twenty-shared/utils';
+import { v4 } from 'uuid';
+
+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';
+import { MessageDirection } from 'src/modules/messaging/common/enums/message-direction.enum';
+
+const APPLICATION_IDENTIFIER = v4();
+const SENDING_PROVIDER_IDENTIFIER = v4();
+const SILENT_PROVIDER_IDENTIFIER = v4();
+const SEND_MESSAGE_IDENTIFIER = v4();
+const MESSAGING_PROVIDER_IDENTIFIER = v4();
+
+const WORKSPACE_SCHEMA = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);
+
+const CHANNEL_HANDLE = 'urn:li:person:jane';
+const CONTACT_HANDLE = 'urn:li:person:ada';
+const THREAD_EXTERNAL_ID = 'urn:li:conversation:1';
+
+const CREATE_CHANNEL_MUTATION = gql`
+ mutation CreateAppMessageChannel($input: CreateAppMessageChannelInput!) {
+ createAppMessageChannel(input: $input) {
+ id
+ }
+ }
+`;
+
+const UPDATE_CHANNEL_MUTATION = gql`
+ mutation UpdateAppMessageChannel($input: UpdateAppMessageChannelInput!) {
+ updateAppMessageChannel(input: $input) {
+ id
+ }
+ }
+`;
+
+const INGEST_MESSAGES_MUTATION = gql`
+ mutation IngestAppMessages($input: IngestAppMessagesInput!) {
+ ingestAppMessages(input: $input) {
+ messages {
+ messageId
+ messageThreadId
+ }
+ }
+ }
+`;
+
+const SEND_MESSAGE_MUTATION = gql`
+ mutation SendAppChannelMessage($input: SendAppChannelMessageInput!) {
+ sendAppChannelMessage(input: $input) {
+ messageId
+ messageThreadId
+ }
+ }
+`;
+
+describe('sendAppChannelMessage (e2e)', () => {
+ let fixtureDirectory: string;
+ let sendExecutionsPath: string;
+ let applicationToken: string;
+ let applicationDbId: string;
+ let sendingConnectionId: string;
+ let silentConnectionId: string;
+
+ const readSendExecutions = (): SendAppMessagePayload[] => {
+ if (!existsSync(sendExecutionsPath)) {
+ return [];
+ }
+
+ return readFileSync(sendExecutionsPath, 'utf8')
+ .trim()
+ .split('\n')
+ .map((line) => JSON.parse(line));
+ };
+
+ const asApplication = (
+ operation: Parameters<typeof makeMetadataApiRequest>[0],
+ ) => makeMetadataApiRequest(operation, applicationToken);
+
+ const createChannel = ({
+ connectedAccountId,
+ messagingProviderUniversalIdentifier,
+ }: {
+ connectedAccountId: string;
+ messagingProviderUniversalIdentifier?: string;
+ }) =>
+ asApplication({
+ query: CREATE_CHANNEL_MUTATION,
+ variables: {
+ input: {
+ connectedAccountId,
+ handle: CHANNEL_HANDLE,
+ displayName: 'Jane Doe',
+ visibility: MessageChannelVisibility.SHARE_EVERYTHING,
+ messagingProviderUniversalIdentifier,
+ },
+ },
+ });
+
+ const bindChannel = ({
+ messageChannelId,
+ messagingProviderUniversalIdentifier,
+ }: {
+ messageChannelId: string;
+ messagingProviderUniversalIdentifier: string | null;
+ }) =>
+ asApplication({
+ query: UPDATE_CHANNEL_MUTATION,
+ variables: {
+ input: { id: messageChannelId, messagingProviderUniversalIdentifier },
+ },
+ });
+
+ const startConversation = async ({
+ connectedAccountId,
+ messagingProviderUniversalIdentifier,
+ }: {
+ connectedAccountId: string;
+ messagingProviderUniversalIdentifier?: string;
+ }) => {
+ const channelResponse = await createChannel({
+ connectedAccountId,
+ messagingProviderUniversalIdentifier,
+ });
+
+ expect(channelResponse.body.errors).toBeUndefined();
+
+ const messageChannelId: string =
+ channelResponse.body.data.createAppMessageChannel.id;
+
+ const ingestResponse = await asApplication({
+ query: INGEST_MESSAGES_MUTATION,
+ variables: {
+ input: {
+ messageChannelId,
+ messages: [
+ {
+ externalId: 'inbound-1',
+ threadExternalId: THREAD_EXTERNAL_ID,
+ text: 'Are you free next week?',
+ receivedAt: '2026-10-20T10:00:00.000Z',
+ participants: [
+ {
+ role: MessageParticipantRole.FROM,
+ handle: CONTACT_HANDLE,
+ displayName: 'Ada Lovelace',
+ },
+ {
+ role: MessageParticipantRole.TO,
+ handle: CHANNEL_HANDLE,
+ displayName: 'Jane Doe',
+ },
+ ],
+ },
+ ],
+ },
+ },
+ });
+
+ expect(ingestResponse.body.errors).toBeUndefined();
+
+ const [{ messageThreadId }]: { messageThreadId: string }[] =
+ ingestResponse.body.data.ingestAppMessages.messages;
+
+ return { messageChannelId, messageThreadId };
+ };
+
+ const send = ({
+ idempotencyKey = v4(),
+ ...input
+ }: {
+ messageChannelId: string;
+ messageThreadId: string;
+ text: string;
+ idempotencyKey?: string;
+ }) =>
+ makeMetadataApiRequest({
+ query: SEND_MESSAGE_MUTATION,
+ variables: { input: { ...input, idempotencyKey } },
+ });
+
+ const insertConnection = async (connectionProviderId: string) => {
+ const id = v4();
+
+ await globalThis.testDataSource.query(
+ `INSERT INTO core."connectedAccount"
+ (id, handle, provider, scope, "workspaceId", "userWorkspaceId",
+ "applicationId", "connectionProviderId")
+ VALUES ($1, $2, $3, 'WORKSPACE', $4, $5, $6, $7)`,
+ [
+ id,
+ CHANNEL_HANDLE,
+ ConnectedAccountProvider.APP,
+ SEED_APPLE_WORKSPACE_ID,
+ USER_WORKSPACE_DATA_SEED_IDS.JANE,
+ applicationDbId,
+ connectionProviderId,
+ ],
+ );
+
+ return id;
+ };
+
+ beforeAll(async () => {
+ fixtureDirectory = mkdtempSync(join(tmpdir(), 'app-channel-send-'));
+ sendExecutionsPath = join(fixtureDirectory, 'send-executions');
+
+ await setupApplicationForSync({
+ applicationUniversalIdentifier: APPLICATION_IDENTIFIER,
+ name: 'App channel send integration',
+ description: 'Replies sent through an app message channel',
+ sourcePath: 'app-channel-send-integration',
+ });
+ jest.useRealTimers();
+
+ const sendMessageSource = `import { appendFileSync } from 'node:fs';
+export const handler = (payload) => {
+ appendFileSync(${JSON.stringify(sendExecutionsPath)}, JSON.stringify(payload) + '\\n');
+ if (payload.text === 'refused') throw new Error('provider refused the message');
+ return { externalId: 'sent:' + payload.text, sentAt: '2026-10-21T10:00:00.000Z' };
+};`;
+
+ const uploaded = await uploadApplicationFile({
+ applicationUniversalIdentifier: APPLICATION_IDENTIFIER,
+ fileFolder: 'BuiltLogicFunction',
+ filePath: 'dist/send-message.mjs',
+ filename: 'send-message.mjs',
+ contentType: 'application/javascript',
+ fileBuffer: Buffer.from(sendMessageSource),
+ });
+
+ expect(uploaded.errors).toBeUndefined();
+
+ const oauth = {
+ authorizationEndpoint: 'https://provider.example.com/authorize',
+ tokenEndpoint: 'https://provider.example.com/token',
+ scopes: [],
+ clientIdVariable: 'CLIENT_ID',
+ clientSecretVariable: 'CLIENT_SECRET',
+ };
+
+ const { errors } = await syncApplication({
+ manifest: buildBaseManifest({
+ appId: APPLICATION_IDENTIFIER,
+ roleId: v4(),
+ overrides: {
+ logicFunctions: [
+ {
+ universalIdentifier: SEND_MESSAGE_IDENTIFIER,
+ name: 'send-message',
+ handlerName: 'handler',
+ sourceHandlerPath: 'src/send-message.ts',
+ builtHandlerPath: 'dist/send-message.mjs',
+ builtHandlerChecksum: createHash('sha256')
+ .update(sendMessageSource)
+ .digest('hex'),
+ timeoutSeconds: 10,
+ },
+ ],
+ connectionProviders: [
+ {
+ universalIdentifier: SENDING_PROVIDER_IDENTIFIER,
+ name: 'sending',
+ displayName: 'Sending',
+ type: 'oauth',
+ oauth,
+ },
+ {
+ universalIdentifier: SILENT_PROVIDER_IDENTIFIER,
+ name: 'silent',
+ displayName: 'Silent',
+ type: 'oauth',
+ oauth,
+ },
+ ],
+ messagingProviders: [
+ {
+ universalIdentifier: MESSAGING_PROVIDER_IDENTIFIER,
+ name: 'linkedin-messaging',
+ displayName: 'LinkedIn Messages',
+ connectionProvider: {
+ universalIdentifier: SENDING_PROVIDER_IDENTIFIER,
+ },
+ sendMessageLogicFunction: {
+ universalIdentifier: SEND_MESSAGE_IDENTIFIER,
+ },
+ },
+ ],
+ },
+ }),
+ });
+
+ expect(errors).toBeUndefined();
+ jest.useRealTimers();
+
+ const providers = await findConnectionProvidersByApplication(
+ APPLICATION_IDENTIFIER,
+ );
+ const findProviderId = (name: string): string => {
+ const provider = providers.find(
+ (connectionProvider) => connectionProvider.name === name,
+ );
+
+ assertIsDefinedOrThrow(provider);
+
+ return provider.id;
+ };
+
+ applicationDbId = providers[0].applicationId;
+
+ const tokenPair = await generateAppleAdminApplicationTokenPair({
+ applicationId: applicationDbId,
+ });
+
+ applicationToken = tokenPair.applicationAccessToken.token;
+
+ sendingConnectionId = await insertConnection(findProviderId('sending'));
+ silentConnectionId = await insertConnection(findProviderId('silent'));
+ }, 180000);
+
+ beforeEach(() => {
+ rmSync(sendExecutionsPath, { force: true });
+ });
+
+ afterEach(async () => {
+ const messages: { id: string; messageThreadId: string | null }[] =
+ await globalThis.testDataSource.query(
+ `SELECT id, "messageThreadId" FROM "${WORKSPACE_SCHEMA}"."message"
+ WHERE "headerMessageId" LIKE $1`,
+ [`app:${applicationDbId}:%`],
+ );
+ const messageIds = messages.map((message) => message.id);
+ const messageThreadIds = [
+ ...new Set(
+ messages.map((message) => message.messageThreadId).filter(isDefined),
+ ),
+ ];
+
+ for (const table of [
+ 'messageChannelMessageAssociation',
+ 'messageParticipant',
+ ]) {
+ await globalThis.testDataSource.query(
+ `DELETE FROM "${WORKSPACE_SCHEMA}"."${table}" WHERE "messageId" = ANY($1)`,
+ [messageIds],
+ );
+ }
+ await globalThis.testDataSource.query(
+ `DELETE FROM "${WORKSPACE_SCHEMA}"."message" WHERE id = ANY($1)`,
+ [messageIds],
+ );
+ await globalThis.testDataSource.query(
+ `DELETE FROM "${WORKSPACE_SCHEMA}"."messageThreadTarget" WHERE "messageThreadId" = ANY($1)`,
+ [messageThreadIds],
+ );
+ await globalThis.testDataSource.query(
+ `DELETE FROM "${WORKSPACE_SCHEMA}"."messageThread" WHERE id = ANY($1)`,
+ [messageThreadIds],
+ );
+ await globalThis.testDataSource.query(
+ `DELETE FROM core."messageChannel" WHERE "connectedAccountId" = ANY($1)`,
+ [[sendingConnectionId, silentConnectionId]],
+ );
+ });
+
+ afterAll(async () => {
+ await globalThis.testDataSource.query(
+ `DELETE FROM core."connectedAccount" WHERE "applicationId" = $1`,
+ [applicationDbId],
+ );
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: APPLICATION_IDENTIFIER,
+ });
+ rmSync(fixtureDirectory, { recursive: true, force: true });
+ }, 120000);
+
+ it('sends through the app and records the reply in the same thread', async () => {
+ const { messageChannelId, messageThreadId } = await startConversation({
+ connectedAccountId: sendingConnectionId,
+ messagingProviderUniversalIdentifier: MESSAGING_PROVIDER_IDENTIFIER,
+ });
+
+ const response = await send({
+ messageChannelId,
+ messageThreadId,
+ text: 'Tuesday works',
+ });
+
+ expect(response.body.errors).toBeUndefined();
+ expect(response.body.data.sendAppChannelMessage.messageThreadId).toBe(
+ messageThreadId,
+ );
+ expect(readSendExecutions()).toEqual([
+ expect.objectContaining({
+ messagingProviderName: 'linkedin-messaging',
+ connectedAccountId: sendingConnectionId,
+ messageChannelId,
+ threadExternalId: THREAD_EXTERNAL_ID,
+ text: 'Tuesday works',
+ recipients: [{ handle: CONTACT_HANDLE, displayName: 'Ada Lovelace' }],
+ }),
+ ]);
+
+ const [association] = await globalThis.testDataSource.query(
+ `SELECT direction, "messageExternalId"
+ FROM "${WORKSPACE_SCHEMA}"."messageChannelMessageAssociation"
+ WHERE "messageId" = $1`,
+ [response.body.data.sendAppChannelMessage.messageId],
+ );
+
+ expect(association).toEqual({
+ direction: MessageDirection.OUTGOING,
+ messageExternalId: 'sent:Tuesday works',
+ });
+ });
+
+ it('keeps one message when the app later ingests the reply it sent', async () => {
+ const { messageChannelId, messageThreadId } = await startConversation({
+ connectedAccountId: sendingConnectionId,
+ messagingProviderUniversalIdentifier: MESSAGING_PROVIDER_IDENTIFIER,
+ });
+
+ const sendResponse = await send({
+ messageChannelId,
+ messageThreadId,
+ text: 'Tuesday works',
+ });
+
+ const echoResponse = await asApplication({
+ query: INGEST_MESSAGES_MUTATION,
+ variables: {
+ input: {
+ messageChannelId,
+ messages: [
+ {
+ externalId: 'sent:Tuesday works',
+ threadExternalId: THREAD_EXTERNAL_ID,
+ text: 'Tuesday works',
+ receivedAt: '2026-10-21T10:00:00.000Z',
+ participants: [
+ { role: MessageParticipantRole.FROM, handle: CHANNEL_HANDLE },
+ { role: MessageParticipantRole.TO, handle: CONTACT_HANDLE },
+ ],
+ },
+ ],
+ },
+ },
+ });
+
+ expect(echoResponse.body.data.ingestAppMessages.messages[0].messageId).toBe(
+ sendResponse.body.data.sendAppChannelMessage.messageId,
+ );
+
+ const participants: { handle: string; role: string }[] =
+ await globalThis.testDataSource.query(
+ `SELECT handle, role FROM "${WORKSPACE_SCHEMA}"."messageParticipant"
+ WHERE "messageId" = $1 ORDER BY role`,
+ [sendResponse.body.data.sendAppChannelMessage.messageId],
+ );
+
+ expect(participants).toEqual([
+ { handle: CHANNEL_HANDLE, role: MessageParticipantRole.FROM },
+ { handle: CONTACT_HANDLE, role: MessageParticipantRole.TO },
+ ]);
+ });
+
+ it('sends once and returns the recorded reply when retried with the same idempotency key', async () => {
+ const { messageChannelId, messageThreadId } = await startConversation({
+ connectedAccountId: sendingConnectionId,
+ messagingProviderUniversalIdentifier: MESSAGING_PROVIDER_IDENTIFIER,
+ });
+ const idempotencyKey = v4();
+
+ const firstResponse = await send({
+ messageChannelId,
+ messageThreadId,
+ text: 'Tuesday works',
+ idempotencyKey,
+ });
+ const retryResponse = await send({
+ messageChannelId,
+ messageThreadId,
+ text: 'Tuesday works',
+ idempotencyKey,
+ });
+
+ expect(retryResponse.body.errors).toBeUndefined();
+ expect(retryResponse.body.data.sendAppChannelMessage.messageId).toBe(
+ firstResponse.body.data.sendAppChannelMessage.messageId,
+ );
+ expect(readSendExecutions()).toEqual([
+ expect.objectContaining({ text: 'Tuesday works', idempotencyKey }),
+ ]);
+ });
+
+ it('replies to the latest message participants only, not to someone who left the conversation', async () => {
+ const { messageChannelId, messageThreadId } = await startConversation({
+ connectedAccountId: sendingConnectionId,
+ messagingProviderUniversalIdentifier: MESSAGING_PROVIDER_IDENTIFIER,
+ });
+
+ const olderMessageResponse = await asApplication({
+ query: INGEST_MESSAGES_MUTATION,
+ variables: {
+ input: {
+ messageChannelId,
+ messages: [
+ {
+ externalId: 'inbound-older',
+ threadExternalId: THREAD_EXTERNAL_ID,
+ text: 'Welcome Grace',
+ receivedAt: '2026-10-19T10:00:00.000Z',
+ participants: [
+ { role: MessageParticipantRole.FROM, handle: CONTACT_HANDLE },
+ { role: MessageParticipantRole.TO, handle: CHANNEL_HANDLE },
+ {
+ role: MessageParticipantRole.TO,
+ handle: 'urn:li:person:grace',
+ },
+ ],
+ },
+ ],
+ },
+ },
+ });
+
+ expect(olderMessageResponse.body.errors).toBeUndefined();
+
+ const response = await send({
+ messageChannelId,
+ messageThreadId,
+ text: 'Tuesday works',
+ });
+
+ expect(response.body.errors).toBeUndefined();
+ expect(readSendExecutions()).toEqual([
+ expect.objectContaining({
+ recipients: [{ handle: CONTACT_HANDLE, displayName: 'Ada Lovelace' }],
+ }),
+ ]);
+ });
+
+ it('takes recipients only from messages of the channel it replies through', async () => {
+ const { messageChannelId, messageThreadId } = await startConversation({
+ connectedAccountId: sendingConnectionId,
+ messagingProviderUniversalIdentifier: MESSAGING_PROVIDER_IDENTIFIER,
+ });
+
+ const otherChannelResponse = await createChannel({
+ connectedAccountId: silentConnectionId,
+ });
+ const otherMessageChannelId: string =
+ otherChannelResponse.body.data.createAppMessageChannel.id;
+
+ const otherIngestResponse = await asApplication({
+ query: INGEST_MESSAGES_MUTATION,
+ variables: {
+ input: {
+ messageChannelId: otherMessageChannelId,
+ messages: [
+ {
+ externalId: 'other-channel-1',
+ threadExternalId: 'urn:li:conversation:other',
+ text: 'Newer message from another channel',
+ receivedAt: '2026-10-22T10:00:00.000Z',
+ participants: [
+ {
+ role: MessageParticipantRole.FROM,
+ handle: 'urn:li:person:grace',
+ },
+ { role: MessageParticipantRole.TO, handle: CHANNEL_HANDLE },
+ ],
+ },
+ ],
+ },
+ },
+ });
+
+ expect(otherIngestResponse.body.errors).toBeUndefined();
+
+ const [otherMessage]: { messageId: string; messageThreadId: string }[] =
+ otherIngestResponse.body.data.ingestAppMessages.messages;
+
+ await globalThis.testDataSource.query(
+ `UPDATE "${WORKSPACE_SCHEMA}"."message" SET "messageThreadId" = $1 WHERE id = $2`,
+ [messageThreadId, otherMessage.messageId],
+ );
+ await globalThis.testDataSource.query(
+ `DELETE FROM "${WORKSPACE_SCHEMA}"."messageThreadTarget" WHERE "messageThreadId" = $1`,
+ [otherMessage.messageThreadId],
+ );
+ await globalThis.testDataSource.query(
+ `DELETE FROM "${WORKSPACE_SCHEMA}"."messageThread" WHERE id = $1`,
+ [otherMessage.messageThreadId],
+ );
+
+ const response = await send({
+ messageChannelId,
+ messageThreadId,
+ text: 'Tuesday works',
+ });
+
+ expect(response.body.errors).toBeUndefined();
+ expect(readSendExecutions()).toEqual([
+ expect.objectContaining({
+ threadExternalId: THREAD_EXTERNAL_ID,
+ recipients: [{ handle: CONTACT_HANDLE, displayName: 'Ada Lovelace' }],
+ }),
+ ]);
+ });
+
+ it('records nothing when the app fails to send', async () => {
+ const { messageChannelId, messageThreadId } = await startConversation({
+ connectedAccountId: sendingConnectionId,
+ messagingProviderUniversalIdentifier: MESSAGING_PROVIDER_IDENTIFIER,
+ });
+
+ const response = await send({
+ messageChannelId,
+ messageThreadId,
+ text: 'refused',
+ });
+
+ expect(response.body.errors).toBeDefined();
+
+ const [{ count }] = await globalThis.testDataSource.query(
+ `SELECT COUNT(*)::int AS count FROM "${WORKSPACE_SCHEMA}"."message" WHERE "messageThreadId" = $1`,
+ [messageThreadId],
+ );
+
+ expect(count).toBe(1);
+ });
+
+ it('refuses a channel whose sync is turned off without calling the app', async () => {
+ const { messageChannelId, messageThreadId } = await startConversation({
+ connectedAccountId: sendingConnectionId,
+ messagingProviderUniversalIdentifier: MESSAGING_PROVIDER_IDENTIFIER,
+ });
+
+ await asApplication({
+ query: UPDATE_CHANNEL_MUTATION,
+ variables: { input: { id: messageChannelId, isSyncEnabled: false } },
+ });
+
+ const response = await send({
+ messageChannelId,
+ messageThreadId,
+ text: 'Tuesday works',
+ });
+
+ expect(response.body.errors).toBeDefined();
+ expect(readSendExecutions()).toEqual([]);
+ });
+
+ it('sends only while the channel is bound to a messaging provider', async () => {
+ const { messageChannelId, messageThreadId } = await startConversation({
+ connectedAccountId: sendingConnectionId,
+ });
+
+ const unboundResponse = await send({
+ messageChannelId,
+ messageThreadId,
+ text: 'Tuesday works',
+ });
+
+ expect(unboundResponse.body.errors?.[0]?.extensions?.code).toBe(
+ 'NOT_FOUND',
+ );
+
+ const bindResponse = await bindChannel({
+ messageChannelId,
+ messagingProviderUniversalIdentifier: MESSAGING_PROVIDER_IDENTIFIER,
+ });
+
+ expect(bindResponse.body.errors).toBeUndefined();
+
+ const boundResponse = await send({
+ messageChannelId,
+ messageThreadId,
+ text: 'Tuesday works',
+ });
+
+ expect(boundResponse.body.errors).toBeUndefined();
+
+ await bindChannel({
+ messageChannelId,
+ messagingProviderUniversalIdentifier: null,
+ });
+
+ const unboundAgainResponse = await send({
+ messageChannelId,
+ messageThreadId,
+ text: 'Wednesday works',
+ });
+
+ expect(unboundAgainResponse.body.errors?.[0]?.extensions?.code).toBe(
+ 'NOT_FOUND',
+ );
+ expect(readSendExecutions()).toHaveLength(1);
+ });
+
+ it('refuses a messaging provider that uses another connection provider', async () => {
+ const response = await createChannel({
+ connectedAccountId: silentConnectionId,
+ messagingProviderUniversalIdentifier: MESSAGING_PROVIDER_IDENTIFIER,
+ });
+
+ expect(response.body.errors?.[0]?.extensions?.code).toBe('BAD_USER_INPUT');
+ });
+});
diff --git a/packages/twenty-server/test/integration/metadata/suites/messaging-provider/messaging-provider-manifest-sync.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/messaging-provider/messaging-provider-manifest-sync.integration-spec.ts
new file mode 100644
index 00000000000..3897f5b0d0e
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/messaging-provider/messaging-provider-manifest-sync.integration-spec.ts
@@ -0,0 +1,208 @@
+import { buildBaseManifest } from 'test/integration/metadata/suites/application/utils/build-base-manifest.util';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import { setupApplicationForSync } from 'test/integration/metadata/suites/application/utils/setup-application-for-sync.util';
+import { syncApplication } from 'test/integration/metadata/suites/application/utils/sync-application.util';
+import {
+ type ConnectionProviderManifest,
+ type MessagingProviderManifest,
+} from 'twenty-shared/application';
+import { v4 as uuidv4 } from 'uuid';
+
+const TEST_APP_ID = uuidv4();
+const TEST_ROLE_ID = uuidv4();
+const FIRST_CONNECTION_PROVIDER_ID = uuidv4();
+const SECOND_CONNECTION_PROVIDER_ID = uuidv4();
+const MESSAGING_PROVIDER_ID = uuidv4();
+
+const buildConnectionProvider = ({
+ universalIdentifier,
+ name,
+}: {
+ universalIdentifier: string;
+ name: string;
+}): ConnectionProviderManifest => ({
+ universalIdentifier,
+ name,
+ displayName: name,
+ type: 'oauth',
+ oauth: {
+ authorizationEndpoint: 'https://provider.example.com/authorize',
+ tokenEndpoint: 'https://provider.example.com/token',
+ scopes: [],
+ clientIdVariable: 'CLIENT_ID',
+ clientSecretVariable: 'CLIENT_SECRET',
+ },
+});
+
+const CONNECTION_PROVIDERS = [
+ buildConnectionProvider({
+ universalIdentifier: FIRST_CONNECTION_PROVIDER_ID,
+ name: 'unipile',
+ }),
+ buildConnectionProvider({
+ universalIdentifier: SECOND_CONNECTION_PROVIDER_ID,
+ name: 'unipile-sandbox',
+ }),
+];
+
+const buildMessagingProvider = (
+ overrides: Partial<MessagingProviderManifest> = {},
+): MessagingProviderManifest => ({
+ universalIdentifier: MESSAGING_PROVIDER_ID,
+ name: 'linkedin-messaging',
+ displayName: 'LinkedIn Messages',
+ connectionProvider: { universalIdentifier: FIRST_CONNECTION_PROVIDER_ID },
+ ...overrides,
+});
+
+const syncMessagingProviders = ({
+ messagingProviders,
+ expectToFail = false,
+}: {
+ messagingProviders: MessagingProviderManifest[];
+ expectToFail?: boolean;
+}) =>
+ syncApplication({
+ manifest: buildBaseManifest({
+ appId: TEST_APP_ID,
+ roleId: TEST_ROLE_ID,
+ overrides: {
+ connectionProviders: CONNECTION_PROVIDERS,
+ messagingProviders,
+ },
+ }),
+ expectToFail,
+ });
+
+const findMessagingProviders = async (): Promise<
+ {
+ name: string;
+ connectionProviderUniversalIdentifier: string;
+ sendMessageLogicFunctionUniversalIdentifier: string | null;
+ }[]
+> =>
+ globalThis.testDataSource.query(
+ `SELECT mp.name, mp."connectionProviderUniversalIdentifier",
+ mp."sendMessageLogicFunctionUniversalIdentifier"
+ FROM core."messagingProvider" mp
+ JOIN core."application" app ON app.id = mp."applicationId"
+ WHERE app."universalIdentifier" = $1`,
+ [TEST_APP_ID],
+ );
+
+describe('messaging provider manifest sync', () => {
+ beforeEach(async () => {
+ await setupApplicationForSync({
+ applicationUniversalIdentifier: TEST_APP_ID,
+ name: 'Test Application',
+ description: 'App for testing messaging providers',
+ sourcePath: 'test-messaging-provider-sync',
+ });
+ }, 60000);
+
+ afterEach(async () => {
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: TEST_APP_ID,
+ });
+ });
+
+ it('stores an ingestion-only messaging provider on its connection provider', async () => {
+ await syncMessagingProviders({
+ messagingProviders: [buildMessagingProvider()],
+ });
+
+ expect(await findMessagingProviders()).toEqual([
+ {
+ name: 'linkedin-messaging',
+ connectionProviderUniversalIdentifier: FIRST_CONNECTION_PROVIDER_ID,
+ sendMessageLogicFunctionUniversalIdentifier: null,
+ },
+ ]);
+ }, 60000);
+
+ it('refuses a connection provider that is not in the application', async () => {
+ const { errors } = await syncMessagingProviders({
+ messagingProviders: [
+ buildMessagingProvider({
+ connectionProvider: { universalIdentifier: uuidv4() },
+ }),
+ ],
+ expectToFail: true,
+ });
+
+ expect(JSON.stringify(errors)).toContain(
+ 'was not found in this application',
+ );
+ expect(await findMessagingProviders()).toEqual([]);
+ }, 60000);
+
+ it('refuses a send function that is not in the application', async () => {
+ const { errors } = await syncMessagingProviders({
+ messagingProviders: [
+ buildMessagingProvider({
+ sendMessageLogicFunction: { universalIdentifier: uuidv4() },
+ }),
+ ],
+ expectToFail: true,
+ });
+
+ expect(JSON.stringify(errors)).toContain('Send message logic function');
+ }, 60000);
+
+ it('refuses moving a messaging provider to another connection provider', async () => {
+ await syncMessagingProviders({
+ messagingProviders: [buildMessagingProvider()],
+ });
+
+ const { errors } = await syncMessagingProviders({
+ messagingProviders: [
+ buildMessagingProvider({
+ connectionProvider: {
+ universalIdentifier: SECOND_CONNECTION_PROVIDER_ID,
+ },
+ }),
+ ],
+ expectToFail: true,
+ });
+
+ expect(JSON.stringify(errors)).toContain(
+ 'connection provider cannot be changed after creation',
+ );
+ expect(await findMessagingProviders()).toEqual([
+ expect.objectContaining({
+ connectionProviderUniversalIdentifier: FIRST_CONNECTION_PROVIDER_ID,
+ }),
+ ]);
+ }, 60000);
+
+ it('refuses renaming a messaging provider to a name its application already uses', async () => {
+ const otherMessagingProvider = buildMessagingProvider({
+ universalIdentifier: uuidv4(),
+ name: 'whatsapp-messaging',
+ displayName: 'WhatsApp',
+ });
+
+ await syncMessagingProviders({
+ messagingProviders: [buildMessagingProvider(), otherMessagingProvider],
+ });
+
+ const { errors } = await syncMessagingProviders({
+ messagingProviders: [
+ buildMessagingProvider(),
+ { ...otherMessagingProvider, name: 'linkedin-messaging' },
+ ],
+ expectToFail: true,
+ });
+
+ expect(JSON.stringify(errors)).toContain('already exists');
+ }, 60000);
+
+ it('deletes a messaging provider the manifest no longer declares', async () => {
+ await syncMessagingProviders({
+ messagingProviders: [buildMessagingProvider()],
+ });
+ await syncMessagingProviders({ messagingProviders: [] });
+
+ expect(await findMessagingProviders()).toEqual([]);
+ }, 60000);
+});
diff --git a/packages/twenty-shared/src/application/appConnectionType.ts b/packages/twenty-shared/src/application/appConnectionType.ts
index 24bae516751..4ec11febeee 100644
--- a/packages/twenty-shared/src/application/appConnectionType.ts
+++ b/packages/twenty-shared/src/application/appConnectionType.ts
@@ -5,7 +5,7 @@
// `getConnection`) and the server controller / DTO — pick from one source
// of truth. Adding a field on either side without updating this type will
// fail typecheck.
-export type AppConnection = {
+type AppConnectionBase = {
id: string;
// The app-developer-facing provider name (e.g. "linear"), as declared on
// `defineConnectionProvider({ name })`. Useful when listing across providers
@@ -28,7 +28,6 @@ export type AppConnection = {
// The workspace member who created the credential. null when the creating
// user is no longer a member of the workspace.
workspaceMemberId: string | null;
- accessToken: string;
// OAuth scopes actually granted by the upstream provider on the most recent
// token issuance (may be a subset of what the app requested).
scopes: string[];
@@ -40,3 +39,9 @@ export type AppConnection = {
// Human-readable explanation for `authFailedAt`, when the reporter gave one.
authFailedReason: string | null;
};
+
+export type AppConnection = AppConnectionBase &
+ (
+ | { providerType: 'oauth'; accessToken: string }
+ | { providerType: 'custom'; accessToken: string | null }
+ );
diff --git a/packages/twenty-shared/src/application/appMessageChannelType.ts b/packages/twenty-shared/src/application/appMessageChannelType.ts
index 555bbe3369e..4760c488e34 100644
--- a/packages/twenty-shared/src/application/appMessageChannelType.ts
+++ b/packages/twenty-shared/src/application/appMessageChannelType.ts
@@ -14,4 +14,5 @@ export type AppMessageChannel = {
isSyncEnabled: boolean;
// Person field participant handles are matched against; null when the app links participants itself.
participantHandleFieldUniversalIdentifier: string | null;
+ messagingProviderUniversalIdentifier: string | null;
};
diff --git a/packages/twenty-shared/src/application/connectionProviderManifestType.ts b/packages/twenty-shared/src/application/connectionProviderManifestType.ts
index 2042bad9deb..c2ee52516b4 100644
--- a/packages/twenty-shared/src/application/connectionProviderManifestType.ts
+++ b/packages/twenty-shared/src/application/connectionProviderManifestType.ts
@@ -1,15 +1,20 @@
import { type ConnectionProviderScope } from '@/application/connectionProviderScopeType';
+import { type CustomConnectionProviderConfig } from '@/application/customConnectionProviderConfigType';
import { type OAuthConnectionProviderConfig } from '@/application/oauthConnectionProviderConfigType';
import { type SyncableEntityOptions } from '@/application/syncableEntityOptionsType';
-export type ConnectionProviderManifest = SyncableEntityOptions & {
+type ConnectionProviderManifestBase = SyncableEntityOptions & {
name: string;
displayName: string;
logo?: string;
- type: 'oauth';
scope?: ConnectionProviderScope;
- oauth: OAuthConnectionProviderConfig;
identifyAccountLogicFunction?: SyncableEntityOptions;
onConnectLogicFunction?: SyncableEntityOptions;
onDisconnectLogicFunction?: SyncableEntityOptions;
};
+
+export type ConnectionProviderManifest = ConnectionProviderManifestBase &
+ (
+ | { type: 'oauth'; oauth: OAuthConnectionProviderConfig }
+ | { type: 'custom'; custom: CustomConnectionProviderConfig }
+ );
diff --git a/packages/twenty-shared/src/application/connectionProviderType.ts b/packages/twenty-shared/src/application/connectionProviderType.ts
index 2cffc4f146c..1fa64df60fa 100644
--- a/packages/twenty-shared/src/application/connectionProviderType.ts
+++ b/packages/twenty-shared/src/application/connectionProviderType.ts
@@ -1,5 +1,5 @@
// Discriminator on `connectionProvider.type`. Each value pairs with a
-// typed sub-config column on the entity (today only `oauthConfig`).
+// typed sub-config column on the entity.
//
// Anticipated future values:
// - 'apiKey' — single long-lived token in an applicationVariable
@@ -9,4 +9,4 @@
// Adding a value is purely additive: define the new sub-config column on
// the entity, the manifest type, and the SDK; existing 'oauth' callers
// keep working.
-export type ConnectionProviderType = 'oauth';
+export type ConnectionProviderType = 'oauth' | 'custom';
diff --git a/packages/twenty-shared/src/application/customConnectionFlowType.ts b/packages/twenty-shared/src/application/customConnectionFlowType.ts
new file mode 100644
index 00000000000..bd0b7194830
--- /dev/null
+++ b/packages/twenty-shared/src/application/customConnectionFlowType.ts
@@ -0,0 +1,27 @@
+export type AuthorizeConnectionPayload = {
+ connectionProviderId: string;
+ connectionProviderName: string;
+ callbackUrl: string;
+};
+
+export type AuthorizeConnectionResult = {
+ authorizationUrl: string;
+};
+
+export type ConnectionCallbackPayload = {
+ connectionProviderId: string;
+ connectionProviderName: string;
+ httpMethod: 'GET' | 'POST';
+ queryStringParameters: Record<string, string | undefined>;
+ headers: Record<string, string | undefined>;
+ body: object | null;
+ rawBody: string | null;
+};
+
+export type ConnectedAccountFromCallback = {
+ externalAccountId: string;
+ handle?: string;
+ accessToken?: string;
+};
+
+export type ConnectionCallbackResult = ConnectedAccountFromCallback | null;
diff --git a/packages/twenty-shared/src/application/customConnectionProviderConfigType.ts b/packages/twenty-shared/src/application/customConnectionProviderConfigType.ts
new file mode 100644
index 00000000000..144a225d581
--- /dev/null
+++ b/packages/twenty-shared/src/application/customConnectionProviderConfigType.ts
@@ -0,0 +1,6 @@
+import { type SyncableEntityOptions } from '@/application/syncableEntityOptionsType';
+
+export type CustomConnectionProviderConfig = {
+ authorizeLogicFunction: SyncableEntityOptions;
+ callbackLogicFunction: SyncableEntityOptions;
+};
diff --git a/packages/twenty-shared/src/application/enums/syncable-entities.enum.ts b/packages/twenty-shared/src/application/enums/syncable-entities.enum.ts
index 5d979b32408..5c392677cc2 100644
--- a/packages/twenty-shared/src/application/enums/syncable-entities.enum.ts
+++ b/packages/twenty-shared/src/application/enums/syncable-entities.enum.ts
@@ -7,6 +7,7 @@ export enum SyncableEntity {
Skill = 'skill',
Agent = 'agent',
ConnectionProvider = 'connectionProvider',
+ MessagingProvider = 'messagingProvider',
View = 'view',
ViewField = 'viewField',
NavigationMenuItem = 'navigationMenuItem',
diff --git a/packages/twenty-shared/src/application/index.ts b/packages/twenty-shared/src/application/index.ts
index b24ca384ff1..75fc558f037 100644
--- a/packages/twenty-shared/src/application/index.ts
+++ b/packages/twenty-shared/src/application/index.ts
@@ -97,6 +97,14 @@ export { NODE_ESM_CJS_BANNER } from './constants/NodeEsmCjsBanner';
export { OUTPUT_DIR } from './constants/OutputDirectory';
export { TWENTY_STANDARD_APPLICATION_NAME } from './constants/TwentyStandardApplicationName';
export { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from './constants/TwentyStandardApplicationUniversalIdentifier';
+export type {
+ AuthorizeConnectionPayload,
+ AuthorizeConnectionResult,
+ ConnectionCallbackPayload,
+ ConnectedAccountFromCallback,
+ ConnectionCallbackResult,
+} from './customConnectionFlowType';
+export type { CustomConnectionProviderConfig } from './customConnectionProviderConfigType';
export { computeDeterministicUuid } from './deterministic-identifier/compute-deterministic-uuid.util';
export type { DeterministicEntityNamespace } from './deterministic-identifier/deterministic-entity-namespace.type';
export { getAgentUniversalIdentifier } from './deterministic-identifier/get-agent-universal-identifier.util';
@@ -185,6 +193,7 @@ export type {
HttpRouteTriggerSettings,
} from './logicFunctionManifestType';
export type { TranslationsManifest, Manifest } from './manifestType';
+export type { MessagingProviderManifest } from './messagingProviderManifestType';
export type { NavigationMenuItemManifest } from './navigationMenuItemManifestType';
export type {
NormalizedPageLayoutWidgetManifest,
@@ -225,6 +234,11 @@ export type {
RunAgentInput,
RunAgentResult,
} from './runAgentType';
+export type {
+ SendAppMessageRecipient,
+ SendAppMessagePayload,
+ SendAppMessageResult,
+} from './sendAppMessageType';
export type { SendInboxMessageInput } from './sendInboxMessageInputType';
export type { SendInboxMessageResult } from './sendInboxMessageResultType';
export type { SendInboxMessageToolCall } from './sendInboxMessageToolCallType';
@@ -242,6 +256,7 @@ export {
DEFAULT_SETTINGS_MENU_ITEM_SCOPE,
} from './settingsMenuItemManifestType';
export type { SkillManifest } from './skillManifestType';
+export type { StoredCustomConnectionProviderConfig } from './storedCustomConnectionProviderConfigType';
export type { StoredOAuthConnectionProviderConfig } from './storedOAuthConnectionProviderConfigType';
export type { SyncableEntityOptions } from './syncableEntityOptionsType';
export type {
diff --git a/packages/twenty-shared/src/application/manifestType.ts b/packages/twenty-shared/src/application/manifestType.ts
index 440d758de70..2b476c97500 100644
--- a/packages/twenty-shared/src/application/manifestType.ts
+++ b/packages/twenty-shared/src/application/manifestType.ts
@@ -12,6 +12,7 @@ import {
} from './frontComponentManifestType';
import { type IndexManifest } from './indexManifestType';
import { type LogicFunctionManifest } from './logicFunctionManifestType';
+import { type MessagingProviderManifest } from './messagingProviderManifestType';
import { type NavigationMenuItemManifest } from './navigationMenuItemManifestType';
import { type ObjectManifest } from './objectManifestType';
import {
@@ -46,6 +47,7 @@ export type Manifest = {
skills: SkillManifest[];
agents: AgentManifest[];
connectionProviders?: ConnectionProviderManifest[];
+ messagingProviders?: MessagingProviderManifest[];
publicAssets: AssetManifest[];
views: ViewManifest[];
viewFields: StandaloneViewFieldManifest[];
diff --git a/packages/twenty-shared/src/application/messagingProviderManifestType.ts b/packages/twenty-shared/src/application/messagingProviderManifestType.ts
new file mode 100644
index 00000000000..1fe9b69b4ee
--- /dev/null
+++ b/packages/twenty-shared/src/application/messagingProviderManifestType.ts
@@ -0,0 +1,8 @@
+import { type SyncableEntityOptions } from '@/application/syncableEntityOptionsType';
+
+export type MessagingProviderManifest = SyncableEntityOptions & {
+ name: string;
+ displayName: string;
+ connectionProvider: SyncableEntityOptions;
+ sendMessageLogicFunction?: SyncableEntityOptions;
+};
diff --git a/packages/twenty-shared/src/application/sendAppMessageType.ts b/packages/twenty-shared/src/application/sendAppMessageType.ts
new file mode 100644
index 00000000000..5b9b529e5c2
--- /dev/null
+++ b/packages/twenty-shared/src/application/sendAppMessageType.ts
@@ -0,0 +1,19 @@
+export type SendAppMessageRecipient = {
+ handle: string;
+ displayName: string | null;
+};
+
+export type SendAppMessagePayload = {
+ messagingProviderName: string;
+ connectedAccountId: string;
+ messageChannelId: string;
+ threadExternalId: string;
+ text: string;
+ idempotencyKey: string;
+ recipients: SendAppMessageRecipient[];
+};
+
+export type SendAppMessageResult = {
+ externalId: string;
+ sentAt?: string;
+};
diff --git a/packages/twenty-shared/src/application/storedCustomConnectionProviderConfigType.ts b/packages/twenty-shared/src/application/storedCustomConnectionProviderConfigType.ts
new file mode 100644
index 00000000000..9345c309c78
--- /dev/null
+++ b/packages/twenty-shared/src/application/storedCustomConnectionProviderConfigType.ts
@@ -0,0 +1,4 @@
+export type StoredCustomConnectionProviderConfig = {
+ authorizeLogicFunctionUniversalIdentifier: string;
+ callbackLogicFunctionUniversalIdentifier: string;
+};
diff --git a/packages/twenty-shared/src/metadata/constants/all-metadata-name.constant.ts b/packages/twenty-shared/src/metadata/constants/all-metadata-name.constant.ts
index 2ed9985c86e..bf6fb501042 100644
--- a/packages/twenty-shared/src/metadata/constants/all-metadata-name.constant.ts
+++ b/packages/twenty-shared/src/metadata/constants/all-metadata-name.constant.ts
@@ -29,6 +29,7 @@ export const ALL_METADATA_NAME = {
webhook: 'webhook',
applicationVariable: 'applicationVariable',
connectionProvider: 'connectionProvider',
+ messagingProvider: 'messagingProvider',
searchFieldMetadata: 'searchFieldMetadata',
timelineActivityType: 'timelineActivityType',
settingsMenuItem: 'settingsMenuItem',