Skip to content

The open alternative to Salesforce, designed for AI.

Let applications and workflows start conversations in a member's chats (#27049)

Félix Malfait58a2969e01bd
diff --git a/packages/twenty-agent-skills/references/develop-app/logic.md b/packages/twenty-agent-skills/references/develop-app/logic.md
index 2043ca924ae..f6b46f0d4d1 100644
--- a/packages/twenty-agent-skills/references/develop-app/logic.md
+++ b/packages/twenty-agent-skills/references/develop-app/logic.md
@@ -78,6 +78,18 @@ When adding AI behavior:
- Avoid exposing raw IDs, timestamps, or nested API output to end users when a readable answer is possible.
- A `defineAgent` `roleUniversalIdentifier` must reference a role the app defines, and the application role (`defineApplicationRole` or `defaultRoleUniversalIdentifier`) must cover every permission that agent role grants. The build and `yarn twenty apply` fail otherwise, listing the excess grants.
+## Inbox Messages
+
+`sendInboxMessage` from `twenty-sdk/logic-function` posts a message from the app in a workspace member's chats.
+
+- `workspaceMemberId` is the member who receives it, and `text` is the message, in markdown.
+- `threadKey` picks the conversation per app and member: a new key starts one titled `title`, a known key adds to it. `idempotencyKey` identifies the message in it, so sending again with the same keys writes nothing and retries never duplicate it.
+- `toolCall` (optional) ends the message on `ask_questions`, `request_form` or `propose_email`, which pause the conversation until the member answers, or on one of the app's own tools by `logicFunctionUniversalIdentifier`, rendered by its front component without pausing.
+- Only one call the member answers (`ask_questions`, `request_form`, `propose_email`) can wait at a time; another fails with `THREAD_AWAITING_ANSWER` until they answer. Plain messages and app tool calls are still accepted.
+- A conversation the member deleted is not recreated.
+- The app's default role needs `SystemPermissionFlag.AI`, and the member needs the AI permission.
+- It always uses the app's access and ignores `runAs`.
+
## Connection Providers
For third-party connections:
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index 632f170d9c8..903c6478f31 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -2091,6 +2091,7 @@ enum FeatureFlagKey {
IS_CONVERSATIONS_TAB_ENABLED
IS_VALIDATION_RULES_ENABLED
IS_RECORD_LEVEL_SHARING_ENABLED
+ IS_WORKFLOW_SEND_CHAT_MESSAGE_ENABLED
}
type WorkspaceUrls {
@@ -3495,6 +3496,10 @@ type AgentChatEvent {
event: JSON!
}
+type SendInboxMessageResult {
+ threadId: UUID!
+}
+
type StartWorkspaceSetupChatResult {
outcome: WorkspaceSetupChatOutcome!
thread: AgentChatThread
@@ -4303,6 +4308,7 @@ type Mutation {
stopAgentChatStream(threadId: UUID!): Boolean!
deleteQueuedChatMessage(messageId: UUID!): Boolean!
startWorkspaceSetupChat(companyContext: JSON, personContext: JSON): StartWorkspaceSetupChatResult!
+ sendInboxMessage(input: SendInboxMessageInput!): SendInboxMessageResult!
createSkill(input: CreateSkillInput!): Skill!
updateSkill(input: UpdateSkillInput!): Skill!
deleteSkill(id: UUID!): Skill!
@@ -5581,6 +5587,15 @@ input FileAttachmentInput {
filename: String!
}
+input SendInboxMessageInput {
+ workspaceMemberId: UUID!
+ threadKey: String!
+ idempotencyKey: String!
+ title: String!
+ text: String!
+ toolCall: JSON
+}
+
input CreateSkillInput {
id: UUID
name: String!
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index 20b41eb8e9c..faf2c8be55f 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -1686,7 +1686,7 @@ export interface FeatureFlag {
__typename: 'FeatureFlag'
}
-export type FeatureFlagKey = 'IS_APPLICATION_WORKFLOWS_ENABLED' | 'IS_ASYNC_CSV_EXPORT_ENABLED' | 'IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED' | 'IS_JSON_FILTER_ENABLED' | 'IS_MESSAGE_CAMPAIGN_ENABLED' | 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT' | 'IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED' | 'IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED' | 'IS_AI_CHAT_SHARING_DROPDOWN_ENABLED' | 'IS_INITIAL_OBJECT_VIEW_ENABLED' | 'IS_WEBHOOK_RATE_LIMIT_ENABLED' | 'IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED' | 'IS_EXECUTION_QUOTA_ENABLED' | 'IS_RECORD_CREATION_FORM_ENABLED' | 'IS_LOGS_SETTINGS_SECTION_ENABLED' | 'IS_CONVERSATIONS_TAB_ENABLED' | 'IS_VALIDATION_RULES_ENABLED' | 'IS_RECORD_LEVEL_SHARING_ENABLED'
+export type FeatureFlagKey = 'IS_APPLICATION_WORKFLOWS_ENABLED' | 'IS_ASYNC_CSV_EXPORT_ENABLED' | 'IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED' | 'IS_JSON_FILTER_ENABLED' | 'IS_MESSAGE_CAMPAIGN_ENABLED' | 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT' | 'IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED' | 'IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED' | 'IS_AI_CHAT_SHARING_DROPDOWN_ENABLED' | 'IS_INITIAL_OBJECT_VIEW_ENABLED' | 'IS_WEBHOOK_RATE_LIMIT_ENABLED' | 'IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED' | 'IS_EXECUTION_QUOTA_ENABLED' | 'IS_RECORD_CREATION_FORM_ENABLED' | 'IS_LOGS_SETTINGS_SECTION_ENABLED' | 'IS_CONVERSATIONS_TAB_ENABLED' | 'IS_VALIDATION_RULES_ENABLED' | 'IS_RECORD_LEVEL_SHARING_ENABLED' | 'IS_WORKFLOW_SEND_CHAT_MESSAGE_ENABLED'
export interface WorkspaceUrls {
customUrl?: Scalars['String']
@@ -3081,6 +3081,11 @@ export interface AgentChatEvent {
__typename: 'AgentChatEvent'
}
+export interface SendInboxMessageResult {
+ threadId: Scalars['UUID']
+ __typename: 'SendInboxMessageResult'
+}
+
export interface StartWorkspaceSetupChatResult {
outcome: WorkspaceSetupChatOutcome
thread?: AgentChatThread
@@ -3695,6 +3700,7 @@ export interface Mutation {
stopAgentChatStream: Scalars['Boolean']
deleteQueuedChatMessage: Scalars['Boolean']
startWorkspaceSetupChat: StartWorkspaceSetupChatResult
+ sendInboxMessage: SendInboxMessageResult
createSkill: Skill
updateSkill: Skill
deleteSkill: Skill
@@ -7002,6 +7008,12 @@ export interface AgentChatEventGenqlSelection{
__scalar?: boolean | number
}
+export interface SendInboxMessageResultGenqlSelection{
+ threadId?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
export interface StartWorkspaceSetupChatResultGenqlSelection{
outcome?: boolean | number
thread?: AgentChatThreadGenqlSelection
@@ -7673,6 +7685,7 @@ export interface MutationGenqlSelection{
stopAgentChatStream?: { __args: {threadId: Scalars['UUID']} }
deleteQueuedChatMessage?: { __args: {messageId: Scalars['UUID']} }
startWorkspaceSetupChat?: (StartWorkspaceSetupChatResultGenqlSelection & { __args?: {companyContext?: (Scalars['JSON'] | null), personContext?: (Scalars['JSON'] | null)} })
+ sendInboxMessage?: (SendInboxMessageResultGenqlSelection & { __args: {input: SendInboxMessageInput} })
createSkill?: (SkillGenqlSelection & { __args: {input: CreateSkillInput} })
updateSkill?: (SkillGenqlSelection & { __args: {input: UpdateSkillInput} })
deleteSkill?: (SkillGenqlSelection & { __args: {id: Scalars['UUID']} })
@@ -8148,6 +8161,8 @@ export interface ReportAppConnectionAuthFailureInput {id: Scalars['ID'],reason?:
export interface FileAttachmentInput {id: Scalars['UUID'],filename: Scalars['String']}
+export interface SendInboxMessageInput {workspaceMemberId: Scalars['UUID'],threadKey: Scalars['String'],idempotencyKey: Scalars['String'],title: Scalars['String'],text: Scalars['String'],toolCall?: (Scalars['JSON'] | null)}
+
export interface CreateSkillInput {id?: (Scalars['UUID'] | null),name: Scalars['String'],label: Scalars['String'],icon?: (Scalars['String'] | null),description?: (Scalars['String'] | null),content: Scalars['String']}
export interface UpdateSkillInput {id: Scalars['UUID'],name?: (Scalars['String'] | null),label?: (Scalars['String'] | null),icon?: (Scalars['String'] | null),description?: (Scalars['String'] | null),content?: (Scalars['String'] | null),isActive?: (Scalars['Boolean'] | null)}
@@ -10491,6 +10506,14 @@ export interface CreateRecordExportInput {objectMetadataId: Scalars['UUID'],fiel
+ const SendInboxMessageResult_possibleTypes: string[] = ['SendInboxMessageResult']
+ export const isSendInboxMessageResult = (obj?: { __typename?: any } | null): obj is SendInboxMessageResult => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isSendInboxMessageResult"')
+ return SendInboxMessageResult_possibleTypes.includes(obj.__typename)
+ }
+
+
+
const StartWorkspaceSetupChatResult_possibleTypes: string[] = ['StartWorkspaceSetupChatResult']
export const isStartWorkspaceSetupChatResult = (obj?: { __typename?: any } | null): obj is StartWorkspaceSetupChatResult => {
if (!obj?.__typename) throw new Error('__typename is missing in "isStartWorkspaceSetupChatResult"')
@@ -11299,7 +11322,8 @@ export const enumFeatureFlagKey = {
IS_LOGS_SETTINGS_SECTION_ENABLED: 'IS_LOGS_SETTINGS_SECTION_ENABLED' as const,
IS_CONVERSATIONS_TAB_ENABLED: 'IS_CONVERSATIONS_TAB_ENABLED' as const,
IS_VALIDATION_RULES_ENABLED: 'IS_VALIDATION_RULES_ENABLED' as const,
- IS_RECORD_LEVEL_SHARING_ENABLED: 'IS_RECORD_LEVEL_SHARING_ENABLED' as const
+ IS_RECORD_LEVEL_SHARING_ENABLED: 'IS_RECORD_LEVEL_SHARING_ENABLED' as const,
+ IS_WORKFLOW_SEND_CHAT_MESSAGE_ENABLED: 'IS_WORKFLOW_SEND_CHAT_MESSAGE_ENABLED' as const
}
export const enumIdentityProviderType = {
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index c817d411865..d6000ebd79e 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -93,21 +93,21 @@ export default {
348,
349,
352,
- 385,
- 399,
- 401,
+ 386,
+ 400,
402,
403,
404,
- 406,
- 408,
- 415,
- 434,
- 438,
- 449,
- 569,
- 573,
- 602
+ 405,
+ 407,
+ 409,
+ 416,
+ 435,
+ 439,
+ 450,
+ 570,
+ 574,
+ 604
],
"types": {
"BillingProductDTO": {
@@ -6919,9 +6919,17 @@ export default {
1
]
},
+ "SendInboxMessageResult": {
+ "threadId": [
+ 3
+ ],
+ "__typename": [
+ 1
+ ]
+ },
"StartWorkspaceSetupChatResult": {
"outcome": [
- 385
+ 386
],
"thread": [
377
@@ -6992,13 +7000,13 @@ export default {
},
"EventLogQueryResult": {
"records": [
- 388
+ 389
],
"totalCount": [
30
],
"pageInfo": [
- 389
+ 390
],
"__typename": [
1
@@ -7069,7 +7077,7 @@ export default {
3
],
"evaluations": [
- 393
+ 394
],
"messages": [
361
@@ -7134,7 +7142,7 @@ export default {
9
],
"scope": [
- 399
+ 400
],
"__typename": [
1
@@ -7149,19 +7157,19 @@ export default {
1
],
"syncStatus": [
- 401
+ 402
],
"syncStage": [
- 402
+ 403
],
"visibility": [
- 403
+ 404
],
"isContactAutoCreationEnabled": [
8
],
"contactAutoCreationPolicy": [
- 404
+ 405
],
"isSyncEnabled": [
8
@@ -7212,7 +7220,7 @@ export default {
1
],
"pendingSyncAction": [
- 406
+ 407
],
"messageChannelId": [
3
@@ -7254,7 +7262,7 @@ export default {
1
],
"provenance": [
- 408
+ 409
],
"__typename": [
1
@@ -7283,7 +7291,7 @@ export default {
3
],
"through": [
- 409
+ 410
],
"__typename": [
1
@@ -7303,7 +7311,7 @@ export default {
1
],
"emit": [
- 410
+ 411
],
"action": [
1
@@ -7405,7 +7413,7 @@ export default {
},
"CollectionHash": {
"collectionName": [
- 415
+ 416
],
"hash": [
1
@@ -7469,13 +7477,13 @@ export default {
},
"MinimalMetadata": {
"objectMetadataItems": [
- 416
+ 417
],
"views": [
- 417
+ 418
],
"collectionHashes": [
- 414
+ 415
],
"__typename": [
1
@@ -7486,7 +7494,7 @@ export default {
173,
{
"target": [
- 420,
+ 421,
"RecordSharingTargetInput!"
]
}
@@ -7553,7 +7561,7 @@ export default {
161,
{
"input": [
- 421,
+ 422,
"UsageQuotaScopeInput!"
]
}
@@ -7712,7 +7720,7 @@ export default {
10,
{
"input": [
- 422,
+ 423,
"AgentIdInput!"
]
}
@@ -7725,7 +7733,7 @@ export default {
"CursorPaging!"
],
"filter": [
- 423,
+ 424,
"ObjectFilter!"
]
}
@@ -7758,7 +7766,7 @@ export default {
23,
{
"input": [
- 424,
+ 425,
"LogicFunctionIdInput!"
]
}
@@ -7770,7 +7778,7 @@ export default {
9,
{
"input": [
- 424,
+ 425,
"LogicFunctionIdInput!"
]
}
@@ -7779,7 +7787,7 @@ export default {
1,
{
"input": [
- 424,
+ 425,
"LogicFunctionIdInput!"
]
}
@@ -7824,7 +7832,7 @@ export default {
193,
{
"input": [
- 425
+ 426
]
}
],
@@ -7864,7 +7872,7 @@ export default {
2,
{
"input": [
- 426,
+ 427,
"GetApiKeyInput!"
]
}
@@ -8106,7 +8114,7 @@ export default {
342,
{
"input": [
- 427,
+ 428,
"PreviewMessageCampaignAudienceInput!"
]
}
@@ -8115,7 +8123,7 @@ export default {
350,
{
"input": [
- 428,
+ 429,
"FindMessageSuppressionsInput!"
]
}
@@ -8135,7 +8143,7 @@ export default {
331,
{
"filter": [
- 429
+ 430
]
}
],
@@ -8167,7 +8175,7 @@ export default {
}
],
"myMessageFolders": [
- 405,
+ 406,
{
"messageChannelId": [
3
@@ -8175,7 +8183,7 @@ export default {
}
],
"myCalendarChannels": [
- 400,
+ 401,
{
"connectedAccountId": [
3
@@ -8183,20 +8191,20 @@ export default {
}
],
"getPermissionFlags": [
- 413
+ 414
],
"minimalMetadata": [
- 418
+ 419
],
"appKeyValue": [
- 398,
+ 399,
{
"key": [
1,
"String!"
],
"scope": [
- 399
+ 400
]
}
],
@@ -8213,7 +8221,7 @@ export default {
239,
{
"filter": [
- 430
+ 431
]
}
],
@@ -8227,7 +8235,7 @@ export default {
}
],
"findWorkspaceAiStats": [
- 395
+ 396
],
"aiChatUsage": [
375
@@ -8275,7 +8283,7 @@ export default {
}
],
"agentTurns": [
- 394,
+ 395,
{
"agentId": [
3,
@@ -8284,7 +8292,7 @@ export default {
}
],
"validationRules": [
- 412,
+ 413,
{
"objectMetadataId": [
3,
@@ -8293,22 +8301,22 @@ export default {
}
],
"timelineActivityTypes": [
- 411
+ 412
],
"metadataTranslations": [
- 407,
+ 408,
{
"input": [
- 431,
+ 432,
"MetadataTranslationsInput!"
]
}
],
"recordPermissions": [
- 392,
+ 393,
{
"targets": [
- 432,
+ 433,
"[RecordPermissionsTargetInput!]!"
]
}
@@ -8371,10 +8379,10 @@ export default {
244
],
"eventLogs": [
- 390,
+ 391,
{
"input": [
- 433,
+ 434,
"EventLogQueryInput!"
]
}
@@ -8383,7 +8391,7 @@ export default {
373,
{
"input": [
- 439,
+ 440,
"PieChartDataInput!"
]
}
@@ -8392,7 +8400,7 @@ export default {
371,
{
"input": [
- 440,
+ 441,
"LineChartDataInput!"
]
}
@@ -8401,7 +8409,7 @@ export default {
368,
{
"input": [
- 441,
+ 442,
"BarChartDataInput!"
]
}
@@ -8528,10 +8536,10 @@ export default {
},
"ObjectFilter": {
"and": [
- 423
+ 424
],
"or": [
- 423
+ 424
],
"id": [
33
@@ -8677,10 +8685,10 @@ export default {
},
"EventLogQueryInput": {
"table": [
- 434
+ 435
],
"filters": [
- 435
+ 436
],
"first": [
30
@@ -8701,7 +8709,7 @@ export default {
1
],
"dateRange": [
- 436
+ 437
],
"recordId": [
1
@@ -8710,7 +8718,7 @@ export default {
1
],
"fieldFilters": [
- 437
+ 438
],
"__typename": [
1
@@ -8732,7 +8740,7 @@ export default {
1
],
"operand": [
- 438
+ 439
],
"values": [
1
@@ -8780,7 +8788,7 @@ export default {
8,
{
"input": [
- 443,
+ 444,
"AddQuerySubscriptionInput!"
]
}
@@ -8789,7 +8797,7 @@ export default {
8,
{
"input": [
- 444,
+ 445,
"RemoveQueryFromEventStreamInput!"
]
}
@@ -8798,11 +8806,11 @@ export default {
173,
{
"target": [
- 420,
+ 421,
"RecordSharingTargetInput!"
],
"principal": [
- 445,
+ 446,
"RecordSharePrincipalInput!"
],
"enabled": [
@@ -8818,7 +8826,7 @@ export default {
166,
{
"inputs": [
- 446,
+ 447,
"[CreateNavigationMenuItemInput!]!"
]
}
@@ -8827,7 +8835,7 @@ export default {
166,
{
"input": [
- 446,
+ 447,
"CreateNavigationMenuItemInput!"
]
}
@@ -8836,7 +8844,7 @@ export default {
166,
{
"inputs": [
- 447,
+ 448,
"[UpdateOneNavigationMenuItemInput!]!"
]
}
@@ -8845,7 +8853,7 @@ export default {
166,
{
"input": [
- 447,
+ 448,
"UpdateOneNavigationMenuItemInput!"
]
}
@@ -8919,7 +8927,7 @@ export default {
163,
{
"file": [
- 449,
+ 450,
"Upload!"
]
}
@@ -8928,7 +8936,7 @@ export default {
163,
{
"file": [
- 449,
+ 450,
"Upload!"
]
}
@@ -8955,7 +8963,7 @@ export default {
163,
{
"file": [
- 449,
+ 450,
"Upload!"
],
"fieldMetadataUniversalIdentifier": [
@@ -8968,7 +8976,7 @@ export default {
162,
{
"input": [
- 450,
+ 451,
"CreateUsageLimitInput!"
]
}
@@ -8977,7 +8985,7 @@ export default {
162,
{
"input": [
- 451,
+ 452,
"UpdateUsageLimitInput!"
]
}
@@ -8995,7 +9003,7 @@ export default {
100,
{
"input": [
- 452,
+ 453,
"CreatePageLayoutWidgetInput!"
]
}
@@ -9008,7 +9016,7 @@ export default {
"String!"
],
"input": [
- 453,
+ 454,
"UpdatePageLayoutWidgetInput!"
]
}
@@ -9026,7 +9034,7 @@ export default {
146,
{
"input": [
- 454,
+ 455,
"CreatePageLayoutTabInput!"
]
}
@@ -9039,7 +9047,7 @@ export default {
"String!"
],
"input": [
- 455,
+ 456,
"UpdatePageLayoutTabInput!"
]
}
@@ -9057,7 +9065,7 @@ export default {
147,
{
"input": [
- 456,
+ 457,
"CreatePageLayoutInput!"
]
}
@@ -9070,7 +9078,7 @@ export default {
"String!"
],
"input": [
- 457,
+ 458,
"UpdatePageLayoutInput!"
]
}
@@ -9092,7 +9100,7 @@ export default {
"String!"
],
"input": [
- 458,
+ 459,
"UpdatePageLayoutWithTabsInput!"
]
}
@@ -9128,7 +9136,7 @@ export default {
65,
{
"input": [
- 461,
+ 462,
"CreateViewInput!"
]
}
@@ -9141,7 +9149,7 @@ export default {
"String!"
],
"input": [
- 462,
+ 463,
"UpdateViewInput!"
]
}
@@ -9168,7 +9176,7 @@ export default {
65,
{
"input": [
- 463,
+ 464,
"UpsertViewWidgetInput!"
]
}
@@ -9177,7 +9185,7 @@ export default {
62,
{
"input": [
- 469,
+ 470,
"CreateViewSortInput!"
]
}
@@ -9186,7 +9194,7 @@ export default {
62,
{
"input": [
- 470,
+ 471,
"UpdateViewSortInput!"
]
}
@@ -9195,7 +9203,7 @@ export default {
8,
{
"input": [
- 472,
+ 473,
"DeleteViewSortInput!"
]
}
@@ -9204,7 +9212,7 @@ export default {
8,
{
"input": [
- 473,
+ 474,
"DestroyViewSortInput!"
]
}
@@ -9213,7 +9221,7 @@ export default {
59,
{
"input": [
- 474,
+ 475,
"CreateViewFilterInput!"
]
}
@@ -9222,7 +9230,7 @@ export default {
59,
{
"input": [
- 475,
+ 476,
"UpdateViewFilterInput!"
]
}
@@ -9231,7 +9239,7 @@ export default {
59,
{
"input": [
- 477,
+ 478,
"DeleteViewFilterInput!"
]
}
@@ -9240,7 +9248,7 @@ export default {
59,
{
"input": [
- 478,
+ 479,
"DestroyViewFilterInput!"
]
}
@@ -9249,7 +9257,7 @@ export default {
55,
{
"input": [
- 479,
+ 480,
"UpdateViewFieldInput!"
]
}
@@ -9258,7 +9266,7 @@ export default {
55,
{
"input": [
- 481,
+ 482,
"CreateViewFieldInput!"
]
}
@@ -9267,7 +9275,7 @@ export default {
55,
{
"inputs": [
- 481,
+ 482,
"[CreateViewFieldInput!]!"
]
}
@@ -9276,7 +9284,7 @@ export default {
55,
{
"input": [
- 482,
+ 483,
"DeleteViewFieldInput!"
]
}
@@ -9285,7 +9293,7 @@ export default {
55,
{
"input": [
- 483,
+ 484,
"DestroyViewFieldInput!"
]
}
@@ -9294,7 +9302,7 @@ export default {
64,
{
"input": [
- 484,
+ 485,
"UpdateViewFieldGroupInput!"
]
}
@@ -9303,7 +9311,7 @@ export default {
64,
{
"input": [
- 486,
+ 487,
"CreateViewFieldGroupInput!"
]
}
@@ -9312,7 +9320,7 @@ export default {
64,
{
"inputs": [
- 486,
+ 487,
"[CreateViewFieldGroupInput!]!"
]
}
@@ -9321,7 +9329,7 @@ export default {
64,
{
"input": [
- 487,
+ 488,
"DeleteViewFieldGroupInput!"
]
}
@@ -9330,7 +9338,7 @@ export default {
64,
{
"input": [
- 488,
+ 489,
"DestroyViewFieldGroupInput!"
]
}
@@ -9339,7 +9347,7 @@ export default {
65,
{
"input": [
- 489,
+ 490,
"UpsertFieldsWidgetInput!"
]
}
@@ -9348,7 +9356,7 @@ export default {
10,
{
"input": [
- 492,
+ 493,
"CreateAgentInput!"
]
}
@@ -9357,7 +9365,7 @@ export default {
10,
{
"input": [
- 493,
+ 494,
"UpdateAgentInput!"
]
}
@@ -9366,7 +9374,7 @@ export default {
10,
{
"input": [
- 422,
+ 423,
"AgentIdInput!"
]
}
@@ -9375,7 +9383,7 @@ export default {
25,
{
"input": [
- 494,
+ 495,
"CreateOneObjectInput!"
]
}
@@ -9384,7 +9392,7 @@ export default {
25,
{
"input": [
- 496,
+ 497,
"DeleteOneObjectInput!"
]
}
@@ -9393,7 +9401,7 @@ export default {
25,
{
"input": [
- 497,
+ 498,
"UpdateOneObjectInput!"
]
}
@@ -9402,7 +9410,7 @@ export default {
25,
{
"inputs": [
- 497,
+ 498,
"[UpdateOneObjectInput!]!"
]
}
@@ -9411,7 +9419,7 @@ export default {
272,
{
"input": [
- 500,
+ 501,
"CreateOneIndexInput!"
]
}
@@ -9420,7 +9428,7 @@ export default {
272,
{
"input": [
- 503,
+ 504,
"DeleteOneIndexInput!"
]
}
@@ -9441,7 +9449,7 @@ export default {
23,
{
"input": [
- 424,
+ 425,
"LogicFunctionIdInput!"
]
}
@@ -9450,7 +9458,7 @@ export default {
23,
{
"input": [
- 504,
+ 505,
"CreateLogicFunctionFromSourceInput!"
]
}
@@ -9459,7 +9467,7 @@ export default {
151,
{
"input": [
- 505,
+ 506,
"ExecuteOneLogicFunctionInput!"
]
}
@@ -9468,7 +9476,7 @@ export default {
8,
{
"input": [
- 506,
+ 507,
"UpdateLogicFunctionFromSourceInput!"
]
}
@@ -9477,7 +9485,7 @@ export default {
14,
{
"input": [
- 508,
+ 509,
"CreateCommandMenuItemInput!"
]
}
@@ -9486,7 +9494,7 @@ export default {
14,
{
"input": [
- 509,
+ 510,
"UpdateCommandMenuItemInput!"
]
}
@@ -9522,7 +9530,7 @@ export default {
13,
{
"input": [
- 510,
+ 511,
"CreateFrontComponentInput!"
]
}
@@ -9531,7 +9539,7 @@ export default {
13,
{
"input": [
- 511,
+ 512,
"UpdateFrontComponentInput!"
]
}
@@ -9707,7 +9715,7 @@ export default {
194,
{
"input": [
- 513,
+ 514,
"CreateApprovedAccessDomainInput!"
]
}
@@ -9716,7 +9724,7 @@ export default {
8,
{
"input": [
- 514,
+ 515,
"DeleteApprovedAccessDomainInput!"
]
}
@@ -9725,7 +9733,7 @@ export default {
194,
{
"input": [
- 515,
+ 516,
"ValidateApprovedAccessDomainInput!"
]
}
@@ -9747,7 +9755,7 @@ export default {
50,
{
"createRoleInput": [
- 516,
+ 517,
"CreateRoleInput!"
]
}
@@ -9756,7 +9764,7 @@ export default {
50,
{
"updateRoleInput": [
- 517,
+ 518,
"UpdateRoleInput!"
]
}
@@ -9774,7 +9782,7 @@ export default {
47,
{
"upsertObjectPermissionsInput": [
- 519,
+ 520,
"UpsertObjectPermissionsInput!"
]
}
@@ -9783,7 +9791,7 @@ export default {
48,
{
"upsertPermissionFlagsInput": [
- 521,
+ 522,
"UpsertPermissionFlagsInput!"
]
}
@@ -9792,7 +9800,7 @@ export default {
42,
{
"upsertFieldPermissionsInput": [
- 522,
+ 523,
"UpsertFieldPermissionsInput!"
]
}
@@ -9801,7 +9809,7 @@ export default {
285,
{
"input": [
- 524,
+ 525,
"UpsertRowLevelPermissionPredicatesInput!"
]
}
@@ -9832,7 +9840,7 @@ export default {
2,
{
"input": [
- 527,
+ 528,
"CreateApiKeyInput!"
]
}
@@ -9841,7 +9849,7 @@ export default {
2,
{
"input": [
- 528,
+ 529,
"UpdateApiKeyInput!"
]
}
@@ -9850,7 +9858,7 @@ export default {
2,
{
"input": [
- 529,
+ 530,
"RevokeApiKeyInput!"
]
}
@@ -9872,7 +9880,7 @@ export default {
57,
{
"input": [
- 530,
+ 531,
"CreateViewFilterGroupInput!"
]
}
@@ -9885,7 +9893,7 @@ export default {
"String!"
],
"input": [
- 531,
+ 532,
"UpdateViewFilterGroupInput!"
]
}
@@ -9930,7 +9938,7 @@ export default {
71,
{
"data": [
- 532,
+ 533,
"ActivateWorkspaceInput!"
]
}
@@ -9939,7 +9947,7 @@ export default {
71,
{
"data": [
- 533,
+ 534,
"UpdateWorkspaceInput!"
]
}
@@ -9948,7 +9956,7 @@ export default {
71,
{
"data": [
- 534,
+ 535,
"UpdateWorkspaceAllowedIframeOriginsInput!"
]
}
@@ -9979,7 +9987,7 @@ export default {
236,
{
"input": [
- 535,
+ 536,
"CreateApplicationRegistrationInput!"
]
}
@@ -9988,7 +9996,7 @@ export default {
78,
{
"input": [
- 536,
+ 537,
"UpdateApplicationRegistrationInput!"
]
}
@@ -10015,7 +10023,7 @@ export default {
208,
{
"input": [
- 538,
+ 539,
"UpdateApplicationRegistrationVariableInput!"
]
}
@@ -10033,7 +10041,7 @@ export default {
78,
{
"file": [
- 449,
+ 450,
"Upload!"
],
"universalIdentifier": [
@@ -10067,7 +10075,7 @@ export default {
260,
{
"input": [
- 540,
+ 541,
"GrantApplicationCapabilitiesInput!"
]
}
@@ -10100,7 +10108,7 @@ export default {
258,
{
"input": [
- 541,
+ 542,
"TriggerInstallApplicationJobInput!"
]
}
@@ -10109,7 +10117,7 @@ export default {
259,
{
"input": [
- 542,
+ 543,
"TriggerUninstallApplicationJobInput!"
]
}
@@ -10122,7 +10130,7 @@ export default {
"UUID!"
],
"input": [
- 543,
+ 544,
"UpdateApplicationInput!"
]
}
@@ -10152,7 +10160,7 @@ export default {
264,
{
"input": [
- 544,
+ 545,
"CreateOneFieldMetadataInput!"
]
}
@@ -10161,7 +10169,7 @@ export default {
264,
{
"input": [
- 546,
+ 547,
"UpdateOneFieldMetadataInput!"
]
}
@@ -10170,7 +10178,7 @@ export default {
264,
{
"input": [
- 548,
+ 549,
"DeleteOneFieldInput!"
]
}
@@ -10179,7 +10187,7 @@ export default {
61,
{
"input": [
- 549,
+ 550,
"CreateViewGroupInput!"
]
}
@@ -10188,7 +10196,7 @@ export default {
61,
{
"inputs": [
- 549,
+ 550,
"[CreateViewGroupInput!]!"
]
}
@@ -10197,7 +10205,7 @@ export default {
61,
{
"input": [
- 550,
+ 551,
"UpdateViewGroupInput!"
]
}
@@ -10206,7 +10214,7 @@ export default {
61,
{
"inputs": [
- 550,
+ 551,
"[UpdateViewGroupInput!]!"
]
}
@@ -10215,7 +10223,7 @@ export default {
61,
{
"input": [
- 552,
+ 553,
"DeleteViewGroupInput!"
]
}
@@ -10224,7 +10232,7 @@ export default {
61,
{
"input": [
- 553,
+ 554,
"DestroyViewGroupInput!"
]
}
@@ -10233,7 +10241,7 @@ export default {
345,
{
"input": [
- 554,
+ 555,
"SendMessageCampaignInput!"
]
}
@@ -10242,7 +10250,7 @@ export default {
343,
{
"input": [
- 555,
+ 556,
"CancelMessageCampaignInput!"
]
}
@@ -10251,7 +10259,7 @@ export default {
344,
{
"input": [
- 556,
+ 557,
"SendMessageCampaignTestInput!"
]
}
@@ -10269,7 +10277,7 @@ export default {
347,
{
"input": [
- 557,
+ 558,
"CreateMessageSuppressionInput!"
]
}
@@ -10287,7 +10295,7 @@ export default {
351,
{
"input": [
- 558,
+ 559,
"CreateUnsubscribeTopicInput!"
]
}
@@ -10296,7 +10304,7 @@ export default {
351,
{
"input": [
- 559,
+ 560,
"UpdateUnsubscribeTopicInput!"
]
}
@@ -10314,7 +10322,7 @@ export default {
331,
{
"input": [
- 560,
+ 561,
"UpdateMessageChannelInput!"
]
}
@@ -10323,7 +10331,7 @@ export default {
341,
{
"input": [
- 562,
+ 563,
"CreateEmailGroupChannelInput!"
]
}
@@ -10332,7 +10340,7 @@ export default {
331,
{
"input": [
- 563,
+ 564,
"UpdateEmailGroupChannelInput!"
]
}
@@ -10350,7 +10358,7 @@ export default {
331,
{
"input": [
- 564,
+ 565,
"CreateAppMessageChannelInput!"
]
}
@@ -10359,7 +10367,7 @@ export default {
331,
{
"input": [
- 565,
+ 566,
"UpdateAppMessageChannelInput!"
]
}
@@ -10377,7 +10385,7 @@ export default {
340,
{
"input": [
- 566,
+ 567,
"IngestAppMessagesInput!"
]
}
@@ -10386,7 +10394,7 @@ export default {
327,
{
"input": [
- 570,
+ 571,
"CreateEmailingDomainInput!"
]
}
@@ -10413,7 +10421,7 @@ export default {
364,
{
"input": [
- 571,
+ 572,
"RunAgentInput!"
]
}
@@ -10422,7 +10430,7 @@ export default {
362,
{
"input": [
- 575,
+ 576,
"CreateWebhookInput!"
]
}
@@ -10431,7 +10439,7 @@ export default {
362,
{
"input": [
- 576,
+ 577,
"UpdateWebhookInput!"
]
}
@@ -10446,37 +10454,37 @@ export default {
}
],
"updateMessageFolder": [
- 405,
+ 406,
{
"input": [
- 578,
+ 579,
"UpdateMessageFolderInput!"
]
}
],
"updateMessageFolders": [
- 405,
+ 406,
{
"input": [
- 580,
+ 581,
"UpdateMessageFoldersInput!"
]
}
],
"updateCalendarChannel": [
- 400,
+ 401,
{
"input": [
- 581,
+ 582,
"UpdateCalendarChannelInput!"
]
}
],
"setAppKeyValue": [
- 398,
+ 399,
{
"input": [
- 583,
+ 584,
"SetAppKeyValueInput!"
]
}
@@ -10489,24 +10497,24 @@ export default {
"String!"
],
"scope": [
- 399
+ 400
]
}
],
"enqueueJob": [
- 396,
+ 397,
{
"input": [
- 584,
+ 585,
"EnqueueJobInput!"
]
}
],
"enqueueJobs": [
- 397,
+ 398,
{
"input": [
- 585,
+ 586,
"EnqueueJobsInput!"
]
}
@@ -10515,7 +10523,7 @@ export default {
8,
{
"input": [
- 587,
+ 588,
"ReportAppConnectionAuthFailureInput!"
]
}
@@ -10545,7 +10553,7 @@ export default {
1
],
"fileAttachments": [
- 588,
+ 589,
"[FileAttachmentInput!]"
]
}
@@ -10581,7 +10589,7 @@ export default {
}
],
"startWorkspaceSetupChat": [
- 384,
+ 385,
{
"companyContext": [
9
@@ -10591,11 +10599,20 @@ export default {
]
}
],
+ "sendInboxMessage": [
+ 384,
+ {
+ "input": [
+ 590,
+ "SendInboxMessageInput!"
+ ]
+ }
+ ],
"createSkill": [
376,
{
"input": [
- 589,
+ 591,
"CreateSkillInput!"
]
}
@@ -10604,7 +10621,7 @@ export default {
376,
{
"input": [
- 590,
+ 592,
"UpdateSkillInput!"
]
}
@@ -10637,7 +10654,7 @@ export default {
}
],
"evaluateAgentTurn": [
- 393,
+ 394,
{
"turnId": [
3,
@@ -10646,7 +10663,7 @@ export default {
}
],
"runEvaluationInput": [
- 394,
+ 395,
{
"agentId": [
3,
@@ -10659,25 +10676,25 @@ export default {
}
],
"createValidationRule": [
- 412,
+ 413,
{
"input": [
- 591,
+ 593,
"CreateValidationRuleInput!"
]
}
],
"updateValidationRule": [
- 412,
+ 413,
{
"input": [
- 592,
+ 594,
"UpdateValidationRuleInput!"
]
}
],
"deleteValidationRule": [
- 412,
+ 413,
{
"id": [
3,
@@ -10686,16 +10703,16 @@ export default {
}
],
"updateTimelineActivityType": [
- 411,
+ 412,
{
"input": [
- 594,
+ 596,
"UpdateTimelineActivityTypeInput!"
]
}
],
"resetTimelineActivityType": [
- 411,
+ 412,
{
"id": [
3,
@@ -10707,7 +10724,7 @@ export default {
294,
{
"input": [
- 595,
+ 597,
"GetAuthorizationUrlForSSOInput!"
]
}
@@ -10873,7 +10890,7 @@ export default {
297,
{
"input": [
- 596
+ 598
]
}
],
@@ -10885,7 +10902,7 @@ export default {
"String!"
],
"file": [
- 449,
+ 450,
"Upload!"
]
}
@@ -11081,7 +11098,7 @@ export default {
8,
{
"input": [
- 597,
+ 599,
"UpdateWorkspaceMemberSettingsInput!"
]
}
@@ -11115,7 +11132,7 @@ export default {
245,
{
"input": [
- 598,
+ 600,
"SetupOIDCSsoInput!"
]
}
@@ -11124,7 +11141,7 @@ export default {
245,
{
"input": [
- 599,
+ 601,
"SetupSAMLSsoInput!"
]
}
@@ -11133,7 +11150,7 @@ export default {
241,
{
"input": [
- 600,
+ 602,
"DeleteSsoInput!"
]
}
@@ -11142,13 +11159,13 @@ export default {
242,
{
"input": [
- 601,
+ 603,
"EditSsoInput!"
]
}
],
"createObjectEvent": [
- 387,
+ 388,
{
"event": [
1,
@@ -11168,10 +11185,10 @@ export default {
}
],
"trackAnalytics": [
- 387,
+ 388,
{
"type": [
- 602,
+ 604,
"AnalyticsType!"
],
"name": [
@@ -11214,16 +11231,16 @@ export default {
366,
{
"input": [
- 603,
+ 605,
"CreateCalendarEventInput!"
]
}
],
"sendEmail": [
- 386,
+ 387,
{
"input": [
- 604,
+ 606,
"SendEmailInput!"
]
}
@@ -11245,7 +11262,7 @@ export default {
"String!"
],
"connectionParameters": [
- 606,
+ 608,
"EmailAccountConnectionParameters!"
],
"id": [
@@ -11257,7 +11274,7 @@ export default {
205,
{
"input": [
- 608,
+ 610,
"UpdateLabPublicFeatureFlagInput!"
]
}
@@ -11325,7 +11342,7 @@ export default {
316,
{
"file": [
- 449,
+ 450,
"Upload!"
],
"applicationUniversalIdentifier": [
@@ -11350,7 +11367,7 @@ export default {
"String!"
],
"files": [
- 609,
+ 611,
"[ApplicationFileUploadRequestInput!]!"
]
}
@@ -11478,7 +11495,7 @@ export default {
3
],
"update": [
- 448
+ 449
],
"__typename": [
1
@@ -11551,7 +11568,7 @@ export default {
3
],
"payload": [
- 450
+ 451
],
"__typename": [
1
@@ -11685,7 +11702,7 @@ export default {
8
],
"tabs": [
- 459
+ 460
],
"__typename": [
1
@@ -11708,7 +11725,7 @@ export default {
104
],
"widgets": [
- 460
+ 461
],
"__typename": [
1
@@ -11875,19 +11892,19 @@ export default {
3
],
"view": [
- 464
+ 465
],
"viewFields": [
- 465
+ 466
],
"viewFilters": [
- 466
+ 467
],
"viewFilterGroups": [
- 467
+ 468
],
"viewSorts": [
- 468
+ 469
],
"__typename": [
1
@@ -12036,7 +12053,7 @@ export default {
3
],
"update": [
- 471
+ 472
],
"__typename": [
1
@@ -12106,7 +12123,7 @@ export default {
3
],
"update": [
- 476
+ 477
],
"__typename": [
1
@@ -12159,7 +12176,7 @@ export default {
3
],
"update": [
- 480
+ 481
],
"__typename": [
1
@@ -12235,7 +12252,7 @@ export default {
3
],
"update": [
- 485
+ 486
],
"__typename": [
1
@@ -12299,10 +12316,10 @@ export default {
3
],
"groups": [
- 490
+ 491
],
"fields": [
- 491
+ 492
],
"__typename": [
1
@@ -12322,7 +12339,7 @@ export default {
8
],
"fields": [
- 491
+ 492
],
"__typename": [
1
@@ -12420,7 +12437,7 @@ export default {
},
"CreateOneObjectInput": {
"object": [
- 495
+ 496
],
"__typename": [
1
@@ -12480,7 +12497,7 @@ export default {
},
"UpdateOneObjectInput": {
"update": [
- 498
+ 499
],
"id": [
3
@@ -12536,7 +12553,7 @@ export default {
27
],
"translations": [
- 499
+ 500
],
"__typename": [
1
@@ -12558,7 +12575,7 @@ export default {
},
"CreateOneIndexInput": {
"index": [
- 501
+ 502
],
"__typename": [
1
@@ -12569,7 +12586,7 @@ export default {
3
],
"fields": [
- 502
+ 503
],
"indexType": [
273
@@ -12654,7 +12671,7 @@ export default {
3
],
"update": [
- 507
+ 508
],
"__typename": [
1
@@ -12823,7 +12840,7 @@ export default {
3
],
"update": [
- 512
+ 513
],
"__typename": [
1
@@ -12916,7 +12933,7 @@ export default {
},
"UpdateRoleInput": {
"update": [
- 518
+ 519
],
"id": [
3
@@ -12971,7 +12988,7 @@ export default {
3
],
"objectPermissions": [
- 520
+ 521
],
"__typename": [
1
@@ -13013,7 +13030,7 @@ export default {
3
],
"fieldPermissions": [
- 523
+ 524
],
"__typename": [
1
@@ -13044,10 +13061,10 @@ export default {
3
],
"predicates": [
- 525
+ 526
],
"predicateGroups": [
- 526
+ 527
],
"__typename": [
1
@@ -13314,7 +13331,7 @@ export default {
1
],
"update": [
- 537
+ 538
],
"__typename": [
1
@@ -13339,7 +13356,7 @@ export default {
1
],
"update": [
- 539
+ 540
],
"__typename": [
1
@@ -13396,7 +13413,7 @@ export default {
},
"CreateOneFieldMetadataInput": {
"field": [
- 545
+ 546
],
"__typename": [
1
@@ -13475,7 +13492,7 @@ export default {
3
],
"update": [
- 547
+ 548
],
"__typename": [
1
@@ -13540,7 +13557,7 @@ export default {
9
],
"translations": [
- 499
+ 500
],
"__typename": [
1
@@ -13579,7 +13596,7 @@ export default {
3
],
"update": [
- 551
+ 552
],
"__typename": [
1
@@ -13704,7 +13721,7 @@ export default {
3
],
"update": [
- 561
+ 562
],
"__typename": [
1
@@ -13797,7 +13814,7 @@ export default {
3
],
"messages": [
- 567
+ 568
],
"__typename": [
1
@@ -13820,7 +13837,7 @@ export default {
4
],
"participants": [
- 568
+ 569
],
"__typename": [
1
@@ -13828,7 +13845,7 @@ export default {
},
"AppMessageParticipantInput": {
"role": [
- 569
+ 570
],
"handle": [
1
@@ -13866,7 +13883,7 @@ export default {
3
],
"messages": [
- 572
+ 573
],
"__typename": [
1
@@ -13874,13 +13891,13 @@ export default {
},
"RunAgentMessageInput": {
"role": [
- 573
+ 574
],
"content": [
1
],
"attachments": [
- 574
+ 575
],
"__typename": [
1
@@ -13923,7 +13940,7 @@ export default {
3
],
"update": [
- 577
+ 578
],
"__typename": [
1
@@ -13951,7 +13968,7 @@ export default {
3
],
"update": [
- 579
+ 580
],
"__typename": [
1
@@ -13970,7 +13987,7 @@ export default {
3
],
"update": [
- 579
+ 580
],
"__typename": [
1
@@ -13981,7 +13998,7 @@ export default {
3
],
"update": [
- 582
+ 583
],
"__typename": [
1
@@ -13989,13 +14006,13 @@ export default {
},
"UpdateCalendarChannelInputUpdates": {
"visibility": [
- 403
+ 404
],
"isContactAutoCreationEnabled": [
8
],
"contactAutoCreationPolicy": [
- 404
+ 405
],
"isSyncEnabled": [
8
@@ -14012,7 +14029,7 @@ export default {
9
],
"scope": [
- 399
+ 400
],
"__typename": [
1
@@ -14046,7 +14063,7 @@ export default {
9
],
"jobs": [
- 586
+ 587
],
"retryLimit": [
30
@@ -14091,6 +14108,29 @@ export default {
1
]
},
+ "SendInboxMessageInput": {
+ "workspaceMemberId": [
+ 3
+ ],
+ "threadKey": [
+ 1
+ ],
+ "idempotencyKey": [
+ 1
+ ],
+ "title": [
+ 1
+ ],
+ "text": [
+ 1
+ ],
+ "toolCall": [
+ 9
+ ],
+ "__typename": [
+ 1
+ ]
+ },
"CreateSkillInput": {
"id": [
3
@@ -14174,7 +14214,7 @@ export default {
3
],
"update": [
- 593
+ 595
],
"__typename": [
1
@@ -14220,7 +14260,7 @@ export default {
8
],
"translations": [
- 499
+ 500
],
"__typename": [
1
@@ -14386,7 +14426,7 @@ export default {
1
],
"files": [
- 605
+ 607
],
"__typename": [
1
@@ -14408,13 +14448,13 @@ export default {
1
],
"IMAP": [
- 607
+ 609
],
"SMTP": [
- 607
+ 609
],
"CALDAV": [
- 607
+ 609
],
"__typename": [
1
@@ -14479,7 +14519,7 @@ export default {
286,
{
"input": [
- 611,
+ 613,
"LogicFunctionLogsInput!"
]
}
@@ -14494,23 +14534,23 @@ export default {
}
],
"eventLogsLive": [
- 388,
+ 389,
{
"table": [
- 434,
+ 435,
"EventLogTable!"
],
"fieldFilters": [
- 437,
+ 438,
"[EventLogFieldFilterInput!]"
]
}
],
"exportRecords": [
- 391,
+ 392,
{
"input": [
- 612,
+ 614,
"CreateRecordExportInput!"
]
}
diff --git a/packages/twenty-docs/developers/extend/apps/logic/credits.mdx b/packages/twenty-docs/developers/extend/apps/logic/credits.mdx
index 11fe2bf958c..4bb954ed2e9 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/credits.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/credits.mdx
@@ -126,7 +126,7 @@ Notes:
## Checking before you spend
-A workspace can run out of credits. When that happens your function is refused before your code starts, and the platform's own work stops too: `runAgent` returns an error instead of running, and the other AI entry points refuse outright. Uninstall and disconnect hooks are the exception and always run, so an app can still be removed cleanly. An execution that does get through can still fail late, on a platform call it did not write, if the workspace runs out mid-run.
+A workspace can run out of credits. When that happens your function is refused before your code starts, and the platform's own work stops too: `runAgent` returns an error instead of running, and the other AI entry points refuse outright. `sendInboxMessage` runs no model and adds no AI charge of its own, though the function calling it is refused like any other; the member's reply is charged like any chat turn. Uninstall and disconnect hooks are the exception and always run, so an app can still be removed cleanly. An execution that does get through can still fail late, on a platform call it did not write, if the workspace runs out mid-run.
Ask first:
diff --git a/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx b/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
index 7172f473a80..4bc079bd8cb 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/logic-functions.mdx
@@ -584,7 +584,7 @@ const asApplication = new RestApiClient({ runAs: 'application' });
Check `context.workspaceMemberId` when a function behaves differently depending on whether someone is behind it, for instance to attribute a record.
</Note>
-The SDK helpers that reach your application's own resources always use its access and ignore `runAs`: the [key-value store](/developers/extend/apps/logic/key-value-store), [connections](/developers/extend/apps/logic/connections), [messaging channels](/developers/extend/apps/logic/messaging-channels), `runAgent`, `getPublicAssetUrl` and [credit charging](/developers/extend/apps/logic/credits).
+The SDK helpers that reach your application's own resources always use its access and ignore `runAs`: the [key-value store](/developers/extend/apps/logic/key-value-store), [connections](/developers/extend/apps/logic/connections), [messaging channels](/developers/extend/apps/logic/messaging-channels), `runAgent`, `getPublicAssetUrl` and [credit charging](/developers/extend/apps/logic/credits). `sendInboxMessage` also uses your application's access and ignores `runAs`, though it writes to the chats of the member you name.
#### Exposing a function as an AI tool or workflow action
diff --git a/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx b/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx
index a4281a31422..e4af30471d1 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/skills-and-agents.mdx
@@ -237,5 +237,58 @@ name a member at all.
for.
</Warning>
+</Accordion>
+<Accordion title="sendInboxMessage" description="Start or continue a conversation in a member's chats">
+
+`sendInboxMessage()` posts a message from your app in a workspace member's
+chats. It can end on a tool call the member answers from the chat, after which
+the conversation continues with Twenty's assistant.
+
+```ts src/logic-functions/notify-first-recording.ts
+import { sendInboxMessage } from 'twenty-sdk/logic-function';
+
+const { threadId } = await sendInboxMessage({
+ workspaceMemberId,
+ threadKey: 'first-call-recording',
+ idempotencyKey: 'first-call-recording',
+ title: 'Your first call recording is ready',
+ text: 'Your first call was recorded: **Weekly sync**.',
+ toolCall: {
+ toolName: 'ask_questions',
+ input: {
+ questions: [
+ {
+ header: 'Share',
+ question: 'Do you want to share it with the other attendees?',
+ options: [{ label: 'Draft a recap email' }, { label: 'Not now' }],
+ },
+ ],
+ },
+ },
+});
+```
+
+Key points:
+- `threadKey` picks the conversation for this app and member. A new key starts
+ a conversation titled `title`; a key you used before adds the message to that
+ conversation.
+- `idempotencyKey` identifies the message within the conversation. Sending
+ again with the same keys writes nothing new, so retries and concurrent runs
+ never duplicate a message.
+- `toolCall` (optional) ends the message on one of:
+ - a call the member answers, which pauses the conversation: `ask_questions`
+ (1 to 4 multiple-choice questions), `request_form` (fields to fill in) or
+ `propose_email` (an email to review, then send, save or discard);
+ - one of your app's own tools, by `logicFunctionUniversalIdentifier`, rendered
+ by its front component with the `input` and `output` you pass. It does not
+ pause the conversation.
+- Only one call the member answers can wait in a conversation at a time:
+ sending another before they answer fails with `THREAD_AWAITING_ANSWER`. Plain
+ messages and app tool calls are still accepted.
+- A conversation the member deleted is not recreated, and nothing is added to it.
+- The member must have the `AI` permission, and your app's
+ [default role](/developers/extend/apps/config/roles) must grant
+ `SystemPermissionFlag.AI`.
+
</Accordion>
</AccordionGroup>
diff --git a/packages/twenty-front/src/generated-admin/graphql.ts b/packages/twenty-front/src/generated-admin/graphql.ts
index 9a039ea5164..1b5a822fb43 100644
--- a/packages/twenty-front/src/generated-admin/graphql.ts
+++ b/packages/twenty-front/src/generated-admin/graphql.ts
@@ -492,7 +492,8 @@ export enum FeatureFlagKey {
IS_REST_METADATA_API_NEW_FORMAT_DIRECT = 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT',
IS_VALIDATION_RULES_ENABLED = 'IS_VALIDATION_RULES_ENABLED',
IS_WEBHOOK_RATE_LIMIT_ENABLED = 'IS_WEBHOOK_RATE_LIMIT_ENABLED',
- IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED = 'IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED'
+ IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED = 'IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED',
+ IS_WORKFLOW_SEND_CHAT_MESSAGE_ENABLED = 'IS_WORKFLOW_SEND_CHAT_MESSAGE_ENABLED'
}
export type FindApplicationRegistrationInstalledWorkspacesInput = {
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index 38eba66fc3c..d7b1ecbf8c7 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -2147,7 +2147,8 @@ export enum FeatureFlagKey {
IS_REST_METADATA_API_NEW_FORMAT_DIRECT = 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT',
IS_VALIDATION_RULES_ENABLED = 'IS_VALIDATION_RULES_ENABLED',
IS_WEBHOOK_RATE_LIMIT_ENABLED = 'IS_WEBHOOK_RATE_LIMIT_ENABLED',
- IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED = 'IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED'
+ IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED = 'IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED',
+ IS_WORKFLOW_SEND_CHAT_MESSAGE_ENABLED = 'IS_WORKFLOW_SEND_CHAT_MESSAGE_ENABLED'
}
export type Field = {
@@ -3225,6 +3226,7 @@ export type Mutation = {
saveImapSmtpCaldavAccount: ImapSmtpCaldavConnectionSuccess;
sendChatMessage: SendChatMessageResult;
sendEmail: SendEmailOutput;
+ sendInboxMessage: SendInboxMessageResult;
sendInvitations: SendInvitations;
sendMessageCampaign: SendMessageCampaignOutputDto;
sendMessageCampaignTest: SendEmailViaDomainOutput;
@@ -4151,6 +4153,11 @@ export type MutationSendEmailArgs = {
};
+export type MutationSendInboxMessageArgs = {
+ input: SendInboxMessageInput;
+};
+
+
export type MutationSendInvitationsArgs = {
emails: Array<Scalars['String']['input']>;
roleId?: InputMaybe<Scalars['UUID']['input']>;
@@ -6142,6 +6149,20 @@ export type SendEmailViaDomainOutput = {
messageId: Scalars['String']['output'];
};
+export type SendInboxMessageInput = {
+ idempotencyKey: Scalars['String']['input'];
+ text: Scalars['String']['input'];
+ threadKey: Scalars['String']['input'];
+ title: Scalars['String']['input'];
+ toolCall?: InputMaybe<Scalars['JSON']['input']>;
+ workspaceMemberId: Scalars['UUID']['input'];
+};
+
+export type SendInboxMessageResult = {
+ __typename?: 'SendInboxMessageResult';
+ threadId: Scalars['UUID']['output'];
+};
+
export type SendInvitations = {
__typename?: 'SendInvitations';
errors: Array<Scalars['String']['output']>;
diff --git a/packages/twenty-front/src/generated/graphql.ts b/packages/twenty-front/src/generated/graphql.ts
index 44f6b1978a6..54bbe1fd603 100644
--- a/packages/twenty-front/src/generated/graphql.ts
+++ b/packages/twenty-front/src/generated/graphql.ts
@@ -1093,6 +1093,7 @@ export enum WorkflowActionType {
ITERATOR = 'ITERATOR',
LOGIC_FUNCTION = 'LOGIC_FUNCTION',
PICK_RECORD = 'PICK_RECORD',
+ SEND_CHAT_MESSAGE = 'SEND_CHAT_MESSAGE',
SEND_EMAIL = 'SEND_EMAIL',
UPDATE_RECORD = 'UPDATE_RECORD',
UPSERT_RECORD = 'UPSERT_RECORD'
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts b/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts
index 5d76d942453..fba2f045b58 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts
+++ b/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts
@@ -78,4 +78,8 @@ export const SETTINGS_ADMIN_FEATURE_FLAG_METADATA: Partial<
label: msg`Validation rules`,
description: msg`Let admins add conditions a record must meet to be saved, checked on every write.`,
},
+ [FeatureFlagKey.IS_WORKFLOW_SEND_CHAT_MESSAGE_ENABLED]: {
+ label: msg`Workflow chat messages`,
+ description: msg`Add a workflow step that posts a message in a member's AI chat.`,
+ },
};
diff --git a/packages/twenty-front/src/modules/side-panel/pages/workflow/action/components/SidePanelWorkflowSelectAction.tsx b/packages/twenty-front/src/modules/side-panel/pages/workflow/action/components/SidePanelWorkflowSelectAction.tsx
index b5e67e4441f..2f255887dad 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/workflow/action/components/SidePanelWorkflowSelectAction.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/workflow/action/components/SidePanelWorkflowSelectAction.tsx
@@ -5,6 +5,7 @@ import { logicFunctionsSelector } from '@/logic-functions/states/logicFunctionsS
import { ToolMenuItem } from '@/side-panel/pages/workflow/action/components/ToolMenuItem';
import { WorkflowActionMenuItems } from '@/side-panel/pages/workflow/action/components/WorkflowActionMenuItems';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
+import { useWorkspaceFeatureFlagsMap } from '@/workspace/hooks/useWorkspaceFeatureFlagsMap';
import { type WorkflowActionType } from '@/workflow/types/Workflow';
import { JEV_MODEL_ID } from 'twenty-shared/ai';
import { SidePanelStepListContainer } from '@/workflow/workflow-steps/components/SidePanelWorkflowSelectStepContainer';
@@ -16,6 +17,7 @@ import { HUMAN_INPUT_ACTIONS } from '@/workflow/workflow-steps/workflow-actions/
import { RECORD_ACTIONS } from '@/workflow/workflow-steps/workflow-actions/constants/RecordActions';
import { useLingui } from '@lingui/react/macro';
import { isDefined } from 'twenty-shared/utils';
+import { WORKFLOW_ACTION_FEATURE_FLAGS } from 'twenty-shared/workflow';
export type WorkflowActionSelection = {
type: WorkflowActionType;
@@ -44,6 +46,14 @@ export const SidePanelWorkflowSelectAction = ({
: action,
);
+ const featureFlagsMap = useWorkspaceFeatureFlagsMap();
+
+ const isActionEnabled = ({ type }: { type: WorkflowActionType }) => {
+ const featureFlag = WORKFLOW_ACTION_FEATURE_FLAGS[type];
+
+ return !isDefined(featureFlag) || featureFlagsMap[featureFlag] === true;
+ };
+
const logicFunctions = useAtomStateValue(logicFunctionsSelector);
const currentWorkspace = useAtomStateValue(currentWorkspaceState);
@@ -73,7 +83,7 @@ export const SidePanelWorkflowSelectAction = ({
{t`Data`}
</SidePanelWorkflowSelectStepTitle>
<WorkflowActionMenuItems
- actions={RECORD_ACTIONS}
+ actions={RECORD_ACTIONS.filter(isActionEnabled)}
onClick={handleActionClick}
/>
@@ -81,7 +91,7 @@ export const SidePanelWorkflowSelectAction = ({
{t`AI`}
</SidePanelWorkflowSelectStepTitle>
<WorkflowActionMenuItems
- actions={aiActions}
+ actions={aiActions.filter(isActionEnabled)}
onClick={handleActionClick}
/>
@@ -89,7 +99,7 @@ export const SidePanelWorkflowSelectAction = ({
{t`Flow`}
</SidePanelWorkflowSelectStepTitle>
<WorkflowActionMenuItems
- actions={FLOW_ACTIONS}
+ actions={FLOW_ACTIONS.filter(isActionEnabled)}
onClick={handleActionClick}
/>
@@ -97,7 +107,7 @@ export const SidePanelWorkflowSelectAction = ({
{t`Core`}
</SidePanelWorkflowSelectStepTitle>
<WorkflowActionMenuItems
- actions={CORE_ACTIONS}
+ actions={CORE_ACTIONS.filter(isActionEnabled)}
onClick={handleActionClick}
/>
@@ -105,7 +115,7 @@ export const SidePanelWorkflowSelectAction = ({
{t`Human Input`}
</SidePanelWorkflowSelectStepTitle>
<WorkflowActionMenuItems
- actions={HUMAN_INPUT_ACTIONS}
+ actions={HUMAN_INPUT_ACTIONS.filter(isActionEnabled)}
onClick={handleActionClick}
/>
diff --git a/packages/twenty-front/src/modules/workflow/types/Workflow.ts b/packages/twenty-front/src/modules/workflow/types/Workflow.ts
index 272de9d0cba..46107692eaa 100644
--- a/packages/twenty-front/src/modules/workflow/types/Workflow.ts
+++ b/packages/twenty-front/src/modules/workflow/types/Workflow.ts
@@ -26,6 +26,7 @@ import {
type workflowRunStateSchema,
type workflowRunStatusSchema,
type workflowRunStepStatusSchema,
+ type workflowSendChatMessageActionSchema,
type workflowSendEmailActionSchema,
type workflowTriggerSchema,
type workflowUpdateRecordActionSchema,
@@ -44,6 +45,9 @@ export type WorkflowSendEmailAction = z.infer<
export type WorkflowDraftEmailAction = z.infer<
typeof workflowDraftEmailActionSchema
>;
+export type WorkflowSendChatMessageAction = z.infer<
+ typeof workflowSendChatMessageActionSchema
+>;
export type WorkflowCreateCalendarEventAction = z.infer<
typeof workflowCreateCalendarEventActionSchema
>;
@@ -86,6 +90,7 @@ export type WorkflowAction =
| WorkflowLogicFunctionAction
| WorkflowSendEmailAction
| WorkflowDraftEmailAction
+ | WorkflowSendChatMessageAction
| WorkflowCreateCalendarEventAction
| WorkflowCreateRecordAction
| WorkflowUpdateRecordAction
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/components/WorkflowRunStepNodeDetail.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/components/WorkflowRunStepNodeDetail.tsx
index 8728e2540fd..0a524855449 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/components/WorkflowRunStepNodeDetail.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/components/WorkflowRunStepNodeDetail.tsx
@@ -8,6 +8,7 @@ import { WorkflowEditActionAiAgent } from '@/workflow/workflow-steps/workflow-ac
import { WorkflowEditActionClassify } from '@/workflow/workflow-steps/workflow-actions/classify-action/components/WorkflowEditActionClassify';
import { WorkflowActionCode } from '@/workflow/workflow-steps/workflow-actions/code-action/components/WorkflowActionCode';
import { WorkflowEditActionCreateCalendarEvent } from '@/workflow/workflow-steps/workflow-actions/components/WorkflowEditActionCreateCalendarEvent';
+import { WorkflowEditActionSendChatMessage } from '@/workflow/workflow-steps/workflow-actions/send-chat-message-action/components/WorkflowEditActionSendChatMessage';
import { WorkflowEditActionCreateRecord } from '@/workflow/workflow-steps/workflow-actions/components/WorkflowEditActionCreateRecord';
import { WorkflowEditActionDeleteRecord } from '@/workflow/workflow-steps/workflow-actions/components/WorkflowEditActionDeleteRecord';
import { WorkflowEditActionEmpty } from '@/workflow/workflow-steps/workflow-actions/components/WorkflowEditActionEmpty';
@@ -142,6 +143,17 @@ export const WorkflowRunStepNodeDetail = ({
/>
);
}
+ case 'SEND_CHAT_MESSAGE': {
+ return (
+ <WorkflowEditActionSendChatMessage
+ key={stepId}
+ action={stepDefinition.definition}
+ actionOptions={{
+ readonly: true,
+ }}
+ />
+ );
+ }
case 'CREATE_CALENDAR_EVENT': {
return (
<WorkflowEditActionCreateCalendarEvent
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/components/WorkflowStepDetail.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/components/WorkflowStepDetail.tsx
index b449d7ea34c..5df68c17d7f 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/components/WorkflowStepDetail.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/components/WorkflowStepDetail.tsx
@@ -7,6 +7,7 @@ import { WorkflowEditActionAiAgent } from '@/workflow/workflow-steps/workflow-ac
import { WorkflowEditActionClassify } from '@/workflow/workflow-steps/workflow-actions/classify-action/components/WorkflowEditActionClassify';
import { WorkflowActionCode } from '@/workflow/workflow-steps/workflow-actions/code-action/components/WorkflowActionCode';
import { WorkflowEditActionCreateCalendarEvent } from '@/workflow/workflow-steps/workflow-actions/components/WorkflowEditActionCreateCalendarEvent';
+import { WorkflowEditActionSendChatMessage } from '@/workflow/workflow-steps/workflow-actions/send-chat-message-action/components/WorkflowEditActionSendChatMessage';
import { WorkflowEditActionCreateRecord } from '@/workflow/workflow-steps/workflow-actions/components/WorkflowEditActionCreateRecord';
import { WorkflowEditActionDeleteRecord } from '@/workflow/workflow-steps/workflow-actions/components/WorkflowEditActionDeleteRecord';
import { WorkflowEditActionEmpty } from '@/workflow/workflow-steps/workflow-actions/components/WorkflowEditActionEmpty';
@@ -138,6 +139,15 @@ export const WorkflowStepDetail = ({
/>
);
}
+ case 'SEND_CHAT_MESSAGE': {
+ return (
+ <WorkflowEditActionSendChatMessage
+ key={stepId}
+ action={stepDefinition.definition}
+ actionOptions={props}
+ />
+ );
+ }
case 'CREATE_CALENDAR_EVENT': {
return (
<WorkflowEditActionCreateCalendarEvent
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/constants/HumanInputActions.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/constants/HumanInputActions.ts
index 78cc038f0fc..9a6375a2feb 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/constants/HumanInputActions.ts
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/constants/HumanInputActions.ts
@@ -1,8 +1,9 @@
import { type WorkflowActionType } from '@/workflow/types/Workflow';
import { FORM_ACTION } from '@/workflow/workflow-steps/workflow-actions/constants/actions/FormAction';
+import { SEND_CHAT_MESSAGE_ACTION } from '@/workflow/workflow-steps/workflow-actions/constants/actions/SendChatMessageAction';
export const HUMAN_INPUT_ACTIONS: Array<{
defaultLabel: string;
- type: Extract<WorkflowActionType, 'FORM'>;
+ type: Extract<WorkflowActionType, 'FORM' | 'SEND_CHAT_MESSAGE'>;
icon: string;
-}> = [FORM_ACTION];
+}> = [FORM_ACTION, SEND_CHAT_MESSAGE_ACTION];
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/constants/actions/SendChatMessageAction.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/constants/actions/SendChatMessageAction.ts
new file mode 100644
index 00000000000..b474938f9e5
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/constants/actions/SendChatMessageAction.ts
@@ -0,0 +1,11 @@
+import { type WorkflowActionType } from '@/workflow/types/Workflow';
+
+export const SEND_CHAT_MESSAGE_ACTION: {
+ defaultLabel: string;
+ type: Extract<WorkflowActionType, 'SEND_CHAT_MESSAGE'>;
+ icon: string;
+} = {
+ defaultLabel: 'Send Chat Message',
+ type: 'SEND_CHAT_MESSAGE',
+ icon: 'IconMessage',
+};
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/send-chat-message-action/components/WorkflowEditActionSendChatMessage.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/send-chat-message-action/components/WorkflowEditActionSendChatMessage.tsx
new file mode 100644
index 00000000000..14938174885
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/send-chat-message-action/components/WorkflowEditActionSendChatMessage.tsx
@@ -0,0 +1,103 @@
+import { FormSingleRecordPicker } from '@/object-record/record-field/ui/form-types/components/FormSingleRecordPicker';
+import { FormTextFieldInput } from '@/object-record/record-field/ui/form-types/components/FormTextFieldInput';
+import { type WorkflowSendChatMessageAction } from '@/workflow/types/Workflow';
+import { WorkflowStepBody } from '@/workflow/workflow-steps/components/WorkflowStepBody';
+import { WorkflowStepFooter } from '@/workflow/workflow-steps/components/WorkflowStepFooter';
+import { WorkflowVariablePicker } from '@/workflow/workflow-variables/components/WorkflowVariablePicker';
+import { t } from '@lingui/core/macro';
+import { useEffect, useState } from 'react';
+import { CoreObjectNameSingular } from 'twenty-shared/types';
+import { useDebouncedCallback } from 'use-debounce';
+
+type SendChatMessageFormData =
+ WorkflowSendChatMessageAction['settings']['input'];
+
+type WorkflowEditActionSendChatMessageProps = {
+ action: WorkflowSendChatMessageAction;
+ actionOptions:
+ | {
+ readonly: true;
+ }
+ | {
+ readonly?: false;
+ onActionUpdate: (action: WorkflowSendChatMessageAction) => void;
+ };
+};
+
+export const WorkflowEditActionSendChatMessage = ({
+ action,
+ actionOptions,
+}: WorkflowEditActionSendChatMessageProps) => {
+ const [formData, setFormData] = useState<SendChatMessageFormData>(
+ action.settings.input,
+ );
+
+ const saveAction = useDebouncedCallback(
+ (nextFormData: SendChatMessageFormData) => {
+ if (actionOptions.readonly === true) {
+ return;
+ }
+
+ actionOptions.onActionUpdate({
+ ...action,
+ settings: {
+ ...action.settings,
+ input: nextFormData,
+ },
+ });
+ },
+ 1_000,
+ );
+
+ useEffect(() => {
+ return () => {
+ saveAction.flush();
+ };
+ }, [saveAction]);
+
+ const handleFieldChange = (
+ fieldName: keyof SendChatMessageFormData,
+ value: string,
+ ) => {
+ const nextFormData = { ...formData, [fieldName]: value };
+
+ setFormData(nextFormData);
+ saveAction(nextFormData);
+ };
+
+ return (
+ <>
+ <WorkflowStepBody>
+ <FormSingleRecordPicker
+ label={t`Recipient`}
+ objectNameSingulars={[CoreObjectNameSingular.WorkspaceMember]}
+ defaultValue={formData.workspaceMemberId}
+ onChange={(workspaceMemberId) =>
+ handleFieldChange('workspaceMemberId', workspaceMemberId ?? '')
+ }
+ disabled={actionOptions.readonly}
+ testId="workflow-edit-action-send-chat-message-recipient"
+ VariablePicker={WorkflowVariablePicker}
+ />
+ <FormTextFieldInput
+ label={t`Conversation title`}
+ placeholder={t`Defaults to the step name`}
+ readonly={actionOptions.readonly}
+ defaultValue={formData.title}
+ onChange={(value) => handleFieldChange('title', value)}
+ VariablePicker={WorkflowVariablePicker}
+ />
+ <FormTextFieldInput
+ label={t`Message`}
+ placeholder={t`Enter the message to post`}
+ multiline
+ readonly={actionOptions.readonly}
+ defaultValue={formData.text}
+ onChange={(value) => handleFieldChange('text', value)}
+ VariablePicker={WorkflowVariablePicker}
+ />
+ </WorkflowStepBody>
+ {!actionOptions.readonly && <WorkflowStepFooter stepId={action.id} />}
+ </>
+ );
+};
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/__tests__/getActionHeaderTypeOrThrow.test.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/__tests__/getActionHeaderTypeOrThrow.test.ts
index c3cf63c24d5..43dedcfb897 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/__tests__/getActionHeaderTypeOrThrow.test.ts
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/__tests__/getActionHeaderTypeOrThrow.test.ts
@@ -20,6 +20,9 @@ describe('getActionHeaderTypeOrThrow', () => {
it('should return "Human Input" for FORM action type', () => {
expect(getActionHeaderTypeOrThrow('FORM').message).toBe('Human Input');
+ expect(getActionHeaderTypeOrThrow('SEND_CHAT_MESSAGE').message).toBe(
+ 'Human Input',
+ );
});
it('should return "Core" for SEND_EMAIL action type', () => {
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/__tests__/getActionIconColorOrThrow.test.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/__tests__/getActionIconColorOrThrow.test.ts
index 988ab804f48..50d2c957e41 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/__tests__/getActionIconColorOrThrow.test.ts
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/__tests__/getActionIconColorOrThrow.test.ts
@@ -35,11 +35,14 @@ describe('getActionIconColorOrThrow', () => {
});
});
- it('returns orange9 for FORM', () => {
- expect(getActionIconColorOrThrow('FORM')).toBe(
- themeCssVariables.color.orange9,
- );
- });
+ it.each(['FORM', 'SEND_CHAT_MESSAGE'] as const)(
+ 'returns orange9 for %s',
+ (type) => {
+ expect(getActionIconColorOrThrow(type)).toBe(
+ themeCssVariables.color.orange9,
+ );
+ },
+ );
it('returns green9 for ITERATOR, EMPTY, FILTER, IF_ELSE, DELAY', () => {
const greenActions: WorkflowActionType[] = [
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/__tests__/getActionIconStrokeOrThrow.test.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/__tests__/getActionIconStrokeOrThrow.test.ts
index e5e6aa08fef..cf0a3fcd2ba 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/__tests__/getActionIconStrokeOrThrow.test.ts
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/__tests__/getActionIconStrokeOrThrow.test.ts
@@ -21,6 +21,7 @@ describe('getActionIconStrokeOrThrow', () => {
it.each([
'FORM',
+ 'SEND_CHAT_MESSAGE',
'ITERATOR',
'EMPTY',
'FILTER',
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/getActionIcon.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/getActionIcon.ts
index 5c2692f01ee..eeb1bb6a88a 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/getActionIcon.ts
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/getActionIcon.ts
@@ -26,6 +26,7 @@ export const getActionIcon = (actionType: WorkflowActionType) => {
case 'LOGIC_FUNCTION':
return 'IconFunction';
case 'FORM':
+ case 'SEND_CHAT_MESSAGE':
return HUMAN_INPUT_ACTIONS.find((item) => item.type === actionType)?.icon;
case 'ITERATOR':
case 'DELAY':
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/getActionIconColorOrThrow.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/getActionIconColorOrThrow.ts
index 94cb3ae0f6e..fd570a5a6e5 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/getActionIconColorOrThrow.ts
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/getActionIconColorOrThrow.ts
@@ -21,6 +21,7 @@ export const getActionIconColorOrThrow = (
case 'PICK_RECORD':
return themeCssVariables.color.gray9;
case 'FORM':
+ case 'SEND_CHAT_MESSAGE':
return themeCssVariables.color.orange9;
case 'ITERATOR':
case 'EMPTY':
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/getActionIconStrokeOrThrow.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/getActionIconStrokeOrThrow.ts
index 16aefb9174e..1d487e40342 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/getActionIconStrokeOrThrow.ts
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/utils/getActionIconStrokeOrThrow.ts
@@ -20,6 +20,7 @@ export const getActionIconStrokeOrThrow = (
case 'IF_ELSE':
return 'sm';
case 'FORM':
+ case 'SEND_CHAT_MESSAGE':
case 'ITERATOR':
case 'EMPTY':
case 'FILTER':
diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/computeStepOutputSchema.ts b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/computeStepOutputSchema.ts
index 32d25e9cdf1..c7730d15fbb 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/computeStepOutputSchema.ts
+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/generate/computeStepOutputSchema.ts
@@ -218,6 +218,17 @@ export const computeStepOutputSchema = ({
return generateFormOutputSchema(formFields, objectMetadataItems);
}
+ case 'SEND_CHAT_MESSAGE': {
+ return {
+ threadId: {
+ isLeaf: true,
+ type: FieldMetadataType.UUID,
+ label: 'Conversation ID',
+ value: '',
+ },
+ };
+ }
+
case 'SEND_EMAIL': {
return {
success: {
diff --git a/packages/twenty-sdk/src/sdk/logic-function/inbox/__tests__/send-inbox-message.spec.ts b/packages/twenty-sdk/src/sdk/logic-function/inbox/__tests__/send-inbox-message.spec.ts
new file mode 100644
index 00000000000..1a879451699
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/logic-function/inbox/__tests__/send-inbox-message.spec.ts
@@ -0,0 +1,98 @@
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+ type MockInstance,
+} from 'vitest';
+
+import { sendInboxMessage } from '@/sdk/logic-function/inbox/send-inbox-message';
+
+describe('sendInboxMessage', () => {
+ let fetchSpy: MockInstance<typeof fetch>;
+
+ beforeEach(() => {
+ process.env.TWENTY_API_URL = 'https://api.test';
+ process.env.TWENTY_APP_APPLICATION_ACCESS_TOKEN = 'app-token';
+ fetchSpy = vi.spyOn(globalThis, 'fetch');
+ });
+
+ afterEach(() => {
+ delete process.env.TWENTY_API_URL;
+ delete process.env.TWENTY_APP_APPLICATION_ACCESS_TOKEN;
+ fetchSpy.mockRestore();
+ });
+
+ it('POSTs the sendInboxMessage mutation to /metadata and returns the thread', async () => {
+ fetchSpy.mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ data: { sendInboxMessage: { threadId: 'thread-1' } },
+ }),
+ { status: 200 },
+ ),
+ );
+
+ const input = {
+ workspaceMemberId: 'member-1',
+ threadKey: 'first-call-recording',
+ idempotencyKey: 'first-call-recording',
+ title: 'Your first recording is ready',
+ text: 'Your call was recorded.',
+ toolCall: {
+ toolName: 'ask_questions' as const,
+ input: {
+ questions: [
+ {
+ header: 'Share',
+ question: 'Share the recording with the attendees?',
+ options: [{ label: 'Draft an email' }, { label: 'Not now' }],
+ },
+ ],
+ },
+ },
+ };
+
+ const result = await sendInboxMessage(input);
+
+ expect(result).toEqual({ threadId: 'thread-1' });
+
+ const [url, requestInit] = fetchSpy.mock.calls[0];
+
+ expect(url).toBe('https://api.test/metadata');
+ expect(requestInit).toEqual(
+ expect.objectContaining({
+ method: 'POST',
+ headers: expect.objectContaining({
+ Authorization: 'Bearer app-token',
+ }),
+ }),
+ );
+
+ const sentBody = JSON.parse(requestInit?.body as string);
+
+ expect(sentBody.query).toContain('sendInboxMessage(input: $input)');
+ expect(sentBody.variables).toEqual({ input });
+ });
+
+ it('surfaces GraphQL errors as a regular Error', async () => {
+ fetchSpy.mockResolvedValue(
+ new Response(
+ JSON.stringify({ errors: [{ message: 'Chat thread not found.' }] }),
+ { status: 200 },
+ ),
+ );
+
+ await expect(
+ sendInboxMessage({
+ workspaceMemberId: 'member-1',
+ threadKey: 'thread',
+ idempotencyKey: 'key',
+ title: 'Title',
+ text: 'Text',
+ }),
+ ).rejects.toThrow(/Chat thread not found/);
+ });
+});
diff --git a/packages/twenty-sdk/src/sdk/logic-function/inbox/send-inbox-message.ts b/packages/twenty-sdk/src/sdk/logic-function/inbox/send-inbox-message.ts
new file mode 100644
index 00000000000..19fddf60a80
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/logic-function/inbox/send-inbox-message.ts
@@ -0,0 +1,29 @@
+import {
+ type SendInboxMessageInput,
+ type SendInboxMessageResult,
+} from 'twenty-shared/application';
+
+import { postGraphqlRequest } from '@/sdk/logic-function/utils/post-graphql-request.util';
+
+const SEND_INBOX_MESSAGE_MUTATION = `
+ mutation SendInboxMessage($input: SendInboxMessageInput!) {
+ sendInboxMessage(input: $input) {
+ threadId
+ }
+ }
+`;
+
+export const sendInboxMessage = async (
+ input: SendInboxMessageInput,
+): Promise<SendInboxMessageResult> => {
+ const { sendInboxMessage: result } = await postGraphqlRequest<
+ { input: SendInboxMessageInput },
+ { sendInboxMessage: SendInboxMessageResult }
+ >({
+ query: SEND_INBOX_MESSAGE_MUTATION,
+ variables: { input },
+ caller: 'sendInboxMessage',
+ });
+
+ return result;
+};
diff --git a/packages/twenty-sdk/src/sdk/logic-function/index.ts b/packages/twenty-sdk/src/sdk/logic-function/index.ts
index e22376686c1..7c07726549b 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/index.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/index.ts
@@ -68,6 +68,12 @@ export type { AppMessageChannel } from '@/sdk/logic-function/messaging/types/app
export { runAgent } from '@/sdk/logic-function/agents/run-agent';
export type { RunAgentInput, RunAgentResult } from 'twenty-shared/application';
+export { sendInboxMessage } from '@/sdk/logic-function/inbox/send-inbox-message';
+export type {
+ SendInboxMessageInput,
+ SendInboxMessageResult,
+} from 'twenty-shared/application';
+
export { enqueueJob } from '@/sdk/logic-function/jobs/enqueue-job';
export { enqueueJobs } from '@/sdk/logic-function/jobs/enqueue-jobs';
export { getJobs } from '@/sdk/logic-function/jobs/get-jobs';
diff --git a/packages/twenty-server/src/database/commands/agent-history/__tests__/agent-history-migration.postgres.spec.ts b/packages/twenty-server/src/database/commands/agent-history/__tests__/agent-history-migration.postgres.spec.ts
index 139f0c270d1..c0c5f511631 100644
--- a/packages/twenty-server/src/database/commands/agent-history/__tests__/agent-history-migration.postgres.spec.ts
+++ b/packages/twenty-server/src/database/commands/agent-history/__tests__/agent-history-migration.postgres.spec.ts
@@ -4,6 +4,9 @@ import { AgentHistoryWorkspaceStorageService } from 'src/engine/metadata-modules
import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
import { withWorkspaceContext } from 'src/engine/twenty-orm/storage/orm-workspace-context.storage';
import { AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
+import { AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
+import { AgentHistoryTransactionService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-history-transaction.service';
+import { AgentConversationWriterService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service';
import { AgentChatActorService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-actor.service';
import { AgentTurnWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-turn.workspace-entity';
import { AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message-part.workspace-entity';
@@ -147,6 +150,8 @@ const SCHEMA = getWorkspaceSchemaName(WORKSPACE_ID);
),
getRepository:
workspaceDataSource.getRepository.bind(workspaceDataSource),
+ runInWorkspaceTransaction:
+ workspaceDataSource.transaction.bind(workspaceDataSource),
};
};
const orm = createOrm();
@@ -172,37 +177,54 @@ const SCHEMA = getWorkspaceSchemaName(WORKSPACE_ID);
}
};
+ const turns = new AgentHistoryRepository<AgentTurnWorkspaceEntity>(
+ 'agentTurn',
+ storage,
+ orm,
+ );
+ const messageParts =
+ new AgentHistoryRepository<AgentMessagePartWorkspaceEntity>(
+ 'agentMessagePart',
+ storage,
+ orm,
+ );
+
+ const chatSharing = {
+ getThreadWithAccess: ({
+ workspaceId,
+ threadId,
+ }: {
+ workspaceId: string;
+ threadId: string;
+ }) => threads.findOne(workspaceId, { where: { id: threadId } }),
+ getAuthContext: jest.fn().mockResolvedValue({
+ userWorkspaceId: OWNER_ID,
+ workspaceMemberId: MEMBER_ID,
+ }),
+ getPermissions: jest.fn().mockResolvedValue({ canRead: true }),
+ };
+ const chatRecordEvents = {
+ emitThreadUpdated: jest.fn().mockResolvedValue(undefined),
+ };
const createChatService = (messageRepository: typeof messages) =>
new AgentChatService(
threads,
- new AgentHistoryRepository<AgentTurnWorkspaceEntity>(
- 'agentTurn',
- storage,
- orm,
- ),
+ turns,
messageRepository,
- new AgentHistoryRepository<AgentMessagePartWorkspaceEntity>(
- 'agentMessagePart',
- storage,
- orm,
- ),
+ messageParts,
{} as never,
{} as never,
- {
- getThreadWithAccess: ({
- workspaceId,
- threadId,
- }: {
- workspaceId: string;
- threadId: string;
- }) => threads.findOne(workspaceId, { where: { id: threadId } }),
- getAuthContext: jest.fn().mockResolvedValue({
- userWorkspaceId: OWNER_ID,
- workspaceMemberId: MEMBER_ID,
- }),
- getPermissions: jest.fn().mockResolvedValue({ canRead: true }),
- } as never,
- { emitThreadUpdated: jest.fn().mockResolvedValue(undefined) } as never,
+ chatSharing as never,
+ chatRecordEvents as never,
+ new AgentConversationWriterService(
+ turns as never,
+ new AgentHistoryTransactionService(workspaceStorage, orm as never),
+ ),
+ new AgentChatThreadService(
+ threads as never,
+ chatSharing as never,
+ chatRecordEvents as never,
+ ),
);
const createActorService = (messageRepository: typeof messages) =>
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-step-manifest-to-action-or-throw.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-step-manifest-to-action-or-throw.util.spec.ts
index 1d9930e6d11..7f2e19c827c 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-step-manifest-to-action-or-throw.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-workflow-step-manifest-to-action-or-throw.util.spec.ts
@@ -189,7 +189,9 @@ describe('application workflow actions', () => {
it.each(
Object.values(WorkflowActionType).filter(
- (type) => type !== WorkflowActionType.CODE,
+ (type) =>
+ type !== WorkflowActionType.CODE &&
+ type !== WorkflowActionType.SEND_CHAT_MESSAGE,
),
)('converts %s to its runtime action', (type) => {
expect(convert(type)).toMatchObject({ id: STEP_ID, type, valid: true });
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/logic-function-tool.provider.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/logic-function-tool.provider.ts
index 77c25a8e8af..55057ac4f99 100644
--- a/packages/twenty-server/src/engine/core-modules/tool-provider/providers/logic-function-tool.provider.ts
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/providers/logic-function-tool.provider.ts
@@ -17,6 +17,7 @@ import { type ToolIndexEntry } from 'src/engine/core-modules/tool-provider/types
import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
import { WorkspaceManyOrAllFlatEntityMapsCacheService } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.service';
import { type FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
+import { buildLogicFunctionToolName } from 'src/engine/core-modules/tool-provider/utils/build-logic-function-tool-name.util';
@Injectable()
export class LogicFunctionToolProvider implements ToolProvider {
@@ -92,7 +93,7 @@ export class LogicFunctionToolProvider implements ToolProvider {
const descriptors: (ToolIndexEntry | ToolDescriptor)[] = [];
for (const logicFunction of logicFunctionsWithSchema) {
- const toolName = this.buildLogicFunctionToolName(logicFunction.name);
+ const toolName = buildLogicFunctionToolName(logicFunction.name);
const base: ToolIndexEntry = {
name: toolName,
@@ -127,11 +128,4 @@ export class LogicFunctionToolProvider implements ToolProvider {
return descriptors;
}
-
- private buildLogicFunctionToolName(functionName: string): string {
- return `app_${functionName
- .toLowerCase()
- .replace(/[^a-z0-9]+/g, '_')
- .replace(/^_+|_+$/g, '')}`;
- }
}
diff --git a/packages/twenty-server/src/engine/core-modules/tool-provider/utils/build-logic-function-tool-name.util.ts b/packages/twenty-server/src/engine/core-modules/tool-provider/utils/build-logic-function-tool-name.util.ts
new file mode 100644
index 00000000000..cdcccf113c8
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/tool-provider/utils/build-logic-function-tool-name.util.ts
@@ -0,0 +1,5 @@
+export const buildLogicFunctionToolName = (functionName: string): string =>
+ `app_${functionName
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '_')
+ .replace(/^_+|_+$/g, '')}`;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/agent-chat-thread.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/agent-chat-thread.module.ts
new file mode 100644
index 00000000000..160ef8e5a32
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/agent-chat-thread.module.ts
@@ -0,0 +1,26 @@
+import { Module } from '@nestjs/common';
+
+import { RecordShareModule } from 'src/engine/core-modules/record-share/record-share.module';
+import { UserWorkspaceModule } from 'src/engine/core-modules/user-workspace/user-workspace.module';
+import { AgentChatThreadLifecycleModule } from 'src/engine/metadata-modules/ai/ai-chat/agent-chat-thread-lifecycle.module';
+import { AgentChatSharingService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service';
+import { AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
+import { AgentHistoryModule } from 'src/engine/metadata-modules/ai/ai-history/ai-history.module';
+import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permissions.module';
+import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
+
+// separate from AiChatModule so workflow actions can open and update member
+// chats without its streaming, tool and workflow dependencies
+@Module({
+ imports: [
+ AgentChatThreadLifecycleModule,
+ AgentHistoryModule,
+ PermissionsModule,
+ RecordShareModule,
+ UserWorkspaceModule,
+ WorkspaceCacheModule,
+ ],
+ providers: [AgentChatSharingService, AgentChatThreadService],
+ exports: [AgentChatSharingService, AgentChatThreadService],
+})
+export class AgentChatThreadModule {}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/agent-inbox.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/agent-inbox.module.ts
new file mode 100644
index 00000000000..3e77e6da73d
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/agent-inbox.module.ts
@@ -0,0 +1,13 @@
+import { Module } from '@nestjs/common';
+
+import { AgentChatThreadModule } from 'src/engine/metadata-modules/ai/ai-chat/agent-chat-thread.module';
+import { AgentInboxService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.service';
+import { AgentHistoryModule } from 'src/engine/metadata-modules/ai/ai-history/ai-history.module';
+import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
+
+@Module({
+ imports: [AgentChatThreadModule, AgentHistoryModule, WorkspaceCacheModule],
+ providers: [AgentInboxService],
+ exports: [AgentInboxService],
+})
+export class AgentInboxModule {}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/ai-chat.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/ai-chat.module.ts
index 4b2559307c3..41ea384fe7d 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/ai-chat.module.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/ai-chat.module.ts
@@ -1,8 +1,9 @@
import { AgentChatActorService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-actor.service';
import { RecordShareModule } from 'src/engine/core-modules/record-share/record-share.module';
-import { AgentChatSharingService } from './services/agent-chat-sharing.service';
import { AgentChatStreamStateModule } from 'src/engine/metadata-modules/ai/ai-chat/agent-chat-stream-state.module';
import { AgentChatThreadLifecycleModule } from 'src/engine/metadata-modules/ai/ai-chat/agent-chat-thread-lifecycle.module';
+import { AgentChatThreadModule } from 'src/engine/metadata-modules/ai/ai-chat/agent-chat-thread.module';
+import { AgentInboxModule } from 'src/engine/metadata-modules/ai/ai-chat/agent-inbox.module';
import { AgentHistoryModule } from 'src/engine/metadata-modules/ai/ai-history/ai-history.module';
import { UsageLimitModule } from 'src/engine/core-modules/usage-limit/usage-limit.module';
import { AiChatUsageService } from 'src/engine/metadata-modules/ai/ai-chat/services/ai-chat-usage.service';
@@ -37,6 +38,7 @@ import { AgentChatThreadEntity } from './entities/agent-chat-thread.entity';
import { StreamAgentChatJob } from './jobs/stream-agent-chat.job';
import { AgentChatResolver } from './resolvers/agent-chat.resolver';
import { AgentChatSubscriptionResolver } from './resolvers/agent-chat-subscription.resolver';
+import { AgentInboxResolver } from './resolvers/agent-inbox.resolver';
import { WorkspaceSetupChatResolver } from './resolvers/workspace-setup-chat.resolver';
import { WorkspaceSetupChatService } from './services/workspace-setup-chat.service';
import { AgentChatCancelSubscriberService } from './services/agent-chat-cancel-subscriber.service';
@@ -54,6 +56,8 @@ import { SystemPromptBuilderService } from './services/system-prompt-builder.ser
RecordShareModule,
AgentChatStreamStateModule,
AgentChatThreadLifecycleModule,
+ AgentChatThreadModule,
+ AgentInboxModule,
AgentHistoryModule,
UsageLimitModule,
TypeOrmModule.forFeature([
@@ -82,13 +86,13 @@ import { SystemPromptBuilderService } from './services/system-prompt-builder.ser
],
providers: [
AgentChatActorService,
- AgentChatSharingService,
AiChatUsageService,
AiChatUsageResolver,
AgentChatCancelSubscriberService,
AgentChatResolver,
AgentChatSubscriptionResolver,
WorkspaceSetupChatResolver,
+ AgentInboxResolver,
AgentChatService,
AgentChatThreadTargetService,
AgentChatStreamingService,
@@ -103,8 +107,8 @@ import { SystemPromptBuilderService } from './services/system-prompt-builder.ser
provideWorkspaceScopedRepository(FileEntity),
],
exports: [
+ AgentChatThreadModule,
AgentChatActorService,
- AgentChatSharingService,
AgentChatService,
AgentChatStreamingService,
AgentChatThreadTargetService,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/inbox-message-id-namespace.constant.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/inbox-message-id-namespace.constant.ts
new file mode 100644
index 00000000000..ec4043d0cc3
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/inbox-message-id-namespace.constant.ts
@@ -0,0 +1,2 @@
+export const INBOX_MESSAGE_ID_NAMESPACE =
+ '6fc1c54d-bbcc-4bca-aff3-ec124aa00cf4';
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/send-inbox-message-result.dto.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/send-inbox-message-result.dto.ts
new file mode 100644
index 00000000000..643b1fd7b7c
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/send-inbox-message-result.dto.ts
@@ -0,0 +1,11 @@
+import { Field, ObjectType } from '@nestjs/graphql';
+
+import { type SendInboxMessageResult } from 'twenty-shared/application';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+
+@ObjectType('SendInboxMessageResult')
+export class SendInboxMessageResultDTO implements SendInboxMessageResult {
+ @Field(() => UUIDScalarType)
+ threadId: string;
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/send-inbox-message.input.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/send-inbox-message.input.ts
new file mode 100644
index 00000000000..ab4f3604708
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/send-inbox-message.input.ts
@@ -0,0 +1,37 @@
+import { Field, InputType } from '@nestjs/graphql';
+
+import GraphQLJSON from 'graphql-type-json';
+import { IsNotEmpty, IsOptional, IsString, IsUUID } from 'class-validator';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+
+@InputType('SendInboxMessageInput')
+export class SendInboxMessageInputDTO {
+ @IsUUID()
+ @Field(() => UUIDScalarType)
+ workspaceMemberId: string;
+
+ @IsString()
+ @IsNotEmpty()
+ @Field()
+ threadKey: string;
+
+ @IsString()
+ @IsNotEmpty()
+ @Field()
+ idempotencyKey: string;
+
+ @IsString()
+ @IsNotEmpty()
+ @Field()
+ title: string;
+
+ @IsString()
+ @IsNotEmpty()
+ @Field()
+ text: string;
+
+ @IsOptional()
+ @Field(() => GraphQLJSON, { nullable: true })
+ toolCall?: unknown;
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/__tests__/agent-chat.resolver.sharing.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/__tests__/agent-chat.resolver.sharing.spec.ts
index ca6c9f5b9ab..7b3b582c8f0 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/__tests__/agent-chat.resolver.sharing.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/__tests__/agent-chat.resolver.sharing.spec.ts
@@ -5,6 +5,7 @@ import {
import { AgentChatResolver } from 'src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat.resolver';
import { AgentChatThreadLifecycleService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-lifecycle.service';
import { AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
+import { AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
import { DatabaseEventAction } from 'src/engine/api/graphql/graphql-query-runner/enums/database-event-action';
import { AgentChatTurnPreflightService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-turn-preflight.service';
@@ -72,6 +73,12 @@ const buildResolver = () => {
{} as never,
sharing as never,
recordEvents as never,
+ {} as never,
+ new AgentChatThreadService(
+ threadRepository as never,
+ sharing as never,
+ recordEvents as never,
+ ),
);
const streaming = {
streamAgentChat: jest
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-inbox.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-inbox.resolver.ts
new file mode 100644
index 00000000000..4fb337ab0d7
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-inbox.resolver.ts
@@ -0,0 +1,53 @@
+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 { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+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 { type FlatWorkspace } from 'src/engine/core-modules/workspace/types/flat-workspace.type';
+import { AuthApplication } from 'src/engine/decorators/auth/auth-application.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 { SendInboxMessageResultDTO } from 'src/engine/metadata-modules/ai/ai-chat/dtos/send-inbox-message-result.dto';
+import { SendInboxMessageInputDTO } from 'src/engine/metadata-modules/ai/ai-chat/dtos/send-inbox-message.input';
+import { AgentInboxService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.service';
+import { AiGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules/ai/interceptors/ai-graphql-api-exception.interceptor';
+
+@UseGuards(
+ AuthPrincipalGuard({
+ userSession: false,
+ apiKey: false,
+ oauthClient: false,
+ application: true,
+ }),
+ SettingsPermissionGuard(PermissionFlagType.AI),
+)
+@UseInterceptors(AiGraphqlApiExceptionInterceptor)
+@UseFilters(AuthGraphqlApiExceptionFilter)
+@UsePipes(ResolverValidationPipe)
+@MetadataResolver()
+export class AgentInboxResolver {
+ constructor(private readonly agentInboxService: AgentInboxService) {}
+
+ @Mutation(() => SendInboxMessageResultDTO)
+ async sendInboxMessage(
+ @Args('input') input: SendInboxMessageInputDTO,
+ @AuthWorkspace() workspace: FlatWorkspace,
+ @AuthApplication() application: FlatApplication,
+ ): Promise<SendInboxMessageResultDTO> {
+ return this.agentInboxService.sendMessage({
+ workspaceId: workspace.id,
+ sender: { type: 'application', application },
+ input,
+ });
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.get-messages.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.get-messages.spec.ts
index 80af64f135b..d61373957fb 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.get-messages.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.get-messages.spec.ts
@@ -1,4 +1,5 @@
import { AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
+import { AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
const WORKSPACE_ID = 'workspace-id';
const THREAD_ID = 'thread-id';
@@ -9,6 +10,10 @@ const buildService = () => {
findOne: jest.fn().mockResolvedValue({ id: THREAD_ID }),
};
const messageRepository = { find: jest.fn().mockResolvedValue([]) };
+ const sharingService = {
+ getThreadWithAccess: jest.fn().mockResolvedValue({ id: THREAD_ID }),
+ getReadableThread: jest.fn().mockResolvedValue({ id: THREAD_ID }),
+ };
const service = new AgentChatService(
threadRepository as never,
@@ -17,11 +22,14 @@ const buildService = () => {
{} as never,
{} as never,
{} as never,
- {
- getThreadWithAccess: jest.fn().mockResolvedValue({ id: THREAD_ID }),
- getReadableThread: jest.fn().mockResolvedValue({ id: THREAD_ID }),
- } as never,
+ sharingService as never,
+ {} as never,
{} as never,
+ new AgentChatThreadService(
+ threadRepository as never,
+ sharingService as never,
+ {} as never,
+ ),
);
return { service, messageRepository };
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.kickoff-message.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.kickoff-message.spec.ts
index 44dc483b605..705015cd3e6 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.kickoff-message.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.kickoff-message.spec.ts
@@ -3,6 +3,7 @@ import {
AgentMessageStatus,
} from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';
import { AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
+import { AgentConversationWriterService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service';
const WORKSPACE_ID = 'workspace-id';
const THREAD_ID = 'thread-id';
@@ -14,9 +15,7 @@ const buildService = ({ existingHiddenMessage = null as unknown } = {}) => {
};
const messageRepository = {
findOne: jest.fn().mockResolvedValue(existingHiddenMessage),
- insert: jest
- .fn()
- .mockResolvedValue({ identifiers: [{ id: 'kickoff-message-id' }] }),
+ insert: jest.fn().mockResolvedValue({}),
delete: jest.fn().mockResolvedValue({ affected: 1 }),
};
const turnRepository = {
@@ -26,6 +25,21 @@ const buildService = ({ existingHiddenMessage = null as unknown } = {}) => {
delete: jest.fn().mockResolvedValue({ affected: 1 }),
};
const messagePartRepository = { insert: jest.fn().mockResolvedValue({}) };
+ const run = jest.fn(
+ (
+ workspaceId: string,
+ work: (scope: {
+ insert: (name: string, values: unknown) => Promise<unknown>;
+ }) => Promise<unknown>,
+ ) =>
+ work({
+ insert: (name, values) =>
+ (name === 'agentMessage'
+ ? messageRepository
+ : messagePartRepository
+ ).insert(workspaceId, values),
+ }),
+ );
const service = new AgentChatService(
threadRepository as never,
@@ -38,6 +52,11 @@ const buildService = ({ existingHiddenMessage = null as unknown } = {}) => {
getReadableThread: jest.fn().mockResolvedValue({ id: THREAD_ID }),
} as never,
{} as never,
+ new AgentConversationWriterService(
+ turnRepository as never,
+ { run } as never,
+ ),
+ {} as never,
);
return { service, messageRepository, turnRepository, messagePartRepository };
@@ -96,7 +115,7 @@ describe('AgentChatService ensureHiddenKickoffMessage', () => {
]);
expect(result).toEqual({
- id: 'kickoff-message-id',
+ id: insertedMessage.id,
turnId: 'kickoff-turn-id',
});
});
@@ -136,7 +155,7 @@ describe('AgentChatService ensureHiddenKickoffMessage', () => {
id: 'partial-turn-id',
});
expect(result).toEqual({
- id: 'kickoff-message-id',
+ id: messageRepository.insert.mock.calls[0][1].id,
turnId: 'kickoff-turn-id',
});
});
@@ -157,7 +176,7 @@ describe('AgentChatService ensureHiddenKickoffMessage', () => {
});
expect(turnRepository.delete).not.toHaveBeenCalled();
expect(result).toEqual({
- id: 'kickoff-message-id',
+ id: messageRepository.insert.mock.calls[0][1].id,
turnId: 'kickoff-turn-id',
});
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service.ts
new file mode 100644
index 00000000000..0f06cc24c55
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service.ts
@@ -0,0 +1,115 @@
+import { Injectable } from '@nestjs/common';
+
+import { AgentChatSharingService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service';
+import { AgentChatThreadRecordEventService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-record-event.service';
+import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
+import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
+import { AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
+import {
+ AiException,
+ AiExceptionCode,
+} from 'src/engine/metadata-modules/ai/ai.exception';
+
+@Injectable()
+export class AgentChatThreadService {
+ constructor(
+ @InjectAgentHistoryRepository('agentChatThread')
+ private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,
+ private readonly sharingService: AgentChatSharingService,
+ private readonly threadRecordEventService: AgentChatThreadRecordEventService,
+ ) {}
+
+ async createThread({
+ workspaceMemberId,
+ workspaceId,
+ id,
+ title,
+ }: {
+ workspaceMemberId: string;
+ workspaceId: string;
+ id?: string;
+ title?: string;
+ }) {
+ const savedThread = await this.sharingService.createThread({
+ workspaceId,
+ workspaceMemberId,
+ id,
+ title,
+ });
+
+ await this.threadRecordEventService.emitThreadCreated({
+ workspaceId,
+ threadId: savedThread.id,
+ });
+
+ return savedThread;
+ }
+
+ async findWritableThread({
+ threadId,
+ workspaceMemberId,
+ workspaceId,
+ }: {
+ threadId: string;
+ workspaceMemberId: string;
+ workspaceId: string;
+ }) {
+ try {
+ return await this.getWritableThread({
+ threadId,
+ workspaceMemberId,
+ workspaceId,
+ });
+ } catch (error) {
+ if (
+ error instanceof AiException &&
+ error.code === AiExceptionCode.THREAD_NOT_FOUND
+ ) {
+ return null;
+ }
+ throw error;
+ }
+ }
+
+ async getWritableThread(args: {
+ threadId: string;
+ workspaceMemberId: string;
+ workspaceId: string;
+ }) {
+ return this.sharingService.getThreadWithAccess({
+ ...args,
+ operationType: 'update',
+ });
+ }
+
+ async notifyThreadActivityUpdated({
+ threadId,
+ workspaceMemberId,
+ workspaceId,
+ }: {
+ threadId: string;
+ workspaceMemberId: string;
+ workspaceId: string;
+ }): Promise<void> {
+ const thread = await this.getWritableThread({
+ threadId,
+ workspaceMemberId,
+ workspaceId,
+ });
+
+ const threadAfter = { ...thread, updatedAt: new Date().toISOString() };
+
+ // conversations sort by last change, so bump on send rather than at turn end
+ await this.threadRepository.update(
+ workspaceId,
+ { id: threadId },
+ { updatedAt: threadAfter.updatedAt },
+ );
+
+ await this.threadRecordEventService.emitThreadUpdated({
+ workspaceId,
+ threadBefore: thread,
+ threadAfter,
+ });
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts
index 1aeb9a92463..1355e3aa765 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts
@@ -32,6 +32,8 @@ import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
import { AiChatFileAttachment } from 'src/engine/metadata-modules/ai/ai-chat/types/ai-chat-file-attachment.type';
import { AgentChatThreadRecordEventService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-record-event.service';
+import { AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
+import { AgentConversationWriterService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service';
import { AgentTitleGenerationService } from './agent-title-generation.service';
import { DatabaseEventAction } from 'src/engine/api/graphql/graphql-query-runner/enums/database-event-action';
@@ -53,70 +55,24 @@ export class AgentChatService {
private readonly titleGenerationService: AgentTitleGenerationService,
private readonly sharingService: AgentChatSharingService,
private readonly threadRecordEventService: AgentChatThreadRecordEventService,
+ private readonly conversationWriterService: AgentConversationWriterService,
+ private readonly threadService: AgentChatThreadService,
) {}
- async createThread({
- workspaceMemberId,
- workspaceId,
- id,
- title,
- }: {
- workspaceMemberId: string;
- workspaceId: string;
- id?: string;
- title?: string;
- }) {
- const savedThread = await this.sharingService.createThread({
- workspaceId,
- workspaceMemberId,
- id,
- title,
- });
-
- await this.threadRecordEventService.emitThreadCreated({
- workspaceId,
- threadId: savedThread.id,
- });
-
- return savedThread;
+ createThread(args: Parameters<AgentChatThreadService['createThread']>[0]) {
+ return this.threadService.createThread(args);
}
- async findWritableThread({
- threadId,
- workspaceMemberId,
- workspaceId,
- }: {
- threadId: string;
- workspaceMemberId: string;
- workspaceId: string;
- }) {
- try {
- return await this.sharingService.getThreadWithAccess({
- threadId,
- workspaceMemberId,
- workspaceId,
- operationType: 'update',
- });
- } catch (error) {
- if (
- error instanceof AiException &&
- error.code === AiExceptionCode.THREAD_NOT_FOUND
- ) {
- return null;
- }
- throw error;
- }
+ findWritableThread(
+ args: Parameters<AgentChatThreadService['findWritableThread']>[0],
+ ) {
+ return this.threadService.findWritableThread(args);
}
- async getWritableThread(args: {
- threadId: string;
- workspaceMemberId: string;
- workspaceId: string;
- }) {
- return this.sharingService.getThreadWithAccess({
- ...args,
- operationType: 'update',
- });
+ getWritableThread(
+ args: Parameters<AgentChatThreadService['getWritableThread']>[0],
+ ) {
+ return this.threadService.getWritableThread(args);
}
private getMessageSenderValues({
@@ -162,49 +118,32 @@ export class AgentChatService {
processedAt?: Date;
userWorkspaceId?: string;
}) {
- let actualTurnId = turnId;
-
- if (!actualTurnId) {
- const turnInsertResult = await this.turnRepository.insert(workspaceId, {
+ const actualTurnId =
+ turnId ??
+ (await this.conversationWriterService.insertTurn({
+ workspaceId,
threadId,
agentId: agentId ?? null,
- });
+ }));
- actualTurnId = turnInsertResult.identifiers[0].id as string;
- }
+ const senderValues = this.getMessageSenderValues({
+ workspaceId,
+ userWorkspaceId,
+ });
+ const resolvedProcessedAt = processedAt ?? new Date();
- const messageValues = {
- ...(id ? { id } : {}),
+ const savedMessageId = await this.conversationWriterService.insertMessage({
+ workspaceId,
+ id,
threadId,
turnId: actualTurnId,
role: uiMessage.role as AgentMessageRole,
agentId: agentId ?? null,
- processedAt: (processedAt ?? new Date()).toISOString(),
- ...this.getMessageSenderValues({ workspaceId, userWorkspaceId }),
- ...(isDefined(isHidden) ? { isHidden } : {}),
- };
-
- const insertResult = await this.messageRepository.insert(
- workspaceId,
- messageValues,
- );
-
- const savedMessageId = (id ?? insertResult.identifiers[0].id) as string;
-
- if (uiMessage.parts && uiMessage.parts.length > 0) {
- const dbParts = mapUIMessagePartsToPersistedDBParts(
- uiMessage.parts,
- savedMessageId,
- workspaceId,
- );
-
- if (dbParts.length > 0) {
- await this.messagePartRepository.insert(
- workspaceId,
- dbParts as QueryDeepPartialEntity<AgentMessagePartWorkspaceEntity>[],
- );
- }
- }
+ ...senderValues,
+ isHidden,
+ processedAt: resolvedProcessedAt,
+ parts: uiMessage.parts ?? [],
+ });
return {
id: savedMessageId,
@@ -212,9 +151,8 @@ export class AgentChatService {
turnId: actualTurnId,
role: uiMessage.role as AgentMessageRole,
agentId: agentId ?? null,
- processedAt: messageValues.processedAt,
- senderUserWorkspaceId: messageValues.senderUserWorkspaceId,
- senderApplicationId: messageValues.senderApplicationId,
+ processedAt: resolvedProcessedAt.toISOString(),
+ ...senderValues,
};
}
@@ -553,13 +491,12 @@ export class AgentChatService {
threadId: string;
workspaceId: string;
}): Promise<string | null> {
- const turnInsertResult = await this.turnRepository.insert(workspaceId, {
+ const savedTurnId = await this.conversationWriterService.insertTurn({
+ workspaceId,
threadId,
agentId: null,
});
- const savedTurnId = turnInsertResult.identifiers[0].id as string;
-
const result = await this.messageRepository.update(
workspaceId,
{ id: messageId, threadId, status: AgentMessageStatus.QUEUED },
@@ -730,35 +667,10 @@ export class AgentChatService {
return thread;
}
- async notifyThreadActivityUpdated({
- threadId,
- workspaceMemberId,
- workspaceId,
- }: {
- threadId: string;
- workspaceMemberId: string;
- workspaceId: string;
- }): Promise<void> {
- const thread = await this.getWritableThread({
- threadId,
- workspaceMemberId,
- workspaceId,
- });
-
- const threadAfter = { ...thread, updatedAt: new Date().toISOString() };
-
- // conversations sort by last change, so bump on send rather than at turn end
- await this.threadRepository.update(
- workspaceId,
- { id: threadId },
- { updatedAt: threadAfter.updatedAt },
- );
-
- await this.threadRecordEventService.emitThreadUpdated({
- workspaceId,
- threadBefore: thread,
- threadAfter,
- });
+ notifyThreadActivityUpdated(
+ args: Parameters<AgentChatThreadService['notifyThreadActivityUpdated']>[0],
+ ) {
+ return this.threadService.notifyThreadActivityUpdated(args);
}
async notifyThreadUsageUpdated({
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.service.ts
new file mode 100644
index 00000000000..3efafe85b82
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.service.ts
@@ -0,0 +1,282 @@
+import { Injectable } from '@nestjs/common';
+
+import { type ExtendedUIMessagePart } from 'twenty-shared/ai';
+import {
+ type SendInboxMessageInput,
+ type SendInboxMessageResult,
+} from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';
+import { AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';
+import { type AgentInboxSender } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-inbox-sender.type';
+import { buildInboxMessageIds } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-ids.util';
+import { buildInboxMessageToolCallPart } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-tool-call-part.util';
+import { getAgentInboxSenderDetails } from 'src/engine/metadata-modules/ai/ai-chat/utils/get-agent-inbox-sender-details.util';
+import { isUniqueViolationError } from 'src/engine/metadata-modules/ai/ai-chat/utils/is-unique-violation-error.util';
+import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
+import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
+import { AgentConversationWriterService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service';
+import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
+import { type AgentMessageWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message.workspace-entity';
+import { type FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+
+@Injectable()
+export class AgentInboxService {
+ constructor(
+ @InjectAgentHistoryRepository('agentChatThread')
+ private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,
+ @InjectAgentHistoryRepository('agentMessage')
+ private readonly messageRepository: AgentHistoryRepository<AgentMessageWorkspaceEntity>,
+ private readonly threadService: AgentChatThreadService,
+ private readonly conversationWriterService: AgentConversationWriterService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ ) {}
+
+ // Every record has an id derived from the keys: the thread key picks the
+ // conversation, and the idempotency key the message in it, so a retry or a
+ // concurrent send completes the same message instead of writing another.
+ // A message is written with its parts at once, so one that exists is done.
+ async sendMessage({
+ workspaceId,
+ sender,
+ input,
+ }: {
+ workspaceId: string;
+ sender: AgentInboxSender;
+ input: Omit<SendInboxMessageInput, 'toolCall'> & { toolCall?: unknown };
+ }): Promise<SendInboxMessageResult> {
+ const senderDetails = getAgentInboxSenderDetails(sender);
+ const { threadId, turnId, openingMessageId, messageId, toolCallId } =
+ buildInboxMessageIds({
+ senderKey: senderDetails.key,
+ workspaceMemberId: input.workspaceMemberId,
+ threadKey: input.threadKey,
+ idempotencyKey: input.idempotencyKey,
+ });
+
+ const existingThread = await this.findThread({ workspaceId, threadId });
+
+ // A member who deleted the conversation has dismissed it, and a message
+ // that exists was already delivered.
+ if (
+ isDefined(existingThread?.deletedAt) ||
+ (await this.messageExists({ workspaceId, id: messageId }))
+ ) {
+ return { threadId };
+ }
+
+ const toolCallPart = isDefined(input.toolCall)
+ ? await buildInboxMessageToolCallPart({
+ toolCall: input.toolCall,
+ toolCallId,
+ findApplicationTool: (logicFunctionUniversalIdentifier) =>
+ this.findApplicationTool({
+ workspaceId,
+ applicationId: senderDetails.applicationId,
+ logicFunctionUniversalIdentifier,
+ }),
+ })
+ : undefined;
+
+ const thread =
+ existingThread ??
+ (await this.createThread({
+ workspaceId,
+ threadId,
+ workspaceMemberId: input.workspaceMemberId,
+ title: input.title,
+ }));
+
+ await this.ensureOpener({
+ workspaceId,
+ threadId,
+ turnId,
+ openingMessageId,
+ memberUserWorkspaceId: thread.userWorkspaceId,
+ senderDescription: senderDetails.description,
+ });
+
+ const parts: ExtendedUIMessagePart[] = [{ type: 'text', text: input.text }];
+
+ if (isDefined(toolCallPart)) {
+ parts.push(toolCallPart.part);
+ }
+
+ const isWritten = await this.ignoreDuplicate(() =>
+ this.conversationWriterService.insertMessage({
+ workspaceId,
+ id: messageId,
+ threadId,
+ turnId,
+ role: AgentMessageRole.ASSISTANT,
+ agentId: null,
+ senderUserWorkspaceId: null,
+ senderApplicationId: senderDetails.applicationId,
+ isAwaitingAnswer: toolCallPart?.isAwaitingAnswer,
+ parts,
+ }),
+ );
+
+ if (isWritten) {
+ await this.threadService.notifyThreadActivityUpdated({
+ threadId,
+ workspaceMemberId: input.workspaceMemberId,
+ workspaceId,
+ });
+ }
+
+ return { threadId };
+ }
+
+ // Answering a tool call resolves who may answer from the user message of
+ // its turn, and models expect a conversation to open with one. It holds
+ // no text from the sender, so nothing the sender wrote reads as the
+ // member's request.
+ private async ensureOpener({
+ workspaceId,
+ threadId,
+ turnId,
+ openingMessageId,
+ memberUserWorkspaceId,
+ senderDescription,
+ }: {
+ workspaceId: string;
+ threadId: string;
+ turnId: string;
+ openingMessageId: string;
+ memberUserWorkspaceId: string | null;
+ senderDescription: string;
+ }): Promise<void> {
+ await this.ignoreDuplicate(() =>
+ this.conversationWriterService.insertTurn({
+ workspaceId,
+ id: turnId,
+ threadId,
+ agentId: null,
+ }),
+ );
+
+ await this.ignoreDuplicate(() =>
+ this.conversationWriterService.insertMessage({
+ workspaceId,
+ id: openingMessageId,
+ threadId,
+ turnId,
+ role: AgentMessageRole.USER,
+ agentId: null,
+ senderUserWorkspaceId: memberUserWorkspaceId,
+ isHidden: true,
+ parts: [
+ {
+ type: 'text',
+ text: `${senderDescription} started this conversation. Its messages follow.`,
+ },
+ ],
+ }),
+ );
+ }
+
+ private findThread({
+ workspaceId,
+ threadId,
+ }: {
+ workspaceId: string;
+ threadId: string;
+ }) {
+ return this.threadRepository.findOne(workspaceId, {
+ where: { id: threadId },
+ });
+ }
+
+ private async createThread({
+ workspaceId,
+ threadId,
+ workspaceMemberId,
+ title,
+ }: {
+ workspaceId: string;
+ threadId: string;
+ workspaceMemberId: string;
+ title: string;
+ }): Promise<AgentChatThreadWorkspaceEntity> {
+ try {
+ return await this.threadService.createThread({
+ workspaceId,
+ workspaceMemberId,
+ id: threadId,
+ title,
+ });
+ } catch (error) {
+ const concurrentlyCreatedThread = isUniqueViolationError(error)
+ ? await this.findThread({ workspaceId, threadId })
+ : null;
+
+ if (!isDefined(concurrentlyCreatedThread)) {
+ throw error;
+ }
+
+ return concurrentlyCreatedThread;
+ }
+ }
+
+ // Every id is derived from the keys, so a row that already exists was
+ // written by a concurrent send of the same conversation.
+ private async ignoreDuplicate(write: () => Promise<unknown>) {
+ try {
+ await write();
+
+ return true;
+ } catch (error) {
+ if (isUniqueViolationError(error)) {
+ return false;
+ }
+
+ throw error;
+ }
+ }
+
+ private async messageExists({
+ workspaceId,
+ id,
+ }: {
+ workspaceId: string;
+ id: string;
+ }): Promise<boolean> {
+ return isDefined(
+ await this.messageRepository.findOne(workspaceId, {
+ where: { id },
+ select: ['id'],
+ }),
+ );
+ }
+
+ private async findApplicationTool({
+ workspaceId,
+ applicationId,
+ logicFunctionUniversalIdentifier,
+ }: {
+ workspaceId: string;
+ applicationId: string | null;
+ logicFunctionUniversalIdentifier: string;
+ }): Promise<FlatLogicFunction | undefined> {
+ if (!isDefined(applicationId)) {
+ return undefined;
+ }
+
+ const { flatLogicFunctionMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatLogicFunctionMaps',
+ ]);
+ const logicFunction =
+ flatLogicFunctionMaps.byUniversalIdentifier[
+ logicFunctionUniversalIdentifier
+ ];
+
+ return logicFunction?.applicationId === applicationId &&
+ !isDefined(logicFunction.deletedAt)
+ ? logicFunction
+ : undefined;
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/workspace-setup-chat.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/workspace-setup-chat.service.ts
index afcb0ffcaa8..f70ad018ca5 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/workspace-setup-chat.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/workspace-setup-chat.service.ts
@@ -7,9 +7,7 @@ import {
type WorkspaceCompanyEnrichment,
type WorkspacePersonEnrichment,
} from 'twenty-shared/workspace';
-import { QueryFailedError } from 'typeorm';
-import { POSTGRESQL_ERROR_CODES } from 'src/engine/api/graphql/workspace-query-runner/constants/postgres-error-codes.constants';
import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';
import { I18nService } from 'src/engine/core-modules/i18n/i18n.service';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
@@ -20,6 +18,7 @@ import { WorkspaceSetupChatOutcome } from 'src/engine/metadata-modules/ai/ai-cha
import { AgentChatStreamingService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service';
import { AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
import { buildWorkspaceSetupChatThreadId } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-chat-thread-id.util';
+import { isUniqueViolationError } from 'src/engine/metadata-modules/ai/ai-chat/utils/is-unique-violation-error.util';
import { buildWorkspaceSetupKickoffMessageText } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-kickoff-message-text.util';
import { tagAiChatStreamScope } from 'src/engine/metadata-modules/ai/ai-chat/utils/tag-ai-chat-stream-scope.util';
import { AiModelRegistryService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';
@@ -219,7 +218,7 @@ export class WorkspaceSetupChatService {
title,
});
} catch (error) {
- if (this.isUniqueViolation(error)) {
+ if (isUniqueViolationError(error)) {
const concurrentlyCreatedThread =
await this.agentChatService.findWritableThread({
threadId,
@@ -236,14 +235,6 @@ export class WorkspaceSetupChatService {
}
}
- private isUniqueViolation(error: unknown): boolean {
- return (
- error instanceof QueryFailedError &&
- (error as QueryFailedError & { code?: string }).code ===
- POSTGRESQL_ERROR_CODES.UNIQUE_VIOLATION
- );
- }
-
private async resolveUserLocale({
userId,
userLocale,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/ask-questions.tool.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/ask-questions.tool.ts
index 34d231f5e71..b7d9a881b12 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/ask-questions.tool.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/ask-questions.tool.ts
@@ -66,6 +66,15 @@ type AskQuestionsPendingOutput = {
result: AskQuestionsToolResult;
};
+// An application that asks through the inbox writes the same output.
+export const buildAskQuestionsPendingOutput = (
+ input: AskQuestionsToolInput,
+): AskQuestionsPendingOutput => ({
+ success: true,
+ message: 'Questions presented to the user; awaiting their answer.',
+ result: { questions: input.questions, status: 'pending' },
+});
+
const STANDARD_DESCRIPTION =
'Ask the user one or more multiple-choice questions when you need a decision you cannot ' +
'infer from the request or context and that has no obvious default. The conversation ' +
@@ -91,9 +100,6 @@ export const createAskQuestionsTool = ({
inputSchema: askQuestionsInputSchema,
execute: async (
input: AskQuestionsToolInput,
- ): Promise<AskQuestionsPendingOutput> => ({
- success: true,
- message: 'Questions presented to the user; awaiting their answer.',
- result: { questions: input.questions, status: 'pending' },
- }),
+ ): Promise<AskQuestionsPendingOutput> =>
+ buildAskQuestionsPendingOutput(input),
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/propose-email.tool.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/propose-email.tool.ts
index ac6aee8751f..510750e4ec5 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/propose-email.tool.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/propose-email.tool.ts
@@ -45,15 +45,19 @@ type ProposeEmailPendingOutput = {
result: ProposeEmailToolResult;
};
+// An application that proposes an email through the inbox writes the same output.
+export const buildProposeEmailPendingOutput = (
+ input: ProposedEmail,
+): ProposeEmailPendingOutput => ({
+ success: true,
+ message: 'Email proposed to the user; awaiting their decision.',
+ result: { status: 'pending', email: input },
+});
+
export const createProposeEmailTool = () => ({
description:
'Propose an email for the user to review before it goes out. The conversation pauses while they edit it and then send it, save it as a draft or discard it; the result says which, with the final content. Prefer this over send_email whenever the user has not explicitly asked you to send without review.',
inputSchema: proposeEmailInputSchema,
- execute: async (
- input: ProposedEmail,
- ): Promise<ProposeEmailPendingOutput> => ({
- success: true,
- message: 'Email proposed to the user; awaiting their decision.',
- result: { status: 'pending', email: input },
- }),
+ execute: async (input: ProposedEmail): Promise<ProposeEmailPendingOutput> =>
+ buildProposeEmailPendingOutput(input),
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/types/agent-inbox-sender.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/types/agent-inbox-sender.type.ts
new file mode 100644
index 00000000000..e6095649986
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/types/agent-inbox-sender.type.ts
@@ -0,0 +1,5 @@
+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+
+export type AgentInboxSender =
+ | { type: 'application'; application: FlatApplication }
+ | { type: 'workflow'; workflowId: string; workflowName: string };
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-inbox-message-ids.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-inbox-message-ids.util.spec.ts
new file mode 100644
index 00000000000..3670d2a49f8
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-inbox-message-ids.util.spec.ts
@@ -0,0 +1,57 @@
+import { buildInboxMessageIds } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-ids.util';
+
+const INPUT = {
+ senderKey: 'application:application-id',
+ workspaceMemberId: 'workspace-member-id',
+ threadKey: 'first-call-recording',
+ idempotencyKey: 'first-call-recording',
+};
+
+describe('buildInboxMessageIds', () => {
+ it('returns the same ids for the same sender, member and keys', () => {
+ expect(buildInboxMessageIds(INPUT)).toEqual(buildInboxMessageIds(INPUT));
+ });
+
+ it('returns distinct ids for each record of one message', () => {
+ const ids = Object.values(buildInboxMessageIds(INPUT));
+
+ expect(new Set(ids).size).toBe(ids.length);
+ });
+
+ it('keeps the thread, turn and opener and changes the message for another idempotency key', () => {
+ const first = buildInboxMessageIds(INPUT);
+ const second = buildInboxMessageIds({
+ ...INPUT,
+ idempotencyKey: 'second-message',
+ });
+
+ expect(second).toEqual({
+ ...first,
+ messageId: expect.any(String),
+ toolCallId: expect.any(String),
+ });
+ expect(second.messageId).not.toBe(first.messageId);
+ expect(second.toolCallId).not.toBe(first.toolCallId);
+ });
+
+ it.each(['opening', 'turn'])(
+ 'keeps the message apart from the opener and turn for the key %s',
+ (idempotencyKey) => {
+ const ids = Object.values(
+ buildInboxMessageIds({ ...INPUT, idempotencyKey }),
+ );
+
+ expect(new Set(ids).size).toBe(ids.length);
+ },
+ );
+
+ it.each([
+ { senderKey: 'application:other-application-id' },
+ { workspaceMemberId: 'other-workspace-member-id' },
+ { threadKey: 'other-thread' },
+ ])('returns another thread when %o differs', (override) => {
+ expect(buildInboxMessageIds({ ...INPUT, ...override }).threadId).not.toBe(
+ buildInboxMessageIds(INPUT).threadId,
+ );
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-inbox-message-tool-call-part.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-inbox-message-tool-call-part.util.spec.ts
new file mode 100644
index 00000000000..bd2bd55f0a7
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/build-inbox-message-tool-call-part.util.spec.ts
@@ -0,0 +1,135 @@
+import { buildInboxMessageToolCallPart } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-tool-call-part.util';
+import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';
+import { type FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
+
+const TOOL_CALL_ID = 'call_inbox';
+
+const SHARE_RECORDING_TOOL = {
+ universalIdentifier: 'share-recording-tool',
+ name: 'share-recording',
+ toolTriggerSettings: { frontComponentUniversalIdentifier: 'component-id' },
+} as FlatLogicFunction;
+
+const build = (toolCall: unknown) =>
+ buildInboxMessageToolCallPart({
+ toolCall,
+ toolCallId: TOOL_CALL_ID,
+ findApplicationTool: async (logicFunctionUniversalIdentifier) =>
+ logicFunctionUniversalIdentifier ===
+ SHARE_RECORDING_TOOL.universalIdentifier
+ ? SHARE_RECORDING_TOOL
+ : undefined,
+ });
+
+describe('buildInboxMessageToolCallPart', () => {
+ it('asks questions as a pending ask_questions call', async () => {
+ const questions = [
+ {
+ header: 'Share',
+ question: 'Share the recording?',
+ options: [{ label: 'Draft a recap email' }, { label: 'Not now' }],
+ },
+ ];
+
+ await expect(
+ build({ toolName: 'ask_questions', input: { questions } }),
+ ).resolves.toEqual({
+ isAwaitingAnswer: true,
+ part: {
+ type: 'tool-ask_questions',
+ toolCallId: TOOL_CALL_ID,
+ state: 'output-available',
+ input: { questions },
+ output: expect.objectContaining({
+ result: { questions, status: 'pending' },
+ }),
+ },
+ });
+ });
+
+ it('requests a form as a pending request_form call', async () => {
+ const fields = [{ name: 'note', label: 'Note', type: 'TEXT' }];
+
+ await expect(
+ build({ toolName: 'request_form', input: { fields } }),
+ ).resolves.toEqual({
+ isAwaitingAnswer: true,
+ part: expect.objectContaining({
+ type: 'tool-request_form',
+ input: { fields },
+ output: expect.objectContaining({ result: { status: 'pending' } }),
+ }),
+ });
+ });
+
+ it('proposes an email as a pending propose_email call', async () => {
+ const email = {
+ recipients: { to: '[email protected]', cc: '', bcc: '' },
+ subject: 'Recap',
+ body: 'Here is the recap.',
+ };
+
+ await expect(
+ build({ toolName: 'propose_email', input: email }),
+ ).resolves.toEqual({
+ isAwaitingAnswer: true,
+ part: expect.objectContaining({
+ type: 'tool-propose_email',
+ input: email,
+ output: expect.objectContaining({
+ result: { status: 'pending', email },
+ }),
+ }),
+ });
+ });
+
+ it('renders an application tool with its front component without pausing', async () => {
+ await expect(
+ build({
+ logicFunctionUniversalIdentifier: 'share-recording-tool',
+ input: { callRecordingId: 'call-recording-1' },
+ }),
+ ).resolves.toEqual({
+ isAwaitingAnswer: false,
+ part: {
+ type: 'tool-app_share_recording',
+ toolCallId: TOOL_CALL_ID,
+ state: 'output-available',
+ input: { callRecordingId: 'call-recording-1' },
+ output: {},
+ },
+ });
+ });
+
+ it.each([
+ ['an unknown tool', { toolName: 'send_email', input: {} }],
+ ['invalid input', { toolName: 'ask_questions', input: { questions: [] } }],
+ [
+ 'a tool of another application',
+ { logicFunctionUniversalIdentifier: 'other-tool' },
+ ],
+ ['a non-object tool call', 'ask_questions'],
+ [
+ 'an application tool with a non-object input',
+ { logicFunctionUniversalIdentifier: 'share-recording-tool', input: [] },
+ ],
+ [
+ 'an application tool with a non-object output',
+ {
+ logicFunctionUniversalIdentifier: 'share-recording-tool',
+ output: 'done',
+ },
+ ],
+ [
+ 'a tool call naming both a tool and an application tool',
+ {
+ toolName: 'ask_questions',
+ logicFunctionUniversalIdentifier: 'share-recording-tool',
+ },
+ ],
+ ])('rejects %s', async (_, toolCall) => {
+ await expect(build(toolCall)).rejects.toMatchObject({
+ code: AiExceptionCode.INVALID_AGENT_INPUT,
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/get-agent-inbox-sender-details.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/get-agent-inbox-sender-details.util.spec.ts
new file mode 100644
index 00000000000..c0965800173
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/get-agent-inbox-sender-details.util.spec.ts
@@ -0,0 +1,34 @@
+import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+import { getAgentInboxSenderDetails } from 'src/engine/metadata-modules/ai/ai-chat/utils/get-agent-inbox-sender-details.util';
+
+describe('getAgentInboxSenderDetails', () => {
+ it('attributes an application message to the application', () => {
+ expect(
+ getAgentInboxSenderDetails({
+ type: 'application',
+ application: {
+ id: 'application-id',
+ name: 'Call recorder',
+ } as FlatApplication,
+ }),
+ ).toEqual({
+ key: 'application:application-id',
+ applicationId: 'application-id',
+ description: 'The "Call recorder" application',
+ });
+ });
+
+ it('attributes a workflow message to no application', () => {
+ expect(
+ getAgentInboxSenderDetails({
+ type: 'workflow',
+ workflowId: 'workflow-id',
+ workflowName: 'Welcome new deals',
+ }),
+ ).toEqual({
+ key: 'workflow:workflow-id',
+ applicationId: null,
+ description: 'The "Welcome new deals" workflow',
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-ids.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-ids.util.ts
new file mode 100644
index 00000000000..2177609f83b
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-ids.util.ts
@@ -0,0 +1,42 @@
+import { v5 } from 'uuid';
+
+import { INBOX_MESSAGE_ID_NAMESPACE } from 'src/engine/metadata-modules/ai/ai-chat/constants/inbox-message-id-namespace.constant';
+
+type InboxMessageIds = {
+ threadId: string;
+ turnId: string;
+ openingMessageId: string;
+ messageId: string;
+ toolCallId: string;
+};
+
+export const buildInboxMessageIds = ({
+ senderKey,
+ workspaceMemberId,
+ threadKey,
+ idempotencyKey,
+}: {
+ senderKey: string;
+ workspaceMemberId: string;
+ threadKey: string;
+ idempotencyKey: string;
+}): InboxMessageIds => {
+ const threadId = v5(
+ `${senderKey}:${workspaceMemberId}:${threadKey}`,
+ INBOX_MESSAGE_ID_NAMESPACE,
+ );
+ const messageId = v5(
+ `${threadId}:message:${idempotencyKey}`,
+ INBOX_MESSAGE_ID_NAMESPACE,
+ );
+
+ // A thread holds a single hidden message, so every message the
+ // application sends shares the turn that opener starts.
+ return {
+ threadId,
+ messageId,
+ toolCallId: `call_${messageId.replace(/-/g, '')}`,
+ turnId: v5(`${threadId}:turn`, INBOX_MESSAGE_ID_NAMESPACE),
+ openingMessageId: v5(`${threadId}:opening`, INBOX_MESSAGE_ID_NAMESPACE),
+ };
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-tool-call-part.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-tool-call-part.util.ts
new file mode 100644
index 00000000000..8ac0216aac7
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-tool-call-part.util.ts
@@ -0,0 +1,187 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import {
+ ASK_QUESTIONS_TOOL_NAME,
+ type ExtendedUIMessagePart,
+ PROPOSE_EMAIL_TOOL_NAME,
+ REQUEST_FORM_TOOL_NAME,
+} from 'twenty-shared/ai';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+import { type z } from 'zod';
+
+import { buildLogicFunctionToolName } from 'src/engine/core-modules/tool-provider/utils/build-logic-function-tool-name.util';
+import {
+ askQuestionsInputSchema,
+ buildAskQuestionsPendingOutput,
+} from 'src/engine/metadata-modules/ai/ai-chat/tools/ask-questions.tool';
+import {
+ buildProposeEmailPendingOutput,
+ proposeEmailInputSchema,
+} from 'src/engine/metadata-modules/ai/ai-chat/tools/propose-email.tool';
+import {
+ buildRequestFormPendingOutput,
+ requestFormInputSchema,
+} from 'src/engine/metadata-modules/ai/ai-chat/tools/request-form.tool';
+import {
+ AiException,
+ AiExceptionCode,
+} from 'src/engine/metadata-modules/ai/ai.exception';
+import { type FlatLogicFunction } from 'src/engine/metadata-modules/logic-function/types/flat-logic-function.type';
+
+type InboxMessageToolCallPart = {
+ part: ExtendedUIMessagePart;
+ isAwaitingAnswer: boolean;
+};
+
+const throwInvalidToolCall = (reason: string): never => {
+ throw new AiException(
+ `Invalid inbox message tool call: ${reason}`,
+ AiExceptionCode.INVALID_AGENT_INPUT,
+ );
+};
+
+const parseInput = <TInput>(schema: z.ZodType<TInput>, input: unknown) => {
+ const parseResult = schema.safeParse(input);
+
+ return parseResult.success
+ ? parseResult.data
+ : throwInvalidToolCall(parseResult.error.message);
+};
+
+const parseOptionalRecord = (
+ name: string,
+ value: unknown,
+): Record<string, unknown> => {
+ if (!isDefined(value)) {
+ return {};
+ }
+
+ return isPlainObject(value)
+ ? value
+ : throwInvalidToolCall(`${name} must be an object`);
+};
+
+const buildToolPart = ({
+ toolName,
+ toolCallId,
+ input,
+ output,
+}: {
+ toolName: string;
+ toolCallId: string;
+ input: unknown;
+ output: unknown;
+}): ExtendedUIMessagePart => ({
+ type: `tool-${toolName}`,
+ toolCallId,
+ state: 'output-available',
+ input,
+ output,
+});
+
+const buildPausingToolPart = ({
+ toolName,
+ toolCallId,
+ input,
+}: {
+ toolName: unknown;
+ toolCallId: string;
+ input: unknown;
+}): ExtendedUIMessagePart => {
+ switch (toolName) {
+ case ASK_QUESTIONS_TOOL_NAME: {
+ const questionsInput = parseInput(askQuestionsInputSchema, input);
+
+ return buildToolPart({
+ toolName,
+ toolCallId,
+ input: questionsInput,
+ output: buildAskQuestionsPendingOutput(questionsInput),
+ });
+ }
+ case REQUEST_FORM_TOOL_NAME:
+ return buildToolPart({
+ toolName,
+ toolCallId,
+ input: parseInput(requestFormInputSchema, input),
+ output: buildRequestFormPendingOutput(),
+ });
+ case PROPOSE_EMAIL_TOOL_NAME: {
+ const email = parseInput(proposeEmailInputSchema, input);
+
+ return buildToolPart({
+ toolName,
+ toolCallId,
+ input: email,
+ output: buildProposeEmailPendingOutput(email),
+ });
+ }
+ default:
+ return throwInvalidToolCall(
+ `toolName must be ${ASK_QUESTIONS_TOOL_NAME}, ${REQUEST_FORM_TOOL_NAME} or ${PROPOSE_EMAIL_TOOL_NAME}`,
+ );
+ }
+};
+
+// A tool call is either one the member answers, which pauses the
+// conversation, or one of the application's own tools, rendered by its front
+// component with the input and output the application gives. The caller
+// resolves that tool, scoped to the sending application.
+export const buildInboxMessageToolCallPart = async ({
+ toolCall,
+ toolCallId,
+ findApplicationTool,
+}: {
+ toolCall: unknown;
+ toolCallId: string;
+ findApplicationTool: (
+ logicFunctionUniversalIdentifier: string,
+ ) => Promise<FlatLogicFunction | undefined>;
+}): Promise<InboxMessageToolCallPart> => {
+ if (!isPlainObject(toolCall)) {
+ return throwInvalidToolCall('toolCall must be an object');
+ }
+
+ if (!isNonEmptyString(toolCall.logicFunctionUniversalIdentifier)) {
+ return {
+ part: buildPausingToolPart({
+ toolName: toolCall.toolName,
+ toolCallId,
+ input: toolCall.input,
+ }),
+ isAwaitingAnswer: true,
+ };
+ }
+
+ if (isDefined(toolCall.toolName)) {
+ return throwInvalidToolCall(
+ 'set either toolName or logicFunctionUniversalIdentifier, not both',
+ );
+ }
+
+ const input = parseOptionalRecord('input', toolCall.input);
+ const output = parseOptionalRecord('output', toolCall.output);
+ const applicationTool = await findApplicationTool(
+ toolCall.logicFunctionUniversalIdentifier,
+ );
+
+ if (
+ !isDefined(applicationTool) ||
+ !isDefined(
+ applicationTool.toolTriggerSettings?.frontComponentUniversalIdentifier,
+ )
+ ) {
+ return throwInvalidToolCall(
+ 'logicFunctionUniversalIdentifier must name a tool of this application that has a front component',
+ );
+ }
+
+ return {
+ part: buildToolPart({
+ toolName: buildLogicFunctionToolName(applicationTool.name),
+ toolCallId,
+ input,
+ output,
+ }),
+ isAwaitingAnswer: false,
+ };
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/get-agent-inbox-sender-details.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/get-agent-inbox-sender-details.util.ts
new file mode 100644
index 00000000000..45d8d44dba0
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/get-agent-inbox-sender-details.util.ts
@@ -0,0 +1,22 @@
+import { type AgentInboxSender } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-inbox-sender.type';
+
+type AgentInboxSenderDetails = {
+ key: string;
+ applicationId: string | null;
+ description: string;
+};
+
+export const getAgentInboxSenderDetails = (
+ sender: AgentInboxSender,
+): AgentInboxSenderDetails =>
+ sender.type === 'application'
+ ? {
+ key: `application:${sender.application.id}`,
+ applicationId: sender.application.id,
+ description: `The "${sender.application.name}" application`,
+ }
+ : {
+ key: `workflow:${sender.workflowId}`,
+ applicationId: null,
+ description: `The "${sender.workflowName}" workflow`,
+ };
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/is-unique-violation-error.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/is-unique-violation-error.util.ts
new file mode 100644
index 00000000000..e371d230d46
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/is-unique-violation-error.util.ts
@@ -0,0 +1,11 @@
+import { QueryFailedError } from 'typeorm';
+
+import { POSTGRESQL_ERROR_CODES } from 'src/engine/api/graphql/workspace-query-runner/constants/postgres-error-codes.constants';
+import { type QueryFailedErrorWithCode } from 'src/engine/api/graphql/workspace-query-runner/utils/workspace-query-runner-graphql-api-exception-handler.util';
+import { isDuplicateEntryError } from 'src/engine/twenty-orm/utils/is-duplicate-entry-error.util';
+
+export const isUniqueViolationError = (error: unknown): boolean =>
+ isDuplicateEntryError(error) ||
+ (error instanceof QueryFailedError &&
+ (error as QueryFailedErrorWithCode).code ===
+ POSTGRESQL_ERROR_CODES.UNIQUE_VIOLATION);
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/ai-history.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/ai-history.module.ts
index 9e3acb2974b..2d604c0c939 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/ai-history.module.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/ai-history.module.ts
@@ -1,5 +1,7 @@
import { AGENT_HISTORY_OBJECT_NAMES } from 'src/engine/metadata-modules/ai/ai-history/constants/agent-history-object-names.constant';
import { Module } from '@nestjs/common';
+import { AgentConversationWriterService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service';
+import { AgentHistoryTransactionService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-history-transaction.service';
import { AgentHistoryWorkspaceStorageService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-history-workspace-storage.service';
import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
import { getAgentHistoryRepositoryToken } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
@@ -16,7 +18,16 @@ const REPOSITORY_PROVIDERS = AGENT_HISTORY_OBJECT_NAMES.map((objectName) => ({
}));
@Module({
- providers: [AgentHistoryWorkspaceStorageService, ...REPOSITORY_PROVIDERS],
- exports: [AgentHistoryWorkspaceStorageService, ...REPOSITORY_PROVIDERS],
+ providers: [
+ AgentHistoryWorkspaceStorageService,
+ AgentHistoryTransactionService,
+ AgentConversationWriterService,
+ ...REPOSITORY_PROVIDERS,
+ ],
+ exports: [
+ AgentHistoryWorkspaceStorageService,
+ AgentConversationWriterService,
+ ...REPOSITORY_PROVIDERS,
+ ],
})
export class AgentHistoryModule {}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service.ts
new file mode 100644
index 00000000000..3a896a0e494
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service.ts
@@ -0,0 +1,124 @@
+import { Injectable } from '@nestjs/common';
+
+import { randomUUID } from 'node:crypto';
+
+import { type ExtendedUIMessagePart } from 'twenty-shared/ai';
+import { isDefined } from 'twenty-shared/utils';
+import { IsNull } from 'typeorm';
+
+import { type AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';
+import { type AgentTurnEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-turn.entity';
+import { mapUIMessagePartsToPersistedDBParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ui-message-parts-to-persisted-db-parts.util';
+import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
+import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
+import { AgentHistoryTransactionService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-history-transaction.service';
+import {
+ AiException,
+ AiExceptionCode,
+} from 'src/engine/metadata-modules/ai/ai.exception';
+
+@Injectable()
+export class AgentConversationWriterService {
+ constructor(
+ @InjectAgentHistoryRepository('agentTurn')
+ private readonly turnRepository: AgentHistoryRepository<AgentTurnEntity>,
+ private readonly transactionService: AgentHistoryTransactionService,
+ ) {}
+
+ async insertTurn({
+ workspaceId,
+ threadId,
+ agentId,
+ id,
+ }: {
+ workspaceId: string;
+ threadId: string;
+ agentId: string | null;
+ id?: string;
+ }): Promise<string> {
+ const turnInsertResult = await this.turnRepository.insert(workspaceId, {
+ ...(isDefined(id) ? { id } : {}),
+ threadId,
+ agentId,
+ });
+
+ return (id ?? turnInsertResult.identifiers[0].id) as string;
+ }
+
+ // The message and its parts are written together, so a message that
+ // exists is complete. A message that awaits an answer also takes the
+ // thread's single pending slot in the same write, and fails if another
+ // message holds it.
+ async insertMessage({
+ workspaceId,
+ id,
+ threadId,
+ turnId,
+ role,
+ agentId,
+ senderUserWorkspaceId,
+ senderApplicationId,
+ isHidden,
+ isAwaitingAnswer,
+ processedAt,
+ parts,
+ }: {
+ workspaceId: string;
+ id?: string;
+ threadId: string;
+ turnId: string;
+ role: AgentMessageRole;
+ agentId: string | null;
+ senderUserWorkspaceId: string | null;
+ senderApplicationId?: string | null;
+ isHidden?: boolean;
+ isAwaitingAnswer?: boolean;
+ processedAt?: Date;
+ parts: ExtendedUIMessagePart[];
+ }): Promise<string> {
+ const messageId = id ?? randomUUID();
+
+ await this.transactionService.run(workspaceId, async (scope) => {
+ await scope.insert('agentMessage', {
+ id: messageId,
+ threadId,
+ turnId,
+ role,
+ agentId,
+ processedAt: (processedAt ?? new Date()).toISOString(),
+ ...(isDefined(senderUserWorkspaceId) ? { senderUserWorkspaceId } : {}),
+ ...(isDefined(senderApplicationId) ? { senderApplicationId } : {}),
+ ...(isDefined(isHidden) ? { isHidden } : {}),
+ });
+
+ const dbParts = mapUIMessagePartsToPersistedDBParts(
+ parts,
+ messageId,
+ workspaceId,
+ );
+
+ if (dbParts.length > 0) {
+ await scope.insert('agentMessagePart', dbParts);
+ }
+
+ if (!isAwaitingAnswer) {
+ return;
+ }
+
+ const claimedThreadCount = await scope.update(
+ 'agentChatThread',
+ { id: threadId, pendingQuestionMessageId: IsNull() },
+ { pendingQuestionMessageId: messageId },
+ );
+
+ if (claimedThreadCount === 0) {
+ throw new AiException(
+ 'The conversation is waiting for an answer to an earlier question',
+ AiExceptionCode.THREAD_AWAITING_ANSWER,
+ );
+ }
+ });
+
+ return messageId;
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-history-transaction.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-history-transaction.service.ts
new file mode 100644
index 00000000000..373bbdcd119
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/services/agent-history-transaction.service.ts
@@ -0,0 +1,65 @@
+import { Injectable } from '@nestjs/common';
+
+import { AgentHistoryWorkspaceStorageService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-history-workspace-storage.service';
+import { type AgentHistoryObjectName } from 'src/engine/metadata-modules/ai/ai-history/types/agent-history-object-name.type';
+import { type AgentHistoryTransactionScope } from 'src/engine/metadata-modules/ai/ai-history/types/agent-history-transaction-scope.type';
+import { addAgentMessageSenderWorkspaceMember } from 'src/engine/metadata-modules/ai/ai-history/utils/add-agent-message-sender-workspace-member.util';
+import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
+import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
+
+@Injectable()
+export class AgentHistoryTransactionService {
+ constructor(
+ private readonly storageService: AgentHistoryWorkspaceStorageService,
+ private readonly workspaceOrmManager: WorkspaceOrmManager,
+ ) {}
+
+ run<TResult>(
+ workspaceId: string,
+ work: (scope: AgentHistoryTransactionScope) => Promise<TResult>,
+ ): Promise<TResult> {
+ return this.storageService.run(workspaceId, (context) =>
+ this.workspaceOrmManager.executeInWorkspaceContext(
+ () =>
+ this.workspaceOrmManager.runInWorkspaceTransaction(
+ (transactionScope) => {
+ const getRepository = (name: AgentHistoryObjectName) =>
+ transactionScope.getRepository(
+ name,
+ { shouldBypassPermissionChecks: true },
+ { shouldSkipEventEmission: true },
+ );
+
+ return work({
+ insert: async (name, values) => {
+ await getRepository(name).insert(
+ name === 'agentMessage'
+ ? await addAgentMessageSenderWorkspaceMember(
+ values,
+ workspaceId,
+ context,
+ )
+ : values,
+ );
+ },
+ update: async (name, where, values) => {
+ const result = await getRepository(name)
+ .createQueryBuilder()
+ .withDeleted()
+ .where(where)
+ .update()
+ .set(values)
+ .returning(['id'])
+ .execute();
+
+ return result.generatedMaps.length;
+ },
+ });
+ },
+ ),
+ buildSystemAuthContext(workspaceId),
+ { lite: true },
+ ),
+ );
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/types/agent-history-transaction-scope.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/types/agent-history-transaction-scope.type.ts
new file mode 100644
index 00000000000..2115c5aee7a
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/types/agent-history-transaction-scope.type.ts
@@ -0,0 +1,15 @@
+import { type ObjectLiteral } from 'typeorm';
+
+import { type AgentHistoryObjectName } from 'src/engine/metadata-modules/ai/ai-history/types/agent-history-object-name.type';
+
+export type AgentHistoryTransactionScope = {
+ insert: (
+ name: AgentHistoryObjectName,
+ values: ObjectLiteral | ObjectLiteral[],
+ ) => Promise<void>;
+ update: (
+ name: AgentHistoryObjectName,
+ where: ObjectLiteral,
+ values: ObjectLiteral,
+ ) => Promise<number>;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai.exception.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai.exception.ts
index 0f3c9a1c1f8..b6e07187049 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai.exception.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai.exception.ts
@@ -33,6 +33,7 @@ export enum AiExceptionCode {
INVALID_EVALUATION_REQUEST = 'INVALID_EVALUATION_REQUEST',
TOOL_CALL_RESOLUTION_FORBIDDEN = 'TOOL_CALL_RESOLUTION_FORBIDDEN',
THREAD_AWAITING_WORKFLOW_INPUT = 'THREAD_AWAITING_WORKFLOW_INPUT',
+ THREAD_AWAITING_ANSWER = 'THREAD_AWAITING_ANSWER',
}
const getAiExceptionUserFriendlyMessage = (code: AiExceptionCode) => {
@@ -93,6 +94,8 @@ const getAiExceptionUserFriendlyMessage = (code: AiExceptionCode) => {
return msg`You are not allowed to answer this request.`;
case AiExceptionCode.THREAD_AWAITING_WORKFLOW_INPUT:
return msg`This workflow is waiting for an answer. Answer it before sending a message.`;
+ case AiExceptionCode.THREAD_AWAITING_ANSWER:
+ return msg`This conversation is waiting for an answer to an earlier request.`;
default:
assertUnreachable(code);
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/utils/ai-graphql-api-exception-handler.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/utils/ai-graphql-api-exception-handler.util.ts
index 63ceaf62917..949fe3efad4 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/utils/ai-graphql-api-exception-handler.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/utils/ai-graphql-api-exception-handler.util.ts
@@ -36,6 +36,7 @@ export const aiGraphqlApiExceptionHandler = (error: Error) => {
case AiExceptionCode.AGENT_ALREADY_EXISTS:
case AiExceptionCode.NO_FAILED_TURN_TO_RETRY:
case AiExceptionCode.THREAD_AWAITING_WORKFLOW_INPUT:
+ case AiExceptionCode.THREAD_AWAITING_ANSWER:
throw new ConflictError(error);
case AiExceptionCode.AGENT_IS_STANDARD:
case AiExceptionCode.ROLE_CANNOT_BE_ASSIGNED_TO_AGENTS:
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-feature-flags.util.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-feature-flags.util.ts
index 97e52dd3c3d..f80c7dd43a2 100644
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-feature-flags.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-feature-flags.util.ts
@@ -13,6 +13,7 @@ const DEFAULT_SEEDED_FEATURE_FLAGS: Partial<Record<FeatureFlagKey, boolean>> = {
[FeatureFlagKey.IS_CONVERSATIONS_TAB_ENABLED]: false,
[FeatureFlagKey.IS_VALIDATION_RULES_ENABLED]: true,
[FeatureFlagKey.IS_RECORD_LEVEL_SHARING_ENABLED]: false,
+ [FeatureFlagKey.IS_WORKFLOW_SEND_CHAT_MESSAGE_ENABLED]: true,
};
type SeedFeatureFlagsArgs = {
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-agent-chat-pending-input.workspace-service.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-agent-chat-pending-input.workspace-service.ts
index 7385ef21085..dab66c303a3 100644
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-agent-chat-pending-input.workspace-service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-agent-chat-pending-input.workspace-service.ts
@@ -3,7 +3,6 @@ import { Injectable } from '@nestjs/common';
import {
ASK_QUESTIONS_TOOL_NAME,
type AskQuestionItem,
- type ExtendedUIMessagePart,
PROPOSE_EMAIL_TOOL_NAME,
type ProposedEmail,
REQUEST_FORM_TOOL_NAME,
@@ -17,23 +16,19 @@ import {
RecordShareRowCause,
} from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
-import { type QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
import { v5 } from 'uuid';
import { RecordShareStorageService } from 'src/engine/core-modules/record-share/services/record-share-storage.service';
-import { type AgentMessagePartEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message-part.entity';
import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';
-import { type AgentTurnEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-turn.entity';
import { PAUSING_TOOLS } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/pausing-tools.constant';
import { mapAiStepsToUiMessageParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ai-steps-to-ui-message-parts.util';
-import { mapUIMessagePartsToDBParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/mapUIMessagePartsToDBParts';
import { createAskQuestionsTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/ask-questions.tool';
import { createProposeEmailTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/propose-email.tool';
import { createRequestFormTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/request-form.tool';
import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
+import { AgentConversationWriterService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service';
import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
-import { type AgentMessageWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message.workspace-entity';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
import { AGENT_CHAT_PENDING_INPUT_THREAD_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/constants/agent-chat-seeds.constant';
import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
@@ -314,12 +309,7 @@ export class DevSeederAgentChatPendingInputWorkspaceService {
constructor(
@InjectAgentHistoryRepository('agentChatThread')
private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,
- @InjectAgentHistoryRepository('agentTurn')
- private readonly turnRepository: AgentHistoryRepository<AgentTurnEntity>,
- @InjectAgentHistoryRepository('agentMessage')
- private readonly messageRepository: AgentHistoryRepository<AgentMessageWorkspaceEntity>,
- @InjectAgentHistoryRepository('agentMessagePart')
- private readonly messagePartRepository: AgentHistoryRepository<AgentMessagePartEntity>,
+ private readonly conversationWriterService: AgentConversationWriterService,
private readonly recordShareStorageService: RecordShareStorageService,
private readonly workspaceCacheService: WorkspaceCacheService,
) {}
@@ -383,17 +373,20 @@ export class DevSeederAgentChatPendingInputWorkspaceService {
const questionTurnId = seedId('questionTurn');
- await this.turnRepository.insert(workspaceId, {
+ await this.conversationWriterService.insertTurn({
+ workspaceId,
id: questionTurnId,
threadId,
+ agentId: null,
});
- await this.insertMessage({
+ await this.conversationWriterService.insertMessage({
workspaceId,
id: seedId('promptMessage'),
threadId,
turnId: questionTurnId,
role: AgentMessageRole.USER,
+ agentId: null,
senderUserWorkspaceId: askedBy.userWorkspaceId,
parts: [{ type: 'text', text: conversation.prompt }],
});
@@ -411,12 +404,13 @@ export class DevSeederAgentChatPendingInputWorkspaceService {
})
: undefined;
- await this.insertMessage({
+ await this.conversationWriterService.insertMessage({
workspaceId,
id: seedId('assistantMessage'),
threadId,
turnId: questionTurnId,
role: AgentMessageRole.ASSISTANT,
+ agentId: null,
senderUserWorkspaceId: null,
parts: mapAiStepsToUiMessageParts([
{
@@ -451,68 +445,36 @@ export class DevSeederAgentChatPendingInputWorkspaceService {
const answerTurnId = seedId('answerTurn');
- await this.turnRepository.insert(workspaceId, {
+ await this.conversationWriterService.insertTurn({
+ workspaceId,
id: answerTurnId,
threadId,
+ agentId: null,
});
- await this.insertMessage({
+ await this.conversationWriterService.insertMessage({
workspaceId,
id: seedId('answerMessage'),
threadId,
turnId: answerTurnId,
role: AgentMessageRole.USER,
+ agentId: null,
senderUserWorkspaceId: askedBy.userWorkspaceId,
parts: [{ type: 'text', text: completion.answerText }],
});
- await this.insertMessage({
+ await this.conversationWriterService.insertMessage({
workspaceId,
id: seedId('replyMessage'),
threadId,
turnId: answerTurnId,
role: AgentMessageRole.ASSISTANT,
+ agentId: null,
senderUserWorkspaceId: null,
parts: [{ type: 'text', text: conversation.answer.reply }],
});
}
- private async insertMessage({
- workspaceId,
- id,
- threadId,
- turnId,
- role,
- senderUserWorkspaceId,
- parts,
- }: {
- workspaceId: string;
- id: string;
- threadId: string;
- turnId: string;
- role: AgentMessageRole;
- senderUserWorkspaceId: string | null;
- parts: ExtendedUIMessagePart[];
- }): Promise<void> {
- await this.messageRepository.insert(workspaceId, {
- id,
- threadId,
- turnId,
- role,
- processedAt: new Date().toISOString(),
- ...(isDefined(senderUserWorkspaceId) ? { senderUserWorkspaceId } : {}),
- });
-
- await this.messagePartRepository.insert(
- workspaceId,
- mapUIMessagePartsToDBParts(
- parts,
- id,
- workspaceId,
- ) as QueryDeepPartialEntity<AgentMessagePartEntity>[],
- );
- }
-
private async shareConversations(workspaceId: string): Promise<void> {
const { flatObjectMetadataMaps } =
await this.workspaceCacheService.getOrRecompute(workspaceId, [
diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service.ts
index 2d3f4b1a4f1..04cbd7fd9d9 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service.ts
@@ -11,6 +11,7 @@ import {
import { isDefined, isValidUuid } from 'twenty-shared/utils';
import {
IF_ELSE_BRANCH_POSITION_OFFSETS,
+ WORKFLOW_ACTION_FEATURE_FLAGS,
WorkflowActionType,
getFunctionInputFromInputSchema,
type StepIfElseBranch,
@@ -19,6 +20,7 @@ import { v4 } from 'uuid';
import { getFlatFieldsFromFlatObjectMetadata } from 'src/engine/api/graphql/workspace-schema-builder/utils/get-flat-fields-for-flat-object-metadata.util';
import { FindRecordsService } from 'src/engine/core-modules/record-crud/services/find-records.service';
+import { FeatureFlagService } from 'src/engine/core-modules/feature-flag/services/feature-flag.service';
import { type WorkflowStepPositionInput } from 'src/engine/core-modules/workflow/dtos/update-workflow-step-position.input';
import { WorkflowVersionCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-version-core-sync.service';
import { AiAgentRoleService } from 'src/engine/metadata-modules/ai/ai-agent-role/ai-agent-role.service';
@@ -87,6 +89,7 @@ export class WorkflowVersionStepOperationsWorkspaceService {
private readonly flatEntityMapsCacheService: WorkspaceManyOrAllFlatEntityMapsCacheService,
private readonly workflowVersionCoreSyncService: WorkflowVersionCoreSyncService,
private readonly findRecordsService: FindRecordsService,
+ private readonly featureFlagService: FeatureFlagService,
) {}
async runWorkflowVersionStepDeletionSideEffects({
@@ -179,6 +182,8 @@ export class WorkflowVersionStepOperationsWorkspaceService {
nextStepIds: [],
};
+ await this.assertActionTypeEnabled({ type, workspaceId });
+
switch (type) {
case WorkflowActionType.CODE: {
const logicFunctionId = id ?? v4();
@@ -333,6 +338,23 @@ export class WorkflowVersionStepOperationsWorkspaceService {
},
};
}
+ case WorkflowActionType.SEND_CHAT_MESSAGE: {
+ return {
+ builtStep: {
+ ...baseStep,
+ name: 'Send Chat Message',
+ type: WorkflowActionType.SEND_CHAT_MESSAGE,
+ settings: {
+ ...BASE_STEP_DEFINITION,
+ input: {
+ workspaceMemberId: '',
+ title: '',
+ text: '',
+ },
+ },
+ },
+ };
+ }
case WorkflowActionType.CREATE_CALENDAR_EVENT: {
return {
builtStep: {
@@ -713,6 +735,29 @@ export class WorkflowVersionStepOperationsWorkspaceService {
}
}
+ private async assertActionTypeEnabled({
+ type,
+ workspaceId,
+ }: {
+ type: WorkflowActionType;
+ workspaceId: string;
+ }) {
+ const featureFlag = WORKFLOW_ACTION_FEATURE_FLAGS[type];
+
+ if (
+ isDefined(featureFlag) &&
+ !(await this.featureFlagService.isFeatureEnabled(
+ featureFlag,
+ workspaceId,
+ ))
+ ) {
+ throw new WorkflowVersionStepException(
+ `WorkflowActionType '${type}' is not enabled`,
+ WorkflowVersionStepExceptionCode.INVALID_REQUEST,
+ );
+ }
+ }
+
async enrichFormStepResponse({
workspaceId,
step,
@@ -851,6 +896,8 @@ export class WorkflowVersionStepOperationsWorkspaceService {
y: step.position?.y ?? 0,
};
+ await this.assertActionTypeEnabled({ type: step.type, workspaceId });
+
switch (step.type) {
case WorkflowActionType.CODE: {
const newLogicFunction =
diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step.module.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step.module.ts
index 8be48a6f83b..1a4fe3bd171 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step.module.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step.module.ts
@@ -1,6 +1,7 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
+import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';
import { WorkflowVersionCoreModule } from 'src/engine/core-modules/workflow/workflow-version-core.module';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { AiAgentRoleModule } from 'src/engine/metadata-modules/ai/ai-agent-role/ai-agent-role.module';
@@ -28,6 +29,7 @@ import { RecordCrudModule } from 'src/engine/core-modules/record-crud/record-cru
LogicFunctionModule,
WorkflowCommonModule,
CodeStepBuildModule,
+ FeatureFlagModule,
AiAgentRoleModule,
AiAgentModule,
WorkspaceCacheModule,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/factories/workflow-action.factory.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/factories/workflow-action.factory.ts
index 3c76d530ee7..152a44f5524 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/factories/workflow-action.factory.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/factories/workflow-action.factory.ts
@@ -20,6 +20,7 @@ import { IteratorWorkflowAction } from 'src/modules/workflow/workflow-executor/w
import { LogicFunctionWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/logic-function/logic-function.workflow-action';
import { DraftEmailWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/draft-email.workflow-action';
import { SendEmailWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/send-email.workflow-action';
+import { SendChatMessageWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action';
import { CreateRecordWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/record-crud/create-record.workflow-action';
import { DeleteRecordWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/record-crud/delete-record.workflow-action';
import { FindRecordsWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/record-crud/find-records.workflow-action';
@@ -46,6 +47,7 @@ export class WorkflowActionFactory {
private readonly httpRequestWorkflowAction: HttpRequestWorkflowAction,
private readonly sendEmailWorkflowAction: SendEmailWorkflowAction,
private readonly draftEmailWorkflowAction: DraftEmailWorkflowAction,
+ private readonly sendChatMessageWorkflowAction: SendChatMessageWorkflowAction,
private readonly createCalendarEventWorkflowAction: CreateCalendarEventWorkflowAction,
private readonly aiAgentWorkflowAction: AiAgentWorkflowAction,
private readonly classifyWorkflowAction: ClassifyWorkflowAction,
@@ -63,6 +65,8 @@ export class WorkflowActionFactory {
return this.sendEmailWorkflowAction;
case WorkflowActionType.DRAFT_EMAIL:
return this.draftEmailWorkflowAction;
+ case WorkflowActionType.SEND_CHAT_MESSAGE:
+ return this.sendChatMessageWorkflowAction;
case WorkflowActionType.CREATE_CALENDAR_EVENT:
return this.createCalendarEventWorkflowAction;
case WorkflowActionType.CREATE_RECORD:
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/build-step-execution-key.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/build-step-execution-key.util.spec.ts
new file mode 100644
index 00000000000..ccaffb0eb56
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/build-step-execution-key.util.spec.ts
@@ -0,0 +1,70 @@
+import {
+ createMockCodeStep,
+ createMockIteratorStep,
+} from 'src/modules/workflow/workflow-executor/utils/create-mock-workflow-steps.util';
+import { buildStepExecutionKey } from 'src/modules/workflow/workflow-executor/utils/build-step-execution-key.util';
+
+const STEPS = [
+ createMockIteratorStep('outer', [], ['inner']),
+ createMockIteratorStep('inner', ['outer'], ['send']),
+ createMockCodeStep('send', ['inner']),
+ createMockCodeStep('after'),
+];
+
+const contextAt = (outerIndex: number, innerIndex: number) => ({
+ outer: { currentItemIndex: outerIndex, hasProcessedAllItems: false },
+ inner: { currentItemIndex: innerIndex, hasProcessedAllItems: false },
+});
+
+describe('buildStepExecutionKey', () => {
+ it('keeps the key of a step outside any iterator', () => {
+ expect(
+ buildStepExecutionKey({
+ stepId: 'after',
+ steps: STEPS,
+ context: contextAt(3, 2),
+ }),
+ ).toBe('after');
+ });
+
+ it('keeps the key when the same iteration runs the step again', () => {
+ expect(
+ buildStepExecutionKey({
+ stepId: 'send',
+ steps: STEPS,
+ context: contextAt(1, 2),
+ }),
+ ).toBe(
+ buildStepExecutionKey({
+ stepId: 'send',
+ steps: STEPS,
+ context: contextAt(1, 2),
+ }),
+ );
+ });
+
+ it.each([
+ [contextAt(1, 3), 'the inner iteration'],
+ [contextAt(2, 2), 'the outer iteration'],
+ ])('changes the key with %s', (context) => {
+ expect(
+ buildStepExecutionKey({ stepId: 'send', steps: STEPS, context }),
+ ).not.toBe(
+ buildStepExecutionKey({
+ stepId: 'send',
+ steps: STEPS,
+ context: contextAt(1, 2),
+ }),
+ );
+ });
+
+ it('names every enclosing iteration', () => {
+ expect(
+ buildStepExecutionKey({
+ stepId: 'send',
+ steps: STEPS,
+ context: contextAt(1, 2),
+ }),
+ ).toBe('send:inner=2:outer=1');
+ });
+});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/build-step-execution-key.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/build-step-execution-key.util.ts
new file mode 100644
index 00000000000..e07913c9618
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/build-step-execution-key.util.ts
@@ -0,0 +1,43 @@
+import { isNonEmptyArray } from 'twenty-shared/utils';
+
+import { isWorkflowIteratorAction } from 'src/modules/workflow/workflow-executor/workflow-actions/iterator/guards/is-workflow-iterator-action.guard';
+import { type WorkflowIteratorResult } from 'src/modules/workflow/workflow-executor/workflow-actions/iterator/types/workflow-iterator-result.type';
+import { getAllStepIdsInLoop } from 'src/modules/workflow/workflow-executor/workflow-actions/iterator/utils/get-all-step-ids-in-loop.util';
+import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
+
+// Identifies one execution of a step within a run: a retry keeps the key,
+// while each iteration of an enclosing iterator gets its own.
+export const buildStepExecutionKey = ({
+ stepId,
+ steps,
+ context,
+}: {
+ stepId: string;
+ steps: WorkflowAction[];
+ context: Record<string, unknown>;
+}): string => {
+ const iterationKeys = steps
+ .filter(isWorkflowIteratorAction)
+ .filter((iterator) => {
+ const { initialLoopStepIds } = iterator.settings.input;
+
+ return (
+ isNonEmptyArray(initialLoopStepIds) &&
+ getAllStepIdsInLoop({
+ iteratorStepId: iterator.id,
+ initialLoopStepIds,
+ steps,
+ }).includes(stepId)
+ );
+ })
+ .map((iterator) => {
+ const iteration = context[iterator.id] as
+ | WorkflowIteratorResult
+ | undefined;
+
+ return `${iterator.id}=${iteration?.currentItemIndex ?? 0}`;
+ })
+ .sort();
+
+ return [stepId, ...iterationKeys].join(':');
+};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts
index 78abf223094..222618cabb6 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts
@@ -1,7 +1,5 @@
import { Injectable } from '@nestjs/common';
-import { randomUUID } from 'node:crypto';
-
import { convertToModelMessages, type ModelMessage } from 'ai';
import {
type ExtendedUIMessage,
@@ -9,23 +7,19 @@ import {
REQUEST_FORM_TOOL_NAME,
type RequestFormToolInput,
} from 'twenty-shared/ai';
-import { isDefined } from 'twenty-shared/utils';
-import { type QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
-import { type AgentMessagePartEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message-part.entity';
import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';
-import { type AgentTurnEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-turn.entity';
import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
import { type AgentMessageWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message.workspace-entity';
import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';
import { finalizeDanglingToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/finalize-dangling-tool-parts.util';
import { mapAiStepsToUiMessageParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ai-steps-to-ui-message-parts.util';
import { mapDBPartsToUIMessageParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/mapDBPartsToUIMessageParts';
-import { mapUIMessagePartsToPersistedDBParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ui-message-parts-to-persisted-db-parts.util';
import { findAwaitingPausingToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/find-awaiting-pausing-tool-parts.util';
import { buildRequestFormPendingOutput } from 'src/engine/metadata-modules/ai/ai-chat/tools/request-form.tool';
import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
+import { AgentConversationWriterService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-conversation-writer.service';
import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
export type RecordedExecutionResult = {
@@ -45,12 +39,9 @@ export class WorkflowAgentConversationWorkspaceService {
constructor(
@InjectAgentHistoryRepository('agentChatThread')
private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,
- @InjectAgentHistoryRepository('agentTurn')
- private readonly turnRepository: AgentHistoryRepository<AgentTurnEntity>,
@InjectAgentHistoryRepository('agentMessage')
private readonly messageRepository: AgentHistoryRepository<AgentMessageWorkspaceEntity>,
- @InjectAgentHistoryRepository('agentMessagePart')
- private readonly messagePartRepository: AgentHistoryRepository<AgentMessagePartEntity>,
+ private readonly conversationWriterService: AgentConversationWriterService,
private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,
) {}
@@ -81,7 +72,7 @@ export class WorkflowAgentConversationWorkspaceService {
agentId,
});
- await this.insertMessage({
+ await this.conversationWriterService.insertMessage({
workspaceId,
threadId,
turnId,
@@ -124,13 +115,14 @@ export class WorkflowAgentConversationWorkspaceService {
agentId: null,
});
- const messageId = await this.insertMessage({
+ await this.conversationWriterService.insertMessage({
workspaceId,
threadId,
turnId,
role: AgentMessageRole.ASSISTANT,
agentId: null,
senderUserWorkspaceId: null,
+ isAwaitingAnswer: true,
parts: [
{
type: `tool-${REQUEST_FORM_TOOL_NAME}`,
@@ -141,12 +133,6 @@ export class WorkflowAgentConversationWorkspaceService {
} as ExtendedUIMessagePart,
],
});
-
- await this.threadRepository.update(
- workspaceId,
- { id: threadId },
- { pendingQuestionMessageId: messageId },
- );
}
// The answer is already the last message, so only the agent's reply is added
@@ -161,7 +147,11 @@ export class WorkflowAgentConversationWorkspaceService {
agentId: string | null;
executionResult: RecordedExecutionResult;
}): Promise<RecordedConversation> {
- const turnId = await this.insertTurn({ workspaceId, threadId, agentId });
+ const turnId = await this.conversationWriterService.insertTurn({
+ workspaceId,
+ threadId,
+ agentId,
+ });
const isAwaitingAnswer = await this.recordReply({
workspaceId,
@@ -221,33 +211,24 @@ export class WorkflowAgentConversationWorkspaceService {
return false;
}
- const messageId = await this.insertMessage({
+ const awaitingParts = findAwaitingPausingToolParts(replyParts);
+ const isAwaitingAnswer =
+ executionResult.isPaused === true &&
+ awaitingParts.length > 0 &&
+ awaitingParts.every(({ isAnswerable }) => isAnswerable);
+
+ await this.conversationWriterService.insertMessage({
workspaceId,
threadId,
turnId,
role: AgentMessageRole.ASSISTANT,
agentId,
senderUserWorkspaceId: null,
+ isAwaitingAnswer,
parts: replyParts,
});
- const awaitingParts = findAwaitingPausingToolParts(replyParts);
-
- if (
- executionResult.isPaused !== true ||
- awaitingParts.length === 0 ||
- !awaitingParts.every(({ isAnswerable }) => isAnswerable)
- ) {
- return false;
- }
-
- await this.threadRepository.update(
- workspaceId,
- { id: threadId },
- { pendingQuestionMessageId: messageId },
- );
-
- return true;
+ return isAwaitingAnswer;
}
private async openConversation({
@@ -269,7 +250,11 @@ export class WorkflowAgentConversationWorkspaceService {
});
const threadId = threadInsertResult.identifiers[0].id as string;
- const turnId = await this.insertTurn({ workspaceId, threadId, agentId });
+ const turnId = await this.conversationWriterService.insertTurn({
+ workspaceId,
+ threadId,
+ agentId,
+ });
await this.workflowRunWorkspaceService.setStepThreadId({
stepId,
@@ -280,66 +265,4 @@ export class WorkflowAgentConversationWorkspaceService {
return { threadId, turnId };
}
-
- private async insertTurn({
- workspaceId,
- threadId,
- agentId,
- }: {
- workspaceId: string;
- threadId: string;
- agentId: string | null;
- }): Promise<string> {
- const turnInsertResult = await this.turnRepository.insert(workspaceId, {
- threadId,
- agentId,
- });
-
- return turnInsertResult.identifiers[0].id as string;
- }
-
- private async insertMessage({
- workspaceId,
- threadId,
- turnId,
- role,
- agentId,
- senderUserWorkspaceId,
- parts,
- }: {
- workspaceId: string;
- threadId: string;
- turnId: string;
- role: AgentMessageRole;
- agentId: string | null;
- senderUserWorkspaceId: string | null;
- parts: ExtendedUIMessagePart[];
- }): Promise<string> {
- const messageId = randomUUID();
-
- await this.messageRepository.insert(workspaceId, {
- id: messageId,
- threadId,
- turnId,
- role,
- agentId,
- processedAt: new Date().toISOString(),
- ...(isDefined(senderUserWorkspaceId) ? { senderUserWorkspaceId } : {}),
- });
-
- const dbParts = mapUIMessagePartsToPersistedDBParts(
- parts,
- messageId,
- workspaceId,
- );
-
- if (dbParts.length > 0) {
- await this.messagePartRepository.insert(
- workspaceId,
- dbParts as QueryDeepPartialEntity<AgentMessagePartEntity>[],
- );
- }
-
- return messageId;
- }
}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/__tests__/send-chat-message.workflow-action.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/__tests__/send-chat-message.workflow-action.spec.ts
new file mode 100644
index 00000000000..b41d492c896
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/__tests__/send-chat-message.workflow-action.spec.ts
@@ -0,0 +1,172 @@
+import { WorkflowActionType } from 'twenty-shared/workflow';
+
+import { type WorkflowCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-core-sync.service';
+import { type AgentInboxService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.service';
+import { type WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
+import { WorkflowStepExecutorExceptionCode } from 'src/modules/workflow/workflow-executor/exceptions/workflow-step-executor.exception';
+import { createMockIteratorStep } from 'src/modules/workflow/workflow-executor/utils/create-mock-workflow-steps.util';
+import { SendChatMessageWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action';
+import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
+
+const WORKSPACE_ID = 'workspace-id';
+const WORKFLOW_RUN_ID = 'workflow-run-id';
+const WORKFLOW_ID = 'workflow-id';
+const WORKSPACE_MEMBER_ID = '20202020-2222-4222-8222-222222222222';
+
+const buildStep = (input: Record<string, unknown>): WorkflowAction =>
+ ({
+ id: 'step-1',
+ type: WorkflowActionType.SEND_CHAT_MESSAGE,
+ name: 'Send Chat Message',
+ valid: true,
+ settings: {
+ outputSchema: {},
+ errorHandlingOptions: {
+ retryOnFailure: { value: 0 },
+ continueOnFailure: { value: false },
+ },
+ input,
+ },
+ }) as WorkflowAction;
+
+describe('SendChatMessageWorkflowAction', () => {
+ const sendMessage = jest.fn();
+ const findWorkflowRun = jest.fn();
+ const findCoreWorkflowById = jest.fn();
+ let action: SendChatMessageWorkflowAction;
+
+ const execute = (input: Record<string, unknown>) =>
+ action.execute({
+ currentStepId: 'step-1',
+ steps: [buildStep(input)],
+ context: { trigger: { ownerId: WORKSPACE_MEMBER_ID, name: 'Acme' } },
+ runInfo: { workflowRunId: WORKFLOW_RUN_ID, workspaceId: WORKSPACE_ID },
+ });
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ sendMessage.mockResolvedValue({ threadId: 'thread-id' });
+ findWorkflowRun.mockResolvedValue({
+ id: WORKFLOW_RUN_ID,
+ coreWorkflowId: WORKFLOW_ID,
+ });
+ findCoreWorkflowById.mockResolvedValue({
+ id: WORKFLOW_ID,
+ name: 'New deals',
+ });
+
+ action = new SendChatMessageWorkflowAction(
+ { sendMessage } as unknown as AgentInboxService,
+ {
+ executeInWorkspaceContext: jest.fn((callback) => callback()),
+ getRepository: jest.fn().mockReturnValue({ findOne: findWorkflowRun }),
+ } as unknown as WorkspaceOrmManager,
+ { findCoreWorkflowById } as unknown as WorkflowCoreSyncService,
+ );
+ });
+
+ it('posts the resolved message in the run conversation of the member', async () => {
+ const output = await execute({
+ workspaceMemberId: '{{trigger.ownerId}}',
+ title: 'New deal: {{trigger.name}}',
+ text: '**{{trigger.name}}** just signed.',
+ });
+
+ expect(output).toEqual({ result: { threadId: 'thread-id' } });
+ expect(sendMessage).toHaveBeenCalledWith({
+ workspaceId: WORKSPACE_ID,
+ sender: {
+ type: 'workflow',
+ workflowId: WORKFLOW_ID,
+ workflowName: 'New deals',
+ },
+ input: {
+ workspaceMemberId: WORKSPACE_MEMBER_ID,
+ threadKey: WORKFLOW_RUN_ID,
+ idempotencyKey: 'step-1',
+ title: 'New deal: Acme',
+ text: '**Acme** just signed.',
+ },
+ });
+ });
+
+ it('sends each iteration once, even when two iterations say the same thing', async () => {
+ const input = {
+ workspaceMemberId: WORKSPACE_MEMBER_ID,
+ title: 'Daily digest',
+ text: 'Same message every time',
+ };
+ const steps = [
+ createMockIteratorStep('iterator', [], ['step-1']),
+ { ...buildStep(input), nextStepIds: ['iterator'] } as WorkflowAction,
+ ];
+ const runIteration = (currentItemIndex: number) =>
+ action.execute({
+ currentStepId: 'step-1',
+ steps,
+ context: {
+ iterator: { currentItemIndex, hasProcessedAllItems: false },
+ },
+ runInfo: { workflowRunId: WORKFLOW_RUN_ID, workspaceId: WORKSPACE_ID },
+ });
+
+ await runIteration(0);
+ await runIteration(0);
+ await runIteration(1);
+
+ const idempotencyKeys = sendMessage.mock.calls.map(
+ ([{ input: sentInput }]) => sentInput.idempotencyKey,
+ );
+
+ expect(idempotencyKeys).toEqual([
+ 'step-1:iterator=0',
+ 'step-1:iterator=0',
+ 'step-1:iterator=1',
+ ]);
+ });
+
+ it('titles the conversation with the step name when no title is set', async () => {
+ await execute({
+ workspaceMemberId: WORKSPACE_MEMBER_ID,
+ title: '',
+ text: 'Hello',
+ });
+
+ expect(sendMessage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ input: expect.objectContaining({ title: 'Send Chat Message' }),
+ }),
+ );
+ });
+
+ it('fails the step when the run has no core workflow', async () => {
+ findWorkflowRun.mockResolvedValue({
+ id: WORKFLOW_RUN_ID,
+ coreWorkflowId: null,
+ });
+
+ await expect(
+ execute({
+ workspaceMemberId: WORKSPACE_MEMBER_ID,
+ title: '',
+ text: 'Hello',
+ }),
+ ).rejects.toMatchObject({
+ code: WorkflowStepExecutorExceptionCode.INTERNAL_ERROR,
+ });
+ expect(sendMessage).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['no recipient', { workspaceMemberId: '', title: '', text: 'Hello' }],
+ [
+ 'no text',
+ { workspaceMemberId: WORKSPACE_MEMBER_ID, title: '', text: '' },
+ ],
+ ])('fails the step with %s', async (_, input) => {
+ await expect(execute(input)).rejects.toMatchObject({
+ code: WorkflowStepExecutorExceptionCode.INVALID_STEP_INPUT,
+ });
+ expect(sendMessage).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/guards/is-workflow-send-chat-message-action.guard.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/guards/is-workflow-send-chat-message-action.guard.ts
new file mode 100644
index 00000000000..f74e6ab2fd0
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/guards/is-workflow-send-chat-message-action.guard.ts
@@ -0,0 +1,11 @@
+import { WorkflowActionType } from 'twenty-shared/workflow';
+
+import {
+ type WorkflowAction,
+ type WorkflowSendChatMessageAction,
+} from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
+
+export const isWorkflowSendChatMessageAction = (
+ action: WorkflowAction,
+): action is WorkflowSendChatMessageAction =>
+ action.type === WorkflowActionType.SEND_CHAT_MESSAGE;
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message-action.module.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message-action.module.ts
new file mode 100644
index 00000000000..6f89def8281
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message-action.module.ts
@@ -0,0 +1,12 @@
+import { Module } from '@nestjs/common';
+
+import { WorkflowCoreModule } from 'src/engine/core-modules/workflow/workflow-core.module';
+import { AgentInboxModule } from 'src/engine/metadata-modules/ai/ai-chat/agent-inbox.module';
+import { SendChatMessageWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action';
+
+@Module({
+ imports: [AgentInboxModule, WorkflowCoreModule],
+ providers: [SendChatMessageWorkflowAction],
+ exports: [SendChatMessageWorkflowAction],
+})
+export class SendChatMessageActionModule {}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action.ts
new file mode 100644
index 00000000000..51db4de0479
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message.workflow-action.ts
@@ -0,0 +1,134 @@
+import { Injectable } from '@nestjs/common';
+
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined, isValidUuid, resolveInput } from 'twenty-shared/utils';
+
+import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/interfaces/workflow-action.interface';
+
+import { type WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workflow.entity';
+import { WorkflowCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-core-sync.service';
+import { AgentInboxService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.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 { type WorkflowRunWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
+import {
+ WorkflowStepExecutorException,
+ WorkflowStepExecutorExceptionCode,
+} from 'src/modules/workflow/workflow-executor/exceptions/workflow-step-executor.exception';
+import { type WorkflowActionInput } from 'src/modules/workflow/workflow-executor/types/workflow-action-input.type';
+import { type WorkflowActionOutput } from 'src/modules/workflow/workflow-executor/types/workflow-action-output.type';
+import { buildStepExecutionKey } from 'src/modules/workflow/workflow-executor/utils/build-step-execution-key.util';
+import { findStepOrThrow } from 'src/modules/workflow/workflow-executor/utils/find-step-or-throw.util';
+import { isWorkflowSendChatMessageAction } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/guards/is-workflow-send-chat-message-action.guard';
+import { type WorkflowSendChatMessageActionInput } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/workflow-send-chat-message-action-input.type';
+
+@Injectable()
+export class SendChatMessageWorkflowAction implements WorkflowAction {
+ constructor(
+ private readonly agentInboxService: AgentInboxService,
+ private readonly workspaceOrmManager: WorkspaceOrmManager,
+ private readonly workflowCoreSyncService: WorkflowCoreSyncService,
+ ) {}
+
+ async execute({
+ currentStepId,
+ steps,
+ context,
+ runInfo,
+ }: WorkflowActionInput): Promise<WorkflowActionOutput> {
+ const step = findStepOrThrow({ stepId: currentStepId, steps });
+
+ if (!isWorkflowSendChatMessageAction(step)) {
+ throw new WorkflowStepExecutorException(
+ 'Step is not a send chat message action',
+ WorkflowStepExecutorExceptionCode.INVALID_STEP_TYPE,
+ );
+ }
+
+ const { workspaceMemberId, title, text } = resolveInput(
+ step.settings.input,
+ context,
+ ) as WorkflowSendChatMessageActionInput;
+
+ if (!isValidUuid(workspaceMemberId)) {
+ throw new WorkflowStepExecutorException(
+ 'Recipient must be a workspace member',
+ WorkflowStepExecutorExceptionCode.INVALID_STEP_INPUT,
+ );
+ }
+
+ if (!isNonEmptyString(text)) {
+ throw new WorkflowStepExecutorException(
+ 'Text is required',
+ WorkflowStepExecutorExceptionCode.INVALID_STEP_INPUT,
+ );
+ }
+
+ const workflow = await this.findRunWorkflowOrThrow(runInfo);
+
+ // Each run gets its own conversation with the member, so every message
+ // a run sends reads as one exchange.
+ const { threadId } = await this.agentInboxService.sendMessage({
+ workspaceId: runInfo.workspaceId,
+ sender: {
+ type: 'workflow',
+ workflowId: workflow.id,
+ workflowName: isNonEmptyString(workflow.name)
+ ? workflow.name
+ : 'Untitled',
+ },
+ input: {
+ workspaceMemberId,
+ threadKey: runInfo.workflowRunId,
+ idempotencyKey: buildStepExecutionKey({
+ stepId: currentStepId,
+ steps,
+ context,
+ }),
+ title: isNonEmptyString(title) ? title : step.name,
+ text,
+ },
+ });
+
+ return { result: { threadId } };
+ }
+
+ // Every run carries the core workflow it was started from, which is the
+ // identity the executor bills and the conversation is attributed to.
+ private async findRunWorkflowOrThrow({
+ workflowRunId,
+ workspaceId,
+ }: WorkflowActionInput['runInfo']): Promise<
+ Pick<WorkflowEntity, 'id' | 'name'>
+ > {
+ const workflowRun =
+ await this.workspaceOrmManager.executeInWorkspaceContext(
+ () =>
+ this.workspaceOrmManager
+ .getRepository<WorkflowRunWorkspaceEntity>('workflowRun', {
+ shouldBypassPermissionChecks: true,
+ })
+ .findOne({
+ where: { id: workflowRunId },
+ select: ['id', 'coreWorkflowId'],
+ }),
+ buildSystemAuthContext(workspaceId),
+ );
+
+ const workflow = isDefined(workflowRun?.coreWorkflowId)
+ ? await this.workflowCoreSyncService.findCoreWorkflowById(
+ workspaceId,
+ workflowRun.coreWorkflowId,
+ )
+ : null;
+
+ if (!isDefined(workflow)) {
+ throw new WorkflowStepExecutorException(
+ 'Workflow run has no workflow',
+ WorkflowStepExecutorExceptionCode.INTERNAL_ERROR,
+ );
+ }
+
+ return workflow;
+ }
+}
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/workflow-send-chat-message-action-input.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/workflow-send-chat-message-action-input.type.ts
new file mode 100644
index 00000000000..d2e25d6b516
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/workflow-send-chat-message-action-input.type.ts
@@ -0,0 +1,5 @@
+export type WorkflowSendChatMessageActionInput = {
+ workspaceMemberId: string;
+ title: string;
+ text: string;
+};
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/workflow-send-chat-message-action-settings.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/workflow-send-chat-message-action-settings.type.ts
new file mode 100644
index 00000000000..4be61bdcf7c
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/workflow-send-chat-message-action-settings.type.ts
@@ -0,0 +1,7 @@
+import { type WorkflowSendChatMessageActionInput } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/workflow-send-chat-message-action-input.type';
+import { type BaseWorkflowActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action-settings.type';
+
+export type WorkflowSendChatMessageActionSettings =
+ BaseWorkflowActionSettings & {
+ input: WorkflowSendChatMessageActionInput;
+ };
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action-settings.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action-settings.type.ts
index ac21642cda3..e7c3002ccfd 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action-settings.type.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action-settings.type.ts
@@ -10,6 +10,7 @@ import { type WorkflowIfElseActionSettings } from 'src/modules/workflow/workflow
import { type WorkflowIteratorActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/iterator/types/workflow-iterator-action-settings.type';
import { type WorkflowLogicFunctionActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/logic-function/types/workflow-logic-function-action-settings.type';
import { type WorkflowSendEmailActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/types/workflow-send-email-action-settings.type';
+import { type WorkflowSendChatMessageActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/workflow-send-chat-message-action-settings.type';
import {
type WorkflowCreateRecordActionSettings,
type WorkflowDeleteRecordActionSettings,
@@ -38,6 +39,7 @@ export type WithExpectedOutputSchema = {
export type WorkflowActionSettings =
| WorkflowLogicFunctionActionSettings
| WorkflowSendEmailActionSettings
+ | WorkflowSendChatMessageActionSettings
| WorkflowCreateCalendarEventActionSettings
| WorkflowCodeActionSettings
| WorkflowCreateRecordActionSettings
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type.ts
index db9471bf2ac..9e26c9722db 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type.ts
@@ -12,6 +12,7 @@ import { type WorkflowIfElseActionSettings } from 'src/modules/workflow/workflow
import { type WorkflowIteratorActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/iterator/types/workflow-iterator-action-settings.type';
import { type WorkflowLogicFunctionActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/logic-function/types/workflow-logic-function-action-settings.type';
import { type WorkflowSendEmailActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/types/workflow-send-email-action-settings.type';
+import { type WorkflowSendChatMessageActionSettings } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/types/workflow-send-chat-message-action-settings.type';
import {
type WorkflowCreateRecordActionSettings,
type WorkflowDeleteRecordActionSettings,
@@ -55,6 +56,11 @@ export type WorkflowDraftEmailAction = BaseWorkflowAction & {
settings: WorkflowSendEmailActionSettings;
};
+export type WorkflowSendChatMessageAction = BaseWorkflowAction & {
+ type: WorkflowActionType.SEND_CHAT_MESSAGE;
+ settings: WorkflowSendChatMessageActionSettings;
+};
+
export type WorkflowCreateCalendarEventAction = BaseWorkflowAction & {
type: WorkflowActionType.CREATE_CALENDAR_EVENT;
settings: WorkflowCreateCalendarEventActionSettings;
@@ -139,6 +145,7 @@ export type WorkflowAction =
| WorkflowLogicFunctionAction
| WorkflowSendEmailAction
| WorkflowDraftEmailAction
+ | WorkflowSendChatMessageAction
| WorkflowCreateCalendarEventAction
| WorkflowCreateRecordAction
| WorkflowUpdateRecordAction
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-executor.module.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-executor.module.ts
index ec241f4ddef..b49d16ecc1d 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-executor.module.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-executor.module.ts
@@ -22,6 +22,7 @@ import { IfElseActionModule } from 'src/modules/workflow/workflow-executor/workf
import { IteratorActionModule } from 'src/modules/workflow/workflow-executor/workflow-actions/iterator/iterator-action.module';
import { LogicFunctionActionModule } from 'src/modules/workflow/workflow-executor/workflow-actions/logic-function/logic-function-action.module';
import { MailSenderActionModule } from 'src/modules/workflow/workflow-executor/workflow-actions/mail-sender/mail-sender-action.module';
+import { SendChatMessageActionModule } from 'src/modules/workflow/workflow-executor/workflow-actions/send-chat-message/send-chat-message-action.module';
import { RecordCRUDActionModule } from 'src/modules/workflow/workflow-executor/workflow-actions/record-crud/record-crud-action.module';
import { WorkflowExecutorWorkspaceService } from 'src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service';
import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.module';
@@ -47,6 +48,7 @@ import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow
FeatureFlagModule,
HttpRequestActionModule,
MailSenderActionModule,
+ SendChatMessageActionModule,
CreateCalendarEventActionModule,
MetricsModule,
UsageLimitModule,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts
index 681594c8ea9..9c7dbc9ddea 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts
@@ -6,11 +6,16 @@ import { isDefined } from 'twenty-shared/utils';
import {
getWorkflowRunContext,
StepStatus,
+ WORKFLOW_ACTION_FEATURE_FLAGS,
WorkflowRunStepInfo,
WorkflowRunStepInfos,
type WorkflowRunStepLog,
} from 'twenty-shared/workflow';
+import {
+ WorkflowStepExecutorException,
+ WorkflowStepExecutorExceptionCode,
+} from 'src/modules/workflow/workflow-executor/exceptions/workflow-step-executor.exception';
import { BillingUsageService } from 'src/engine/core-modules/billing/services/billing-usage.service';
import { UsageLimitQuotaService } from 'src/engine/core-modules/usage-limit/services/usage-limit-quota.service';
import { isUsageRefusedError } from 'src/engine/core-modules/billing/utils/is-usage-refused-error.util';
@@ -380,6 +385,29 @@ export class WorkflowExecutorWorkspaceService {
});
}
+ private async assertActionTypeEnabled({
+ type,
+ workspaceId,
+ }: {
+ type: WorkflowAction['type'];
+ workspaceId: string;
+ }): Promise<void> {
+ const featureFlag = WORKFLOW_ACTION_FEATURE_FLAGS[type];
+
+ if (
+ isDefined(featureFlag) &&
+ !(await this.featureFlagService.isFeatureEnabled(
+ featureFlag,
+ workspaceId,
+ ))
+ ) {
+ throw new WorkflowStepExecutorException(
+ `WorkflowActionType '${type}' is not enabled`,
+ WorkflowStepExecutorExceptionCode.INVALID_STEP_TYPE,
+ );
+ }
+ }
+
private async getNodeRunRefusal({
workspaceId,
billingSpenders,
@@ -546,6 +574,8 @@ export class WorkflowExecutorWorkspaceService {
});
try {
+ await this.assertActionTypeEnabled({ type: step.type, workspaceId });
+
// A resumed step's quota was checked when it first ran and paused.
const nodeRunRefusal = isDefined(resumedThreadId)
? undefined
diff --git a/packages/twenty-server/src/modules/workflow/workflow-tools/tools/create-complete-workflow.tool.ts b/packages/twenty-server/src/modules/workflow/workflow-tools/tools/create-complete-workflow.tool.ts
index 16c262a38b9..58f1a11984f 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-tools/tools/create-complete-workflow.tool.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-tools/tools/create-complete-workflow.tool.ts
@@ -1,5 +1,6 @@
import { isDefined } from 'twenty-shared/utils';
import {
+ WORKFLOW_ACTION_FEATURE_FLAGS,
workflowActionSchema,
WorkflowActionType,
workflowTriggerSchema,
@@ -223,6 +224,17 @@ const assertStepTypesAreSupported = (steps: WorkflowAction[]): void => {
WorkflowVersionStepExceptionCode.INVALID_REQUEST,
);
}
+
+ const flagGatedStep = steps.find((step) =>
+ isDefined(WORKFLOW_ACTION_FEATURE_FLAGS[step.type]),
+ );
+
+ if (isDefined(flagGatedStep)) {
+ throw new WorkflowVersionStepException(
+ `${flagGatedStep.type} steps cannot be created via create_complete_workflow. Use create_workflow_version_step instead.`,
+ WorkflowVersionStepExceptionCode.INVALID_REQUEST,
+ );
+ }
};
const findInitialDraftCoreVersionIdOrThrow = async ({
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
new file mode 100644
index 00000000000..289ebe0d797
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/ai-chat-inbox-message.integration-spec.ts
@@ -0,0 +1,365 @@
+import { parse } from 'graphql';
+import { answerToolCall } from 'test/integration/graphql/suites/workflow/utils/answer-tool-call.util';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import {
+ type ApplicationWithResources,
+ setupApplicationWithResources,
+} from 'test/integration/metadata/suites/application/utils/setup-application-with-resources.util';
+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { destroyAgentChatThread } from 'test/integration/utils/destroy-agent-chat-thread.util';
+import { generateApplicationTokenPair } from 'test/integration/utils/generate-application-token-pair.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { SystemPermissionFlag } from 'twenty-shared/constants';
+import { v4 as uuidv4 } from 'uuid';
+
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+import { type MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
+import { getQueueToken } from 'src/engine/core-modules/message-queue/utils/get-queue-token.util';
+import { buildInboxMessageIds } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-inbox-message-ids.util';
+import { type AiModelRegistryService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';
+import { type WorkspaceRepository } from 'src/engine/twenty-orm/repository/workspace-repository';
+import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
+import { type WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
+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 { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
+
+const schema = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);
+
+const SEND_INBOX_MESSAGE = parse(`
+ mutation SendInboxMessage($input: SendInboxMessageInput!) {
+ sendInboxMessage(input: $input) {
+ threadId
+ }
+ }
+`);
+
+const QUESTIONS = [
+ {
+ header: 'Share',
+ question: 'Do you want to share it with the other attendees?',
+ options: [{ label: 'Draft a recap email' }, { label: 'Not now' }],
+ },
+];
+
+// The model is not called here: the resumed stream is only checked for being
+// queued.
+describe('Sending an inbox message as an application', () => {
+ const input = {
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ threadKey: `inbox-thread-${uuidv4()}`,
+ idempotencyKey: 'first-recording',
+ title: 'Your first call recording is ready',
+ text: 'Your first call was recorded: **Weekly sync**.',
+ toolCall: { toolName: 'ask_questions', input: { questions: QUESTIONS } },
+ };
+ let application: ApplicationWithResources;
+ let applicationToken: string;
+ let threadId: string;
+ let enqueueStream: jest.SpyInstance;
+ const spies: jest.SpyInstance[] = [];
+
+ const sendInboxMessage = (
+ token: string,
+ overrides: Record<string, unknown> = {},
+ ) =>
+ makeMetadataApiRequest(
+ {
+ query: SEND_INBOX_MESSAGE,
+ variables: { input: { ...input, ...overrides } },
+ },
+ token,
+ );
+
+ const readPendingQuestionMessageId = async () =>
+ (
+ await global.testDataSource.query(
+ `SELECT "pendingQuestionMessageId" FROM "${schema}"."agentChatThread" WHERE id = $1`,
+ [threadId],
+ )
+ )[0].pendingQuestionMessageId as string | null;
+
+ const readMessages = (id: string) =>
+ global.testDataSource.query(
+ `SELECT id, role, "isHidden", "senderUserWorkspaceId", "senderApplicationId"
+ FROM "${schema}"."agentMessage" WHERE "threadId" = $1
+ ORDER BY "processedAt" ASC`,
+ [id],
+ );
+
+ beforeAll(async () => {
+ application = await setupApplicationWithResources({
+ name: 'Inbox Application',
+ permissionFlagUniversalIdentifiers: [SystemPermissionFlag.AI],
+ });
+ jest.useRealTimers();
+
+ const tokenPair = await generateApplicationTokenPair({
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ applicationId: application.id,
+ });
+
+ applicationToken = tokenPair.applicationAccessToken.token;
+
+ const aiModelRegistryService =
+ getAppProviderByClassName<AiModelRegistryService>(
+ 'AiModelRegistryService',
+ );
+
+ spies.push(
+ jest
+ .spyOn(aiModelRegistryService, 'getAvailableModels')
+ .mockReturnValue([{ modelId: 'test-model' }] as never),
+ jest
+ .spyOn(aiModelRegistryService, 'validateModelAvailability')
+ .mockReturnValue(undefined as never),
+ );
+ enqueueStream = jest
+ .spyOn(
+ global.app.get<MessageQueueService>(
+ getQueueToken(MessageQueue.aiStreamQueue),
+ ),
+ 'add',
+ )
+ .mockResolvedValue(undefined as never);
+ spies.push(enqueueStream);
+
+ const response = await sendInboxMessage(applicationToken);
+
+ if (response.body.errors !== undefined) {
+ throw new Error(
+ `Could not send the inbox message: ${JSON.stringify(response.body.errors)}`,
+ );
+ }
+
+ threadId = response.body.data.sendInboxMessage.threadId;
+ });
+
+ afterAll(async () => {
+ spies.forEach((spy) => spy.mockRestore());
+
+ if (threadId !== undefined) {
+ await makeMetadataApiRequest({
+ query: parse(
+ 'mutation Stop($threadId: UUID!) { stopAgentChatStream(threadId: $threadId) }',
+ ),
+ variables: { threadId },
+ });
+ await destroyAgentChatThread({ threadId });
+ }
+
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: application.universalIdentifier,
+ });
+ });
+
+ it('rejects a member session', async () => {
+ const response = await sendInboxMessage(APPLE_JANE_ADMIN_ACCESS_TOKEN);
+
+ expect(response.body.errors).toBeDefined();
+ });
+
+ it('opens a conversation for the member that starts with the application message', async () => {
+ const [thread] = await global.testDataSource.query(
+ `SELECT title, "workspaceMemberId", "pendingQuestionMessageId"
+ FROM "${schema}"."agentChatThread" WHERE id = $1`,
+ [threadId],
+ );
+ const messages = await readMessages(threadId);
+
+ expect(thread).toMatchObject({
+ title: input.title,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ });
+ expect(messages).toEqual([
+ expect.objectContaining({
+ role: 'user',
+ isHidden: true,
+ senderUserWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JANE,
+ senderApplicationId: null,
+ }),
+ expect.objectContaining({
+ role: 'assistant',
+ isHidden: false,
+ senderApplicationId: application.id,
+ }),
+ ]);
+ expect(thread.pendingQuestionMessageId).toBe(messages[1].id);
+ });
+
+ it('returns the same conversation when sent again with the same key', async () => {
+ const response = await sendInboxMessage(applicationToken);
+
+ expect(response.body.errors).toBeUndefined();
+ expect(response.body.data.sendInboxMessage.threadId).toBe(threadId);
+ expect(await readMessages(threadId)).toHaveLength(2);
+ });
+
+ it('refuses another question while an earlier one waits on the member', async () => {
+ const pendingQuestionMessageId = await readPendingQuestionMessageId();
+ const response = await sendInboxMessage(applicationToken, {
+ idempotencyKey: 'second-question',
+ });
+
+ expect(JSON.stringify(response.body.errors)).toContain(
+ 'THREAD_AWAITING_ANSWER',
+ );
+ expect(await readPendingQuestionMessageId()).toBe(pendingQuestionMessageId);
+ });
+
+ it('posts a follow-up message in the same conversation', async () => {
+ const pendingQuestionMessageId = await readPendingQuestionMessageId();
+ const response = await sendInboxMessage(applicationToken, {
+ idempotencyKey: 'transcript-ready',
+ text: 'The transcript is ready too.',
+ toolCall: null,
+ });
+
+ expect(response.body.errors).toBeUndefined();
+ expect(response.body.data.sendInboxMessage.threadId).toBe(threadId);
+ expect(await readMessages(threadId)).toHaveLength(3);
+ expect(await readPendingQuestionMessageId()).toBe(pendingQuestionMessageId);
+ });
+
+ it('keeps a single waiting question when two are sent at once', async () => {
+ const threadKey = `inbox-thread-${uuidv4()}`;
+ const responses = await Promise.all(
+ ['first-question', 'second-question'].map((idempotencyKey) =>
+ sendInboxMessage(applicationToken, { threadKey, idempotencyKey }),
+ ),
+ );
+ const sentResponses = responses.filter(
+ (response) => response.body.errors === undefined,
+ );
+ const concurrentThreadId =
+ sentResponses[0]?.body.data.sendInboxMessage.threadId;
+
+ try {
+ expect(sentResponses).toHaveLength(1);
+ expect(
+ JSON.stringify(
+ responses.find((response) => response.body.errors !== undefined)?.body
+ .errors,
+ ),
+ ).toContain('THREAD_AWAITING_ANSWER');
+ expect(await readMessages(concurrentThreadId)).toHaveLength(2);
+ } finally {
+ if (concurrentThreadId !== undefined) {
+ await destroyAgentChatThread({ threadId: concurrentThreadId });
+ }
+ }
+ });
+
+ it('writes nothing for a message whose parts fail, and completes it on retry', async () => {
+ const threadKey = `inbox-thread-${uuidv4()}`;
+ // The app runs in Jest's global setup, so its repository class is not the
+ // one this file would import.
+ const workspaceOrmManager = getAppProviderByClassName<WorkspaceOrmManager>(
+ 'WorkspaceOrmManager',
+ );
+ const workspaceRepositoryPrototype: WorkspaceRepository =
+ await workspaceOrmManager.executeInWorkspaceContext(
+ () =>
+ Object.getPrototypeOf(
+ workspaceOrmManager.getRepository('agentMessagePart', {
+ shouldBypassPermissionChecks: true,
+ }),
+ ),
+ buildSystemAuthContext(SEED_APPLE_WORKSPACE_ID),
+ { lite: true },
+ );
+ const insert = workspaceRepositoryPrototype.insert;
+ let partWriteCount = 0;
+ const failMessagePartsSpy = jest
+ .spyOn(workspaceRepositoryPrototype, 'insert')
+ .mockImplementation(function (
+ this: WorkspaceRepository,
+ ...args: Parameters<WorkspaceRepository['insert']>
+ ) {
+ const { tableShape } = (
+ this as unknown as {
+ options: { tableShape: { nameSingular: string } };
+ }
+ ).options;
+
+ // The opener's parts come first, then the application message's.
+ if (
+ tableShape.nameSingular === 'agentMessagePart' &&
+ ++partWriteCount === 2
+ ) {
+ return Promise.reject(new Error('Message parts write failed'));
+ }
+
+ return insert.apply(this, args);
+ });
+
+ let failedResponse;
+
+ try {
+ failedResponse = await sendInboxMessage(applicationToken, { threadKey });
+ } finally {
+ failMessagePartsSpy.mockRestore();
+ }
+
+ const { threadId: failedThreadId } = buildInboxMessageIds({
+ senderKey: `application:${application.id}`,
+ workspaceMemberId: input.workspaceMemberId,
+ threadKey,
+ idempotencyKey: input.idempotencyKey,
+ });
+
+ try {
+ expect(failedResponse.body.errors).toBeDefined();
+ expect(await readMessages(failedThreadId)).toHaveLength(1);
+ expect(
+ (
+ await global.testDataSource.query(
+ `SELECT "pendingQuestionMessageId" FROM "${schema}"."agentChatThread" WHERE id = $1`,
+ [failedThreadId],
+ )
+ )[0].pendingQuestionMessageId,
+ ).toBeNull();
+
+ const retryResponse = await sendInboxMessage(applicationToken, {
+ threadKey,
+ });
+ const messages = await readMessages(failedThreadId);
+ const [assistantParts] = await global.testDataSource.query(
+ `SELECT COUNT(*)::int AS count FROM "${schema}"."agentMessagePart" WHERE "messageId" = $1`,
+ [messages[1]?.id],
+ );
+
+ expect(retryResponse.body.errors).toBeUndefined();
+ expect(retryResponse.body.data.sendInboxMessage.threadId).toBe(
+ failedThreadId,
+ );
+ expect(messages).toHaveLength(2);
+ expect(assistantParts.count).toBe(2);
+ } finally {
+ await destroyAgentChatThread({ threadId: failedThreadId });
+ }
+ });
+
+ it('lets the member answer the question and resumes the chat', async () => {
+ const pendingQuestionMessageId = await readPendingQuestionMessageId();
+ const response = await answerToolCall({
+ toolCall: {
+ threadId,
+ toolCallId: `call_${pendingQuestionMessageId!.replace(/-/g, '')}`,
+ },
+ response: {
+ answers: [{ questionIndex: 0, selectedOptionIndices: [0] }],
+ },
+ });
+
+ expect(response.body.errors).toBeUndefined();
+ expect(enqueueStream).toHaveBeenLastCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ threadId,
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JANE,
+ }),
+ );
+ });
+});
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/utils/run-workflow-action-step.util.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/utils/run-workflow-action-step.util.ts
index 89741e1908f..cef4196a5d2 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/utils/run-workflow-action-step.util.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/utils/run-workflow-action-step.util.ts
@@ -12,6 +12,7 @@ import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graph
type WorkflowActionStepType =
| 'SEND_EMAIL'
| 'DRAFT_EMAIL'
+ | 'SEND_CHAT_MESSAGE'
| 'CREATE_CALENDAR_EVENT'
| 'CREATE_RECORD'
| 'UPDATE_RECORD'
@@ -187,12 +188,14 @@ export const runWorkflowActionStep = async ({
input,
payload,
runToken,
+ beforeRun,
}: {
name: string;
stepType: WorkflowActionStepType;
input: Record<string, unknown>;
payload?: object;
runToken?: string;
+ beforeRun?: () => Promise<unknown>;
}): Promise<WorkflowActionStepRun> => {
const workflowId = await createWorkflow(name);
@@ -218,6 +221,8 @@ export const runWorkflowActionStep = async ({
await updateWorkflowVersionStepInput({ workflowVersionId, step, input });
+ await beforeRun?.();
+
workflowRunId = await runWorkflowVersion({
workflowVersionId,
payload,
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-send-chat-message.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-send-chat-message.integration-spec.ts
new file mode 100644
index 00000000000..39ce2e4b1b9
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/workflow-send-chat-message.integration-spec.ts
@@ -0,0 +1,173 @@
+import gql from 'graphql-tag';
+import { runWorkflowActionStep } from 'test/integration/graphql/suites/workflow/utils/run-workflow-action-step.util';
+import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';
+import { updateFeatureFlag } from 'test/integration/metadata/suites/utils/update-feature-flag.util';
+import { destroyAgentChatThread } from 'test/integration/utils/destroy-agent-chat-thread.util';
+import { FeatureFlagKey } from 'twenty-shared/types';
+import { v4 as uuidv4 } 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 { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
+
+const SCHEMA = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);
+
+const setSendChatMessageEnabled = (value: boolean) =>
+ updateFeatureFlag({
+ featureFlag: FeatureFlagKey.IS_WORKFLOW_SEND_CHAT_MESSAGE_ENABLED,
+ value,
+ expectToFail: false,
+ });
+
+describe('Send chat message workflow step', () => {
+ afterAll(async () => {
+ await setSendChatMessageEnabled(true);
+ });
+
+ it('posts the message in a conversation of the recipient', async () => {
+ await setSendChatMessageEnabled(true);
+
+ const title = `Your new deal is ready ${uuidv4()}`;
+ const { status, stepStatus, stepResult, stepError } =
+ await runWorkflowActionStep({
+ name: 'Welcome new deal owners',
+ stepType: 'SEND_CHAT_MESSAGE',
+ input: {
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ title,
+ text: 'You now own the **Acme renewal**.',
+ },
+ });
+ const threadId = stepResult?.threadId as string | undefined;
+
+ try {
+ expect({ status, stepStatus, stepError }).toEqual({
+ status: 'COMPLETED',
+ stepStatus: 'SUCCESS',
+ stepError: undefined,
+ });
+
+ const [thread] = await global.testDataSource.query(
+ `SELECT title, "workspaceMemberId" FROM "${SCHEMA}"."agentChatThread" WHERE id = $1`,
+ [threadId],
+ );
+ const messages = await global.testDataSource.query(
+ `SELECT m.role, m."isHidden", p."textContent"
+ FROM "${SCHEMA}"."agentMessage" m
+ JOIN "${SCHEMA}"."agentMessagePart" p ON p."messageId" = m.id
+ WHERE m."threadId" = $1
+ ORDER BY m."processedAt" ASC`,
+ [threadId],
+ );
+
+ expect(thread).toEqual({
+ title,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ });
+ expect(messages).toEqual([
+ {
+ role: 'user',
+ isHidden: true,
+ textContent:
+ 'The "Welcome new deal owners" workflow started this conversation. Its messages follow.',
+ },
+ {
+ role: 'assistant',
+ isHidden: false,
+ textContent: 'You now own the **Acme renewal**.',
+ },
+ ]);
+ } finally {
+ if (threadId !== undefined) {
+ await destroyAgentChatThread({ threadId });
+ }
+ }
+ }, 120000);
+
+ it('fails a step that runs after the feature flag is turned off', async () => {
+ await setSendChatMessageEnabled(true);
+
+ const { stepStatus, stepError } = await runWorkflowActionStep({
+ name: 'Send chat message turned off',
+ stepType: 'SEND_CHAT_MESSAGE',
+ input: {
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ title: 'Should not be sent',
+ text: 'Hello',
+ },
+ beforeRun: () => setSendChatMessageEnabled(false),
+ });
+
+ expect(stepStatus).toBe('FAILED');
+ expect(stepError).toContain('is not enabled');
+ }, 120000);
+
+ it('cannot be added to a workflow while the feature flag is off', async () => {
+ await setSendChatMessageEnabled(false);
+
+ const workflowResponse = await makeGraphqlApiRequest({
+ query: gql`
+ mutation CreateWorkflow($name: String!) {
+ createWorkflow(data: { name: $name }) {
+ id
+ }
+ }
+ `,
+ variables: { name: 'Send chat message disabled' },
+ });
+ const workflow = workflowResponse.body.data.createWorkflow;
+
+ try {
+ const versionResponse = await makeGraphqlApiRequest({
+ query: gql`
+ query FindDraftWorkflowVersion($workflowId: UUID!) {
+ workflowVersions(filter: { workflowId: { eq: $workflowId } }) {
+ edges {
+ node {
+ id
+ }
+ }
+ }
+ }
+ `,
+ variables: { workflowId: workflow.id },
+ });
+
+ const stepResponse = await makeGraphqlApiRequest({
+ query: gql`
+ mutation CreateWorkflowVersionStep(
+ $input: CreateWorkflowVersionStepInput!
+ ) {
+ createWorkflowVersionStep(input: $input) {
+ stepsDiff
+ }
+ }
+ `,
+ variables: {
+ input: {
+ workflowVersionId:
+ versionResponse.body.data.workflowVersions.edges[0].node.id,
+ stepType: 'SEND_CHAT_MESSAGE',
+ parentStepId: 'trigger',
+ position: { x: 200, y: 0 },
+ },
+ },
+ });
+
+ expect(JSON.stringify(stepResponse.body.errors)).toContain(
+ 'is not enabled',
+ );
+ } finally {
+ await makeGraphqlApiRequest({
+ query: gql`
+ mutation DestroyWorkflow($id: ID!) {
+ destroyWorkflow(id: $id) {
+ id
+ }
+ }
+ `,
+ variables: { id: workflow.id },
+ });
+ }
+ }, 120000);
+});
diff --git a/packages/twenty-shared/src/application/index.ts b/packages/twenty-shared/src/application/index.ts
index d6969d29e6f..fd285509693 100644
--- a/packages/twenty-shared/src/application/index.ts
+++ b/packages/twenty-shared/src/application/index.ts
@@ -205,6 +205,9 @@ export type {
RunAgentInput,
RunAgentResult,
} from './runAgentType';
+export type { SendInboxMessageInput } from './sendInboxMessageInputType';
+export type { SendInboxMessageResult } from './sendInboxMessageResultType';
+export type { SendInboxMessageToolCall } from './sendInboxMessageToolCallType';
export type { ServerVariables } from './server-variables.type';
export type { ServerRouteDispatchResult } from './serverRouteDispatchResultType';
export type { ServerRouteTriggerSettings } from './serverRouteTriggerSettingsType';
diff --git a/packages/twenty-shared/src/application/sendInboxMessageInputType.ts b/packages/twenty-shared/src/application/sendInboxMessageInputType.ts
new file mode 100644
index 00000000000..57bec032f3f
--- /dev/null
+++ b/packages/twenty-shared/src/application/sendInboxMessageInputType.ts
@@ -0,0 +1,10 @@
+import { type SendInboxMessageToolCall } from '@/application/sendInboxMessageToolCallType';
+
+export type SendInboxMessageInput = {
+ workspaceMemberId: string;
+ threadKey: string;
+ idempotencyKey: string;
+ title: string;
+ text: string;
+ toolCall?: SendInboxMessageToolCall;
+};
diff --git a/packages/twenty-shared/src/application/sendInboxMessageResultType.ts b/packages/twenty-shared/src/application/sendInboxMessageResultType.ts
new file mode 100644
index 00000000000..218b6340847
--- /dev/null
+++ b/packages/twenty-shared/src/application/sendInboxMessageResultType.ts
@@ -0,0 +1,3 @@
+export type SendInboxMessageResult = {
+ threadId: string;
+};
diff --git a/packages/twenty-shared/src/application/sendInboxMessageToolCallType.ts b/packages/twenty-shared/src/application/sendInboxMessageToolCallType.ts
new file mode 100644
index 00000000000..d42223b3f67
--- /dev/null
+++ b/packages/twenty-shared/src/application/sendInboxMessageToolCallType.ts
@@ -0,0 +1,26 @@
+import { type AskQuestionsToolInput } from '@/ai/types/AskQuestionsToolInput';
+import { type ProposedEmail } from '@/ai/types/ProposedEmail';
+import { type RequestFormToolInput } from '@/ai/types/RequestFormToolInput';
+
+export type SendInboxMessageToolCall =
+ | {
+ toolName: 'ask_questions';
+ input: AskQuestionsToolInput;
+ logicFunctionUniversalIdentifier?: never;
+ }
+ | {
+ toolName: 'request_form';
+ input: RequestFormToolInput;
+ logicFunctionUniversalIdentifier?: never;
+ }
+ | {
+ toolName: 'propose_email';
+ input: ProposedEmail;
+ logicFunctionUniversalIdentifier?: never;
+ }
+ | {
+ logicFunctionUniversalIdentifier: string;
+ toolName?: never;
+ input?: Record<string, unknown>;
+ output?: Record<string, unknown>;
+ };
diff --git a/packages/twenty-shared/src/types/FeatureFlagKey.ts b/packages/twenty-shared/src/types/FeatureFlagKey.ts
index 30d40f04128..d4b6669974d 100644
--- a/packages/twenty-shared/src/types/FeatureFlagKey.ts
+++ b/packages/twenty-shared/src/types/FeatureFlagKey.ts
@@ -17,4 +17,5 @@ export enum FeatureFlagKey {
IS_CONVERSATIONS_TAB_ENABLED = 'IS_CONVERSATIONS_TAB_ENABLED',
IS_VALIDATION_RULES_ENABLED = 'IS_VALIDATION_RULES_ENABLED',
IS_RECORD_LEVEL_SHARING_ENABLED = 'IS_RECORD_LEVEL_SHARING_ENABLED',
+ IS_WORKFLOW_SEND_CHAT_MESSAGE_ENABLED = 'IS_WORKFLOW_SEND_CHAT_MESSAGE_ENABLED',
}
diff --git a/packages/twenty-shared/src/workflow/constants/WorkflowActionFeatureFlags.ts b/packages/twenty-shared/src/workflow/constants/WorkflowActionFeatureFlags.ts
new file mode 100644
index 00000000000..1d0d083cae0
--- /dev/null
+++ b/packages/twenty-shared/src/workflow/constants/WorkflowActionFeatureFlags.ts
@@ -0,0 +1,9 @@
+import { FeatureFlagKey } from '@/types';
+import { WorkflowActionType } from '@/workflow/types/WorkflowActionType';
+
+export const WORKFLOW_ACTION_FEATURE_FLAGS: Partial<
+ Record<`${WorkflowActionType}`, FeatureFlagKey>
+> = {
+ [WorkflowActionType.SEND_CHAT_MESSAGE]:
+ FeatureFlagKey.IS_WORKFLOW_SEND_CHAT_MESSAGE_ENABLED,
+};
diff --git a/packages/twenty-shared/src/workflow/index.ts b/packages/twenty-shared/src/workflow/index.ts
index 9003c0169f2..42508445be0 100644
--- a/packages/twenty-shared/src/workflow/index.ts
+++ b/packages/twenty-shared/src/workflow/index.ts
@@ -14,6 +14,7 @@ export { OBJECTS_BLOCKED_FROM_AUTOMATION } from './constants/ObjectsBlockedFromA
export { OBJECTS_SYNCED_FROM_CONNECTED_ACCOUNTS } from './constants/ObjectsSyncedFromConnectedAccounts';
export { STEP_RETRY_DELAYS_MS } from './constants/StepRetryDelaysMs';
export { TRIGGER_STEP_ID } from './constants/TriggerStepId';
+export { WORKFLOW_ACTION_FEATURE_FLAGS } from './constants/WorkflowActionFeatureFlags';
export { WORKFLOW_TRIGGER_METADATA_KEY } from './constants/WorkflowTriggerMetadataKey';
export { WORKFLOW_TRIGGER_METADATA_LABEL } from './constants/WorkflowTriggerMetadataLabel';
export { WORKFLOW_TRIGGER_METADATA_WORKSPACE_MEMBER_ID_KEY } from './constants/WorkflowTriggerMetadataWorkspaceMemberIdKey';
@@ -84,6 +85,8 @@ export {
workflowPickRecordStrategySchema,
workflowPickRecordActionSettingsSchema,
} from './schemas/pick-record-action-settings-schema';
+export { workflowSendChatMessageActionSchema } from './schemas/send-chat-message-action-schema';
+export { workflowSendChatMessageActionSettingsSchema } from './schemas/send-chat-message-action-settings-schema';
export { workflowSendEmailActionSchema } from './schemas/send-email-action-schema';
export type { WorkflowEmailFiles } from './schemas/send-email-action-settings-schema';
export {
diff --git a/packages/twenty-shared/src/workflow/schemas/send-chat-message-action-schema.ts b/packages/twenty-shared/src/workflow/schemas/send-chat-message-action-schema.ts
new file mode 100644
index 00000000000..00e9ebb0f7c
--- /dev/null
+++ b/packages/twenty-shared/src/workflow/schemas/send-chat-message-action-schema.ts
@@ -0,0 +1,9 @@
+import { z } from 'zod';
+import { baseWorkflowActionSchema } from './base-workflow-action-schema';
+import { workflowSendChatMessageActionSettingsSchema } from './send-chat-message-action-settings-schema';
+
+export const workflowSendChatMessageActionSchema =
+ baseWorkflowActionSchema.extend({
+ type: z.literal('SEND_CHAT_MESSAGE'),
+ settings: workflowSendChatMessageActionSettingsSchema,
+ });
diff --git a/packages/twenty-shared/src/workflow/schemas/send-chat-message-action-settings-schema.ts b/packages/twenty-shared/src/workflow/schemas/send-chat-message-action-settings-schema.ts
new file mode 100644
index 00000000000..b34e3ed20f6
--- /dev/null
+++ b/packages/twenty-shared/src/workflow/schemas/send-chat-message-action-settings-schema.ts
@@ -0,0 +1,11 @@
+import { z } from 'zod';
+import { baseWorkflowActionSettingsSchema } from './base-workflow-action-settings-schema';
+
+export const workflowSendChatMessageActionSettingsSchema =
+ baseWorkflowActionSettingsSchema.extend({
+ input: z.object({
+ workspaceMemberId: z.string(),
+ title: z.string(),
+ text: z.string(),
+ }),
+ });
diff --git a/packages/twenty-shared/src/workflow/schemas/workflow-action-schema.ts b/packages/twenty-shared/src/workflow/schemas/workflow-action-schema.ts
index 74e53da2e8f..b89c5efc55f 100644
--- a/packages/twenty-shared/src/workflow/schemas/workflow-action-schema.ts
+++ b/packages/twenty-shared/src/workflow/schemas/workflow-action-schema.ts
@@ -15,6 +15,7 @@ import { workflowIfElseActionSchema } from './if-else-action-schema';
import { workflowIteratorActionSchema } from './iterator-action-schema';
import { workflowLogicFunctionActionSchema } from './logic-function-action-schema';
import { workflowPickRecordActionSchema } from './pick-record-action-schema';
+import { workflowSendChatMessageActionSchema } from './send-chat-message-action-schema';
import { workflowSendEmailActionSchema } from './send-email-action-schema';
import { workflowUpdateRecordActionSchema } from './update-record-action-schema';
import { workflowUpsertRecordActionSchema } from './upsert-record-action-schema';
@@ -25,6 +26,7 @@ export const workflowActionSchema = z.discriminatedUnion('type', [
workflowLogicFunctionActionSchema,
workflowSendEmailActionSchema,
workflowDraftEmailActionSchema,
+ workflowSendChatMessageActionSchema,
workflowCreateCalendarEventActionSchema,
workflowCreateRecordActionSchema,
workflowUpdateRecordActionSchema,
diff --git a/packages/twenty-shared/src/workflow/types/WorkflowActionType.ts b/packages/twenty-shared/src/workflow/types/WorkflowActionType.ts
index ec230dadf07..b53b177bc60 100644
--- a/packages/twenty-shared/src/workflow/types/WorkflowActionType.ts
+++ b/packages/twenty-shared/src/workflow/types/WorkflowActionType.ts
@@ -2,6 +2,7 @@ export enum WorkflowActionType {
CODE = 'CODE',
LOGIC_FUNCTION = 'LOGIC_FUNCTION',
SEND_EMAIL = 'SEND_EMAIL',
+ SEND_CHAT_MESSAGE = 'SEND_CHAT_MESSAGE',
DRAFT_EMAIL = 'DRAFT_EMAIL',
CREATE_CALENDAR_EVENT = 'CREATE_CALENDAR_EVENT',
CREATE_RECORD = 'CREATE_RECORD',