Skip to content

The open alternative to Salesforce, designed for AI.

feat(ai): answer every Ask through answerAsk, let agents propose emails and wait on several Asks at once (#26930)

Félix Malfaitc2f42106a39f
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index ac4225ec58d..c766189ae20 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -3412,46 +3412,6 @@ type DuplicatedDashboard {
updatedAt: String!
}
-type SendEmailOutput {
- success: Boolean!
- error: String
- messageThreadId: String
-}
-
-type Analytics {
- """Boolean that confirms query was dispatched"""
- success: Boolean!
-}
-
-type EventLogRecord {
- event: String!
- timestamp: DateTime!
- userId: String
- properties: JSON
- recordId: String
- objectMetadataId: String
- isCustom: Boolean
-}
-
-type EventLogPageInfo {
- endCursor: String
- hasNextPage: Boolean!
-}
-
-type EventLogQueryResult {
- records: [EventLogRecord!]!
- totalCount: Int!
- pageInfo: EventLogPageInfo!
-}
-
-type RecordExport {
- id: UUID!
- filename: String!
- progress: Int!
- errorMessage: String
- downloadPath: String
-}
-
type AiChatUsage {
limitValue: BigInt!
consumedValue: BigInt
@@ -3534,6 +3494,46 @@ enum WorkspaceSetupChatOutcome {
UNAVAILABLE
}
+type SendEmailOutput {
+ success: Boolean!
+ error: String
+ messageThreadId: String
+}
+
+type Analytics {
+ """Boolean that confirms query was dispatched"""
+ success: Boolean!
+}
+
+type EventLogRecord {
+ event: String!
+ timestamp: DateTime!
+ userId: String
+ properties: JSON
+ recordId: String
+ objectMetadataId: String
+ isCustom: Boolean
+}
+
+type EventLogPageInfo {
+ endCursor: String
+ hasNextPage: Boolean!
+}
+
+type EventLogQueryResult {
+ records: [EventLogRecord!]!
+ totalCount: Int!
+ pageInfo: EventLogPageInfo!
+}
+
+type RecordExport {
+ id: UUID!
+ filename: String!
+ progress: Int!
+ errorMessage: String
+ downloadPath: String
+}
+
type RecordPermissionsResult {
objectMetadataId: UUID!
recordId: UUID!
@@ -3815,38 +3815,22 @@ type Query {
usageQuotasWithConsumption: [UsageQuotaWithConsumption!]!
usageQuotaDefinitions: UsageQuotaDefinitions!
usageQuotaScopeConsumption(input: UsageQuotaScopeInput!): UsageQuotaScopeConsumption
- getUsageAnalytics(input: UsageAnalyticsInput): UsageAnalytics!
- getViewFilterGroups(viewId: String): [ViewFilterGroup!]!
- getViewFilterGroup(id: String!): ViewFilterGroup
- getViewFilters(viewId: String): [ViewFilter!]!
- getViewFilter(id: String!): ViewFilter
+ getPageLayoutWidgets(pageLayoutTabId: String!): [PageLayoutWidget!]!
+ getPageLayoutWidget(id: String!): PageLayoutWidget!
+ getPageLayoutTabs(pageLayoutId: String!): [PageLayoutTab!]!
+ getPageLayoutTab(id: String!): PageLayoutTab!
+ getPageLayouts(objectMetadataId: String, pageLayoutType: PageLayoutType): [PageLayout!]!
+ getPageLayout(id: String!): PageLayout
getViews(objectMetadataId: String, viewTypes: [ViewType!]): [View!]!
getView(id: String!): View
getViewSorts(viewId: String): [ViewSort!]!
getViewSort(id: String!): ViewSort
+ getViewFilters(viewId: String): [ViewFilter!]!
+ getViewFilter(id: String!): ViewFilter
getViewFields(viewId: String!): [ViewField!]!
getViewField(id: String!): ViewField
getViewFieldGroups(viewId: String!): [ViewFieldGroup!]!
getViewFieldGroup(id: String!): ViewFieldGroup
- apiKeys: [ApiKey!]!
- getApiKeyRoles: [Role!]!
- apiKey(input: GetApiKeyInput!): ApiKey
- currentUserSessions: [UserSession!]!
- billingPortalSession(returnUrlPath: String, forPaymentMethodUpdate: Boolean): BillingSession!
- listPlans: [BillingPlan!]!
- getResourceCreditUsage: [BillingResourceCreditUsage!]!
- myConnectedAccounts: [ConnectedAccountPublicDTO!]!
- applicationConnectedAccounts(applicationId: UUID!): [ApplicationConnectedAccountDTO!]!
- applicationConnectionProviders(applicationId: UUID!): [ApplicationConnectionProvider!]!
- getInviteSuggestions: [InviteSuggestion!]!
- findWorkspaceInvitations: [WorkspaceInvitation!]!
- getApprovedAccessDomains: [ApprovedAccessDomain!]!
- getPageLayoutTabs(pageLayoutId: String!): [PageLayoutTab!]!
- getPageLayoutTab(id: String!): PageLayoutTab!
- getPageLayouts(objectMetadataId: String, pageLayoutType: PageLayoutType): [PageLayout!]!
- getPageLayout(id: String!): PageLayout
- getPageLayoutWidgets(pageLayoutTabId: String!): [PageLayoutWidget!]!
- getPageLayoutWidget(id: String!): PageLayoutWidget!
findManyAgents: [Agent!]!
findOneAgent(input: AgentIdInput!): Agent!
objects(
@@ -3862,6 +3846,7 @@ type Query {
): Object!
objectRecordCounts: [ObjectRecordCount!]!
mostlyEmptyFieldMetadataIds(objectMetadataId: UUID!): [UUID!]!
+ currentUserSessions: [UserSession!]!
findOneLogicFunction(input: LogicFunctionIdInput!): LogicFunction!
findManyLogicFunctions: [LogicFunction!]!
getAvailablePackages(input: LogicFunctionIdInput!): JSON!
@@ -3870,9 +3855,24 @@ type Query {
commandMenuItem(id: UUID!): CommandMenuItem
frontComponents: [FrontComponent!]!
frontComponent(id: UUID!): FrontComponent
+ billingPortalSession(returnUrlPath: String, forPaymentMethodUpdate: Boolean): BillingSession!
+ listPlans: [BillingPlan!]!
+ getResourceCreditUsage: [BillingResourceCreditUsage!]!
+ getUsageAnalytics(input: UsageAnalyticsInput): UsageAnalytics!
+ myConnectedAccounts: [ConnectedAccountPublicDTO!]!
+ applicationConnectedAccounts(applicationId: UUID!): [ApplicationConnectedAccountDTO!]!
+ applicationConnectionProviders(applicationId: UUID!): [ApplicationConnectionProvider!]!
currentWorkspace: Workspace!
getPublicWorkspaceDataByDomain(origin: String): PublicWorkspaceData!
getPublicWorkspaceDataById(id: UUID!): PublicWorkspaceDataSummary!
+ getInviteSuggestions: [InviteSuggestion!]!
+ findWorkspaceInvitations: [WorkspaceInvitation!]!
+ getApprovedAccessDomains: [ApprovedAccessDomain!]!
+ getViewFilterGroups(viewId: String): [ViewFilterGroup!]!
+ getViewFilterGroup(id: String!): ViewFilterGroup
+ apiKeys: [ApiKey!]!
+ getApiKeyRoles: [Role!]!
+ apiKey(input: GetApiKeyInput!): ApiKey
findApplicationRegistrationByClientId(clientId: String!): PublicApplicationRegistration
findApplicationRegistrationByUniversalIdentifier(universalIdentifier: String!): ApplicationRegistration
findManyApplicationRegistrations: [ApplicationRegistration!]!
@@ -3972,17 +3972,6 @@ input UsageQuotaScopeInput {
meter: String!
}
-input UsageAnalyticsInput {
- periodStart: DateTime
- periodEnd: DateTime
- userWorkspaceId: String
- operationTypes: [UsageOperationType!]
-}
-
-input GetApiKeyInput {
- id: UUID!
-}
-
input AgentIdInput {
"""The id of the agent."""
id: UUID!
@@ -4007,6 +3996,17 @@ input LogicFunctionIdInput {
id: ID!
}
+input UsageAnalyticsInput {
+ periodStart: DateTime
+ periodEnd: DateTime
+ userWorkspaceId: String
+ operationTypes: [UsageOperationType!]
+}
+
+input GetApiKeyInput {
+ id: UUID!
+}
+
input PreviewMessageCampaignAudienceInput {
listId: String!
unsubscribeTopicId: String
@@ -4119,14 +4119,19 @@ type Mutation {
createUsageLimit(input: CreateUsageLimitInput!): UsageLimit!
updateUsageLimit(input: UpdateUsageLimitInput!): UsageLimit!
deleteUsageLimit(usageLimitId: UUID!): Boolean!
- createViewFilterGroup(input: CreateViewFilterGroupInput!): ViewFilterGroup!
- updateViewFilterGroup(id: String!, input: UpdateViewFilterGroupInput!): ViewFilterGroup!
- deleteViewFilterGroup(id: String!): Boolean!
- destroyViewFilterGroup(id: String!): Boolean!
- createViewFilter(input: CreateViewFilterInput!): ViewFilter!
- updateViewFilter(input: UpdateViewFilterInput!): ViewFilter!
- deleteViewFilter(input: DeleteViewFilterInput!): ViewFilter!
- destroyViewFilter(input: DestroyViewFilterInput!): ViewFilter!
+ createPageLayoutWidget(input: CreatePageLayoutWidgetInput!): PageLayoutWidget!
+ updatePageLayoutWidget(id: String!, input: UpdatePageLayoutWidgetInput!): PageLayoutWidget!
+ destroyPageLayoutWidget(id: String!): Boolean!
+ createPageLayoutTab(input: CreatePageLayoutTabInput!): PageLayoutTab!
+ updatePageLayoutTab(id: String!, input: UpdatePageLayoutTabInput!): PageLayoutTab!
+ destroyPageLayoutTab(id: String!): Boolean!
+ createPageLayout(input: CreatePageLayoutInput!): PageLayout!
+ updatePageLayout(id: String!, input: UpdatePageLayoutInput!): PageLayout!
+ destroyPageLayout(id: String!): Boolean!
+ updatePageLayoutWithTabsAndWidgets(id: String!, input: UpdatePageLayoutWithTabsInput!): PageLayout!
+ resetPageLayoutToDefault(id: String!): PageLayout!
+ resetPageLayoutWidgetToDefault(id: String!): PageLayoutWidget!
+ resetPageLayoutTabToDefault(id: String!): PageLayoutTab!
createView(input: CreateViewInput!): View!
updateView(id: String!, input: UpdateViewInput!): View!
deleteView(id: String!): Boolean!
@@ -4136,6 +4141,10 @@ type Mutation {
updateViewSort(input: UpdateViewSortInput!): ViewSort!
deleteViewSort(input: DeleteViewSortInput!): Boolean!
destroyViewSort(input: DestroyViewSortInput!): Boolean!
+ createViewFilter(input: CreateViewFilterInput!): ViewFilter!
+ updateViewFilter(input: UpdateViewFilterInput!): ViewFilter!
+ deleteViewFilter(input: DeleteViewFilterInput!): ViewFilter!
+ destroyViewFilter(input: DestroyViewFilterInput!): ViewFilter!
updateViewField(input: UpdateViewFieldInput!): ViewField!
createViewField(input: CreateViewFieldInput!): ViewField!
createManyViewFields(inputs: [CreateViewFieldInput!]!): [ViewField!]!
@@ -4147,48 +4156,6 @@ type Mutation {
deleteViewFieldGroup(input: DeleteViewFieldGroupInput!): ViewFieldGroup!
destroyViewFieldGroup(input: DestroyViewFieldGroupInput!): ViewFieldGroup!
upsertFieldsWidget(input: UpsertFieldsWidgetInput!): View!
- createApiKey(input: CreateApiKeyInput!): ApiKey!
- updateApiKey(input: UpdateApiKeyInput!): ApiKey
- revokeApiKey(input: RevokeApiKeyInput!): ApiKey
- assignRoleToApiKey(apiKeyId: UUID!, roleId: UUID!): Boolean!
- revokeUserSession(userSessionId: UUID!): Boolean!
- revokeAllOtherUserSessions: Int!
- checkoutSession(recurringInterval: SubscriptionInterval!, plan: BillingPlanKey! = PRO, requirePaymentMethod: Boolean! = true, successUrlPath: String): BillingSession!
- createSubscriptionPaymentIntent(recurringInterval: SubscriptionInterval!, plan: BillingPlanKey! = PRO, requirePaymentMethod: Boolean! = true, successUrlPath: String, idempotencyKey: String!): BillingPaymentIntent!
- createBillingPaymentMethodSetupIntent: BillingPaymentIntent!
- switchSubscriptionInterval: BillingUpdate!
- switchBillingPlan: BillingUpdate!
- cancelSwitchBillingPlan: BillingUpdate!
- cancelSwitchBillingInterval: BillingUpdate!
- setResourceCreditSubscriptionPrice(priceId: String!): BillingUpdate!
- endSubscriptionTrialPeriod: BillingEndTrialPeriod!
- cancelSwitchResourceCreditPrice: BillingUpdate!
- deleteConnectedAccount(id: UUID!): ConnectedAccountPublicDTO!
- disconnectConnectedAccount(id: UUID!): ConnectedAccountPublicDTO!
- updateOneApplicationVariable(key: String!, value: String!, applicationId: UUID): Boolean!
- skipSyncEmailOnboardingStep(isAutoSkipped: Boolean! = false): OnboardingStepSuccess!
- completeBookCallOnboardingStep(hasBookedCall: Boolean! = false, isAutoSkipped: Boolean! = false): OnboardingStepSuccess!
- triggerInstallAppsOnboardingStep(universalIdentifiers: [String!]!, isAutoSkipped: Boolean! = false): OnboardingStepSuccess!
- goBackToPreviousOnboardingStep: OnboardingStepNavigation!
- deleteWorkspaceInvitation(appTokenId: String!): String!
- resendWorkspaceInvitation(appTokenId: String!): SendInvitations!
- sendInvitations(emails: [String!]!, roleId: UUID): SendInvitations!
- createApprovedAccessDomain(input: CreateApprovedAccessDomainInput!): ApprovedAccessDomain!
- deleteApprovedAccessDomain(input: DeleteApprovedAccessDomainInput!): Boolean!
- validateApprovedAccessDomain(input: ValidateApprovedAccessDomainInput!): ApprovedAccessDomain!
- createPageLayoutTab(input: CreatePageLayoutTabInput!): PageLayoutTab!
- updatePageLayoutTab(id: String!, input: UpdatePageLayoutTabInput!): PageLayoutTab!
- destroyPageLayoutTab(id: String!): Boolean!
- createPageLayout(input: CreatePageLayoutInput!): PageLayout!
- updatePageLayout(id: String!, input: UpdatePageLayoutInput!): PageLayout!
- destroyPageLayout(id: String!): Boolean!
- updatePageLayoutWithTabsAndWidgets(id: String!, input: UpdatePageLayoutWithTabsInput!): PageLayout!
- resetPageLayoutToDefault(id: String!): PageLayout!
- resetPageLayoutWidgetToDefault(id: String!): PageLayoutWidget!
- resetPageLayoutTabToDefault(id: String!): PageLayoutTab!
- createPageLayoutWidget(input: CreatePageLayoutWidgetInput!): PageLayoutWidget!
- updatePageLayoutWidget(id: String!, input: UpdatePageLayoutWidgetInput!): PageLayoutWidget!
- destroyPageLayoutWidget(id: String!): Boolean!
createOneAgent(input: CreateAgentInput!): Agent!
updateOneAgent(input: UpdateAgentInput!): Agent!
deleteOneAgent(input: AgentIdInput!): Agent!
@@ -4198,6 +4165,8 @@ type Mutation {
updateManyObjects(inputs: [UpdateOneObjectInput!]!): [Object!]!
createOneIndex(input: CreateOneIndexInput!): Index!
deleteOneIndex(input: DeleteOneIndexInput!): Index!
+ revokeUserSession(userSessionId: UUID!): Boolean!
+ revokeAllOtherUserSessions: Int!
deleteOneLogicFunction(input: LogicFunctionIdInput!): LogicFunction!
createOneLogicFunction(input: CreateLogicFunctionFromSourceInput!): LogicFunction!
executeOneLogicFunction(input: ExecuteOneLogicFunctionInput!): LogicFunctionExecutionResult!
@@ -4210,12 +4179,43 @@ type Mutation {
createFrontComponent(input: CreateFrontComponentInput!): FrontComponent!
updateFrontComponent(input: UpdateFrontComponentInput!): FrontComponent!
deleteFrontComponent(id: UUID!): FrontComponent!
+ updateOneApplicationVariable(key: String!, value: String!, applicationId: UUID): Boolean!
+ checkoutSession(recurringInterval: SubscriptionInterval!, plan: BillingPlanKey! = PRO, requirePaymentMethod: Boolean! = true, successUrlPath: String): BillingSession!
+ createSubscriptionPaymentIntent(recurringInterval: SubscriptionInterval!, plan: BillingPlanKey! = PRO, requirePaymentMethod: Boolean! = true, successUrlPath: String, idempotencyKey: String!): BillingPaymentIntent!
+ createBillingPaymentMethodSetupIntent: BillingPaymentIntent!
+ switchSubscriptionInterval: BillingUpdate!
+ switchBillingPlan: BillingUpdate!
+ cancelSwitchBillingPlan: BillingUpdate!
+ cancelSwitchBillingInterval: BillingUpdate!
+ setResourceCreditSubscriptionPrice(priceId: String!): BillingUpdate!
+ endSubscriptionTrialPeriod: BillingEndTrialPeriod!
+ cancelSwitchResourceCreditPrice: BillingUpdate!
+ deleteConnectedAccount(id: UUID!): ConnectedAccountPublicDTO!
+ disconnectConnectedAccount(id: UUID!): ConnectedAccountPublicDTO!
activateWorkspace(data: ActivateWorkspaceInput!): Workspace!
updateWorkspace(data: UpdateWorkspaceInput!): Workspace!
updateWorkspaceAllowedIframeOrigins(data: UpdateWorkspaceAllowedIframeOriginsInput!): Workspace!
deleteCurrentWorkspace: Workspace!
checkCustomDomainValidRecords: DomainValidRecords
enrichWorkspaceCompany: WorkspaceCompanyEnrichmentResult!
+ skipSyncEmailOnboardingStep(isAutoSkipped: Boolean! = false): OnboardingStepSuccess!
+ completeBookCallOnboardingStep(hasBookedCall: Boolean! = false, isAutoSkipped: Boolean! = false): OnboardingStepSuccess!
+ triggerInstallAppsOnboardingStep(universalIdentifiers: [String!]!, isAutoSkipped: Boolean! = false): OnboardingStepSuccess!
+ goBackToPreviousOnboardingStep: OnboardingStepNavigation!
+ deleteWorkspaceInvitation(appTokenId: String!): String!
+ resendWorkspaceInvitation(appTokenId: String!): SendInvitations!
+ sendInvitations(emails: [String!]!, roleId: UUID): SendInvitations!
+ createApprovedAccessDomain(input: CreateApprovedAccessDomainInput!): ApprovedAccessDomain!
+ deleteApprovedAccessDomain(input: DeleteApprovedAccessDomainInput!): Boolean!
+ validateApprovedAccessDomain(input: ValidateApprovedAccessDomainInput!): ApprovedAccessDomain!
+ createViewFilterGroup(input: CreateViewFilterGroupInput!): ViewFilterGroup!
+ updateViewFilterGroup(id: String!, input: UpdateViewFilterGroupInput!): ViewFilterGroup!
+ deleteViewFilterGroup(id: String!): Boolean!
+ destroyViewFilterGroup(id: String!): Boolean!
+ createApiKey(input: CreateApiKeyInput!): ApiKey!
+ updateApiKey(input: UpdateApiKeyInput!): ApiKey
+ revokeApiKey(input: RevokeApiKeyInput!): ApiKey
+ assignRoleToApiKey(apiKeyId: UUID!, roleId: UUID!): Boolean!
upgradeApplication(appRegistrationId: String!, targetVersion: String!): Boolean!
createApplicationRegistration(input: CreateApplicationRegistrationInput!): CreateApplicationRegistration!
updateApplicationRegistration(input: UpdateApplicationRegistrationInput!): ApplicationRegistration!
@@ -4289,7 +4289,6 @@ type Mutation {
createChatThread: AgentChatThread!
sendChatMessage(threadId: UUID!, text: String!, messageId: UUID!, browsingContext: JSON, modelId: String, fileAttachments: [FileAttachmentInput!]): SendChatMessageResult!
retryChatMessage(threadId: UUID!, modelId: String): SendChatMessageResult!
- answerAgentChatQuestion(threadId: UUID!, messageId: UUID!, answers: [AgentChatQuestionAnswerInput!]!, modelId: String, fileAttachments: [FileAttachmentInput!]): SendChatMessageResult!
stopAgentChatStream(threadId: UUID!): Boolean!
renameChatThread(id: UUID!, title: String!): AgentChatThread!
archiveChatThread(id: UUID!): AgentChatThread!
@@ -4354,6 +4353,7 @@ type Mutation {
startChannelSync(connectedAccountId: UUID!): ChannelSyncSuccess!
saveImapSmtpCaldavAccount(handle: String!, connectionParameters: EmailAccountConnectionParameters!, id: UUID): ImapSmtpCaldavConnectionSuccess!
updateLabPublicFeatureFlag(input: UpdateLabPublicFeatureFlagInput!): FeatureFlag!
+ answerAgentChatQuestion(threadId: UUID!, messageId: UUID!, answers: [AgentChatQuestionAnswerInput!]!, modelId: String, fileAttachments: [FileAttachmentInput!]): SendChatMessageResult! @deprecated(reason: "Use answerAsk with the question's Ask")
createPublicDomain(domain: String!, applicationId: String!): PublicDomain!
deletePublicDomain(domain: String!): Boolean!
checkPublicDomainValidRecords(domain: String!): DomainValidRecords
@@ -4438,60 +4438,79 @@ input UpdateUsageLimitInput {
payload: CreateUsageLimitInput!
}
-input CreateViewFilterGroupInput {
- id: UUID
- parentViewFilterGroupId: UUID
- logicalOperator: ViewFilterGroupLogicalOperator = AND
- positionInViewFilterGroup: Float
- viewId: UUID!
+input CreatePageLayoutWidgetInput {
+ pageLayoutTabId: UUID!
+ title: String!
+ type: WidgetType!
+ objectMetadataId: UUID
+ position: JSON
+ configuration: JSON!
}
-input UpdateViewFilterGroupInput {
- id: UUID
- parentViewFilterGroupId: UUID
- logicalOperator: ViewFilterGroupLogicalOperator = AND
- positionInViewFilterGroup: Float
- viewId: UUID
+input UpdatePageLayoutWidgetInput {
+ pageLayoutTabId: UUID
+ title: String
+ type: WidgetType
+ objectMetadataId: UUID
+ position: JSON
+ configuration: JSON
+ conditionalDisplay: JSON
+ conditionalAvailabilityExpression: String
}
-input CreateViewFilterInput {
- id: UUID
- fieldMetadataId: UUID!
- operand: ViewFilterOperand
- value: JSON!
- viewFilterGroupId: UUID
- positionInViewFilterGroup: Float
- subFieldName: String
- relationTargetFieldMetadataId: UUID
- viewId: UUID!
+input CreatePageLayoutTabInput {
+ title: String!
+ position: Float
+ pageLayoutId: UUID!
+ layoutMode: PageLayoutTabLayoutMode = GRID
+}
+
+input UpdatePageLayoutTabInput {
+ title: String
+ position: Float
+ icon: String
+ layoutMode: PageLayoutTabLayoutMode
}
-input UpdateViewFilterInput {
- """The id of the view filter to update"""
- id: UUID!
+input CreatePageLayoutInput {
+ name: String!
+ type: PageLayoutType = RECORD_PAGE
+ objectMetadataId: UUID
+}
- """The view filter to update"""
- update: UpdateViewFilterInputUpdates!
+input UpdatePageLayoutInput {
+ name: String
+ type: PageLayoutType
+ objectMetadataId: UUID
}
-input UpdateViewFilterInputUpdates {
- fieldMetadataId: UUID
- operand: ViewFilterOperand
- value: JSON
- viewFilterGroupId: UUID
- positionInViewFilterGroup: Float
- subFieldName: String
- relationTargetFieldMetadataId: UUID
+input UpdatePageLayoutWithTabsInput {
+ name: String!
+ type: PageLayoutType!
+ objectMetadataId: UUID
+ isFirstTabPinned: Boolean
+ tabs: [UpdatePageLayoutTabWithWidgetsInput!]!
}
-input DeleteViewFilterInput {
- """The id of the view filter to delete."""
+input UpdatePageLayoutTabWithWidgetsInput {
id: UUID!
+ title: String!
+ position: Float!
+ icon: String
+ layoutMode: PageLayoutTabLayoutMode = GRID
+ widgets: [UpdatePageLayoutWidgetWithIdInput!]!
}
-input DestroyViewFilterInput {
- """The id of the view filter to destroy."""
+input UpdatePageLayoutWidgetWithIdInput {
id: UUID!
+ pageLayoutTabId: UUID!
+ title: String!
+ type: WidgetType!
+ objectMetadataId: UUID
+ position: JSON
+ configuration: JSON
+ conditionalDisplay: JSON
+ conditionalAvailabilityExpression: String
}
input CreateViewInput {
@@ -4657,6 +4676,46 @@ input DestroyViewSortInput {
id: UUID!
}
+input CreateViewFilterInput {
+ id: UUID
+ fieldMetadataId: UUID!
+ operand: ViewFilterOperand
+ value: JSON!
+ viewFilterGroupId: UUID
+ positionInViewFilterGroup: Float
+ subFieldName: String
+ relationTargetFieldMetadataId: UUID
+ viewId: UUID!
+}
+
+input UpdateViewFilterInput {
+ """The id of the view filter to update"""
+ id: UUID!
+
+ """The view filter to update"""
+ update: UpdateViewFilterInputUpdates!
+}
+
+input UpdateViewFilterInputUpdates {
+ fieldMetadataId: UUID
+ operand: ViewFilterOperand
+ value: JSON
+ viewFilterGroupId: UUID
+ positionInViewFilterGroup: Float
+ subFieldName: String
+ relationTargetFieldMetadataId: UUID
+}
+
+input DeleteViewFilterInput {
+ """The id of the view filter to delete."""
+ id: UUID!
+}
+
+input DestroyViewFilterInput {
+ """The id of the view filter to destroy."""
+ id: UUID!
+}
+
input UpdateViewFieldInput {
"""The id of the view field to update"""
id: UUID!
@@ -4762,113 +4821,6 @@ input UpsertFieldsWidgetFieldInput {
position: Float!
}
-input CreateApiKeyInput {
- name: String!
- expiresAt: String!
- revokedAt: String
- roleId: UUID!
-}
-
-input UpdateApiKeyInput {
- id: UUID!
- name: String
- expiresAt: String
- revokedAt: String
-}
-
-input RevokeApiKeyInput {
- id: UUID!
-}
-
-input CreateApprovedAccessDomainInput {
- domain: String!
- email: String!
-}
-
-input DeleteApprovedAccessDomainInput {
- id: UUID!
-}
-
-input ValidateApprovedAccessDomainInput {
- validationToken: String!
- approvedAccessDomainId: UUID!
-}
-
-input CreatePageLayoutTabInput {
- title: String!
- position: Float
- pageLayoutId: UUID!
- layoutMode: PageLayoutTabLayoutMode = GRID
-}
-
-input UpdatePageLayoutTabInput {
- title: String
- position: Float
- icon: String
- layoutMode: PageLayoutTabLayoutMode
-}
-
-input CreatePageLayoutInput {
- name: String!
- type: PageLayoutType = RECORD_PAGE
- objectMetadataId: UUID
-}
-
-input UpdatePageLayoutInput {
- name: String
- type: PageLayoutType
- objectMetadataId: UUID
-}
-
-input UpdatePageLayoutWithTabsInput {
- name: String!
- type: PageLayoutType!
- objectMetadataId: UUID
- isFirstTabPinned: Boolean
- tabs: [UpdatePageLayoutTabWithWidgetsInput!]!
-}
-
-input UpdatePageLayoutTabWithWidgetsInput {
- id: UUID!
- title: String!
- position: Float!
- icon: String
- layoutMode: PageLayoutTabLayoutMode = GRID
- widgets: [UpdatePageLayoutWidgetWithIdInput!]!
-}
-
-input UpdatePageLayoutWidgetWithIdInput {
- id: UUID!
- pageLayoutTabId: UUID!
- title: String!
- type: WidgetType!
- objectMetadataId: UUID
- position: JSON
- configuration: JSON
- conditionalDisplay: JSON
- conditionalAvailabilityExpression: String
-}
-
-input CreatePageLayoutWidgetInput {
- pageLayoutTabId: UUID!
- title: String!
- type: WidgetType!
- objectMetadataId: UUID
- position: JSON
- configuration: JSON!
-}
-
-input UpdatePageLayoutWidgetInput {
- pageLayoutTabId: UUID
- title: String
- type: WidgetType
- objectMetadataId: UUID
- position: JSON
- configuration: JSON
- conditionalDisplay: JSON
- conditionalAvailabilityExpression: String
-}
-
input CreateAgentInput {
name: String
label: String!
@@ -5119,6 +5071,54 @@ input UpdateWorkspaceAllowedIframeOriginsInput {
origin: String!
}
+input CreateApprovedAccessDomainInput {
+ domain: String!
+ email: String!
+}
+
+input DeleteApprovedAccessDomainInput {
+ id: UUID!
+}
+
+input ValidateApprovedAccessDomainInput {
+ validationToken: String!
+ approvedAccessDomainId: UUID!
+}
+
+input CreateViewFilterGroupInput {
+ id: UUID
+ parentViewFilterGroupId: UUID
+ logicalOperator: ViewFilterGroupLogicalOperator = AND
+ positionInViewFilterGroup: Float
+ viewId: UUID!
+}
+
+input UpdateViewFilterGroupInput {
+ id: UUID
+ parentViewFilterGroupId: UUID
+ logicalOperator: ViewFilterGroupLogicalOperator = AND
+ positionInViewFilterGroup: Float
+ viewId: UUID
+}
+
+input CreateApiKeyInput {
+ name: String!
+ expiresAt: String!
+ revokedAt: String
+ roleId: UUID!
+}
+
+input UpdateApiKeyInput {
+ id: UUID!
+ name: String
+ expiresAt: String
+ revokedAt: String
+}
+
+input RevokeApiKeyInput {
+ id: UUID!
+}
+
input CreateApplicationRegistrationInput {
name: String!
universalIdentifier: String
@@ -5575,12 +5575,6 @@ input FileAttachmentInput {
filename: String!
}
-input AgentChatQuestionAnswerInput {
- questionIndex: Int!
- selectedOptionIndices: [Int!]!
- freeText: String
-}
-
input CreateSkillInput {
id: UUID
name: String!
@@ -5731,6 +5725,12 @@ input UpdateLabPublicFeatureFlagInput {
value: Boolean!
}
+input AgentChatQuestionAnswerInput {
+ questionIndex: Int!
+ selectedOptionIndices: [Int!]!
+ freeText: String
+}
+
input ApplicationFileUploadRequestInput {
fileFolder: FileFolder!
filePath: String!
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index baadf7cc51a..aa18a7d71b2 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -2992,52 +2992,6 @@ export interface DuplicatedDashboard {
__typename: 'DuplicatedDashboard'
}
-export interface SendEmailOutput {
- success: Scalars['Boolean']
- error?: Scalars['String']
- messageThreadId?: Scalars['String']
- __typename: 'SendEmailOutput'
-}
-
-export interface Analytics {
- /** Boolean that confirms query was dispatched */
- success: Scalars['Boolean']
- __typename: 'Analytics'
-}
-
-export interface EventLogRecord {
- event: Scalars['String']
- timestamp: Scalars['DateTime']
- userId?: Scalars['String']
- properties?: Scalars['JSON']
- recordId?: Scalars['String']
- objectMetadataId?: Scalars['String']
- isCustom?: Scalars['Boolean']
- __typename: 'EventLogRecord'
-}
-
-export interface EventLogPageInfo {
- endCursor?: Scalars['String']
- hasNextPage: Scalars['Boolean']
- __typename: 'EventLogPageInfo'
-}
-
-export interface EventLogQueryResult {
- records: EventLogRecord[]
- totalCount: Scalars['Int']
- pageInfo: EventLogPageInfo
- __typename: 'EventLogQueryResult'
-}
-
-export interface RecordExport {
- id: Scalars['UUID']
- filename: Scalars['String']
- progress: Scalars['Int']
- errorMessage?: Scalars['String']
- downloadPath?: Scalars['String']
- __typename: 'RecordExport'
-}
-
export interface AiChatUsage {
limitValue: Scalars['BigInt']
consumedValue?: Scalars['BigInt']
@@ -3126,6 +3080,52 @@ export interface StartWorkspaceSetupChatResult {
export type WorkspaceSetupChatOutcome = 'STARTED' | 'ALREADY_STARTED' | 'UNAVAILABLE'
+export interface SendEmailOutput {
+ success: Scalars['Boolean']
+ error?: Scalars['String']
+ messageThreadId?: Scalars['String']
+ __typename: 'SendEmailOutput'
+}
+
+export interface Analytics {
+ /** Boolean that confirms query was dispatched */
+ success: Scalars['Boolean']
+ __typename: 'Analytics'
+}
+
+export interface EventLogRecord {
+ event: Scalars['String']
+ timestamp: Scalars['DateTime']
+ userId?: Scalars['String']
+ properties?: Scalars['JSON']
+ recordId?: Scalars['String']
+ objectMetadataId?: Scalars['String']
+ isCustom?: Scalars['Boolean']
+ __typename: 'EventLogRecord'
+}
+
+export interface EventLogPageInfo {
+ endCursor?: Scalars['String']
+ hasNextPage: Scalars['Boolean']
+ __typename: 'EventLogPageInfo'
+}
+
+export interface EventLogQueryResult {
+ records: EventLogRecord[]
+ totalCount: Scalars['Int']
+ pageInfo: EventLogPageInfo
+ __typename: 'EventLogQueryResult'
+}
+
+export interface RecordExport {
+ id: Scalars['UUID']
+ filename: Scalars['String']
+ progress: Scalars['Int']
+ errorMessage?: Scalars['String']
+ downloadPath?: Scalars['String']
+ __typename: 'RecordExport'
+}
+
export interface RecordPermissionsResult {
objectMetadataId: Scalars['UUID']
recordId: Scalars['UUID']
@@ -3355,44 +3355,29 @@ export interface Query {
usageQuotasWithConsumption: UsageQuotaWithConsumption[]
usageQuotaDefinitions: UsageQuotaDefinitions
usageQuotaScopeConsumption?: UsageQuotaScopeConsumption
- getUsageAnalytics: UsageAnalytics
- getViewFilterGroups: ViewFilterGroup[]
- getViewFilterGroup?: ViewFilterGroup
- getViewFilters: ViewFilter[]
- getViewFilter?: ViewFilter
+ getPageLayoutWidgets: PageLayoutWidget[]
+ getPageLayoutWidget: PageLayoutWidget
+ getPageLayoutTabs: PageLayoutTab[]
+ getPageLayoutTab: PageLayoutTab
+ getPageLayouts: PageLayout[]
+ getPageLayout?: PageLayout
getViews: View[]
getView?: View
getViewSorts: ViewSort[]
getViewSort?: ViewSort
+ getViewFilters: ViewFilter[]
+ getViewFilter?: ViewFilter
getViewFields: ViewField[]
getViewField?: ViewField
getViewFieldGroups: ViewFieldGroup[]
getViewFieldGroup?: ViewFieldGroup
- apiKeys: ApiKey[]
- getApiKeyRoles: Role[]
- apiKey?: ApiKey
- currentUserSessions: UserSession[]
- billingPortalSession: BillingSession
- listPlans: BillingPlan[]
- getResourceCreditUsage: BillingResourceCreditUsage[]
- myConnectedAccounts: ConnectedAccountPublicDTO[]
- applicationConnectedAccounts: ApplicationConnectedAccountDTO[]
- applicationConnectionProviders: ApplicationConnectionProvider[]
- getInviteSuggestions: InviteSuggestion[]
- findWorkspaceInvitations: WorkspaceInvitation[]
- getApprovedAccessDomains: ApprovedAccessDomain[]
- getPageLayoutTabs: PageLayoutTab[]
- getPageLayoutTab: PageLayoutTab
- getPageLayouts: PageLayout[]
- getPageLayout?: PageLayout
- getPageLayoutWidgets: PageLayoutWidget[]
- getPageLayoutWidget: PageLayoutWidget
findManyAgents: Agent[]
findOneAgent: Agent
objects: ObjectConnection
object: Object
objectRecordCounts: ObjectRecordCount[]
mostlyEmptyFieldMetadataIds: Scalars['UUID'][]
+ currentUserSessions: UserSession[]
findOneLogicFunction: LogicFunction
findManyLogicFunctions: LogicFunction[]
getAvailablePackages: Scalars['JSON']
@@ -3401,9 +3386,24 @@ export interface Query {
commandMenuItem?: CommandMenuItem
frontComponents: FrontComponent[]
frontComponent?: FrontComponent
+ billingPortalSession: BillingSession
+ listPlans: BillingPlan[]
+ getResourceCreditUsage: BillingResourceCreditUsage[]
+ getUsageAnalytics: UsageAnalytics
+ myConnectedAccounts: ConnectedAccountPublicDTO[]
+ applicationConnectedAccounts: ApplicationConnectedAccountDTO[]
+ applicationConnectionProviders: ApplicationConnectionProvider[]
currentWorkspace: Workspace
getPublicWorkspaceDataByDomain: PublicWorkspaceData
getPublicWorkspaceDataById: PublicWorkspaceDataSummary
+ getInviteSuggestions: InviteSuggestion[]
+ findWorkspaceInvitations: WorkspaceInvitation[]
+ getApprovedAccessDomains: ApprovedAccessDomain[]
+ getViewFilterGroups: ViewFilterGroup[]
+ getViewFilterGroup?: ViewFilterGroup
+ apiKeys: ApiKey[]
+ getApiKeyRoles: Role[]
+ apiKey?: ApiKey
findApplicationRegistrationByClientId?: PublicApplicationRegistration
findApplicationRegistrationByUniversalIdentifier?: ApplicationRegistration
findManyApplicationRegistrations: ApplicationRegistration[]
@@ -3511,14 +3511,19 @@ export interface Mutation {
createUsageLimit: UsageLimit
updateUsageLimit: UsageLimit
deleteUsageLimit: Scalars['Boolean']
- createViewFilterGroup: ViewFilterGroup
- updateViewFilterGroup: ViewFilterGroup
- deleteViewFilterGroup: Scalars['Boolean']
- destroyViewFilterGroup: Scalars['Boolean']
- createViewFilter: ViewFilter
- updateViewFilter: ViewFilter
- deleteViewFilter: ViewFilter
- destroyViewFilter: ViewFilter
+ createPageLayoutWidget: PageLayoutWidget
+ updatePageLayoutWidget: PageLayoutWidget
+ destroyPageLayoutWidget: Scalars['Boolean']
+ createPageLayoutTab: PageLayoutTab
+ updatePageLayoutTab: PageLayoutTab
+ destroyPageLayoutTab: Scalars['Boolean']
+ createPageLayout: PageLayout
+ updatePageLayout: PageLayout
+ destroyPageLayout: Scalars['Boolean']
+ updatePageLayoutWithTabsAndWidgets: PageLayout
+ resetPageLayoutToDefault: PageLayout
+ resetPageLayoutWidgetToDefault: PageLayoutWidget
+ resetPageLayoutTabToDefault: PageLayoutTab
createView: View
updateView: View
deleteView: Scalars['Boolean']
@@ -3528,6 +3533,10 @@ export interface Mutation {
updateViewSort: ViewSort
deleteViewSort: Scalars['Boolean']
destroyViewSort: Scalars['Boolean']
+ createViewFilter: ViewFilter
+ updateViewFilter: ViewFilter
+ deleteViewFilter: ViewFilter
+ destroyViewFilter: ViewFilter
updateViewField: ViewField
createViewField: ViewField
createManyViewFields: ViewField[]
@@ -3539,48 +3548,6 @@ export interface Mutation {
deleteViewFieldGroup: ViewFieldGroup
destroyViewFieldGroup: ViewFieldGroup
upsertFieldsWidget: View
- createApiKey: ApiKey
- updateApiKey?: ApiKey
- revokeApiKey?: ApiKey
- assignRoleToApiKey: Scalars['Boolean']
- revokeUserSession: Scalars['Boolean']
- revokeAllOtherUserSessions: Scalars['Int']
- checkoutSession: BillingSession
- createSubscriptionPaymentIntent: BillingPaymentIntent
- createBillingPaymentMethodSetupIntent: BillingPaymentIntent
- switchSubscriptionInterval: BillingUpdate
- switchBillingPlan: BillingUpdate
- cancelSwitchBillingPlan: BillingUpdate
- cancelSwitchBillingInterval: BillingUpdate
- setResourceCreditSubscriptionPrice: BillingUpdate
- endSubscriptionTrialPeriod: BillingEndTrialPeriod
- cancelSwitchResourceCreditPrice: BillingUpdate
- deleteConnectedAccount: ConnectedAccountPublicDTO
- disconnectConnectedAccount: ConnectedAccountPublicDTO
- updateOneApplicationVariable: Scalars['Boolean']
- skipSyncEmailOnboardingStep: OnboardingStepSuccess
- completeBookCallOnboardingStep: OnboardingStepSuccess
- triggerInstallAppsOnboardingStep: OnboardingStepSuccess
- goBackToPreviousOnboardingStep: OnboardingStepNavigation
- deleteWorkspaceInvitation: Scalars['String']
- resendWorkspaceInvitation: SendInvitations
- sendInvitations: SendInvitations
- createApprovedAccessDomain: ApprovedAccessDomain
- deleteApprovedAccessDomain: Scalars['Boolean']
- validateApprovedAccessDomain: ApprovedAccessDomain
- createPageLayoutTab: PageLayoutTab
- updatePageLayoutTab: PageLayoutTab
- destroyPageLayoutTab: Scalars['Boolean']
- createPageLayout: PageLayout
- updatePageLayout: PageLayout
- destroyPageLayout: Scalars['Boolean']
- updatePageLayoutWithTabsAndWidgets: PageLayout
- resetPageLayoutToDefault: PageLayout
- resetPageLayoutWidgetToDefault: PageLayoutWidget
- resetPageLayoutTabToDefault: PageLayoutTab
- createPageLayoutWidget: PageLayoutWidget
- updatePageLayoutWidget: PageLayoutWidget
- destroyPageLayoutWidget: Scalars['Boolean']
createOneAgent: Agent
updateOneAgent: Agent
deleteOneAgent: Agent
@@ -3590,6 +3557,8 @@ export interface Mutation {
updateManyObjects: Object[]
createOneIndex: Index
deleteOneIndex: Index
+ revokeUserSession: Scalars['Boolean']
+ revokeAllOtherUserSessions: Scalars['Int']
deleteOneLogicFunction: LogicFunction
createOneLogicFunction: LogicFunction
executeOneLogicFunction: LogicFunctionExecutionResult
@@ -3602,12 +3571,43 @@ export interface Mutation {
createFrontComponent: FrontComponent
updateFrontComponent: FrontComponent
deleteFrontComponent: FrontComponent
+ updateOneApplicationVariable: Scalars['Boolean']
+ checkoutSession: BillingSession
+ createSubscriptionPaymentIntent: BillingPaymentIntent
+ createBillingPaymentMethodSetupIntent: BillingPaymentIntent
+ switchSubscriptionInterval: BillingUpdate
+ switchBillingPlan: BillingUpdate
+ cancelSwitchBillingPlan: BillingUpdate
+ cancelSwitchBillingInterval: BillingUpdate
+ setResourceCreditSubscriptionPrice: BillingUpdate
+ endSubscriptionTrialPeriod: BillingEndTrialPeriod
+ cancelSwitchResourceCreditPrice: BillingUpdate
+ deleteConnectedAccount: ConnectedAccountPublicDTO
+ disconnectConnectedAccount: ConnectedAccountPublicDTO
activateWorkspace: Workspace
updateWorkspace: Workspace
updateWorkspaceAllowedIframeOrigins: Workspace
deleteCurrentWorkspace: Workspace
checkCustomDomainValidRecords?: DomainValidRecords
enrichWorkspaceCompany: WorkspaceCompanyEnrichmentResult
+ skipSyncEmailOnboardingStep: OnboardingStepSuccess
+ completeBookCallOnboardingStep: OnboardingStepSuccess
+ triggerInstallAppsOnboardingStep: OnboardingStepSuccess
+ goBackToPreviousOnboardingStep: OnboardingStepNavigation
+ deleteWorkspaceInvitation: Scalars['String']
+ resendWorkspaceInvitation: SendInvitations
+ sendInvitations: SendInvitations
+ createApprovedAccessDomain: ApprovedAccessDomain
+ deleteApprovedAccessDomain: Scalars['Boolean']
+ validateApprovedAccessDomain: ApprovedAccessDomain
+ createViewFilterGroup: ViewFilterGroup
+ updateViewFilterGroup: ViewFilterGroup
+ deleteViewFilterGroup: Scalars['Boolean']
+ destroyViewFilterGroup: Scalars['Boolean']
+ createApiKey: ApiKey
+ updateApiKey?: ApiKey
+ revokeApiKey?: ApiKey
+ assignRoleToApiKey: Scalars['Boolean']
upgradeApplication: Scalars['Boolean']
createApplicationRegistration: CreateApplicationRegistration
updateApplicationRegistration: ApplicationRegistration
@@ -3684,7 +3684,6 @@ export interface Mutation {
createChatThread: AgentChatThread
sendChatMessage: SendChatMessageResult
retryChatMessage: SendChatMessageResult
- answerAgentChatQuestion: SendChatMessageResult
stopAgentChatStream: Scalars['Boolean']
renameChatThread: AgentChatThread
archiveChatThread: AgentChatThread
@@ -3750,6 +3749,8 @@ export interface Mutation {
startChannelSync: ChannelSyncSuccess
saveImapSmtpCaldavAccount: ImapSmtpCaldavConnectionSuccess
updateLabPublicFeatureFlag: FeatureFlag
+ /** @deprecated Use answerAsk with the question's Ask */
+ answerAgentChatQuestion: SendChatMessageResult
createPublicDomain: PublicDomain
deletePublicDomain: Scalars['Boolean']
checkPublicDomainValidRecords?: DomainValidRecords
@@ -6899,63 +6900,11 @@ export interface DuplicatedDashboardGenqlSelection{
__scalar?: boolean | number
}
-export interface SendEmailOutputGenqlSelection{
- success?: boolean | number
- error?: boolean | number
- messageThreadId?: boolean | number
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
-export interface AnalyticsGenqlSelection{
- /** Boolean that confirms query was dispatched */
- success?: boolean | number
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
-export interface EventLogRecordGenqlSelection{
- event?: boolean | number
- timestamp?: boolean | number
- userId?: boolean | number
- properties?: boolean | number
- recordId?: boolean | number
- objectMetadataId?: boolean | number
- isCustom?: boolean | number
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
-export interface EventLogPageInfoGenqlSelection{
- endCursor?: boolean | number
- hasNextPage?: boolean | number
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
-export interface EventLogQueryResultGenqlSelection{
- records?: EventLogRecordGenqlSelection
- totalCount?: boolean | number
- pageInfo?: EventLogPageInfoGenqlSelection
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
-export interface RecordExportGenqlSelection{
- id?: boolean | number
- filename?: boolean | number
- progress?: boolean | number
- errorMessage?: boolean | number
- downloadPath?: boolean | number
- __typename?: boolean | number
- __scalar?: boolean | number
-}
-
-export interface AiChatUsageGenqlSelection{
- limitValue?: boolean | number
- consumedValue?: boolean | number
- periodEnd?: boolean | number
- kind?: boolean | number
+export interface AiChatUsageGenqlSelection{
+ limitValue?: boolean | number
+ consumedValue?: boolean | number
+ periodEnd?: boolean | number
+ kind?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
@@ -7047,6 +6996,58 @@ export interface StartWorkspaceSetupChatResultGenqlSelection{
__scalar?: boolean | number
}
+export interface SendEmailOutputGenqlSelection{
+ success?: boolean | number
+ error?: boolean | number
+ messageThreadId?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
+export interface AnalyticsGenqlSelection{
+ /** Boolean that confirms query was dispatched */
+ success?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
+export interface EventLogRecordGenqlSelection{
+ event?: boolean | number
+ timestamp?: boolean | number
+ userId?: boolean | number
+ properties?: boolean | number
+ recordId?: boolean | number
+ objectMetadataId?: boolean | number
+ isCustom?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
+export interface EventLogPageInfoGenqlSelection{
+ endCursor?: boolean | number
+ hasNextPage?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
+export interface EventLogQueryResultGenqlSelection{
+ records?: EventLogRecordGenqlSelection
+ totalCount?: boolean | number
+ pageInfo?: EventLogPageInfoGenqlSelection
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
+export interface RecordExportGenqlSelection{
+ id?: boolean | number
+ filename?: boolean | number
+ progress?: boolean | number
+ errorMessage?: boolean | number
+ downloadPath?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
export interface RecordPermissionsResultGenqlSelection{
objectMetadataId?: boolean | number
recordId?: boolean | number
@@ -7275,38 +7276,22 @@ export interface QueryGenqlSelection{
usageQuotasWithConsumption?: UsageQuotaWithConsumptionGenqlSelection
usageQuotaDefinitions?: UsageQuotaDefinitionsGenqlSelection
usageQuotaScopeConsumption?: (UsageQuotaScopeConsumptionGenqlSelection & { __args: {input: UsageQuotaScopeInput} })
- getUsageAnalytics?: (UsageAnalyticsGenqlSelection & { __args?: {input?: (UsageAnalyticsInput | null)} })
- getViewFilterGroups?: (ViewFilterGroupGenqlSelection & { __args?: {viewId?: (Scalars['String'] | null)} })
- getViewFilterGroup?: (ViewFilterGroupGenqlSelection & { __args: {id: Scalars['String']} })
- getViewFilters?: (ViewFilterGenqlSelection & { __args?: {viewId?: (Scalars['String'] | null)} })
- getViewFilter?: (ViewFilterGenqlSelection & { __args: {id: Scalars['String']} })
+ getPageLayoutWidgets?: (PageLayoutWidgetGenqlSelection & { __args: {pageLayoutTabId: Scalars['String']} })
+ getPageLayoutWidget?: (PageLayoutWidgetGenqlSelection & { __args: {id: Scalars['String']} })
+ getPageLayoutTabs?: (PageLayoutTabGenqlSelection & { __args: {pageLayoutId: Scalars['String']} })
+ getPageLayoutTab?: (PageLayoutTabGenqlSelection & { __args: {id: Scalars['String']} })
+ getPageLayouts?: (PageLayoutGenqlSelection & { __args?: {objectMetadataId?: (Scalars['String'] | null), pageLayoutType?: (PageLayoutType | null)} })
+ getPageLayout?: (PageLayoutGenqlSelection & { __args: {id: Scalars['String']} })
getViews?: (ViewGenqlSelection & { __args?: {objectMetadataId?: (Scalars['String'] | null), viewTypes?: (ViewType[] | null)} })
getView?: (ViewGenqlSelection & { __args: {id: Scalars['String']} })
getViewSorts?: (ViewSortGenqlSelection & { __args?: {viewId?: (Scalars['String'] | null)} })
getViewSort?: (ViewSortGenqlSelection & { __args: {id: Scalars['String']} })
+ getViewFilters?: (ViewFilterGenqlSelection & { __args?: {viewId?: (Scalars['String'] | null)} })
+ getViewFilter?: (ViewFilterGenqlSelection & { __args: {id: Scalars['String']} })
getViewFields?: (ViewFieldGenqlSelection & { __args: {viewId: Scalars['String']} })
getViewField?: (ViewFieldGenqlSelection & { __args: {id: Scalars['String']} })
getViewFieldGroups?: (ViewFieldGroupGenqlSelection & { __args: {viewId: Scalars['String']} })
getViewFieldGroup?: (ViewFieldGroupGenqlSelection & { __args: {id: Scalars['String']} })
- apiKeys?: ApiKeyGenqlSelection
- getApiKeyRoles?: RoleGenqlSelection
- apiKey?: (ApiKeyGenqlSelection & { __args: {input: GetApiKeyInput} })
- currentUserSessions?: UserSessionGenqlSelection
- billingPortalSession?: (BillingSessionGenqlSelection & { __args?: {returnUrlPath?: (Scalars['String'] | null), forPaymentMethodUpdate?: (Scalars['Boolean'] | null)} })
- listPlans?: BillingPlanGenqlSelection
- getResourceCreditUsage?: BillingResourceCreditUsageGenqlSelection
- myConnectedAccounts?: ConnectedAccountPublicDTOGenqlSelection
- applicationConnectedAccounts?: (ApplicationConnectedAccountDTOGenqlSelection & { __args: {applicationId: Scalars['UUID']} })
- applicationConnectionProviders?: (ApplicationConnectionProviderGenqlSelection & { __args: {applicationId: Scalars['UUID']} })
- getInviteSuggestions?: InviteSuggestionGenqlSelection
- findWorkspaceInvitations?: WorkspaceInvitationGenqlSelection
- getApprovedAccessDomains?: ApprovedAccessDomainGenqlSelection
- getPageLayoutTabs?: (PageLayoutTabGenqlSelection & { __args: {pageLayoutId: Scalars['String']} })
- getPageLayoutTab?: (PageLayoutTabGenqlSelection & { __args: {id: Scalars['String']} })
- getPageLayouts?: (PageLayoutGenqlSelection & { __args?: {objectMetadataId?: (Scalars['String'] | null), pageLayoutType?: (PageLayoutType | null)} })
- getPageLayout?: (PageLayoutGenqlSelection & { __args: {id: Scalars['String']} })
- getPageLayoutWidgets?: (PageLayoutWidgetGenqlSelection & { __args: {pageLayoutTabId: Scalars['String']} })
- getPageLayoutWidget?: (PageLayoutWidgetGenqlSelection & { __args: {id: Scalars['String']} })
findManyAgents?: AgentGenqlSelection
findOneAgent?: (AgentGenqlSelection & { __args: {input: AgentIdInput} })
objects?: (ObjectConnectionGenqlSelection & { __args: {
@@ -7319,6 +7304,7 @@ export interface QueryGenqlSelection{
id: Scalars['UUID']} })
objectRecordCounts?: ObjectRecordCountGenqlSelection
mostlyEmptyFieldMetadataIds?: { __args: {objectMetadataId: Scalars['UUID']} }
+ currentUserSessions?: UserSessionGenqlSelection
findOneLogicFunction?: (LogicFunctionGenqlSelection & { __args: {input: LogicFunctionIdInput} })
findManyLogicFunctions?: LogicFunctionGenqlSelection
getAvailablePackages?: { __args: {input: LogicFunctionIdInput} }
@@ -7327,9 +7313,24 @@ export interface QueryGenqlSelection{
commandMenuItem?: (CommandMenuItemGenqlSelection & { __args: {id: Scalars['UUID']} })
frontComponents?: FrontComponentGenqlSelection
frontComponent?: (FrontComponentGenqlSelection & { __args: {id: Scalars['UUID']} })
+ billingPortalSession?: (BillingSessionGenqlSelection & { __args?: {returnUrlPath?: (Scalars['String'] | null), forPaymentMethodUpdate?: (Scalars['Boolean'] | null)} })
+ listPlans?: BillingPlanGenqlSelection
+ getResourceCreditUsage?: BillingResourceCreditUsageGenqlSelection
+ getUsageAnalytics?: (UsageAnalyticsGenqlSelection & { __args?: {input?: (UsageAnalyticsInput | null)} })
+ myConnectedAccounts?: ConnectedAccountPublicDTOGenqlSelection
+ applicationConnectedAccounts?: (ApplicationConnectedAccountDTOGenqlSelection & { __args: {applicationId: Scalars['UUID']} })
+ applicationConnectionProviders?: (ApplicationConnectionProviderGenqlSelection & { __args: {applicationId: Scalars['UUID']} })
currentWorkspace?: WorkspaceGenqlSelection
getPublicWorkspaceDataByDomain?: (PublicWorkspaceDataGenqlSelection & { __args?: {origin?: (Scalars['String'] | null)} })
getPublicWorkspaceDataById?: (PublicWorkspaceDataSummaryGenqlSelection & { __args: {id: Scalars['UUID']} })
+ getInviteSuggestions?: InviteSuggestionGenqlSelection
+ findWorkspaceInvitations?: WorkspaceInvitationGenqlSelection
+ getApprovedAccessDomains?: ApprovedAccessDomainGenqlSelection
+ getViewFilterGroups?: (ViewFilterGroupGenqlSelection & { __args?: {viewId?: (Scalars['String'] | null)} })
+ getViewFilterGroup?: (ViewFilterGroupGenqlSelection & { __args: {id: Scalars['String']} })
+ apiKeys?: ApiKeyGenqlSelection
+ getApiKeyRoles?: RoleGenqlSelection
+ apiKey?: (ApiKeyGenqlSelection & { __args: {input: GetApiKeyInput} })
findApplicationRegistrationByClientId?: (PublicApplicationRegistrationGenqlSelection & { __args: {clientId: Scalars['String']} })
findApplicationRegistrationByUniversalIdentifier?: (ApplicationRegistrationGenqlSelection & { __args: {universalIdentifier: Scalars['String']} })
findManyApplicationRegistrations?: ApplicationRegistrationGenqlSelection
@@ -7418,10 +7419,6 @@ export interface RecordSharingTargetInput {objectMetadataId: Scalars['UUID'],rec
export interface UsageQuotaScopeInput {resourceType: UsageResourceType,operationType: UsageOperationType,spenderType: Scalars['String'],spenderId?: (Scalars['String'] | null),periodUnit: Scalars['String'],meter: Scalars['String']}
-export interface UsageAnalyticsInput {periodStart?: (Scalars['DateTime'] | null),periodEnd?: (Scalars['DateTime'] | null),userWorkspaceId?: (Scalars['String'] | null),operationTypes?: (UsageOperationType[] | null)}
-
-export interface GetApiKeyInput {id: Scalars['UUID']}
-
export interface AgentIdInput {
/** The id of the agent. */
id: Scalars['UUID']}
@@ -7432,6 +7429,10 @@ export interface LogicFunctionIdInput {
/** The id of the function. */
id: Scalars['ID']}
+export interface UsageAnalyticsInput {periodStart?: (Scalars['DateTime'] | null),periodEnd?: (Scalars['DateTime'] | null),userWorkspaceId?: (Scalars['String'] | null),operationTypes?: (UsageOperationType[] | null)}
+
+export interface GetApiKeyInput {id: Scalars['UUID']}
+
export interface PreviewMessageCampaignAudienceInput {listId: Scalars['String'],unsubscribeTopicId?: (Scalars['String'] | null)}
export interface FindMessageSuppressionsInput {reason?: (MessageSuppressionReason | null),searchTerm?: (Scalars['String'] | null),unsubscribeTopicId?: (Scalars['UUID'] | null),limit: Scalars['Int'],offset: Scalars['Int']}
@@ -7484,14 +7485,19 @@ export interface MutationGenqlSelection{
createUsageLimit?: (UsageLimitGenqlSelection & { __args: {input: CreateUsageLimitInput} })
updateUsageLimit?: (UsageLimitGenqlSelection & { __args: {input: UpdateUsageLimitInput} })
deleteUsageLimit?: { __args: {usageLimitId: Scalars['UUID']} }
- createViewFilterGroup?: (ViewFilterGroupGenqlSelection & { __args: {input: CreateViewFilterGroupInput} })
- updateViewFilterGroup?: (ViewFilterGroupGenqlSelection & { __args: {id: Scalars['String'], input: UpdateViewFilterGroupInput} })
- deleteViewFilterGroup?: { __args: {id: Scalars['String']} }
- destroyViewFilterGroup?: { __args: {id: Scalars['String']} }
- createViewFilter?: (ViewFilterGenqlSelection & { __args: {input: CreateViewFilterInput} })
- updateViewFilter?: (ViewFilterGenqlSelection & { __args: {input: UpdateViewFilterInput} })
- deleteViewFilter?: (ViewFilterGenqlSelection & { __args: {input: DeleteViewFilterInput} })
- destroyViewFilter?: (ViewFilterGenqlSelection & { __args: {input: DestroyViewFilterInput} })
+ createPageLayoutWidget?: (PageLayoutWidgetGenqlSelection & { __args: {input: CreatePageLayoutWidgetInput} })
+ updatePageLayoutWidget?: (PageLayoutWidgetGenqlSelection & { __args: {id: Scalars['String'], input: UpdatePageLayoutWidgetInput} })
+ destroyPageLayoutWidget?: { __args: {id: Scalars['String']} }
+ createPageLayoutTab?: (PageLayoutTabGenqlSelection & { __args: {input: CreatePageLayoutTabInput} })
+ updatePageLayoutTab?: (PageLayoutTabGenqlSelection & { __args: {id: Scalars['String'], input: UpdatePageLayoutTabInput} })
+ destroyPageLayoutTab?: { __args: {id: Scalars['String']} }
+ createPageLayout?: (PageLayoutGenqlSelection & { __args: {input: CreatePageLayoutInput} })
+ updatePageLayout?: (PageLayoutGenqlSelection & { __args: {id: Scalars['String'], input: UpdatePageLayoutInput} })
+ destroyPageLayout?: { __args: {id: Scalars['String']} }
+ updatePageLayoutWithTabsAndWidgets?: (PageLayoutGenqlSelection & { __args: {id: Scalars['String'], input: UpdatePageLayoutWithTabsInput} })
+ resetPageLayoutToDefault?: (PageLayoutGenqlSelection & { __args: {id: Scalars['String']} })
+ resetPageLayoutWidgetToDefault?: (PageLayoutWidgetGenqlSelection & { __args: {id: Scalars['String']} })
+ resetPageLayoutTabToDefault?: (PageLayoutTabGenqlSelection & { __args: {id: Scalars['String']} })
createView?: (ViewGenqlSelection & { __args: {input: CreateViewInput} })
updateView?: (ViewGenqlSelection & { __args: {id: Scalars['String'], input: UpdateViewInput} })
deleteView?: { __args: {id: Scalars['String']} }
@@ -7501,6 +7507,10 @@ export interface MutationGenqlSelection{
updateViewSort?: (ViewSortGenqlSelection & { __args: {input: UpdateViewSortInput} })
deleteViewSort?: { __args: {input: DeleteViewSortInput} }
destroyViewSort?: { __args: {input: DestroyViewSortInput} }
+ createViewFilter?: (ViewFilterGenqlSelection & { __args: {input: CreateViewFilterInput} })
+ updateViewFilter?: (ViewFilterGenqlSelection & { __args: {input: UpdateViewFilterInput} })
+ deleteViewFilter?: (ViewFilterGenqlSelection & { __args: {input: DeleteViewFilterInput} })
+ destroyViewFilter?: (ViewFilterGenqlSelection & { __args: {input: DestroyViewFilterInput} })
updateViewField?: (ViewFieldGenqlSelection & { __args: {input: UpdateViewFieldInput} })
createViewField?: (ViewFieldGenqlSelection & { __args: {input: CreateViewFieldInput} })
createManyViewFields?: (ViewFieldGenqlSelection & { __args: {inputs: CreateViewFieldInput[]} })
@@ -7512,48 +7522,6 @@ export interface MutationGenqlSelection{
deleteViewFieldGroup?: (ViewFieldGroupGenqlSelection & { __args: {input: DeleteViewFieldGroupInput} })
destroyViewFieldGroup?: (ViewFieldGroupGenqlSelection & { __args: {input: DestroyViewFieldGroupInput} })
upsertFieldsWidget?: (ViewGenqlSelection & { __args: {input: UpsertFieldsWidgetInput} })
- createApiKey?: (ApiKeyGenqlSelection & { __args: {input: CreateApiKeyInput} })
- updateApiKey?: (ApiKeyGenqlSelection & { __args: {input: UpdateApiKeyInput} })
- revokeApiKey?: (ApiKeyGenqlSelection & { __args: {input: RevokeApiKeyInput} })
- assignRoleToApiKey?: { __args: {apiKeyId: Scalars['UUID'], roleId: Scalars['UUID']} }
- revokeUserSession?: { __args: {userSessionId: Scalars['UUID']} }
- revokeAllOtherUserSessions?: boolean | number
- checkoutSession?: (BillingSessionGenqlSelection & { __args: {recurringInterval: SubscriptionInterval, plan: BillingPlanKey, requirePaymentMethod: Scalars['Boolean'], successUrlPath?: (Scalars['String'] | null)} })
- createSubscriptionPaymentIntent?: (BillingPaymentIntentGenqlSelection & { __args: {recurringInterval: SubscriptionInterval, plan: BillingPlanKey, requirePaymentMethod: Scalars['Boolean'], successUrlPath?: (Scalars['String'] | null), idempotencyKey: Scalars['String']} })
- createBillingPaymentMethodSetupIntent?: BillingPaymentIntentGenqlSelection
- switchSubscriptionInterval?: BillingUpdateGenqlSelection
- switchBillingPlan?: BillingUpdateGenqlSelection
- cancelSwitchBillingPlan?: BillingUpdateGenqlSelection
- cancelSwitchBillingInterval?: BillingUpdateGenqlSelection
- setResourceCreditSubscriptionPrice?: (BillingUpdateGenqlSelection & { __args: {priceId: Scalars['String']} })
- endSubscriptionTrialPeriod?: BillingEndTrialPeriodGenqlSelection
- cancelSwitchResourceCreditPrice?: BillingUpdateGenqlSelection
- deleteConnectedAccount?: (ConnectedAccountPublicDTOGenqlSelection & { __args: {id: Scalars['UUID']} })
- disconnectConnectedAccount?: (ConnectedAccountPublicDTOGenqlSelection & { __args: {id: Scalars['UUID']} })
- updateOneApplicationVariable?: { __args: {key: Scalars['String'], value: Scalars['String'], applicationId?: (Scalars['UUID'] | null)} }
- skipSyncEmailOnboardingStep?: (OnboardingStepSuccessGenqlSelection & { __args: {isAutoSkipped: Scalars['Boolean']} })
- completeBookCallOnboardingStep?: (OnboardingStepSuccessGenqlSelection & { __args: {hasBookedCall: Scalars['Boolean'], isAutoSkipped: Scalars['Boolean']} })
- triggerInstallAppsOnboardingStep?: (OnboardingStepSuccessGenqlSelection & { __args: {universalIdentifiers: Scalars['String'][], isAutoSkipped: Scalars['Boolean']} })
- goBackToPreviousOnboardingStep?: OnboardingStepNavigationGenqlSelection
- deleteWorkspaceInvitation?: { __args: {appTokenId: Scalars['String']} }
- resendWorkspaceInvitation?: (SendInvitationsGenqlSelection & { __args: {appTokenId: Scalars['String']} })
- sendInvitations?: (SendInvitationsGenqlSelection & { __args: {emails: Scalars['String'][], roleId?: (Scalars['UUID'] | null)} })
- createApprovedAccessDomain?: (ApprovedAccessDomainGenqlSelection & { __args: {input: CreateApprovedAccessDomainInput} })
- deleteApprovedAccessDomain?: { __args: {input: DeleteApprovedAccessDomainInput} }
- validateApprovedAccessDomain?: (ApprovedAccessDomainGenqlSelection & { __args: {input: ValidateApprovedAccessDomainInput} })
- createPageLayoutTab?: (PageLayoutTabGenqlSelection & { __args: {input: CreatePageLayoutTabInput} })
- updatePageLayoutTab?: (PageLayoutTabGenqlSelection & { __args: {id: Scalars['String'], input: UpdatePageLayoutTabInput} })
- destroyPageLayoutTab?: { __args: {id: Scalars['String']} }
- createPageLayout?: (PageLayoutGenqlSelection & { __args: {input: CreatePageLayoutInput} })
- updatePageLayout?: (PageLayoutGenqlSelection & { __args: {id: Scalars['String'], input: UpdatePageLayoutInput} })
- destroyPageLayout?: { __args: {id: Scalars['String']} }
- updatePageLayoutWithTabsAndWidgets?: (PageLayoutGenqlSelection & { __args: {id: Scalars['String'], input: UpdatePageLayoutWithTabsInput} })
- resetPageLayoutToDefault?: (PageLayoutGenqlSelection & { __args: {id: Scalars['String']} })
- resetPageLayoutWidgetToDefault?: (PageLayoutWidgetGenqlSelection & { __args: {id: Scalars['String']} })
- resetPageLayoutTabToDefault?: (PageLayoutTabGenqlSelection & { __args: {id: Scalars['String']} })
- createPageLayoutWidget?: (PageLayoutWidgetGenqlSelection & { __args: {input: CreatePageLayoutWidgetInput} })
- updatePageLayoutWidget?: (PageLayoutWidgetGenqlSelection & { __args: {id: Scalars['String'], input: UpdatePageLayoutWidgetInput} })
- destroyPageLayoutWidget?: { __args: {id: Scalars['String']} }
createOneAgent?: (AgentGenqlSelection & { __args: {input: CreateAgentInput} })
updateOneAgent?: (AgentGenqlSelection & { __args: {input: UpdateAgentInput} })
deleteOneAgent?: (AgentGenqlSelection & { __args: {input: AgentIdInput} })
@@ -7563,6 +7531,8 @@ export interface MutationGenqlSelection{
updateManyObjects?: (ObjectGenqlSelection & { __args: {inputs: UpdateOneObjectInput[]} })
createOneIndex?: (IndexGenqlSelection & { __args: {input: CreateOneIndexInput} })
deleteOneIndex?: (IndexGenqlSelection & { __args: {input: DeleteOneIndexInput} })
+ revokeUserSession?: { __args: {userSessionId: Scalars['UUID']} }
+ revokeAllOtherUserSessions?: boolean | number
deleteOneLogicFunction?: (LogicFunctionGenqlSelection & { __args: {input: LogicFunctionIdInput} })
createOneLogicFunction?: (LogicFunctionGenqlSelection & { __args: {input: CreateLogicFunctionFromSourceInput} })
executeOneLogicFunction?: (LogicFunctionExecutionResultGenqlSelection & { __args: {input: ExecuteOneLogicFunctionInput} })
@@ -7575,12 +7545,43 @@ export interface MutationGenqlSelection{
createFrontComponent?: (FrontComponentGenqlSelection & { __args: {input: CreateFrontComponentInput} })
updateFrontComponent?: (FrontComponentGenqlSelection & { __args: {input: UpdateFrontComponentInput} })
deleteFrontComponent?: (FrontComponentGenqlSelection & { __args: {id: Scalars['UUID']} })
+ updateOneApplicationVariable?: { __args: {key: Scalars['String'], value: Scalars['String'], applicationId?: (Scalars['UUID'] | null)} }
+ checkoutSession?: (BillingSessionGenqlSelection & { __args: {recurringInterval: SubscriptionInterval, plan: BillingPlanKey, requirePaymentMethod: Scalars['Boolean'], successUrlPath?: (Scalars['String'] | null)} })
+ createSubscriptionPaymentIntent?: (BillingPaymentIntentGenqlSelection & { __args: {recurringInterval: SubscriptionInterval, plan: BillingPlanKey, requirePaymentMethod: Scalars['Boolean'], successUrlPath?: (Scalars['String'] | null), idempotencyKey: Scalars['String']} })
+ createBillingPaymentMethodSetupIntent?: BillingPaymentIntentGenqlSelection
+ switchSubscriptionInterval?: BillingUpdateGenqlSelection
+ switchBillingPlan?: BillingUpdateGenqlSelection
+ cancelSwitchBillingPlan?: BillingUpdateGenqlSelection
+ cancelSwitchBillingInterval?: BillingUpdateGenqlSelection
+ setResourceCreditSubscriptionPrice?: (BillingUpdateGenqlSelection & { __args: {priceId: Scalars['String']} })
+ endSubscriptionTrialPeriod?: BillingEndTrialPeriodGenqlSelection
+ cancelSwitchResourceCreditPrice?: BillingUpdateGenqlSelection
+ deleteConnectedAccount?: (ConnectedAccountPublicDTOGenqlSelection & { __args: {id: Scalars['UUID']} })
+ disconnectConnectedAccount?: (ConnectedAccountPublicDTOGenqlSelection & { __args: {id: Scalars['UUID']} })
activateWorkspace?: (WorkspaceGenqlSelection & { __args: {data: ActivateWorkspaceInput} })
updateWorkspace?: (WorkspaceGenqlSelection & { __args: {data: UpdateWorkspaceInput} })
updateWorkspaceAllowedIframeOrigins?: (WorkspaceGenqlSelection & { __args: {data: UpdateWorkspaceAllowedIframeOriginsInput} })
deleteCurrentWorkspace?: WorkspaceGenqlSelection
checkCustomDomainValidRecords?: DomainValidRecordsGenqlSelection
enrichWorkspaceCompany?: WorkspaceCompanyEnrichmentResultGenqlSelection
+ skipSyncEmailOnboardingStep?: (OnboardingStepSuccessGenqlSelection & { __args: {isAutoSkipped: Scalars['Boolean']} })
+ completeBookCallOnboardingStep?: (OnboardingStepSuccessGenqlSelection & { __args: {hasBookedCall: Scalars['Boolean'], isAutoSkipped: Scalars['Boolean']} })
+ triggerInstallAppsOnboardingStep?: (OnboardingStepSuccessGenqlSelection & { __args: {universalIdentifiers: Scalars['String'][], isAutoSkipped: Scalars['Boolean']} })
+ goBackToPreviousOnboardingStep?: OnboardingStepNavigationGenqlSelection
+ deleteWorkspaceInvitation?: { __args: {appTokenId: Scalars['String']} }
+ resendWorkspaceInvitation?: (SendInvitationsGenqlSelection & { __args: {appTokenId: Scalars['String']} })
+ sendInvitations?: (SendInvitationsGenqlSelection & { __args: {emails: Scalars['String'][], roleId?: (Scalars['UUID'] | null)} })
+ createApprovedAccessDomain?: (ApprovedAccessDomainGenqlSelection & { __args: {input: CreateApprovedAccessDomainInput} })
+ deleteApprovedAccessDomain?: { __args: {input: DeleteApprovedAccessDomainInput} }
+ validateApprovedAccessDomain?: (ApprovedAccessDomainGenqlSelection & { __args: {input: ValidateApprovedAccessDomainInput} })
+ createViewFilterGroup?: (ViewFilterGroupGenqlSelection & { __args: {input: CreateViewFilterGroupInput} })
+ updateViewFilterGroup?: (ViewFilterGroupGenqlSelection & { __args: {id: Scalars['String'], input: UpdateViewFilterGroupInput} })
+ deleteViewFilterGroup?: { __args: {id: Scalars['String']} }
+ destroyViewFilterGroup?: { __args: {id: Scalars['String']} }
+ createApiKey?: (ApiKeyGenqlSelection & { __args: {input: CreateApiKeyInput} })
+ updateApiKey?: (ApiKeyGenqlSelection & { __args: {input: UpdateApiKeyInput} })
+ revokeApiKey?: (ApiKeyGenqlSelection & { __args: {input: RevokeApiKeyInput} })
+ assignRoleToApiKey?: { __args: {apiKeyId: Scalars['UUID'], roleId: Scalars['UUID']} }
upgradeApplication?: { __args: {appRegistrationId: Scalars['String'], targetVersion: Scalars['String']} }
createApplicationRegistration?: (CreateApplicationRegistrationGenqlSelection & { __args: {input: CreateApplicationRegistrationInput} })
updateApplicationRegistration?: (ApplicationRegistrationGenqlSelection & { __args: {input: UpdateApplicationRegistrationInput} })
@@ -7657,7 +7658,6 @@ export interface MutationGenqlSelection{
createChatThread?: AgentChatThreadGenqlSelection
sendChatMessage?: (SendChatMessageResultGenqlSelection & { __args: {threadId: Scalars['UUID'], text: Scalars['String'], messageId: Scalars['UUID'], browsingContext?: (Scalars['JSON'] | null), modelId?: (Scalars['String'] | null), fileAttachments?: (FileAttachmentInput[] | null)} })
retryChatMessage?: (SendChatMessageResultGenqlSelection & { __args: {threadId: Scalars['UUID'], modelId?: (Scalars['String'] | null)} })
- answerAgentChatQuestion?: (SendChatMessageResultGenqlSelection & { __args: {threadId: Scalars['UUID'], messageId: Scalars['UUID'], answers: AgentChatQuestionAnswerInput[], modelId?: (Scalars['String'] | null), fileAttachments?: (FileAttachmentInput[] | null)} })
stopAgentChatStream?: { __args: {threadId: Scalars['UUID']} }
renameChatThread?: (AgentChatThreadGenqlSelection & { __args: {id: Scalars['UUID'], title: Scalars['String']} })
archiveChatThread?: (AgentChatThreadGenqlSelection & { __args: {id: Scalars['UUID']} })
@@ -7723,6 +7723,8 @@ export interface MutationGenqlSelection{
startChannelSync?: (ChannelSyncSuccessGenqlSelection & { __args: {connectedAccountId: Scalars['UUID']} })
saveImapSmtpCaldavAccount?: (ImapSmtpCaldavConnectionSuccessGenqlSelection & { __args: {handle: Scalars['String'], connectionParameters: EmailAccountConnectionParameters, id?: (Scalars['UUID'] | null)} })
updateLabPublicFeatureFlag?: (FeatureFlagGenqlSelection & { __args: {input: UpdateLabPublicFeatureFlagInput} })
+ /** @deprecated Use answerAsk with the question's Ask */
+ answerAgentChatQuestion?: (SendChatMessageResultGenqlSelection & { __args: {threadId: Scalars['UUID'], messageId: Scalars['UUID'], answers: AgentChatQuestionAnswerInput[], modelId?: (Scalars['String'] | null), fileAttachments?: (FileAttachmentInput[] | null)} })
createPublicDomain?: (PublicDomainGenqlSelection & { __args: {domain: Scalars['String'], applicationId: Scalars['String']} })
deletePublicDomain?: { __args: {domain: Scalars['String']} }
checkPublicDomainValidRecords?: (DomainValidRecordsGenqlSelection & { __args: {domain: Scalars['String']} })
@@ -7758,27 +7760,23 @@ export interface CreateUsageLimitInput {resourceType: UsageResourceType,operatio
export interface UpdateUsageLimitInput {id: Scalars['UUID'],payload: CreateUsageLimitInput}
-export interface CreateViewFilterGroupInput {id?: (Scalars['UUID'] | null),parentViewFilterGroupId?: (Scalars['UUID'] | null),logicalOperator?: (ViewFilterGroupLogicalOperator | null),positionInViewFilterGroup?: (Scalars['Float'] | null),viewId: Scalars['UUID']}
+export interface CreatePageLayoutWidgetInput {pageLayoutTabId: Scalars['UUID'],title: Scalars['String'],type: WidgetType,objectMetadataId?: (Scalars['UUID'] | null),position?: (Scalars['JSON'] | null),configuration: Scalars['JSON']}
-export interface UpdateViewFilterGroupInput {id?: (Scalars['UUID'] | null),parentViewFilterGroupId?: (Scalars['UUID'] | null),logicalOperator?: (ViewFilterGroupLogicalOperator | null),positionInViewFilterGroup?: (Scalars['Float'] | null),viewId?: (Scalars['UUID'] | null)}
+export interface UpdatePageLayoutWidgetInput {pageLayoutTabId?: (Scalars['UUID'] | null),title?: (Scalars['String'] | null),type?: (WidgetType | null),objectMetadataId?: (Scalars['UUID'] | null),position?: (Scalars['JSON'] | null),configuration?: (Scalars['JSON'] | null),conditionalDisplay?: (Scalars['JSON'] | null),conditionalAvailabilityExpression?: (Scalars['String'] | null)}
-export interface CreateViewFilterInput {id?: (Scalars['UUID'] | null),fieldMetadataId: Scalars['UUID'],operand?: (ViewFilterOperand | null),value: Scalars['JSON'],viewFilterGroupId?: (Scalars['UUID'] | null),positionInViewFilterGroup?: (Scalars['Float'] | null),subFieldName?: (Scalars['String'] | null),relationTargetFieldMetadataId?: (Scalars['UUID'] | null),viewId: Scalars['UUID']}
+export interface CreatePageLayoutTabInput {title: Scalars['String'],position?: (Scalars['Float'] | null),pageLayoutId: Scalars['UUID'],layoutMode?: (PageLayoutTabLayoutMode | null)}
-export interface UpdateViewFilterInput {
-/** The id of the view filter to update */
-id: Scalars['UUID'],
-/** The view filter to update */
-update: UpdateViewFilterInputUpdates}
+export interface UpdatePageLayoutTabInput {title?: (Scalars['String'] | null),position?: (Scalars['Float'] | null),icon?: (Scalars['String'] | null),layoutMode?: (PageLayoutTabLayoutMode | null)}
-export interface UpdateViewFilterInputUpdates {fieldMetadataId?: (Scalars['UUID'] | null),operand?: (ViewFilterOperand | null),value?: (Scalars['JSON'] | null),viewFilterGroupId?: (Scalars['UUID'] | null),positionInViewFilterGroup?: (Scalars['Float'] | null),subFieldName?: (Scalars['String'] | null),relationTargetFieldMetadataId?: (Scalars['UUID'] | null)}
+export interface CreatePageLayoutInput {name: Scalars['String'],type?: (PageLayoutType | null),objectMetadataId?: (Scalars['UUID'] | null)}
-export interface DeleteViewFilterInput {
-/** The id of the view filter to delete. */
-id: Scalars['UUID']}
+export interface UpdatePageLayoutInput {name?: (Scalars['String'] | null),type?: (PageLayoutType | null),objectMetadataId?: (Scalars['UUID'] | null)}
-export interface DestroyViewFilterInput {
-/** The id of the view filter to destroy. */
-id: Scalars['UUID']}
+export interface UpdatePageLayoutWithTabsInput {name: Scalars['String'],type: PageLayoutType,objectMetadataId?: (Scalars['UUID'] | null),isFirstTabPinned?: (Scalars['Boolean'] | null),tabs: UpdatePageLayoutTabWithWidgetsInput[]}
+
+export interface UpdatePageLayoutTabWithWidgetsInput {id: Scalars['UUID'],title: Scalars['String'],position: Scalars['Float'],icon?: (Scalars['String'] | null),layoutMode?: (PageLayoutTabLayoutMode | null),widgets: UpdatePageLayoutWidgetWithIdInput[]}
+
+export interface UpdatePageLayoutWidgetWithIdInput {id: Scalars['UUID'],pageLayoutTabId: Scalars['UUID'],title: Scalars['String'],type: WidgetType,objectMetadataId?: (Scalars['UUID'] | null),position?: (Scalars['JSON'] | null),configuration?: (Scalars['JSON'] | null),conditionalDisplay?: (Scalars['JSON'] | null),conditionalAvailabilityExpression?: (Scalars['String'] | null)}
export interface CreateViewInput {id?: (Scalars['UUID'] | null),name: Scalars['String'],objectMetadataId: Scalars['UUID'],type?: (ViewType | null),key?: (ViewKey | null),icon: Scalars['String'],position?: (Scalars['Float'] | null),isCompact?: (Scalars['Boolean'] | null),shouldHideEmptyGroups?: (Scalars['Boolean'] | null),kanbanColumnWidth?: (Scalars['Int'] | null),groupLoadLimit?: (Scalars['Int'] | null),
/** Deprecated: Superseded by objectMetadata.openRecordIn and the workspace member preference; kept one release for API compatibility, no longer read by the frontend. */
@@ -7838,6 +7836,24 @@ export interface DestroyViewSortInput {
/** The id of the view sort to destroy. */
id: Scalars['UUID']}
+export interface CreateViewFilterInput {id?: (Scalars['UUID'] | null),fieldMetadataId: Scalars['UUID'],operand?: (ViewFilterOperand | null),value: Scalars['JSON'],viewFilterGroupId?: (Scalars['UUID'] | null),positionInViewFilterGroup?: (Scalars['Float'] | null),subFieldName?: (Scalars['String'] | null),relationTargetFieldMetadataId?: (Scalars['UUID'] | null),viewId: Scalars['UUID']}
+
+export interface UpdateViewFilterInput {
+/** The id of the view filter to update */
+id: Scalars['UUID'],
+/** The view filter to update */
+update: UpdateViewFilterInputUpdates}
+
+export interface UpdateViewFilterInputUpdates {fieldMetadataId?: (Scalars['UUID'] | null),operand?: (ViewFilterOperand | null),value?: (Scalars['JSON'] | null),viewFilterGroupId?: (Scalars['UUID'] | null),positionInViewFilterGroup?: (Scalars['Float'] | null),subFieldName?: (Scalars['String'] | null),relationTargetFieldMetadataId?: (Scalars['UUID'] | null)}
+
+export interface DeleteViewFilterInput {
+/** The id of the view filter to delete. */
+id: Scalars['UUID']}
+
+export interface DestroyViewFilterInput {
+/** The id of the view filter to destroy. */
+id: Scalars['UUID']}
+
export interface UpdateViewFieldInput {
/** The id of the view field to update */
id: Scalars['UUID'],
@@ -7890,36 +7906,6 @@ viewFieldId?: (Scalars['UUID'] | null),
/** The id of the field metadata. Used to create a new view field when viewFieldId is not provided. */
fieldMetadataId?: (Scalars['UUID'] | null),isVisible: Scalars['Boolean'],position: Scalars['Float']}
-export interface CreateApiKeyInput {name: Scalars['String'],expiresAt: Scalars['String'],revokedAt?: (Scalars['String'] | null),roleId: Scalars['UUID']}
-
-export interface UpdateApiKeyInput {id: Scalars['UUID'],name?: (Scalars['String'] | null),expiresAt?: (Scalars['String'] | null),revokedAt?: (Scalars['String'] | null)}
-
-export interface RevokeApiKeyInput {id: Scalars['UUID']}
-
-export interface CreateApprovedAccessDomainInput {domain: Scalars['String'],email: Scalars['String']}
-
-export interface DeleteApprovedAccessDomainInput {id: Scalars['UUID']}
-
-export interface ValidateApprovedAccessDomainInput {validationToken: Scalars['String'],approvedAccessDomainId: Scalars['UUID']}
-
-export interface CreatePageLayoutTabInput {title: Scalars['String'],position?: (Scalars['Float'] | null),pageLayoutId: Scalars['UUID'],layoutMode?: (PageLayoutTabLayoutMode | null)}
-
-export interface UpdatePageLayoutTabInput {title?: (Scalars['String'] | null),position?: (Scalars['Float'] | null),icon?: (Scalars['String'] | null),layoutMode?: (PageLayoutTabLayoutMode | null)}
-
-export interface CreatePageLayoutInput {name: Scalars['String'],type?: (PageLayoutType | null),objectMetadataId?: (Scalars['UUID'] | null)}
-
-export interface UpdatePageLayoutInput {name?: (Scalars['String'] | null),type?: (PageLayoutType | null),objectMetadataId?: (Scalars['UUID'] | null)}
-
-export interface UpdatePageLayoutWithTabsInput {name: Scalars['String'],type: PageLayoutType,objectMetadataId?: (Scalars['UUID'] | null),isFirstTabPinned?: (Scalars['Boolean'] | null),tabs: UpdatePageLayoutTabWithWidgetsInput[]}
-
-export interface UpdatePageLayoutTabWithWidgetsInput {id: Scalars['UUID'],title: Scalars['String'],position: Scalars['Float'],icon?: (Scalars['String'] | null),layoutMode?: (PageLayoutTabLayoutMode | null),widgets: UpdatePageLayoutWidgetWithIdInput[]}
-
-export interface UpdatePageLayoutWidgetWithIdInput {id: Scalars['UUID'],pageLayoutTabId: Scalars['UUID'],title: Scalars['String'],type: WidgetType,objectMetadataId?: (Scalars['UUID'] | null),position?: (Scalars['JSON'] | null),configuration?: (Scalars['JSON'] | null),conditionalDisplay?: (Scalars['JSON'] | null),conditionalAvailabilityExpression?: (Scalars['String'] | null)}
-
-export interface CreatePageLayoutWidgetInput {pageLayoutTabId: Scalars['UUID'],title: Scalars['String'],type: WidgetType,objectMetadataId?: (Scalars['UUID'] | null),position?: (Scalars['JSON'] | null),configuration: Scalars['JSON']}
-
-export interface UpdatePageLayoutWidgetInput {pageLayoutTabId?: (Scalars['UUID'] | null),title?: (Scalars['String'] | null),type?: (WidgetType | null),objectMetadataId?: (Scalars['UUID'] | null),position?: (Scalars['JSON'] | null),configuration?: (Scalars['JSON'] | null),conditionalDisplay?: (Scalars['JSON'] | null),conditionalAvailabilityExpression?: (Scalars['String'] | null)}
-
export interface CreateAgentInput {name?: (Scalars['String'] | null),label: Scalars['String'],icon?: (Scalars['String'] | null),description?: (Scalars['String'] | null),prompt: Scalars['String'],modelId: Scalars['String'],roleId?: (Scalars['UUID'] | null),responseFormat?: (Scalars['JSON'] | null),modelConfiguration?: (Scalars['JSON'] | null),evaluationInputs?: (Scalars['String'][] | null)}
export interface UpdateAgentInput {id: Scalars['UUID'],name?: (Scalars['String'] | null),label?: (Scalars['String'] | null),icon?: (Scalars['String'] | null),description?: (Scalars['String'] | null),prompt?: (Scalars['String'] | null),modelId?: (Scalars['String'] | null),roleId?: (Scalars['UUID'] | null),responseFormat?: (Scalars['JSON'] | null),modelConfiguration?: (Scalars['JSON'] | null),evaluationInputs?: (Scalars['String'][] | null)}
@@ -7992,6 +7978,22 @@ export interface UpdateWorkspaceInput {subdomain?: (Scalars['String'] | null),cu
export interface UpdateWorkspaceAllowedIframeOriginsInput {operation: Scalars['String'],origin: Scalars['String']}
+export interface CreateApprovedAccessDomainInput {domain: Scalars['String'],email: Scalars['String']}
+
+export interface DeleteApprovedAccessDomainInput {id: Scalars['UUID']}
+
+export interface ValidateApprovedAccessDomainInput {validationToken: Scalars['String'],approvedAccessDomainId: Scalars['UUID']}
+
+export interface CreateViewFilterGroupInput {id?: (Scalars['UUID'] | null),parentViewFilterGroupId?: (Scalars['UUID'] | null),logicalOperator?: (ViewFilterGroupLogicalOperator | null),positionInViewFilterGroup?: (Scalars['Float'] | null),viewId: Scalars['UUID']}
+
+export interface UpdateViewFilterGroupInput {id?: (Scalars['UUID'] | null),parentViewFilterGroupId?: (Scalars['UUID'] | null),logicalOperator?: (ViewFilterGroupLogicalOperator | null),positionInViewFilterGroup?: (Scalars['Float'] | null),viewId?: (Scalars['UUID'] | null)}
+
+export interface CreateApiKeyInput {name: Scalars['String'],expiresAt: Scalars['String'],revokedAt?: (Scalars['String'] | null),roleId: Scalars['UUID']}
+
+export interface UpdateApiKeyInput {id: Scalars['UUID'],name?: (Scalars['String'] | null),expiresAt?: (Scalars['String'] | null),revokedAt?: (Scalars['String'] | null)}
+
+export interface RevokeApiKeyInput {id: Scalars['UUID']}
+
export interface CreateApplicationRegistrationInput {name: Scalars['String'],universalIdentifier?: (Scalars['String'] | null),oAuthRedirectUris?: (Scalars['String'][] | null),oAuthScopes?: (Scalars['String'][] | null)}
export interface UpdateApplicationRegistrationInput {id: Scalars['String'],update: UpdateApplicationRegistrationPayload}
@@ -8140,8 +8142,6 @@ export interface ReportAppConnectionAuthFailureInput {id: Scalars['ID'],reason?:
export interface FileAttachmentInput {id: Scalars['UUID'],filename: Scalars['String']}
-export interface AgentChatQuestionAnswerInput {questionIndex: Scalars['Int'],selectedOptionIndices: Scalars['Int'][],freeText?: (Scalars['String'] | 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)}
@@ -8180,6 +8180,8 @@ export interface ConnectionParametersInput {host: Scalars['String'],port: Scalar
export interface UpdateLabPublicFeatureFlagInput {publicFeatureFlag: Scalars['String'],value: Scalars['Boolean']}
+export interface AgentChatQuestionAnswerInput {questionIndex: Scalars['Int'],selectedOptionIndices: Scalars['Int'][],freeText?: (Scalars['String'] | null)}
+
export interface ApplicationFileUploadRequestInput {fileFolder: FileFolder,filePath: Scalars['String'],size: Scalars['Int']}
export interface SubscriptionGenqlSelection{
@@ -10405,54 +10407,6 @@ export interface CreateRecordExportInput {objectMetadataId: Scalars['UUID'],fiel
- const SendEmailOutput_possibleTypes: string[] = ['SendEmailOutput']
- export const isSendEmailOutput = (obj?: { __typename?: any } | null): obj is SendEmailOutput => {
- if (!obj?.__typename) throw new Error('__typename is missing in "isSendEmailOutput"')
- return SendEmailOutput_possibleTypes.includes(obj.__typename)
- }
-
-
-
- const Analytics_possibleTypes: string[] = ['Analytics']
- export const isAnalytics = (obj?: { __typename?: any } | null): obj is Analytics => {
- if (!obj?.__typename) throw new Error('__typename is missing in "isAnalytics"')
- return Analytics_possibleTypes.includes(obj.__typename)
- }
-
-
-
- const EventLogRecord_possibleTypes: string[] = ['EventLogRecord']
- export const isEventLogRecord = (obj?: { __typename?: any } | null): obj is EventLogRecord => {
- if (!obj?.__typename) throw new Error('__typename is missing in "isEventLogRecord"')
- return EventLogRecord_possibleTypes.includes(obj.__typename)
- }
-
-
-
- const EventLogPageInfo_possibleTypes: string[] = ['EventLogPageInfo']
- export const isEventLogPageInfo = (obj?: { __typename?: any } | null): obj is EventLogPageInfo => {
- if (!obj?.__typename) throw new Error('__typename is missing in "isEventLogPageInfo"')
- return EventLogPageInfo_possibleTypes.includes(obj.__typename)
- }
-
-
-
- const EventLogQueryResult_possibleTypes: string[] = ['EventLogQueryResult']
- export const isEventLogQueryResult = (obj?: { __typename?: any } | null): obj is EventLogQueryResult => {
- if (!obj?.__typename) throw new Error('__typename is missing in "isEventLogQueryResult"')
- return EventLogQueryResult_possibleTypes.includes(obj.__typename)
- }
-
-
-
- const RecordExport_possibleTypes: string[] = ['RecordExport']
- export const isRecordExport = (obj?: { __typename?: any } | null): obj is RecordExport => {
- if (!obj?.__typename) throw new Error('__typename is missing in "isRecordExport"')
- return RecordExport_possibleTypes.includes(obj.__typename)
- }
-
-
-
const AiChatUsage_possibleTypes: string[] = ['AiChatUsage']
export const isAiChatUsage = (obj?: { __typename?: any } | null): obj is AiChatUsage => {
if (!obj?.__typename) throw new Error('__typename is missing in "isAiChatUsage"')
@@ -10533,6 +10487,54 @@ export interface CreateRecordExportInput {objectMetadataId: Scalars['UUID'],fiel
+ const SendEmailOutput_possibleTypes: string[] = ['SendEmailOutput']
+ export const isSendEmailOutput = (obj?: { __typename?: any } | null): obj is SendEmailOutput => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isSendEmailOutput"')
+ return SendEmailOutput_possibleTypes.includes(obj.__typename)
+ }
+
+
+
+ const Analytics_possibleTypes: string[] = ['Analytics']
+ export const isAnalytics = (obj?: { __typename?: any } | null): obj is Analytics => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isAnalytics"')
+ return Analytics_possibleTypes.includes(obj.__typename)
+ }
+
+
+
+ const EventLogRecord_possibleTypes: string[] = ['EventLogRecord']
+ export const isEventLogRecord = (obj?: { __typename?: any } | null): obj is EventLogRecord => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isEventLogRecord"')
+ return EventLogRecord_possibleTypes.includes(obj.__typename)
+ }
+
+
+
+ const EventLogPageInfo_possibleTypes: string[] = ['EventLogPageInfo']
+ export const isEventLogPageInfo = (obj?: { __typename?: any } | null): obj is EventLogPageInfo => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isEventLogPageInfo"')
+ return EventLogPageInfo_possibleTypes.includes(obj.__typename)
+ }
+
+
+
+ const EventLogQueryResult_possibleTypes: string[] = ['EventLogQueryResult']
+ export const isEventLogQueryResult = (obj?: { __typename?: any } | null): obj is EventLogQueryResult => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isEventLogQueryResult"')
+ return EventLogQueryResult_possibleTypes.includes(obj.__typename)
+ }
+
+
+
+ const RecordExport_possibleTypes: string[] = ['RecordExport']
+ export const isRecordExport = (obj?: { __typename?: any } | null): obj is RecordExport => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isRecordExport"')
+ return RecordExport_possibleTypes.includes(obj.__typename)
+ }
+
+
+
const RecordPermissionsResult_possibleTypes: string[] = ['RecordPermissionsResult']
export const isRecordPermissionsResult = (obj?: { __typename?: any } | null): obj is RecordPermissionsResult => {
if (!obj?.__typename) throw new Error('__typename is missing in "isRecordPermissionsResult"')
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index b32faa8e24b..e7c84844ef3 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -93,7 +93,7 @@ export default {
347,
348,
351,
- 390,
+ 384,
398,
400,
401,
@@ -107,7 +107,7 @@ export default {
448,
568,
572,
- 602
+ 601
],
"types": {
"BillingProductDTO": {
@@ -6719,99 +6719,6 @@ export default {
1
]
},
- "SendEmailOutput": {
- "success": [
- 8
- ],
- "error": [
- 1
- ],
- "messageThreadId": [
- 1
- ],
- "__typename": [
- 1
- ]
- },
- "Analytics": {
- "success": [
- 8
- ],
- "__typename": [
- 1
- ]
- },
- "EventLogRecord": {
- "event": [
- 1
- ],
- "timestamp": [
- 4
- ],
- "userId": [
- 1
- ],
- "properties": [
- 9
- ],
- "recordId": [
- 1
- ],
- "objectMetadataId": [
- 1
- ],
- "isCustom": [
- 8
- ],
- "__typename": [
- 1
- ]
- },
- "EventLogPageInfo": {
- "endCursor": [
- 1
- ],
- "hasNextPage": [
- 8
- ],
- "__typename": [
- 1
- ]
- },
- "EventLogQueryResult": {
- "records": [
- 376
- ],
- "totalCount": [
- 30
- ],
- "pageInfo": [
- 377
- ],
- "__typename": [
- 1
- ]
- },
- "RecordExport": {
- "id": [
- 3
- ],
- "filename": [
- 1
- ],
- "progress": [
- 30
- ],
- "errorMessage": [
- 1
- ],
- "downloadPath": [
- 1
- ],
- "__typename": [
- 1
- ]
- },
"AiChatUsage": {
"limitValue": [
159
@@ -6930,7 +6837,7 @@ export default {
},
"AiSystemPromptPreview": {
"sections": [
- 383
+ 377
],
"estimatedTokenCount": [
30
@@ -6958,7 +6865,7 @@ export default {
30
],
"error": [
- 385
+ 379
],
"__typename": [
1
@@ -6991,16 +6898,109 @@ export default {
},
"StartWorkspaceSetupChatResult": {
"outcome": [
- 390
+ 384
],
"thread": [
- 382
+ 376
],
"__typename": [
1
]
},
"WorkspaceSetupChatOutcome": {},
+ "SendEmailOutput": {
+ "success": [
+ 8
+ ],
+ "error": [
+ 1
+ ],
+ "messageThreadId": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "Analytics": {
+ "success": [
+ 8
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "EventLogRecord": {
+ "event": [
+ 1
+ ],
+ "timestamp": [
+ 4
+ ],
+ "userId": [
+ 1
+ ],
+ "properties": [
+ 9
+ ],
+ "recordId": [
+ 1
+ ],
+ "objectMetadataId": [
+ 1
+ ],
+ "isCustom": [
+ 8
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "EventLogPageInfo": {
+ "endCursor": [
+ 1
+ ],
+ "hasNextPage": [
+ 8
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "EventLogQueryResult": {
+ "records": [
+ 387
+ ],
+ "totalCount": [
+ 30
+ ],
+ "pageInfo": [
+ 388
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "RecordExport": {
+ "id": [
+ 3
+ ],
+ "filename": [
+ 1
+ ],
+ "progress": [
+ 30
+ ],
+ "errorMessage": [
+ 1
+ ],
+ "downloadPath": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
"RecordPermissionsResult": {
"objectMetadataId": [
3
@@ -7535,24 +7535,35 @@ export default {
]
}
],
- "getUsageAnalytics": [
- 192,
+ "getPageLayoutWidgets": [
+ 100,
{
- "input": [
- 421
+ "pageLayoutTabId": [
+ 1,
+ "String!"
]
}
],
- "getViewFilterGroups": [
- 57,
+ "getPageLayoutWidget": [
+ 100,
{
- "viewId": [
- 1
+ "id": [
+ 1,
+ "String!"
]
}
],
- "getViewFilterGroup": [
- 57,
+ "getPageLayoutTabs": [
+ 145,
+ {
+ "pageLayoutId": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
+ "getPageLayoutTab": [
+ 145,
{
"id": [
1,
@@ -7560,16 +7571,19 @@ export default {
]
}
],
- "getViewFilters": [
- 59,
+ "getPageLayouts": [
+ 146,
{
- "viewId": [
+ "objectMetadataId": [
1
+ ],
+ "pageLayoutType": [
+ 147
]
}
],
- "getViewFilter": [
- 59,
+ "getPageLayout": [
+ 146,
{
"id": [
1,
@@ -7615,6 +7629,23 @@ export default {
]
}
],
+ "getViewFilters": [
+ 59,
+ {
+ "viewId": [
+ 1
+ ]
+ }
+ ],
+ "getViewFilter": [
+ 59,
+ {
+ "id": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
"getViewFields": [
55,
{
@@ -7651,135 +7682,14 @@ export default {
]
}
],
- "apiKeys": [
- 2
- ],
- "getApiKeyRoles": [
- 50
- ],
- "apiKey": [
- 2,
- {
- "input": [
- 422,
- "GetApiKeyInput!"
- ]
- }
- ],
- "currentUserSessions": [
- 182
- ],
- "billingPortalSession": [
- 187,
- {
- "returnUrlPath": [
- 1
- ],
- "forPaymentMethodUpdate": [
- 8
- ]
- }
- ],
- "listPlans": [
- 185
- ],
- "getResourceCreditUsage": [
- 184
- ],
- "myConnectedAccounts": [
- 202
- ],
- "applicationConnectedAccounts": [
- 203,
- {
- "applicationId": [
- 3,
- "UUID!"
- ]
- }
- ],
- "applicationConnectionProviders": [
- 149,
- {
- "applicationId": [
- 3,
- "UUID!"
- ]
- }
- ],
- "getInviteSuggestions": [
- 194
- ],
- "findWorkspaceInvitations": [
- 197
- ],
- "getApprovedAccessDomains": [
- 193
- ],
- "getPageLayoutTabs": [
- 145,
- {
- "pageLayoutId": [
- 1,
- "String!"
- ]
- }
- ],
- "getPageLayoutTab": [
- 145,
- {
- "id": [
- 1,
- "String!"
- ]
- }
- ],
- "getPageLayouts": [
- 146,
- {
- "objectMetadataId": [
- 1
- ],
- "pageLayoutType": [
- 147
- ]
- }
- ],
- "getPageLayout": [
- 146,
- {
- "id": [
- 1,
- "String!"
- ]
- }
- ],
- "getPageLayoutWidgets": [
- 100,
- {
- "pageLayoutTabId": [
- 1,
- "String!"
- ]
- }
- ],
- "getPageLayoutWidget": [
- 100,
- {
- "id": [
- 1,
- "String!"
- ]
- }
- ],
- "findManyAgents": [
- 10
+ "findManyAgents": [
+ 10
],
"findOneAgent": [
10,
{
"input": [
- 423,
+ 421,
"AgentIdInput!"
]
}
@@ -7792,7 +7702,7 @@ export default {
"CursorPaging!"
],
"filter": [
- 424,
+ 422,
"ObjectFilter!"
]
}
@@ -7818,11 +7728,14 @@ export default {
]
}
],
+ "currentUserSessions": [
+ 182
+ ],
"findOneLogicFunction": [
23,
{
"input": [
- 425,
+ 423,
"LogicFunctionIdInput!"
]
}
@@ -7834,7 +7747,7 @@ export default {
9,
{
"input": [
- 425,
+ 423,
"LogicFunctionIdInput!"
]
}
@@ -7843,7 +7756,7 @@ export default {
1,
{
"input": [
- 425,
+ 423,
"LogicFunctionIdInput!"
]
}
@@ -7872,6 +7785,52 @@ export default {
]
}
],
+ "billingPortalSession": [
+ 187,
+ {
+ "returnUrlPath": [
+ 1
+ ],
+ "forPaymentMethodUpdate": [
+ 8
+ ]
+ }
+ ],
+ "listPlans": [
+ 185
+ ],
+ "getResourceCreditUsage": [
+ 184
+ ],
+ "getUsageAnalytics": [
+ 192,
+ {
+ "input": [
+ 424
+ ]
+ }
+ ],
+ "myConnectedAccounts": [
+ 202
+ ],
+ "applicationConnectedAccounts": [
+ 203,
+ {
+ "applicationId": [
+ 3,
+ "UUID!"
+ ]
+ }
+ ],
+ "applicationConnectionProviders": [
+ 149,
+ {
+ "applicationId": [
+ 3,
+ "UUID!"
+ ]
+ }
+ ],
"currentWorkspace": [
71
],
@@ -7892,6 +7851,47 @@ export default {
]
}
],
+ "getInviteSuggestions": [
+ 194
+ ],
+ "findWorkspaceInvitations": [
+ 197
+ ],
+ "getApprovedAccessDomains": [
+ 193
+ ],
+ "getViewFilterGroups": [
+ 57,
+ {
+ "viewId": [
+ 1
+ ]
+ }
+ ],
+ "getViewFilterGroup": [
+ 57,
+ {
+ "id": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
+ "apiKeys": [
+ 2
+ ],
+ "getApiKeyRoles": [
+ 50
+ ],
+ "apiKey": [
+ 2,
+ {
+ "input": [
+ 425,
+ "GetApiKeyInput!"
+ ]
+ }
+ ],
"findApplicationRegistrationByClientId": [
236,
{
@@ -8207,13 +8207,13 @@ export default {
394
],
"aiChatUsage": [
- 380
+ 374
],
"chatThreads": [
- 382
+ 376
],
"chatThread": [
- 382,
+ 376,
{
"id": [
3,
@@ -8231,7 +8231,7 @@ export default {
}
],
"chatStreamCatchupChunks": [
- 386,
+ 380,
{
"threadId": [
3,
@@ -8240,13 +8240,13 @@ export default {
}
],
"getAiSystemPromptPreview": [
- 384
+ 378
],
"skills": [
- 381
+ 375
],
"skill": [
- 381,
+ 375,
{
"id": [
3,
@@ -8351,7 +8351,7 @@ export default {
243
],
"eventLogs": [
- 378,
+ 389,
{
"input": [
432,
@@ -8498,31 +8498,6 @@ export default {
1
]
},
- "UsageAnalyticsInput": {
- "periodStart": [
- 4
- ],
- "periodEnd": [
- 4
- ],
- "userWorkspaceId": [
- 1
- ],
- "operationTypes": [
- 156
- ],
- "__typename": [
- 1
- ]
- },
- "GetApiKeyInput": {
- "id": [
- 3
- ],
- "__typename": [
- 1
- ]
- },
"AgentIdInput": {
"id": [
3
@@ -8533,10 +8508,10 @@ export default {
},
"ObjectFilter": {
"and": [
- 424
+ 422
],
"or": [
- 424
+ 422
],
"id": [
33
@@ -8577,12 +8552,37 @@ export default {
1
]
},
- "PreviewMessageCampaignAudienceInput": {
- "listId": [
- 1
+ "UsageAnalyticsInput": {
+ "periodStart": [
+ 4
],
- "unsubscribeTopicId": [
- 1
+ "periodEnd": [
+ 4
+ ],
+ "userWorkspaceId": [
+ 1
+ ],
+ "operationTypes": [
+ 156
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "GetApiKeyInput": {
+ "id": [
+ 3
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "PreviewMessageCampaignAudienceInput": {
+ "listId": [
+ 1
+ ],
+ "unsubscribeTopicId": [
+ 1
],
"__typename": [
1
@@ -8971,17 +8971,17 @@ export default {
]
}
],
- "createViewFilterGroup": [
- 57,
+ "createPageLayoutWidget": [
+ 100,
{
"input": [
451,
- "CreateViewFilterGroupInput!"
+ "CreatePageLayoutWidgetInput!"
]
}
],
- "updateViewFilterGroup": [
- 57,
+ "updatePageLayoutWidget": [
+ 100,
{
"id": [
1,
@@ -8989,11 +8989,11 @@ export default {
],
"input": [
452,
- "UpdateViewFilterGroupInput!"
+ "UpdatePageLayoutWidgetInput!"
]
}
],
- "deleteViewFilterGroup": [
+ "destroyPageLayoutWidget": [
8,
{
"id": [
@@ -9002,48 +9002,105 @@ export default {
]
}
],
- "destroyViewFilterGroup": [
- 8,
+ "createPageLayoutTab": [
+ 145,
+ {
+ "input": [
+ 453,
+ "CreatePageLayoutTabInput!"
+ ]
+ }
+ ],
+ "updatePageLayoutTab": [
+ 145,
{
"id": [
1,
"String!"
+ ],
+ "input": [
+ 454,
+ "UpdatePageLayoutTabInput!"
]
}
],
- "createViewFilter": [
- 59,
+ "destroyPageLayoutTab": [
+ 8,
{
- "input": [
- 453,
- "CreateViewFilterInput!"
+ "id": [
+ 1,
+ "String!"
]
}
],
- "updateViewFilter": [
- 59,
+ "createPageLayout": [
+ 146,
{
"input": [
- 454,
- "UpdateViewFilterInput!"
+ 455,
+ "CreatePageLayoutInput!"
]
}
],
- "deleteViewFilter": [
- 59,
+ "updatePageLayout": [
+ 146,
{
+ "id": [
+ 1,
+ "String!"
+ ],
"input": [
456,
- "DeleteViewFilterInput!"
+ "UpdatePageLayoutInput!"
]
}
],
- "destroyViewFilter": [
- 59,
+ "destroyPageLayout": [
+ 8,
+ {
+ "id": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
+ "updatePageLayoutWithTabsAndWidgets": [
+ 146,
{
+ "id": [
+ 1,
+ "String!"
+ ],
"input": [
457,
- "DestroyViewFilterInput!"
+ "UpdatePageLayoutWithTabsInput!"
+ ]
+ }
+ ],
+ "resetPageLayoutToDefault": [
+ 146,
+ {
+ "id": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
+ "resetPageLayoutWidgetToDefault": [
+ 100,
+ {
+ "id": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
+ "resetPageLayoutTabToDefault": [
+ 145,
+ {
+ "id": [
+ 1,
+ "String!"
]
}
],
@@ -9051,7 +9108,7 @@ export default {
65,
{
"input": [
- 458,
+ 460,
"CreateViewInput!"
]
}
@@ -9064,7 +9121,7 @@ export default {
"String!"
],
"input": [
- 459,
+ 461,
"UpdateViewInput!"
]
}
@@ -9091,7 +9148,7 @@ export default {
65,
{
"input": [
- 460,
+ 462,
"UpsertViewWidgetInput!"
]
}
@@ -9100,7 +9157,7 @@ export default {
62,
{
"input": [
- 466,
+ 468,
"CreateViewSortInput!"
]
}
@@ -9109,7 +9166,7 @@ export default {
62,
{
"input": [
- 467,
+ 469,
"UpdateViewSortInput!"
]
}
@@ -9118,7 +9175,7 @@ export default {
8,
{
"input": [
- 469,
+ 471,
"DeleteViewSortInput!"
]
}
@@ -9127,16 +9184,52 @@ export default {
8,
{
"input": [
- 470,
+ 472,
"DestroyViewSortInput!"
]
}
],
+ "createViewFilter": [
+ 59,
+ {
+ "input": [
+ 473,
+ "CreateViewFilterInput!"
+ ]
+ }
+ ],
+ "updateViewFilter": [
+ 59,
+ {
+ "input": [
+ 474,
+ "UpdateViewFilterInput!"
+ ]
+ }
+ ],
+ "deleteViewFilter": [
+ 59,
+ {
+ "input": [
+ 476,
+ "DeleteViewFilterInput!"
+ ]
+ }
+ ],
+ "destroyViewFilter": [
+ 59,
+ {
+ "input": [
+ 477,
+ "DestroyViewFilterInput!"
+ ]
+ }
+ ],
"updateViewField": [
55,
{
"input": [
- 471,
+ 478,
"UpdateViewFieldInput!"
]
}
@@ -9145,7 +9238,7 @@ export default {
55,
{
"input": [
- 473,
+ 480,
"CreateViewFieldInput!"
]
}
@@ -9154,7 +9247,7 @@ export default {
55,
{
"inputs": [
- 473,
+ 480,
"[CreateViewFieldInput!]!"
]
}
@@ -9163,7 +9256,7 @@ export default {
55,
{
"input": [
- 474,
+ 481,
"DeleteViewFieldInput!"
]
}
@@ -9172,7 +9265,7 @@ export default {
55,
{
"input": [
- 475,
+ 482,
"DestroyViewFieldInput!"
]
}
@@ -9181,7 +9274,7 @@ export default {
64,
{
"input": [
- 476,
+ 483,
"UpdateViewFieldGroupInput!"
]
}
@@ -9190,7 +9283,7 @@ export default {
64,
{
"input": [
- 478,
+ 485,
"CreateViewFieldGroupInput!"
]
}
@@ -9199,7 +9292,7 @@ export default {
64,
{
"inputs": [
- 478,
+ 485,
"[CreateViewFieldGroupInput!]!"
]
}
@@ -9208,7 +9301,7 @@ export default {
64,
{
"input": [
- 479,
+ 486,
"DeleteViewFieldGroupInput!"
]
}
@@ -9217,7 +9310,7 @@ export default {
64,
{
"input": [
- 480,
+ 487,
"DestroyViewFieldGroupInput!"
]
}
@@ -9226,84 +9319,249 @@ export default {
65,
{
"input": [
- 481,
+ 488,
"UpsertFieldsWidgetInput!"
]
}
],
- "createApiKey": [
- 2,
+ "createOneAgent": [
+ 10,
{
"input": [
- 484,
- "CreateApiKeyInput!"
+ 491,
+ "CreateAgentInput!"
]
}
],
- "updateApiKey": [
- 2,
+ "updateOneAgent": [
+ 10,
{
"input": [
- 485,
- "UpdateApiKeyInput!"
+ 492,
+ "UpdateAgentInput!"
]
}
],
- "revokeApiKey": [
- 2,
+ "deleteOneAgent": [
+ 10,
{
"input": [
- 486,
- "RevokeApiKeyInput!"
+ 421,
+ "AgentIdInput!"
]
}
],
- "assignRoleToApiKey": [
- 8,
+ "createOneObject": [
+ 25,
{
- "apiKeyId": [
- 3,
- "UUID!"
- ],
- "roleId": [
- 3,
- "UUID!"
+ "input": [
+ 493,
+ "CreateOneObjectInput!"
]
}
],
- "revokeUserSession": [
- 8,
+ "deleteOneObject": [
+ 25,
{
- "userSessionId": [
- 3,
- "UUID!"
+ "input": [
+ 495,
+ "DeleteOneObjectInput!"
]
}
],
- "revokeAllOtherUserSessions": [
- 30
- ],
- "checkoutSession": [
- 187,
+ "updateOneObject": [
+ 25,
{
- "recurringInterval": [
- 86,
- "SubscriptionInterval!"
- ],
- "plan": [
- 82,
- "BillingPlanKey!"
- ],
- "requirePaymentMethod": [
- 8,
- "Boolean!"
- ],
- "successUrlPath": [
- 1
+ "input": [
+ 496,
+ "UpdateOneObjectInput!"
]
}
],
- "createSubscriptionPaymentIntent": [
+ "updateManyObjects": [
+ 25,
+ {
+ "inputs": [
+ 496,
+ "[UpdateOneObjectInput!]!"
+ ]
+ }
+ ],
+ "createOneIndex": [
+ 271,
+ {
+ "input": [
+ 499,
+ "CreateOneIndexInput!"
+ ]
+ }
+ ],
+ "deleteOneIndex": [
+ 271,
+ {
+ "input": [
+ 502,
+ "DeleteOneIndexInput!"
+ ]
+ }
+ ],
+ "revokeUserSession": [
+ 8,
+ {
+ "userSessionId": [
+ 3,
+ "UUID!"
+ ]
+ }
+ ],
+ "revokeAllOtherUserSessions": [
+ 30
+ ],
+ "deleteOneLogicFunction": [
+ 23,
+ {
+ "input": [
+ 423,
+ "LogicFunctionIdInput!"
+ ]
+ }
+ ],
+ "createOneLogicFunction": [
+ 23,
+ {
+ "input": [
+ 503,
+ "CreateLogicFunctionFromSourceInput!"
+ ]
+ }
+ ],
+ "executeOneLogicFunction": [
+ 150,
+ {
+ "input": [
+ 504,
+ "ExecuteOneLogicFunctionInput!"
+ ]
+ }
+ ],
+ "updateOneLogicFunction": [
+ 8,
+ {
+ "input": [
+ 505,
+ "UpdateLogicFunctionFromSourceInput!"
+ ]
+ }
+ ],
+ "createCommandMenuItem": [
+ 14,
+ {
+ "input": [
+ 507,
+ "CreateCommandMenuItemInput!"
+ ]
+ }
+ ],
+ "updateCommandMenuItem": [
+ 14,
+ {
+ "input": [
+ 508,
+ "UpdateCommandMenuItemInput!"
+ ]
+ }
+ ],
+ "resetCommandMenuItem": [
+ 14,
+ {
+ "id": [
+ 3,
+ "UUID!"
+ ]
+ }
+ ],
+ "deleteCommandMenuItem": [
+ 14,
+ {
+ "id": [
+ 3,
+ "UUID!"
+ ]
+ }
+ ],
+ "generateFrontComponentApplicationTokenPair": [
+ 12,
+ {
+ "applicationId": [
+ 3,
+ "UUID!"
+ ]
+ }
+ ],
+ "createFrontComponent": [
+ 13,
+ {
+ "input": [
+ 509,
+ "CreateFrontComponentInput!"
+ ]
+ }
+ ],
+ "updateFrontComponent": [
+ 13,
+ {
+ "input": [
+ 510,
+ "UpdateFrontComponentInput!"
+ ]
+ }
+ ],
+ "deleteFrontComponent": [
+ 13,
+ {
+ "id": [
+ 3,
+ "UUID!"
+ ]
+ }
+ ],
+ "updateOneApplicationVariable": [
+ 8,
+ {
+ "key": [
+ 1,
+ "String!"
+ ],
+ "value": [
+ 1,
+ "String!"
+ ],
+ "applicationId": [
+ 3
+ ]
+ }
+ ],
+ "checkoutSession": [
+ 187,
+ {
+ "recurringInterval": [
+ 86,
+ "SubscriptionInterval!"
+ ],
+ "plan": [
+ 82,
+ "BillingPlanKey!"
+ ],
+ "requirePaymentMethod": [
+ 8,
+ "Boolean!"
+ ],
+ "successUrlPath": [
+ 1
+ ]
+ }
+ ],
+ "createSubscriptionPaymentIntent": [
186,
{
"recurringInterval": [
@@ -9375,22 +9633,42 @@ export default {
]
}
],
- "updateOneApplicationVariable": [
- 8,
+ "activateWorkspace": [
+ 71,
{
- "key": [
- 1,
- "String!"
- ],
- "value": [
- 1,
- "String!"
- ],
- "applicationId": [
- 3
+ "data": [
+ 512,
+ "ActivateWorkspaceInput!"
+ ]
+ }
+ ],
+ "updateWorkspace": [
+ 71,
+ {
+ "data": [
+ 513,
+ "UpdateWorkspaceInput!"
+ ]
+ }
+ ],
+ "updateWorkspaceAllowedIframeOrigins": [
+ 71,
+ {
+ "data": [
+ 514,
+ "UpdateWorkspaceAllowedIframeOriginsInput!"
]
}
],
+ "deleteCurrentWorkspace": [
+ 71
+ ],
+ "checkCustomDomainValidRecords": [
+ 283
+ ],
+ "enrichWorkspaceCompany": [
+ 260
+ ],
"skipSyncEmailOnboardingStep": [
196,
{
@@ -9463,7 +9741,7 @@ export default {
193,
{
"input": [
- 487,
+ 515,
"CreateApprovedAccessDomainInput!"
]
}
@@ -9472,7 +9750,7 @@ export default {
8,
{
"input": [
- 488,
+ 516,
"DeleteApprovedAccessDomainInput!"
]
}
@@ -9481,34 +9759,34 @@ export default {
193,
{
"input": [
- 489,
+ 517,
"ValidateApprovedAccessDomainInput!"
]
}
],
- "createPageLayoutTab": [
- 145,
+ "createViewFilterGroup": [
+ 57,
{
"input": [
- 490,
- "CreatePageLayoutTabInput!"
+ 518,
+ "CreateViewFilterGroupInput!"
]
}
],
- "updatePageLayoutTab": [
- 145,
+ "updateViewFilterGroup": [
+ 57,
{
"id": [
1,
"String!"
],
"input": [
- 491,
- "UpdatePageLayoutTabInput!"
+ 519,
+ "UpdateViewFilterGroupInput!"
]
}
],
- "destroyPageLayoutTab": [
+ "deleteViewFilterGroup": [
8,
{
"id": [
@@ -9517,61 +9795,8 @@ export default {
]
}
],
- "createPageLayout": [
- 146,
- {
- "input": [
- 492,
- "CreatePageLayoutInput!"
- ]
- }
- ],
- "updatePageLayout": [
- 146,
- {
- "id": [
- 1,
- "String!"
- ],
- "input": [
- 493,
- "UpdatePageLayoutInput!"
- ]
- }
- ],
- "destroyPageLayout": [
- 8,
- {
- "id": [
- 1,
- "String!"
- ]
- }
- ],
- "updatePageLayoutWithTabsAndWidgets": [
- 146,
- {
- "id": [
- 1,
- "String!"
- ],
- "input": [
- 494,
- "UpdatePageLayoutWithTabsInput!"
- ]
- }
- ],
- "resetPageLayoutToDefault": [
- 146,
- {
- "id": [
- 1,
- "String!"
- ]
- }
- ],
- "resetPageLayoutWidgetToDefault": [
- 100,
+ "destroyViewFilterGroup": [
+ 8,
{
"id": [
1,
@@ -9579,271 +9804,46 @@ export default {
]
}
],
- "resetPageLayoutTabToDefault": [
- 145,
- {
- "id": [
- 1,
- "String!"
- ]
- }
- ],
- "createPageLayoutWidget": [
- 100,
- {
- "input": [
- 497,
- "CreatePageLayoutWidgetInput!"
- ]
- }
- ],
- "updatePageLayoutWidget": [
- 100,
- {
- "id": [
- 1,
- "String!"
- ],
- "input": [
- 498,
- "UpdatePageLayoutWidgetInput!"
- ]
- }
- ],
- "destroyPageLayoutWidget": [
- 8,
- {
- "id": [
- 1,
- "String!"
- ]
- }
- ],
- "createOneAgent": [
- 10,
- {
- "input": [
- 499,
- "CreateAgentInput!"
- ]
- }
- ],
- "updateOneAgent": [
- 10,
- {
- "input": [
- 500,
- "UpdateAgentInput!"
- ]
- }
- ],
- "deleteOneAgent": [
- 10,
- {
- "input": [
- 423,
- "AgentIdInput!"
- ]
- }
- ],
- "createOneObject": [
- 25,
- {
- "input": [
- 501,
- "CreateOneObjectInput!"
- ]
- }
- ],
- "deleteOneObject": [
- 25,
- {
- "input": [
- 503,
- "DeleteOneObjectInput!"
- ]
- }
- ],
- "updateOneObject": [
- 25,
- {
- "input": [
- 504,
- "UpdateOneObjectInput!"
- ]
- }
- ],
- "updateManyObjects": [
- 25,
- {
- "inputs": [
- 504,
- "[UpdateOneObjectInput!]!"
- ]
- }
- ],
- "createOneIndex": [
- 271,
- {
- "input": [
- 507,
- "CreateOneIndexInput!"
- ]
- }
- ],
- "deleteOneIndex": [
- 271,
- {
- "input": [
- 510,
- "DeleteOneIndexInput!"
- ]
- }
- ],
- "deleteOneLogicFunction": [
- 23,
+ "createApiKey": [
+ 2,
{
"input": [
- 425,
- "LogicFunctionIdInput!"
+ 520,
+ "CreateApiKeyInput!"
]
}
],
- "createOneLogicFunction": [
- 23,
+ "updateApiKey": [
+ 2,
{
"input": [
- 511,
- "CreateLogicFunctionFromSourceInput!"
+ 521,
+ "UpdateApiKeyInput!"
]
}
],
- "executeOneLogicFunction": [
- 150,
+ "revokeApiKey": [
+ 2,
{
"input": [
- 512,
- "ExecuteOneLogicFunctionInput!"
+ 522,
+ "RevokeApiKeyInput!"
]
}
],
- "updateOneLogicFunction": [
+ "assignRoleToApiKey": [
8,
{
- "input": [
- 513,
- "UpdateLogicFunctionFromSourceInput!"
- ]
- }
- ],
- "createCommandMenuItem": [
- 14,
- {
- "input": [
- 515,
- "CreateCommandMenuItemInput!"
- ]
- }
- ],
- "updateCommandMenuItem": [
- 14,
- {
- "input": [
- 516,
- "UpdateCommandMenuItemInput!"
- ]
- }
- ],
- "resetCommandMenuItem": [
- 14,
- {
- "id": [
- 3,
- "UUID!"
- ]
- }
- ],
- "deleteCommandMenuItem": [
- 14,
- {
- "id": [
- 3,
- "UUID!"
- ]
- }
- ],
- "generateFrontComponentApplicationTokenPair": [
- 12,
- {
- "applicationId": [
+ "apiKeyId": [
3,
"UUID!"
- ]
- }
- ],
- "createFrontComponent": [
- 13,
- {
- "input": [
- 517,
- "CreateFrontComponentInput!"
- ]
- }
- ],
- "updateFrontComponent": [
- 13,
- {
- "input": [
- 518,
- "UpdateFrontComponentInput!"
- ]
- }
- ],
- "deleteFrontComponent": [
- 13,
- {
- "id": [
+ ],
+ "roleId": [
3,
"UUID!"
]
}
],
- "activateWorkspace": [
- 71,
- {
- "data": [
- 520,
- "ActivateWorkspaceInput!"
- ]
- }
- ],
- "updateWorkspace": [
- 71,
- {
- "data": [
- 521,
- "UpdateWorkspaceInput!"
- ]
- }
- ],
- "updateWorkspaceAllowedIframeOrigins": [
- 71,
- {
- "data": [
- 522,
- "UpdateWorkspaceAllowedIframeOriginsInput!"
- ]
- }
- ],
- "deleteCurrentWorkspace": [
- 71
- ],
- "checkCustomDomainValidRecords": [
- 283
- ],
- "enrichWorkspaceCompany": [
- 260
- ],
"upgradeApplication": [
8,
{
@@ -10501,10 +10501,10 @@ export default {
}
],
"createChatThread": [
- 382
+ 376
],
"sendChatMessage": [
- 387,
+ 381,
{
"threadId": [
3,
@@ -10531,38 +10531,14 @@ export default {
}
],
"retryChatMessage": [
- 387,
- {
- "threadId": [
- 3,
- "UUID!"
- ],
- "modelId": [
- 1
- ]
- }
- ],
- "answerAgentChatQuestion": [
- 387,
+ 381,
{
"threadId": [
3,
"UUID!"
],
- "messageId": [
- 3,
- "UUID!"
- ],
- "answers": [
- 588,
- "[AgentChatQuestionAnswerInput!]!"
- ],
"modelId": [
1
- ],
- "fileAttachments": [
- 587,
- "[FileAttachmentInput!]"
]
}
],
@@ -10576,7 +10552,7 @@ export default {
}
],
"renameChatThread": [
- 382,
+ 376,
{
"id": [
3,
@@ -10589,7 +10565,7 @@ export default {
}
],
"archiveChatThread": [
- 382,
+ 376,
{
"id": [
3,
@@ -10598,7 +10574,7 @@ export default {
}
],
"unarchiveChatThread": [
- 382,
+ 376,
{
"id": [
3,
@@ -10625,7 +10601,7 @@ export default {
}
],
"startWorkspaceSetupChat": [
- 389,
+ 383,
{
"companyContext": [
9
@@ -10636,25 +10612,25 @@ export default {
}
],
"createSkill": [
- 381,
+ 375,
{
"input": [
- 589,
+ 588,
"CreateSkillInput!"
]
}
],
"updateSkill": [
- 381,
+ 375,
{
"input": [
- 590,
+ 589,
"UpdateSkillInput!"
]
}
],
"deleteSkill": [
- 381,
+ 375,
{
"id": [
3,
@@ -10663,7 +10639,7 @@ export default {
}
],
"activateSkill": [
- 381,
+ 375,
{
"id": [
3,
@@ -10672,7 +10648,7 @@ export default {
}
],
"deactivateSkill": [
- 381,
+ 375,
{
"id": [
3,
@@ -10706,7 +10682,7 @@ export default {
411,
{
"input": [
- 591,
+ 590,
"CreateValidationRuleInput!"
]
}
@@ -10715,7 +10691,7 @@ export default {
411,
{
"input": [
- 592,
+ 591,
"UpdateValidationRuleInput!"
]
}
@@ -10733,7 +10709,7 @@ export default {
410,
{
"input": [
- 594,
+ 593,
"UpdateTimelineActivityTypeInput!"
]
}
@@ -10751,7 +10727,7 @@ export default {
293,
{
"input": [
- 595,
+ 594,
"GetAuthorizationUrlForSSOInput!"
]
}
@@ -10917,7 +10893,7 @@ export default {
296,
{
"input": [
- 596
+ 595
]
}
],
@@ -11125,7 +11101,7 @@ export default {
8,
{
"input": [
- 597,
+ 596,
"UpdateWorkspaceMemberSettingsInput!"
]
}
@@ -11159,7 +11135,7 @@ export default {
244,
{
"input": [
- 598,
+ 597,
"SetupOIDCSsoInput!"
]
}
@@ -11168,7 +11144,7 @@ export default {
244,
{
"input": [
- 599,
+ 598,
"SetupSAMLSsoInput!"
]
}
@@ -11177,7 +11153,7 @@ export default {
240,
{
"input": [
- 600,
+ 599,
"DeleteSsoInput!"
]
}
@@ -11186,13 +11162,13 @@ export default {
241,
{
"input": [
- 601,
+ 600,
"EditSsoInput!"
]
}
],
"createObjectEvent": [
- 375,
+ 386,
{
"event": [
1,
@@ -11212,10 +11188,10 @@ export default {
}
],
"trackAnalytics": [
- 375,
+ 386,
{
"type": [
- 602,
+ 601,
"AnalyticsType!"
],
"name": [
@@ -11258,16 +11234,16 @@ export default {
365,
{
"input": [
- 603,
+ 602,
"CreateCalendarEventInput!"
]
}
],
"sendEmail": [
- 374,
+ 385,
{
"input": [
- 604,
+ 603,
"SendEmailInput!"
]
}
@@ -11289,7 +11265,7 @@ export default {
"String!"
],
"connectionParameters": [
- 606,
+ 605,
"EmailAccountConnectionParameters!"
],
"id": [
@@ -11301,11 +11277,35 @@ export default {
204,
{
"input": [
- 608,
+ 607,
"UpdateLabPublicFeatureFlagInput!"
]
}
],
+ "answerAgentChatQuestion": [
+ 381,
+ {
+ "threadId": [
+ 3,
+ "UUID!"
+ ],
+ "messageId": [
+ 3,
+ "UUID!"
+ ],
+ "answers": [
+ 608,
+ "[AgentChatQuestionAnswerInput!]!"
+ ],
+ "modelId": [
+ 1
+ ],
+ "fileAttachments": [
+ 587,
+ "[FileAttachmentInput!]"
+ ]
+ }
+ ],
"createPublicDomain": [
324,
{
@@ -11583,144 +11583,208 @@ export default {
"limitValue": [
159
],
- "burstValue": [
- 159
+ "burstValue": [
+ 159
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UpdateUsageLimitInput": {
+ "id": [
+ 3
+ ],
+ "payload": [
+ 449
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "CreatePageLayoutWidgetInput": {
+ "pageLayoutTabId": [
+ 3
+ ],
+ "title": [
+ 1
+ ],
+ "type": [
+ 101
+ ],
+ "objectMetadataId": [
+ 3
+ ],
+ "position": [
+ 9
+ ],
+ "configuration": [
+ 9
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UpdatePageLayoutWidgetInput": {
+ "pageLayoutTabId": [
+ 3
+ ],
+ "title": [
+ 1
+ ],
+ "type": [
+ 101
+ ],
+ "objectMetadataId": [
+ 3
+ ],
+ "position": [
+ 9
+ ],
+ "configuration": [
+ 9
+ ],
+ "conditionalDisplay": [
+ 9
+ ],
+ "conditionalAvailabilityExpression": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "CreatePageLayoutTabInput": {
+ "title": [
+ 1
+ ],
+ "position": [
+ 15
+ ],
+ "pageLayoutId": [
+ 3
+ ],
+ "layoutMode": [
+ 104
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UpdatePageLayoutTabInput": {
+ "title": [
+ 1
+ ],
+ "position": [
+ 15
+ ],
+ "icon": [
+ 1
+ ],
+ "layoutMode": [
+ 104
],
"__typename": [
1
]
},
- "UpdateUsageLimitInput": {
- "id": [
- 3
+ "CreatePageLayoutInput": {
+ "name": [
+ 1
],
- "payload": [
- 449
+ "type": [
+ 147
+ ],
+ "objectMetadataId": [
+ 3
],
"__typename": [
1
]
},
- "CreateViewFilterGroupInput": {
- "id": [
- 3
- ],
- "parentViewFilterGroupId": [
- 3
- ],
- "logicalOperator": [
- 58
+ "UpdatePageLayoutInput": {
+ "name": [
+ 1
],
- "positionInViewFilterGroup": [
- 15
+ "type": [
+ 147
],
- "viewId": [
+ "objectMetadataId": [
3
],
"__typename": [
1
]
},
- "UpdateViewFilterGroupInput": {
- "id": [
- 3
+ "UpdatePageLayoutWithTabsInput": {
+ "name": [
+ 1
],
- "parentViewFilterGroupId": [
- 3
+ "type": [
+ 147
],
- "logicalOperator": [
- 58
+ "objectMetadataId": [
+ 3
],
- "positionInViewFilterGroup": [
- 15
+ "isFirstTabPinned": [
+ 8
],
- "viewId": [
- 3
+ "tabs": [
+ 458
],
"__typename": [
1
]
},
- "CreateViewFilterInput": {
+ "UpdatePageLayoutTabWithWidgetsInput": {
"id": [
3
],
- "fieldMetadataId": [
- 3
- ],
- "operand": [
- 60
- ],
- "value": [
- 9
- ],
- "viewFilterGroupId": [
- 3
+ "title": [
+ 1
],
- "positionInViewFilterGroup": [
+ "position": [
15
],
- "subFieldName": [
+ "icon": [
1
],
- "relationTargetFieldMetadataId": [
- 3
+ "layoutMode": [
+ 104
],
- "viewId": [
- 3
+ "widgets": [
+ 459
],
"__typename": [
1
]
},
- "UpdateViewFilterInput": {
+ "UpdatePageLayoutWidgetWithIdInput": {
"id": [
3
],
- "update": [
- 455
- ],
- "__typename": [
- 1
- ]
- },
- "UpdateViewFilterInputUpdates": {
- "fieldMetadataId": [
+ "pageLayoutTabId": [
3
],
- "operand": [
- 60
+ "title": [
+ 1
],
- "value": [
- 9
+ "type": [
+ 101
],
- "viewFilterGroupId": [
+ "objectMetadataId": [
3
],
- "positionInViewFilterGroup": [
- 15
- ],
- "subFieldName": [
- 1
+ "position": [
+ 9
],
- "relationTargetFieldMetadataId": [
- 3
+ "configuration": [
+ 9
],
- "__typename": [
- 1
- ]
- },
- "DeleteViewFilterInput": {
- "id": [
- 3
+ "conditionalDisplay": [
+ 9
],
- "__typename": [
+ "conditionalAvailabilityExpression": [
1
- ]
- },
- "DestroyViewFilterInput": {
- "id": [
- 3
],
"__typename": [
1
@@ -11855,19 +11919,19 @@ export default {
3
],
"view": [
- 461
+ 463
],
"viewFields": [
- 462
+ 464
],
"viewFilters": [
- 463
+ 465
],
"viewFilterGroups": [
- 464
+ 466
],
"viewSorts": [
- 465
+ 467
],
"__typename": [
1
@@ -11950,230 +12014,98 @@ export default {
"positionInViewFilterGroup": [
15
],
- "subFieldName": [
- 1
- ],
- "relationTargetFieldMetadataId": [
- 3
- ],
- "__typename": [
- 1
- ]
- },
- "UpsertViewWidgetViewFilterGroupInput": {
- "id": [
- 3
- ],
- "parentViewFilterGroupId": [
- 3
- ],
- "logicalOperator": [
- 58
- ],
- "positionInViewFilterGroup": [
- 15
- ],
- "__typename": [
- 1
- ]
- },
- "UpsertViewWidgetViewSortInput": {
- "id": [
- 3
- ],
- "fieldMetadataId": [
- 3
- ],
- "direction": [
- 63
- ],
- "__typename": [
- 1
- ]
- },
- "CreateViewSortInput": {
- "id": [
- 3
- ],
- "fieldMetadataId": [
- 3
- ],
- "direction": [
- 63
- ],
- "subFieldName": [
- 1
- ],
- "viewId": [
- 3
- ],
- "__typename": [
- 1
- ]
- },
- "UpdateViewSortInput": {
- "id": [
- 3
- ],
- "update": [
- 468
- ],
- "__typename": [
- 1
- ]
- },
- "UpdateViewSortInputUpdates": {
- "direction": [
- 63
- ],
- "subFieldName": [
- 1
- ],
- "__typename": [
- 1
- ]
- },
- "DeleteViewSortInput": {
- "id": [
- 3
- ],
- "__typename": [
- 1
- ]
- },
- "DestroyViewSortInput": {
- "id": [
- 3
- ],
- "__typename": [
- 1
- ]
- },
- "UpdateViewFieldInput": {
- "id": [
- 3
- ],
- "update": [
- 472
- ],
- "__typename": [
- 1
- ]
- },
- "UpdateViewFieldInputUpdates": {
- "isVisible": [
- 8
- ],
- "size": [
- 15
- ],
- "position": [
- 15
- ],
- "aggregateOperation": [
- 56
+ "subFieldName": [
+ 1
],
- "viewFieldGroupId": [
+ "relationTargetFieldMetadataId": [
3
],
"__typename": [
1
]
},
- "CreateViewFieldInput": {
+ "UpsertViewWidgetViewFilterGroupInput": {
"id": [
3
],
- "fieldMetadataId": [
- 3
- ],
- "viewId": [
+ "parentViewFilterGroupId": [
3
],
- "isVisible": [
- 8
- ],
- "size": [
- 15
+ "logicalOperator": [
+ 58
],
- "position": [
+ "positionInViewFilterGroup": [
15
],
- "aggregateOperation": [
- 56
- ],
- "viewFieldGroupId": [
- 3
- ],
"__typename": [
1
]
},
- "DeleteViewFieldInput": {
+ "UpsertViewWidgetViewSortInput": {
"id": [
3
],
+ "fieldMetadataId": [
+ 3
+ ],
+ "direction": [
+ 63
+ ],
"__typename": [
1
]
},
- "DestroyViewFieldInput": {
+ "CreateViewSortInput": {
"id": [
3
],
+ "fieldMetadataId": [
+ 3
+ ],
+ "direction": [
+ 63
+ ],
+ "subFieldName": [
+ 1
+ ],
+ "viewId": [
+ 3
+ ],
"__typename": [
1
]
},
- "UpdateViewFieldGroupInput": {
+ "UpdateViewSortInput": {
"id": [
3
],
"update": [
- 477
+ 470
],
"__typename": [
1
]
},
- "UpdateViewFieldGroupInputUpdates": {
- "name": [
- 1
- ],
- "position": [
- 15
- ],
- "isVisible": [
- 8
+ "UpdateViewSortInputUpdates": {
+ "direction": [
+ 63
],
- "deletedAt": [
+ "subFieldName": [
1
],
"__typename": [
1
]
},
- "CreateViewFieldGroupInput": {
+ "DeleteViewSortInput": {
"id": [
3
],
- "name": [
- 1
- ],
- "viewId": [
- 3
- ],
- "position": [
- 15
- ],
- "isVisible": [
- 8
- ],
"__typename": [
1
]
},
- "DeleteViewFieldGroupInput": {
+ "DestroyViewSortInput": {
"id": [
3
],
@@ -12181,100 +12113,76 @@ export default {
1
]
},
- "DestroyViewFieldGroupInput": {
+ "CreateViewFilterInput": {
"id": [
3
],
- "__typename": [
- 1
- ]
- },
- "UpsertFieldsWidgetInput": {
- "widgetId": [
+ "fieldMetadataId": [
3
],
- "groups": [
- 482
+ "operand": [
+ 60
],
- "fields": [
- 483
+ "value": [
+ 9
],
- "__typename": [
- 1
- ]
- },
- "UpsertFieldsWidgetGroupInput": {
- "id": [
+ "viewFilterGroupId": [
3
],
- "name": [
- 1
- ],
- "position": [
+ "positionInViewFilterGroup": [
15
],
- "isVisible": [
- 8
+ "subFieldName": [
+ 1
],
- "fields": [
- 483
+ "relationTargetFieldMetadataId": [
+ 3
+ ],
+ "viewId": [
+ 3
],
"__typename": [
1
]
},
- "UpsertFieldsWidgetFieldInput": {
- "viewFieldId": [
- 3
- ],
- "fieldMetadataId": [
+ "UpdateViewFilterInput": {
+ "id": [
3
],
- "isVisible": [
- 8
- ],
- "position": [
- 15
+ "update": [
+ 475
],
"__typename": [
1
]
},
- "CreateApiKeyInput": {
- "name": [
- 1
- ],
- "expiresAt": [
- 1
+ "UpdateViewFilterInputUpdates": {
+ "fieldMetadataId": [
+ 3
],
- "revokedAt": [
- 1
+ "operand": [
+ 60
],
- "roleId": [
- 3
+ "value": [
+ 9
],
- "__typename": [
- 1
- ]
- },
- "UpdateApiKeyInput": {
- "id": [
+ "viewFilterGroupId": [
3
],
- "name": [
- 1
+ "positionInViewFilterGroup": [
+ 15
],
- "expiresAt": [
+ "subFieldName": [
1
],
- "revokedAt": [
- 1
+ "relationTargetFieldMetadataId": [
+ 3
],
"__typename": [
1
]
},
- "RevokeApiKeyInput": {
+ "DeleteViewFilterInput": {
"id": [
3
],
@@ -12282,220 +12190,200 @@ export default {
1
]
},
- "CreateApprovedAccessDomainInput": {
- "domain": [
- 1
- ],
- "email": [
- 1
+ "DestroyViewFilterInput": {
+ "id": [
+ 3
],
"__typename": [
1
]
},
- "DeleteApprovedAccessDomainInput": {
+ "UpdateViewFieldInput": {
"id": [
3
],
+ "update": [
+ 479
+ ],
"__typename": [
1
]
},
- "ValidateApprovedAccessDomainInput": {
- "validationToken": [
- 1
+ "UpdateViewFieldInputUpdates": {
+ "isVisible": [
+ 8
],
- "approvedAccessDomainId": [
+ "size": [
+ 15
+ ],
+ "position": [
+ 15
+ ],
+ "aggregateOperation": [
+ 56
+ ],
+ "viewFieldGroupId": [
3
],
"__typename": [
1
]
},
- "CreatePageLayoutTabInput": {
- "title": [
- 1
+ "CreateViewFieldInput": {
+ "id": [
+ 3
],
- "position": [
- 15
+ "fieldMetadataId": [
+ 3
],
- "pageLayoutId": [
+ "viewId": [
3
],
- "layoutMode": [
- 104
+ "isVisible": [
+ 8
],
- "__typename": [
- 1
- ]
- },
- "UpdatePageLayoutTabInput": {
- "title": [
- 1
+ "size": [
+ 15
],
"position": [
15
],
- "icon": [
- 1
+ "aggregateOperation": [
+ 56
],
- "layoutMode": [
- 104
+ "viewFieldGroupId": [
+ 3
],
"__typename": [
1
]
},
- "CreatePageLayoutInput": {
- "name": [
- 1
- ],
- "type": [
- 147
- ],
- "objectMetadataId": [
+ "DeleteViewFieldInput": {
+ "id": [
3
],
"__typename": [
1
]
},
- "UpdatePageLayoutInput": {
- "name": [
- 1
- ],
- "type": [
- 147
+ "DestroyViewFieldInput": {
+ "id": [
+ 3
],
- "objectMetadataId": [
+ "__typename": [
+ 1
+ ]
+ },
+ "UpdateViewFieldGroupInput": {
+ "id": [
3
],
+ "update": [
+ 484
+ ],
"__typename": [
1
]
},
- "UpdatePageLayoutWithTabsInput": {
+ "UpdateViewFieldGroupInputUpdates": {
"name": [
1
],
- "type": [
- 147
- ],
- "objectMetadataId": [
- 3
+ "position": [
+ 15
],
- "isFirstTabPinned": [
+ "isVisible": [
8
],
- "tabs": [
- 495
+ "deletedAt": [
+ 1
],
"__typename": [
1
]
},
- "UpdatePageLayoutTabWithWidgetsInput": {
+ "CreateViewFieldGroupInput": {
"id": [
3
],
- "title": [
+ "name": [
1
],
+ "viewId": [
+ 3
+ ],
"position": [
15
],
- "icon": [
- 1
- ],
- "layoutMode": [
- 104
- ],
- "widgets": [
- 496
+ "isVisible": [
+ 8
],
"__typename": [
1
]
},
- "UpdatePageLayoutWidgetWithIdInput": {
+ "DeleteViewFieldGroupInput": {
"id": [
3
],
- "pageLayoutTabId": [
+ "__typename": [
+ 1
+ ]
+ },
+ "DestroyViewFieldGroupInput": {
+ "id": [
3
],
- "title": [
+ "__typename": [
1
- ],
- "type": [
- 101
- ],
- "objectMetadataId": [
+ ]
+ },
+ "UpsertFieldsWidgetInput": {
+ "widgetId": [
3
],
- "position": [
- 9
- ],
- "configuration": [
- 9
- ],
- "conditionalDisplay": [
- 9
+ "groups": [
+ 489
],
- "conditionalAvailabilityExpression": [
- 1
+ "fields": [
+ 490
],
"__typename": [
1
]
},
- "CreatePageLayoutWidgetInput": {
- "pageLayoutTabId": [
+ "UpsertFieldsWidgetGroupInput": {
+ "id": [
3
],
- "title": [
+ "name": [
1
],
- "type": [
- 101
- ],
- "objectMetadataId": [
- 3
- ],
"position": [
- 9
+ 15
],
- "configuration": [
- 9
+ "isVisible": [
+ 8
+ ],
+ "fields": [
+ 490
],
"__typename": [
1
]
},
- "UpdatePageLayoutWidgetInput": {
- "pageLayoutTabId": [
+ "UpsertFieldsWidgetFieldInput": {
+ "viewFieldId": [
3
],
- "title": [
- 1
- ],
- "type": [
- 101
- ],
- "objectMetadataId": [
+ "fieldMetadataId": [
3
],
- "position": [
- 9
- ],
- "configuration": [
- 9
- ],
- "conditionalDisplay": [
- 9
+ "isVisible": [
+ 8
],
- "conditionalAvailabilityExpression": [
- 1
+ "position": [
+ 15
],
"__typename": [
1
@@ -12576,7 +12464,7 @@ export default {
},
"CreateOneObjectInput": {
"object": [
- 502
+ 494
],
"__typename": [
1
@@ -12636,7 +12524,7 @@ export default {
},
"UpdateOneObjectInput": {
"update": [
- 505
+ 497
],
"id": [
3
@@ -12692,7 +12580,7 @@ export default {
27
],
"translations": [
- 506
+ 498
],
"__typename": [
1
@@ -12714,7 +12602,7 @@ export default {
},
"CreateOneIndexInput": {
"index": [
- 508
+ 500
],
"__typename": [
1
@@ -12725,7 +12613,7 @@ export default {
3
],
"fields": [
- 509
+ 501
],
"indexType": [
272
@@ -12810,7 +12698,7 @@ export default {
3
],
"update": [
- 514
+ 506
],
"__typename": [
1
@@ -12979,7 +12867,7 @@ export default {
3
],
"update": [
- 519
+ 511
],
"__typename": [
1
@@ -13101,6 +12989,118 @@ export default {
1
]
},
+ "CreateApprovedAccessDomainInput": {
+ "domain": [
+ 1
+ ],
+ "email": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "DeleteApprovedAccessDomainInput": {
+ "id": [
+ 3
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "ValidateApprovedAccessDomainInput": {
+ "validationToken": [
+ 1
+ ],
+ "approvedAccessDomainId": [
+ 3
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "CreateViewFilterGroupInput": {
+ "id": [
+ 3
+ ],
+ "parentViewFilterGroupId": [
+ 3
+ ],
+ "logicalOperator": [
+ 58
+ ],
+ "positionInViewFilterGroup": [
+ 15
+ ],
+ "viewId": [
+ 3
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UpdateViewFilterGroupInput": {
+ "id": [
+ 3
+ ],
+ "parentViewFilterGroupId": [
+ 3
+ ],
+ "logicalOperator": [
+ 58
+ ],
+ "positionInViewFilterGroup": [
+ 15
+ ],
+ "viewId": [
+ 3
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "CreateApiKeyInput": {
+ "name": [
+ 1
+ ],
+ "expiresAt": [
+ 1
+ ],
+ "revokedAt": [
+ 1
+ ],
+ "roleId": [
+ 3
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "UpdateApiKeyInput": {
+ "id": [
+ 3
+ ],
+ "name": [
+ 1
+ ],
+ "expiresAt": [
+ 1
+ ],
+ "revokedAt": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "RevokeApiKeyInput": {
+ "id": [
+ 3
+ ],
+ "__typename": [
+ 1
+ ]
+ },
"CreateApplicationRegistrationInput": {
"name": [
1
@@ -13349,7 +13349,7 @@ export default {
9
],
"translations": [
- 506
+ 498
],
"__typename": [
1
@@ -14135,20 +14135,6 @@ export default {
1
]
},
- "AgentChatQuestionAnswerInput": {
- "questionIndex": [
- 30
- ],
- "selectedOptionIndices": [
- 30
- ],
- "freeText": [
- 1
- ],
- "__typename": [
- 1
- ]
- },
"CreateSkillInput": {
"id": [
3
@@ -14232,7 +14218,7 @@ export default {
3
],
"update": [
- 593
+ 592
],
"__typename": [
1
@@ -14278,7 +14264,7 @@ export default {
8
],
"translations": [
- 506
+ 498
],
"__typename": [
1
@@ -14444,7 +14430,7 @@ export default {
1
],
"files": [
- 605
+ 604
],
"__typename": [
1
@@ -14466,13 +14452,13 @@ export default {
1
],
"IMAP": [
- 607
+ 606
],
"SMTP": [
- 607
+ 606
],
"CALDAV": [
- 607
+ 606
],
"__typename": [
1
@@ -14509,6 +14495,20 @@ export default {
1
]
},
+ "AgentChatQuestionAnswerInput": {
+ "questionIndex": [
+ 30
+ ],
+ "selectedOptionIndices": [
+ 30
+ ],
+ "freeText": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
"ApplicationFileUploadRequestInput": {
"fileFolder": [
319
@@ -14543,7 +14543,7 @@ export default {
}
],
"onAgentChatEvent": [
- 388,
+ 382,
{
"threadId": [
3,
@@ -14552,7 +14552,7 @@ export default {
}
],
"eventLogsLive": [
- 376,
+ 387,
{
"table": [
433,
@@ -14565,7 +14565,7 @@ export default {
}
],
"exportRecords": [
- 379,
+ 390,
{
"input": [
612,
diff --git a/packages/twenty-front/codegen.cjs b/packages/twenty-front/codegen.cjs
index ea426e135b2..2f68ea8c357 100644
--- a/packages/twenty-front/codegen.cjs
+++ b/packages/twenty-front/codegen.cjs
@@ -12,6 +12,7 @@ module.exports = {
'./src/modules/activities/calendar/graphql/queries/**/*.{ts,tsx}',
'./src/modules/search/graphql/**/*.{ts,tsx}',
'./src/modules/command-menu/graphql/**/*.{ts,tsx}',
+ './src/modules/input-ask/graphql/**/*.{ts,tsx}',
'!./src/**/*.test.{ts,tsx}',
'!./src/**/*.stories.{ts,tsx}',
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index 5a5fef6f68b..8d001c900c2 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -3054,6 +3054,7 @@ export type Mutation = {
activateSkill: Skill;
activateWorkspace: Workspace;
addQueryToEventStream: Scalars['Boolean']['output'];
+ /** @deprecated Use answerAsk with the question's Ask */
answerAgentChatQuestion: SendChatMessageResult;
archiveChatThread: AgentChatThread;
assignRoleToAgent: Scalars['Boolean']['output'];
@@ -7928,17 +7929,6 @@ export type ActivateSkillMutationVariables = Exact<{
export type ActivateSkillMutation = { __typename?: 'Mutation', activateSkill: { __typename?: 'Skill', id: string, name: string, label: string, description?: string | null, icon?: string | null, content: string, isCustom: boolean, isSystem: boolean, isActive: boolean, applicationId?: string | null, createdAt: string, updatedAt: string } };
-export type AnswerAgentChatQuestionMutationVariables = Exact<{
- threadId: Scalars['UUID']['input'];
- messageId: Scalars['UUID']['input'];
- answers: Array<AgentChatQuestionAnswerInput> | AgentChatQuestionAnswerInput;
- modelId?: InputMaybe<Scalars['String']['input']>;
- fileAttachments?: InputMaybe<Array<FileAttachmentInput> | FileAttachmentInput>;
-}>;
-
-
-export type AnswerAgentChatQuestionMutation = { __typename?: 'Mutation', answerAgentChatQuestion: { __typename?: 'SendChatMessageResult', messageId: string, queued: boolean, streamId?: string | null } };
-
export type ArchiveChatThreadMutationVariables = Exact<{
id: Scalars['UUID']['input'];
}>;
@@ -10577,7 +10567,6 @@ export const ResetTimelineActivityTypeDocument = {"kind":"Document","definitions
export const UpdateTimelineActivityTypeIsActiveDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateTimelineActivityTypeIsActive"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateTimelineActivityTypeInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateTimelineActivityType"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}}]}}]}}]} as unknown as DocumentNode<UpdateTimelineActivityTypeIsActiveMutation, UpdateTimelineActivityTypeIsActiveMutationVariables>;
export const FindManyTimelineActivityTypesDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindManyTimelineActivityTypes"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"timelineActivityTypes"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"emit"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"on"}},{"kind":"Field","name":{"kind":"Name","value":"objectUniversalIdentifier"}}]}},{"kind":"Field","name":{"kind":"Name","value":"frontComponentUniversalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}}]}}]}}]} as unknown as DocumentNode<FindManyTimelineActivityTypesQuery, FindManyTimelineActivityTypesQueryVariables>;
export const ActivateSkillDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"ActivateSkill"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"activateSkill"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SkillFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SkillFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Skill"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"isCustom"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<ActivateSkillMutation, ActivateSkillMutationVariables>;
-export const AnswerAgentChatQuestionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"AnswerAgentChatQuestion"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"messageId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"answers"}},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"AgentChatQuestionAnswerInput"}}}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"modelId"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"fileAttachments"}},"type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"FileAttachmentInput"}}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"answerAgentChatQuestion"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"threadId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}}},{"kind":"Argument","name":{"kind":"Name","value":"messageId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"messageId"}}},{"kind":"Argument","name":{"kind":"Name","value":"answers"},"value":{"kind":"Variable","name":{"kind":"Name","value":"answers"}}},{"kind":"Argument","name":{"kind":"Name","value":"modelId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"modelId"}}},{"kind":"Argument","name":{"kind":"Name","value":"fileAttachments"},"value":{"kind":"Variable","name":{"kind":"Name","value":"fileAttachments"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"messageId"}},{"kind":"Field","name":{"kind":"Name","value":"queued"}},{"kind":"Field","name":{"kind":"Name","value":"streamId"}}]}}]}}]} as unknown as DocumentNode<AnswerAgentChatQuestionMutation, AnswerAgentChatQuestionMutationVariables>;
export const ArchiveChatThreadDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"ArchiveChatThread"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"archiveChatThread"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<ArchiveChatThreadMutation, ArchiveChatThreadMutationVariables>;
export const AssignRoleToAgentDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"AssignRoleToAgent"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"agentId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"roleId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"assignRoleToAgent"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"agentId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"agentId"}}},{"kind":"Argument","name":{"kind":"Name","value":"roleId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"roleId"}}}]}]}}]} as unknown as DocumentNode<AssignRoleToAgentMutation, AssignRoleToAgentMutationVariables>;
export const CreateChatThreadDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CreateChatThread"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"createChatThread"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<CreateChatThreadMutation, CreateChatThreadMutationVariables>;
diff --git a/packages/twenty-front/src/generated/graphql.ts b/packages/twenty-front/src/generated/graphql.ts
index a47b345bb6f..90070dca511 100644
--- a/packages/twenty-front/src/generated/graphql.ts
+++ b/packages/twenty-front/src/generated/graphql.ts
@@ -18,6 +18,18 @@ export type Scalars = {
UUID: { input: any; output: any; }
};
+export type AnswerAskInput = {
+ askId: Scalars['UUID']['input'];
+ modelId?: InputMaybe<Scalars['String']['input']>;
+ /** The answer, validated against what the Ask asked (its form kind) */
+ response: Scalars['JSON']['input'];
+};
+
+export type AnswerAskResult = {
+ __typename?: 'AnswerAskResult';
+ streamId?: Maybe<Scalars['String']['output']>;
+};
+
export enum CalendarChannelVisibility {
METADATA = 'METADATA',
SHARE_EVERYTHING = 'SHARE_EVERYTHING'
@@ -420,6 +432,7 @@ export type Mutation = {
__typename?: 'Mutation';
activateCoreWorkflowVersion: Scalars['Boolean']['output'];
activateWorkflowVersion: Scalars['Boolean']['output'];
+ answerAsk: AnswerAskResult;
computeStepOutputSchema: Scalars['JSON']['output'];
createCoreWorkflow: CoreWorkflowDto;
createCoreWorkflowVersionEdge: WorkflowVersionStepChanges;
@@ -447,6 +460,7 @@ export type Mutation = {
runCoreWorkflowVersion: RunWorkflowVersion;
runWorkflowVersion: RunWorkflowVersion;
stopWorkflowRun: WorkflowRun;
+ /** @deprecated Use answerAsk with the form step's Ask */
submitFormStep: Scalars['Boolean']['output'];
testHttpRequest: TestHttpRequest;
updateCoreWorkflow?: Maybe<CoreWorkflowDto>;
@@ -472,6 +486,11 @@ export type MutationActivateWorkflowVersionArgs = {
};
+export type MutationAnswerAskArgs = {
+ input: AnswerAskInput;
+};
+
+
export type MutationComputeStepOutputSchemaArgs = {
input: ComputeStepOutputSchemaInput;
};
@@ -1210,6 +1229,13 @@ export type SearchQueryVariables = Exact<{
export type SearchQuery = { __typename?: 'Query', search: { __typename?: 'SearchResultConnection', edges: Array<{ __typename?: 'SearchResultEdge', cursor: string, node: { __typename?: 'SearchRecord', recordId: any, objectNameSingular: string, objectLabelSingular: string, label: string, imageUrl?: string | null, tsRankCD: number, tsRank: number } }>, pageInfo: { __typename?: 'SearchResultPageInfo', hasNextPage: boolean, endCursor?: string | null } } };
+export type AnswerAskMutationVariables = Exact<{
+ input: AnswerAskInput;
+}>;
+
+
+export type AnswerAskMutation = { __typename?: 'Mutation', answerAsk: { __typename?: 'AnswerAskResult', streamId?: string | null } };
+
export type ActivateCoreWorkflowVersionMutationVariables = Exact<{
coreWorkflowVersionId: Scalars['UUID']['input'];
}>;
@@ -1510,13 +1536,6 @@ export type WorkflowStepConnectedAccountHandleQueryVariables = Exact<{
export type WorkflowStepConnectedAccountHandleQuery = { __typename?: 'Query', workflowStepConnectedAccountHandle?: { __typename?: 'ConnectedAccountHandleDTO', id: any, handle: string, provider: string, handleAliases?: Array<string> | null } | null };
-export type SubmitFormStepMutationVariables = Exact<{
- input: SubmitFormStepInput;
-}>;
-
-
-export type SubmitFormStepMutation = { __typename?: 'Mutation', submitFormStep: boolean };
-
export type TestHttpRequestMutationVariables = Exact<{
input: TestHttpRequestInput;
}>;
@@ -1549,6 +1568,7 @@ export const WorkflowDiffFragmentFragmentDoc = {"kind":"Document","definitions":
export const GetTimelineCalendarEventsFromObjectRecordDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetTimelineCalendarEventsFromObjectRecord"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"objectNameSingular"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"recordId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"page"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"pageSize"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getTimelineCalendarEventsFromObjectRecord"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"objectNameSingular"},"value":{"kind":"Variable","name":{"kind":"Name","value":"objectNameSingular"}}},{"kind":"Argument","name":{"kind":"Name","value":"recordId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"recordId"}}},{"kind":"Argument","name":{"kind":"Name","value":"page"},"value":{"kind":"Variable","name":{"kind":"Name","value":"page"}}},{"kind":"Argument","name":{"kind":"Name","value":"pageSize"},"value":{"kind":"Variable","name":{"kind":"Name","value":"pageSize"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"TimelineCalendarEventsWithTotalFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"TimelineCalendarEventParticipantFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineCalendarEventParticipant"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"personId"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMemberId"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"avatarUrl"}},{"kind":"Field","name":{"kind":"Name","value":"handle"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"TimelineCalendarEventCallRecordingFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineCalendarEventCallRecording"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"TimelineCalendarEventFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineCalendarEvent"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"location"}},{"kind":"Field","name":{"kind":"Name","value":"startsAt"}},{"kind":"Field","name":{"kind":"Name","value":"endsAt"}},{"kind":"Field","name":{"kind":"Name","value":"isFullDay"}},{"kind":"Field","name":{"kind":"Name","value":"visibility"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"TimelineCalendarEventParticipantFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"callRecordings"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"TimelineCalendarEventCallRecordingFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"TimelineCalendarEventsWithTotalFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineCalendarEventsWithTotal"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"totalNumberOfCalendarEvents"}},{"kind":"Field","name":{"kind":"Name","value":"relatedPersonIds"}},{"kind":"Field","name":{"kind":"Name","value":"timelineCalendarEvents"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"TimelineCalendarEventFragment"}}]}}]}}]} as unknown as DocumentNode<GetTimelineCalendarEventsFromObjectRecordQuery, GetTimelineCalendarEventsFromObjectRecordQueryVariables>;
export const GetTimelineThreadsFromObjectRecordDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetTimelineThreadsFromObjectRecord"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"objectNameSingular"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"recordId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"page"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"pageSize"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getTimelineThreadsFromObjectRecord"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"objectNameSingular"},"value":{"kind":"Variable","name":{"kind":"Name","value":"objectNameSingular"}}},{"kind":"Argument","name":{"kind":"Name","value":"recordId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"recordId"}}},{"kind":"Argument","name":{"kind":"Name","value":"page"},"value":{"kind":"Variable","name":{"kind":"Name","value":"page"}}},{"kind":"Argument","name":{"kind":"Name","value":"pageSize"},"value":{"kind":"Variable","name":{"kind":"Name","value":"pageSize"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"TimelineThreadsWithTotalFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ParticipantFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineThreadParticipant"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"personId"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceMemberId"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"avatarUrl"}},{"kind":"Field","name":{"kind":"Name","value":"handle"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"TimelineThreadFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"read"}},{"kind":"Field","name":{"kind":"Name","value":"visibility"}},{"kind":"Field","name":{"kind":"Name","value":"firstParticipant"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ParticipantFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"lastTwoParticipants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"ParticipantFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"lastMessageReceivedAt"}},{"kind":"Field","name":{"kind":"Name","value":"lastMessageBody"}},{"kind":"Field","name":{"kind":"Name","value":"subject"}},{"kind":"Field","name":{"kind":"Name","value":"numberOfMessagesInThread"}},{"kind":"Field","name":{"kind":"Name","value":"participantCount"}},{"kind":"Field","name":{"kind":"Name","value":"lastMessageIsDraft"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"TimelineThreadsWithTotalFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineThreadsWithTotal"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"totalNumberOfThreads"}},{"kind":"Field","name":{"kind":"Name","value":"relatedPersonIds"}},{"kind":"Field","name":{"kind":"Name","value":"timelineThreads"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"TimelineThreadFragment"}}]}}]}}]} as unknown as DocumentNode<GetTimelineThreadsFromObjectRecordQuery, GetTimelineThreadsFromObjectRecordQueryVariables>;
export const SearchDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"Search"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"searchInput"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"limit"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"after"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"excludedObjectNameSingulars"}},"type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"includedObjectNameSingulars"}},"type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"filter"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"ObjectRecordFilterInput"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"search"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"searchInput"},"value":{"kind":"Variable","name":{"kind":"Name","value":"searchInput"}}},{"kind":"Argument","name":{"kind":"Name","value":"limit"},"value":{"kind":"Variable","name":{"kind":"Name","value":"limit"}}},{"kind":"Argument","name":{"kind":"Name","value":"after"},"value":{"kind":"Variable","name":{"kind":"Name","value":"after"}}},{"kind":"Argument","name":{"kind":"Name","value":"excludedObjectNameSingulars"},"value":{"kind":"Variable","name":{"kind":"Name","value":"excludedObjectNameSingulars"}}},{"kind":"Argument","name":{"kind":"Name","value":"includedObjectNameSingulars"},"value":{"kind":"Variable","name":{"kind":"Name","value":"includedObjectNameSingulars"}}},{"kind":"Argument","name":{"kind":"Name","value":"filter"},"value":{"kind":"Variable","name":{"kind":"Name","value":"filter"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"edges"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"node"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"recordId"}},{"kind":"Field","name":{"kind":"Name","value":"objectNameSingular"}},{"kind":"Field","name":{"kind":"Name","value":"objectLabelSingular"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"imageUrl"}},{"kind":"Field","name":{"kind":"Name","value":"tsRankCD"}},{"kind":"Field","name":{"kind":"Name","value":"tsRank"}}]}},{"kind":"Field","name":{"kind":"Name","value":"cursor"}}]}},{"kind":"Field","name":{"kind":"Name","value":"pageInfo"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"hasNextPage"}},{"kind":"Field","name":{"kind":"Name","value":"endCursor"}}]}}]}}]}}]} as unknown as DocumentNode<SearchQuery, SearchQueryVariables>;
+export const AnswerAskDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"AnswerAsk"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"AnswerAskInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"answerAsk"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"streamId"}}]}}]}}]} as unknown as DocumentNode<AnswerAskMutation, AnswerAskMutationVariables>;
export const ActivateCoreWorkflowVersionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"ActivateCoreWorkflowVersion"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"coreWorkflowVersionId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"activateWorkflowVersion"},"name":{"kind":"Name","value":"activateCoreWorkflowVersion"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"coreWorkflowVersionId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"coreWorkflowVersionId"}}}]}]}}]} as unknown as DocumentNode<ActivateCoreWorkflowVersionMutation, ActivateCoreWorkflowVersionMutationVariables>;
export const CreateCoreWorkflowDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CreateCoreWorkflow"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"CreateCoreWorkflowInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"createCoreWorkflow"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"statuses"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceWorkflowId"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<CreateCoreWorkflowMutation, CreateCoreWorkflowMutationVariables>;
export const CreateCoreWorkflowVersionEdgeDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CreateCoreWorkflowVersionEdge"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"CreateCoreWorkflowVersionEdgeInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"createWorkflowVersionEdge"},"name":{"kind":"Name","value":"createCoreWorkflowVersionEdge"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"WorkflowDiffFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"WorkflowDiffFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkflowVersionStepChanges"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"triggerDiff"}},{"kind":"Field","name":{"kind":"Name","value":"stepsDiff"}}]}}]} as unknown as DocumentNode<CreateCoreWorkflowVersionEdgeMutation, CreateCoreWorkflowVersionEdgeMutationVariables>;
@@ -1591,7 +1611,6 @@ export const UpdateWorkflowRunStepDocument = {"kind":"Document","definitions":[{
export const UpdateWorkflowVersionStepDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateWorkflowVersionStep"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateWorkflowVersionStepInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateWorkflowVersionStep"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"settings"}},{"kind":"Field","name":{"kind":"Name","value":"valid"}},{"kind":"Field","name":{"kind":"Name","value":"nextStepIds"}},{"kind":"Field","name":{"kind":"Name","value":"position"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"x"}},{"kind":"Field","name":{"kind":"Name","value":"y"}}]}}]}}]}}]} as unknown as DocumentNode<UpdateWorkflowVersionStepMutation, UpdateWorkflowVersionStepMutationVariables>;
export const UpdateWorkflowVersionTriggerDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateWorkflowVersionTrigger"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateWorkflowVersionTriggerInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateWorkflowVersionTrigger"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"trigger"}}]}}]}}]} as unknown as DocumentNode<UpdateWorkflowVersionTriggerMutation, UpdateWorkflowVersionTriggerMutationVariables>;
export const WorkflowStepConnectedAccountHandleDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"WorkflowStepConnectedAccountHandle"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"connectedAccountId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"workflowStepConnectedAccountHandle"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"connectedAccountId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"connectedAccountId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"handle"}},{"kind":"Field","name":{"kind":"Name","value":"provider"}},{"kind":"Field","name":{"kind":"Name","value":"handleAliases"}}]}}]}}]} as unknown as DocumentNode<WorkflowStepConnectedAccountHandleQuery, WorkflowStepConnectedAccountHandleQueryVariables>;
-export const SubmitFormStepDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"SubmitFormStep"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SubmitFormStepInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"submitFormStep"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}]}]}}]} as unknown as DocumentNode<SubmitFormStepMutation, SubmitFormStepMutationVariables>;
export const TestHttpRequestDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"TestHttpRequest"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"TestHttpRequestInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"testHttpRequest"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"success"}},{"kind":"Field","name":{"kind":"Name","value":"message"}},{"kind":"Field","name":{"kind":"Name","value":"result"}},{"kind":"Field","name":{"kind":"Name","value":"error"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"statusText"}},{"kind":"Field","name":{"kind":"Name","value":"headers"}}]}}]}}]} as unknown as DocumentNode<TestHttpRequestMutation, TestHttpRequestMutationVariables>;
export const UpdateWorkflowVersionPositionsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateWorkflowVersionPositions"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateWorkflowVersionPositionsInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateWorkflowVersionPositions"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}]}]}}]} as unknown as DocumentNode<UpdateWorkflowVersionPositionsMutation, UpdateWorkflowVersionPositionsMutationVariables>;
export const GetWorkflowVersionContentDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetWorkflowVersionContent"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workflowVersionId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"workflowVersionContent"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workflowVersionId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workflowVersionId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"workflowVersionId"}},{"kind":"Field","name":{"kind":"Name","value":"trigger"}},{"kind":"Field","name":{"kind":"Name","value":"steps"}}]}}]}}]} as unknown as DocumentNode<GetWorkflowVersionContentQuery, GetWorkflowVersionContentQueryVariables>;
\ No newline at end of file
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatAskCard.tsx b/packages/twenty-front/src/modules/ai/components/AiChatAskCard.tsx
new file mode 100644
index 00000000000..3a4da74f9ec
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/AiChatAskCard.tsx
@@ -0,0 +1,36 @@
+import { assertUnreachable } from 'twenty-shared/utils';
+
+import { AiChatEmailApprovalCard } from '@/ai/components/AiChatEmailApprovalCard';
+import { AiChatQuestionCard } from '@/ai/components/AiChatQuestionCard';
+import { type AgentChatPendingAsk } from '@/ai/types/AgentChatPendingAsk';
+
+type AiChatAskCardProps = {
+ pendingAsk: AgentChatPendingAsk;
+};
+
+export const AiChatAskCard = ({ pendingAsk }: AiChatAskCardProps) => {
+ const { id, toolCallId, form } = pendingAsk;
+
+ switch (form.kind) {
+ case 'questions':
+ return (
+ <AiChatQuestionCard
+ pendingQuestion={{
+ askId: id,
+ toolCallId,
+ questions: form.questions,
+ }}
+ />
+ );
+ case 'emailApproval':
+ return (
+ <AiChatEmailApprovalCard
+ askId={id}
+ toolCallId={toolCallId}
+ email={form.email}
+ />
+ );
+ default:
+ return assertUnreachable(form);
+ }
+};
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatAskStyledComponents.tsx b/packages/twenty-front/src/modules/ai/components/AiChatAskStyledComponents.tsx
new file mode 100644
index 00000000000..e499b5968bd
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/AiChatAskStyledComponents.tsx
@@ -0,0 +1,31 @@
+import { styled } from '@linaria/react';
+import { themeCssVariables } from 'twenty-ui/theme';
+
+export const StyledAiChatAskCard = styled.div`
+ background-color: ${themeCssVariables.background.transparent.lighter};
+ border: 1px solid ${themeCssVariables.border.color.medium};
+ border-radius: ${themeCssVariables.border.radius.sm};
+ box-sizing: border-box;
+ display: flex;
+ flex-direction: column;
+ width: 100%;
+`;
+
+export const StyledAiChatAskStatusContainer = styled.div`
+ align-items: flex-start;
+ color: ${themeCssVariables.font.color.tertiary};
+ display: flex;
+ gap: ${themeCssVariables.spacing[1]};
+ padding: ${themeCssVariables.spacing[1]} 0;
+
+ svg {
+ flex-shrink: 0;
+ margin-top: 1px;
+ }
+`;
+
+export const StyledAiChatAskStatusMessage = styled.span`
+ color: ${themeCssVariables.font.color.tertiary};
+ font-size: ${themeCssVariables.font.size.md};
+ font-weight: ${themeCssVariables.font.weight.medium};
+`;
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatAssistantMessageRenderer.tsx b/packages/twenty-front/src/modules/ai/components/AiChatAssistantMessageRenderer.tsx
index b2d8fcf6775..cb6669ec904 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatAssistantMessageRenderer.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatAssistantMessageRenderer.tsx
@@ -4,6 +4,7 @@ import { CodeExecutionDisplay } from '@/ai/components/CodeExecutionDisplay';
import { RoutingStatusDisplay } from '@/ai/components/RoutingStatusDisplay';
import { ThinkingStepsDisplay } from '@/ai/components/ThinkingStepsDisplay';
+import { AiChatEmailApprovalStatusRenderer } from '@/ai/components/AiChatEmailApprovalStatusRenderer';
import { AiChatQuestionStatusRenderer } from '@/ai/components/AiChatQuestionStatusRenderer';
import { AiChatToolPartRenderer } from '@/ai/components/AiChatToolPartRenderer';
import { LazyMarkdownContent } from '@/ai/components/LazyMarkdownRenderer';
@@ -21,6 +22,7 @@ import {
ASK_QUESTIONS_TOOL_NAME,
type ExtendedUIMessagePart,
isSucceededCompleteWorkspaceSetupToolPart,
+ PROPOSE_EMAIL_TOOL_NAME,
} from 'twenty-shared/ai';
import { themeCssVariables } from 'twenty-ui/theme';
@@ -70,6 +72,15 @@ const MessagePartRenderer = ({
);
}
+ if (getToolName(part) === PROPOSE_EMAIL_TOOL_NAME) {
+ return (
+ <AiChatEmailApprovalStatusRenderer
+ toolPart={part}
+ isStreaming={isStreaming}
+ />
+ );
+ }
+
const widget = widgetByToolName.get(getEffectiveToolName(part));
if (!shouldToolPartRenderStandalone(part, widget)) {
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx
index cac4987dc0f..e234464bf42 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx
@@ -7,12 +7,13 @@ import { EditorContent } from '@tiptap/react';
import { useLingui } from '@lingui/react/macro';
import { themeCssVariables } from 'twenty-ui/theme';
+import { CoreObjectNameSingular } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { AiChatInlineBanner } from '@/ai/components/AiChatInlineBanner';
import { AiModelTierDropdown } from '@/ai/components/AiModelTierDropdown';
import { AiChatEmptyState } from '@/ai/components/AiChatEmptyState';
-import { AiChatQuestionCard } from '@/ai/components/AiChatQuestionCard';
+import { AiChatPendingAskGate } from '@/ai/components/AiChatPendingAskGate';
import { AIChatNoMoreBillingCreditsBanner } from '@/ai/components/AIChatNoMoreBillingCreditsBanner';
import { AiChatUsageLimitReachedBanner } from '@/ai/components/AiChatUsageLimitReachedBanner';
import { AiChatStandaloneError } from '@/ai/components/AiChatStandaloneError';
@@ -29,10 +30,12 @@ import { useInsertDictatedText } from '@/ai/dictation/hooks/useInsertDictatedTex
import { useIsAiChatComposerCentered } from '@/ai/hooks/useIsAiChatComposerCentered';
import { useHasReachedAiChatCreditsCap } from '@/ai/hooks/useHasReachedAiChatCreditsCap';
import { useHasReachedAiChatUsageLimit } from '@/ai/hooks/useHasReachedAiChatUsageLimit';
-import { agentChatPendingQuestionComponentSelector } from '@/ai/states/selectors/agentChatPendingQuestionComponentSelector';
+import { AGENT_CHAT_NEW_THREAD_DRAFT_KEY } from '@/ai/states/agentChatDraftsByThreadIdState';
+import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';
+import { objectMetadataItemFamilySelector } from '@/object-metadata/states/objectMetadataItemFamilySelector';
import { aiModelsState } from '@/client-config/states/aiModelsState';
import { useIsMobile } from 'twenty-ui/utilities';
-import { useAtomComponentSelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentSelectorValue';
+import { useAtomFamilySelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
const StyledInputArea = styled(StyledAiChatContentContainer)<{
@@ -163,8 +166,45 @@ const EditableAiChatEditorSection = () => {
const insertDictatedText = useInsertDictatedText(editor);
const [dictationInterimText, setDictationInterimText] = useState('');
- const pendingQuestion = useAtomComponentSelectorValue(
- agentChatPendingQuestionComponentSelector,
+ const agentChatDisplayedThread = useAtomStateValue(
+ agentChatDisplayedThreadState,
+ );
+ // A workspace the Ask object has not reached yet has nothing to wait on.
+ const inputAskObjectMetadataItem = useAtomFamilySelectorValue(
+ objectMetadataItemFamilySelector,
+ { objectName: CoreObjectNameSingular.InputAsk, objectNameType: 'singular' },
+ );
+ const pendingAskThreadId =
+ isDefined(inputAskObjectMetadataItem) &&
+ isDefined(agentChatDisplayedThread) &&
+ agentChatDisplayedThread !== AGENT_CHAT_NEW_THREAD_DRAFT_KEY
+ ? agentChatDisplayedThread
+ : null;
+
+ const composer = (
+ <StyledInputBox isMobile={isMobile}>
+ <StyledEditorWrapper isMobile={isMobile}>
+ <EditorContent editor={editor} />
+ </StyledEditorWrapper>
+ <AiChatDictationHint interimText={dictationInterimText} />
+ <StyledButtonsContainer>
+ <StyledLeftButtonsContainer>
+ <AiChatAddMenu editor={editor} />
+ <AiChatDictationButton />
+ <AiChatContextUsageButton />
+ </StyledLeftButtonsContainer>
+ <StyledRightButtonsContainer>
+ <AiModelTierDropdown
+ dropdownId="ai-chat-model-tier-dropdown"
+ disabled={hasNoEnabledModels}
+ />
+ <SendMessageButton
+ onSend={handleSendAndClear}
+ isDisabled={hasNoEnabledModels}
+ />
+ </StyledRightButtonsContainer>
+ </StyledButtonsContainer>
+ </StyledInputBox>
);
return (
@@ -186,32 +226,12 @@ const EditableAiChatEditorSection = () => {
)}
{hasReachedAiChatCreditsCap && <AIChatNoMoreBillingCreditsBanner />}
{shouldShowUsageLimitBanner && <AiChatUsageLimitReachedBanner />}
- {isDefined(pendingQuestion) ? (
- <AiChatQuestionCard pendingQuestion={pendingQuestion} />
+ {isDefined(pendingAskThreadId) ? (
+ <AiChatPendingAskGate threadId={pendingAskThreadId}>
+ {composer}
+ </AiChatPendingAskGate>
) : (
- <StyledInputBox isMobile={isMobile}>
- <StyledEditorWrapper isMobile={isMobile}>
- <EditorContent editor={editor} />
- </StyledEditorWrapper>
- <AiChatDictationHint interimText={dictationInterimText} />
- <StyledButtonsContainer>
- <StyledLeftButtonsContainer>
- <AiChatAddMenu editor={editor} />
- <AiChatDictationButton />
- <AiChatContextUsageButton />
- </StyledLeftButtonsContainer>
- <StyledRightButtonsContainer>
- <AiModelTierDropdown
- dropdownId="ai-chat-model-tier-dropdown"
- disabled={hasNoEnabledModels}
- />
- <SendMessageButton
- onSend={handleSendAndClear}
- isDisabled={hasNoEnabledModels}
- />
- </StyledRightButtonsContainer>
- </StyledButtonsContainer>
- </StyledInputBox>
+ composer
)}
</StyledInputArea>
<StyledComposerBottomSpacer
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatEmailApprovalCard.tsx b/packages/twenty-front/src/modules/ai/components/AiChatEmailApprovalCard.tsx
new file mode 100644
index 00000000000..16c864de249
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/AiChatEmailApprovalCard.tsx
@@ -0,0 +1,277 @@
+import { styled } from '@linaria/react';
+import { useLingui } from '@lingui/react/macro';
+import { type FocusEvent, useId, useState } from 'react';
+import TextareaAutosize from 'react-textarea-autosize';
+import {
+ type EmailApprovalDecision,
+ type InputAskEmailApprovalResponse,
+ type ProposeEmailToolResult,
+ type ProposedEmail,
+} from 'twenty-shared/ai';
+import { LightButton } from 'twenty-ui/components';
+import { IconDeviceFloppy, IconSend, IconTrash } from 'twenty-ui/icon';
+import { Button } from 'twenty-ui/primitives/input';
+import { themeCssVariables } from 'twenty-ui/theme';
+
+import { parseEmailRecipients } from '@/activities/emails/recipients/utils/parseEmailRecipients';
+import { serializeEmailRecipients } from '@/activities/emails/recipients/utils/serializeEmailRecipients';
+import { StyledAiChatAskCard } from '@/ai/components/AiChatAskStyledComponents';
+import { AiChatEmailRecipientsRow } from '@/ai/components/internal/AiChatEmailRecipientsRow';
+import { useAnswerAgentChatAsk } from '@/ai/hooks/useAnswerAgentChatAsk';
+import { usePushFocusItemToFocusStack } from '@/ui/utilities/focus/hooks/usePushFocusItemToFocusStack';
+import { useRemoveFocusItemFromFocusStackById } from '@/ui/utilities/focus/hooks/useRemoveFocusItemFromFocusStackById';
+import { FocusComponentType } from '@/ui/utilities/focus/types/FocusComponentType';
+
+const StyledHeader = styled.div`
+ color: ${themeCssVariables.font.color.primary};
+ font-size: ${themeCssVariables.font.size.md};
+ font-weight: ${themeCssVariables.font.weight.medium};
+ padding: ${themeCssVariables.spacing[2]} ${themeCssVariables.spacing[3]} 0;
+`;
+
+const StyledFields = styled.div`
+ display: flex;
+ flex-direction: column;
+ gap: ${themeCssVariables.spacing[1]};
+ padding: ${themeCssVariables.spacing[2]} ${themeCssVariables.spacing[3]};
+`;
+
+const StyledSubjectInput = styled.input`
+ background: transparent;
+ border: none;
+ border-bottom: 1px solid ${themeCssVariables.border.color.light};
+ color: ${themeCssVariables.font.color.primary};
+ font-family: inherit;
+ font-size: ${themeCssVariables.font.size.md};
+ font-weight: ${themeCssVariables.font.weight.medium};
+ outline: none;
+ padding: ${themeCssVariables.spacing[1]} 0;
+`;
+
+const StyledBodyTextarea = styled(TextareaAutosize)`
+ background: transparent;
+ border: none;
+ color: ${themeCssVariables.font.color.primary};
+ font-family: inherit;
+ font-size: ${themeCssVariables.font.size.md};
+ line-height: 1.5;
+ outline: none;
+ padding: ${themeCssVariables.spacing[1]} 0;
+ resize: none;
+`;
+
+const StyledRecipientToggles = styled.div`
+ display: flex;
+ gap: ${themeCssVariables.spacing[1]};
+`;
+
+const StyledDivider = styled.div`
+ background: ${themeCssVariables.border.color.light};
+ height: 1px;
+ width: 100%;
+`;
+
+const StyledActions = styled.div`
+ display: flex;
+ gap: ${themeCssVariables.spacing[2]};
+ justify-content: flex-end;
+ padding: ${themeCssVariables.spacing[2]};
+`;
+
+type AiChatEmailApprovalCardProps = {
+ askId: string;
+ toolCallId: string;
+ email: ProposedEmail;
+};
+
+export const AiChatEmailApprovalCard = ({
+ askId,
+ toolCallId,
+ email,
+}: AiChatEmailApprovalCardProps) => {
+ const { t } = useLingui();
+ const focusId = useId();
+ const { answerAgentChatAsk } = useAnswerAgentChatAsk();
+ const { pushFocusItemToFocusStack } = usePushFocusItemToFocusStack();
+ const { removeFocusItemFromFocusStackById } =
+ useRemoveFocusItemFromFocusStackById();
+
+ const [to, setTo] = useState(() => parseEmailRecipients(email.recipients.to));
+ const [cc, setCc] = useState(() => parseEmailRecipients(email.recipients.cc));
+ const [bcc, setBcc] = useState(() =>
+ parseEmailRecipients(email.recipients.bcc),
+ );
+ // Shown from the start when the draft has any, and kept once opened, so
+ // removing the last recipient does not take the field away.
+ const [isCcShown, setIsCcShown] = useState(cc.length > 0);
+ const [isBccShown, setIsBccShown] = useState(bcc.length > 0);
+ const [subject, setSubject] = useState(email.subject);
+ const [body, setBody] = useState(email.body);
+ const [pendingDecision, setPendingDecision] =
+ useState<EmailApprovalDecision | null>(null);
+
+ const isAnswering = pendingDecision !== null;
+
+ // Typing in the card must not trigger the page's keyboard shortcuts. Focus
+ // events bubble up from every field, and from the buttons between them,
+ // which are left out since a button removed on click may never blur.
+ const handleFieldFocus = (event: FocusEvent) => {
+ if (
+ !(event.target instanceof HTMLInputElement) &&
+ !(event.target instanceof HTMLTextAreaElement)
+ ) {
+ return;
+ }
+
+ pushFocusItemToFocusStack({
+ focusId,
+ component: { type: FocusComponentType.TEXT_AREA, instanceId: focusId },
+ globalHotkeysConfig: {
+ enableGlobalHotkeysConflictingWithKeyboard: false,
+ },
+ });
+ };
+
+ const handleFieldBlur = () => {
+ removeFocusItemFromFocusStackById({ focusId });
+ };
+
+ const decide = async (decision: EmailApprovalDecision) => {
+ setPendingDecision(decision);
+
+ const editedEmail: ProposedEmail = {
+ ...email,
+ recipients: {
+ to: serializeEmailRecipients(to),
+ cc: serializeEmailRecipients(cc),
+ bcc: serializeEmailRecipients(bcc),
+ },
+ subject,
+ body,
+ };
+ const response: InputAskEmailApprovalResponse =
+ decision === 'discard' ? { decision } : { decision, email: editedEmail };
+
+ const isAnswered = await answerAgentChatAsk({
+ askId,
+ toolCallId,
+ response,
+ // Only a discard is known before the server answers: sending or saving
+ // can still fail.
+ optimisticToolOutput:
+ decision === 'discard'
+ ? {
+ success: true,
+ result: {
+ status: 'discarded',
+ email,
+ } satisfies ProposeEmailToolResult,
+ }
+ : undefined,
+ });
+
+ // The card goes once its Ask does, so it stays disabled until then.
+ if (!isAnswered) {
+ setPendingDecision(null);
+ }
+ };
+
+ return (
+ <StyledAiChatAskCard>
+ <StyledHeader>{t`Review this email before it goes out`}</StyledHeader>
+ <StyledFields onFocus={handleFieldFocus} onBlur={handleFieldBlur}>
+ <AiChatEmailRecipientsRow
+ label={t`To`}
+ recipients={to}
+ disabled={isAnswering}
+ onChange={setTo}
+ />
+ {(!isCcShown || !isBccShown) && (
+ <StyledRecipientToggles>
+ {!isCcShown && (
+ <LightButton
+ disabled={isAnswering}
+ onClick={() => setIsCcShown(true)}
+ >
+ {t`Cc`}
+ </LightButton>
+ )}
+ {!isBccShown && (
+ <LightButton
+ disabled={isAnswering}
+ onClick={() => setIsBccShown(true)}
+ >
+ {t`Bcc`}
+ </LightButton>
+ )}
+ </StyledRecipientToggles>
+ )}
+ {isCcShown && (
+ <AiChatEmailRecipientsRow
+ label={t`Cc`}
+ recipients={cc}
+ disabled={isAnswering}
+ onChange={setCc}
+ />
+ )}
+ {isBccShown && (
+ <AiChatEmailRecipientsRow
+ label={t`Bcc`}
+ recipients={bcc}
+ disabled={isAnswering}
+ onChange={setBcc}
+ />
+ )}
+ <StyledSubjectInput
+ aria-label={t`Subject`}
+ placeholder={t`Subject`}
+ value={subject}
+ disabled={isAnswering}
+ onChange={(event) => setSubject(event.target.value)}
+ />
+ <StyledBodyTextarea
+ aria-label={t`Email body`}
+ minRows={4}
+ maxRows={16}
+ value={body}
+ disabled={isAnswering}
+ onChange={(event) => setBody(event.target.value)}
+ />
+ </StyledFields>
+ <StyledDivider />
+ <StyledActions>
+ <Button
+ size="sm"
+ variant="ghost"
+ startIcon={<IconTrash />}
+ disabled={isAnswering}
+ loading={pendingDecision === 'discard'}
+ onClick={() => void decide('discard')}
+ >
+ {t`Discard`}
+ </Button>
+ <Button
+ size="sm"
+ variant="outline"
+ startIcon={<IconDeviceFloppy />}
+ disabled={isAnswering}
+ loading={pendingDecision === 'saveDraft'}
+ onClick={() => void decide('saveDraft')}
+ >
+ {t`Save as draft`}
+ </Button>
+ <Button
+ size="sm"
+ variant="solid"
+ color="accent"
+ startIcon={<IconSend />}
+ disabled={isAnswering || to.length === 0}
+ loading={pendingDecision === 'send'}
+ onClick={() => void decide('send')}
+ >
+ {t`Send`}
+ </Button>
+ </StyledActions>
+ </StyledAiChatAskCard>
+ );
+};
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatEmailApprovalStatusRenderer.tsx b/packages/twenty-front/src/modules/ai/components/AiChatEmailApprovalStatusRenderer.tsx
new file mode 100644
index 00000000000..602b05c2354
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/AiChatEmailApprovalStatusRenderer.tsx
@@ -0,0 +1,88 @@
+import { styled } from '@linaria/react';
+import { useLingui } from '@lingui/react/macro';
+import { isNonEmptyString } from '@sniptt/guards';
+import { type DynamicToolUIPart, type ToolUIPart } from 'ai';
+import {
+ type ProposeEmailToolResult,
+ type ProposeEmailToolStatus,
+} from 'twenty-shared/ai';
+import { isDefined } from 'twenty-shared/utils';
+import { IconMail } from 'twenty-ui/icon';
+import { useTheme, themeCssVariables } from 'twenty-ui/theme';
+
+import {
+ StyledAiChatAskStatusContainer,
+ StyledAiChatAskStatusMessage,
+} from '@/ai/components/AiChatAskStyledComponents';
+import { ShimmeringText } from '@/ai/components/ShimmeringText';
+
+const StyledContent = styled.div`
+ display: flex;
+ flex-direction: column;
+ gap: ${themeCssVariables.spacing['0.5']};
+ min-width: 0;
+`;
+
+const StyledDetail = styled.span`
+ color: ${themeCssVariables.font.color.secondary};
+ font-size: ${themeCssVariables.font.size.sm};
+ overflow-wrap: anywhere;
+`;
+
+export const AiChatEmailApprovalStatusRenderer = ({
+ toolPart,
+ isStreaming,
+}: {
+ toolPart: ToolUIPart | DynamicToolUIPart;
+ isStreaming: boolean;
+}) => {
+ const { t } = useLingui();
+ const theme = useTheme();
+
+ const result = (
+ toolPart.output as { result?: ProposeEmailToolResult } | null | undefined
+ )?.result;
+ const status: ProposeEmailToolStatus = result?.status ?? 'pending';
+
+ const messageByStatus: Record<ProposeEmailToolStatus, string> = {
+ pending: isDefined(result)
+ ? t`Email waiting for your review`
+ : t`Drafting an email...`,
+ sent: t`Email sent`,
+ drafted: t`Email saved as draft`,
+ discarded: t`Email discarded`,
+ failed: t`Email could not go through`,
+ skipped: t`Email skipped`,
+ };
+ const message = messageByStatus[status];
+
+ const recipients = result?.email.recipients.to;
+ const subject = result?.email.subject;
+ const hasEmailDetail =
+ (status === 'sent' || status === 'drafted') &&
+ isNonEmptyString(subject) &&
+ isNonEmptyString(recipients);
+
+ return (
+ <StyledAiChatAskStatusContainer>
+ <IconMail size={theme.icon.size.sm} />
+ <StyledContent>
+ {isStreaming && status === 'pending' ? (
+ <ShimmeringText>
+ <StyledAiChatAskStatusMessage>
+ {message}
+ </StyledAiChatAskStatusMessage>
+ </ShimmeringText>
+ ) : (
+ <StyledAiChatAskStatusMessage>{message}</StyledAiChatAskStatusMessage>
+ )}
+ {hasEmailDetail && (
+ <StyledDetail>{t`"${subject}" to ${recipients}`}</StyledDetail>
+ )}
+ {status === 'failed' && isNonEmptyString(result?.error) && (
+ <StyledDetail>{result.error}</StyledDetail>
+ )}
+ </StyledContent>
+ </StyledAiChatAskStatusContainer>
+ );
+};
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatPendingAskGate.tsx b/packages/twenty-front/src/modules/ai/components/AiChatPendingAskGate.tsx
new file mode 100644
index 00000000000..07a7a2acb86
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/AiChatPendingAskGate.tsx
@@ -0,0 +1,54 @@
+import { styled } from '@linaria/react';
+import { useLingui } from '@lingui/react/macro';
+import { type ReactNode } from 'react';
+import { isDefined } from 'twenty-shared/utils';
+import { themeCssVariables } from 'twenty-ui/theme';
+
+import { AiChatAskCard } from '@/ai/components/AiChatAskCard';
+import { useAgentChatPendingAsks } from '@/ai/hooks/useAgentChatPendingAsks';
+
+const StyledGate = styled.div`
+ display: flex;
+ flex-direction: column;
+ gap: ${themeCssVariables.spacing[1]};
+ width: 100%;
+`;
+
+const StyledWaitingCount = styled.span`
+ color: ${themeCssVariables.font.color.light};
+ font-size: ${themeCssVariables.font.size.sm};
+ padding: 0 ${themeCssVariables.spacing[1]};
+`;
+
+type AiChatPendingAskGateProps = {
+ threadId: string;
+ children: ReactNode;
+};
+
+// The agent continues once every call it paused on is answered, so the
+// cards come one at a time, oldest first, each taking the composer's place.
+export const AiChatPendingAskGate = ({
+ threadId,
+ children,
+}: AiChatPendingAskGateProps) => {
+ const { t } = useLingui();
+ const pendingAsks = useAgentChatPendingAsks({ threadId });
+ const [currentAsk] = pendingAsks;
+
+ if (!isDefined(currentAsk)) {
+ return children;
+ }
+
+ const waitingCount = pendingAsks.length;
+
+ return (
+ <StyledGate>
+ {waitingCount > 1 && (
+ <StyledWaitingCount>
+ {t`${waitingCount} requests are waiting on you`}
+ </StyledWaitingCount>
+ )}
+ <AiChatAskCard key={currentAsk.id} pendingAsk={currentAsk} />
+ </StyledGate>
+ );
+};
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatQuestionCard.tsx b/packages/twenty-front/src/modules/ai/components/AiChatQuestionCard.tsx
index a5c6f82a3c9..33a206b8e65 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatQuestionCard.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatQuestionCard.tsx
@@ -1,7 +1,11 @@
import { styled } from '@linaria/react';
import { useLingui } from '@lingui/react/macro';
-import { type KeyboardEvent, useMemo, useState } from 'react';
-import { type AskQuestionAnswer, type AskQuestionItem } from 'twenty-shared/ai';
+import { type KeyboardEvent, useState } from 'react';
+import {
+ type AskQuestionAnswer,
+ type AskQuestionItem,
+ type AskQuestionsToolResult,
+} from 'twenty-shared/ai';
import { isDefined } from 'twenty-shared/utils';
import { IconButton, LightIconButton } from 'twenty-ui/components';
import {
@@ -23,12 +27,12 @@ import {
import { Tooltip } from 'twenty-ui/primitives/surfaces';
import { useTheme, themeCssVariables } from 'twenty-ui/theme';
+import { StyledAiChatAskCard } from '@/ai/components/AiChatAskStyledComponents';
import { AiModelTierDropdown } from '@/ai/components/AiModelTierDropdown';
import { TextWithChatReferences } from '@/ai/components/TextWithChatReferences';
-import { AgentChatFileUploadButton } from '@/ai/components/internal/AgentChatFileUploadButton';
import { AiChatContextUsageButton } from '@/ai/components/internal/AiChatContextUsageButton';
import { AiChatQuestionOtherOption } from '@/ai/components/internal/AiChatQuestionOtherOption';
-import { useSubmitQuestionAnswer } from '@/ai/hooks/useSubmitQuestionAnswer';
+import { useAnswerAgentChatAsk } from '@/ai/hooks/useAnswerAgentChatAsk';
import { type AgentChatPendingQuestion } from '@/ai/types/AgentChatPendingQuestion';
import { aiModelsState } from '@/client-config/states/aiModelsState';
import { TooltipDelay } from '@/ui/layout/tooltip/constants/TooltipDelay';
@@ -46,16 +50,6 @@ const NUMBER_ICONS: IconComponent[] = [
IconSquareNumber9,
];
-const StyledCard = styled.div`
- background-color: ${themeCssVariables.background.transparent.lighter};
- border: 1px solid ${themeCssVariables.border.color.medium};
- border-radius: ${themeCssVariables.border.radius.sm};
- box-sizing: border-box;
- display: flex;
- flex-direction: column;
- width: 100%;
-`;
-
const StyledQuestionSection = styled.div`
display: flex;
flex-direction: column;
@@ -203,7 +197,7 @@ export const AiChatQuestionCard = ({
}: AiChatQuestionCardProps) => {
const { t } = useLingui();
const theme = useTheme();
- const { messageId, toolCallId, questions } = pendingQuestion;
+ const { askId, toolCallId, questions } = pendingQuestion;
const [currentIndex, setCurrentIndex] = useState(0);
const [selectedByQuestion, setSelectedByQuestion] = useState<
@@ -217,7 +211,7 @@ export const AiChatQuestionCard = ({
>({});
const [isSubmitting, setIsSubmitting] = useState(false);
- const { submitAnswer } = useSubmitQuestionAnswer();
+ const { answerAgentChatAsk } = useAnswerAgentChatAsk();
const aiModels = useAtomStateValue(aiModelsState);
const hasNoEnabledModels = aiModels.length === 0;
@@ -248,8 +242,25 @@ export const AiChatQuestionCard = ({
}
setIsSubmitting(true);
- await submitAnswer({ messageId, toolCallId, answers });
- setIsSubmitting(false);
+
+ const isAnswered = await answerAgentChatAsk({
+ askId,
+ toolCallId,
+ response: { answers },
+ optimisticToolOutput: {
+ success: true,
+ result: {
+ questions,
+ status: 'answered',
+ answers,
+ } satisfies AskQuestionsToolResult,
+ },
+ });
+
+ // The card goes once its Ask does, so it stays disabled until then.
+ if (!isAnswered) {
+ setIsSubmitting(false);
+ }
};
const handleSelectOption = (optionIndex: number) => {
@@ -337,20 +348,11 @@ export const AiChatQuestionCard = ({
}
};
- const allQuestionsAnswered = useMemo(
- () =>
- areAllQuestionsAnswered(
- questions,
- selectedByQuestion,
- freeTextByQuestion,
- otherSelectedByQuestion,
- ),
- [
- questions,
- selectedByQuestion,
- freeTextByQuestion,
- otherSelectedByQuestion,
- ],
+ const allQuestionsAnswered = areAllQuestionsAnswered(
+ questions,
+ selectedByQuestion,
+ freeTextByQuestion,
+ otherSelectedByQuestion,
);
const handleSend = () => {
@@ -376,7 +378,7 @@ export const AiChatQuestionCard = ({
};
return (
- <StyledCard>
+ <StyledAiChatAskCard>
<StyledQuestionSection>
<StyledQuestionHeaderRow>
<StyledQuestionText>
@@ -500,7 +502,6 @@ export const AiChatQuestionCard = ({
<StyledComposerSection>
<StyledActionsRow>
<StyledLeftActions>
- <AgentChatFileUploadButton />
<AiChatContextUsageButton />
</StyledLeftActions>
<StyledRightActions>
@@ -522,6 +523,6 @@ export const AiChatQuestionCard = ({
</StyledRightActions>
</StyledActionsRow>
</StyledComposerSection>
- </StyledCard>
+ </StyledAiChatAskCard>
);
};
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatQuestionStatusRenderer.tsx b/packages/twenty-front/src/modules/ai/components/AiChatQuestionStatusRenderer.tsx
index 778cec62f4c..82e2c3634ae 100644
--- a/packages/twenty-front/src/modules/ai/components/AiChatQuestionStatusRenderer.tsx
+++ b/packages/twenty-front/src/modules/ai/components/AiChatQuestionStatusRenderer.tsx
@@ -6,27 +6,12 @@ import { type AskQuestionsToolResult } from 'twenty-shared/ai';
import { IconHelpCircle } from 'twenty-ui/icon';
import { useTheme, themeCssVariables } from 'twenty-ui/theme';
+import {
+ StyledAiChatAskStatusContainer,
+ StyledAiChatAskStatusMessage,
+} from '@/ai/components/AiChatAskStyledComponents';
import { ShimmeringText } from '@/ai/components/ShimmeringText';
-const StyledContainer = styled.div`
- align-items: flex-start;
- color: ${themeCssVariables.font.color.tertiary};
- display: flex;
- gap: ${themeCssVariables.spacing[1]};
- padding: ${themeCssVariables.spacing[1]} 0;
-
- svg {
- flex-shrink: 0;
- margin-top: 1px;
- }
-`;
-
-const StyledMessage = styled.span`
- color: ${themeCssVariables.font.color.tertiary};
- font-size: ${themeCssVariables.font.size.md};
- font-weight: ${themeCssVariables.font.weight.medium};
-`;
-
const StyledAnswersCard = styled.div`
background-color: ${themeCssVariables.background.transparent.lighter};
border: 1px solid ${themeCssVariables.border.color.medium};
@@ -76,16 +61,16 @@ export const AiChatQuestionStatusRenderer = ({
const label = t`Asking questions...`;
return (
- <StyledContainer>
+ <StyledAiChatAskStatusContainer>
<IconHelpCircle size={theme.icon.size.sm} />
{isStreaming ? (
<ShimmeringText>
- <StyledMessage>{label}</StyledMessage>
+ <StyledAiChatAskStatusMessage>{label}</StyledAiChatAskStatusMessage>
</ShimmeringText>
) : (
- <StyledMessage>{label}</StyledMessage>
+ <StyledAiChatAskStatusMessage>{label}</StyledAiChatAskStatusMessage>
)}
- </StyledContainer>
+ </StyledAiChatAskStatusContainer>
);
}
@@ -93,7 +78,7 @@ export const AiChatQuestionStatusRenderer = ({
return (
<StyledAnswersCard>
- <StyledMessage>{t`Answers`}</StyledMessage>
+ <StyledAiChatAskStatusMessage>{t`Answers`}</StyledAiChatAskStatusMessage>
{questions.map((question, index) => {
const answer = answers.find(
(candidate) => candidate.questionIndex === index,
diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatQuestionCard.stories.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatQuestionCard.stories.tsx
index fa1007c5de2..95a2631df08 100644
--- a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatQuestionCard.stories.tsx
+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatQuestionCard.stories.tsx
@@ -23,7 +23,7 @@ const StyledContainer = styled.div`
const INSTANCE_ID = 'agentChatQuestionCardStory';
const singleQuestion: AgentChatPendingQuestion = {
- messageId: 'assistant-1',
+ askId: 'ask-1',
toolCallId: 'call-1',
questions: [
{
@@ -43,7 +43,7 @@ const singleQuestion: AgentChatPendingQuestion = {
};
const multipleQuestions: AgentChatPendingQuestion = {
- messageId: 'assistant-1',
+ askId: 'ask-2',
toolCallId: 'call-2',
questions: [
singleQuestion.questions[0],
@@ -59,7 +59,7 @@ const multipleQuestions: AgentChatPendingQuestion = {
};
const longQuestion: AgentChatPendingQuestion = {
- messageId: 'assistant-1',
+ askId: 'ask-3',
toolCallId: 'call-3',
questions: [
{
@@ -78,7 +78,7 @@ const longQuestion: AgentChatPendingQuestion = {
};
const multiSelectQuestion: AgentChatPendingQuestion = {
- messageId: 'assistant-1',
+ askId: 'ask-4',
toolCallId: 'call-4',
questions: [
{
diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEditorSection.sharing.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEditorSection.sharing.test.tsx
index 3aa3639a9a3..26066315e99 100644
--- a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEditorSection.sharing.test.tsx
+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEditorSection.sharing.test.tsx
@@ -19,6 +19,11 @@ jest.mock('@/ai/hooks/useAiChatEditor', () => ({
jest.mock('@/ai/components/AiChatStandaloneError', () => ({
AiChatStandaloneError: () => null,
}));
+// The gate's Ask cards pull in the form filler's rich text editor, which
+// Jest cannot load; this suite is about the composer, not the gate.
+jest.mock('@/ai/components/AiChatPendingAskGate', () => ({
+ AiChatPendingAskGate: ({ children }: { children: ReactNode }) => children,
+}));
const Wrapper = ({ children }: { children: ReactNode }) => (
<JotaiProvider store={jotaiStore}>
<I18nProvider i18n={i18n}>{children}</I18nProvider>
diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEmailApprovalCard.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEmailApprovalCard.test.tsx
new file mode 100644
index 00000000000..39a4e1187db
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatEmailApprovalCard.test.tsx
@@ -0,0 +1,163 @@
+import { i18n } from '@lingui/core';
+import { I18nProvider } from '@lingui/react';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { createStore, Provider } from 'jotai';
+
+import { AiChatEmailApprovalCard } from '@/ai/components/AiChatEmailApprovalCard';
+
+const answerAgentChatAsk = jest.fn();
+jest.mock('@/ai/hooks/useAnswerAgentChatAsk', () => ({
+ useAnswerAgentChatAsk: () => ({ answerAgentChatAsk }),
+}));
+
+const EMAIL = {
+ recipients: { to: '[email protected]', cc: '[email protected]', bcc: '' },
+ subject: 'Your renewal',
+ body: 'Hi Tim,\nYour plan renews next week.',
+ connectedAccountId: 'connected-account-id',
+};
+
+const renderCard = () =>
+ render(
+ <I18nProvider i18n={i18n}>
+ <Provider store={createStore()}>
+ <AiChatEmailApprovalCard
+ askId="ask-1"
+ toolCallId="call-1"
+ email={EMAIL}
+ />
+ </Provider>
+ </I18nProvider>,
+ );
+
+describe('AiChatEmailApprovalCard', () => {
+ beforeEach(() => {
+ answerAgentChatAsk.mockReset();
+ });
+
+ it('sends the email as the person edited it', async () => {
+ const user = userEvent.setup();
+ answerAgentChatAsk.mockReturnValue(new Promise(() => {}));
+
+ renderCard();
+
+ const subject = screen.getByRole('textbox', { name: 'Subject' });
+ await user.clear(subject);
+ await user.type(subject, 'Renewal confirmed');
+ await user.click(screen.getByRole('button', { name: 'Send' }));
+
+ expect(answerAgentChatAsk).toHaveBeenCalledWith({
+ askId: 'ask-1',
+ toolCallId: 'call-1',
+ response: {
+ decision: 'send',
+ email: { ...EMAIL, subject: 'Renewal confirmed' },
+ },
+ optimisticToolOutput: undefined,
+ });
+ // Nothing else can be decided while the answer is on its way.
+ expect(
+ screen.getByRole('button', { name: 'Save as draft' }),
+ ).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'Discard' })).toBeDisabled();
+ });
+
+ it('saves a draft to the recipients the person chose', async () => {
+ const user = userEvent.setup();
+ answerAgentChatAsk.mockResolvedValue(true);
+
+ renderCard();
+
+ await user.click(
+ screen.getByRole('button', { name: 'Remove [email protected]' }),
+ );
+ await user.type(
+ screen.getByRole('textbox', { name: 'Add a recipient to To' }),
+ 'Phil Schiller <[email protected]>{Enter}',
+ );
+ await user.click(screen.getByRole('button', { name: 'Save as draft' }));
+
+ expect(answerAgentChatAsk).toHaveBeenCalledWith(
+ expect.objectContaining({
+ response: {
+ decision: 'saveDraft',
+ email: {
+ ...EMAIL,
+ recipients: {
+ bcc: '',
+ },
+ },
+ },
+ }),
+ );
+ });
+
+ it('lets the person add a Bcc the draft did not have', async () => {
+ const user = userEvent.setup();
+
+ renderCard();
+
+ expect(
+ screen.queryByRole('textbox', { name: 'Add a recipient to Bcc' }),
+ ).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Cc' })).toBeNull();
+
+ await user.click(screen.getByRole('button', { name: 'Bcc' }));
+
+ expect(
+ screen.getByRole('textbox', { name: 'Add a recipient to Bcc' }),
+ ).toBeVisible();
+ expect(screen.queryByRole('button', { name: 'Bcc' })).toBeNull();
+ });
+
+ it('cannot send once every recipient is removed', async () => {
+ const user = userEvent.setup();
+
+ renderCard();
+
+ await user.click(
+ screen.getByRole('button', { name: 'Remove [email protected]' }),
+ );
+
+ expect(screen.getByRole('button', { name: 'Send' })).toBeDisabled();
+ expect(
+ screen.getByRole('button', { name: 'Save as draft' }),
+ ).not.toBeDisabled();
+ });
+
+ it('discards the email without sending it, and shows it discarded right away', async () => {
+ const user = userEvent.setup();
+ answerAgentChatAsk.mockResolvedValue(true);
+
+ renderCard();
+
+ await user.click(screen.getByRole('button', { name: 'Discard' }));
+
+ expect(answerAgentChatAsk).toHaveBeenCalledWith({
+ askId: 'ask-1',
+ toolCallId: 'call-1',
+ response: { decision: 'discard' },
+ optimisticToolOutput: {
+ success: true,
+ result: { status: 'discarded', email: EMAIL },
+ },
+ });
+ });
+
+ it('lets the person decide again when the answer is refused', async () => {
+ const user = userEvent.setup();
+ answerAgentChatAsk.mockResolvedValue(false);
+
+ renderCard();
+
+ await user.click(screen.getByRole('button', { name: 'Send' }));
+
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: 'Send' })).not.toBeDisabled(),
+ );
+ expect(screen.getByRole('button', { name: 'Discard' })).not.toBeDisabled();
+ });
+});
diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPendingAskGate.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPendingAskGate.test.tsx
new file mode 100644
index 00000000000..25b9af73ea2
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPendingAskGate.test.tsx
@@ -0,0 +1,125 @@
+import { i18n } from '@lingui/core';
+import { I18nProvider } from '@lingui/react';
+import { render, screen } from '@testing-library/react';
+import { type AskQuestionItem, type ProposedEmail } from 'twenty-shared/ai';
+
+import { AiChatPendingAskGate } from '@/ai/components/AiChatPendingAskGate';
+import { type AgentChatPendingQuestion } from '@/ai/types/AgentChatPendingQuestion';
+
+const useAgentChatPendingAsks = jest.fn();
+jest.mock('@/ai/hooks/useAgentChatPendingAsks', () => ({
+ useAgentChatPendingAsks: (args: { threadId: string }) =>
+ useAgentChatPendingAsks(args),
+}));
+jest.mock('@/ai/components/AiChatQuestionCard', () => ({
+ AiChatQuestionCard: ({
+ pendingQuestion,
+ }: {
+ pendingQuestion: AgentChatPendingQuestion;
+ }) => (
+ <div role="group" aria-label="Questions">
+ {pendingQuestion.questions[0].question}
+ </div>
+ ),
+}));
+jest.mock('@/ai/components/AiChatEmailApprovalCard', () => ({
+ AiChatEmailApprovalCard: ({ email }: { email: ProposedEmail }) => (
+ <div role="group" aria-label="Email approval">
+ {email.subject}
+ </div>
+ ),
+}));
+
+const QUESTIONS: AskQuestionItem[] = [
+ {
+ header: 'Plan',
+ question: 'Which plan?',
+ options: [{ label: 'Pro' }, { label: 'Team' }],
+ },
+];
+
+const EMAIL_ASK = {
+ id: 'ask-2',
+ toolCallId: 'call-2',
+ form: {
+ kind: 'emailApproval',
+ email: {
+ recipients: { to: '[email protected]', cc: '', bcc: '' },
+ subject: 'Your renewal',
+ body: 'Hi Tim',
+ },
+ },
+};
+
+const renderGate = () =>
+ render(
+ <I18nProvider i18n={i18n}>
+ <AiChatPendingAskGate threadId="thread-id">
+ <textarea aria-label="Message" />
+ </AiChatPendingAskGate>
+ </I18nProvider>,
+ );
+
+describe('AiChatPendingAskGate', () => {
+ it('shows the questions the thread waits on in place of the composer', () => {
+ useAgentChatPendingAsks.mockReturnValue([
+ {
+ id: 'ask-1',
+ toolCallId: 'call-1',
+ form: { kind: 'questions', questions: QUESTIONS },
+ },
+ ]);
+
+ renderGate();
+
+ expect(useAgentChatPendingAsks).toHaveBeenCalledWith({
+ threadId: 'thread-id',
+ });
+ expect(screen.getByRole('group', { name: 'Questions' })).toHaveTextContent(
+ 'Which plan?',
+ );
+ expect(screen.queryByRole('textbox', { name: 'Message' })).toBeNull();
+ });
+
+ it('shows an email waiting for approval in place of the composer', () => {
+ useAgentChatPendingAsks.mockReturnValue([EMAIL_ASK]);
+
+ renderGate();
+
+ expect(
+ screen.getByRole('group', { name: 'Email approval' }),
+ ).toHaveTextContent('Your renewal');
+ expect(screen.queryByRole('textbox', { name: 'Message' })).toBeNull();
+ });
+
+ it('shows the oldest of several requests first and says how many wait', () => {
+ useAgentChatPendingAsks.mockReturnValue([
+ EMAIL_ASK,
+ {
+ id: 'ask-3',
+ toolCallId: 'call-3',
+ form: { kind: 'questions', questions: QUESTIONS },
+ },
+ ]);
+
+ renderGate();
+
+ expect(
+ screen.getByRole('group', { name: 'Email approval' }),
+ ).toHaveTextContent('Your renewal');
+ expect(screen.queryByRole('group', { name: 'Questions' })).toBeNull();
+ expect(
+ screen.getByText('2 requests are waiting on you'),
+ ).toBeInTheDocument();
+ expect(screen.queryByRole('textbox', { name: 'Message' })).toBeNull();
+ });
+
+ it('shows the composer once nothing is pending', () => {
+ useAgentChatPendingAsks.mockReturnValue([]);
+
+ renderGate();
+
+ expect(screen.getByRole('textbox', { name: 'Message' })).toBeVisible();
+ expect(screen.queryByRole('group')).toBeNull();
+ });
+});
diff --git a/packages/twenty-front/src/modules/ai/components/internal/AgentChatFileUploadButton.tsx b/packages/twenty-front/src/modules/ai/components/internal/AgentChatFileUploadButton.tsx
deleted file mode 100644
index a2bdb5eb60d..00000000000
--- a/packages/twenty-front/src/modules/ai/components/internal/AgentChatFileUploadButton.tsx
+++ /dev/null
@@ -1,34 +0,0 @@
-import { AgentChatFileInput } from '@/ai/components/internal/AgentChatFileInput';
-import { styled } from '@linaria/react';
-import { t } from '@lingui/core/macro';
-import { useRef } from 'react';
-import { IconPaperclip } from 'twenty-ui/icon';
-import { IconButton } from 'twenty-ui/components';
-import { themeCssVariables } from 'twenty-ui/theme';
-
-const StyledFileUploadContainer = styled.div`
- display: flex;
- flex-direction: column;
- gap: ${themeCssVariables.spacing[2]};
-`;
-
-export const AgentChatFileUploadButton = () => {
- const fileInputRef = useRef<HTMLInputElement>(null);
-
- return (
- <StyledFileUploadContainer>
- <AgentChatFileInput ref={fileInputRef} />
-
- <IconButton
- variant="ghost"
- size="sm"
- onClick={() => {
- fileInputRef.current?.click();
- }}
- aria-label={t`Attach files`}
- >
- <IconPaperclip />
- </IconButton>
- </StyledFileUploadContainer>
- );
-};
diff --git a/packages/twenty-front/src/modules/ai/components/internal/AiChatEmailRecipientsRow.tsx b/packages/twenty-front/src/modules/ai/components/internal/AiChatEmailRecipientsRow.tsx
new file mode 100644
index 00000000000..9caf664233b
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/internal/AiChatEmailRecipientsRow.tsx
@@ -0,0 +1,127 @@
+import { styled } from '@linaria/react';
+import { useLingui } from '@lingui/react/macro';
+import { type KeyboardEvent, useState } from 'react';
+import { LightIconButton } from 'twenty-ui/components';
+import { IconX } from 'twenty-ui/icon';
+import { Chip } from 'twenty-ui/primitives/data-display';
+import { themeCssVariables } from 'twenty-ui/theme';
+
+import { type EmailRecipient } from '@/activities/emails/recipients/types/EmailRecipient';
+import { parseEmailRecipients } from '@/activities/emails/recipients/utils/parseEmailRecipients';
+
+const StyledRow = styled.div`
+ align-items: center;
+ display: flex;
+ flex-wrap: wrap;
+ gap: ${themeCssVariables.spacing[1]};
+ min-height: 28px;
+`;
+
+const StyledRowLabel = styled.span`
+ color: ${themeCssVariables.font.color.tertiary};
+ font-size: ${themeCssVariables.font.size.sm};
+ width: 32px;
+`;
+
+const StyledInput = styled.input`
+ background: transparent;
+ border: none;
+ color: ${themeCssVariables.font.color.primary};
+ flex: 1 0 80px;
+ font-family: inherit;
+ font-size: ${themeCssVariables.font.size.sm};
+ min-width: 80px;
+ outline: none;
+
+ &::placeholder {
+ color: ${themeCssVariables.font.color.light};
+ }
+`;
+
+type AiChatEmailRecipientsRowProps = {
+ label: string;
+ recipients: EmailRecipient[];
+ disabled: boolean;
+ onChange: (recipients: EmailRecipient[]) => void;
+};
+
+export const AiChatEmailRecipientsRow = ({
+ label,
+ recipients,
+ disabled,
+ onChange,
+}: AiChatEmailRecipientsRowProps) => {
+ const { t } = useLingui();
+ const [draftRecipient, setDraftRecipient] = useState('');
+
+ const addDraftRecipients = () => {
+ const addedRecipients = parseEmailRecipients(draftRecipient).filter(
+ ({ address }) =>
+ !recipients.some((recipient) => recipient.address === address),
+ );
+
+ setDraftRecipient('');
+
+ if (addedRecipients.length > 0) {
+ onChange([...recipients, ...addedRecipients]);
+ }
+ };
+
+ const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
+ if (event.key === 'Enter' || event.key === ',') {
+ event.preventDefault();
+ addDraftRecipients();
+
+ return;
+ }
+
+ if (
+ event.key === 'Backspace' &&
+ draftRecipient.length === 0 &&
+ recipients.length > 0
+ ) {
+ onChange(recipients.slice(0, -1));
+ }
+ };
+
+ return (
+ <StyledRow>
+ <StyledRowLabel>{label}</StyledRowLabel>
+ {recipients.map(({ address }) => (
+ <Chip
+ key={address}
+ variant="soft"
+ endElement={
+ disabled ? undefined : (
+ <LightIconButton
+ size="sm"
+ aria-label={t`Remove ${address}`}
+ onClick={() =>
+ onChange(
+ recipients.filter(
+ (recipient) => recipient.address !== address,
+ ),
+ )
+ }
+ >
+ <IconX />
+ </LightIconButton>
+ )
+ }
+ >
+ {address}
+ </Chip>
+ ))}
+ {!disabled && (
+ <StyledInput
+ aria-label={t`Add a recipient to ${label}`}
+ placeholder={recipients.length === 0 ? t`Add recipient` : undefined}
+ value={draftRecipient}
+ onChange={(event) => setDraftRecipient(event.target.value)}
+ onKeyDown={handleKeyDown}
+ onBlur={addDraftRecipients}
+ />
+ )}
+ </StyledRow>
+ );
+};
diff --git a/packages/twenty-front/src/modules/ai/constants/PausingToolNames.ts b/packages/twenty-front/src/modules/ai/constants/PausingToolNames.ts
new file mode 100644
index 00000000000..f004051cd9c
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/constants/PausingToolNames.ts
@@ -0,0 +1,10 @@
+import {
+ ASK_QUESTIONS_TOOL_NAME,
+ PROPOSE_EMAIL_TOOL_NAME,
+} from 'twenty-shared/ai';
+
+// Tools whose call waits on a person, each rendered with its own status.
+export const PAUSING_TOOL_NAMES: ReadonlySet<string> = new Set([
+ ASK_QUESTIONS_TOOL_NAME,
+ PROPOSE_EMAIL_TOOL_NAME,
+]);
diff --git a/packages/twenty-front/src/modules/ai/graphql/mutations/answerAgentChatQuestion.ts b/packages/twenty-front/src/modules/ai/graphql/mutations/answerAgentChatQuestion.ts
deleted file mode 100644
index 22e01b16e41..00000000000
--- a/packages/twenty-front/src/modules/ai/graphql/mutations/answerAgentChatQuestion.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { gql } from '@apollo/client';
-
-export const ANSWER_AGENT_CHAT_QUESTION = gql`
- mutation AnswerAgentChatQuestion(
- $threadId: UUID!
- $messageId: UUID!
- $answers: [AgentChatQuestionAnswerInput!]!
- $modelId: String
- $fileAttachments: [FileAttachmentInput!]
- ) {
- answerAgentChatQuestion(
- threadId: $threadId
- messageId: $messageId
- answers: $answers
- modelId: $modelId
- fileAttachments: $fileAttachments
- ) {
- messageId
- queued
- streamId
- }
- }
-`;
diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChatSubscription.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChatSubscription.test.tsx
index 2a6dc7370b2..52f26a938ce 100644
--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChatSubscription.test.tsx
+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChatSubscription.test.tsx
@@ -2,6 +2,7 @@ import { act, renderHook, waitFor } from '@testing-library/react';
import { Provider as JotaiProvider } from 'jotai';
import { type ReactNode } from 'react';
+import { AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME } from '@/ai/constants/AgentChatRefetchMessagesEventName';
import { AgentChatComponentInstanceContext } from '@/ai/contexts/AgentChatComponentInstanceContext';
import { useAgentChatSubscription } from '@/ai/hooks/useAgentChatSubscription';
import { agentChatMessagesComponentFamilyState } from '@/ai/states/agentChatMessagesComponentFamilyState';
@@ -116,6 +117,33 @@ describe('Shared conversation access revocation', () => {
},
);
+ it('refetches the conversation when one of its tool calls is resolved', () => {
+ const refetchListener = jest.fn();
+ window.addEventListener(
+ AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME,
+ refetchListener,
+ );
+ const { unmount } = renderHook(() => useAgentChatSubscription('thread'), {
+ wrapper: Wrapper,
+ });
+ act(() =>
+ subscribe.mock.calls[0][1].next({
+ data: {
+ onAgentChatEvent: {
+ threadId: 'thread',
+ event: { type: 'tool-call-resolved', toolCallId: 'call-1' },
+ },
+ },
+ }),
+ );
+ expect(refetchListener).toHaveBeenCalledTimes(1);
+ unmount();
+ window.removeEventListener(
+ AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME,
+ refetchListener,
+ );
+ });
+
it('clears content and disconnects when the AI permission guard denies access', () => {
renderHook(() => useAgentChatSubscription('thread'), { wrapper: Wrapper });
act(() =>
diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useAnswerAgentChatAsk.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useAnswerAgentChatAsk.test.tsx
new file mode 100644
index 00000000000..6ba392bd3d0
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useAnswerAgentChatAsk.test.tsx
@@ -0,0 +1,159 @@
+import { CombinedGraphQLErrors } from '@apollo/client/errors';
+import { act, renderHook } from '@testing-library/react';
+import { Provider as JotaiProvider } from 'jotai';
+import { type ReactNode } from 'react';
+import { type ExtendedUIMessage } from 'twenty-shared/ai';
+
+import { AGENT_CHAT_INSTANCE_ID } from '@/ai/constants/AgentChatInstanceId';
+import { AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME } from '@/ai/constants/AgentChatRefetchMessagesEventName';
+import { useAnswerAgentChatAsk } from '@/ai/hooks/useAnswerAgentChatAsk';
+import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';
+import { agentChatIsAwaitingFirstChunkComponentFamilyState } from '@/ai/states/agentChatIsAwaitingFirstChunkComponentFamilyState';
+import { agentChatMessagesComponentFamilyState } from '@/ai/states/agentChatMessagesComponentFamilyState';
+import {
+ jotaiStore,
+ resetJotaiStore,
+} from '@/ui/utilities/state/jotai/jotaiStore';
+
+const mutate = jest.fn();
+jest.mock('@/object-metadata/hooks/useApolloCoreClient', () => ({
+ useApolloCoreClient: () => ({ mutate }),
+}));
+const enqueueToast = jest.fn();
+jest.mock('twenty-ui/components', () => ({
+ useToast: () => ({ enqueueToast }),
+}));
+jest.mock('@/ai/hooks/useAgentChatModelId', () => ({
+ useAgentChatModelId: () => ({ modelIdForRequest: 'model-id' }),
+}));
+
+const key = {
+ instanceId: AGENT_CHAT_INSTANCE_ID,
+ familyKey: { threadId: 'thread-id' },
+};
+const messagesAtom = agentChatMessagesComponentFamilyState.atomFamily(key);
+const isAwaitingFirstChunkAtom =
+ agentChatIsAwaitingFirstChunkComponentFamilyState.atomFamily(key);
+
+const PENDING_OUTPUT = { result: { questions: [], status: 'pending' } };
+const ANSWERED_OUTPUT = { result: { questions: [], status: 'answered' } };
+
+const readToolOutput = () =>
+ (
+ jotaiStore.get(messagesAtom)[0].parts[0] as unknown as {
+ output: unknown;
+ }
+ ).output;
+
+const Wrapper = ({ children }: { children: ReactNode }) => (
+ <JotaiProvider store={jotaiStore}>{children}</JotaiProvider>
+);
+
+const renderAnswerAgentChatAsk = () =>
+ renderHook(() => useAnswerAgentChatAsk(), { wrapper: Wrapper }).result.current
+ .answerAgentChatAsk;
+
+const answer = async () => {
+ const answerAgentChatAsk = renderAnswerAgentChatAsk();
+ let isAnswered = false;
+
+ await act(async () => {
+ isAnswered = await answerAgentChatAsk({
+ askId: 'ask-1',
+ toolCallId: 'call-1',
+ response: { answers: [] },
+ optimisticToolOutput: ANSWERED_OUTPUT,
+ });
+ });
+
+ return isAnswered;
+};
+
+describe('useAnswerAgentChatAsk', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ resetJotaiStore();
+ jotaiStore.set(agentChatDisplayedThreadState.atom, 'thread-id');
+ jotaiStore.set(messagesAtom, [
+ {
+ id: 'assistant-1',
+ role: 'assistant',
+ parts: [
+ {
+ type: 'tool-ask_questions',
+ toolCallId: 'call-1',
+ state: 'output-available',
+ input: { questions: [] },
+ output: PENDING_OUTPUT,
+ },
+ ],
+ },
+ ] as unknown as ExtendedUIMessage[]);
+ });
+
+ it('answers the Ask and shows the answer in its tool call right away', async () => {
+ mutate.mockResolvedValue({ data: { answerAsk: { streamId: 's' } } });
+
+ expect(await answer()).toBe(true);
+ expect(mutate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ variables: {
+ input: {
+ askId: 'ask-1',
+ response: { answers: [] },
+ modelId: 'model-id',
+ },
+ },
+ }),
+ );
+ expect(readToolOutput()).toEqual(ANSWERED_OUTPUT);
+ expect(jotaiStore.get(isAwaitingFirstChunkAtom)).toBe(true);
+ });
+
+ it('expects no stream when the answer resumes a workflow run', async () => {
+ mutate.mockResolvedValue({
+ data: { answerAsk: { streamId: null } },
+ });
+
+ await answer();
+
+ expect(jotaiStore.get(isAwaitingFirstChunkAtom)).toBe(false);
+ });
+
+ it('puts the tool call back as it was when the answer is refused', async () => {
+ mutate.mockRejectedValue(new Error('Network down'));
+
+ expect(await answer()).toBe(false);
+ expect(readToolOutput()).toEqual(PENDING_OUTPUT);
+ expect(jotaiStore.get(isAwaitingFirstChunkAtom)).toBe(false);
+ expect(enqueueToast).toHaveBeenCalled();
+ });
+
+ it('refetches the conversation instead when the Ask was already answered elsewhere', async () => {
+ const refetchListener = jest.fn();
+ window.addEventListener(
+ AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME,
+ refetchListener,
+ );
+ mutate.mockRejectedValue(
+ new CombinedGraphQLErrors({
+ data: null,
+ errors: [
+ {
+ message: 'No longer waiting',
+ extensions: { code: 'ASK_NOT_PENDING' },
+ },
+ ],
+ }),
+ );
+
+ expect(await answer()).toBe(false);
+ expect(refetchListener).toHaveBeenCalledTimes(1);
+ expect(readToolOutput()).toEqual(ANSWERED_OUTPUT);
+
+ window.removeEventListener(
+ AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME,
+ refetchListener,
+ );
+ });
+});
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAgentChatPendingAsks.ts b/packages/twenty-front/src/modules/ai/hooks/useAgentChatPendingAsks.ts
new file mode 100644
index 00000000000..767b9438875
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/hooks/useAgentChatPendingAsks.ts
@@ -0,0 +1,88 @@
+import { useCallback, useMemo } from 'react';
+import {
+ CoreObjectNameSingular,
+ type RecordGqlOperationOrderBy,
+} from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type AgentChatPendingAsk } from '@/ai/types/AgentChatPendingAsk';
+import { useListenToObjectRecordOperationBrowserEvent } from '@/browser-event/hooks/useListenToObjectRecordOperationBrowserEvent';
+import { parseInputAskForm } from '@/input-ask/utils/parseInputAskForm';
+import { useObjectMetadataItem } from '@/object-metadata/hooks/useObjectMetadataItem';
+import { useFindManyRecords } from '@/object-record/hooks/useFindManyRecords';
+import { type ObjectRecord } from '@/object-record/types/ObjectRecord';
+import { useListenToEventsForQuery } from '@/sse-db-event/hooks/useListenToEventsForQuery';
+
+const ORDER_BY_CREATION: RecordGqlOperationOrderBy = [
+ { createdAt: 'AscNullsLast' },
+];
+
+type PendingInputAskRecord = ObjectRecord & {
+ toolCallId: string | null;
+ form: unknown;
+};
+
+// The Asks are the record of what the conversation waits on, so the cards
+// are read from them rather than from the last message, and follow them live.
+// A step that paused on several calls waits on one Ask each, oldest first.
+export const useAgentChatPendingAsks = ({
+ threadId,
+}: {
+ threadId: string;
+}): AgentChatPendingAsk[] => {
+ const { objectMetadataItem: inputAskObjectMetadataItem } =
+ useObjectMetadataItem({
+ objectNameSingular: CoreObjectNameSingular.InputAsk,
+ });
+
+ const filter = useMemo(
+ () => ({
+ threadId: { eq: threadId },
+ status: { in: ['PENDING'] },
+ }),
+ [threadId],
+ );
+
+ const { records, refetch } = useFindManyRecords<PendingInputAskRecord>({
+ objectNameSingular: CoreObjectNameSingular.InputAsk,
+ filter,
+ orderBy: ORDER_BY_CREATION,
+ recordGqlFields: { id: true, toolCallId: true, form: true },
+ fetchPolicy: 'network-only',
+ });
+
+ const refetchPendingInputAsks = useCallback(async () => {
+ await refetch();
+ }, [refetch]);
+
+ const operationSignature = useMemo(
+ () => ({
+ objectNameSingular: CoreObjectNameSingular.InputAsk,
+ variables: { filter },
+ }),
+ [filter],
+ );
+
+ useListenToEventsForQuery({
+ queryId: `agent-chat-pending-input-ask-${threadId}`,
+ operationSignature,
+ onSseReconnected: refetchPendingInputAsks,
+ });
+
+ useListenToObjectRecordOperationBrowserEvent({
+ onObjectRecordOperationBrowserEvent: refetchPendingInputAsks,
+ objectMetadataItemId: inputAskObjectMetadataItem.id,
+ });
+
+ return useMemo(
+ () =>
+ records.flatMap((record) => {
+ const form = parseInputAskForm(record.form);
+
+ return isDefined(record.toolCallId) && isDefined(form)
+ ? [{ id: record.id, toolCallId: record.toolCallId, form }]
+ : [];
+ }),
+ [records],
+ );
+};
diff --git a/packages/twenty-front/src/modules/ai/hooks/useAgentChatSubscription.ts b/packages/twenty-front/src/modules/ai/hooks/useAgentChatSubscription.ts
index b0f4a3a7514..b84b6838f62 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useAgentChatSubscription.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAgentChatSubscription.ts
@@ -382,7 +382,7 @@ export const useAgentChatSubscription = (threadId: string | null) => {
break;
}
- case 'question-answered': {
+ case 'tool-call-resolved': {
dispatchBrowserEvent(AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME);
break;
}
diff --git a/packages/twenty-front/src/modules/ai/hooks/useSubmitQuestionAnswer.ts b/packages/twenty-front/src/modules/ai/hooks/useAnswerAgentChatAsk.ts
similarity index 53%
rename from packages/twenty-front/src/modules/ai/hooks/useSubmitQuestionAnswer.ts
rename to packages/twenty-front/src/modules/ai/hooks/useAnswerAgentChatAsk.ts
index 8c0d5c483de..1f9cb7d6dff 100644
--- a/packages/twenty-front/src/modules/ai/hooks/useSubmitQuestionAnswer.ts
+++ b/packages/twenty-front/src/modules/ai/hooks/useAnswerAgentChatAsk.ts
@@ -1,66 +1,51 @@
import { CombinedGraphQLErrors } from '@apollo/client/errors';
-import { useApolloClient } from '@apollo/client/react';
-import { t } from '@lingui/core/macro';
import { useStore } from 'jotai';
import { useCallback } from 'react';
-import { type AskQuestionAnswer } from 'twenty-shared/ai';
-import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+import { isDefined } from 'twenty-shared/utils';
import { AGENT_CHAT_INSTANCE_ID } from '@/ai/constants/AgentChatInstanceId';
import { AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME } from '@/ai/constants/AgentChatRefetchMessagesEventName';
-import { ANSWER_AGENT_CHAT_QUESTION } from '@/ai/graphql/mutations/answerAgentChatQuestion';
import { useAgentChatModelId } from '@/ai/hooks/useAgentChatModelId';
import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';
import { agentChatErrorComponentFamilyState } from '@/ai/states/agentChatErrorComponentFamilyState';
import { agentChatIsAwaitingFirstChunkComponentFamilyState } from '@/ai/states/agentChatIsAwaitingFirstChunkComponentFamilyState';
import { agentChatMessagesComponentFamilyState } from '@/ai/states/agentChatMessagesComponentFamilyState';
-import { agentChatSelectedFilesState } from '@/ai/states/agentChatSelectedFilesState';
-import { agentChatUploadedFilesState } from '@/ai/states/agentChatUploadedFilesState';
import { AiChatErrorCode } from '@/ai/utils/aiChatErrorCode';
+import { findToolPartOutput } from '@/ai/utils/findToolPartOutput';
import { isAiChatCreditsExhaustedError } from '@/ai/utils/isAiChatCreditsExhaustedError';
-import { markQuestionAnswered } from '@/ai/utils/markQuestionAnswered';
-import { markQuestionPending } from '@/ai/utils/markQuestionPending';
+import { updateToolPartOutput } from '@/ai/utils/updateToolPartOutput';
import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
import { dispatchBrowserEvent } from '@/browser-event/utils/dispatchBrowserEvent';
import { getToastOptionsFromError } from '@/error-handler/utils/getToastOptionsFromError';
+import { useAnswerAsk } from '@/input-ask/hooks/useAnswerAsk';
import { markWorkspaceCreditsExhausted } from '@/workspace/utils/updateWorkspaceResourceCreditCap';
import { useToast } from 'twenty-ui/components';
-import { type AnswerAgentChatQuestionMutation } from '~/generated-metadata/graphql';
import { isGraphqlErrorOfType } from '~/utils/is-graphql-error-of-type.util';
-export const useSubmitQuestionAnswer = () => {
- const apolloClient = useApolloClient();
+export const useAnswerAgentChatAsk = () => {
+ const { answerAsk } = useAnswerAsk();
const store = useStore();
const { enqueueToast } = useToast();
const { modelIdForRequest } = useAgentChatModelId();
- const submitAnswer = useCallback(
+ // Returns whether the Ask was answered, so a card can keep itself disabled
+ // until the Ask is gone rather than invite a second answer.
+ const answerAgentChatAsk = useCallback(
async ({
- messageId,
+ askId,
toolCallId,
- answers,
+ response,
+ optimisticToolOutput,
}: {
- messageId: string;
+ askId: string;
toolCallId: string;
- answers: AskQuestionAnswer[];
- }) => {
+ response: Record<string, unknown>;
+ optimisticToolOutput?: unknown;
+ }): Promise<boolean> => {
const threadId = store.get(agentChatDisplayedThreadState.atom);
if (!isDefined(threadId)) {
- return;
- }
-
- const agentChatSelectedFiles = store.get(
- agentChatSelectedFilesState.atom,
- );
-
- if (isNonEmptyArray(agentChatSelectedFiles)) {
- enqueueToast({
- variant: 'info',
- children: t`Wait for files to finish uploading before answering.`,
- });
-
- return;
+ return false;
}
const messagesAtom = agentChatMessagesComponentFamilyState.atomFamily({
@@ -76,49 +61,42 @@ export const useSubmitQuestionAnswer = () => {
instanceId: AGENT_CHAT_INSTANCE_ID,
familyKey: { threadId },
});
- const previousMessages = store.get(messagesAtom);
-
- const uploadedFiles = store.get(agentChatUploadedFilesState.atom);
- const fileAttachments = uploadedFiles.map((file) => ({
- id: file.fileId,
- filename: file.filename,
- }));
-
- store.set(
- messagesAtom,
- markQuestionAnswered(previousMessages, messageId, toolCallId, answers),
- );
+
+ const previousToolOutput = findToolPartOutput({
+ messages: store.get(messagesAtom),
+ toolCallId,
+ });
+
+ if (isDefined(optimisticToolOutput)) {
+ store.set(messagesAtom, (messages) =>
+ updateToolPartOutput({
+ messages,
+ toolCallId,
+ output: optimisticToolOutput,
+ }),
+ );
+ }
+
store.set(isAwaitingFirstChunkAtom, true);
- store.set(agentChatUploadedFilesState.atom, []);
try {
- const { data } =
- await apolloClient.mutate<AnswerAgentChatQuestionMutation>({
- mutation: ANSWER_AGENT_CHAT_QUESTION,
- variables: {
- threadId,
- messageId,
- answers,
- modelId: modelIdForRequest,
- fileAttachments: isNonEmptyArray(fileAttachments)
- ? fileAttachments
- : undefined,
- },
- });
-
- // A workflow agent's answer resumes its run, not a chat stream, so
- // no first chunk will arrive.
- if (!isDefined(data?.answerAgentChatQuestion.streamId)) {
+ const { streamId } = await answerAsk({
+ askId,
+ response,
+ modelId: modelIdForRequest,
+ });
+
+ // No chunk follows when a workflow run resumes in its own executor,
+ // or when other calls of the same step still wait on their answers.
+ if (!isDefined(streamId)) {
store.set(isAwaitingFirstChunkAtom, false);
}
dispatchBrowserEvent(AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME);
+
+ return true;
} catch (error) {
store.set(isAwaitingFirstChunkAtom, false);
- store.set(agentChatUploadedFilesState.atom, (currentUploadedFiles) => [
- ...uploadedFiles,
- ...currentUploadedFiles,
- ]);
// The banner reads the workspace flag, then the thread error when no resource credit item carries that flag
if (isAiChatCreditsExhaustedError(error)) {
@@ -131,22 +109,25 @@ export const useSubmitQuestionAnswer = () => {
);
}
- if (isGraphqlErrorOfType(error, AiChatErrorCode.QUESTION_NOT_PENDING)) {
+ if (isGraphqlErrorOfType(error, AiChatErrorCode.ASK_NOT_PENDING)) {
dispatchBrowserEvent(AGENT_CHAT_REFETCH_MESSAGES_EVENT_NAME);
- } else {
- const currentMessages = store.get(messagesAtom);
-
- store.set(
- messagesAtom,
- markQuestionPending(currentMessages, messageId, toolCallId),
+ } else if (isDefined(optimisticToolOutput)) {
+ store.set(messagesAtom, (messages) =>
+ updateToolPartOutput({
+ messages,
+ toolCallId,
+ output: previousToolOutput,
+ }),
);
}
enqueueToast(getToastOptionsFromError({ error }));
+
+ return false;
}
},
- [apolloClient, store, enqueueToast, modelIdForRequest],
+ [answerAsk, store, enqueueToast, modelIdForRequest],
);
- return { submitAnswer };
+ return { answerAgentChatAsk };
};
diff --git a/packages/twenty-front/src/modules/ai/states/selectors/agentChatPendingQuestionComponentSelector.ts b/packages/twenty-front/src/modules/ai/states/selectors/agentChatPendingQuestionComponentSelector.ts
deleted file mode 100644
index faccac326fa..00000000000
--- a/packages/twenty-front/src/modules/ai/states/selectors/agentChatPendingQuestionComponentSelector.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { getToolName, isToolUIPart } from 'ai';
-import {
- ASK_QUESTIONS_TOOL_NAME,
- type AskQuestionsToolResult,
-} from 'twenty-shared/ai';
-
-import { AgentChatComponentInstanceContext } from '@/ai/contexts/AgentChatComponentInstanceContext';
-import { agentChatDisplayedThreadState } from '@/ai/states/agentChatDisplayedThreadState';
-import { agentChatMessagesComponentFamilyState } from '@/ai/states/agentChatMessagesComponentFamilyState';
-import { type AgentChatPendingQuestion } from '@/ai/types/AgentChatPendingQuestion';
-import { createAtomComponentSelector } from '@/ui/utilities/state/jotai/utils/createAtomComponentSelector';
-
-export const agentChatPendingQuestionComponentSelector =
- createAtomComponentSelector<AgentChatPendingQuestion | null>({
- key: 'agentChatPendingQuestionComponentSelector',
- componentInstanceContext: AgentChatComponentInstanceContext,
- get:
- ({ instanceId }) =>
- ({ get }) => {
- const currentThreadId = get(agentChatDisplayedThreadState);
-
- const messages = get(agentChatMessagesComponentFamilyState, {
- instanceId,
- familyKey: { threadId: currentThreadId },
- });
-
- const lastAssistantMessage = [...messages]
- .reverse()
- .find((message) => message.role === 'assistant');
-
- if (!lastAssistantMessage) {
- return null;
- }
-
- for (const part of lastAssistantMessage.parts) {
- if (
- !isToolUIPart(part) ||
- getToolName(part) !== ASK_QUESTIONS_TOOL_NAME
- ) {
- continue;
- }
-
- const result = (part.output as { result?: AskQuestionsToolResult })
- ?.result;
-
- if (result?.status === 'pending') {
- return {
- messageId: lastAssistantMessage.id,
- toolCallId: part.toolCallId,
- questions: result.questions,
- };
- }
- }
-
- return null;
- },
- });
diff --git a/packages/twenty-front/src/modules/ai/types/AgentChatPendingAsk.ts b/packages/twenty-front/src/modules/ai/types/AgentChatPendingAsk.ts
new file mode 100644
index 00000000000..c85c4deab71
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/types/AgentChatPendingAsk.ts
@@ -0,0 +1,8 @@
+import { type InputAskForm } from 'twenty-shared/ai';
+
+// A form step's Ask is answered from its run, never from a chat.
+export type AgentChatPendingAsk = {
+ id: string;
+ toolCallId: string;
+ form: Exclude<InputAskForm, { kind: 'formFields' }>;
+};
diff --git a/packages/twenty-front/src/modules/ai/types/AgentChatPendingQuestion.ts b/packages/twenty-front/src/modules/ai/types/AgentChatPendingQuestion.ts
index 9afde6d3c2b..8d0c07cba2e 100644
--- a/packages/twenty-front/src/modules/ai/types/AgentChatPendingQuestion.ts
+++ b/packages/twenty-front/src/modules/ai/types/AgentChatPendingQuestion.ts
@@ -1,7 +1,7 @@
import { type AskQuestionItem } from 'twenty-shared/ai';
export type AgentChatPendingQuestion = {
- messageId: string;
+ askId: string;
toolCallId: string;
questions: AskQuestionItem[];
};
diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/markQuestionAnswered.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/markQuestionAnswered.test.ts
deleted file mode 100644
index 6ac0a6a43e0..00000000000
--- a/packages/twenty-front/src/modules/ai/utils/__tests__/markQuestionAnswered.test.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import { type ExtendedUIMessage } from 'twenty-shared/ai';
-
-import { markQuestionAnswered } from '@/ai/utils/markQuestionAnswered';
-
-const buildMessages = (status: 'pending' | 'answered'): ExtendedUIMessage[] => [
- {
- id: 'assistant-1',
- role: 'assistant',
- parts: [
- {
- type: 'tool-ask_questions',
- toolCallId: 'call-1',
- state: 'output-available',
- input: { questions: [] },
- output: {
- success: true,
- message: 'x',
- result: {
- questions: [
- { header: 'Type', question: 'Which?', options: [{ label: 'A' }] },
- ],
- status,
- },
- },
- },
- ],
- metadata: { createdAt: '2024-01-01T00:00:00.000Z' },
- } as unknown as ExtendedUIMessage,
-];
-
-describe('markQuestionAnswered', () => {
- it('flips the matching tool part to answered and stores the answers', () => {
- const answers = [
- { questionIndex: 0, selectedOptionIndices: [0], freeText: undefined },
- ];
-
- const result = markQuestionAnswered(
- buildMessages('pending'),
- 'assistant-1',
- 'call-1',
- answers,
- );
-
- const output = (result[0].parts[0] as { output?: { result?: unknown } })
- .output;
-
- expect(output).toMatchObject({
- result: { status: 'answered', answers },
- });
- });
-
- it('preserves the original questions on the resolved part', () => {
- const result = markQuestionAnswered(
- buildMessages('pending'),
- 'assistant-1',
- 'call-1',
- [{ questionIndex: 0, selectedOptionIndices: [0] }],
- );
-
- const output = (
- result[0].parts[0] as {
- output?: { result?: { questions?: unknown[] } };
- }
- ).output;
-
- expect(output?.result?.questions).toHaveLength(1);
- });
-
- it('leaves non-matching tool calls untouched', () => {
- const result = markQuestionAnswered(
- buildMessages('pending'),
- 'assistant-1',
- 'other-call',
- [{ questionIndex: 0, selectedOptionIndices: [0] }],
- );
-
- const output = (
- result[0].parts[0] as { output?: { result?: { status?: string } } }
- ).output;
-
- expect(output?.result?.status).toBe('pending');
- });
-});
diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/updateToolPartOutput.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/updateToolPartOutput.test.ts
new file mode 100644
index 00000000000..29e748e957a
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/updateToolPartOutput.test.ts
@@ -0,0 +1,50 @@
+import { type ExtendedUIMessage } from 'twenty-shared/ai';
+
+import { updateToolPartOutput } from '@/ai/utils/updateToolPartOutput';
+
+const messages = [
+ {
+ id: 'assistant-1',
+ role: 'assistant',
+ parts: [
+ { type: 'text', text: 'Before asking' },
+ {
+ type: 'tool-ask_questions',
+ toolCallId: 'call-1',
+ state: 'output-available',
+ input: { questions: [] },
+ output: { result: { questions: [], status: 'pending' } },
+ },
+ ],
+ },
+ {
+ id: 'assistant-2',
+ role: 'assistant',
+ parts: [{ type: 'text', text: 'Untouched' }],
+ },
+] as unknown as ExtendedUIMessage[];
+
+describe('updateToolPartOutput', () => {
+ it('replaces the output of the matching tool call only', () => {
+ const answeredOutput = { result: { questions: [], status: 'answered' } };
+
+ const result = updateToolPartOutput({
+ messages,
+ toolCallId: 'call-1',
+ output: answeredOutput,
+ });
+
+ expect(result[0].parts[1]).toMatchObject({
+ toolCallId: 'call-1',
+ output: answeredOutput,
+ });
+ expect(result[0].parts[0]).toBe(messages[0].parts[0]);
+ expect(result[1]).toBe(messages[1]);
+ });
+
+ it('leaves the messages as they are for an unknown tool call', () => {
+ expect(
+ updateToolPartOutput({ messages, toolCallId: 'unknown', output: {} }),
+ ).toEqual(messages);
+ });
+});
diff --git a/packages/twenty-front/src/modules/ai/utils/aiChatErrorCode.ts b/packages/twenty-front/src/modules/ai/utils/aiChatErrorCode.ts
index 8ae6e79c057..1b5730c3662 100644
--- a/packages/twenty-front/src/modules/ai/utils/aiChatErrorCode.ts
+++ b/packages/twenty-front/src/modules/ai/utils/aiChatErrorCode.ts
@@ -3,6 +3,6 @@ export const AiChatErrorCode = {
CONTEXT_WINDOW_EXCEEDED: 'CONTEXT_WINDOW_EXCEEDED',
API_KEY_NOT_CONFIGURED: 'API_KEY_NOT_CONFIGURED',
CONNECTION_LOST: 'CONNECTION_LOST',
- QUESTION_NOT_PENDING: 'QUESTION_NOT_PENDING',
+ ASK_NOT_PENDING: 'ASK_NOT_PENDING',
QUOTA_EXHAUSTED: 'QUOTA_EXHAUSTED',
} as const;
diff --git a/packages/twenty-front/src/modules/ai/utils/findToolPartOutput.ts b/packages/twenty-front/src/modules/ai/utils/findToolPartOutput.ts
new file mode 100644
index 00000000000..0f602cec028
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/utils/findToolPartOutput.ts
@@ -0,0 +1,20 @@
+import { isToolUIPart } from 'ai';
+import { type ExtendedUIMessage } from 'twenty-shared/ai';
+
+export const findToolPartOutput = ({
+ messages,
+ toolCallId,
+}: {
+ messages: ExtendedUIMessage[];
+ toolCallId: string;
+}): unknown => {
+ for (const message of messages) {
+ for (const part of message.parts) {
+ if (isToolUIPart(part) && part.toolCallId === toolCallId) {
+ return part.output;
+ }
+ }
+ }
+
+ return undefined;
+};
diff --git a/packages/twenty-front/src/modules/ai/utils/groupContiguousThinkingStepParts.ts b/packages/twenty-front/src/modules/ai/utils/groupContiguousThinkingStepParts.ts
index dc6ef61ff66..323a7bf83cc 100644
--- a/packages/twenty-front/src/modules/ai/utils/groupContiguousThinkingStepParts.ts
+++ b/packages/twenty-front/src/modules/ai/utils/groupContiguousThinkingStepParts.ts
@@ -1,7 +1,7 @@
import { type ExtendedUIMessagePart } from 'twenty-shared/ai';
import { type AssistantMessageRenderItem } from '@/ai/utils/assistantMessageRenderItem';
-import { isAskQuestionsToolPart } from '@/ai/utils/isAskQuestionsToolPart';
+import { isPausingToolPart } from '@/ai/utils/isPausingToolPart';
import { isThinkingStepPart } from '@/ai/utils/isThinkingStepPart';
import { type ThinkingStepPart } from '@/ai/utils/thinkingStepPart';
@@ -30,7 +30,7 @@ export const groupContiguousThinkingStepParts = (
if (
isThinkingStepPart(part) &&
- !isAskQuestionsToolPart(part) &&
+ !isPausingToolPart(part) &&
!shouldRenderStandalone(part)
) {
currentThinkingParts.push(part);
diff --git a/packages/twenty-front/src/modules/ai/utils/isAskQuestionsToolPart.ts b/packages/twenty-front/src/modules/ai/utils/isAskQuestionsToolPart.ts
deleted file mode 100644
index 69fe625e495..00000000000
--- a/packages/twenty-front/src/modules/ai/utils/isAskQuestionsToolPart.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { getToolName, isToolUIPart } from 'ai';
-import {
- ASK_QUESTIONS_TOOL_NAME,
- type ExtendedUIMessagePart,
-} from 'twenty-shared/ai';
-
-export const isAskQuestionsToolPart = (part: ExtendedUIMessagePart): boolean =>
- isToolUIPart(part) && getToolName(part) === ASK_QUESTIONS_TOOL_NAME;
diff --git a/packages/twenty-front/src/modules/ai/utils/isPausingToolPart.ts b/packages/twenty-front/src/modules/ai/utils/isPausingToolPart.ts
new file mode 100644
index 00000000000..697f53e0cf6
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/utils/isPausingToolPart.ts
@@ -0,0 +1,7 @@
+import { getToolName, isToolUIPart } from 'ai';
+import { type ExtendedUIMessagePart } from 'twenty-shared/ai';
+
+import { PAUSING_TOOL_NAMES } from '@/ai/constants/PausingToolNames';
+
+export const isPausingToolPart = (part: ExtendedUIMessagePart): boolean =>
+ isToolUIPart(part) && PAUSING_TOOL_NAMES.has(getToolName(part));
diff --git a/packages/twenty-front/src/modules/ai/utils/markQuestionAnswered.ts b/packages/twenty-front/src/modules/ai/utils/markQuestionAnswered.ts
deleted file mode 100644
index c60025c5824..00000000000
--- a/packages/twenty-front/src/modules/ai/utils/markQuestionAnswered.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { isToolUIPart } from 'ai';
-import {
- type AskQuestionAnswer,
- type AskQuestionsToolResult,
- type ExtendedUIMessage,
- type ExtendedUIMessagePart,
-} from 'twenty-shared/ai';
-import { isDefined } from 'twenty-shared/utils';
-
-export const markQuestionAnswered = (
- messages: ExtendedUIMessage[],
- messageId: string,
- toolCallId: string,
- answers: AskQuestionAnswer[],
-): ExtendedUIMessage[] =>
- messages.map((message) => {
- if (message.id !== messageId) {
- return message;
- }
-
- return {
- ...message,
- parts: message.parts.map((part) => {
- if (!isToolUIPart(part) || part.toolCallId !== toolCallId) {
- return part;
- }
-
- const previousOutput = isDefined(part.output)
- ? (part.output as Record<string, unknown>)
- : {};
- const previousResult = previousOutput.result as
- | AskQuestionsToolResult
- | undefined;
-
- return {
- ...part,
- output: {
- ...previousOutput,
- result: {
- questions: previousResult?.questions ?? [],
- status: 'answered',
- answers,
- } satisfies AskQuestionsToolResult,
- },
- } as ExtendedUIMessagePart;
- }),
- };
- });
diff --git a/packages/twenty-front/src/modules/ai/utils/markQuestionPending.ts b/packages/twenty-front/src/modules/ai/utils/markQuestionPending.ts
deleted file mode 100644
index 151affef18e..00000000000
--- a/packages/twenty-front/src/modules/ai/utils/markQuestionPending.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { isToolUIPart } from 'ai';
-import {
- type AskQuestionsToolResult,
- type ExtendedUIMessage,
- type ExtendedUIMessagePart,
-} from 'twenty-shared/ai';
-import { isDefined } from 'twenty-shared/utils';
-
-export const markQuestionPending = (
- messages: ExtendedUIMessage[],
- messageId: string,
- toolCallId: string,
-): ExtendedUIMessage[] =>
- messages.map((message) => {
- if (message.id !== messageId) {
- return message;
- }
-
- return {
- ...message,
- parts: message.parts.map((part) => {
- if (!isToolUIPart(part) || part.toolCallId !== toolCallId) {
- return part;
- }
-
- const previousOutput = isDefined(part.output)
- ? (part.output as Record<string, unknown>)
- : {};
- const previousResult = previousOutput.result as
- | AskQuestionsToolResult
- | undefined;
-
- return {
- ...part,
- output: {
- ...previousOutput,
- result: {
- questions: previousResult?.questions ?? [],
- status: 'pending',
- } satisfies AskQuestionsToolResult,
- },
- } as ExtendedUIMessagePart;
- }),
- };
- });
diff --git a/packages/twenty-front/src/modules/ai/utils/updateToolPartOutput.ts b/packages/twenty-front/src/modules/ai/utils/updateToolPartOutput.ts
new file mode 100644
index 00000000000..e0c5a72a18a
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/utils/updateToolPartOutput.ts
@@ -0,0 +1,29 @@
+import { isToolUIPart } from 'ai';
+import {
+ type ExtendedUIMessage,
+ type ExtendedUIMessagePart,
+} from 'twenty-shared/ai';
+
+export const updateToolPartOutput = ({
+ messages,
+ toolCallId,
+ output,
+}: {
+ messages: ExtendedUIMessage[];
+ toolCallId: string;
+ output: unknown;
+}): ExtendedUIMessage[] =>
+ messages.map((message) =>
+ message.parts.some(
+ (part) => isToolUIPart(part) && part.toolCallId === toolCallId,
+ )
+ ? {
+ ...message,
+ parts: message.parts.map((part) =>
+ isToolUIPart(part) && part.toolCallId === toolCallId
+ ? ({ ...part, output } as ExtendedUIMessagePart)
+ : part,
+ ),
+ }
+ : message,
+ );
diff --git a/packages/twenty-front/src/modules/input-ask/graphql/mutations/answerAsk.ts b/packages/twenty-front/src/modules/input-ask/graphql/mutations/answerAsk.ts
new file mode 100644
index 00000000000..ba0b494431c
--- /dev/null
+++ b/packages/twenty-front/src/modules/input-ask/graphql/mutations/answerAsk.ts
@@ -0,0 +1,9 @@
+import { gql } from '@apollo/client';
+
+export const ANSWER_ASK = gql`
+ mutation AnswerAsk($input: AnswerAskInput!) {
+ answerAsk(input: $input) {
+ streamId
+ }
+ }
+`;
diff --git a/packages/twenty-front/src/modules/input-ask/hooks/useAnswerAsk.ts b/packages/twenty-front/src/modules/input-ask/hooks/useAnswerAsk.ts
new file mode 100644
index 00000000000..eb6fb93bef9
--- /dev/null
+++ b/packages/twenty-front/src/modules/input-ask/hooks/useAnswerAsk.ts
@@ -0,0 +1,37 @@
+import { useCallback } from 'react';
+
+import { ANSWER_ASK } from '@/input-ask/graphql/mutations/answerAsk';
+import { useApolloCoreClient } from '@/object-metadata/hooks/useApolloCoreClient';
+import {
+ type AnswerAskMutation,
+ type AnswerAskMutationVariables,
+} from '~/generated/graphql';
+
+export const useAnswerAsk = () => {
+ const apolloCoreClient = useApolloCoreClient();
+
+ const answerAsk = useCallback(
+ async ({
+ askId,
+ response,
+ modelId,
+ }: {
+ askId: string;
+ response: Record<string, unknown>;
+ modelId?: string;
+ }) => {
+ const { data } = await apolloCoreClient.mutate<
+ AnswerAskMutation,
+ AnswerAskMutationVariables
+ >({
+ mutation: ANSWER_ASK,
+ variables: { input: { askId, response, modelId } },
+ });
+
+ return { streamId: data?.answerAsk.streamId ?? null };
+ },
+ [apolloCoreClient],
+ );
+
+ return { answerAsk };
+};
diff --git a/packages/twenty-front/src/modules/input-ask/utils/__tests__/parseInputAskForm.test.ts b/packages/twenty-front/src/modules/input-ask/utils/__tests__/parseInputAskForm.test.ts
new file mode 100644
index 00000000000..dae1a58aaee
--- /dev/null
+++ b/packages/twenty-front/src/modules/input-ask/utils/__tests__/parseInputAskForm.test.ts
@@ -0,0 +1,35 @@
+import { parseInputAskForm } from '@/input-ask/utils/parseInputAskForm';
+
+const EMAIL = {
+ recipients: { to: '[email protected]', cc: '', bcc: '' },
+ subject: 'Renewal',
+ body: 'Hi Tim',
+};
+
+describe('parseInputAskForm', () => {
+ it.each([
+ [
+ 'questions',
+ {
+ kind: 'questions',
+ questions: [{ header: 'Plan', question: 'Which plan?', options: [] }],
+ },
+ ],
+ ['an email approval', { kind: 'emailApproval', email: EMAIL }],
+ ])('reads %s', (_description, form) => {
+ expect(parseInputAskForm(form)).toEqual(form);
+ });
+
+ it.each([
+ ['no form', null],
+ ['an unknown kind', { kind: 'signature' }],
+ ["a form step's fields", { kind: 'formFields', fields: [] }],
+ ['questions without any question', { kind: 'questions', questions: [] }],
+ [
+ 'an email without a subject',
+ { kind: 'emailApproval', email: { ...EMAIL, subject: undefined } },
+ ],
+ ])('refuses %s', (_description, form) => {
+ expect(parseInputAskForm(form)).toBeNull();
+ });
+});
diff --git a/packages/twenty-front/src/modules/input-ask/utils/parseInputAskForm.ts b/packages/twenty-front/src/modules/input-ask/utils/parseInputAskForm.ts
new file mode 100644
index 00000000000..7f0f332102a
--- /dev/null
+++ b/packages/twenty-front/src/modules/input-ask/utils/parseInputAskForm.ts
@@ -0,0 +1,30 @@
+import { isString } from '@sniptt/guards';
+import { isNonEmptyArray, isPlainObject } from 'twenty-shared/utils';
+
+import { type AgentChatPendingAsk } from '@/ai/types/AgentChatPendingAsk';
+
+type ChatInputAskForm = AgentChatPendingAsk['form'];
+
+// The form is stored as JSON, so what a card renders is checked here rather
+// than trusted.
+export const parseInputAskForm = (form: unknown): ChatInputAskForm | null => {
+ if (!isPlainObject(form)) {
+ return null;
+ }
+
+ switch (form.kind) {
+ case 'questions':
+ return Array.isArray(form.questions) && isNonEmptyArray(form.questions)
+ ? (form as ChatInputAskForm)
+ : null;
+ case 'emailApproval':
+ return isPlainObject(form.email) &&
+ isPlainObject(form.email.recipients) &&
+ isString(form.email.subject) &&
+ isString(form.email.body)
+ ? (form as ChatInputAskForm)
+ : null;
+ default:
+ return null;
+ }
+};
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowEditActionFormFiller.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowEditActionFormFiller.tsx
index 5aff49d94a6..03fdeba114e 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowEditActionFormFiller.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowEditActionFormFiller.tsx
@@ -1,20 +1,23 @@
-import { WorkflowStepCmdEnterButton } from '@/workflow/workflow-steps/components/WorkflowStepCmdEnterButton';
-import { useSidePanelHistory } from '@/side-panel/hooks/useSidePanelHistory';
+import { objectMetadataItemFamilySelector } from '@/object-metadata/states/objectMetadataItemFamilySelector';
+import { useAtomFamilySelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue';
import { FormFieldInput } from '@/object-record/record-field/ui/components/FormFieldInput';
import { FormSingleRecordPicker } from '@/object-record/record-field/ui/form-types/components/FormSingleRecordPicker';
import { type FieldMetadata } from '@/object-record/record-field/ui/types/FieldMetadata';
+import { useSidePanelHistory } from '@/side-panel/hooks/useSidePanelHistory';
import { SidePanelFooter } from '@/ui/layout/side-panel/components/SidePanelFooter';
import { useWorkflowRunIdOrThrow } from '@/workflow/hooks/useWorkflowRunIdOrThrow';
import { type WorkflowFormAction } from '@/workflow/types/Workflow';
import { WorkflowRunSSESubscribeEffect } from '@/workflow/workflow-diagram/components/WorkflowRunSSESubscribeEffect';
import { WorkflowStepBody } from '@/workflow/workflow-steps/components/WorkflowStepBody';
+import { WorkflowStepCmdEnterButton } from '@/workflow/workflow-steps/components/WorkflowStepCmdEnterButton';
import { useUpdateWorkflowRunStep } from '@/workflow/workflow-steps/hooks/useUpdateWorkflowRunStep';
import { WorkflowFormFieldInput } from '@/workflow/workflow-steps/workflow-actions/components/WorkflowFormFieldInput';
-import { useSubmitFormStep } from '@/workflow/workflow-steps/workflow-actions/form-action/hooks/useSubmitFormStep';
+import { WorkflowFormStepAskSubmitButton } from '@/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormStepAskSubmitButton';
import { type WorkflowFormActionField } from '@/workflow/workflow-steps/workflow-actions/form-action/types/WorkflowFormActionField';
import { getDefaultFormFieldSettings } from '@/workflow/workflow-steps/workflow-actions/form-action/utils/getDefaultFormFieldSettings';
import { useLingui } from '@lingui/react/macro';
import { useEffect, useState } from 'react';
+import { CoreObjectNameSingular } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { useDebouncedCallback } from 'use-debounce';
@@ -32,12 +35,17 @@ export const WorkflowEditActionFormFiller = ({
actionOptions,
}: WorkflowEditActionFormFillerProps) => {
const { t } = useLingui();
- const { submitFormStep } = useSubmitFormStep();
const [formData, setFormData] = useState<FormData>(action.settings.input);
const workflowRunId = useWorkflowRunIdOrThrow();
const { goBackFromSidePanel } = useSidePanelHistory();
const { updateWorkflowRunStep } = useUpdateWorkflowRunStep();
const [error, setError] = useState<string | undefined>(undefined);
+ // A form is submitted by answering its Ask, which a workspace the Ask
+ // object has not reached yet cannot do.
+ const inputAskObjectMetadataItem = useAtomFamilySelectorValue(
+ objectMetadataItemFamilySelector,
+ { objectName: CoreObjectNameSingular.InputAsk, objectNameType: 'singular' },
+ );
const canSubmit = !actionOptions.readonly && !isDefined(error);
@@ -46,7 +54,7 @@ export const WorkflowEditActionFormFiller = ({
value,
}: {
fieldId: string;
- value: any;
+ value: unknown;
}) => {
if (actionOptions.readonly === true) {
return;
@@ -75,24 +83,12 @@ export const WorkflowEditActionFormFiller = ({
});
}, 1_000);
- const onSubmit = async () => {
+ const getResponse = async () => {
await saveAction.flush();
- const response = formData.reduce(
- (acc, field) => {
- acc[field.name] = field.value;
- return acc;
- },
- {} as Record<string, any>,
+ return Object.fromEntries(
+ formData.map((field) => [field.name, field.value]),
);
-
- await submitFormStep({
- stepId: action.id,
- workflowRunId,
- response,
- });
-
- goBackFromSidePanel();
};
useEffect(() => {
@@ -113,20 +109,13 @@ export const WorkflowEditActionFormFiller = ({
return null;
}
- const recordId = field.value?.id;
-
return (
<FormSingleRecordPicker
key={field.id}
label={field.label}
- defaultValue={recordId}
+ defaultValue={field.value?.id}
onChange={(recordId) => {
- onFieldUpdate({
- fieldId: field.id,
- value: {
- id: recordId,
- },
- });
+ onFieldUpdate({ fieldId: field.id, value: { id: recordId } });
}}
objectNameSingulars={[objectNameSingular]}
disabled={actionOptions.readonly}
@@ -148,10 +137,7 @@ export const WorkflowEditActionFormFiller = ({
defaultValue={field.value}
readonly={actionOptions.readonly}
onChange={(value) => {
- onFieldUpdate({
- fieldId: field.id,
- value,
- });
+ onFieldUpdate({ fieldId: field.id, value });
}}
/>
);
@@ -166,10 +152,7 @@ export const WorkflowEditActionFormFiller = ({
metadata: {} as FieldMetadata,
}}
onChange={(value) => {
- onFieldUpdate({
- fieldId: field.id,
- value,
- });
+ onFieldUpdate({ fieldId: field.id, value });
}}
defaultValue={field.value}
readonly={actionOptions.readonly}
@@ -177,9 +160,7 @@ export const WorkflowEditActionFormFiller = ({
field.placeholder ??
getDefaultFormFieldSettings(field.type).placeholder
}
- onError={(error) => {
- setError(error);
- }}
+ onError={setError}
/>
);
})}
@@ -187,11 +168,23 @@ export const WorkflowEditActionFormFiller = ({
{!actionOptions.readonly && (
<SidePanelFooter
actions={[
- <WorkflowStepCmdEnterButton
- title={t`Submit`}
- onClick={onSubmit}
- disabled={!canSubmit}
- />,
+ isDefined(inputAskObjectMetadataItem) ? (
+ <WorkflowFormStepAskSubmitButton
+ key="submit"
+ workflowRunId={workflowRunId}
+ stepId={action.id}
+ disabled={!canSubmit}
+ getResponse={getResponse}
+ onSubmitted={goBackFromSidePanel}
+ />
+ ) : (
+ <WorkflowStepCmdEnterButton
+ key="submit"
+ title={t`Submit`}
+ onClick={() => {}}
+ disabled
+ />
+ ),
]}
/>
)}
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormStepAskSubmitButton.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormStepAskSubmitButton.tsx
new file mode 100644
index 00000000000..a298515f9af
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/components/WorkflowFormStepAskSubmitButton.tsx
@@ -0,0 +1,65 @@
+import { getToastOptionsFromError } from '@/error-handler/utils/getToastOptionsFromError';
+import { WorkflowStepCmdEnterButton } from '@/workflow/workflow-steps/components/WorkflowStepCmdEnterButton';
+import { useAnswerFormStepAsk } from '@/workflow/workflow-steps/workflow-actions/form-action/hooks/useAnswerFormStepAsk';
+import { useLingui } from '@lingui/react/macro';
+import { useState } from 'react';
+import { useToast } from 'twenty-ui/components';
+
+type WorkflowFormStepAskSubmitButtonProps = {
+ workflowRunId: string;
+ stepId: string;
+ disabled: boolean;
+ getResponse: () => Promise<Record<string, unknown>>;
+ onSubmitted: () => void;
+};
+
+export const WorkflowFormStepAskSubmitButton = ({
+ workflowRunId,
+ stepId,
+ disabled,
+ getResponse,
+ onSubmitted,
+}: WorkflowFormStepAskSubmitButtonProps) => {
+ const { t } = useLingui();
+ const { enqueueToast } = useToast();
+ const { answerFormStepAsk } = useAnswerFormStepAsk({
+ workflowRunId,
+ stepId,
+ });
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
+ const handleSubmit = async () => {
+ if (disabled || isSubmitting) {
+ return;
+ }
+
+ setIsSubmitting(true);
+
+ try {
+ const isSubmitted = await answerFormStepAsk(await getResponse());
+
+ if (isSubmitted) {
+ onSubmitted();
+
+ return;
+ }
+
+ enqueueToast({
+ variant: 'error',
+ children: t`This form no longer waits for an answer`,
+ });
+ } catch (error) {
+ enqueueToast(getToastOptionsFromError({ error }));
+ }
+
+ setIsSubmitting(false);
+ };
+
+ return (
+ <WorkflowStepCmdEnterButton
+ title={t`Submit`}
+ onClick={() => void handleSubmit()}
+ disabled={disabled || isSubmitting}
+ />
+ );
+};
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/graphql/mutations/submitFormStep.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/graphql/mutations/submitFormStep.ts
deleted file mode 100644
index a8ad41b7718..00000000000
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/graphql/mutations/submitFormStep.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { gql } from '@apollo/client';
-
-export const SUBMIT_FORM_STEP = gql`
- mutation SubmitFormStep($input: SubmitFormStepInput!) {
- submitFormStep(input: $input)
- }
-`;
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/hooks/useAnswerFormStepAsk.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/hooks/useAnswerFormStepAsk.ts
new file mode 100644
index 00000000000..fb804bf3fa6
--- /dev/null
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/hooks/useAnswerFormStepAsk.ts
@@ -0,0 +1,76 @@
+import { useMemo } from 'react';
+import { CoreObjectNameSingular } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+import { useAnswerAsk } from '@/input-ask/hooks/useAnswerAsk';
+import { useApolloCoreClient } from '@/object-metadata/hooks/useApolloCoreClient';
+import { useFindOneRecordQuery } from '@/object-record/hooks/useFindOneRecordQuery';
+import { useLazyFindManyRecords } from '@/object-record/hooks/useLazyFindManyRecords';
+
+export const useAnswerFormStepAsk = ({
+ workflowRunId,
+ stepId,
+}: {
+ workflowRunId: string;
+ stepId: string;
+}) => {
+ const apolloCoreClient = useApolloCoreClient();
+ const { answerAsk } = useAnswerAsk();
+
+ // A form step's Ask is the one of its run and step that no tool call
+ // opened; an agent step's questions are answered from its conversation.
+ const filter = useMemo(
+ () => ({
+ workflowRunId: { eq: workflowRunId },
+ stepId: { eq: stepId },
+ toolCallId: { is: 'NULL' as const },
+ status: { in: ['PENDING'] },
+ }),
+ [workflowRunId, stepId],
+ );
+
+ const { findManyRecordsLazy } = useLazyFindManyRecords({
+ objectNameSingular: CoreObjectNameSingular.InputAsk,
+ filter,
+ limit: 1,
+ recordGqlFields: { id: true },
+ fetchPolicy: 'network-only',
+ });
+
+ const { findOneRecordQuery: findOneWorkflowRunQuery } = useFindOneRecordQuery(
+ {
+ objectNameSingular: CoreObjectNameSingular.WorkflowRun,
+ recordGqlFields: {
+ id: true,
+ name: true,
+ status: true,
+ startedAt: true,
+ endedAt: true,
+ },
+ },
+ );
+
+ // Returns whether the form was submitted: false when it no longer waits.
+ const answerFormStepAsk = async (
+ response: Record<string, unknown>,
+ ): Promise<boolean> => {
+ const { records } = await findManyRecordsLazy();
+ const formStepAsk = records?.[0];
+
+ if (!isDefined(formStepAsk)) {
+ return false;
+ }
+
+ await answerAsk({ askId: formStepAsk.id, response });
+
+ await apolloCoreClient.query({
+ query: findOneWorkflowRunQuery,
+ variables: { objectRecordId: workflowRunId },
+ fetchPolicy: 'network-only',
+ });
+
+ return true;
+ };
+
+ return { answerFormStepAsk };
+};
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/hooks/useSubmitFormStep.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/hooks/useSubmitFormStep.ts
deleted file mode 100644
index e815bdd6b4f..00000000000
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/form-action/hooks/useSubmitFormStep.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-import { useApolloCoreClient } from '@/object-metadata/hooks/useApolloCoreClient';
-import { CoreObjectNameSingular } from 'twenty-shared/types';
-import { useFindOneRecordQuery } from '@/object-record/hooks/useFindOneRecordQuery';
-import { SUBMIT_FORM_STEP } from '@/workflow/workflow-steps/workflow-actions/form-action/graphql/mutations/submitFormStep';
-import { useMutation } from '@apollo/client/react';
-import {
- type SubmitFormStepInput,
- type SubmitFormStepMutation,
- type SubmitFormStepMutationVariables,
-} from '~/generated/graphql';
-
-export const useSubmitFormStep = () => {
- const apolloCoreClient = useApolloCoreClient();
- const [mutate] = useMutation<
- SubmitFormStepMutation,
- SubmitFormStepMutationVariables
- >(SUBMIT_FORM_STEP, {
- client: apolloCoreClient,
- });
-
- const { findOneRecordQuery: findOneWorkflowRunQuery } = useFindOneRecordQuery(
- {
- objectNameSingular: CoreObjectNameSingular.WorkflowRun,
- recordGqlFields: {
- id: true,
- name: true,
- status: true,
- startedAt: true,
- endedAt: true,
- },
- },
- );
-
- const submitFormStep = async (input: SubmitFormStepInput) => {
- const result = await mutate({
- variables: { input },
- awaitRefetchQueries: true,
- refetchQueries: [
- {
- query: findOneWorkflowRunQuery,
- variables: {
- objectRecordId: input.workflowRunId,
- },
- },
- ],
- });
- const isSuccess = result?.data?.submitFormStep;
-
- return isSuccess;
- };
-
- return { submitFormStep };
-};
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 dad01d0b073..e6793382d89 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
@@ -1187,7 +1187,6 @@ const SCHEMA = getWorkspaceSchemaName(WORKSPACE_ID);
totalCacheCreationTokens: 0,
contextWindowTokens: 1000,
conversationSize: 3,
- pendingQuestionMessageId: null,
},
};
expect(
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-upgrade-version-command.module.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-upgrade-version-command.module.ts
index 8eda754a3ba..5a6dbddacae 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-upgrade-version-command.module.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-upgrade-version-command.module.ts
@@ -16,6 +16,7 @@ import { RemoveAddNodeWorkflowCommandMenuItemCommand } from 'src/database/comman
import { OpenAgentChatThreadArchivedAtWritabilityCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790672076234-open-agent-chat-thread-archived-at-writability.command';
import { AddInputAskObjectCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790681093095-add-input-ask-object.command';
import { GateConversationsWidgetOnFeatureFlagCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790700866168-gate-conversations-widget-on-feature-flag.command';
+import { OpenAsksForPendingInputCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790714482317-open-asks-for-pending-input.command';
import { ApplicationModule } from 'src/engine/core-modules/application/application.module';
import { WorkspaceMigrationRunnerModule } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/workspace-migration-runner.module';
@@ -41,6 +42,7 @@ import { WorkspaceMigrationRunnerModule } from 'src/engine/workspace-manager/wor
OpenAgentChatThreadArchivedAtWritabilityCommand,
AddInputAskObjectCommand,
GateConversationsWidgetOnFeatureFlagCommand,
+ OpenAsksForPendingInputCommand,
],
})
export class V2_44_UpgradeVersionCommandModule {}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790714482317-open-asks-for-pending-input.command.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790714482317-open-asks-for-pending-input.command.ts
new file mode 100644
index 00000000000..7bec0b1e2e0
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790714482317-open-asks-for-pending-input.command.ts
@@ -0,0 +1,355 @@
+import { Command } from 'nest-commander';
+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
+import { FieldActorSource } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+import { StepStatus, WorkflowActionType } from 'twenty-shared/workflow';
+import { IsNull, Not } from 'typeorm';
+
+import { AgentHistoryUpgradeStorageService } from 'src/database/commands/agent-history/agent-history-upgrade-storage.service';
+import { ProvisionedWorkspaceCommandRunner } from 'src/database/commands/command-runners/provisioned-workspace.command-runner';
+import { WorkspaceIteratorService } from 'src/database/commands/command-runners/workspace-iterator.service';
+import { type RunOnWorkspaceArgs } from 'src/database/commands/command-runners/workspace.command-runner';
+import { findPendingAskQuestionsPart } from 'src/database/commands/upgrade-version-command/2-44/utils/find-pending-ask-questions-part.util';
+import { RegisteredWorkspaceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-workspace-command.decorator';
+import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';
+import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
+import { type AgentMessagePartWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message-part.workspace-entity';
+import { type AgentMessageWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-message.workspace-entity';
+import {
+ TwentyOrmException,
+ TwentyOrmExceptionCode,
+} from 'src/engine/twenty-orm/exceptions/twenty-orm.exception';
+import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
+import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { InputAskStatus } from 'src/modules/input-ask/enums/input-ask-status.enum';
+import { type InputAskWorkspaceEntity } from 'src/modules/input-ask/standard-objects/input-ask.workspace-entity';
+import {
+ WorkflowRunStatus,
+ type WorkflowRunWorkspaceEntity,
+} from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
+
+type PendingQuestionThread = Pick<
+ AgentChatThreadWorkspaceEntity,
+ 'id' | 'pendingQuestionMessageId' | 'workflowRunId' | 'workspaceMemberId'
+>;
+
+// Every pause for a person is now answered through its Ask, and one that
+// started before this release may have none: an agent question was answered
+// through its conversation's pending marker, a form step through its run.
+// Each one still waiting gets the Ask it would have opened.
+@RegisteredWorkspaceCommand('2.44.0', 1790714482317)
+@Command({
+ name: 'upgrade:2-44:open-asks-for-pending-input',
+ description:
+ 'Open an Ask for every agent question and form step still waiting on an answer',
+})
+export class OpenAsksForPendingInputCommand extends ProvisionedWorkspaceCommandRunner {
+ constructor(
+ protected readonly workspaceIteratorService: WorkspaceIteratorService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ private readonly workspaceOrmManager: WorkspaceOrmManager,
+ private readonly storage: AgentHistoryUpgradeStorageService,
+ ) {
+ super(workspaceIteratorService);
+ }
+
+ override async runOnWorkspace(args: RunOnWorkspaceArgs): Promise<void> {
+ await this.up(args);
+ }
+
+ async up({ workspaceId, options }: RunOnWorkspaceArgs): Promise<void> {
+ const { flatObjectMetadataMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'flatObjectMetadataMaps',
+ ]);
+
+ if (
+ !isDefined(
+ flatObjectMetadataMaps.byUniversalIdentifier[
+ STANDARD_OBJECTS.inputAsk.universalIdentifier
+ ],
+ ) ||
+ !isDefined(
+ flatObjectMetadataMaps.byUniversalIdentifier[
+ STANDARD_OBJECTS.agentChatThread.universalIdentifier
+ ],
+ )
+ ) {
+ this.logger.log(
+ `inputAsk or agentChatThread object not found for workspace ${workspaceId}, skipping`,
+ );
+
+ return;
+ }
+
+ // The history fence: its tables cannot move while the questions are read.
+ const isDryRun = options.dryRun ?? false;
+ const questionCount = await this.storage.run(workspaceId, () =>
+ this.workspaceOrmManager.executeInWorkspaceContext(
+ () => this.openAsksForPendingQuestions({ isDryRun }),
+ buildSystemAuthContext(workspaceId),
+ ),
+ );
+ const formStepCount =
+ await this.workspaceOrmManager.executeInWorkspaceContext(
+ () => this.openAsksForPendingFormSteps({ isDryRun }),
+ buildSystemAuthContext(workspaceId),
+ );
+
+ this.logger.log(
+ `${isDryRun ? '[DRY RUN] Would open' : 'Opened'} ${questionCount} Ask(s) for pending agent questions and ${formStepCount} for pending form steps in workspace ${workspaceId}`,
+ );
+ }
+
+ async down(_args: RunOnWorkspaceArgs): Promise<void> {
+ // The Asks are where these pauses are answered from now on; the
+ // conversations' pending markers are left as they were.
+ }
+
+ private async openAsksForPendingQuestions({
+ isDryRun,
+ }: {
+ isDryRun: boolean;
+ }): Promise<number> {
+ const threadRepository =
+ this.workspaceOrmManager.getRepository<AgentChatThreadWorkspaceEntity>(
+ 'agentChatThread',
+ { shouldBypassPermissionChecks: true },
+ );
+
+ const threads: PendingQuestionThread[] = await threadRepository.find({
+ where: { pendingQuestionMessageId: Not(IsNull()) },
+ select: {
+ id: true,
+ pendingQuestionMessageId: true,
+ workflowRunId: true,
+ workspaceMemberId: true,
+ },
+ });
+
+ let openedCount = 0;
+
+ for (const thread of threads) {
+ const isOpened = await this.openAskForThread({
+ thread,
+ isDryRun,
+ });
+
+ if (isOpened) {
+ openedCount++;
+ }
+ }
+
+ return openedCount;
+ }
+
+ private async openAskForThread({
+ thread,
+ isDryRun,
+ }: {
+ thread: PendingQuestionThread;
+ isDryRun: boolean;
+ }): Promise<boolean> {
+ if (!isDefined(thread.pendingQuestionMessageId)) {
+ return false;
+ }
+
+ const messageRepository =
+ this.workspaceOrmManager.getRepository<AgentMessageWorkspaceEntity>(
+ 'agentMessage',
+ { shouldBypassPermissionChecks: true },
+ );
+ const messagePartRepository =
+ this.workspaceOrmManager.getRepository<AgentMessagePartWorkspaceEntity>(
+ 'agentMessagePart',
+ { shouldBypassPermissionChecks: true },
+ );
+ const inputAskRepository =
+ this.workspaceOrmManager.getRepository<InputAskWorkspaceEntity>(
+ 'inputAsk',
+ { shouldBypassPermissionChecks: true },
+ );
+
+ const questionMessage = await messageRepository.findOne({
+ where: { id: thread.pendingQuestionMessageId, threadId: thread.id },
+ select: { id: true, turnId: true },
+ });
+
+ if (!isDefined(questionMessage)) {
+ return false;
+ }
+
+ const pendingPart = findPendingAskQuestionsPart(
+ await messagePartRepository.find({
+ where: { messageId: questionMessage.id },
+ select: { toolName: true, toolCallId: true, toolOutput: true },
+ }),
+ );
+
+ if (!isDefined(pendingPart)) {
+ return false;
+ }
+
+ const existingInputAsk = await inputAskRepository.findOne({
+ where: { threadId: thread.id, toolCallId: pendingPart.toolCallId },
+ select: { id: true },
+ });
+
+ if (isDefined(existingInputAsk)) {
+ return false;
+ }
+
+ if (isDryRun) {
+ return true;
+ }
+
+ const turnSender = isDefined(questionMessage.turnId)
+ ? await messageRepository.findOne({
+ where: {
+ turnId: questionMessage.turnId,
+ role: AgentMessageRole.USER,
+ senderWorkspaceMemberId: Not(IsNull()),
+ },
+ order: { createdAt: 'ASC' },
+ select: { senderWorkspaceMemberId: true },
+ })
+ : null;
+
+ const lowestPosition = await inputAskRepository.minimum('position');
+
+ try {
+ await inputAskRepository.insert({
+ name: pendingPart.questions[0]?.question ?? '',
+ status: InputAskStatus.PENDING,
+ form: { kind: 'questions', questions: pendingPart.questions },
+ threadId: thread.id,
+ toolCallId: pendingPart.toolCallId,
+ workflowRunId: thread.workflowRunId,
+ stepId: await this.findRunStepId(thread),
+ assigneeId:
+ turnSender?.senderWorkspaceMemberId ??
+ thread.workspaceMemberId ??
+ null,
+ position: (lowestPosition ?? 0) - 1,
+ });
+ } catch (error) {
+ // An Ask opened for the same call in the meantime is the one wanted.
+ if (
+ error instanceof TwentyOrmException &&
+ error.code === TwentyOrmExceptionCode.DUPLICATE_ENTRY_DETECTED
+ ) {
+ return false;
+ }
+
+ throw error;
+ }
+
+ return true;
+ }
+
+ private async openAsksForPendingFormSteps({
+ isDryRun,
+ }: {
+ isDryRun: boolean;
+ }): Promise<number> {
+ const workflowRunRepository =
+ this.workspaceOrmManager.getRepository<WorkflowRunWorkspaceEntity>(
+ 'workflowRun',
+ { shouldBypassPermissionChecks: true },
+ );
+ const inputAskRepository =
+ this.workspaceOrmManager.getRepository<InputAskWorkspaceEntity>(
+ 'inputAsk',
+ { shouldBypassPermissionChecks: true },
+ );
+
+ // Only a running run accepts a submission. Loaded whole: the ORM selects
+ // columns, and createdBy is a composite field spread over several.
+ const workflowRuns = await workflowRunRepository.find({
+ where: { status: WorkflowRunStatus.RUNNING },
+ });
+
+ let openedCount = 0;
+
+ for (const workflowRun of workflowRuns) {
+ const stepInfos = workflowRun.state?.stepInfos ?? {};
+
+ for (const step of workflowRun.state?.flow?.steps ?? []) {
+ if (
+ step.type !== WorkflowActionType.FORM ||
+ stepInfos[step.id]?.status !== StepStatus.PENDING ||
+ isDefined(stepInfos[step.id]?.error)
+ ) {
+ continue;
+ }
+
+ const existingInputAsk = await inputAskRepository.findOne({
+ where: {
+ workflowRunId: workflowRun.id,
+ stepId: step.id,
+ toolCallId: IsNull(),
+ },
+ select: { id: true },
+ });
+
+ if (isDefined(existingInputAsk)) {
+ continue;
+ }
+
+ openedCount++;
+
+ if (isDryRun) {
+ continue;
+ }
+
+ const lowestPosition = await inputAskRepository.minimum('position');
+
+ await inputAskRepository.insert({
+ name: step.name,
+ status: InputAskStatus.PENDING,
+ form: {
+ kind: 'formFields',
+ fields: step.settings.input,
+ },
+ workflowRunId: workflowRun.id,
+ stepId: step.id,
+ assigneeId:
+ workflowRun.createdBy?.source === FieldActorSource.MANUAL
+ ? (workflowRun.createdBy.workspaceMemberId ?? null)
+ : null,
+ position: (lowestPosition ?? 0) - 1,
+ });
+ }
+ }
+
+ return openedCount;
+ }
+
+ // A run conversation belongs to the step whose current execution recorded
+ // it, which only the run's state says.
+ private async findRunStepId(
+ thread: PendingQuestionThread,
+ ): Promise<string | null> {
+ if (!isDefined(thread.workflowRunId)) {
+ return null;
+ }
+
+ const workflowRun = await this.workspaceOrmManager
+ .getRepository<WorkflowRunWorkspaceEntity>('workflowRun', {
+ shouldBypassPermissionChecks: true,
+ })
+ .findOne({
+ where: { id: thread.workflowRunId },
+ select: { id: true, state: true },
+ });
+
+ const stepInfos = workflowRun?.state?.stepInfos ?? {};
+
+ return (
+ Object.keys(stepInfos).find(
+ (stepId) => stepInfos[stepId]?.threadId === thread.id,
+ ) ?? null
+ );
+ }
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/utils/__tests__/find-pending-ask-questions-part.util.spec.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/utils/__tests__/find-pending-ask-questions-part.util.spec.ts
new file mode 100644
index 00000000000..64fa348e43a
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/utils/__tests__/find-pending-ask-questions-part.util.spec.ts
@@ -0,0 +1,36 @@
+import { findPendingAskQuestionsPart } from 'src/database/commands/upgrade-version-command/2-44/utils/find-pending-ask-questions-part.util';
+
+const QUESTIONS = [
+ { header: 'Quote', question: 'Send it?', options: [{ label: 'Yes' }] },
+];
+
+const askQuestionsPart = (status: string) => ({
+ toolName: 'ask_questions',
+ toolCallId: 'call-1',
+ toolOutput: { success: true, result: { questions: QUESTIONS, status } },
+});
+
+describe('findPendingAskQuestionsPart', () => {
+ it('finds the ask_questions call still waiting on an answer', () => {
+ expect(
+ findPendingAskQuestionsPart([
+ { toolName: null, toolCallId: null, toolOutput: null },
+ askQuestionsPart('pending'),
+ ]),
+ ).toEqual({ toolCallId: 'call-1', questions: QUESTIONS });
+ });
+
+ it.each(['answered', 'skipped'])('ignores a call already %s', (status) => {
+ expect(
+ findPendingAskQuestionsPart([askQuestionsPart(status)]),
+ ).toBeUndefined();
+ });
+
+ it('ignores other tools with a pending-looking output', () => {
+ expect(
+ findPendingAskQuestionsPart([
+ { ...askQuestionsPart('pending'), toolName: 'search' },
+ ]),
+ ).toBeUndefined();
+ });
+});
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/utils/find-pending-ask-questions-part.util.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/utils/find-pending-ask-questions-part.util.ts
new file mode 100644
index 00000000000..0defd68d87a
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/utils/find-pending-ask-questions-part.util.ts
@@ -0,0 +1,36 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { type AskQuestionItem } from 'twenty-shared/ai';
+import { isNonEmptyArray, isPlainObject } from 'twenty-shared/utils';
+
+type StoredToolPart = {
+ toolName: string | null;
+ toolCallId: string | null;
+ toolOutput: unknown;
+};
+
+// The shape ask_questions stored while waiting, as of 2.44.
+export const findPendingAskQuestionsPart = (
+ parts: StoredToolPart[],
+): { toolCallId: string; questions: AskQuestionItem[] } | undefined => {
+ for (const part of parts) {
+ const result = isPlainObject(part.toolOutput)
+ ? part.toolOutput.result
+ : undefined;
+
+ if (
+ part.toolName === 'ask_questions' &&
+ isNonEmptyString(part.toolCallId) &&
+ isPlainObject(result) &&
+ result.status === 'pending' &&
+ Array.isArray(result.questions) &&
+ isNonEmptyArray(result.questions)
+ ) {
+ return {
+ toolCallId: part.toolCallId,
+ questions: result.questions as unknown as AskQuestionItem[],
+ };
+ }
+ }
+
+ return undefined;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/core-engine.module.ts b/packages/twenty-server/src/engine/core-modules/core-engine.module.ts
index c02a44000eb..9558b3f31e6 100644
--- a/packages/twenty-server/src/engine/core-modules/core-engine.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/core-engine.module.ts
@@ -83,6 +83,7 @@ import { ChannelSyncModule } from 'src/modules/connected-account/channel-sync/ch
import { CreateCalendarEventModule } from 'src/modules/calendar/calendar-event-creation-manager/create-calendar-event.module';
import { CallRecordingModule } from 'src/modules/call-recording/call-recording.module';
import { DashboardModule } from 'src/modules/dashboard/dashboard.module';
+import { AnswerAskModule } from 'src/modules/input-ask/answer-ask/answer-ask.module';
import { SendEmailModule } from 'src/modules/messaging/message-outbound-manager/send-email.module';
import { ClientConfigModule } from './client-config/client-config.module';
import { EventLogsViewerModule } from './event-logs/event-logs-viewer.module';
@@ -128,6 +129,7 @@ import { FileApiModule } from './file/file-api.module';
CloudflareModule,
DnsManagerModule,
WorkflowApiModule,
+ AnswerAskModule,
WorkspaceEventEmitterModule,
ActorModule,
TelemetryModule,
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-version-step.resolver.ts b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-version-step.resolver.ts
index df4e22c2b30..d0d7c6cf8ed 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-version-step.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/workflow-version-step.resolver.ts
@@ -11,7 +11,6 @@ import { HttpTool } from 'src/engine/core-modules/tool/tools/http-tool/http-tool
import { CreateWorkflowVersionStepInput } from 'src/engine/core-modules/workflow/dtos/create-workflow-version-step.input';
import { DeleteWorkflowVersionStepInput } from 'src/engine/core-modules/workflow/dtos/delete-workflow-version-step.input';
import { DuplicateWorkflowVersionStepInput } from 'src/engine/core-modules/workflow/dtos/duplicate-workflow-version-step.input';
-import { SubmitFormStepInput } from 'src/engine/core-modules/workflow/dtos/submit-form-step.input';
import { TestHttpRequestInput } from 'src/engine/core-modules/workflow/dtos/test-http-request.input';
import { TestHttpRequestDTO } from 'src/engine/core-modules/workflow/dtos/test-http-request.dto';
import { UpdateWorkflowRunStepInput } from 'src/engine/core-modules/workflow/dtos/update-workflow-run-step.input';
@@ -34,7 +33,6 @@ import { PermissionsGraphqlApiExceptionFilter } from 'src/engine/metadata-module
import { CoreWorkflowAccessService } from 'src/engine/core-modules/workflow/services/core-workflow-access.service';
import { WorkflowVersionStepWorkspaceService } from 'src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step.workspace-service';
import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
-import { WorkflowRunnerWorkspaceService } from 'src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service';
import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filters/auth-graphql-api-exception.filter';
@CoreResolver()
@@ -54,7 +52,6 @@ import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filt
export class WorkflowVersionStepResolver {
constructor(
private readonly workflowVersionStepWorkspaceService: WorkflowVersionStepWorkspaceService,
- private readonly workflowRunnerWorkspaceService: WorkflowRunnerWorkspaceService,
private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,
private readonly httpTool: HttpTool,
private readonly connectedAccountMetadataService: ConnectedAccountMetadataService,
@@ -177,22 +174,6 @@ export class WorkflowVersionStepResolver {
});
}
- @Mutation(() => Boolean)
- async submitFormStep(
- @AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
- @Args('input')
- { stepId, workflowRunId, response }: SubmitFormStepInput,
- ) {
- await this.workflowRunnerWorkspaceService.submitFormStep({
- workspaceId,
- stepId,
- workflowRunId,
- response,
- });
-
- return true;
- }
-
@Mutation(() => WorkflowActionDTO)
async updateWorkflowRunStep(
@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/__tests__/ask-questions.pausing-tool.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/__tests__/ask-questions.pausing-tool.spec.ts
new file mode 100644
index 00000000000..955e15de95d
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/__tests__/ask-questions.pausing-tool.spec.ts
@@ -0,0 +1,121 @@
+import { ASK_QUESTIONS_PAUSING_TOOL } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/ask-questions.pausing-tool';
+
+const QUESTIONS = [
+ {
+ header: 'Plan',
+ question: 'Which plan?',
+ options: [{ label: 'Pro' }, { label: 'Team' }],
+ },
+ {
+ header: 'Add-ons',
+ question: 'Which add-ons?',
+ options: [{ label: 'SSO' }, { label: 'Audit log' }],
+ allowMultiSelect: true,
+ },
+];
+
+const parseCall = () => {
+ const call = ASK_QUESTIONS_PAUSING_TOOL.parseCall({ questions: QUESTIONS });
+
+ if (call === null) {
+ throw new Error('Expected the call to parse');
+ }
+
+ return call;
+};
+
+describe('ASK_QUESTIONS_PAUSING_TOOL', () => {
+ it('cannot read a call without questions', () => {
+ expect(ASK_QUESTIONS_PAUSING_TOOL.parseCall({ questions: [] })).toBeNull();
+ expect(ASK_QUESTIONS_PAUSING_TOOL.parseCall(undefined)).toBeNull();
+ });
+
+ it('asks the first question as the Ask name and keeps every question as its form', () => {
+ expect(parseCall().buildAsk()).toEqual({
+ name: 'Which plan?',
+ form: { kind: 'questions', questions: QUESTIONS },
+ });
+ });
+
+ const NO_TOOLS = { executeTool: jest.fn() };
+
+ it('turns an accepted answer into the answered result and the answer message', async () => {
+ const answers = [
+ { questionIndex: 0, selectedOptionIndices: [1] },
+ { questionIndex: 1, selectedOptionIndices: [0, 1] },
+ ];
+ const call = parseCall();
+
+ expect(call.validate({ answers })).toEqual({
+ isValid: true,
+ output: { answers },
+ });
+ expect(
+ await call.complete({ output: { answers }, context: NO_TOOLS }),
+ ).toEqual({
+ toolResult: {
+ success: true,
+ message: 'User answered the questions.',
+ result: { questions: QUESTIONS, status: 'answered', answers },
+ },
+ answerText: 'Which plan?\nTeam\n\nWhich add-ons?\nSSO, Audit log',
+ });
+ expect(NO_TOOLS.executeTool).not.toHaveBeenCalled();
+ });
+
+ it('prefers free text and leaves unanswered questions out of the answer message', async () => {
+ const completion = await parseCall().complete({
+ output: {
+ answers: [
+ { questionIndex: 0, selectedOptionIndices: [0], freeText: ' Both ' },
+ { questionIndex: 1, selectedOptionIndices: [] },
+ ],
+ },
+ context: NO_TOOLS,
+ });
+
+ expect(completion.answerText).toBe('Which plan?\nBoth');
+ });
+
+ it.each([
+ ['no answer at all', { answers: [] }],
+ [
+ 'only blank answers',
+ {
+ answers: [
+ { questionIndex: 0, selectedOptionIndices: [], freeText: ' ' },
+ ],
+ },
+ ],
+ [
+ 'an unknown question',
+ { answers: [{ questionIndex: 5, selectedOptionIndices: [0] }] },
+ ],
+ [
+ 'an unknown option',
+ { answers: [{ questionIndex: 0, selectedOptionIndices: [2] }] },
+ ],
+ [
+ 'several options on a single-select question',
+ { answers: [{ questionIndex: 0, selectedOptionIndices: [0, 1] }] },
+ ],
+ [
+ 'the same question twice',
+ {
+ answers: [
+ { questionIndex: 0, selectedOptionIndices: [0] },
+ { questionIndex: 0, selectedOptionIndices: [1] },
+ ],
+ },
+ ],
+ ['a malformed output', { answers: 'Team' }],
+ ])('refuses %s', (_description, output) => {
+ expect(parseCall().validate(output)).toMatchObject({ isValid: false });
+ });
+
+ it('closes a skipped call with its questions', () => {
+ expect(parseCall().toSkippedToolResult()).toMatchObject({
+ result: { questions: QUESTIONS, status: 'skipped' },
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/__tests__/find-awaiting-pausing-tool-parts.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/__tests__/find-awaiting-pausing-tool-parts.util.spec.ts
new file mode 100644
index 00000000000..d97c173271d
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/__tests__/find-awaiting-pausing-tool-parts.util.spec.ts
@@ -0,0 +1,95 @@
+import { type ExtendedUIMessagePart } from 'twenty-shared/ai';
+
+import { findAwaitingPausingToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/find-awaiting-pausing-tool-parts.util';
+
+const QUESTIONS = [
+ { header: 'h', question: 'q', options: [{ label: 'a' }, { label: 'b' }] },
+];
+
+const toolPart = ({
+ toolName,
+ status,
+ toolCallId = 'call-1',
+ input = { questions: QUESTIONS },
+}: {
+ toolName: string;
+ status: 'pending' | 'answered';
+ toolCallId?: string;
+ input?: unknown;
+}): ExtendedUIMessagePart =>
+ ({
+ type: `tool-${toolName}`,
+ toolCallId,
+ state: 'output-available',
+ input,
+ output: { success: true, result: { questions: QUESTIONS, status } },
+ }) as unknown as ExtendedUIMessagePart;
+
+const textPart = { type: 'text', text: 'hello' } as ExtendedUIMessagePart;
+
+describe('findAwaitingPausingToolParts', () => {
+ it('finds the pausing tool call still waiting on an output, with its Ask', () => {
+ expect(
+ findAwaitingPausingToolParts([
+ textPart,
+ toolPart({ toolName: 'ask_questions', status: 'pending' }),
+ ]),
+ ).toEqual([
+ {
+ toolName: 'ask_questions',
+ toolCallId: 'call-1',
+ ask: { name: 'q', form: { kind: 'questions', questions: QUESTIONS } },
+ },
+ ]);
+ });
+
+ it('finds a waiting call it cannot read, without an Ask', () => {
+ expect(
+ findAwaitingPausingToolParts([
+ toolPart({
+ toolName: 'ask_questions',
+ status: 'pending',
+ input: { questions: [] },
+ }),
+ ]),
+ ).toEqual([{ toolName: 'ask_questions', toolCallId: 'call-1', ask: null }]);
+ });
+
+ it('finds every waiting call of a step, in the order they were made', () => {
+ expect(
+ findAwaitingPausingToolParts([
+ toolPart({
+ toolName: 'ask_questions',
+ status: 'pending',
+ toolCallId: 'call-1',
+ }),
+ toolPart({
+ toolName: 'ask_questions',
+ status: 'answered',
+ toolCallId: 'call-2',
+ }),
+ toolPart({
+ toolName: 'ask_questions',
+ status: 'pending',
+ toolCallId: 'call-3',
+ }),
+ ]).map((awaitingPart) => awaitingPart.toolCallId),
+ ).toEqual(['call-1', 'call-3']);
+ });
+
+ it('ignores a pausing tool call already answered', () => {
+ expect(
+ findAwaitingPausingToolParts([
+ toolPart({ toolName: 'ask_questions', status: 'answered' }),
+ ]),
+ ).toEqual([]);
+ });
+
+ it('ignores tools that do not pause, whatever they return', () => {
+ expect(
+ findAwaitingPausingToolParts([
+ toolPart({ toolName: 'search_help_center', status: 'pending' }),
+ ]),
+ ).toEqual([]);
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/__tests__/propose-email.pausing-tool.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/__tests__/propose-email.pausing-tool.spec.ts
new file mode 100644
index 00000000000..6fd3a03a41c
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/__tests__/propose-email.pausing-tool.spec.ts
@@ -0,0 +1,161 @@
+import { PROPOSE_EMAIL_PAUSING_TOOL } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/propose-email.pausing-tool';
+
+const PROPOSED_EMAIL = {
+ recipients: { to: '[email protected]', cc: '', bcc: '' },
+ subject: 'Your renewal',
+ body: 'Hi Tim,\nThanks for renewing.\n\nBest, Jane',
+ connectedAccountId: '20202020-9b3e-4c55-8f0b-7c1d2e3f4a5b',
+};
+
+const parseCall = () => {
+ const call = PROPOSE_EMAIL_PAUSING_TOOL.parseCall(PROPOSED_EMAIL);
+
+ if (call === null) {
+ throw new Error('Expected the call to parse');
+ }
+
+ return call;
+};
+
+const buildContext = (toolOutput: Record<string, unknown>) => ({
+ executeTool: jest.fn().mockResolvedValue(toolOutput),
+});
+
+describe('PROPOSE_EMAIL_PAUSING_TOOL', () => {
+ it('asks for approval of the proposed email, named after its subject', () => {
+ expect(parseCall().buildAsk()).toEqual({
+ name: 'Your renewal',
+ form: { kind: 'emailApproval', email: PROPOSED_EMAIL },
+ });
+ });
+
+ it.each([
+ ['an unknown decision', { decision: 'forward' }],
+ [
+ 'sending without a recipient',
+ {
+ decision: 'send',
+ email: {
+ ...PROPOSED_EMAIL,
+ recipients: { to: ' ', cc: '', bcc: '' },
+ },
+ },
+ ],
+ ['sending without the email', { decision: 'send' }],
+ ])('refuses %s', (_description, output) => {
+ expect(parseCall().validate(output)).toMatchObject({ isValid: false });
+ });
+
+ it('sends the edited email through send_email and says it was sent', async () => {
+ const context = buildContext({
+ success: true,
+ message: 'Email sent successfully to [email protected]',
+ result: { messageId: 'message-id' },
+ });
+ const editedEmail = { ...PROPOSED_EMAIL, subject: 'Renewal confirmed' };
+
+ const completion = await parseCall().complete({
+ output: { decision: 'send', email: editedEmail },
+ context,
+ });
+
+ expect(context.executeTool).toHaveBeenCalledWith({
+ toolName: 'send_email',
+ args: {
+ recipients: PROPOSED_EMAIL.recipients,
+ subject: 'Renewal confirmed',
+ body: '<p>Hi Tim,<br>Thanks for renewing.</p><p>Best, Jane</p>',
+ connectedAccountId: PROPOSED_EMAIL.connectedAccountId,
+ },
+ });
+ expect(completion.toolResult).toEqual({
+ success: true,
+ message: 'Email sent successfully to [email protected]',
+ result: {
+ status: 'sent',
+ email: editedEmail,
+ details: { messageId: 'message-id' },
+ },
+ });
+ expect(completion.answerText).toBe(
+ 'Send the email "Renewal confirmed" to [email protected].',
+ );
+ });
+
+ it('sends from the proposed account even when the answer names another', async () => {
+ const context = buildContext({ success: true, message: 'Email sent' });
+
+ await parseCall().complete({
+ output: {
+ decision: 'send',
+ email: {
+ ...PROPOSED_EMAIL,
+ connectedAccountId: '20202020-1111-4111-8111-111111111111',
+ },
+ },
+ context,
+ });
+
+ expect(context.executeTool).toHaveBeenCalledWith({
+ toolName: 'send_email',
+ args: expect.objectContaining({
+ connectedAccountId: PROPOSED_EMAIL.connectedAccountId,
+ }),
+ });
+ });
+
+ it('saves the email as a draft through draft_email', async () => {
+ const context = buildContext({ success: true, message: 'Draft created' });
+
+ const completion = await parseCall().complete({
+ output: { decision: 'saveDraft', email: PROPOSED_EMAIL },
+ context,
+ });
+
+ expect(context.executeTool).toHaveBeenCalledWith({
+ toolName: 'draft_email',
+ args: expect.objectContaining({ subject: 'Your renewal' }),
+ });
+ expect(completion.toolResult).toMatchObject({
+ success: true,
+ result: { status: 'drafted' },
+ });
+ });
+
+ it('tells the agent when the email could not go through', async () => {
+ const context = buildContext({
+ success: false,
+ message: 'Failed to send email',
+ error:
+ 'The connected email account does not have permission to send emails.',
+ });
+
+ const completion = await parseCall().complete({
+ output: { decision: 'send', email: PROPOSED_EMAIL },
+ context,
+ });
+
+ expect(completion.toolResult).toMatchObject({
+ success: false,
+ result: {
+ status: 'failed',
+ error:
+ 'The connected email account does not have permission to send emails.',
+ },
+ });
+ });
+
+ it('runs no tool when the email is discarded', async () => {
+ const context = buildContext({ success: true, message: '' });
+
+ const completion = await parseCall().complete({
+ output: { decision: 'discard' },
+ context,
+ });
+
+ expect(context.executeTool).not.toHaveBeenCalled();
+ expect(completion.toolResult).toMatchObject({
+ result: { status: 'discarded', email: PROPOSED_EMAIL },
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/ask-questions.pausing-tool.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/ask-questions.pausing-tool.ts
new file mode 100644
index 00000000000..5de761d26b1
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/ask-questions.pausing-tool.ts
@@ -0,0 +1,135 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import {
+ type AskQuestionAnswer,
+ type AskQuestionsToolInput,
+ type AskQuestionsToolResult,
+} from 'twenty-shared/ai';
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+import { z } from 'zod';
+
+import { definePausingTool } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/define-pausing-tool.util';
+import { askQuestionsInputSchema } from 'src/engine/metadata-modules/ai/ai-chat/tools/ask-questions.tool';
+
+type AskQuestionsToolOutput = {
+ answers: AskQuestionAnswer[];
+};
+
+const askQuestionAnswerSchema = z.object({
+ questionIndex: z.number().int(),
+ selectedOptionIndices: z.array(z.number().int()),
+ freeText: z.string().optional(),
+});
+
+const hasAnswerContent = (answer: AskQuestionAnswer) =>
+ isNonEmptyString(answer.freeText?.trim()) ||
+ isNonEmptyArray(answer.selectedOptionIndices);
+
+const buildAskQuestionsOutputSchema = ({
+ questions,
+}: AskQuestionsToolInput): z.ZodType<AskQuestionsToolOutput> =>
+ z
+ .object({ answers: z.array(askQuestionAnswerSchema) })
+ .superRefine(({ answers }, context) => {
+ const answeredQuestionIndices = new Set<number>();
+
+ for (const answer of answers) {
+ const question = questions[answer.questionIndex];
+
+ if (!isDefined(question)) {
+ context.addIssue({
+ code: 'custom',
+ message: 'Answer references an unknown question.',
+ });
+
+ continue;
+ }
+
+ if (answeredQuestionIndices.has(answer.questionIndex)) {
+ context.addIssue({
+ code: 'custom',
+ message: 'Each question can be answered only once.',
+ });
+ }
+
+ answeredQuestionIndices.add(answer.questionIndex);
+
+ if (
+ answer.selectedOptionIndices.some(
+ (optionIndex) =>
+ optionIndex < 0 || optionIndex >= question.options.length,
+ )
+ ) {
+ context.addIssue({
+ code: 'custom',
+ message: 'Answer references an unknown option.',
+ });
+ }
+
+ if (
+ question.allowMultiSelect !== true &&
+ answer.selectedOptionIndices.length > 1
+ ) {
+ context.addIssue({
+ code: 'custom',
+ message: 'This question allows only one selection.',
+ });
+ }
+ }
+
+ if (!answers.some(hasAnswerContent)) {
+ context.addIssue({
+ code: 'custom',
+ message: 'Provide at least one answer.',
+ });
+ }
+ });
+
+const buildAnswerText = ({
+ answers,
+ questions,
+}: AskQuestionsToolOutput & AskQuestionsToolInput) =>
+ answers
+ .flatMap((answer) => {
+ const question = questions[answer.questionIndex];
+ const freeText = answer.freeText?.trim();
+ const value = isNonEmptyString(freeText)
+ ? freeText
+ : answer.selectedOptionIndices
+ .map((optionIndex) => question.options[optionIndex].label)
+ .join(', ');
+
+ return isNonEmptyString(value) ? [`${question.question}\n${value}`] : [];
+ })
+ .join('\n\n');
+
+// The result keeps the shape the tool part had before answers were resolved
+// through Asks, which the chat renderer, the admin panel and the seeded runs
+// all read.
+export const ASK_QUESTIONS_PAUSING_TOOL = definePausingTool<
+ AskQuestionsToolInput,
+ AskQuestionsToolOutput
+>({
+ inputSchema: askQuestionsInputSchema,
+ outputSchema: buildAskQuestionsOutputSchema,
+ buildAsk: ({ questions }) => ({
+ name: questions[0]?.question ?? '',
+ form: { kind: 'questions', questions },
+ }),
+ complete: async ({ output: { answers }, input: { questions } }) => ({
+ toolResult: {
+ success: true,
+ message: 'User answered the questions.',
+ result: {
+ questions,
+ status: 'answered',
+ answers,
+ } satisfies AskQuestionsToolResult,
+ },
+ answerText: buildAnswerText({ answers, questions }),
+ }),
+ toSkippedToolResult: ({ questions }) => ({
+ success: true,
+ message: 'User skipped the questions and sent another message instead.',
+ result: { questions, status: 'skipped' } satisfies AskQuestionsToolResult,
+ }),
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/pausing-tools.constant.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/pausing-tools.constant.ts
new file mode 100644
index 00000000000..8ccf044e961
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/pausing-tools.constant.ts
@@ -0,0 +1,15 @@
+import {
+ ASK_QUESTIONS_TOOL_NAME,
+ PROPOSE_EMAIL_TOOL_NAME,
+} from 'twenty-shared/ai';
+
+import { ASK_QUESTIONS_PAUSING_TOOL } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/ask-questions.pausing-tool';
+import { PROPOSE_EMAIL_PAUSING_TOOL } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/propose-email.pausing-tool';
+import { type PausingTool } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool.type';
+
+// Tools whose call ends the turn until a person submits its output. Each call
+// opens an Ask, and answerAsk is the only way to answer it.
+export const PAUSING_TOOLS: ReadonlyMap<string, PausingTool> = new Map([
+ [ASK_QUESTIONS_TOOL_NAME, ASK_QUESTIONS_PAUSING_TOOL],
+ [PROPOSE_EMAIL_TOOL_NAME, PROPOSE_EMAIL_PAUSING_TOOL],
+]);
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/propose-email.pausing-tool.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/propose-email.pausing-tool.ts
new file mode 100644
index 00000000000..a3398fdf654
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/propose-email.pausing-tool.ts
@@ -0,0 +1,125 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import {
+ type EmailApprovalDecision,
+ type ProposeEmailToolResult,
+ type ProposedEmail,
+} from 'twenty-shared/ai';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+import { z } from 'zod';
+
+import { convertPlainTextToEmailHtml } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/convert-plain-text-to-email-html.util';
+import { definePausingTool } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/define-pausing-tool.util';
+import { proposeEmailInputSchema } from 'src/engine/metadata-modules/ai/ai-chat/tools/propose-email.tool';
+
+type ProposeEmailToolOutput = {
+ decision: EmailApprovalDecision;
+ email?: ProposedEmail;
+};
+
+const proposeEmailOutputSchema: z.ZodType<ProposeEmailToolOutput> = z
+ .object({
+ decision: z.enum(['send', 'saveDraft', 'discard']),
+ email: proposeEmailInputSchema.optional(),
+ })
+ .superRefine(({ decision, email }, context) => {
+ if (decision === 'send' && !isNonEmptyString(email?.recipients.to.trim())) {
+ context.addIssue({
+ code: 'custom',
+ message: 'Add at least one recipient to send the email.',
+ });
+ }
+ });
+
+const buildResult = ({
+ status,
+ email,
+ error,
+}: {
+ status: ProposeEmailToolResult['status'];
+ email: ProposedEmail;
+ error?: string;
+}): ProposeEmailToolResult => ({
+ status,
+ email,
+ ...(isDefined(error) ? { error } : {}),
+});
+
+const DECISION_TOOLS = {
+ send: { toolName: 'send_email', status: 'sent' },
+ saveDraft: { toolName: 'draft_email', status: 'drafted' },
+} as const;
+
+// Sending or drafting runs the regular email tools as the person who
+// approved, so their connected accounts and permissions decide what happens.
+export const PROPOSE_EMAIL_PAUSING_TOOL = definePausingTool<
+ ProposedEmail,
+ ProposeEmailToolOutput
+>({
+ inputSchema: proposeEmailInputSchema,
+ outputSchema: () => proposeEmailOutputSchema,
+ buildAsk: (email) => ({
+ name: email.subject.trim(),
+ form: { kind: 'emailApproval', email },
+ }),
+ complete: async ({ output: { decision, email }, input, context }) => {
+ // The person may edit what is sent, not which account sends it: the card
+ // offers no choice of account, so one in the answer is not theirs to pick.
+ const finalEmail = {
+ ...(email ?? input),
+ connectedAccountId: input.connectedAccountId,
+ };
+
+ if (decision === 'discard') {
+ return {
+ toolResult: {
+ success: true,
+ message: 'The user discarded the email.',
+ result: buildResult({ status: 'discarded', email: input }),
+ },
+ answerText: `Discard the email "${input.subject}".`,
+ };
+ }
+
+ const { toolName, status } = DECISION_TOOLS[decision];
+
+ const toolOutput = await context.executeTool({
+ toolName,
+ args: {
+ recipients: finalEmail.recipients,
+ subject: finalEmail.subject,
+ body: convertPlainTextToEmailHtml(finalEmail.body),
+ ...(isDefined(finalEmail.connectedAccountId)
+ ? { connectedAccountId: finalEmail.connectedAccountId }
+ : {}),
+ },
+ });
+
+ return {
+ toolResult: {
+ success: toolOutput.success,
+ message: toolOutput.success
+ ? toolOutput.message
+ : `The user approved the email, but it could not go through: ${toolOutput.error ?? toolOutput.message}`,
+ result: {
+ ...buildResult({
+ status: toolOutput.success ? status : 'failed',
+ email: finalEmail,
+ error: toolOutput.success ? undefined : toolOutput.error,
+ }),
+ ...(isPlainObject(toolOutput.result)
+ ? { details: toolOutput.result }
+ : {}),
+ },
+ },
+ answerText:
+ decision === 'send'
+ ? `Send the email "${finalEmail.subject}" to ${finalEmail.recipients.to}.`
+ : `Save the email "${finalEmail.subject}" as a draft.`,
+ };
+ },
+ toSkippedToolResult: (email) => ({
+ success: true,
+ message: 'User sent another message instead of deciding on the email.',
+ result: buildResult({ status: 'skipped', email }),
+ }),
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-ask.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-ask.type.ts
new file mode 100644
index 00000000000..cdd584c2f64
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-ask.type.ts
@@ -0,0 +1,6 @@
+import { type InputAskWorkspaceEntity } from 'src/modules/input-ask/standard-objects/input-ask.workspace-entity';
+
+export type PausingToolAsk = {
+ name: string;
+ form: NonNullable<InputAskWorkspaceEntity['form']>;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-call.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-call.type.ts
new file mode 100644
index 00000000000..f4de3989e0f
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-call.type.ts
@@ -0,0 +1,18 @@
+import { type PausingToolAsk } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-ask.type';
+import { type PausingToolCompletion } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-completion.type';
+import { type PausingToolCompletionContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-completion-context.type';
+
+export type PausingToolValidation =
+ | { isValid: true; output: Record<string, unknown> }
+ | { isValid: false; errorMessage: string };
+
+export type PausingToolCall = {
+ buildAsk: () => PausingToolAsk;
+ validate: (output: unknown) => PausingToolValidation;
+ // Takes an output validate accepted.
+ complete: (args: {
+ output: Record<string, unknown>;
+ context: PausingToolCompletionContext;
+ }) => Promise<PausingToolCompletion>;
+ toSkippedToolResult: () => Record<string, unknown>;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-completion-context.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-completion-context.type.ts
new file mode 100644
index 00000000000..2b00c7ec680
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-completion-context.type.ts
@@ -0,0 +1,10 @@
+import { type ToolOutput } from 'src/engine/core-modules/tool/types/tool-output.type';
+
+// Tools run as the person who answered, with their permissions, never as the
+// agent that asked.
+export type PausingToolCompletionContext = {
+ executeTool: (args: {
+ toolName: string;
+ args: Record<string, unknown>;
+ }) => Promise<ToolOutput>;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-completion.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-completion.type.ts
new file mode 100644
index 00000000000..295b475011d
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-completion.type.ts
@@ -0,0 +1,4 @@
+export type PausingToolCompletion = {
+ toolResult: Record<string, unknown>;
+ answerText: string;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-definition.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-definition.type.ts
new file mode 100644
index 00000000000..ef976a729f6
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-definition.type.ts
@@ -0,0 +1,22 @@
+import { type z } from 'zod';
+
+import { type PausingToolAsk } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-ask.type';
+import { type PausingToolCompletion } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-completion.type';
+import { type PausingToolCompletionContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-completion-context.type';
+
+export type PausingToolDefinition<TInput, TOutput> = {
+ inputSchema: z.ZodType<TInput>;
+ // The output a person may submit depends on what the call asked, so the
+ // schema is built from the call's input.
+ outputSchema: (input: TInput) => z.ZodType<TOutput>;
+ buildAsk: (input: TInput) => PausingToolAsk;
+ // Runs once the person's output is accepted, and only then: whatever the
+ // call does on the person's behalf happens here, and the tool result says
+ // what came of it.
+ complete: (args: {
+ output: TOutput;
+ input: TInput;
+ context: PausingToolCompletionContext;
+ }) => Promise<PausingToolCompletion>;
+ toSkippedToolResult: (input: TInput) => Record<string, unknown>;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool.type.ts
new file mode 100644
index 00000000000..2eeb8fbe2c0
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool.type.ts
@@ -0,0 +1,8 @@
+import { type PausingToolCall } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-call.type';
+
+// A definition with its input and output types bound per call, so tools with
+// different inputs can share one map keyed by tool name.
+export type PausingTool = {
+ isAwaitingOutput: (toolOutput: unknown) => boolean;
+ parseCall: (toolInput: unknown) => PausingToolCall | null;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/convert-plain-text-to-email-html.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/convert-plain-text-to-email-html.util.ts
new file mode 100644
index 00000000000..a6bf8f0affb
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/convert-plain-text-to-email-html.util.ts
@@ -0,0 +1,13 @@
+import { escapeHtml } from 'src/engine/core-modules/emailing-domain/utils/escape-html.util';
+
+// The approval card edits a plain-text body, while the email tools read a
+// string body as HTML, where line breaks would otherwise collapse.
+export const convertPlainTextToEmailHtml = (text: string): string =>
+ text
+ .split(/\n\s*\n/)
+ .map((paragraph) => paragraph.trim())
+ .filter((paragraph) => paragraph.length > 0)
+ .map(
+ (paragraph) => `<p>${escapeHtml(paragraph).replace(/\n/g, '<br>')}</p>`,
+ )
+ .join('');
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/define-pausing-tool.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/define-pausing-tool.util.ts
new file mode 100644
index 00000000000..4bd39a9e6fd
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/define-pausing-tool.util.ts
@@ -0,0 +1,49 @@
+import { isPlainObject } from 'twenty-shared/utils';
+
+import { type PausingTool } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool.type';
+import { type PausingToolDefinition } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-definition.type';
+
+export const definePausingTool = <
+ TInput,
+ TOutput extends Record<string, unknown>,
+>(
+ definition: PausingToolDefinition<TInput, TOutput>,
+): PausingTool => ({
+ isAwaitingOutput: (toolOutput) =>
+ isPlainObject(toolOutput) &&
+ isPlainObject(toolOutput.result) &&
+ toolOutput.result.status === 'pending',
+ parseCall: (toolInput) => {
+ const parsedInput = definition.inputSchema.safeParse(toolInput);
+
+ if (!parsedInput.success) {
+ return null;
+ }
+
+ const input = parsedInput.data;
+ const outputSchema = definition.outputSchema(input);
+
+ return {
+ buildAsk: () => definition.buildAsk(input),
+ toSkippedToolResult: () => definition.toSkippedToolResult(input),
+ validate: (output) => {
+ const parsedOutput = outputSchema.safeParse(output);
+
+ return parsedOutput.success
+ ? { isValid: true, output: parsedOutput.data }
+ : {
+ isValid: false,
+ errorMessage: parsedOutput.error.issues
+ .map((issue) => issue.message)
+ .join(' '),
+ };
+ },
+ complete: ({ output, context }) =>
+ definition.complete({
+ output: outputSchema.parse(output),
+ input,
+ context,
+ }),
+ };
+ },
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/find-awaiting-pausing-tool-parts.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/find-awaiting-pausing-tool-parts.util.ts
new file mode 100644
index 00000000000..58cd29adba2
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/find-awaiting-pausing-tool-parts.util.ts
@@ -0,0 +1,39 @@
+import { getToolName, isToolUIPart } from 'ai';
+import { type ExtendedUIMessagePart } from 'twenty-shared/ai';
+import { isDefined } from 'twenty-shared/utils';
+
+import { PAUSING_TOOLS } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/pausing-tools.constant';
+import { type PausingToolAsk } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-ask.type';
+
+// A call whose input cannot be read has no Ask: nothing can answer it.
+export type AwaitingPausingToolPart = {
+ toolName: string;
+ toolCallId: string;
+ ask: PausingToolAsk | null;
+};
+
+// A step can call several pausing tools at once: each waits on its own Ask,
+// in the order the model made the calls.
+export const findAwaitingPausingToolParts = (
+ parts: ExtendedUIMessagePart[],
+): AwaitingPausingToolPart[] =>
+ parts.flatMap((part) => {
+ if (!isToolUIPart(part)) {
+ return [];
+ }
+
+ const toolName = getToolName(part);
+ const pausingTool = PAUSING_TOOLS.get(toolName);
+
+ if (!isDefined(pausingTool) || !pausingTool.isAwaitingOutput(part.output)) {
+ return [];
+ }
+
+ return [
+ {
+ toolName,
+ toolCallId: part.toolCallId,
+ ask: pausingTool.parseCall(part.input)?.buildAsk() ?? null,
+ },
+ ];
+ });
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/parse-pausing-tool-call.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/parse-pausing-tool-call.util.ts
new file mode 100644
index 00000000000..b74f3f23b69
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/parse-pausing-tool-call.util.ts
@@ -0,0 +1,12 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { PAUSING_TOOLS } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/pausing-tools.constant';
+import { type PausingToolCall } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-call.type';
+
+export const parsePausingToolCall = (
+ toolPart: { toolName: string | null; toolInput: unknown } | null,
+): PausingToolCall | null =>
+ isDefined(toolPart?.toolName)
+ ? (PAUSING_TOOLS.get(toolPart.toolName)?.parseCall(toolPart.toolInput) ??
+ null)
+ : null;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts
index b65b29d8945..37d72c0887f 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service.ts
@@ -405,7 +405,7 @@ export class AgentAsyncExecutorService {
)?.modalities,
});
- const pausingToolNames = Object.keys(pausingTools);
+ const offeredToolNames = Object.keys(pausingTools);
const textResponse = await generateText({
instructions: `${baseSystemPrompt}\n\n${agent ? tipTapDocumentToMarkdown(agent.prompt) : ''}${toolCatalogSection}`,
@@ -414,7 +414,7 @@ export class AgentAsyncExecutorService {
messages: [...priorModelMessages, ...modelMessages],
stopWhen: (step) =>
isStepCount(AGENT_CONFIG.MAX_STEPS)(step) ||
- endsOnPausingToolCall({ steps: step.steps, pausingToolNames }) ||
+ endsOnPausingToolCall({ steps: step.steps, offeredToolNames }) ||
hasNoMoreAvailableCredits,
providerOptions,
...buildAiTelemetry({
@@ -521,7 +521,7 @@ export class AgentAsyncExecutorService {
const endsOnPausingTool = endsOnPausingToolCall({
steps: textResponse.steps,
- pausingToolNames,
+ offeredToolNames,
});
// An execution stopped on a pausing tool has no final answer to structure.
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/ends-on-pausing-tool-call.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/ends-on-pausing-tool-call.util.spec.ts
index 2976ae6d029..64214f0cc80 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/ends-on-pausing-tool-call.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/ends-on-pausing-tool-call.util.spec.ts
@@ -5,11 +5,10 @@ const stepCalling = (...toolNames: string[]) => ({
});
describe('endsOnPausingToolCall', () => {
- it('pauses when the last step calls a pausing tool', () => {
+ it('pauses when the last step calls a declared pausing tool', () => {
expect(
endsOnPausingToolCall({
steps: [stepCalling('search'), stepCalling('ask_questions')],
- pausingToolNames: ['ask_questions'],
}),
).toBe(true);
});
@@ -18,20 +17,32 @@ describe('endsOnPausingToolCall', () => {
expect(
endsOnPausingToolCall({
steps: [stepCalling('ask_questions'), stepCalling('search')],
- pausingToolNames: ['ask_questions'],
}),
).toBe(false);
});
- it('never pauses without pausing tools or steps', () => {
+ it('does not pause on a tool that is not declared as pausing', () => {
+ expect(endsOnPausingToolCall({ steps: [stepCalling('search')] })).toBe(
+ false,
+ );
+ });
+
+ it('only pauses on a pausing tool the run was offered', () => {
expect(
endsOnPausingToolCall({
steps: [stepCalling('ask_questions')],
- pausingToolNames: [],
+ offeredToolNames: [],
}),
).toBe(false);
expect(
- endsOnPausingToolCall({ steps: [], pausingToolNames: ['ask_questions'] }),
- ).toBe(false);
+ endsOnPausingToolCall({
+ steps: [stepCalling('ask_questions')],
+ offeredToolNames: ['ask_questions'],
+ }),
+ ).toBe(true);
+ });
+
+ it('never pauses without steps', () => {
+ expect(endsOnPausingToolCall({ steps: [] })).toBe(false);
});
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/ends-on-pausing-tool-call.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/ends-on-pausing-tool-call.util.ts
index a086e2d9642..217000ff9a4 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/ends-on-pausing-tool-call.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/ends-on-pausing-tool-call.util.ts
@@ -1,12 +1,17 @@
+import { PAUSING_TOOLS } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/pausing-tools.constant';
+
// Not the SDK's hasToolCall: its stop condition may return a promise, and this
// check is also read synchronously once the run returns, to report the pause.
export const endsOnPausingToolCall = ({
steps,
- pausingToolNames,
+ offeredToolNames,
}: {
steps: { toolCalls: { toolName: string }[] }[];
- pausingToolNames: string[];
+ // Narrows the pause to the pausing tools a run was actually given.
+ offeredToolNames?: string[];
}): boolean =>
- steps[steps.length - 1]?.toolCalls.some((toolCall) =>
- pausingToolNames.includes(toolCall.toolName),
+ steps[steps.length - 1]?.toolCalls.some(
+ (toolCall) =>
+ PAUSING_TOOLS.has(toolCall.toolName) &&
+ (offeredToolNames?.includes(toolCall.toolName) ?? true),
) ?? false;
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 8d8b60f6e4a..48d1c7f2762 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
@@ -43,14 +43,13 @@ import { AgentChatCancelSubscriberService } from './services/agent-chat-cancel-s
import { AgentChatStreamingService } from './services/agent-chat-streaming.service';
import { AgentChatService } from './services/agent-chat.service';
import { AgentChatThreadTargetService } from './services/agent-chat-thread-target.service';
+import { AgentChatTurnPreflightService } from './services/agent-chat-turn-preflight.service';
import { AgentTitleGenerationService } from './services/agent-title-generation.service';
import { ChatExecutionService } from './services/chat-execution.service';
import { MessagePruningService } from './services/message-pruning.service';
import { SystemPromptBuilderService } from './services/system-prompt-builder.service';
-import { AgentChatWorkflowQuestionService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-workflow-question.service';
import { InputAskModule } from 'src/modules/input-ask/input-ask.module';
-import { WorkflowRunnerModule } from 'src/modules/workflow/workflow-runner/workflow-runner.module';
@Module({
imports: [
@@ -82,13 +81,11 @@ import { WorkflowRunnerModule } from 'src/modules/workflow/workflow-runner/workf
ToolProviderModule,
DashboardToolsModule,
WorkflowToolsModule,
- WorkflowRunnerModule,
InputAskModule,
],
providers: [
AgentChatActorService,
AgentChatSharingService,
- AgentChatWorkflowQuestionService,
AiChatUsageService,
AiChatUsageResolver,
AgentChatCancelSubscriberService,
@@ -98,6 +95,7 @@ import { WorkflowRunnerModule } from 'src/modules/workflow/workflow-runner/workf
AgentChatService,
AgentChatThreadTargetService,
AgentChatStreamingService,
+ AgentChatTurnPreflightService,
WorkspaceSetupChatService,
AgentTitleGenerationService,
ChatExecutionService,
@@ -108,10 +106,12 @@ import { WorkflowRunnerModule } from 'src/modules/workflow/workflow-runner/workf
provideWorkspaceScopedRepository(FileEntity),
],
exports: [
+ AgentChatActorService,
AgentChatSharingService,
AgentChatService,
AgentChatStreamingService,
AgentChatThreadTargetService,
+ AgentChatTurnPreflightService,
TypeOrmModule.forFeature([AgentChatThreadEntity]),
],
})
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/__tests__/stream-agent-chat.job.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/__tests__/stream-agent-chat.job.spec.ts
index 3cf1cd8197a..49d2d36f198 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/__tests__/stream-agent-chat.job.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/__tests__/stream-agent-chat.job.spec.ts
@@ -74,6 +74,14 @@ const TEXT_PARTS: ModelStreamPart[] = [
const EMPTY_REPLY_PARTS: ModelStreamPart[] = [...START_PARTS, ...FINISH_PARTS];
+const QUESTIONS = [
+ {
+ header: 'Plan',
+ question: 'Which plan?',
+ options: [{ label: 'Pro' }, { label: 'Team' }],
+ },
+];
+
const PENDING_QUESTION_PARTS: ModelStreamPart[] = [
...START_PARTS,
{
@@ -85,14 +93,14 @@ const PENDING_QUESTION_PARTS: ModelStreamPart[] = [
type: 'tool-call',
toolCallId: 'tool-call-id',
toolName: ASK_QUESTIONS_TOOL_NAME,
- input: {},
+ input: { questions: QUESTIONS },
},
{
type: 'tool-result',
toolCallId: 'tool-call-id',
toolName: ASK_QUESTIONS_TOOL_NAME,
- input: {},
- output: { result: { status: 'pending' } },
+ input: { questions: QUESTIONS },
+ output: { result: { questions: QUESTIONS, status: 'pending' } },
},
...FINISH_PARTS,
];
@@ -169,7 +177,9 @@ describe('StreamAgentChatJob', () => {
inputCostPerMillionTokens: 1,
outputCostPerMillionTokens: 2,
},
+ inputAskOpenRejection,
}: {
+ inputAskOpenRejection?: Error;
workspaceFound?: boolean;
chatStream?: ReturnType<typeof createFakeChatStream>;
streamChatRejection?: Error;
@@ -268,6 +278,12 @@ describe('StreamAgentChatJob', () => {
message: { id: 'user-message-id', turnId: 'turn-id' },
}),
};
+ const inputAskWorkspaceService = {
+ open: inputAskOpenRejection
+ ? jest.fn().mockRejectedValue(inputAskOpenRejection)
+ : jest.fn().mockResolvedValue(undefined),
+ cancel: jest.fn().mockResolvedValue(true),
+ };
const job = new StreamAgentChatJob(
threadRepository as never,
workspaceRepository as never,
@@ -280,6 +296,7 @@ describe('StreamAgentChatJob', () => {
metricsService as never,
aiModelRegistryService as never,
actorService as never,
+ inputAskWorkspaceService as never,
);
const turnCounts = (key: string) =>
@@ -300,6 +317,7 @@ describe('StreamAgentChatJob', () => {
cancelCallbacks,
metricsService,
aiModelRegistryService,
+ inputAskWorkspaceService,
turnCounts,
};
};
@@ -814,6 +832,105 @@ describe('StreamAgentChatJob', () => {
expect(turnCounts('ai-chat/turn-failed')).toEqual([]);
});
+ it('opens the Ask of a turn that paused on a question and leaves the queue waiting on it', async () => {
+ const { job, inputAskWorkspaceService, agentChatStreamingService } =
+ buildJob({
+ chatStream: createFakeChatStream({ parts: PENDING_QUESTION_PARTS }),
+ });
+
+ await job.handle(jobData);
+
+ expect(inputAskWorkspaceService.open).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ inputAsk: {
+ name: 'Which plan?',
+ form: { kind: 'questions', questions: QUESTIONS },
+ threadId: 'thread-id',
+ toolCallId: 'tool-call-id',
+ assigneeId: 'member',
+ },
+ });
+ expect(
+ agentChatStreamingService.flushNextQueuedMessage,
+ ).not.toHaveBeenCalled();
+ });
+
+ it('opens no Ask for a turn that did not pause', async () => {
+ const { job, inputAskWorkspaceService } = buildJob();
+
+ await job.handle(jobData);
+
+ expect(inputAskWorkspaceService.open).not.toHaveBeenCalled();
+ });
+
+ it('fails the turn, leaving it retryable, when its Ask cannot be opened', async () => {
+ const { job, publishedEvents, threadRepository, turnCounts } = buildJob({
+ chatStream: createFakeChatStream({ parts: PENDING_QUESTION_PARTS }),
+ inputAskOpenRejection: new Error('Ask insert failed'),
+ });
+
+ await expect(job.handle(jobData)).rejects.toThrow('Ask insert failed');
+
+ expect(threadRepository.update).toHaveBeenCalledWith(
+ 'workspace-id',
+ { id: 'thread-id', activeStreamId: 'stream-id' },
+ {
+ lastStreamError: expect.objectContaining({
+ message: 'Ask insert failed',
+ }),
+ },
+ );
+ expect(publishedEvents.map((event) => event.type)).toContain(
+ 'stream-error',
+ );
+ expect(turnCounts('ai-chat/turn-completed')).toEqual([]);
+ });
+
+ it('cancels the Asks it opened when a later one of the turn cannot be opened', async () => {
+ const askQuestionsCallParts = (toolCallId: string): ModelStreamPart[] => [
+ {
+ type: 'tool-input-start',
+ id: toolCallId,
+ toolName: ASK_QUESTIONS_TOOL_NAME,
+ },
+ {
+ type: 'tool-call',
+ toolCallId,
+ toolName: ASK_QUESTIONS_TOOL_NAME,
+ input: { questions: QUESTIONS },
+ },
+ {
+ type: 'tool-result',
+ toolCallId,
+ toolName: ASK_QUESTIONS_TOOL_NAME,
+ input: { questions: QUESTIONS },
+ output: { result: { questions: QUESTIONS, status: 'pending' } },
+ },
+ ];
+ const { job, inputAskWorkspaceService } = buildJob({
+ chatStream: createFakeChatStream({
+ parts: [
+ ...START_PARTS,
+ ...askQuestionsCallParts('first-call-id'),
+ ...askQuestionsCallParts('second-call-id'),
+ ...FINISH_PARTS,
+ ],
+ }),
+ });
+
+ inputAskWorkspaceService.open
+ .mockResolvedValueOnce(undefined)
+ .mockRejectedValueOnce(new Error('Ask insert failed'));
+
+ await expect(job.handle(jobData)).rejects.toThrow('Ask insert failed');
+
+ expect(inputAskWorkspaceService.cancel).toHaveBeenCalledTimes(1);
+ expect(inputAskWorkspaceService.cancel).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ match: { threadId: 'thread-id', toolCallId: 'first-call-id' },
+ });
+ });
+
it('counts an aborted turn as cancelled rather than leaving it unaccounted', async () => {
const { job, turnCounts } = buildJob({
chatStream: createFakeChatStream({
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat.job.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat.job.ts
index e2603239284..7c176107f66 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat.job.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat.job.ts
@@ -36,6 +36,10 @@ import {
AiExceptionCode,
} from 'src/engine/metadata-modules/ai/ai.exception';
import { AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
+import {
+ type AwaitingPausingToolPart,
+ findAwaitingPausingToolParts,
+} from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/find-awaiting-pausing-tool-parts.util';
import { AgentChatCancelSubscriberService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-cancel-subscriber.service';
import { AgentChatEventPublisherService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-event-publisher.service';
import { AgentChatStreamHeartbeatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-stream-heartbeat.service';
@@ -47,7 +51,6 @@ import {
classifyAgentChatTurnOutcome,
resolveSupersededTurnOutcome,
} from 'src/engine/metadata-modules/ai/ai-chat/utils/classify-agent-chat-turn-outcome.util';
-import { findPendingQuestionPart } from 'src/engine/metadata-modules/ai/ai-chat/utils/find-pending-question-part.util';
import { AGENT_CHAT_CHECKPOINT_INTERVAL_MS } from 'src/engine/metadata-modules/ai/ai-chat/constants/agent-chat-checkpoint-interval-ms.constant';
import { getCancelChannel } from 'src/engine/metadata-modules/ai/ai-chat/utils/get-cancel-channel.util';
import { mapErrorToStreamError } from 'src/engine/metadata-modules/ai/ai-chat/utils/map-error-to-stream-error.util';
@@ -58,6 +61,7 @@ import type { AiModelConfig } from 'src/engine/metadata-modules/ai/ai-models/typ
import { STREAM_AGENT_CHAT_JOB_NAME } from './stream-agent-chat-job-name.constant';
import { type StreamAgentChatJobData } from './stream-agent-chat-job.types';
import { getChatModelId } from 'src/engine/metadata-modules/ai/ai-models/utils/get-chat-model-id.util';
+import { InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-service';
export { STREAM_AGENT_CHAT_JOB_NAME, type StreamAgentChatJobData };
@@ -75,6 +79,10 @@ export class StreamAgentChatJob {
// handle(), which would otherwise count the same turn a second time.
private hasRecordedTurnOutcome = false;
+ // Set once the turn has paused on an Ask, which is what the queue waits on:
+ // a queued message drained now would bypass the answer it is waiting for.
+ private isAwaitingInput = false;
+
constructor(
@InjectAgentHistoryRepository('agentChatThread')
private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,
@@ -89,6 +97,7 @@ export class StreamAgentChatJob {
private readonly metricsService: MetricsService,
private readonly aiModelRegistryService: AiModelRegistryService,
private readonly actorService: AgentChatActorService,
+ private readonly inputAskWorkspaceService: InputAskWorkspaceService,
) {}
@Process(STREAM_AGENT_CHAT_JOB_NAME)
@@ -250,7 +259,7 @@ export class StreamAgentChatJob {
)
.catch(() => {});
- if (!abortController.signal.aborted) {
+ if (!abortController.signal.aborted && !this.isAwaitingInput) {
await this.agentChatStreamingService
.flushNextQueuedMessage({
threadId: data.threadId,
@@ -816,9 +825,9 @@ export class StreamAgentChatJob {
(part) => part.type === 'text' && isNonEmptyString(part.text),
);
- const pendingQuestionPart = findPendingQuestionPart(responseMessage.parts);
+ const awaitingParts = findAwaitingPausingToolParts(responseMessage.parts);
- if ((isAborted || !hasText) && !isDefined(pendingQuestionPart)) {
+ if ((isAborted || !hasText) && awaitingParts.length === 0) {
this.logAssistantTurnWithoutText({
responseMessage,
isAborted,
@@ -839,7 +848,7 @@ export class StreamAgentChatJob {
const outcome = classifyAgentChatTurnOutcome({
hasText,
isAborted,
- isAwaitingUserAnswer: isDefined(pendingQuestionPart),
+ isAwaitingUserAnswer: awaitingParts.length > 0,
outOfCredits,
});
@@ -877,9 +886,6 @@ export class StreamAgentChatJob {
totalCacheCreationTokens,
contextWindowTokens: modelConfig.contextWindowTokens,
conversationSize: lastStepConversationSize,
- pendingQuestionMessageId: isDefined(pendingQuestionPart)
- ? assistantMessageId
- : null,
},
});
@@ -887,6 +893,13 @@ export class StreamAgentChatJob {
return resolveSupersededTurnOutcome(outcome);
}
+ await this.openAsksForAwaitingParts({
+ awaitingParts,
+ threadId,
+ workspaceId,
+ workspaceMemberId,
+ });
+
await this.agentChatService.notifyThreadUsageUpdated({
threadBefore: threadBeforeUsage,
workspaceMemberId,
@@ -896,6 +909,56 @@ export class StreamAgentChatJob {
return outcome;
}
+ // Pausing is only complete once every waiting call has its Ask: without
+ // one nothing can answer that call, so failing here fails the turn, which
+ // leaves it retryable rather than silently stuck. Every call is read before
+ // any Ask opens, and the Asks open in the order of the calls.
+ private async openAsksForAwaitingParts({
+ awaitingParts,
+ threadId,
+ workspaceId,
+ workspaceMemberId,
+ }: {
+ awaitingParts: AwaitingPausingToolPart[];
+ threadId: string;
+ workspaceId: string;
+ workspaceMemberId: string;
+ }): Promise<void> {
+ const inputAsks = awaitingParts.map(({ toolName, toolCallId, ask }) => {
+ if (!isDefined(ask)) {
+ throw new AiException(
+ `The ${toolName} call could not be read`,
+ AiExceptionCode.INVALID_TOOL_CALL_OUTPUT,
+ );
+ }
+
+ return { ...ask, threadId, toolCallId, assigneeId: workspaceMemberId };
+ });
+
+ const openedToolCallIds: string[] = [];
+
+ try {
+ for (const inputAsk of inputAsks) {
+ await this.inputAskWorkspaceService.open({ workspaceId, inputAsk });
+ openedToolCallIds.push(inputAsk.toolCallId);
+ }
+ } catch (error) {
+ // A retry replaces this turn's calls, so the Asks already opened for them
+ // would wait on calls that no longer exist.
+ for (const toolCallId of openedToolCallIds) {
+ await this.inputAskWorkspaceService
+ .cancel({ workspaceId, match: { threadId, toolCallId } })
+ .catch(() => false);
+ }
+
+ throw error;
+ }
+
+ if (inputAsks.length > 0) {
+ this.isAwaitingInput = true;
+ }
+ }
+
private logAssistantTurnWithoutText({
responseMessage,
isAborted,
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 718dd58fcb3..128322c0291 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 { AgentChatTurnPreflightService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-turn-preflight.service';
const WORKSPACE_ID = 'workspace';
const THREAD_ID = 'thread';
@@ -77,7 +78,6 @@ const buildResolver = () => {
streamAgentChat: jest
.fn()
.mockResolvedValue({ queued: false, messageId: 'message' }),
- answerPendingQuestionAndResumeStream: jest.fn(),
reapDeadStream: jest.fn().mockResolvedValue(null),
};
const events = {
@@ -94,19 +94,20 @@ const buildResolver = () => {
{} as never,
recordEvents as never,
);
- const workflowQuestions = { answer: jest.fn() };
const resolver = new AgentChatResolver(
chatService,
sharing as never,
streaming as never,
events as never,
{} as never,
- { assertAiExecutionAllowed: jest.fn() } as never,
- {
- getAvailableModels: () => ['model'],
- validateModelAvailability: jest.fn(),
- } as never,
- workflowQuestions as never,
+ new AgentChatTurnPreflightService(
+ {
+ getAvailableModels: () => ['model'],
+ validateModelAvailability: jest.fn(),
+ } as never,
+ chatService,
+ { assertAiExecutionAllowed: jest.fn() } as never,
+ ),
threadLifecycle,
);
return {
@@ -157,7 +158,6 @@ describe('Shared conversation API boundaries', () => {
it.each([
'send',
- 'answer',
'rename',
'archive',
'unarchive',
@@ -181,17 +181,6 @@ describe('Shared conversation API boundaries', () => {
'member',
workspace,
),
- answer: () =>
- resolver.answerAgentChatQuestion(
- THREAD_ID,
- 'message',
- [],
- undefined,
- null,
- VIEWER_ID,
- 'member',
- workspace,
- ),
rename: () =>
resolver.renameChatThread(THREAD_ID, 'Changed', VIEWER_ID, workspace),
archive: () =>
@@ -218,9 +207,6 @@ describe('Shared conversation API boundaries', () => {
expect(context.threadRepository.delete).not.toHaveBeenCalled();
expect(context.messages.delete).not.toHaveBeenCalled();
expect(context.streaming.streamAgentChat).not.toHaveBeenCalled();
- expect(
- context.streaming.answerPendingQuestionAndResumeStream,
- ).not.toHaveBeenCalled();
expect(context.events.publish).not.toHaveBeenCalled();
expect(context.redis.getClient).not.toHaveBeenCalled();
},
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat.resolver.ts
index faa695cfb03..2ae89e32897 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat.resolver.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat.resolver.ts
@@ -2,8 +2,6 @@ import { AuthWorkspaceMemberId } from 'src/engine/decorators/auth/auth-workspace
import { UserAuthGuard } from 'src/engine/guards/user-auth.guard';
import { AgentChatThreadLifecycleService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-lifecycle.service';
import { AgentChatSharingService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service';
-import { AgentChatWorkflowQuestionService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-workflow-question.service';
-import { isWorkflowRunThread } from 'src/engine/metadata-modules/ai/ai-chat/utils/is-workflow-run-thread.util';
import { UseFilters, UseGuards, UseInterceptors } from '@nestjs/common';
import {
Args,
@@ -29,7 +27,6 @@ import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.g
import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
import { AgentMessageDTO } from 'src/engine/metadata-modules/ai/ai-agent-execution/dtos/agent-message.dto';
import { type BrowsingContextType } from 'src/engine/metadata-modules/ai/ai-agent/types/browsing-context.type';
-import { AgentChatQuestionAnswerInput } from 'src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-question-answer.input';
import { AgentChatThreadDTO } from 'src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-thread.dto';
import { FileAttachmentInput } from 'src/engine/metadata-modules/ai/ai-chat/dtos/file-attachment.input';
import { AiSystemPromptPreviewDTO } from 'src/engine/metadata-modules/ai/ai-chat/dtos/ai-system-prompt-preview.dto';
@@ -38,12 +35,10 @@ import { SendChatMessageResultDTO } from 'src/engine/metadata-modules/ai/ai-chat
import { AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
import { AgentChatEventPublisherService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-event-publisher.service';
import { AgentChatStreamingService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service';
+import { AgentChatTurnPreflightService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-turn-preflight.service';
import { AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
import { SystemPromptBuilderService } from 'src/engine/metadata-modules/ai/ai-chat/services/system-prompt-builder.service';
import { tagAiChatStreamScope } from 'src/engine/metadata-modules/ai/ai-chat/utils/tag-ai-chat-stream-scope.util';
-import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
-import { AiBillingService } from 'src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service';
-import { AiModelRegistryService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';
import {
AiException,
AiExceptionCode,
@@ -51,7 +46,6 @@ import {
import { BillingGraphqlApiExceptionFilter } from 'src/engine/core-modules/billing/filters/billing-graphql-api-exception.filter';
import { UsageLimitGraphqlApiExceptionFilter } from 'src/engine/core-modules/usage-limit/filters/usage-limit-graphql-api-exception.filter';
import { AiGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules/ai/interceptors/ai-graphql-api-exception.interceptor';
-import { getChatModelId } from 'src/engine/metadata-modules/ai/ai-models/utils/get-chat-model-id.util';
import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filters/auth-graphql-api-exception.filter';
@UseGuards(
@@ -73,9 +67,7 @@ export class AgentChatResolver {
private readonly agentChatStreamingService: AgentChatStreamingService,
private readonly eventPublisherService: AgentChatEventPublisherService,
private readonly systemPromptBuilderService: SystemPromptBuilderService,
- private readonly aiBillingService: AiBillingService,
- private readonly aiModelRegistryService: AiModelRegistryService,
- private readonly agentChatWorkflowQuestionService: AgentChatWorkflowQuestionService,
+ private readonly turnPreflightService: AgentChatTurnPreflightService,
private readonly threadLifecycleService: AgentChatThreadLifecycleService,
) {}
@@ -187,30 +179,12 @@ export class AgentChatResolver {
@AuthWorkspaceMemberId() workspaceMemberId: string,
@AuthWorkspace() workspace: WorkspaceEntity,
): Promise<SendChatMessageResultDTO> {
- if (this.aiModelRegistryService.getAvailableModels().length === 0) {
- throw new AiException(
- 'No AI models are available. Configure at least one AI provider.',
- AiExceptionCode.API_KEY_NOT_CONFIGURED,
- );
- }
-
- const resolvedModelId = getChatModelId({
- requestedModelId: modelId,
- workspace,
- });
-
- this.aiModelRegistryService.validateModelAvailability(resolvedModelId);
-
- const thread = await this.agentChatService.getWritableThread({
+ const thread = await this.turnPreflightService.assertCanStartChatTurn({
threadId,
+ modelId,
+ userWorkspaceId,
workspaceMemberId,
- workspaceId: workspace.id,
- });
-
- await this.aiBillingService.assertAiExecutionAllowed({
- workspaceId: workspace.id,
- operationType: UsageOperationType.AI_CHAT_TOKEN,
- spenders: { userWorkspaceId },
+ workspace,
});
if (isDefined(thread.archivedAt)) {
@@ -234,10 +208,7 @@ export class AgentChatResolver {
}
}
- if (
- isNonEmptyString(thread.activeStreamId) ||
- isDefined(thread.pendingQuestionMessageId)
- ) {
+ if (isNonEmptyString(thread.activeStreamId)) {
const queuedMessage = await this.agentChatService.queueMessage({
threadId,
text,
@@ -302,27 +273,12 @@ export class AgentChatResolver {
@AuthWorkspaceMemberId() workspaceMemberId: string,
@AuthWorkspace() workspace: WorkspaceEntity,
): Promise<SendChatMessageResultDTO> {
- if (this.aiModelRegistryService.getAvailableModels().length === 0) {
- throw new AiException(
- 'No AI models are available. Configure at least one AI provider.',
- AiExceptionCode.API_KEY_NOT_CONFIGURED,
- );
- }
-
- this.aiModelRegistryService.validateModelAvailability(
- getChatModelId({ requestedModelId: modelId, workspace }),
- );
-
- await this.agentChatService.getWritableThread({
+ await this.turnPreflightService.assertCanStartChatTurn({
threadId,
+ modelId,
+ userWorkspaceId,
workspaceMemberId,
- workspaceId: workspace.id,
- });
-
- await this.aiBillingService.assertAiExecutionAllowed({
- workspaceId: workspace.id,
- operationType: UsageOperationType.AI_CHAT_TOKEN,
- spenders: { userWorkspaceId },
+ workspace,
});
const result = await this.agentChatStreamingService.retryLastFailedTurn({
@@ -347,94 +303,6 @@ export class AgentChatResolver {
};
}
- @Mutation(() => SendChatMessageResultDTO)
- async answerAgentChatQuestion(
- @Args('threadId', { type: () => UUIDScalarType }) threadId: string,
- @Args('messageId', { type: () => UUIDScalarType }) messageId: string,
- @Args('answers', { type: () => [AgentChatQuestionAnswerInput] })
- answers: AgentChatQuestionAnswerInput[],
- @Args('modelId', { type: () => String, nullable: true })
- modelId: string | undefined,
- @Args('fileAttachments', {
- type: () => [FileAttachmentInput],
- nullable: true,
- })
- fileAttachments: FileAttachmentInput[] | null,
- @AuthUserWorkspaceId() userWorkspaceId: string,
- @AuthWorkspaceMemberId() workspaceMemberId: string,
- @AuthWorkspace() workspace: WorkspaceEntity,
- ): Promise<SendChatMessageResultDTO> {
- const readableThread = await this.sharingService.getReadableThread({
- threadId,
- workspaceMemberId,
- workspaceId: workspace.id,
- });
-
- // A workflow agent's conversation is otherwise read-only: its answer
- // resumes the run rather than a chat stream, so no chat model is involved.
- if (isWorkflowRunThread(readableThread)) {
- await this.agentChatWorkflowQuestionService.answer({
- thread: readableThread,
- messageId,
- answers,
- fileAttachments: fileAttachments ?? undefined,
- userWorkspaceId,
- workspaceId: workspace.id,
- });
-
- return { messageId, queued: false };
- }
-
- if (this.aiModelRegistryService.getAvailableModels().length === 0) {
- throw new AiException(
- 'No AI models are available. Configure at least one AI provider.',
- AiExceptionCode.API_KEY_NOT_CONFIGURED,
- );
- }
-
- const resolvedModelId = getChatModelId({
- requestedModelId: modelId,
- workspace,
- });
-
- this.aiModelRegistryService.validateModelAvailability(resolvedModelId);
-
- await this.agentChatService.getWritableThread({
- threadId,
- workspaceMemberId,
- workspaceId: workspace.id,
- });
-
- await this.aiBillingService.assertAiExecutionAllowed({
- workspaceId: workspace.id,
- operationType: UsageOperationType.AI_CHAT_TOKEN,
- spenders: { userWorkspaceId },
- });
-
- const { streamId, turnId } =
- await this.agentChatStreamingService.answerPendingQuestionAndResumeStream(
- {
- threadId,
- messageId,
- answers,
- userWorkspaceId,
- workspaceMemberId,
- workspace,
- modelId,
- fileAttachments: fileAttachments ?? undefined,
- },
- );
-
- tagAiChatStreamScope({
- streamId,
- turnId,
- threadId,
- workspaceId: workspace.id,
- });
-
- return { messageId, queued: false, streamId };
- }
-
@Mutation(() => Boolean)
async stopAgentChatStream(
@Args('threadId', { type: () => UUIDScalarType }) threadId: string,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-actor.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-actor.service.spec.ts
index 4a273d2e57f..ff484c551bc 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-actor.service.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-actor.service.spec.ts
@@ -237,7 +237,7 @@ describe('Chat execution sender', () => {
});
});
it.each([null, 'other-app'])(
- 'rejects answering an application question from a different context (%s)',
+ 'rejects resolving an application tool call from a different context (%s)',
async (applicationId) => {
const { service, message } = build();
message.senderApplicationId = 'original-app';
@@ -249,14 +249,14 @@ describe('Chat execution sender', () => {
userWorkspaceId: 'sender',
application: applicationId ? { id: applicationId } : undefined,
} as never,
- () => service.authorizeQuestionAnswer(job),
+ () => service.authorizeToolCallResolution(job),
),
- ).rejects.toMatchObject({ code: 'INVALID_QUESTION_ANSWER' });
+ ).rejects.toMatchObject({ code: 'TOOL_CALL_RESOLUTION_FORBIDDEN' });
},
);
it.each([null, 'original-app'])(
- 'allows another participant to answer in the same application context (%s)',
+ 'allows another participant to resolve in the same application context (%s)',
async (applicationId) => {
const { service, message } = build();
message.senderApplicationId = applicationId;
@@ -268,16 +268,18 @@ describe('Chat execution sender', () => {
userWorkspaceId: 'another-participant',
application: applicationId ? { id: applicationId } : undefined,
} as never,
- () => service.authorizeQuestionAnswer(job),
+ () => service.authorizeToolCallResolution(job),
),
).resolves.toBeUndefined();
},
);
- it('rejects an answer without an authenticated request context', async () => {
+ it('rejects a resolution without an authenticated request context', async () => {
const { service } = build();
- await expect(service.authorizeQuestionAnswer(job)).rejects.toMatchObject({
- code: 'INVALID_QUESTION_ANSWER',
+ await expect(
+ service.authorizeToolCallResolution(job),
+ ).rejects.toMatchObject({
+ code: 'TOOL_CALL_RESOLUTION_FORBIDDEN',
});
});
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-sharing.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-sharing.service.spec.ts
index 4995a7ad5bf..8931cfb7fe1 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-sharing.service.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-sharing.service.spec.ts
@@ -277,14 +277,13 @@ describe('Conversation common record access', () => {
});
it.each(['update', 'delete', 'soft-delete', 'restore'] as const)(
- 'refuses %s on a workflow run conversation while still letting its readers read it',
+ 'lets whoever may %s a workflow run conversation do so, like any other',
async (operation) => {
const { service, thread } = buildService();
thread.workflowRunId = 'workflow-run';
- await expect(service.getReadableThread(args)).resolves.toBeDefined();
await expect(
service.getThreadWithAccess({ ...args, operationType: operation }),
- ).rejects.toMatchObject({ code: 'WORKFLOW_RUN_THREAD_READ_ONLY' });
+ ).resolves.toBe(thread);
},
);
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.answer.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.answer.spec.ts
deleted file mode 100644
index a324b081ff4..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.answer.spec.ts
+++ /dev/null
@@ -1,336 +0,0 @@
-import { AgentChatStreamRecoveryService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-stream-recovery.service';
-import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
-import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';
-import { AgentChatStreamingService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service';
-
-describe('AgentChatStreamingService answerPendingQuestionAndResumeStream', () => {
- const workspace = { id: 'workspace-id' } as WorkspaceEntity;
-
- const thread = {
- id: 'thread-id',
- title: 'Thread',
- conversationSize: 0,
- activeStreamId: null,
- lastStreamError: null,
- pendingQuestionMessageId: 'question-message-id',
- };
-
- const buildService = () => {
- const publishedEvents: Array<{ type: string }> = [];
- const threadRepository = {
- findOne: jest.fn().mockResolvedValue(thread),
- findOneOrFail: jest.fn().mockResolvedValue(thread),
- update: jest.fn().mockResolvedValue({ affected: 1 }),
- };
- const messageQueueService = { add: jest.fn().mockResolvedValue(undefined) };
- const fileRepository = { find: jest.fn().mockResolvedValue([]) };
- const agentChatService = {
- getWritableThread: jest
- .fn()
- .mockImplementation(() => threadRepository.findOne()),
- resolvePendingQuestion: jest.fn().mockResolvedValue({
- turnId: 'turn-id',
- answerText: 'Which option?\nFirst option',
- rollback: { partId: 'part-id', previousOutput: {} },
- }),
- restorePendingQuestion: jest.fn().mockResolvedValue(undefined),
- getMessagesForThread: jest.fn().mockResolvedValue([]),
- addMessage: jest
- .fn()
- .mockResolvedValue({ id: 'file-message-id', turnId: 'answer-turn-id' }),
- deleteMessage: jest.fn().mockResolvedValue(undefined),
- };
- const eventPublisherService = {
- publish: jest.fn().mockImplementation(({ event }) => {
- publishedEvents.push(event);
-
- return Promise.resolve();
- }),
- resetStreamState: jest.fn().mockResolvedValue(undefined),
- };
- const streamHeartbeatService = {
- markClaimed: jest.fn().mockResolvedValue(undefined),
- isAlive: jest.fn().mockResolvedValue(true),
- clear: jest.fn().mockResolvedValue(undefined),
- };
-
- const metricsService = { incrementCounterBy: jest.fn() };
-
- const actorService = {
- authorizeQuestionAnswer: jest.fn().mockResolvedValue(undefined),
- };
- const service = new AgentChatStreamingService(
- threadRepository as never,
- fileRepository as never,
- messageQueueService as never,
- agentChatService as never,
- eventPublisherService as never,
- { signFileByIdUrl: jest.fn() } as never,
- streamHeartbeatService as never,
- metricsService as never,
- new AgentChatStreamRecoveryService(
- threadRepository as never,
- streamHeartbeatService as never,
- eventPublisherService as never,
- metricsService as never,
- ),
- actorService as never,
- );
-
- return {
- service,
- actorService,
- threadRepository,
- fileRepository,
- messageQueueService,
- agentChatService,
- eventPublisherService,
- streamHeartbeatService,
- publishedEvents,
- };
- };
-
- const answerArguments = {
- workspaceMemberId: 'member',
- threadId: 'thread-id',
- messageId: 'question-message-id',
- answers: [{ questionIndex: 0, selectedOptionIndices: [0] }],
- userWorkspaceId: 'user-workspace-id',
- workspace,
- };
-
- it.each([
- { answers: [] },
- {
- answers: [
- { questionIndex: 0, selectedOptionIndices: [], freeText: ' ' },
- ],
- },
- ])(
- 'rejects an empty answer without changing the question or queue',
- async ({ answers }) => {
- const {
- service,
- agentChatService,
- messageQueueService,
- streamHeartbeatService,
- } = buildService();
- await expect(
- service.answerPendingQuestionAndResumeStream({
- ...answerArguments,
- answers,
- }),
- ).rejects.toMatchObject({ code: 'INVALID_QUESTION_ANSWER' });
- expect(agentChatService.resolvePendingQuestion).not.toHaveBeenCalled();
- expect(agentChatService.addMessage).not.toHaveBeenCalled();
- expect(messageQueueService.add).not.toHaveBeenCalled();
- expect(streamHeartbeatService.markClaimed).not.toHaveBeenCalled();
- },
- );
-
- it('leaves the pending question untouched when application authorization fails', async () => {
- const {
- service,
- actorService,
- agentChatService,
- messageQueueService,
- streamHeartbeatService,
- } = buildService();
- actorService.authorizeQuestionAnswer.mockRejectedValue(
- new Error('Application context changed'),
- );
- await expect(
- service.answerPendingQuestionAndResumeStream(answerArguments),
- ).rejects.toThrow('Application context changed');
- expect(agentChatService.resolvePendingQuestion).not.toHaveBeenCalled();
- expect(agentChatService.addMessage).not.toHaveBeenCalled();
- expect(messageQueueService.add).not.toHaveBeenCalled();
- expect(streamHeartbeatService.markClaimed).not.toHaveBeenCalled();
- });
-
- it('marks the heartbeat before the pending question claims the thread', async () => {
- const { service, agentChatService, streamHeartbeatService } =
- buildService();
-
- const result =
- await service.answerPendingQuestionAndResumeStream(answerArguments);
-
- expect(result).toEqual({
- streamId: expect.any(String),
- turnId: 'answer-turn-id',
- });
- expect(streamHeartbeatService.markClaimed).toHaveBeenCalledWith(
- result.streamId,
- );
- expect(
- streamHeartbeatService.markClaimed.mock.invocationCallOrder[0],
- ).toBeLessThan(
- agentChatService.resolvePendingQuestion.mock.invocationCallOrder[0],
- );
- expect(streamHeartbeatService.clear).not.toHaveBeenCalled();
- });
-
- it('publishes question-answered only after the resume job is enqueued', async () => {
- const { service, messageQueueService, eventPublisherService } =
- buildService();
-
- await service.answerPendingQuestionAndResumeStream(answerArguments);
-
- expect(eventPublisherService.publish).toHaveBeenCalledWith(
- expect.objectContaining({ event: { type: 'question-answered' } }),
- );
- expect(messageQueueService.add.mock.invocationCallOrder[0]).toBeLessThan(
- eventPublisherService.publish.mock.invocationCallOrder[0],
- );
- expect(messageQueueService.add).toHaveBeenCalledWith(
- expect.any(String),
- expect.objectContaining({
- threadId: 'thread-id',
- existingTurnId: 'answer-turn-id',
- }),
- );
- });
-
- it('clears the heartbeat and rethrows when there is no pending question', async () => {
- const {
- service,
- agentChatService,
- messageQueueService,
- streamHeartbeatService,
- publishedEvents,
- } = buildService();
-
- agentChatService.resolvePendingQuestion.mockRejectedValue(
- new Error('No pending question to answer'),
- );
-
- await expect(
- service.answerPendingQuestionAndResumeStream(answerArguments),
- ).rejects.toThrow('No pending question to answer');
-
- expect(streamHeartbeatService.clear).toHaveBeenCalled();
- expect(messageQueueService.add).not.toHaveBeenCalled();
- expect(publishedEvents).toHaveLength(0);
- });
-
- it('persists the attributed answer and files in a new turn before enqueueing', async () => {
- const { service, agentChatService, fileRepository, messageQueueService } =
- buildService();
-
- fileRepository.find.mockResolvedValue([
- { id: 'file-id', mimeType: 'text/csv' },
- ]);
-
- await service.answerPendingQuestionAndResumeStream({
- ...answerArguments,
- fileAttachments: [{ id: 'file-id', filename: 'contacts.csv' }],
- });
-
- expect(agentChatService.addMessage).toHaveBeenCalledWith({
- threadId: 'thread-id',
- uiMessage: {
- role: AgentMessageRole.USER,
- parts: [
- {
- type: 'text',
- text: 'Which option?\nFirst option',
- },
- {
- type: 'file',
- mediaType: 'text/csv',
- filename: 'contacts.csv',
- url: '',
- fileId: 'file-id',
- },
- ],
- },
- userWorkspaceId: 'user-workspace-id',
- workspaceId: 'workspace-id',
- });
- expect(
- agentChatService.addMessage.mock.invocationCallOrder[0],
- ).toBeLessThan(messageQueueService.add.mock.invocationCallOrder[0]);
- });
-
- it('persists the answer sender even without attachments', async () => {
- const { service, agentChatService } = buildService();
-
- await service.answerPendingQuestionAndResumeStream(answerArguments);
-
- expect(agentChatService.addMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- userWorkspaceId: 'user-workspace-id',
- uiMessage: expect.objectContaining({ role: AgentMessageRole.USER }),
- }),
- );
- });
-
- it('restores the question when persisting attachments fails', async () => {
- const { service, agentChatService, fileRepository, messageQueueService } =
- buildService();
-
- fileRepository.find.mockResolvedValue([
- { id: 'file-id', mimeType: 'text/csv' },
- ]);
- agentChatService.addMessage.mockRejectedValue(new Error('insert failed'));
-
- await expect(
- service.answerPendingQuestionAndResumeStream({
- ...answerArguments,
- fileAttachments: [{ id: 'file-id', filename: 'contacts.csv' }],
- }),
- ).rejects.toThrow('insert failed');
-
- expect(agentChatService.restorePendingQuestion).toHaveBeenCalled();
- expect(messageQueueService.add).not.toHaveBeenCalled();
- });
-
- it('deletes the persisted attachment message when enqueueing fails', async () => {
- const { service, agentChatService, fileRepository, messageQueueService } =
- buildService();
-
- fileRepository.find.mockResolvedValue([
- { id: 'file-id', mimeType: 'text/csv' },
- ]);
- messageQueueService.add.mockRejectedValue(new Error('redis down'));
-
- await expect(
- service.answerPendingQuestionAndResumeStream({
- ...answerArguments,
- fileAttachments: [{ id: 'file-id', filename: 'contacts.csv' }],
- }),
- ).rejects.toThrow('redis down');
-
- expect(agentChatService.deleteMessage).toHaveBeenCalledWith({
- messageId: 'file-message-id',
- workspaceId: 'workspace-id',
- });
- expect(agentChatService.restorePendingQuestion).toHaveBeenCalled();
- });
-
- it('restores the question and clears the heartbeat when enqueueing fails', async () => {
- const {
- service,
- agentChatService,
- messageQueueService,
- streamHeartbeatService,
- publishedEvents,
- } = buildService();
-
- messageQueueService.add.mockRejectedValue(new Error('redis down'));
-
- await expect(
- service.answerPendingQuestionAndResumeStream(answerArguments),
- ).rejects.toThrow('redis down');
-
- expect(agentChatService.restorePendingQuestion).toHaveBeenCalledWith(
- expect.objectContaining({
- threadId: 'thread-id',
- messageId: 'question-message-id',
- rollback: { partId: 'part-id', previousOutput: {} },
- }),
- );
- expect(streamHeartbeatService.clear).toHaveBeenCalled();
- expect(publishedEvents).toHaveLength(0);
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.claim.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.claim.spec.ts
index 69deffa5b71..5ec3df4a6ca 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.claim.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.claim.spec.ts
@@ -1,8 +1,18 @@
+import { isDefined } from 'twenty-shared/utils';
+
import { AgentChatStreamRecoveryService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-stream-recovery.service';
import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';
import { AgentChatStreamingService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service';
+const QUESTIONS = [
+ {
+ header: 'Plan',
+ question: 'Which plan?',
+ options: [{ label: 'Pro' }, { label: 'Team' }],
+ },
+];
+
describe('AgentChatStreamingService claim & reap', () => {
const workspace = { id: 'workspace-id' } as WorkspaceEntity;
@@ -12,7 +22,6 @@ describe('AgentChatStreamingService claim & reap', () => {
conversationSize: 0,
activeStreamId: null,
lastStreamError: null,
- pendingQuestionMessageId: null,
};
const buildService = ({
@@ -20,6 +29,11 @@ describe('AgentChatStreamingService claim & reap', () => {
claimAffected = 1,
queuedMessages = [] as unknown[],
heartbeatAlive = true,
+ pendingInputAsk = null as {
+ id: string;
+ toolCallId: string;
+ workflowRunId: string | null;
+ } | null,
} = {}) => {
const publishedEvents: Array<{ type: string }> = [];
const threadRepository = {
@@ -44,6 +58,24 @@ describe('AgentChatStreamingService claim & reap', () => {
queueMessage: jest.fn().mockResolvedValue({ id: 'queued-message-id' }),
promoteQueuedMessage: jest.fn().mockResolvedValue('turn-id'),
deleteQueuedMessage: jest.fn().mockResolvedValue(true),
+ findToolPart: jest.fn().mockResolvedValue({
+ id: 'part-id',
+ messageId: 'question-message-id',
+ turnId: 'question-turn-id',
+ toolName: 'ask_questions',
+ toolInput: { questions: QUESTIONS },
+ toolOutput: { result: { questions: QUESTIONS, status: 'pending' } },
+ }),
+ updateToolPartOutput: jest.fn().mockResolvedValue(undefined),
+ };
+ const inputAskWorkspaceService = {
+ findPendingForThread: jest
+ .fn()
+ .mockResolvedValue(isDefined(pendingInputAsk) ? [pendingInputAsk] : []),
+ hasPendingForThread: jest
+ .fn()
+ .mockResolvedValue(isDefined(pendingInputAsk)),
+ cancel: jest.fn().mockResolvedValue(true),
};
const eventPublisherService = {
publish: jest.fn().mockImplementation(({ event }) => {
@@ -89,10 +121,12 @@ describe('AgentChatStreamingService claim & reap', () => {
},
}),
} as never,
+ inputAskWorkspaceService as never,
);
return {
service,
+ inputAskWorkspaceService,
threadRepository,
messageQueueService,
agentChatService,
@@ -207,6 +241,81 @@ describe('AgentChatStreamingService claim & reap', () => {
);
});
+ it('cancels a pending chat Ask and closes its call as skipped before streaming', async () => {
+ const {
+ service,
+ inputAskWorkspaceService,
+ agentChatService,
+ messageQueueService,
+ } = buildService({
+ pendingInputAsk: {
+ id: 'input-ask-id',
+ toolCallId: 'tool-call-id',
+ workflowRunId: null,
+ },
+ });
+
+ const result = await service.streamAgentChat(sendArguments);
+
+ expect(result.queued).toBe(false);
+ expect(inputAskWorkspaceService.cancel).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ match: { threadId: 'thread-id', toolCallId: 'tool-call-id' },
+ });
+ expect(agentChatService.updateToolPartOutput).toHaveBeenCalledWith({
+ partId: 'part-id',
+ workspaceId: 'workspace-id',
+ toolOutput: expect.objectContaining({
+ result: { questions: QUESTIONS, status: 'skipped' },
+ }),
+ });
+ expect(
+ agentChatService.updateToolPartOutput.mock.invocationCallOrder[0],
+ ).toBeLessThan(messageQueueService.add.mock.invocationCallOrder[0]);
+ });
+
+ it('leaves the call as it is when another request already closed the Ask', async () => {
+ const { service, inputAskWorkspaceService, agentChatService } =
+ buildService({
+ pendingInputAsk: {
+ id: 'input-ask-id',
+ toolCallId: 'tool-call-id',
+ workflowRunId: null,
+ },
+ });
+
+ inputAskWorkspaceService.cancel.mockResolvedValue(false);
+
+ await service.streamAgentChat(sendArguments);
+
+ expect(agentChatService.updateToolPartOutput).not.toHaveBeenCalled();
+ });
+
+ it("refuses a message while the run's Ask is pending, without canceling it", async () => {
+ const {
+ service,
+ inputAskWorkspaceService,
+ agentChatService,
+ messageQueueService,
+ } = buildService({
+ pendingInputAsk: {
+ id: 'input-ask-id',
+ toolCallId: 'tool-call-id',
+ workflowRunId: 'workflow-run-id',
+ },
+ });
+
+ await expect(
+ service.streamAgentChat(sendArguments),
+ ).rejects.toMatchObject({
+ code: AiExceptionCode.THREAD_AWAITING_WORKFLOW_INPUT,
+ });
+ expect(inputAskWorkspaceService.cancel).not.toHaveBeenCalled();
+ expect(agentChatService.addMessage).not.toHaveBeenCalled();
+ expect(agentChatService.queueMessage).not.toHaveBeenCalled();
+ expect(messageQueueService.add).not.toHaveBeenCalled();
+ });
+
it('releases the claim when enqueueing the job fails', async () => {
const {
service,
@@ -230,6 +339,52 @@ describe('AgentChatStreamingService claim & reap', () => {
});
});
+ describe('flushNextQueuedMessage', () => {
+ const queuedMessages = [
+ {
+ id: 'queued-message-id',
+ parts: [{ type: 'text', textContent: 'next' }],
+ },
+ ];
+
+ it('keeps queued messages waiting behind a pending Ask', async () => {
+ const { service, agentChatService, messageQueueService } = buildService({
+ queuedMessages,
+ pendingInputAsk: {
+ id: 'input-ask-id',
+ toolCallId: 'tool-call-id',
+ workflowRunId: null,
+ },
+ });
+
+ await service.flushNextQueuedMessage({
+ threadId: 'thread-id',
+ workspaceId: 'workspace-id',
+ hasTitle: true,
+ });
+
+ expect(agentChatService.promoteQueuedMessage).not.toHaveBeenCalled();
+ expect(messageQueueService.add).not.toHaveBeenCalled();
+ });
+
+ it('promotes the next queued message once nothing is pending', async () => {
+ const { service, agentChatService, messageQueueService } = buildService({
+ queuedMessages,
+ });
+
+ await service.flushNextQueuedMessage({
+ threadId: 'thread-id',
+ workspaceId: 'workspace-id',
+ hasTitle: true,
+ });
+
+ expect(agentChatService.promoteQueuedMessage).toHaveBeenCalledWith(
+ expect.objectContaining({ messageId: 'queued-message-id' }),
+ );
+ expect(messageQueueService.add).toHaveBeenCalled();
+ });
+ });
+
describe('reapDeadStream', () => {
it('leaves a live stream alone', async () => {
const { service, threadRepository } = buildService();
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.kickoff.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.kickoff.spec.ts
index 0df4bce22d0..6eee8ed1db9 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.kickoff.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.kickoff.spec.ts
@@ -19,7 +19,6 @@ describe('AgentChatStreamingService.startHiddenKickoffStream', () => {
conversationSize: 0,
activeStreamId: null,
lastStreamError: null,
- pendingQuestionMessageId: null,
} as unknown as AgentChatThreadWorkspaceEntity;
const hiddenKickoffMessageEntity = {
@@ -99,6 +98,11 @@ describe('AgentChatStreamingService.startHiddenKickoffStream', () => {
},
}),
} as never,
+ {
+ findPendingForThread: jest.fn().mockResolvedValue([]),
+ hasPendingForThread: jest.fn().mockResolvedValue(false),
+ cancel: jest.fn().mockResolvedValue(false),
+ } as never,
);
return {
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.retry.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.retry.spec.ts
index dc6ca912eee..7809216f5a9 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.retry.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.retry.spec.ts
@@ -99,6 +99,11 @@ describe('AgentChatStreamingService.retryLastFailedTurn', () => {
},
}),
} as never,
+ {
+ findPendingForThread: jest.fn().mockResolvedValue([]),
+ hasPendingForThread: jest.fn().mockResolvedValue(false),
+ cancel: jest.fn().mockResolvedValue(false),
+ } as never,
);
return { service, threadRepository, messageQueueService, agentChatService };
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.sender.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.sender.spec.ts
index 4982ac538de..9609f07fef5 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.sender.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-streaming.service.sender.spec.ts
@@ -48,6 +48,10 @@ const build = () => {
{ incrementCounterBy: jest.fn() } as never,
{} as never,
actors as never,
+ {
+ findPendingForThread: jest.fn().mockResolvedValue([]),
+ hasPendingForThread: jest.fn().mockResolvedValue(false),
+ } as never,
);
return { service, threads, queue, chat, actors, heartbeat };
};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-workflow-question.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-workflow-question.service.spec.ts
deleted file mode 100644
index 27275cc6a94..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-workflow-question.service.spec.ts
+++ /dev/null
@@ -1,210 +0,0 @@
-import { type AskQuestionAnswer } from 'twenty-shared/ai';
-
-import { type AgentMessageEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';
-import { type AiChatFileAttachment } from 'src/engine/metadata-modules/ai/ai-chat/types/ai-chat-file-attachment.type';
-import { AgentChatWorkflowQuestionService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-workflow-question.service';
-import { type AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
-import { type AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
-import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
-import { AiExceptionCode } from 'src/engine/metadata-modules/ai/ai.exception';
-import { type PermissionsService } from 'src/engine/metadata-modules/permissions/permissions.service';
-import { type InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-service';
-import { type WorkflowRunnerWorkspaceService } from 'src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service';
-
-const WORKSPACE_ID = 'workspace-id';
-const WORKFLOW_RUN_ID = 'workflow-run-id';
-const THREAD_ID = 'thread-id';
-const QUESTION_MESSAGE_ID = 'question-message-id';
-const ANSWER_MESSAGE_ID = 'answer-message-id';
-
-const ROLLBACK = { partId: 'part-id', previousOutput: {} };
-
-describe('AgentChatWorkflowQuestionService', () => {
- const messageRepository = { delete: jest.fn() };
-
- const agentChatService = {
- resolvePendingQuestion: jest.fn(),
- addMessage: jest.fn(),
- restorePendingQuestion: jest.fn(),
- closePendingQuestion: jest.fn(),
- };
-
- const permissionsService = {
- userHasWorkspaceSettingPermission: jest.fn(),
- };
-
- const workflowRunnerWorkspaceService = {
- resumeAgentStepWithAnswer: jest.fn(),
- };
-
- const inputAskWorkspaceService = { answerForToolCall: jest.fn() };
-
- const service = new AgentChatWorkflowQuestionService(
- messageRepository as unknown as AgentHistoryRepository<AgentMessageEntity>,
- agentChatService as unknown as AgentChatService,
- permissionsService as unknown as PermissionsService,
- workflowRunnerWorkspaceService as unknown as WorkflowRunnerWorkspaceService,
- inputAskWorkspaceService as unknown as InputAskWorkspaceService,
- );
-
- const answers: AskQuestionAnswer[] = [
- { questionIndex: 0, selectedOptionIndices: [0] },
- ];
-
- const answer = (
- overrides: {
- answers?: AskQuestionAnswer[];
- fileAttachments?: AiChatFileAttachment[];
- } = {},
- ) =>
- service.answer({
- thread: {
- id: THREAD_ID,
- workflowRunId: WORKFLOW_RUN_ID,
- } as AgentChatThreadWorkspaceEntity & { workflowRunId: string },
- messageId: QUESTION_MESSAGE_ID,
- answers,
- userWorkspaceId: 'user-workspace-id',
- workspaceId: WORKSPACE_ID,
- ...overrides,
- });
-
- beforeEach(() => {
- jest.clearAllMocks();
- permissionsService.userHasWorkspaceSettingPermission.mockResolvedValue(
- true,
- );
- agentChatService.resolvePendingQuestion.mockResolvedValue({
- answerText: 'Send the quote?\nSend it',
- turnId: 'turn-id',
- toolCallId: 'tool-call-id',
- rollback: ROLLBACK,
- });
- agentChatService.addMessage.mockResolvedValue({ id: ANSWER_MESSAGE_ID });
- messageRepository.delete.mockResolvedValue(undefined);
- workflowRunnerWorkspaceService.resumeAgentStepWithAnswer.mockResolvedValue({
- status: 'AWAITING_ANSWER',
- stepId: 'agent-step-id',
- });
- });
-
- it('claims the question without a stream, records the answer and resumes the step', async () => {
- await answer();
-
- expect(agentChatService.resolvePendingQuestion).toHaveBeenCalledWith({
- threadId: THREAD_ID,
- messageId: QUESTION_MESSAGE_ID,
- answers,
- streamId: null,
- workspaceId: WORKSPACE_ID,
- });
- expect(agentChatService.addMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- threadId: THREAD_ID,
- uiMessage: {
- role: 'user',
- parts: [{ type: 'text', text: 'Send the quote?\nSend it' }],
- },
- }),
- );
- expect(
- workflowRunnerWorkspaceService.resumeAgentStepWithAnswer,
- ).toHaveBeenCalledWith({
- threadId: THREAD_ID,
- workflowRunId: WORKFLOW_RUN_ID,
- workspaceId: WORKSPACE_ID,
- });
- expect(messageRepository.delete).not.toHaveBeenCalled();
- expect(agentChatService.restorePendingQuestion).not.toHaveBeenCalled();
- expect(inputAskWorkspaceService.answerForToolCall).toHaveBeenCalledWith({
- workspaceId: WORKSPACE_ID,
- threadId: THREAD_ID,
- toolCallId: 'tool-call-id',
- response: { answers, answerText: 'Send the quote?\nSend it' },
- });
- });
-
- it('refuses an answer that says nothing', async () => {
- await expect(
- answer({
- answers: [
- { questionIndex: 0, selectedOptionIndices: [], freeText: ' ' },
- ],
- }),
- ).rejects.toMatchObject({ code: AiExceptionCode.INVALID_QUESTION_ANSWER });
- expect(agentChatService.resolvePendingQuestion).not.toHaveBeenCalled();
- });
-
- it('refuses attachments rather than dropping them', async () => {
- await expect(
- answer({
- fileAttachments: [{ id: 'file-id', filename: 'quote.pdf' }],
- }),
- ).rejects.toMatchObject({ code: AiExceptionCode.INVALID_QUESTION_ANSWER });
- expect(agentChatService.resolvePendingQuestion).not.toHaveBeenCalled();
- });
-
- it('refuses someone without the Workflows permission before claiming anything', async () => {
- permissionsService.userHasWorkspaceSettingPermission.mockResolvedValue(
- false,
- );
-
- await expect(answer()).rejects.toMatchObject({
- code: AiExceptionCode.WORKFLOW_RUN_QUESTION_FORBIDDEN,
- });
- expect(agentChatService.resolvePendingQuestion).not.toHaveBeenCalled();
- });
-
- it('gives the question back when the step has asked but is not parked yet', async () => {
- workflowRunnerWorkspaceService.resumeAgentStepWithAnswer.mockResolvedValue({
- status: 'NOT_YET_AWAITING',
- });
-
- await expect(answer()).rejects.toMatchObject({
- code: AiExceptionCode.QUESTION_NOT_PENDING,
- });
- expect(messageRepository.delete).toHaveBeenCalledWith(WORKSPACE_ID, {
- id: ANSWER_MESSAGE_ID,
- });
- expect(agentChatService.restorePendingQuestion).toHaveBeenCalledWith({
- threadId: THREAD_ID,
- messageId: QUESTION_MESSAGE_ID,
- streamId: null,
- workspaceId: WORKSPACE_ID,
- rollback: ROLLBACK,
- });
- expect(agentChatService.closePendingQuestion).not.toHaveBeenCalled();
- });
-
- it('closes a question nothing can resume any more', async () => {
- workflowRunnerWorkspaceService.resumeAgentStepWithAnswer.mockResolvedValue({
- status: 'NO_LONGER_AWAITING',
- });
-
- await expect(answer()).rejects.toMatchObject({
- code: AiExceptionCode.QUESTION_NOT_PENDING,
- });
- expect(messageRepository.delete).toHaveBeenCalled();
- expect(agentChatService.closePendingQuestion).toHaveBeenCalledWith({
- workspaceId: WORKSPACE_ID,
- rollback: ROLLBACK,
- });
- expect(agentChatService.restorePendingQuestion).not.toHaveBeenCalled();
- });
-
- it('gives the question back when the resume cannot be scheduled', async () => {
- workflowRunnerWorkspaceService.resumeAgentStepWithAnswer.mockRejectedValue(
- new Error('Queue unavailable'),
- );
-
- await expect(answer()).rejects.toThrow('Queue unavailable');
- expect(messageRepository.delete).toHaveBeenCalled();
- expect(agentChatService.restorePendingQuestion).toHaveBeenCalledWith(
- expect.objectContaining({
- streamId: null,
- messageId: QUESTION_MESSAGE_ID,
- }),
- );
- expect(inputAskWorkspaceService.answerForToolCall).not.toHaveBeenCalled();
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.resolve-pending-question.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.resolve-pending-question.spec.ts
deleted file mode 100644
index 2c750743d23..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.resolve-pending-question.spec.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-import { ASK_QUESTIONS_TOOL_NAME } from 'twenty-shared/ai';
-import { IsNull } from 'typeorm';
-
-import { AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
-
-const WORKSPACE_ID = 'workspace-id';
-const THREAD_ID = 'thread-id';
-const QUESTION_MESSAGE_ID = 'question-message-id';
-
-const QUESTIONS = [
- {
- header: 'Quote',
- question: 'Send the quote?',
- options: [{ label: 'Send it' }, { label: 'Hold it' }],
- },
-];
-
-const buildService = () => {
- const threadRepository = {
- update: jest.fn().mockResolvedValue({ affected: 1 }),
- };
- const messageRepository = {
- findOne: jest.fn().mockResolvedValue({
- id: QUESTION_MESSAGE_ID,
- turnId: 'turn-id',
- parts: [
- {
- id: 'part-id',
- toolName: ASK_QUESTIONS_TOOL_NAME,
- toolOutput: { result: { questions: QUESTIONS, status: 'pending' } },
- },
- ],
- }),
- };
- const messagePartRepository = {
- update: jest.fn().mockResolvedValue({ affected: 1 }),
- };
-
- const service = new AgentChatService(
- threadRepository as never,
- {} as never,
- messageRepository as never,
- messagePartRepository as never,
- {} as never,
- {} as never,
- {} as never,
- {} as never,
- {} as never,
- );
-
- return { service, threadRepository, messagePartRepository };
-};
-
-const resolveWithoutStream = (service: AgentChatService) =>
- service.resolvePendingQuestion({
- threadId: THREAD_ID,
- messageId: QUESTION_MESSAGE_ID,
- answers: [{ questionIndex: 0, selectedOptionIndices: [0] }],
- streamId: null,
- workspaceId: WORKSPACE_ID,
- });
-
-describe('AgentChatService resolvePendingQuestion without a stream', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- });
-
- it('claims the question by clearing its marker, leaving the thread free', async () => {
- const { service, threadRepository, messagePartRepository } = buildService();
-
- const resolved = await resolveWithoutStream(service);
-
- expect(threadRepository.update).toHaveBeenCalledTimes(1);
- expect(threadRepository.update).toHaveBeenCalledWith(
- WORKSPACE_ID,
- { id: THREAD_ID, pendingQuestionMessageId: QUESTION_MESSAGE_ID },
- { pendingQuestionMessageId: null },
- );
- expect(messagePartRepository.update).toHaveBeenCalledWith(
- WORKSPACE_ID,
- { id: 'part-id' },
- expect.objectContaining({
- toolOutput: expect.objectContaining({
- result: expect.objectContaining({ status: 'answered' }),
- }),
- }),
- );
- expect(resolved.answerText).toBe('Send the quote?\nSend it');
- });
-
- it('refuses an answer another one has already claimed', async () => {
- const { service, threadRepository, messagePartRepository } = buildService();
-
- threadRepository.update.mockResolvedValue({ affected: 0 });
-
- await expect(resolveWithoutStream(service)).rejects.toThrow(
- 'No pending question to answer',
- );
- expect(threadRepository.update).toHaveBeenCalledTimes(1);
- expect(messagePartRepository.update).not.toHaveBeenCalled();
- });
-
- it('puts the marker back when the question cannot be marked answered', async () => {
- const { service, threadRepository, messagePartRepository } = buildService();
-
- messagePartRepository.update.mockRejectedValue(new Error('write failed'));
-
- await expect(resolveWithoutStream(service)).rejects.toThrow('write failed');
- expect(threadRepository.update).toHaveBeenLastCalledWith(
- WORKSPACE_ID,
- { id: THREAD_ID, pendingQuestionMessageId: IsNull() },
- { pendingQuestionMessageId: QUESTION_MESSAGE_ID },
- );
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-actor.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-actor.service.ts
index 27f61bda871..7664b4d7e58 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-actor.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-actor.service.ts
@@ -157,7 +157,9 @@ export class AgentChatActorService {
return { authContext, rolePermissionConfig, roleId };
}
- async authorizeQuestionAnswer({
+ // The call belongs to the turn that made it, so it is resolved from the
+ // application context that turn was sent from and not from another one.
+ async authorizeToolCallResolution({
workspaceId,
threadId,
messageId,
@@ -166,20 +168,20 @@ export class AgentChatActorService {
threadId: string;
messageId: string;
}): Promise<void> {
- const question = await this.messages.findOne(workspaceId, {
+ const toolCallMessage = await this.messages.findOne(workspaceId, {
where: { id: messageId, threadId, role: AgentMessageRole.ASSISTANT },
select: ['turnId'],
});
- if (!isDefined(question?.turnId)) {
+ if (!isDefined(toolCallMessage?.turnId)) {
throw new AiException(
- 'Question turn not found',
+ 'Tool call turn not found',
AiExceptionCode.MESSAGE_NOT_FOUND,
);
}
const { sender } = await this.resolveMessage({
workspaceId,
threadId,
- turnId: question.turnId,
+ turnId: toolCallMessage.turnId,
});
const request = workspaceAuthContextStorage.getStore();
if (
@@ -189,8 +191,8 @@ export class AgentChatActorService {
(request.application?.id ?? null) !== sender.applicationId
) {
throw new AiException(
- 'Answer requires the original application context',
- AiExceptionCode.INVALID_QUESTION_ANSWER,
+ 'Resolving this tool call requires the original application context',
+ AiExceptionCode.TOOL_CALL_RESOLUTION_FORBIDDEN,
);
}
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.ts
index fef7fe2ce95..421fd36af5e 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.ts
@@ -18,7 +18,6 @@ import { UserWorkspaceAuthContextService } from 'src/engine/core-modules/user-wo
import { AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';
import { hasWorkflowRunThreadFields } from 'src/engine/metadata-modules/ai/ai-history/utils/has-workflow-run-thread-fields.util';
-import { isWorkflowRunThread } from 'src/engine/metadata-modules/ai/ai-chat/utils/is-workflow-run-thread.util';
import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
import {
AiException,
@@ -69,11 +68,6 @@ export class AgentChatSharingService {
if (!isDefined(thread)) {
return this.throwNotFound();
}
- // A run's conversation is the record of what its agent step did, and it is
- // readable by whoever reads the run, so nobody may add to or edit it.
- if (operationType !== 'select') {
- this.assertNotWorkflowRunThread(thread);
- }
const allowedIds = await this.workspaceOrmManager.executeInWorkspaceContext(
() =>
this.workspaceOrmManager
@@ -274,8 +268,6 @@ export class AgentChatSharingService {
objectMetadataId: objectMetadata.id,
threadId: args.threadId,
});
- this.assertNotWorkflowRunThread(thread);
-
const allowedIds = await this.workspaceOrmManager
.getRepositoryWithContextPermissions('agentChatThread')
.findRecordIdsAllowedForOperation({
@@ -294,17 +286,6 @@ export class AgentChatSharingService {
);
}
- private assertNotWorkflowRunThread(
- thread: AgentChatThreadWorkspaceEntity,
- ): void {
- if (isWorkflowRunThread(thread)) {
- throw new AiException(
- 'A workflow run conversation is read-only',
- AiExceptionCode.WORKFLOW_RUN_THREAD_READ_ONLY,
- );
- }
- }
-
async getAuthContext(args: Omit<ThreadAccessArgs, 'threadId'>) {
const authContext = await this.userAuthContextService
.resolveWorkspaceMember(args)
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts
index 2b9533f1f83..974875eae27 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service.ts
@@ -9,7 +9,6 @@ import { Injectable, Logger } from '@nestjs/common';
import { generateId } from 'ai';
import {
- type AskQuestionAnswer,
type ExtendedFileUIPart,
type ExtendedUIMessagePart,
isExtendedFileUIPart,
@@ -30,6 +29,7 @@ import {
AgentMessageRole,
AgentMessageStatus,
} from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';
+import { parsePausingToolCall } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/parse-pausing-tool-call.util';
import { mapDBPartsToUIMessageParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/mapDBPartsToUIMessageParts';
import { type BrowsingContextType } from 'src/engine/metadata-modules/ai/ai-agent/types/browsing-context.type';
import { AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
@@ -40,7 +40,6 @@ import { AgentChatEventPublisherService } from 'src/engine/metadata-modules/ai/a
import { AgentChatStreamHeartbeatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-stream-heartbeat.service';
import { AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
import { AiChatFileAttachment } from 'src/engine/metadata-modules/ai/ai-chat/types/ai-chat-file-attachment.type';
-import { hasQuestionAnswerContent } from 'src/engine/metadata-modules/ai/ai-chat/utils/has-question-answer-content.util';
import { mapErrorToStreamError } from 'src/engine/metadata-modules/ai/ai-chat/utils/map-error-to-stream-error.util';
import {
AiException,
@@ -48,6 +47,8 @@ import {
} from 'src/engine/metadata-modules/ai/ai.exception';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
+import { InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-service';
+
type StreamAgentChatOptions = {
threadId: string;
userWorkspaceId: string;
@@ -78,6 +79,7 @@ export class AgentChatStreamingService {
private readonly metricsService: MetricsService,
private readonly streamRecoveryService: AgentChatStreamRecoveryService,
private readonly actorService: AgentChatActorService,
+ private readonly inputAskWorkspaceService: InputAskWorkspaceService,
) {}
async reapDeadStream({
@@ -93,16 +95,16 @@ export class AgentChatStreamingService {
});
}
- private async tryClaimStream({
+ async tryClaimStream({
threadId,
workspaceId,
streamId,
- where,
+ where = {},
}: {
threadId: string;
workspaceId: string;
streamId: string;
- where: FindOptionsWhere<AgentChatThreadWorkspaceEntity>;
+ where?: FindOptionsWhere<AgentChatThreadWorkspaceEntity>;
}): Promise<boolean> {
await this.streamHeartbeatService.markClaimed(streamId);
@@ -146,10 +148,16 @@ export class AgentChatStreamingService {
workspaceId: workspace.id,
});
- const hasQueuedBacklog = await this.agentChatService.hasQueuedMessages({
- threadId,
- workspaceId: workspace.id,
- });
+ const [, hasQueuedBacklog] = await Promise.all([
+ this.settlePendingInputAsksBeforeSending({
+ threadId,
+ workspaceId: workspace.id,
+ }),
+ this.agentChatService.hasQueuedMessages({
+ threadId,
+ workspaceId: workspace.id,
+ }),
+ ]);
const streamId = generateId();
@@ -159,7 +167,6 @@ export class AgentChatStreamingService {
threadId,
workspaceId: workspace.id,
streamId,
- where: { pendingQuestionMessageId: IsNull() },
}));
if (!claimed) {
@@ -288,7 +295,6 @@ export class AgentChatStreamingService {
threadId,
workspaceId: workspace.id,
streamId,
- where: { pendingQuestionMessageId: IsNull() },
});
if (!hasClaimedStreamForKickoff) {
@@ -526,135 +532,7 @@ export class AgentChatStreamingService {
}
}
- async answerPendingQuestionAndResumeStream({
- threadId,
- messageId,
- answers,
- userWorkspaceId,
- workspaceMemberId,
- workspace,
- modelId,
- fileAttachments,
- }: {
- threadId: string;
- messageId: string;
- answers: AskQuestionAnswer[];
- userWorkspaceId: string;
- workspaceMemberId: string;
- workspace: WorkspaceEntity;
- modelId?: string;
- fileAttachments?: AiChatFileAttachment[];
- }): Promise<{ streamId: string; turnId: string | null }> {
- const thread = await this.agentChatService.getWritableThread({
- threadId,
- workspaceMemberId,
- workspaceId: workspace.id,
- });
- if (
- !hasQuestionAnswerContent(answers) &&
- !isNonEmptyArray(fileAttachments)
- ) {
- throw new AiException(
- 'Provide an answer or attachment',
- AiExceptionCode.INVALID_QUESTION_ANSWER,
- );
- }
- await this.actorService.authorizeQuestionAnswer({
- workspaceId: workspace.id,
- threadId,
- messageId,
- });
- await this.reapDeadStream({ thread, workspaceId: workspace.id });
-
- const streamId = generateId();
-
- await this.streamHeartbeatService.markClaimed(streamId);
-
- let resolved: Awaited<
- ReturnType<AgentChatService['resolvePendingQuestion']>
- >;
-
- try {
- resolved = await this.agentChatService.resolvePendingQuestion({
- threadId,
- messageId,
- answers,
- streamId,
- workspaceId: workspace.id,
- });
- } catch (error) {
- await this.streamHeartbeatService.clear(streamId);
- throw error;
- }
-
- let answerMessageId: string | null = null;
-
- try {
- const fileParts = await this.buildFilePartsFromAttachments(
- fileAttachments,
- workspace.id,
- );
-
- const answerMessage = await this.agentChatService.addMessage({
- threadId,
- userWorkspaceId,
- uiMessage: {
- role: AgentMessageRole.USER,
- parts: [
- {
- type: 'text',
- text: resolved.answerText,
- },
- ...fileParts,
- ],
- },
- workspaceId: workspace.id,
- });
- answerMessageId = answerMessage.id;
- resolved.turnId = answerMessage.turnId;
-
- await this.enqueueResumeStream({
- threadId,
- userWorkspaceId,
- workspaceMemberId,
- workspace,
- turnId: resolved.turnId,
- streamId,
- modelId,
- messageId: answerMessage.id,
- });
- } catch (error) {
- if (isDefined(answerMessageId)) {
- await this.agentChatService
- .deleteMessage({
- messageId: answerMessageId,
- workspaceId: workspace.id,
- })
- .catch(() => {});
- }
- await this.agentChatService.restorePendingQuestion({
- threadId,
- messageId,
- streamId,
- workspaceId: workspace.id,
- rollback: resolved.rollback,
- });
- await this.streamHeartbeatService.clear(streamId);
- throw error;
- }
-
- await this.eventPublisherService
- .publish({
- threadId,
- workspaceId: workspace.id,
- event: { type: 'question-answered' },
- })
- .catch(() => {});
-
- return { streamId, turnId: resolved.turnId };
- }
-
- private async enqueueResumeStream({
+ async enqueueResumeStream({
threadId,
userWorkspaceId,
workspaceMemberId,
@@ -714,14 +592,21 @@ export class AgentChatStreamingService {
}): Promise<void> {
const threadStatus = await this.threadRepository.findOne(workspaceId, {
where: { id: threadId },
- select: ['id', 'archivedAt', 'pendingQuestionMessageId'],
+ select: ['id', 'archivedAt'],
});
if (!threadStatus || threadStatus.archivedAt) {
return;
}
- if (isDefined(threadStatus.pendingQuestionMessageId)) {
+ // Queued messages wait behind an Ask: they are the conversation after
+ // the answer, not a replacement for it.
+ if (
+ await this.inputAskWorkspaceService.hasPendingForThread({
+ threadId,
+ workspaceId,
+ })
+ ) {
return;
}
@@ -809,7 +694,6 @@ export class AgentChatStreamingService {
threadId,
workspaceId,
streamId,
- where: { pendingQuestionMessageId: IsNull() },
});
if (!claimed) {
@@ -886,7 +770,78 @@ export class AgentChatStreamingService {
}
}
- private async releaseStreamClaim(
+ // A message sent while the agent waits on a person moves the conversation
+ // past the chat's own questions, which are closed as skipped so the model
+ // sees why they went unanswered. A workflow run's question gates the run,
+ // so it is never closed by a chat message.
+ private async settlePendingInputAsksBeforeSending({
+ threadId,
+ workspaceId,
+ }: {
+ threadId: string;
+ workspaceId: string;
+ }): Promise<void> {
+ const pendingInputAsks =
+ await this.inputAskWorkspaceService.findPendingForThread({
+ threadId,
+ workspaceId,
+ });
+
+ if (
+ pendingInputAsks.some((pendingInputAsk) =>
+ isDefined(pendingInputAsk.workflowRunId),
+ )
+ ) {
+ throw new AiException(
+ 'This conversation is waiting on an answer to its workflow run',
+ AiExceptionCode.THREAD_AWAITING_WORKFLOW_INPUT,
+ );
+ }
+
+ for (const { toolCallId } of pendingInputAsks) {
+ if (isDefined(toolCallId)) {
+ await this.skipPendingToolCall({ threadId, toolCallId, workspaceId });
+ }
+ }
+ }
+
+ private async skipPendingToolCall({
+ threadId,
+ toolCallId,
+ workspaceId,
+ }: {
+ threadId: string;
+ toolCallId: string;
+ workspaceId: string;
+ }): Promise<void> {
+ const hasCanceled = await this.inputAskWorkspaceService.cancel({
+ workspaceId,
+ match: { threadId, toolCallId },
+ });
+
+ if (!hasCanceled) {
+ return;
+ }
+
+ const toolPart = await this.agentChatService.findToolPart({
+ threadId,
+ toolCallId,
+ workspaceId,
+ });
+ const pausingToolCall = parsePausingToolCall(toolPart);
+
+ if (!isDefined(toolPart) || !isDefined(pausingToolCall)) {
+ return;
+ }
+
+ await this.agentChatService.updateToolPartOutput({
+ partId: toolPart.id,
+ toolOutput: pausingToolCall.toSkippedToolResult(),
+ workspaceId,
+ });
+ }
+
+ async releaseStreamClaim(
threadId: string,
workspaceId: string,
streamId: string,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-turn-preflight.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-turn-preflight.service.ts
new file mode 100644
index 00000000000..ec955cb80b5
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-turn-preflight.service.ts
@@ -0,0 +1,60 @@
+import { Injectable } from '@nestjs/common';
+
+import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-operation-type.enum';
+import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+import { AiBillingService } from 'src/engine/metadata-modules/ai/ai-billing/services/ai-billing.service';
+import { AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
+import { AiModelRegistryService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';
+import { getChatModelId } from 'src/engine/metadata-modules/ai/ai-models/utils/get-chat-model-id.util';
+import {
+ AiException,
+ AiExceptionCode,
+} from 'src/engine/metadata-modules/ai/ai.exception';
+
+@Injectable()
+export class AgentChatTurnPreflightService {
+ constructor(
+ private readonly aiModelRegistryService: AiModelRegistryService,
+ private readonly agentChatService: AgentChatService,
+ private readonly aiBillingService: AiBillingService,
+ ) {}
+
+ async assertCanStartChatTurn({
+ threadId,
+ modelId,
+ userWorkspaceId,
+ workspaceMemberId,
+ workspace,
+ }: {
+ threadId: string;
+ modelId?: string;
+ userWorkspaceId: string;
+ workspaceMemberId: string;
+ workspace: WorkspaceEntity;
+ }) {
+ if (this.aiModelRegistryService.getAvailableModels().length === 0) {
+ throw new AiException(
+ 'No AI models are available. Configure at least one AI provider.',
+ AiExceptionCode.API_KEY_NOT_CONFIGURED,
+ );
+ }
+
+ this.aiModelRegistryService.validateModelAvailability(
+ getChatModelId({ requestedModelId: modelId, workspace }),
+ );
+
+ const thread = await this.agentChatService.getWritableThread({
+ threadId,
+ workspaceMemberId,
+ workspaceId: workspace.id,
+ });
+
+ await this.aiBillingService.assertAiExecutionAllowed({
+ workspaceId: workspace.id,
+ operationType: UsageOperationType.AI_CHAT_TOKEN,
+ spenders: { userWorkspaceId },
+ });
+
+ return thread;
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-workflow-question.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-workflow-question.service.ts
deleted file mode 100644
index d53073335f5..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-workflow-question.service.ts
+++ /dev/null
@@ -1,171 +0,0 @@
-import { Injectable, Logger } from '@nestjs/common';
-
-import { PermissionFlagType } from 'twenty-shared/constants';
-import { type AskQuestionAnswer } from 'twenty-shared/ai';
-import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
-
-import { type AgentMessageEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';
-import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
-import { AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
-import { type AiChatFileAttachment } from 'src/engine/metadata-modules/ai/ai-chat/types/ai-chat-file-attachment.type';
-import { hasQuestionAnswerContent } from 'src/engine/metadata-modules/ai/ai-chat/utils/has-question-answer-content.util';
-import { type WorkflowRunThreadFields } from 'src/engine/metadata-modules/ai/ai-chat/utils/is-workflow-run-thread.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 {
- AiException,
- AiExceptionCode,
-} from 'src/engine/metadata-modules/ai/ai.exception';
-import { PermissionsService } from 'src/engine/metadata-modules/permissions/permissions.service';
-import { InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-service';
-import { WorkflowRunnerWorkspaceService } from 'src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service';
-
-// A workflow agent's question is answered in its run's conversation, but what
-// the answer resumes is the run, not a chat stream: this records the answer in
-// the conversation and hands the step back to the workflow runner, which
-// continues the same conversation with it.
-@Injectable()
-export class AgentChatWorkflowQuestionService {
- private readonly logger = new Logger(AgentChatWorkflowQuestionService.name);
-
- constructor(
- @InjectAgentHistoryRepository('agentMessage')
- private readonly messageRepository: AgentHistoryRepository<AgentMessageEntity>,
- private readonly agentChatService: AgentChatService,
- private readonly permissionsService: PermissionsService,
- private readonly workflowRunnerWorkspaceService: WorkflowRunnerWorkspaceService,
- private readonly inputAskWorkspaceService: InputAskWorkspaceService,
- ) {}
-
- async answer({
- thread,
- messageId,
- answers,
- fileAttachments,
- userWorkspaceId,
- workspaceId,
- }: {
- thread: AgentChatThreadWorkspaceEntity & WorkflowRunThreadFields;
- messageId: string;
- answers: AskQuestionAnswer[];
- fileAttachments?: AiChatFileAttachment[];
- userWorkspaceId: string;
- workspaceId: string;
- }): Promise<void> {
- const { workflowRunId } = thread;
-
- // Only the answer's text is recorded for the resumed agent, so an
- // attachment would be dropped without the agent ever seeing it.
- if (isNonEmptyArray(fileAttachments)) {
- throw new AiException(
- 'A workflow agent question cannot be answered with attachments',
- AiExceptionCode.INVALID_QUESTION_ANSWER,
- );
- }
-
- if (!hasQuestionAnswerContent(answers)) {
- throw new AiException(
- 'Provide an answer',
- AiExceptionCode.INVALID_QUESTION_ANSWER,
- );
- }
-
- // The same permission that lets someone submit a workflow's form.
- const canAnswer =
- await this.permissionsService.userHasWorkspaceSettingPermission({
- userWorkspaceId,
- workspaceId,
- setting: PermissionFlagType.WORKFLOWS,
- applicationId: undefined,
- });
-
- if (!canAnswer) {
- throw new AiException(
- 'Answering a workflow question requires the Workflows permission',
- AiExceptionCode.WORKFLOW_RUN_QUESTION_FORBIDDEN,
- );
- }
-
- // No chat stream continues a workflow conversation, so its question is
- // claimed by its marker alone and nothing is left holding the thread.
- const resolved = await this.agentChatService.resolvePendingQuestion({
- threadId: thread.id,
- messageId,
- answers,
- streamId: null,
- workspaceId,
- });
-
- let answerMessageId: string | undefined;
- let isNoLongerAwaited = false;
-
- try {
- const answerMessage = await this.agentChatService.addMessage({
- threadId: thread.id,
- uiMessage: {
- role: 'user',
- parts: [{ type: 'text', text: resolved.answerText }],
- },
- turnId: resolved.turnId ?? undefined,
- workspaceId,
- userWorkspaceId,
- });
-
- answerMessageId = answerMessage.id;
-
- const stepAwaitingAnswer =
- await this.workflowRunnerWorkspaceService.resumeAgentStepWithAnswer({
- threadId: thread.id,
- workflowRunId,
- workspaceId,
- });
-
- isNoLongerAwaited = stepAwaitingAnswer.status === 'NO_LONGER_AWAITING';
-
- if (stepAwaitingAnswer.status !== 'AWAITING_ANSWER') {
- throw new AiException(
- 'This workflow is no longer waiting for this answer',
- AiExceptionCode.QUESTION_NOT_PENDING,
- );
- }
- } catch (error) {
- if (isDefined(answerMessageId)) {
- await this.messageRepository
- .delete(workspaceId, { id: answerMessageId })
- .catch(() => {});
- }
-
- if (isNoLongerAwaited) {
- await this.agentChatService.closePendingQuestion({
- workspaceId,
- rollback: resolved.rollback,
- });
- } else {
- await this.agentChatService.restorePendingQuestion({
- threadId: thread.id,
- messageId,
- streamId: null,
- workspaceId,
- rollback: resolved.rollback,
- });
- }
-
- throw error;
- }
-
- // Only once the run has taken the answer: the Ask mirrors it and gates
- // nothing, so a failure here must not undo an accepted answer.
- try {
- await this.inputAskWorkspaceService.answerForToolCall({
- workspaceId,
- threadId: thread.id,
- toolCallId: resolved.toolCallId,
- response: { answers, answerText: resolved.answerText },
- });
- } catch (error) {
- this.logger.warn(
- `Failed to record the answer to Ask of tool call ${resolved.toolCallId} in workspace ${workspaceId}: ${error instanceof Error ? error.message : String(error)}`,
- );
- }
- }
-}
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 c9e57053fa4..a31b1f2cec2 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
@@ -1,4 +1,3 @@
-import { isNonEmptyString } from '@sniptt/guards';
import { workspaceAuthContextStorage } from 'src/engine/core-modules/auth/storage/workspace-auth-context.storage';
import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';
import { AgentChatSharingService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service';
@@ -6,15 +5,9 @@ import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-
import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
import { Injectable, Logger } from '@nestjs/common';
-import {
- ASK_QUESTIONS_TOOL_NAME,
- type AskQuestionAnswer,
- type AskQuestionItem,
- type AskQuestionsToolResult,
- ExtendedUIMessage,
-} from 'twenty-shared/ai';
+import { ExtendedUIMessage } from 'twenty-shared/ai';
import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
-import { In, IsNull } from 'typeorm';
+import { In } from 'typeorm';
import type { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
import type { UIDataTypes, UIMessagePart, UITools } from 'ai';
@@ -42,11 +35,6 @@ import { AgentChatThreadRecordEventService } from 'src/engine/metadata-modules/a
import { AgentTitleGenerationService } from './agent-title-generation.service';
import { AgentChatThreadDTO } from '../dtos/agent-chat-thread.dto';
-type PendingQuestionRollback = {
- partId: string;
- previousOutput: Record<string, unknown> & { result?: AskQuestionsToolResult };
-};
-
@Injectable()
export class AgentChatService {
private readonly logger = new Logger(AgentChatService.name);
@@ -688,338 +676,61 @@ export class AgentChatService {
return savedTurnId;
}
- async resolvePendingQuestion({
+ // A tool call id is only unique within the conversation that made it, so
+ // the part is looked up through its message's thread.
+ async findToolPart({
threadId,
- messageId,
- answers,
- streamId,
+ toolCallId,
workspaceId,
}: {
threadId: string;
- messageId: string;
- answers: AskQuestionAnswer[];
- // Null for a conversation no chat stream continues, such as a workflow
- // run's: its question is claimed by its marker alone.
- streamId: string | null;
+ toolCallId: string;
workspaceId: string;
- }): Promise<{
- answerText: string;
- toolCallId: string | null;
- turnId: string | null;
- rollback: PendingQuestionRollback;
- }> {
- const message = await this.messageRepository.findOne(workspaceId, {
- where: { id: messageId, threadId },
- relations: ['parts'],
+ }): Promise<
+ | (Pick<
+ AgentMessagePartWorkspaceEntity,
+ 'id' | 'messageId' | 'toolName' | 'toolInput'
+ > & { turnId: string | null })
+ | null
+ > {
+ const parts = await this.messagePartRepository.find(workspaceId, {
+ where: { toolCallId },
+ select: ['id', 'messageId', 'toolName', 'toolInput'],
});
- if (!message) {
- throw new AiException(
- 'Question message not found',
- AiExceptionCode.MESSAGE_NOT_FOUND,
- );
- }
-
- const pendingPart = (message.parts ?? []).find(
- (part) =>
- part.toolName === ASK_QUESTIONS_TOOL_NAME &&
- (part.toolOutput as { result?: AskQuestionsToolResult } | null)?.result
- ?.status === 'pending',
- );
-
- if (!pendingPart) {
- throw new AiException(
- 'No pending question to answer',
- AiExceptionCode.QUESTION_NOT_PENDING,
- );
- }
-
- const previousOutput =
- (pendingPart.toolOutput as
- | PendingQuestionRollback['previousOutput']
- | null) ?? {};
- const questions = previousOutput.result?.questions ?? [];
-
- this.validateQuestionAnswers(answers, questions);
-
- const isClaimed = isDefined(streamId)
- ? await this.claimQuestionForStream({
- threadId,
- messageId,
- streamId,
- workspaceId,
- })
- : await this.claimQuestionMarker({ threadId, messageId, workspaceId });
-
- if (!isClaimed) {
- throw new AiException(
- 'No pending question to answer',
- AiExceptionCode.QUESTION_NOT_PENDING,
- );
+ if (!isNonEmptyArray(parts)) {
+ return null;
}
- try {
- await this.messagePartRepository.update(
- workspaceId,
- { id: pendingPart.id },
- {
- toolOutput: {
- ...previousOutput,
- success: true,
- message: 'User answered the questions.',
- result: {
- questions,
- status: 'answered',
- answers,
- },
- },
- },
- );
- } catch (error) {
- await this.releaseQuestionClaim({
+ const message = await this.messageRepository.findOne(workspaceId, {
+ where: {
+ id: In(parts.map((part) => part.messageId)),
threadId,
- messageId,
- streamId,
- workspaceId,
- });
- throw error;
- }
-
- const answerText = answers
- .map((answer) => {
- const question = questions[answer.questionIndex];
- const value = isNonEmptyString(answer.freeText)
- ? answer.freeText
- : answer.selectedOptionIndices
- .map((optionIndex) => question.options[optionIndex].label)
- .join(', ');
- return `${question.question}\n${value}`;
- })
- .join('\n\n');
-
- return {
- answerText,
- toolCallId: pendingPart.toolCallId,
- turnId: message.turnId,
- rollback: { partId: pendingPart.id, previousOutput },
- };
- }
-
- private async claimQuestionForStream({
- threadId,
- messageId,
- streamId,
- workspaceId,
- }: {
- threadId: string;
- messageId: string;
- streamId: string;
- workspaceId: string;
- }): Promise<boolean> {
- const claim = await this.threadRepository.update(
- workspaceId,
- {
- id: threadId,
- pendingQuestionMessageId: messageId,
- activeStreamId: IsNull(),
- },
- {
- pendingQuestionMessageId: null,
- activeStreamId: streamId,
- lastStreamError: null,
},
- );
-
- if ((claim.affected ?? 0) > 0) {
- return true;
- }
-
- return this.claimOrphanedQuestion({
- threadId,
- messageId,
- streamId,
- workspaceId,
+ select: ['id', 'turnId'],
});
- }
- // Clearing the marker is the claim: of two concurrent answers only one
- // matches it. No orphan is adopted here, since without a stream an orphaned
- // question cannot be told apart from one another answer has just claimed.
- private async claimQuestionMarker({
- threadId,
- messageId,
- workspaceId,
- }: {
- threadId: string;
- messageId: string;
- workspaceId: string;
- }): Promise<boolean> {
- const claim = await this.threadRepository.update(
- workspaceId,
- { id: threadId, pendingQuestionMessageId: messageId },
- { pendingQuestionMessageId: null },
- );
+ const part = parts.find((candidate) => candidate.messageId === message?.id);
- return (claim.affected ?? 0) > 0;
+ return isDefined(part) && isDefined(message)
+ ? { ...part, turnId: message.turnId }
+ : null;
}
- private async releaseQuestionClaim({
- threadId,
- messageId,
- streamId,
+ async updateToolPartOutput({
+ partId,
+ toolOutput,
workspaceId,
}: {
- threadId: string;
- messageId: string;
- streamId: string | null;
+ partId: string;
+ toolOutput: Record<string, unknown>;
workspaceId: string;
}): Promise<void> {
- const release = isDefined(streamId)
- ? this.threadRepository.update(
- workspaceId,
- { id: threadId, activeStreamId: streamId },
- { pendingQuestionMessageId: messageId, activeStreamId: null },
- )
- : this.threadRepository.update(
- workspaceId,
- { id: threadId, pendingQuestionMessageId: IsNull() },
- { pendingQuestionMessageId: messageId },
- );
-
- await release.catch(() => {});
- }
-
- private async claimOrphanedQuestion({
- threadId,
- messageId,
- streamId,
- workspaceId,
- }: {
- threadId: string;
- messageId: string;
- streamId: string;
- workspaceId: string;
- }): Promise<boolean> {
- const latestAssistantMessage = await this.messageRepository.findOne(
- workspaceId,
- {
- where: { threadId, role: AgentMessageRole.ASSISTANT },
- order: {
- processedAt: { order: 'DESC', nulls: 'NULLS LAST' },
- createdAt: 'DESC',
- id: 'DESC',
- },
- select: ['id'],
- },
- );
-
- if (latestAssistantMessage?.id !== messageId) {
- return false;
- }
-
- const claim = await this.threadRepository.update(
+ await this.messagePartRepository.update(
workspaceId,
- {
- id: threadId,
- pendingQuestionMessageId: IsNull(),
- activeStreamId: IsNull(),
- },
- { activeStreamId: streamId, lastStreamError: null },
+ { id: partId },
+ { toolOutput },
);
-
- return (claim.affected ?? 0) > 0;
- }
-
- async restorePendingQuestion({
- threadId,
- messageId,
- streamId,
- workspaceId,
- rollback,
- }: {
- threadId: string;
- messageId: string;
- streamId: string | null;
- workspaceId: string;
- rollback: PendingQuestionRollback;
- }): Promise<void> {
- await this.messagePartRepository
- .update(
- workspaceId,
- { id: rollback.partId },
- { toolOutput: rollback.previousOutput },
- )
- .catch(() => {});
-
- await this.releaseQuestionClaim({
- threadId,
- messageId,
- streamId,
- workspaceId,
- });
- }
-
- // For a question nothing can consume any more: its run ended, or the step
- // moved on to another conversation. Restoring it would leave a card that
- // every answer is refused on, so it is closed instead. An ending run closes
- // its questions itself; this covers an answer that claimed one just before.
- async closePendingQuestion({
- workspaceId,
- rollback,
- }: {
- workspaceId: string;
- rollback: PendingQuestionRollback;
- }): Promise<void> {
- await this.messagePartRepository
- .update(
- workspaceId,
- { id: rollback.partId },
- {
- toolOutput: {
- ...rollback.previousOutput,
- result: { ...rollback.previousOutput.result, status: 'skipped' },
- },
- },
- )
- .catch(() => {});
- }
-
- private validateQuestionAnswers(
- answers: AskQuestionAnswer[],
- questions: AskQuestionItem[],
- ): void {
- for (const answer of answers) {
- const question = questions[answer.questionIndex];
-
- if (!isDefined(question)) {
- throw new AiException(
- 'Answer references an unknown question.',
- AiExceptionCode.INVALID_QUESTION_ANSWER,
- );
- }
-
- const hasInvalidOption = answer.selectedOptionIndices.some(
- (optionIndex) =>
- optionIndex < 0 || optionIndex >= question.options.length,
- );
-
- if (hasInvalidOption) {
- throw new AiException(
- 'Answer references an unknown option.',
- AiExceptionCode.INVALID_QUESTION_ANSWER,
- );
- }
-
- if (
- question.allowMultiSelect !== true &&
- answer.selectedOptionIndices.length > 1
- ) {
- throw new AiException(
- 'This question allows only one selection.',
- AiExceptionCode.INVALID_QUESTION_ANSWER,
- );
- }
- }
}
async updateThreadTitle({
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts
index 89ce317db8b..c0da27fa4b2 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/chat-execution.service.ts
@@ -47,6 +47,7 @@ import { isToolOutputSuccessful } from 'src/engine/core-modules/tool-provider/ut
import { resolveToolName } from 'src/engine/core-modules/tool-provider/utils/resolve-tool-name.util';
import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { AgentActorContextService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-actor-context.service';
+import { endsOnPausingToolCall } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/ends-on-pausing-tool-call.util';
import { finalizeDanglingToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/finalize-dangling-tool-parts.util';
import { guideUncallableToolCallsToMetaTool } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/guide-uncallable-tool-calls-to-meta-tool.util';
import { AGENT_CONFIG } from 'src/engine/metadata-modules/ai/ai-agent/constants/agent-config.const';
@@ -73,6 +74,10 @@ import {
ATTACH_CONVERSATION_TO_RECORD_TOOL_NAME,
createAttachConversationToRecordTool,
} from 'src/engine/metadata-modules/ai/ai-chat/tools/attach-conversation-to-record.tool';
+import {
+ PROPOSE_EMAIL_TOOL_NAME,
+ createProposeEmailTool,
+} from 'src/engine/metadata-modules/ai/ai-chat/tools/propose-email.tool';
import {
COMPLETE_WORKSPACE_SETUP_TOOL_NAME,
createCompleteWorkspaceSetupTool,
@@ -297,10 +302,16 @@ export class ChatExecutionService {
workspace.id,
));
+ // Proposing an email only helps someone who could then send it.
+ const canProposeEmail = toolCatalog.some(
+ (toolIndexEntry) => toolIndexEntry.name === 'send_email',
+ );
+
const preloadedToolNames = [
...Object.keys(preloadedTools),
...Object.keys(nativeTools),
ASK_QUESTIONS_TOOL_NAME,
+ ...(canProposeEmail ? [PROPOSE_EMAIL_TOOL_NAME] : []),
...(isWorkspaceSetupThread ? [COMPLETE_WORKSPACE_SETUP_TOOL_NAME] : []),
...(canAttachConversationToRecords
? [ATTACH_CONVERSATION_TO_RECORD_TOOL_NAME]
@@ -317,6 +328,9 @@ export class ChatExecutionService {
[ASK_QUESTIONS_TOOL_NAME]: createAskQuestionsTool({
isWorkspaceSetupThread,
}),
+ ...(canProposeEmail
+ ? { [PROPOSE_EMAIL_TOOL_NAME]: createProposeEmailTool() }
+ : {}),
...(isWorkspaceSetupThread
? {
[COMPLETE_WORKSPACE_SETUP_TOOL_NAME]:
@@ -580,12 +594,12 @@ export class ChatExecutionService {
instructions: systemMessage,
messages: modelMessages,
tools: activeTools,
- // Every step of the kickoff turn is forced so it cannot end in prose; stopWhen ends it at the first ask_questions.
+ // Every step of the kickoff turn is forced so it cannot end in prose; stopWhen ends it at the first pausing tool call.
toolChoice: isWorkspaceSetupKickoffTurn ? 'required' : 'auto',
abortSignal,
stopWhen: (step) =>
isStepCount(AGENT_CONFIG.MAX_STEPS)(step) ||
- hasToolCall(ASK_QUESTIONS_TOOL_NAME)(step) ||
+ endsOnPausingToolCall({ steps: step.steps }) ||
hasToolCall(COMPLETE_WORKSPACE_SETUP_TOOL_NAME)(step) ||
hasNoMoreAvailableCredits,
...buildAiTelemetry({
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
new file mode 100644
index 00000000000..ac6aee8751f
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/tools/propose-email.tool.ts
@@ -0,0 +1,59 @@
+import {
+ PROPOSE_EMAIL_TOOL_NAME,
+ type ProposeEmailToolResult,
+ type ProposedEmail,
+} from 'twenty-shared/ai';
+import { isValidUuid } from 'twenty-shared/utils';
+import { z } from 'zod';
+
+export { PROPOSE_EMAIL_TOOL_NAME };
+
+export const proposeEmailInputSchema = z.object({
+ recipients: z
+ .object({
+ to: z.string().describe('Comma-separated recipient email addresses.'),
+ cc: z
+ .string()
+ .optional()
+ .default('')
+ .describe('Comma-separated CC email addresses.'),
+ bcc: z
+ .string()
+ .optional()
+ .default('')
+ .describe('Comma-separated BCC email addresses.'),
+ })
+ .describe('Who the email goes to.'),
+ subject: z.string().describe('The email subject line.'),
+ body: z
+ .string()
+ .describe(
+ 'The email body as plain text. Separate paragraphs with a blank line.',
+ ),
+ connectedAccountId: z
+ .string()
+ .refine((value) => isValidUuid(value))
+ .optional()
+ .describe(
+ 'The UUID of the connected account to send from, from find_connected_accounts. Leave it out to let the person pick.',
+ ),
+});
+
+type ProposeEmailPendingOutput = {
+ success: true;
+ message: string;
+ result: ProposeEmailToolResult;
+};
+
+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 },
+ }),
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/find-pending-question-part.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/find-pending-question-part.util.spec.ts
deleted file mode 100644
index 2a07474d085..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/find-pending-question-part.util.spec.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { type ExtendedUIMessagePart } from 'twenty-shared/ai';
-
-import { findPendingQuestionPart } from 'src/engine/metadata-modules/ai/ai-chat/utils/find-pending-question-part.util';
-
-const askQuestionsPart = (
- status: 'pending' | 'answered',
-): ExtendedUIMessagePart =>
- ({
- type: 'tool-ask_questions',
- toolCallId: 'call-1',
- state: 'output-available',
- input: { questions: [] },
- output: {
- success: true,
- message: 'x',
- result: {
- questions: [{ header: 'h', question: 'q', options: [] }],
- status,
- },
- },
- }) as unknown as ExtendedUIMessagePart;
-
-const textPart = (text: string): ExtendedUIMessagePart =>
- ({ type: 'text', text }) as ExtendedUIMessagePart;
-
-describe('findPendingQuestionPart', () => {
- it('returns the ask_questions part when status is pending', () => {
- const part = findPendingQuestionPart([
- textPart('hello'),
- askQuestionsPart('pending'),
- ]);
-
- expect(part).toBeDefined();
- expect(part?.toolCallId).toBe('call-1');
- });
-
- it('returns undefined when the question has been answered', () => {
- expect(
- findPendingQuestionPart([askQuestionsPart('answered')]),
- ).toBeUndefined();
- });
-
- it('returns undefined when there is no ask_questions part', () => {
- expect(findPendingQuestionPart([textPart('hello')])).toBeUndefined();
- });
-
- it('ignores other tool parts', () => {
- const otherTool = {
- type: 'tool-search_help_center',
- toolCallId: 'call-2',
- state: 'output-available',
- input: {},
- output: { success: true },
- } as unknown as ExtendedUIMessagePart;
-
- expect(findPendingQuestionPart([otherTool])).toBeUndefined();
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/has-question-answer-content.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/has-question-answer-content.util.spec.ts
deleted file mode 100644
index d4b840e1782..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/has-question-answer-content.util.spec.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { hasQuestionAnswerContent } from 'src/engine/metadata-modules/ai/ai-chat/utils/has-question-answer-content.util';
-
-describe('hasQuestionAnswerContent', () => {
- it('accepts a selected option or a written answer', () => {
- expect(
- hasQuestionAnswerContent([
- { questionIndex: 0, selectedOptionIndices: [1] },
- ]),
- ).toBe(true);
- expect(
- hasQuestionAnswerContent([
- { questionIndex: 0, selectedOptionIndices: [], freeText: 'Later' },
- ]),
- ).toBe(true);
- });
-
- it('rejects no answers, or answers that say nothing', () => {
- expect(hasQuestionAnswerContent([])).toBe(false);
- expect(
- hasQuestionAnswerContent([
- { questionIndex: 0, selectedOptionIndices: [], freeText: ' ' },
- ]),
- ).toBe(false);
- });
-});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/find-pending-question-part.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/find-pending-question-part.util.ts
deleted file mode 100644
index 02076768b3c..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/find-pending-question-part.util.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { getToolName, isToolUIPart } from 'ai';
-import {
- ASK_QUESTIONS_TOOL_NAME,
- type AskQuestionsToolResult,
- type ExtendedUIMessagePart,
-} from 'twenty-shared/ai';
-
-type ToolPartWithOutput = ExtendedUIMessagePart & {
- toolCallId: string;
- output?: { result?: AskQuestionsToolResult };
-};
-
-export const findPendingQuestionPart = (
- parts: ExtendedUIMessagePart[],
-): ToolPartWithOutput | undefined => {
- for (const part of parts) {
- if (!isToolUIPart(part) || getToolName(part) !== ASK_QUESTIONS_TOOL_NAME) {
- continue;
- }
-
- const output = (part as ToolPartWithOutput).output;
-
- if (output?.result?.status === 'pending') {
- return part as ToolPartWithOutput;
- }
- }
-
- return undefined;
-};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/has-question-answer-content.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/has-question-answer-content.util.ts
deleted file mode 100644
index 90b08fb6a20..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/has-question-answer-content.util.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { isNonEmptyString } from '@sniptt/guards';
-import { type AskQuestionAnswer } from 'twenty-shared/ai';
-import { isNonEmptyArray } from 'twenty-shared/utils';
-
-export const hasQuestionAnswerContent = (
- answers: AskQuestionAnswer[],
-): boolean =>
- answers.some(
- (answer) =>
- isNonEmptyString(answer.freeText?.trim()) ||
- isNonEmptyArray(answer.selectedOptionIndices),
- );
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/is-workflow-run-thread.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/is-workflow-run-thread.util.ts
deleted file mode 100644
index f48c6f5f435..00000000000
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/is-workflow-run-thread.util.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { isDefined } from 'twenty-shared/utils';
-
-import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
-
-export type WorkflowRunThreadFields = {
- workflowRunId: string;
-};
-
-export const isWorkflowRunThread = <
- TThread extends Pick<AgentChatThreadWorkspaceEntity, 'workflowRunId'>,
->(
- thread: TThread,
-): thread is TThread & WorkflowRunThreadFields =>
- isDefined(thread.workflowRunId);
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/update-agent-chat-thread-usage.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/update-agent-chat-thread-usage.util.ts
index 147cf7b1cd4..b28f6bad1de 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/update-agent-chat-thread-usage.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/update-agent-chat-thread-usage.util.ts
@@ -10,7 +10,6 @@ type ThreadUsageUpdate = {
totalCacheCreationTokens: number;
contextWindowTokens: number | null;
conversationSize: number;
- pendingQuestionMessageId: string | null;
};
export const updateAgentChatThreadUsage = async ({
@@ -40,7 +39,7 @@ export const updateAgentChatThreadUsage = async ({
"totalCacheReadTokens" = "totalCacheReadTokens" + $7,
"totalCacheCreationTokens" = "totalCacheCreationTokens" + $8,
"contextWindowTokens" = $9, "conversationSize" = $10,
- "pendingQuestionMessageId" = $11, "lastStreamError" = NULL, "updatedAt" = now()
+ "lastStreamError" = NULL, "updatedAt" = now()
WHERE id = $1 AND "activeStreamId" = $2
RETURNING id
) SELECT id FROM updated`,
@@ -55,7 +54,6 @@ export const updateAgentChatThreadUsage = async ({
usage.totalCacheCreationTokens,
usage.contextWindowTokens,
usage.conversationSize,
- usage.pendingQuestionMessageId,
],
);
return { affected: rows.length };
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 6b900eaf452..f365327380d 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
@@ -16,8 +16,7 @@ export enum AiExceptionCode {
CONTEXT_WINDOW_EXCEEDED = 'CONTEXT_WINDOW_EXCEEDED',
INVALID_CHAT_THREAD_TITLE = 'INVALID_CHAT_THREAD_TITLE',
MESSAGE_NOT_FOUND = 'MESSAGE_NOT_FOUND',
- QUESTION_NOT_PENDING = 'QUESTION_NOT_PENDING',
- INVALID_QUESTION_ANSWER = 'INVALID_QUESTION_ANSWER',
+ INVALID_TOOL_CALL_OUTPUT = 'INVALID_TOOL_CALL_OUTPUT',
API_KEY_NOT_CONFIGURED = 'API_KEY_NOT_CONFIGURED',
USER_WORKSPACE_ID_NOT_FOUND = 'USER_WORKSPACE_ID_NOT_FOUND',
ROLE_NOT_FOUND = 'ROLE_NOT_FOUND',
@@ -30,8 +29,8 @@ export enum AiExceptionCode {
EVALUATION_MODEL_NOT_FOUND = 'EVALUATION_MODEL_NOT_FOUND',
EVALUATION_QUESTION_UNSUPPORTED = 'EVALUATION_QUESTION_UNSUPPORTED',
INVALID_EVALUATION_REQUEST = 'INVALID_EVALUATION_REQUEST',
- WORKFLOW_RUN_THREAD_READ_ONLY = 'WORKFLOW_RUN_THREAD_READ_ONLY',
- WORKFLOW_RUN_QUESTION_FORBIDDEN = 'WORKFLOW_RUN_QUESTION_FORBIDDEN',
+ TOOL_CALL_RESOLUTION_FORBIDDEN = 'TOOL_CALL_RESOLUTION_FORBIDDEN',
+ THREAD_AWAITING_WORKFLOW_INPUT = 'THREAD_AWAITING_WORKFLOW_INPUT',
}
const getAiExceptionUserFriendlyMessage = (code: AiExceptionCode) => {
@@ -58,10 +57,8 @@ const getAiExceptionUserFriendlyMessage = (code: AiExceptionCode) => {
return msg`Chat thread title cannot be empty.`;
case AiExceptionCode.MESSAGE_NOT_FOUND:
return msg`Chat message not found.`;
- case AiExceptionCode.QUESTION_NOT_PENDING:
- return msg`This question has already been answered.`;
- case AiExceptionCode.INVALID_QUESTION_ANSWER:
- return msg`Invalid answer for this question.`;
+ case AiExceptionCode.INVALID_TOOL_CALL_OUTPUT:
+ return msg`Invalid answer for this request.`;
case AiExceptionCode.API_KEY_NOT_CONFIGURED:
return msg`API key is not configured.`;
case AiExceptionCode.USER_WORKSPACE_ID_NOT_FOUND:
@@ -86,10 +83,10 @@ const getAiExceptionUserFriendlyMessage = (code: AiExceptionCode) => {
return msg`This model cannot answer one of the questions asked.`;
case AiExceptionCode.INVALID_EVALUATION_REQUEST:
return msg`Invalid classification request.`;
- case AiExceptionCode.WORKFLOW_RUN_THREAD_READ_ONLY:
- return msg`This conversation belongs to a workflow run and can only be read.`;
- case AiExceptionCode.WORKFLOW_RUN_QUESTION_FORBIDDEN:
- return msg`You need the Workflows permission to answer a workflow's question.`;
+ case AiExceptionCode.TOOL_CALL_RESOLUTION_FORBIDDEN:
+ 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.`;
default:
assertUnreachable(code);
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/filters/ai-api-exception.filter.ts b/packages/twenty-server/src/engine/metadata-modules/ai/filters/ai-api-exception.filter.ts
index 6ce40b88462..72cb761e925 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/filters/ai-api-exception.filter.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/filters/ai-api-exception.filter.ts
@@ -40,8 +40,7 @@ export class AiRestApiExceptionFilter implements ExceptionFilter {
response,
503, // Service Unavailable - the AI service is not configured
);
- case AiExceptionCode.WORKFLOW_RUN_THREAD_READ_ONLY:
- case AiExceptionCode.WORKFLOW_RUN_QUESTION_FORBIDDEN:
+ case AiExceptionCode.TOOL_CALL_RESOLUTION_FORBIDDEN:
return this.httpExceptionHandlerService.handleError(
exception,
response,
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 b2d607880df..ae4a17de95c 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
@@ -27,20 +27,19 @@ export const aiGraphqlApiExceptionHandler = (error: Error) => {
case AiExceptionCode.CONTEXT_WINDOW_EXCEEDED:
case AiExceptionCode.INVALID_AGENT_INPUT:
case AiExceptionCode.INVALID_CHAT_THREAD_TITLE:
- case AiExceptionCode.QUESTION_NOT_PENDING:
- case AiExceptionCode.INVALID_QUESTION_ANSWER:
+ case AiExceptionCode.INVALID_TOOL_CALL_OUTPUT:
case AiExceptionCode.EVALUATION_QUESTION_UNSUPPORTED:
case AiExceptionCode.INVALID_EVALUATION_REQUEST:
throw new UserInputError(error);
case AiExceptionCode.AGENT_ALREADY_EXISTS:
case AiExceptionCode.NO_FAILED_TURN_TO_RETRY:
+ case AiExceptionCode.THREAD_AWAITING_WORKFLOW_INPUT:
throw new ConflictError(error);
case AiExceptionCode.AGENT_IS_STANDARD:
case AiExceptionCode.ROLE_CANNOT_BE_ASSIGNED_TO_AGENTS:
case AiExceptionCode.RUN_AS_WORKSPACE_MEMBER_NOT_ALLOWED:
case AiExceptionCode.RUN_AGENT_NOT_ALLOWED:
- case AiExceptionCode.WORKFLOW_RUN_THREAD_READ_ONLY:
- case AiExceptionCode.WORKFLOW_RUN_QUESTION_FORBIDDEN:
+ case AiExceptionCode.TOOL_CALL_RESOLUTION_FORBIDDEN:
throw new ForbiddenError(error);
case AiExceptionCode.AGENT_EXECUTION_FAILED:
case AiExceptionCode.API_KEY_NOT_CONFIGURED:
diff --git a/packages/twenty-server/src/engine/twenty-orm/utils/is-duplicate-entry-error.util.ts b/packages/twenty-server/src/engine/twenty-orm/utils/is-duplicate-entry-error.util.ts
new file mode 100644
index 00000000000..a22a50bc7b2
--- /dev/null
+++ b/packages/twenty-server/src/engine/twenty-orm/utils/is-duplicate-entry-error.util.ts
@@ -0,0 +1,8 @@
+import {
+ TwentyOrmException,
+ TwentyOrmExceptionCode,
+} from 'src/engine/twenty-orm/exceptions/twenty-orm.exception';
+
+export const isDuplicateEntryError = (error: unknown): boolean =>
+ error instanceof TwentyOrmException &&
+ error.code === TwentyOrmExceptionCode.DUPLICATE_ENTRY_DETECTED;
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/constants/agent-chat-seeds.constant.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/constants/agent-chat-seeds.constant.ts
index 066ce9ec9f0..afb9db89ef1 100644
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/constants/agent-chat-seeds.constant.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/constants/agent-chat-seeds.constant.ts
@@ -63,3 +63,13 @@ export const APPLE_AGENT_CHAT_CONVERSATION_SEEDS: AgentChatConversationSeed[] =
],
},
];
+
+// Conversations paused on, or already past, a question or an email for Tim's
+// team to decide on.
+export const AGENT_CHAT_INPUT_ASK_THREAD_DATA_SEED_IDS = {
+ PENDING_QUESTIONS: '20202020-0000-4000-8000-000000000015',
+ PENDING_EMAIL_APPROVAL: '20202020-0000-4000-8000-000000000016',
+ SENT_EMAIL_APPROVAL: '20202020-0000-4000-8000-000000000017',
+ ANSWERED_QUESTION: '20202020-0000-4000-8000-000000000018',
+ PENDING_EMAIL_APPROVALS: '20202020-0000-4000-8000-000000000019',
+};
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-agent-chat-input-ask.workspace-service.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-agent-chat-input-ask.workspace-service.ts
new file mode 100644
index 00000000000..6f076fa73ec
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-agent-chat-input-ask.workspace-service.ts
@@ -0,0 +1,496 @@
+import { Injectable } from '@nestjs/common';
+
+import {
+ ASK_QUESTIONS_TOOL_NAME,
+ type AskQuestionItem,
+ type ExtendedUIMessagePart,
+ PROPOSE_EMAIL_TOOL_NAME,
+ type ProposedEmail,
+} from 'twenty-shared/ai';
+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
+import {
+ RecordShareAccessLevel,
+ RecordSharePrincipalType,
+ 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 { 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 { 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_INPUT_ASK_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';
+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';
+import { InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-service';
+
+const AGENT_CHAT_INPUT_ASK_SEED_NAMESPACE =
+ '3c7e1f52-8a4d-4b0e-9d61-2f5a7c9e0b14';
+
+const MEMBERS = {
+ TIM: {
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.TIM,
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.TIM,
+ },
+ JONY: {
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.JONY,
+ },
+ PHIL: {
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.PHIL,
+ userWorkspaceId: USER_WORKSPACE_DATA_SEED_IDS.PHIL,
+ },
+} as const;
+
+type Member = keyof typeof MEMBERS;
+
+const WEBINAR_QUESTIONS: AskQuestionItem[] = [
+ {
+ header: 'Format',
+ question: 'Which format should the Q3 customer webinar use?',
+ options: [
+ {
+ label: 'Live demo',
+ description: 'Forty minutes of product, then questions',
+ isRecommended: true,
+ },
+ { label: 'Customer panel', description: 'Three customers, moderated' },
+ { label: 'Fireside chat', description: 'One guest, one host' },
+ ],
+ },
+ {
+ header: 'Audience',
+ question: 'Who should we invite?',
+ allowMultiSelect: true,
+ options: [
+ { label: 'Customers', isRecommended: true },
+ { label: 'Open opportunities' },
+ { label: 'Churned accounts' },
+ { label: 'Partners' },
+ ],
+ },
+];
+
+const ONBOARDING_OWNER_QUESTIONS: AskQuestionItem[] = [
+ {
+ header: 'Owner',
+ question: 'Who should own the Linear onboarding?',
+ options: [
+ { label: 'Jony', description: 'Designs the rollout with their team' },
+ { label: 'Phil', description: 'Runs the technical setup' },
+ ],
+ },
+];
+
+const AIRBNB_FOLLOW_UP_EMAIL: ProposedEmail = {
+ recipients: {
+ bcc: '',
+ },
+ subject: 'Next steps after our demo',
+ body: 'Hi Airbnb team,\n\nThanks for your time on Tuesday. As promised, here is a summary of what we covered: shared inboxes for your host support team, and workflows that route requests by region.\n\nWould next Thursday work for a technical deep dive with your IT team?\n\nBest,\nJony',
+};
+
+const STRIPE_QUOTE_EMAIL: ProposedEmail = {
+ recipients: { to: '[email protected]', cc: '', bcc: '' },
+ subject: 'Your renewal quote for 2027',
+ body: 'Hi Stripe team,\n\nPlease find your renewal quote for 2027 below: 120 seats on the Organization plan, with the 10% multi-year discount we discussed.\n\nLet me know if anything needs to change before you sign.\n\nBest,\nTim',
+};
+
+export type SeededToolCall = {
+ toolName: string;
+ input: Record<string, unknown>;
+ buildPendingOutput: () => Promise<Record<string, unknown>>;
+};
+
+export const proposeEmailCall = (email: ProposedEmail): SeededToolCall => ({
+ toolName: PROPOSE_EMAIL_TOOL_NAME,
+ input: email,
+ buildPendingOutput: () => createProposeEmailTool().execute(email),
+});
+
+export const askQuestionsCall = (
+ questions: AskQuestionItem[],
+): SeededToolCall => ({
+ toolName: ASK_QUESTIONS_TOOL_NAME,
+ input: { questions },
+ buildPendingOutput: () =>
+ createAskQuestionsTool({ isWorkspaceSetupThread: false }).execute({
+ questions,
+ }),
+});
+
+const LINEAR_WELCOME_EMAIL: ProposedEmail = {
+ recipients: { to: '[email protected]', cc: '', bcc: '' },
+ subject: 'Welcome to Twenty, Linear',
+ body: 'Hi Linear team,\n\nWelcome aboard! Phil will run your onboarding: expect a kickoff invite from him this week, with SSO and your data import on the agenda.\n\nBest,\nTim',
+};
+
+const FIGMA_WELCOME_EMAIL: ProposedEmail = {
+ recipients: { to: '[email protected]', cc: '', bcc: '' },
+ subject: 'Welcome to Twenty, Figma',
+ body: 'Hi Figma team,\n\nWelcome aboard! Your workspace is ready, and we will start with the pipeline import you asked about on our last call.\n\nBest,\nTim',
+};
+
+type ConversationToSeed = {
+ threadId: string;
+ title: string;
+ askedBy: Member;
+ prompt: string;
+ intro: string;
+ // Calls made in the same step, each waiting on its own Ask.
+ calls: SeededToolCall[];
+ // Answers the first call, in a conversation that made only one.
+ answer?: {
+ response: Record<string, unknown>;
+ reply: string;
+ };
+ sharedWith?: { member: Member; accessLevel: RecordShareAccessLevel };
+};
+
+const CONVERSATIONS_TO_SEED: ConversationToSeed[] = [
+ {
+ threadId: AGENT_CHAT_INPUT_ASK_THREAD_DATA_SEED_IDS.PENDING_QUESTIONS,
+ title: 'Plan the Q3 customer webinar',
+ askedBy: 'TIM',
+ prompt: 'Help me plan the Q3 customer webinar and draft the invitation.',
+ intro: 'Two choices before I draft the invitation:',
+ calls: [askQuestionsCall(WEBINAR_QUESTIONS)],
+ },
+ {
+ threadId: AGENT_CHAT_INPUT_ASK_THREAD_DATA_SEED_IDS.PENDING_EMAIL_APPROVAL,
+ title: 'Follow up with Airbnb after the demo',
+ askedBy: 'JONY',
+ prompt: 'Draft the follow-up to Airbnb after Tuesday’s demo.',
+ intro: 'Here is a draft. Review it before it goes out:',
+ calls: [proposeEmailCall(AIRBNB_FOLLOW_UP_EMAIL)],
+ sharedWith: {
+ member: 'JONY',
+ accessLevel: RecordShareAccessLevel.READ_WRITE,
+ },
+ },
+ {
+ threadId: AGENT_CHAT_INPUT_ASK_THREAD_DATA_SEED_IDS.SENT_EMAIL_APPROVAL,
+ title: 'Send the renewal quote to Stripe',
+ askedBy: 'TIM',
+ prompt: 'Send Stripe their renewal quote for 2027.',
+ intro: 'I drafted the quote email. Review it before it goes out:',
+ calls: [proposeEmailCall(STRIPE_QUOTE_EMAIL)],
+ answer: {
+ response: {
+ decision: 'send',
+ email: {
+ ...STRIPE_QUOTE_EMAIL,
+ recipients: {
+ ...STRIPE_QUOTE_EMAIL.recipients,
+ },
+ },
+ },
+ reply:
+ 'Sent. I copied Phil so he can follow up on the signature. Want me to set a reminder for Friday if Stripe hasn’t signed?',
+ },
+ sharedWith: { member: 'PHIL', accessLevel: RecordShareAccessLevel.READ },
+ },
+ {
+ threadId: AGENT_CHAT_INPUT_ASK_THREAD_DATA_SEED_IDS.ANSWERED_QUESTION,
+ title: 'Assign the Linear onboarding',
+ askedBy: 'TIM',
+ prompt: 'Linear signed. Set up their onboarding.',
+ intro: 'One question before I create the onboarding tasks:',
+ calls: [askQuestionsCall(ONBOARDING_OWNER_QUESTIONS)],
+ answer: {
+ response: {
+ answers: [{ questionIndex: 0, selectedOptionIndices: [1] }],
+ },
+ reply:
+ 'Phil owns the Linear onboarding. I will create the kickoff, the SSO setup and the data import tasks for him.',
+ },
+ sharedWith: { member: 'PHIL', accessLevel: RecordShareAccessLevel.READ },
+ },
+ {
+ threadId: AGENT_CHAT_INPUT_ASK_THREAD_DATA_SEED_IDS.PENDING_EMAIL_APPROVALS,
+ title: 'Welcome this week’s new customers',
+ askedBy: 'TIM',
+ prompt: 'Linear and Figma signed this week. Send them a welcome email.',
+ intro: 'I drafted one email for each. Review them before they go out:',
+ calls: [
+ proposeEmailCall(LINEAR_WELCOME_EMAIL),
+ proposeEmailCall(FIGMA_WELCOME_EMAIL),
+ ],
+ },
+];
+
+// Seeds Tim's conversations that wait on a question or an email, or have
+// just been answered, so each card and each answered state renders without
+// calling a model. An Ask is assigned to whoever sent the message it
+// answers.
+@Injectable()
+export class DevSeederAgentChatInputAskWorkspaceService {
+ 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 inputAskWorkspaceService: InputAskWorkspaceService,
+ private readonly recordShareStorageService: RecordShareStorageService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ ) {}
+
+ async seed({ workspaceId }: { workspaceId: string }): Promise<void> {
+ if (workspaceId !== SEED_APPLE_WORKSPACE_ID) {
+ return;
+ }
+
+ for (const conversation of CONVERSATIONS_TO_SEED) {
+ await this.seedConversation({ workspaceId, conversation });
+ }
+
+ await this.shareConversations(workspaceId);
+ }
+
+ private async seedConversation({
+ workspaceId,
+ conversation,
+ }: {
+ workspaceId: string;
+ conversation: ConversationToSeed;
+ }): Promise<void> {
+ const seedId = (name: string) =>
+ v5(
+ `${conversation.threadId}:${name}`,
+ AGENT_CHAT_INPUT_ASK_SEED_NAMESPACE,
+ );
+ const { threadId } = conversation;
+ const askedBy = MEMBERS[conversation.askedBy];
+ const calls = await Promise.all(
+ conversation.calls.map(async (call, callIndex) => {
+ const pausingToolCall = PAUSING_TOOLS.get(call.toolName)?.parseCall(
+ call.input,
+ );
+
+ if (!isDefined(pausingToolCall)) {
+ throw new Error(`Seeded ${call.toolName} call does not parse`);
+ }
+
+ return {
+ ...call,
+ pausingToolCall,
+ pendingOutput: await call.buildPendingOutput(),
+ // The first call keeps the id it had when conversations made one.
+ toolCallId: `call_${seedId(callIndex === 0 ? 'toolCall' : `toolCall${callIndex}`).replace(/-/g, '')}`,
+ };
+ }),
+ );
+ const [firstCall] = calls;
+
+ await this.threadRepository.insert(workspaceId, {
+ id: threadId,
+ title: conversation.title,
+ workspaceMemberId: MEMBERS.TIM.workspaceMemberId,
+ userWorkspaceId: MEMBERS.TIM.userWorkspaceId,
+ });
+
+ const questionTurnId = seedId('questionTurn');
+
+ await this.turnRepository.insert(workspaceId, {
+ id: questionTurnId,
+ threadId,
+ });
+
+ await this.insertMessage({
+ workspaceId,
+ id: seedId('promptMessage'),
+ threadId,
+ turnId: questionTurnId,
+ role: AgentMessageRole.USER,
+ senderUserWorkspaceId: askedBy.userWorkspaceId,
+ parts: [{ type: 'text', text: conversation.prompt }],
+ });
+
+ const completion = isDefined(conversation.answer)
+ ? await firstCall.pausingToolCall.complete({
+ output: conversation.answer.response,
+ context: {
+ // Seeds never send anything: the email reads as sent, as it would
+ // once the person's own send_email succeeded.
+ executeTool: async () => ({
+ success: true,
+ message: 'Email sent successfully',
+ }),
+ },
+ })
+ : undefined;
+
+ await this.insertMessage({
+ workspaceId,
+ id: seedId('assistantMessage'),
+ threadId,
+ turnId: questionTurnId,
+ role: AgentMessageRole.ASSISTANT,
+ senderUserWorkspaceId: null,
+ parts: mapAiStepsToUiMessageParts([
+ {
+ content: [
+ { type: 'text', text: conversation.intro },
+ ...calls.flatMap((call) => [
+ {
+ type: 'tool-call' as const,
+ toolCallId: call.toolCallId,
+ toolName: call.toolName,
+ input: call.input,
+ },
+ {
+ type: 'tool-result' as const,
+ toolCallId: call.toolCallId,
+ toolName: call.toolName,
+ input: call.input,
+ output:
+ call === firstCall && isDefined(completion)
+ ? completion.toolResult
+ : call.pendingOutput,
+ },
+ ]),
+ ],
+ },
+ ]),
+ });
+
+ for (const call of calls) {
+ await this.inputAskWorkspaceService.open({
+ workspaceId,
+ inputAsk: {
+ ...call.pausingToolCall.buildAsk(),
+ threadId,
+ toolCallId: call.toolCallId,
+ assigneeId: askedBy.workspaceMemberId,
+ },
+ });
+ }
+
+ if (!isDefined(conversation.answer) || !isDefined(completion)) {
+ return;
+ }
+
+ await this.inputAskWorkspaceService.answer({
+ workspaceId,
+ key: { threadId, toolCallId: firstCall.toolCallId },
+ response: conversation.answer.response,
+ });
+
+ const answerTurnId = seedId('answerTurn');
+
+ await this.turnRepository.insert(workspaceId, {
+ id: answerTurnId,
+ threadId,
+ });
+
+ await this.insertMessage({
+ workspaceId,
+ id: seedId('answerMessage'),
+ threadId,
+ turnId: answerTurnId,
+ role: AgentMessageRole.USER,
+ senderUserWorkspaceId: askedBy.userWorkspaceId,
+ parts: [{ type: 'text', text: completion.answerText }],
+ });
+
+ await this.insertMessage({
+ workspaceId,
+ id: seedId('replyMessage'),
+ threadId,
+ turnId: answerTurnId,
+ role: AgentMessageRole.ASSISTANT,
+ 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, [
+ 'flatObjectMetadataMaps',
+ ]);
+ const threadObjectMetadataId =
+ flatObjectMetadataMaps.byUniversalIdentifier[
+ STANDARD_OBJECTS.agentChatThread.universalIdentifier
+ ]?.id;
+
+ if (!isDefined(threadObjectMetadataId)) {
+ return;
+ }
+
+ await this.recordShareStorageService.insertMany({
+ workspaceId,
+ recordShares: CONVERSATIONS_TO_SEED.flatMap(({ threadId, sharedWith }) =>
+ isDefined(sharedWith)
+ ? [
+ {
+ recordId: threadId,
+ objectMetadataId: threadObjectMetadataId,
+ principalId: MEMBERS[sharedWith.member].workspaceMemberId,
+ principalType: RecordSharePrincipalType.WORKSPACE_MEMBER,
+ accessLevel: sharedWith.accessLevel,
+ rowCause: RecordShareRowCause.MANUAL,
+ sourceId: threadId,
+ },
+ ]
+ : [],
+ ),
+ });
+ }
+}
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-agent-question.workspace-service.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-agent-question.workspace-service.ts
deleted file mode 100644
index 7c9294389f9..00000000000
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-agent-question.workspace-service.ts
+++ /dev/null
@@ -1,304 +0,0 @@
-import { Injectable } from '@nestjs/common';
-
-import {
- ASK_QUESTIONS_TOOL_NAME,
- type AskQuestionItem,
-} from 'twenty-shared/ai';
-import { type ActorMetadata, FieldActorSource } from 'twenty-shared/types';
-import { StepStatus, WorkflowActionType } from 'twenty-shared/workflow';
-import { v5 } from 'uuid';
-
-import {
- WorkflowVersionEntity,
- WorkflowVersionStatus,
-} from 'src/engine/core-modules/workflow/entities/workflow-version.entity';
-import { WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workflow.entity';
-import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
-import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
-import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
-import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
-import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
-import { WorkflowRunStatus } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
-import { type WorkflowVersionWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow-version.workspace-entity';
-import {
- WorkflowStatus,
- type WorkflowWorkspaceEntity,
-} from 'src/modules/workflow/common/standard-objects/workflow.workspace-entity';
-import { type WorkflowAiAgentAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
-import { WorkflowAgentConversationWorkspaceService } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service';
-import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
-import {
- type WorkflowManualTrigger,
- WorkflowTriggerType,
-} from 'src/modules/workflow/workflow-trigger/types/workflow-trigger.type';
-
-const WORKFLOW_AGENT_QUESTION_SEED_NAMESPACE =
- '6f0a9a3e-2b1f-4c55-9f0b-7c1d2e3f4a5b';
-
-const seedId = (name: string, workspaceId: string) =>
- v5(`${name}:${workspaceId}`, WORKFLOW_AGENT_QUESTION_SEED_NAMESPACE);
-
-const WORKFLOW_NAME = 'Qualify inbound lead';
-
-const SYSTEM_ACTOR: ActorMetadata = {
- source: FieldActorSource.SYSTEM,
- workspaceMemberId: null,
- name: 'System',
- context: {},
-};
-
-const PROMPT =
- 'Qualify the inbound lead from Figma and decide who should follow up.';
-
-const QUESTIONS: AskQuestionItem[] = [
- {
- header: 'Budget',
- question: 'Which budget range did Figma mention on the demo call?',
- options: [
- { label: 'Under $10k' },
- { label: '$10k to $50k', isRecommended: true },
- { label: 'Over $50k' },
- ],
- },
- {
- header: 'Owner',
- question: 'Who should own the follow-up?',
- options: [
- { label: 'Tim', description: 'Account executive' },
- { label: 'Phil', description: 'Solutions engineer' },
- ],
- },
- {
- header: 'Channels',
- question: 'Which channels should the follow-up use?',
- allowMultiSelect: true,
- options: [
- { label: 'Email', isRecommended: true },
- { label: 'Call' },
- { label: 'LinkedIn' },
- ],
- },
-];
-
-// Seeds a workflow whose agent step is waiting on a person, so the run view,
-// the paused conversation and its question card can be tried without calling
-// a model.
-@Injectable()
-export class DevSeederWorkflowAgentQuestionWorkspaceService {
- constructor(
- private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,
- private readonly workflowAgentConversationService: WorkflowAgentConversationWorkspaceService,
- private readonly workspaceOrmManager: WorkspaceOrmManager,
- @InjectWorkspaceScopedRepository(WorkflowEntity)
- private readonly coreWorkflowRepository: WorkspaceScopedRepository<WorkflowEntity>,
- @InjectWorkspaceScopedRepository(WorkflowVersionEntity)
- private readonly coreWorkflowVersionRepository: WorkspaceScopedRepository<WorkflowVersionEntity>,
- ) {}
-
- async seed({
- workspaceId,
- applicationId,
- }: {
- workspaceId: string;
- applicationId: string;
- }): Promise<void> {
- const workspaceWorkflowId = seedId('workflow', workspaceId);
- const workspaceWorkflowVersionId = seedId('workflowVersion', workspaceId);
- const coreWorkflowId = seedId('coreWorkflow', workspaceId);
- const coreWorkflowVersionId = seedId('coreWorkflowVersion', workspaceId);
-
- const agentStep: WorkflowAiAgentAction = {
- id: seedId('agentStep', workspaceId),
- name: 'Qualify the lead',
- type: WorkflowActionType.AI_AGENT,
- valid: true,
- settings: {
- input: {
- prompt: PROMPT,
- canAskQuestions: true,
- },
- outputSchema: {},
- errorHandlingOptions: {
- retryOnFailure: { value: 0 },
- continueOnFailure: { value: false },
- },
- },
- nextStepIds: [],
- };
-
- const trigger: WorkflowManualTrigger = {
- name: 'Launch manually',
- type: WorkflowTriggerType.MANUAL,
- settings: {
- outputSchema: {},
- icon: 'IconUserCheck',
- availability: { type: 'GLOBAL', locations: undefined },
- },
- nextStepIds: [agentStep.id],
- };
-
- await this.insertWorkflow({
- workspaceId,
- applicationId,
- workspaceWorkflowId,
- workspaceWorkflowVersionId,
- coreWorkflowId,
- coreWorkflowVersionId,
- trigger,
- agentStep,
- });
-
- const workflowRunId = seedId('workflowRun', workspaceId);
- const toolCallId = seedId('toolCall', workspaceId);
-
- await this.workflowRunWorkspaceService.createCoreWorkflowRun({
- workflowRunId,
- coreWorkflowId,
- coreWorkflowVersionId,
- workspaceWorkflowId,
- workspaceWorkflowVersionId,
- workflowName: WORKFLOW_NAME,
- trigger,
- steps: [agentStep],
- createdBy: {
- source: FieldActorSource.MANUAL,
- workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.TIM,
- name: 'Tim Apple',
- context: {},
- },
- status: WorkflowRunStatus.NOT_STARTED,
- triggerPayload: {},
- workspaceId,
- });
-
- await this.workflowRunWorkspaceService.startWorkflowRun({
- workflowRunId,
- workspaceId,
- });
-
- await this.workflowRunWorkspaceService.updateWorkflowRunStepInfo({
- stepId: agentStep.id,
- stepInfo: { status: StepStatus.PENDING },
- workflowRunId,
- workspaceId,
- });
-
- await this.workflowAgentConversationService.recordExecution({
- workspaceId,
- workflowRunId,
- stepId: agentStep.id,
- title: agentStep.name,
- agentId: null,
- prompt: PROMPT,
- initiatorUserWorkspaceId: null,
- executionResult: {
- isPaused: true,
- steps: [
- {
- content: [
- {
- type: 'tool-call',
- toolCallId,
- toolName: ASK_QUESTIONS_TOOL_NAME,
- input: { questions: QUESTIONS },
- },
- {
- type: 'tool-result',
- toolCallId,
- toolName: ASK_QUESTIONS_TOOL_NAME,
- input: { questions: QUESTIONS },
- output: {
- success: true,
- message:
- 'Questions presented to the user; awaiting their answer.',
- result: { questions: QUESTIONS, status: 'pending' },
- },
- },
- ],
- },
- ],
- },
- });
- }
-
- private async insertWorkflow({
- workspaceId,
- applicationId,
- workspaceWorkflowId,
- workspaceWorkflowVersionId,
- coreWorkflowId,
- coreWorkflowVersionId,
- trigger,
- agentStep,
- }: {
- workspaceId: string;
- applicationId: string;
- workspaceWorkflowId: string;
- workspaceWorkflowVersionId: string;
- coreWorkflowId: string;
- coreWorkflowVersionId: string;
- trigger: WorkflowManualTrigger;
- agentStep: WorkflowAiAgentAction;
- }): Promise<void> {
- await this.workspaceOrmManager.executeInWorkspaceContext(async () => {
- await this.workspaceOrmManager
- .getRepository<WorkflowWorkspaceEntity>(
- 'workflow',
- { shouldBypassPermissionChecks: true },
- { shouldSkipEventEmission: true },
- )
- .insert({
- id: workspaceWorkflowId,
- name: WORKFLOW_NAME,
- lastPublishedVersionId: workspaceWorkflowVersionId,
- statuses: [WorkflowStatus.ACTIVE],
- position: 3,
- createdBy: SYSTEM_ACTOR,
- updatedBy: SYSTEM_ACTOR,
- coreWorkflowId,
- });
-
- await this.workspaceOrmManager
- .getRepository<WorkflowVersionWorkspaceEntity>(
- 'workflowVersion',
- { shouldBypassPermissionChecks: true },
- { shouldSkipEventEmission: true },
- )
- .insert({
- id: workspaceWorkflowVersionId,
- name: 'v1',
- trigger,
- steps: [agentStep],
- status: WorkflowVersionStatus.ACTIVE,
- position: 1,
- workflowId: workspaceWorkflowId,
- coreWorkflowVersionId,
- });
- }, buildSystemAuthContext(workspaceId));
-
- await this.coreWorkflowRepository.insert(workspaceId, {
- id: coreWorkflowId,
- universalIdentifier: seedId('workflowUniversalIdentifier', workspaceId),
- applicationId,
- name: WORKFLOW_NAME,
- lastPublishedVersionId: workspaceWorkflowVersionId,
- workspaceWorkflowId,
- lastPublishedCoreWorkflowVersionId: coreWorkflowVersionId,
- });
-
- await this.coreWorkflowVersionRepository.insert(workspaceId, {
- id: coreWorkflowVersionId,
- universalIdentifier: seedId(
- 'workflowVersionUniversalIdentifier',
- workspaceId,
- ),
- applicationId,
- triggers: [trigger],
- steps: [agentStep],
- status: WorkflowVersionStatus.ACTIVE,
- workflowId: workspaceWorkflowId,
- coreWorkflowId,
- workspaceWorkflowVersionId,
- });
- }
-}
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-input-ask.workspace-service.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-input-ask.workspace-service.ts
new file mode 100644
index 00000000000..55267b980e2
--- /dev/null
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-input-ask.workspace-service.ts
@@ -0,0 +1,528 @@
+import { Injectable } from '@nestjs/common';
+
+import { type AskQuestionItem, type ProposedEmail } from 'twenty-shared/ai';
+import {
+ type ActorMetadata,
+ FieldActorSource,
+ FieldMetadataType,
+} from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+import { StepStatus, WorkflowActionType } from 'twenty-shared/workflow';
+import { v5 } from 'uuid';
+
+import {
+ WorkflowVersionEntity,
+ WorkflowVersionStatus,
+} from 'src/engine/core-modules/workflow/entities/workflow-version.entity';
+import { WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workflow.entity';
+import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
+import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
+import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
+import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
+import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
+import {
+ askQuestionsCall,
+ proposeEmailCall,
+ type SeededToolCall,
+} from 'src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-agent-chat-input-ask.workspace-service';
+import { WorkflowRunStatus } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
+import { type WorkflowVersionWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow-version.workspace-entity';
+import {
+ WorkflowStatus,
+ type WorkflowWorkspaceEntity,
+} from 'src/modules/workflow/common/standard-objects/workflow.workspace-entity';
+import { type WorkflowPendingAsk } from 'src/modules/workflow/workflow-executor/types/workflow-pending-ask.type';
+import { WorkflowAgentConversationWorkspaceService } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service';
+import {
+ type WorkflowAction,
+ type WorkflowFormAction,
+} from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
+import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
+import {
+ type WorkflowManualTrigger,
+ WorkflowTriggerType,
+} from 'src/modules/workflow/workflow-trigger/types/workflow-trigger.type';
+
+const WORKFLOW_INPUT_ASK_SEED_NAMESPACE =
+ '6f0a9a3e-2b1f-4c55-9f0b-7c1d2e3f4a5b';
+
+const seedId = (name: string, workspaceId: string) =>
+ v5(`${name}:${workspaceId}`, WORKFLOW_INPUT_ASK_SEED_NAMESPACE);
+
+const SYSTEM_ACTOR: ActorMetadata = {
+ source: FieldActorSource.SYSTEM,
+ workspaceMemberId: null,
+ name: 'System',
+ context: {},
+};
+
+const INITIATORS = {
+ TIM: {
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.TIM,
+ name: 'Tim Apple',
+ },
+ JONY: {
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ name: 'Jony Ive',
+ },
+ PHIL: {
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.PHIL,
+ name: 'Phil Schiler',
+ },
+} as const;
+
+type Initiator = keyof typeof INITIATORS;
+
+const QUALIFICATION_QUESTIONS: AskQuestionItem[] = [
+ {
+ header: 'Budget',
+ question: 'Which budget range did Figma mention on the demo call?',
+ options: [
+ { label: 'Under $10k' },
+ { label: '$10k to $50k', isRecommended: true },
+ { label: 'Over $50k' },
+ ],
+ },
+ {
+ header: 'Owner',
+ question: 'Who should own the follow-up?',
+ options: [
+ { label: 'Tim', description: 'Account executive' },
+ { label: 'Phil', description: 'Solutions engineer' },
+ ],
+ },
+ {
+ header: 'Channels',
+ question: 'Which channels should the follow-up use?',
+ allowMultiSelect: true,
+ options: [
+ { label: 'Email', isRecommended: true },
+ { label: 'Call' },
+ { label: 'LinkedIn' },
+ ],
+ },
+];
+
+const RENEWAL_REMINDER_EMAIL: ProposedEmail = {
+ recipients: { to: '[email protected]', cc: '', bcc: '' },
+ subject: 'Your Twenty renewal on October 31',
+ body: 'Hi Stripe team,\n\nYour Twenty subscription renews on October 31 for another year at the same price. If you want to add seats or change plans before then, just reply to this email.\n\nBest,\nPhil',
+};
+
+type AgentWorkflowToSeed = {
+ key: string;
+ name: string;
+ position: number;
+ icon: string;
+ stepKey: string;
+ stepName: string;
+ stepPrompt: string;
+ runKey: string;
+ initiator: Initiator;
+ runPrompt: string;
+ call: SeededToolCall;
+};
+
+const AGENT_WORKFLOWS_TO_SEED: AgentWorkflowToSeed[] = [
+ {
+ key: 'qualifyInboundLead',
+ name: 'Qualify inbound lead',
+ position: 3,
+ icon: 'IconUserCheck',
+ stepKey: 'agentStep',
+ stepName: 'Qualify the lead',
+ stepPrompt: 'Qualify the inbound lead and draft the first reply.',
+ runKey: 'qualification',
+ initiator: 'TIM',
+ runPrompt:
+ 'Qualify the inbound lead from Figma and decide who should follow up.',
+ call: askQuestionsCall(QUALIFICATION_QUESTIONS),
+ },
+ {
+ key: 'draftRenewalReminder',
+ name: 'Draft renewal reminder',
+ position: 4,
+ icon: 'IconMail',
+ stepKey: 'renewalAgentStep',
+ stepName: 'Draft the reminder',
+ stepPrompt:
+ 'Draft a renewal reminder for the account and have it reviewed before it goes out.',
+ runKey: 'renewalReminder',
+ initiator: 'PHIL',
+ runPrompt:
+ 'Stripe renews on October 31. Draft the renewal reminder for their procurement team.',
+ call: proposeEmailCall(RENEWAL_REMINDER_EMAIL),
+ },
+];
+
+const DISCOUNT_RUNS_TO_SEED: {
+ suffix: string;
+ initiator: Initiator;
+ endStatus?: WorkflowRunStatus.COMPLETED | WorkflowRunStatus.STOPPED;
+ response?: Record<string, unknown>;
+}[] = [
+ {
+ suffix: 'Answered',
+ initiator: 'TIM',
+ endStatus: WorkflowRunStatus.COMPLETED,
+ response: {
+ discount: 15,
+ justification: 'Three-year commitment signed by Airbnb procurement.',
+ },
+ },
+ {
+ suffix: 'Stopped',
+ initiator: 'PHIL',
+ endStatus: WorkflowRunStatus.STOPPED,
+ },
+ { suffix: 'Pending', initiator: 'JONY' },
+];
+
+const ERROR_HANDLING_OPTIONS = {
+ retryOnFailure: { value: 0 },
+ continueOnFailure: { value: false },
+};
+
+type SeededWorkflow = {
+ workspaceWorkflowId: string;
+ workspaceWorkflowVersionId: string;
+ coreWorkflowId: string;
+ coreWorkflowVersionId: string;
+ name: string;
+ trigger: WorkflowManualTrigger;
+ step: WorkflowAction;
+};
+
+// Seeds workflow runs waiting on a person, and runs whose wait is over, so
+// the run view, the paused conversations and every kind of Ask card can be
+// tried without calling a model.
+@Injectable()
+export class DevSeederWorkflowInputAskWorkspaceService {
+ constructor(
+ private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,
+ private readonly workflowAgentConversationService: WorkflowAgentConversationWorkspaceService,
+ private readonly workspaceOrmManager: WorkspaceOrmManager,
+ @InjectWorkspaceScopedRepository(WorkflowEntity)
+ private readonly coreWorkflowRepository: WorkspaceScopedRepository<WorkflowEntity>,
+ @InjectWorkspaceScopedRepository(WorkflowVersionEntity)
+ private readonly coreWorkflowVersionRepository: WorkspaceScopedRepository<WorkflowVersionEntity>,
+ ) {}
+
+ async seed({
+ workspaceId,
+ applicationId,
+ }: {
+ workspaceId: string;
+ applicationId: string;
+ }): Promise<void> {
+ for (const agentWorkflow of AGENT_WORKFLOWS_TO_SEED) {
+ const workflow = await this.insertWorkflow({
+ workspaceId,
+ applicationId,
+ key: agentWorkflow.key,
+ name: agentWorkflow.name,
+ position: agentWorkflow.position,
+ icon: agentWorkflow.icon,
+ step: {
+ id: seedId(agentWorkflow.stepKey, workspaceId),
+ name: agentWorkflow.stepName,
+ type: WorkflowActionType.AI_AGENT,
+ valid: true,
+ settings: {
+ input: { prompt: agentWorkflow.stepPrompt, canAskQuestions: true },
+ outputSchema: {},
+ errorHandlingOptions: ERROR_HANDLING_OPTIONS,
+ },
+ nextStepIds: [],
+ },
+ });
+ const workflowRunId = seedId(
+ `workflowRun:${agentWorkflow.runKey}`,
+ workspaceId,
+ );
+ const toolCallId = seedId(
+ `toolCall:${agentWorkflow.runKey}`,
+ workspaceId,
+ );
+ const { toolName, input } = agentWorkflow.call;
+ const output = await agentWorkflow.call.buildPendingOutput();
+
+ await this.seedPausedRun({
+ workspaceId,
+ workflowRunId,
+ workflow,
+ initiator: agentWorkflow.initiator,
+ recordPendingAsks: async () =>
+ (
+ await this.workflowAgentConversationService.recordExecution({
+ workspaceId,
+ workflowRunId,
+ stepId: workflow.step.id,
+ title: workflow.step.name,
+ agentId: null,
+ prompt: agentWorkflow.runPrompt,
+ initiatorUserWorkspaceId: null,
+ executionResult: {
+ isPaused: true,
+ steps: [
+ {
+ content: [
+ { type: 'tool-call', toolCallId, toolName, input },
+ {
+ type: 'tool-result',
+ toolCallId,
+ toolName,
+ input,
+ output,
+ },
+ ],
+ },
+ ],
+ },
+ })
+ )?.pendingAsks,
+ });
+ }
+
+ const formStep: WorkflowFormAction = {
+ id: seedId('formStep', workspaceId),
+ name: 'Approve discount',
+ type: WorkflowActionType.FORM,
+ valid: true,
+ settings: {
+ input: [
+ {
+ id: seedId('formField:discount', workspaceId),
+ name: 'discount',
+ label: 'Approved discount (%)',
+ type: FieldMetadataType.NUMBER,
+ placeholder: '10',
+ },
+ {
+ id: seedId('formField:justification', workspaceId),
+ name: 'justification',
+ label: 'Justification',
+ type: FieldMetadataType.TEXT,
+ placeholder: 'Why this discount is worth it',
+ },
+ ],
+ outputSchema: {},
+ errorHandlingOptions: ERROR_HANDLING_OPTIONS,
+ },
+ nextStepIds: [],
+ };
+
+ const discountWorkflow = await this.insertWorkflow({
+ workspaceId,
+ applicationId,
+ key: 'approveDiscount',
+ name: 'Approve discount',
+ position: 5,
+ icon: 'IconDiscount',
+ step: formStep,
+ });
+
+ for (const discountRun of DISCOUNT_RUNS_TO_SEED) {
+ const workflowRunId = seedId(
+ `workflowRun:discount${discountRun.suffix}`,
+ workspaceId,
+ );
+
+ await this.seedPausedRun({
+ workspaceId,
+ workflowRunId,
+ workflow: discountWorkflow,
+ initiator: discountRun.initiator,
+ recordPendingAsks: async () => [
+ {
+ name: formStep.name,
+ form: { kind: 'formFields', fields: formStep.settings.input },
+ },
+ ],
+ });
+
+ if (isDefined(discountRun.response)) {
+ await this.workflowRunWorkspaceService.updateStepInfoIfPending({
+ stepId: formStep.id,
+ stepInfo: {
+ status: StepStatus.SUCCESS,
+ result: discountRun.response,
+ },
+ inputAskResponse: discountRun.response,
+ workflowRunId,
+ workspaceId,
+ });
+ }
+
+ if (isDefined(discountRun.endStatus)) {
+ await this.workflowRunWorkspaceService.endWorkflowRun({
+ workflowRunId,
+ workspaceId,
+ status: discountRun.endStatus,
+ });
+ }
+ }
+ }
+
+ // Parks the run's step the way the executor parks a step that waits on a
+ // person, opening its Asks assigned to whoever started the run.
+ private async seedPausedRun({
+ workspaceId,
+ workflowRunId,
+ workflow,
+ initiator,
+ recordPendingAsks,
+ }: {
+ workspaceId: string;
+ workflowRunId: string;
+ workflow: SeededWorkflow;
+ initiator: Initiator;
+ recordPendingAsks: () => Promise<WorkflowPendingAsk[] | undefined>;
+ }): Promise<void> {
+ await this.workflowRunWorkspaceService.createCoreWorkflowRun({
+ workflowRunId,
+ coreWorkflowId: workflow.coreWorkflowId,
+ coreWorkflowVersionId: workflow.coreWorkflowVersionId,
+ workspaceWorkflowId: workflow.workspaceWorkflowId,
+ workspaceWorkflowVersionId: workflow.workspaceWorkflowVersionId,
+ workflowName: workflow.name,
+ trigger: workflow.trigger,
+ steps: [workflow.step],
+ createdBy: {
+ source: FieldActorSource.MANUAL,
+ ...INITIATORS[initiator],
+ context: {},
+ },
+ status: WorkflowRunStatus.NOT_STARTED,
+ triggerPayload: {},
+ workspaceId,
+ });
+
+ await this.workflowRunWorkspaceService.startWorkflowRun({
+ workflowRunId,
+ workspaceId,
+ });
+
+ await this.workflowRunWorkspaceService.updateWorkflowRunStepInfo({
+ stepId: workflow.step.id,
+ stepInfo: { status: StepStatus.PENDING },
+ pendingAsks: await recordPendingAsks(),
+ workflowRunId,
+ workspaceId,
+ });
+ }
+
+ private async insertWorkflow({
+ workspaceId,
+ applicationId,
+ key,
+ name,
+ position,
+ icon,
+ step,
+ }: {
+ workspaceId: string;
+ applicationId: string;
+ key: string;
+ name: string;
+ position: number;
+ icon: string;
+ step: WorkflowAction;
+ }): Promise<SeededWorkflow> {
+ const workspaceWorkflowId = seedId(`workflow:${key}`, workspaceId);
+ const workspaceWorkflowVersionId = seedId(
+ `workflowVersion:${key}`,
+ workspaceId,
+ );
+ const coreWorkflowId = seedId(`coreWorkflow:${key}`, workspaceId);
+ const coreWorkflowVersionId = seedId(
+ `coreWorkflowVersion:${key}`,
+ workspaceId,
+ );
+
+ const trigger: WorkflowManualTrigger = {
+ name: 'Launch manually',
+ type: WorkflowTriggerType.MANUAL,
+ settings: {
+ outputSchema: {},
+ icon,
+ availability: { type: 'GLOBAL', locations: undefined },
+ },
+ nextStepIds: [step.id],
+ };
+
+ await this.workspaceOrmManager.executeInWorkspaceContext(async () => {
+ await this.workspaceOrmManager
+ .getRepository<WorkflowWorkspaceEntity>(
+ 'workflow',
+ { shouldBypassPermissionChecks: true },
+ { shouldSkipEventEmission: true },
+ )
+ .insert({
+ id: workspaceWorkflowId,
+ name,
+ lastPublishedVersionId: workspaceWorkflowVersionId,
+ statuses: [WorkflowStatus.ACTIVE],
+ position,
+ createdBy: SYSTEM_ACTOR,
+ updatedBy: SYSTEM_ACTOR,
+ coreWorkflowId,
+ });
+
+ await this.workspaceOrmManager
+ .getRepository<WorkflowVersionWorkspaceEntity>(
+ 'workflowVersion',
+ { shouldBypassPermissionChecks: true },
+ { shouldSkipEventEmission: true },
+ )
+ .insert({
+ id: workspaceWorkflowVersionId,
+ name: 'v1',
+ trigger,
+ steps: [step],
+ status: WorkflowVersionStatus.ACTIVE,
+ position: 1,
+ workflowId: workspaceWorkflowId,
+ coreWorkflowVersionId,
+ });
+ }, buildSystemAuthContext(workspaceId));
+
+ await this.coreWorkflowRepository.insert(workspaceId, {
+ id: coreWorkflowId,
+ universalIdentifier: seedId(
+ `workflowUniversalIdentifier:${key}`,
+ workspaceId,
+ ),
+ applicationId,
+ name,
+ lastPublishedVersionId: workspaceWorkflowVersionId,
+ workspaceWorkflowId,
+ lastPublishedCoreWorkflowVersionId: coreWorkflowVersionId,
+ });
+
+ await this.coreWorkflowVersionRepository.insert(workspaceId, {
+ id: coreWorkflowVersionId,
+ universalIdentifier: seedId(
+ `workflowVersionUniversalIdentifier:${key}`,
+ workspaceId,
+ ),
+ applicationId,
+ triggers: [trigger],
+ steps: [step],
+ status: WorkflowVersionStatus.ACTIVE,
+ workflowId: workspaceWorkflowId,
+ coreWorkflowId,
+ workspaceWorkflowVersionId,
+ });
+
+ return {
+ workspaceWorkflowId,
+ workspaceWorkflowVersionId,
+ coreWorkflowId,
+ coreWorkflowVersionId,
+ name,
+ trigger,
+ step,
+ };
+ }
+}
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/dev-seeder.module.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/dev-seeder.module.ts
index feefba5df52..99f3f817a11 100644
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/dev-seeder.module.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/dev-seeder.module.ts
@@ -10,6 +10,7 @@ import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-
import { SdkClientModule } from 'src/engine/core-modules/sdk-client/sdk-client.module';
import { SecretEncryptionModule } from 'src/engine/core-modules/secret-encryption/secret-encryption.module';
import { FileStorageModule } from 'src/engine/core-modules/file-storage/file-storage.module';
+import { RecordShareStorageModule } from 'src/engine/core-modules/record-share/record-share-storage.module';
import { WorkflowVersionEntity } from 'src/engine/core-modules/workflow/entities/workflow-version.entity';
import { WorkflowEntity } from 'src/engine/core-modules/workflow/entities/workflow.entity';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
@@ -29,9 +30,11 @@ import { WorkspaceCacheStorageModule } from 'src/engine/workspace-cache-storage/
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
import { WorkspaceDataSourceModule } from 'src/engine/workspace-datasource/workspace-datasource.module';
import { DevSeederPermissionsService } from 'src/engine/workspace-manager/dev-seeder/core/services/dev-seeder-permissions.service';
+import { DevSeederAgentChatInputAskWorkspaceService } from 'src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-agent-chat-input-ask.workspace-service';
import { DevSeederDataService } from 'src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-data.service';
-import { DevSeederWorkflowAgentQuestionWorkspaceService } from 'src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-agent-question.workspace-service';
+import { DevSeederWorkflowInputAskWorkspaceService } from 'src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-input-ask.workspace-service';
import { TimelineActivitySeederService } from 'src/engine/workspace-manager/dev-seeder/data/services/timeline-activity-seeder.service';
+import { InputAskModule } from 'src/modules/input-ask/input-ask.module';
import { TimelineActivityModule } from 'src/modules/timeline/timeline-activity.module';
import { DevSeederMetadataService } from 'src/engine/workspace-manager/dev-seeder/metadata/services/dev-seeder-metadata.service';
import { DevSeederWorkspaceService } from 'src/engine/workspace-manager/dev-seeder/services/dev-seeder.workspace-service';
@@ -76,6 +79,8 @@ import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow
UpgradeModule,
WorkflowRunModule,
WorkflowAgentConversationModule,
+ InputAskModule,
+ RecordShareStorageModule,
],
exports: [DevSeederWorkspaceService],
providers: [
@@ -84,7 +89,8 @@ import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow
DevSeederPermissionsService,
DevSeederDataService,
TimelineActivitySeederService,
- DevSeederWorkflowAgentQuestionWorkspaceService,
+ DevSeederWorkflowInputAskWorkspaceService,
+ DevSeederAgentChatInputAskWorkspaceService,
provideWorkspaceScopedRepository(RoleEntity),
provideWorkspaceScopedRepository(ObjectMetadataEntity),
provideWorkspaceScopedRepository(WorkflowEntity),
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/services/dev-seeder.workspace-service.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/services/dev-seeder.workspace-service.ts
index ba8788b7817..c56376bdcdd 100644
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/services/dev-seeder.workspace-service.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/services/dev-seeder.workspace-service.ts
@@ -48,8 +48,9 @@ import { seedUnsubscribeTopics } from 'src/engine/workspace-manager/dev-seeder/c
import { seedUserWorkspaces } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';
import { seedUsers } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-users.util';
import { createWorkspace } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-workspace.util';
+import { DevSeederAgentChatInputAskWorkspaceService } from 'src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-agent-chat-input-ask.workspace-service';
import { DevSeederDataService } from 'src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-data.service';
-import { DevSeederWorkflowAgentQuestionWorkspaceService } from 'src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-agent-question.workspace-service';
+import { DevSeederWorkflowInputAskWorkspaceService } from 'src/engine/workspace-manager/dev-seeder/data/services/dev-seeder-workflow-input-ask.workspace-service';
import { DevSeederMetadataService } from 'src/engine/workspace-manager/dev-seeder/metadata/services/dev-seeder-metadata.service';
import { PrefillFrontComponentService } from 'src/engine/workspace-manager/standard-objects-prefill-data/services/prefill-front-component.service';
import { PrefillLogicFunctionService } from 'src/engine/workspace-manager/standard-objects-prefill-data/services/prefill-logic-function.service';
@@ -70,7 +71,8 @@ export class DevSeederWorkspaceService {
private readonly devSeederMetadataService: DevSeederMetadataService,
private readonly devSeederPermissionsService: DevSeederPermissionsService,
private readonly devSeederDataService: DevSeederDataService,
- private readonly devSeederWorkflowAgentQuestionService: DevSeederWorkflowAgentQuestionWorkspaceService,
+ private readonly devSeederWorkflowInputAskService: DevSeederWorkflowInputAskWorkspaceService,
+ private readonly devSeederAgentChatInputAskService: DevSeederAgentChatInputAskWorkspaceService,
private readonly applicationService: ApplicationService,
private readonly applicationRegistrationService: ApplicationRegistrationService,
private readonly workspaceCacheService: WorkspaceCacheService,
@@ -226,6 +228,9 @@ export class DevSeederWorkspaceService {
light,
});
+ // Before the chat seed, whose owner grants then cover these threads too.
+ await this.devSeederAgentChatInputAskService.seed({ workspaceId });
+
await this.seedAgentChat({
workspaceId,
chatReferenceIds: {
@@ -236,7 +241,7 @@ export class DevSeederWorkspaceService {
},
});
- await this.devSeederWorkflowAgentQuestionService.seed({
+ await this.devSeederWorkflowInputAskService.seed({
workspaceId,
applicationId: workspaceCustomFlatApplication.id,
});
diff --git a/packages/twenty-server/src/modules/contact-creation-manager/services/create-company-and-contact.service.ts b/packages/twenty-server/src/modules/contact-creation-manager/services/create-company-and-contact.service.ts
index a74bdbf1adc..2e0f79a502b 100644
--- a/packages/twenty-server/src/modules/contact-creation-manager/services/create-company-and-contact.service.ts
+++ b/packages/twenty-server/src/modules/contact-creation-manager/services/create-company-and-contact.service.ts
@@ -17,12 +17,9 @@ import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handl
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { type ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
-import {
- TwentyOrmException,
- TwentyOrmExceptionCode,
-} from 'src/engine/twenty-orm/exceptions/twenty-orm.exception';
import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
+import { isDuplicateEntryError } from 'src/engine/twenty-orm/utils/is-duplicate-entry-error.util';
import { CONTACTS_CREATION_BATCH_SIZE } from 'src/modules/contact-creation-manager/constants/contacts-creation-batch-size.constant';
import { CreateCompanyService } from 'src/modules/contact-creation-manager/services/create-company.service';
import { CreatePersonService } from 'src/modules/contact-creation-manager/services/create-person.service';
@@ -37,10 +34,6 @@ import { WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-member/sta
import { computeDisplayName } from 'src/utils/compute-display-name';
import { isWorkDomain, isWorkEmail } from 'src/utils/is-work-email';
-const isDuplicateEntryError = (error: unknown) =>
- error instanceof TwentyOrmException &&
- error.code === TwentyOrmExceptionCode.DUPLICATE_ENTRY_DETECTED;
-
@Injectable()
export class CreateCompanyAndPersonService {
private readonly logger = new Logger(CreateCompanyAndPersonService.name);
diff --git a/packages/twenty-server/src/modules/input-ask/answer-ask/answer-ask.module.ts b/packages/twenty-server/src/modules/input-ask/answer-ask/answer-ask.module.ts
new file mode 100644
index 00000000000..e7b550500d8
--- /dev/null
+++ b/packages/twenty-server/src/modules/input-ask/answer-ask/answer-ask.module.ts
@@ -0,0 +1,38 @@
+import { Module } from '@nestjs/common';
+
+import { ToolProviderModule } from 'src/engine/core-modules/tool-provider/tool-provider.module';
+import { AiAgentExecutionModule } from 'src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module';
+import { AiBillingModule } from 'src/engine/metadata-modules/ai/ai-billing/ai-billing.module';
+import { AgentChatStreamStateModule } from 'src/engine/metadata-modules/ai/ai-chat/agent-chat-stream-state.module';
+import { AiChatModule } from 'src/engine/metadata-modules/ai/ai-chat/ai-chat.module';
+import { AiGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules/ai/interceptors/ai-graphql-api-exception.interceptor';
+import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permissions.module';
+import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
+import { AnswerAgentChatQuestionResolver } from 'src/modules/input-ask/answer-ask/resolvers/answer-agent-chat-question.resolver';
+import { AnswerAskResolver } from 'src/modules/input-ask/answer-ask/resolvers/answer-ask.resolver';
+import { AnswerAskService } from 'src/modules/input-ask/answer-ask/services/answer-ask.service';
+import { InputAskModule } from 'src/modules/input-ask/input-ask.module';
+import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.module';
+import { WorkflowRunnerModule } from 'src/modules/workflow/workflow-runner/workflow-runner.module';
+
+@Module({
+ imports: [
+ AiAgentExecutionModule,
+ AiChatModule,
+ AgentChatStreamStateModule,
+ AiBillingModule,
+ InputAskModule,
+ PermissionsModule,
+ ToolProviderModule,
+ WorkflowRunModule,
+ WorkflowRunnerModule,
+ WorkspaceCacheModule,
+ ],
+ providers: [
+ AnswerAskService,
+ AnswerAskResolver,
+ AnswerAgentChatQuestionResolver,
+ AiGraphqlApiExceptionInterceptor,
+ ],
+})
+export class AnswerAskModule {}
diff --git a/packages/twenty-server/src/modules/input-ask/answer-ask/dtos/answer-ask-result.dto.ts b/packages/twenty-server/src/modules/input-ask/answer-ask/dtos/answer-ask-result.dto.ts
new file mode 100644
index 00000000000..1739c6bc74c
--- /dev/null
+++ b/packages/twenty-server/src/modules/input-ask/answer-ask/dtos/answer-ask-result.dto.ts
@@ -0,0 +1,9 @@
+import { Field, ObjectType } from '@nestjs/graphql';
+
+@ObjectType('AnswerAskResult')
+export class AnswerAskResultDTO {
+ // Only a chat conversation resumes as a stream; a workflow run resumes in
+ // its own executor.
+ @Field(() => String, { nullable: true })
+ streamId: string | null;
+}
diff --git a/packages/twenty-server/src/modules/input-ask/answer-ask/dtos/answer-ask.input.ts b/packages/twenty-server/src/modules/input-ask/answer-ask/dtos/answer-ask.input.ts
new file mode 100644
index 00000000000..e21e20f20ea
--- /dev/null
+++ b/packages/twenty-server/src/modules/input-ask/answer-ask/dtos/answer-ask.input.ts
@@ -0,0 +1,25 @@
+import { Field, InputType } from '@nestjs/graphql';
+
+import { IsObject, IsOptional, IsString, IsUUID } from 'class-validator';
+import GraphQLJSON from 'graphql-type-json';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+
+@InputType()
+export class AnswerAskInput {
+ @Field(() => UUIDScalarType)
+ @IsUUID()
+ askId: string;
+
+ @Field(() => GraphQLJSON, {
+ description:
+ 'The answer, validated against what the Ask asked (its form kind)',
+ })
+ @IsObject()
+ response: Record<string, unknown>;
+
+ @Field(() => String, { nullable: true })
+ @IsOptional()
+ @IsString()
+ modelId?: string;
+}
diff --git a/packages/twenty-server/src/modules/input-ask/answer-ask/resolvers/answer-agent-chat-question.resolver.ts b/packages/twenty-server/src/modules/input-ask/answer-ask/resolvers/answer-agent-chat-question.resolver.ts
new file mode 100644
index 00000000000..afcb0169e0c
--- /dev/null
+++ b/packages/twenty-server/src/modules/input-ask/answer-ask/resolvers/answer-agent-chat-question.resolver.ts
@@ -0,0 +1,107 @@
+import {
+ UseFilters,
+ UseGuards,
+ UseInterceptors,
+ UsePipes,
+} from '@nestjs/common';
+import { Args, Mutation } from '@nestjs/graphql';
+
+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';
+
+import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorators/metadata-resolver.decorator';
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filters/auth-graphql-api-exception.filter';
+import { BillingGraphqlApiExceptionFilter } from 'src/engine/core-modules/billing/filters/billing-graphql-api-exception.filter';
+import { PreventNestToAutoLogGraphqlErrorsFilter } from 'src/engine/core-modules/graphql/filters/prevent-nest-to-auto-log-graphql-errors.filter';
+import { ResolverValidationPipe } from 'src/engine/core-modules/graphql/pipes/resolver-validation.pipe';
+import { UsageLimitGraphqlApiExceptionFilter } from 'src/engine/core-modules/usage-limit/filters/usage-limit-graphql-api-exception.filter';
+import { WorkflowVersionStepGraphqlApiExceptionFilter } from 'src/engine/core-modules/workflow/filters/workflow-version-step-graphql-api-exception.filter';
+import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';
+import { AuthWorkspaceMemberId } from 'src/engine/decorators/auth/auth-workspace-member-id.decorator';
+import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
+import { CustomPermissionGuard } from 'src/engine/guards/custom-permission.guard';
+import { UserAuthGuard } from 'src/engine/guards/user-auth.guard';
+import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
+import { AgentChatQuestionAnswerInput } from 'src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-question-answer.input';
+import { FileAttachmentInput } from 'src/engine/metadata-modules/ai/ai-chat/dtos/file-attachment.input';
+import { SendChatMessageResultDTO } from 'src/engine/metadata-modules/ai/ai-chat/dtos/send-chat-message-result.dto';
+import { tagAiChatStreamScope } from 'src/engine/metadata-modules/ai/ai-chat/utils/tag-ai-chat-stream-scope.util';
+import { AiGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules/ai/interceptors/ai-graphql-api-exception.interceptor';
+import { PermissionsGraphqlApiExceptionFilter } from 'src/engine/metadata-modules/permissions/utils/permissions-graphql-api-exception.filter';
+import { AnswerAskService } from 'src/modules/input-ask/answer-ask/services/answer-ask.service';
+import { InputAskGraphqlApiExceptionFilter } from 'src/modules/input-ask/filters/input-ask-graphql-api-exception.filter';
+import {
+ InputAskException,
+ InputAskExceptionCode,
+} from 'src/modules/input-ask/input-ask.exception';
+
+// The metadata API's answer mutation from before answerAsk, kept so clients
+// built against it keep working for a release. It answers the Ask of the
+// question the message asked, with the same checks as answerAsk.
+@MetadataResolver()
+@UsePipes(ResolverValidationPipe)
+@UseGuards(WorkspaceAuthGuard, UserAuthGuard)
+@UseInterceptors(AiGraphqlApiExceptionInterceptor)
+@UseFilters(
+ InputAskGraphqlApiExceptionFilter,
+ UsageLimitGraphqlApiExceptionFilter,
+ BillingGraphqlApiExceptionFilter,
+ PermissionsGraphqlApiExceptionFilter,
+ WorkflowVersionStepGraphqlApiExceptionFilter,
+ PreventNestToAutoLogGraphqlErrorsFilter,
+ AuthGraphqlApiExceptionFilter,
+)
+export class AnswerAgentChatQuestionResolver {
+ constructor(private readonly answerAskService: AnswerAskService) {}
+
+ @Mutation(() => SendChatMessageResultDTO, {
+ deprecationReason: "Use answerAsk with the question's Ask",
+ })
+ @UseGuards(CustomPermissionGuard)
+ async answerAgentChatQuestion(
+ @Args('threadId', { type: () => UUIDScalarType }) threadId: string,
+ @Args('messageId', { type: () => UUIDScalarType }) messageId: string,
+ @Args('answers', { type: () => [AgentChatQuestionAnswerInput] })
+ answers: AgentChatQuestionAnswerInput[],
+ @Args('modelId', { type: () => String, nullable: true })
+ modelId: string | undefined,
+ @Args('fileAttachments', {
+ type: () => [FileAttachmentInput],
+ nullable: true,
+ })
+ fileAttachments: FileAttachmentInput[] | null,
+ @AuthUserWorkspaceId() userWorkspaceId: string,
+ @AuthWorkspaceMemberId() workspaceMemberId: string,
+ @AuthWorkspace() workspace: WorkspaceEntity,
+ ): Promise<SendChatMessageResultDTO> {
+ if (isNonEmptyArray(fileAttachments)) {
+ throw new InputAskException(
+ 'Files can no longer be sent with an answer: send them in a message',
+ InputAskExceptionCode.INVALID_ASK_RESPONSE,
+ );
+ }
+
+ const { streamId, turnId } =
+ await this.answerAskService.answerQuestionsOfMessage({
+ threadId,
+ messageId,
+ response: { answers: answers.map((answer) => ({ ...answer })) },
+ modelId,
+ userWorkspaceId,
+ workspaceMemberId,
+ workspace,
+ });
+
+ if (isDefined(streamId)) {
+ tagAiChatStreamScope({
+ streamId,
+ turnId,
+ threadId,
+ workspaceId: workspace.id,
+ });
+ }
+
+ return { messageId, queued: false, streamId: streamId ?? undefined };
+ }
+}
diff --git a/packages/twenty-server/src/modules/input-ask/answer-ask/resolvers/answer-ask.resolver.ts b/packages/twenty-server/src/modules/input-ask/answer-ask/resolvers/answer-ask.resolver.ts
new file mode 100644
index 00000000000..63f1a2b3dbe
--- /dev/null
+++ b/packages/twenty-server/src/modules/input-ask/answer-ask/resolvers/answer-ask.resolver.ts
@@ -0,0 +1,115 @@
+import {
+ UseFilters,
+ UseGuards,
+ UseInterceptors,
+ UsePipes,
+} from '@nestjs/common';
+import { Args, Mutation } from '@nestjs/graphql';
+
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { CoreResolver } from 'src/engine/api/graphql/graphql-config/decorators/core-resolver.decorator';
+import { AuthGraphqlApiExceptionFilter } from 'src/engine/core-modules/auth/filters/auth-graphql-api-exception.filter';
+import { BillingGraphqlApiExceptionFilter } from 'src/engine/core-modules/billing/filters/billing-graphql-api-exception.filter';
+import { PreventNestToAutoLogGraphqlErrorsFilter } from 'src/engine/core-modules/graphql/filters/prevent-nest-to-auto-log-graphql-errors.filter';
+import { ResolverValidationPipe } from 'src/engine/core-modules/graphql/pipes/resolver-validation.pipe';
+import { UsageLimitGraphqlApiExceptionFilter } from 'src/engine/core-modules/usage-limit/filters/usage-limit-graphql-api-exception.filter';
+import { SubmitFormStepInput } from 'src/engine/core-modules/workflow/dtos/submit-form-step.input';
+import { WorkflowVersionStepGraphqlApiExceptionFilter } from 'src/engine/core-modules/workflow/filters/workflow-version-step-graphql-api-exception.filter';
+import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';
+import { AuthWorkspaceMemberId } from 'src/engine/decorators/auth/auth-workspace-member-id.decorator';
+import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
+import { CustomPermissionGuard } from 'src/engine/guards/custom-permission.guard';
+import { UserAuthGuard } from 'src/engine/guards/user-auth.guard';
+import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
+import { tagAiChatStreamScope } from 'src/engine/metadata-modules/ai/ai-chat/utils/tag-ai-chat-stream-scope.util';
+import { AiGraphqlApiExceptionInterceptor } from 'src/engine/metadata-modules/ai/interceptors/ai-graphql-api-exception.interceptor';
+import { PermissionsGraphqlApiExceptionFilter } from 'src/engine/metadata-modules/permissions/utils/permissions-graphql-api-exception.filter';
+import { AnswerAskResultDTO } from 'src/modules/input-ask/answer-ask/dtos/answer-ask-result.dto';
+import { AnswerAskInput } from 'src/modules/input-ask/answer-ask/dtos/answer-ask.input';
+import { AnswerAskService } from 'src/modules/input-ask/answer-ask/services/answer-ask.service';
+import { InputAskGraphqlApiExceptionFilter } from 'src/modules/input-ask/filters/input-ask-graphql-api-exception.filter';
+import {
+ InputAskException,
+ InputAskExceptionCode,
+} from 'src/modules/input-ask/input-ask.exception';
+
+// Served on /graphql: the permission an answer needs depends on what the Ask
+// gates, a chat or a workflow run, so it is checked per call rather than by a
+// class guard.
+@CoreResolver()
+@UsePipes(ResolverValidationPipe)
+@UseGuards(WorkspaceAuthGuard, UserAuthGuard)
+@UseInterceptors(AiGraphqlApiExceptionInterceptor)
+@UseFilters(
+ InputAskGraphqlApiExceptionFilter,
+ UsageLimitGraphqlApiExceptionFilter,
+ BillingGraphqlApiExceptionFilter,
+ PermissionsGraphqlApiExceptionFilter,
+ WorkflowVersionStepGraphqlApiExceptionFilter,
+ PreventNestToAutoLogGraphqlErrorsFilter,
+ AuthGraphqlApiExceptionFilter,
+)
+export class AnswerAskResolver {
+ constructor(private readonly answerAskService: AnswerAskService) {}
+
+ @Mutation(() => AnswerAskResultDTO)
+ @UseGuards(CustomPermissionGuard)
+ async answerAsk(
+ @Args('input') { askId, response, modelId }: AnswerAskInput,
+ @AuthUserWorkspaceId() userWorkspaceId: string,
+ @AuthWorkspaceMemberId() workspaceMemberId: string,
+ @AuthWorkspace() workspace: WorkspaceEntity,
+ ): Promise<AnswerAskResultDTO> {
+ const { streamId, threadId, turnId } = await this.answerAskService.answer({
+ askId,
+ response,
+ modelId,
+ userWorkspaceId,
+ workspaceMemberId,
+ workspace,
+ });
+
+ if (isDefined(streamId) && isDefined(threadId)) {
+ tagAiChatStreamScope({
+ streamId,
+ turnId,
+ threadId,
+ workspaceId: workspace.id,
+ });
+ }
+
+ return { streamId };
+ }
+
+ // Kept so clients built before answerAsk keep working for a release.
+ @Mutation(() => Boolean, {
+ deprecationReason: "Use answerAsk with the form step's Ask",
+ })
+ @UseGuards(CustomPermissionGuard)
+ async submitFormStep(
+ @Args('input') { stepId, workflowRunId, response }: SubmitFormStepInput,
+ @AuthUserWorkspaceId() userWorkspaceId: string,
+ @AuthWorkspaceMemberId() workspaceMemberId: string,
+ @AuthWorkspace() workspace: WorkspaceEntity,
+ ): Promise<boolean> {
+ if (!isPlainObject(response)) {
+ throw new InputAskException(
+ 'A form response must be an object',
+ InputAskExceptionCode.INVALID_ASK_RESPONSE,
+ );
+ }
+
+ await this.answerAskService.answerFormStepByStep({
+ workflowRunId,
+ stepId,
+ response,
+ userWorkspaceId,
+ workspaceMemberId,
+ workspace,
+ });
+
+ return true;
+ }
+}
diff --git a/packages/twenty-server/src/modules/input-ask/answer-ask/services/__tests__/answer-ask.service.spec.ts b/packages/twenty-server/src/modules/input-ask/answer-ask/services/__tests__/answer-ask.service.spec.ts
new file mode 100644
index 00000000000..c1e9428eb73
--- /dev/null
+++ b/packages/twenty-server/src/modules/input-ask/answer-ask/services/__tests__/answer-ask.service.spec.ts
@@ -0,0 +1,675 @@
+import { withWorkspaceAuthContext } from 'src/engine/core-modules/auth/storage/workspace-auth-context.storage';
+import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+import { AgentChatTurnPreflightService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-turn-preflight.service';
+import { AnswerAskService } from 'src/modules/input-ask/answer-ask/services/answer-ask.service';
+import { InputAskStatus } from 'src/modules/input-ask/enums/input-ask-status.enum';
+
+const QUESTIONS = [
+ {
+ header: 'Plan',
+ question: 'Which plan?',
+ options: [{ label: 'Pro' }, { label: 'Team' }],
+ },
+];
+
+const ANSWERS = [{ questionIndex: 0, selectedOptionIndices: [1] }];
+
+const PROPOSED_EMAIL = {
+ recipients: { to: '[email protected]', cc: '', bcc: '' },
+ subject: 'Renewal',
+ body: 'Hi Tim,\n\nYour plan renews next week.',
+};
+
+type BuildOptions = {
+ inputAsk?: Record<string, unknown> | null;
+ toolPart?: Record<string, unknown> | null;
+ hasClaimedStream?: boolean;
+ hasAnswered?: boolean;
+ hasPermission?: boolean;
+ hasSubmittedForm?: boolean;
+ hasOtherPendingAsks?: boolean;
+};
+
+const chatInputAsk = {
+ id: 'ask-id',
+ status: InputAskStatus.PENDING,
+ form: { kind: 'questions', questions: QUESTIONS },
+ threadId: 'thread-id',
+ toolCallId: 'tool-call-id',
+ workflowRunId: null,
+ stepId: null,
+};
+
+const questionPart = {
+ id: 'part-id',
+ messageId: 'question-message-id',
+ turnId: 'question-turn-id',
+ toolName: 'ask_questions',
+ toolInput: { questions: QUESTIONS },
+ toolOutput: { result: { questions: QUESTIONS, status: 'pending' } },
+};
+
+describe('AnswerAskService', () => {
+ const workspace = { id: 'workspace-id' } as WorkspaceEntity;
+
+ const answerArguments = {
+ askId: 'ask-id',
+ response: { answers: ANSWERS } as Record<string, unknown>,
+ userWorkspaceId: 'user-workspace-id',
+ workspaceMemberId: 'member-id',
+ workspace,
+ };
+
+ const buildService = ({
+ inputAsk = chatInputAsk,
+ toolPart = questionPart,
+ hasClaimedStream = true,
+ hasAnswered = true,
+ hasPermission = true,
+ hasSubmittedForm = true,
+ hasOtherPendingAsks = false,
+ }: BuildOptions = {}) => {
+ const publishedEvents: Array<{ type: string }> = [];
+ const agentChatService = {
+ findToolPart: jest.fn().mockResolvedValue(toolPart),
+ getWritableThread: jest
+ .fn()
+ .mockResolvedValue({ id: 'thread-id', activeStreamId: null }),
+ updateToolPartOutput: jest.fn().mockResolvedValue(undefined),
+ addMessage: jest
+ .fn()
+ .mockResolvedValue({ id: 'answer-message-id', turnId: 'answer-turn' }),
+ };
+ const agentChatStreamingService = {
+ reapDeadStream: jest.fn().mockResolvedValue(null),
+ tryClaimStream: jest.fn().mockResolvedValue(hasClaimedStream),
+ releaseStreamClaim: jest.fn().mockResolvedValue(undefined),
+ enqueueResumeStream: jest.fn().mockResolvedValue(undefined),
+ };
+ const actorService = {
+ authorizeToolCallResolution: jest.fn().mockResolvedValue(undefined),
+ };
+ const eventPublisherService = {
+ publish: jest.fn().mockImplementation(({ event }) => {
+ publishedEvents.push(event);
+
+ return Promise.resolve();
+ }),
+ };
+ const inputAskWorkspaceService = {
+ findReadable: jest.fn().mockResolvedValue(inputAsk),
+ answer: jest.fn().mockResolvedValue(hasAnswered),
+ hasPendingForThread: jest.fn().mockResolvedValue(hasOtherPendingAsks),
+ };
+ const workflowRunnerWorkspaceService = {
+ resumeAnsweredAgentStep: jest.fn().mockResolvedValue(undefined),
+ submitFormStep: jest.fn().mockResolvedValue(hasSubmittedForm),
+ };
+ const workflowRunWorkspaceService = {
+ resolveStepAwaitingToolCall: jest
+ .fn()
+ .mockResolvedValue({ status: 'RESOLVED', stepId: 'step-id' }),
+ endWorkflowRun: jest.fn().mockResolvedValue(undefined),
+ };
+ const permissionsService = {
+ userHasWorkspaceSettingPermission: jest
+ .fn()
+ .mockResolvedValue(hasPermission),
+ };
+ const aiModelRegistryService = {
+ getAvailableModels: jest.fn().mockReturnValue([{ modelId: 'model' }]),
+ validateModelAvailability: jest.fn(),
+ };
+ const aiBillingService = {
+ assertAiExecutionAllowed: jest.fn().mockResolvedValue(undefined),
+ };
+ const workflowRunRepository = {
+ findOne: jest.fn().mockResolvedValue({ id: 'workflow-run-id' }),
+ };
+ const workspaceOrmManager = {
+ executeInWorkspaceContext: jest.fn().mockImplementation((work) => work()),
+ getRepositoryWithContextPermissions: jest
+ .fn()
+ .mockReturnValue(workflowRunRepository),
+ };
+ const toolRegistryService = {
+ resolveAndExecute: jest.fn().mockResolvedValue({
+ success: true,
+ message: 'Email sent successfully to [email protected]',
+ result: { messageId: 'sent-message-id' },
+ }),
+ };
+
+ const service = new AnswerAskService(
+ agentChatService as never,
+ agentChatStreamingService as never,
+ actorService as never,
+ eventPublisherService as never,
+ inputAskWorkspaceService as never,
+ workflowRunnerWorkspaceService as never,
+ workflowRunWorkspaceService as never,
+ permissionsService as never,
+ new AgentChatTurnPreflightService(
+ aiModelRegistryService as never,
+ agentChatService as never,
+ aiBillingService as never,
+ ),
+ workspaceOrmManager as never,
+ {
+ getOrRecompute: jest.fn().mockResolvedValue({
+ userWorkspaceRoleMap: { 'user-workspace-id': 'role-id' },
+ }),
+ } as never,
+ {
+ buildUserAndAgentActorContext: jest.fn().mockResolvedValue({
+ actorContext: {},
+ roleId: 'role-id',
+ userId: 'user-id',
+ userContext: { locale: 'en' },
+ }),
+ } as never,
+ toolRegistryService as never,
+ );
+
+ return {
+ service,
+ agentChatService,
+ agentChatStreamingService,
+ inputAskWorkspaceService,
+ workflowRunnerWorkspaceService,
+ workflowRunWorkspaceService,
+ permissionsService,
+ workflowRunRepository,
+ toolRegistryService,
+ publishedEvents,
+ };
+ };
+
+ it('treats an Ask the caller cannot read as not found', async () => {
+ const { service } = buildService({ inputAsk: null });
+
+ await expect(service.answer(answerArguments)).rejects.toMatchObject({
+ code: 'ASK_NOT_FOUND',
+ });
+ });
+
+ it('refuses an Ask that is no longer pending before touching anything', async () => {
+ const { service, agentChatStreamingService, agentChatService } =
+ buildService({
+ inputAsk: { ...chatInputAsk, status: InputAskStatus.ANSWERED },
+ });
+
+ await expect(service.answer(answerArguments)).rejects.toMatchObject({
+ code: 'ASK_NOT_PENDING',
+ });
+ expect(agentChatStreamingService.tryClaimStream).not.toHaveBeenCalled();
+ expect(agentChatService.addMessage).not.toHaveBeenCalled();
+ });
+
+ describe('a chat tool call', () => {
+ it('answers the Ask once, records the answer and resumes the stream', async () => {
+ const {
+ service,
+ agentChatService,
+ agentChatStreamingService,
+ inputAskWorkspaceService,
+ publishedEvents,
+ } = buildService();
+
+ const result = await service.answer(answerArguments);
+
+ expect(result).toEqual({
+ streamId: expect.any(String),
+ threadId: 'thread-id',
+ turnId: 'answer-turn',
+ });
+ expect(inputAskWorkspaceService.answer).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ key: { threadId: 'thread-id', toolCallId: 'tool-call-id' },
+ response: { answers: ANSWERS },
+ });
+ expect(agentChatService.updateToolPartOutput).toHaveBeenCalledWith({
+ partId: 'part-id',
+ workspaceId: 'workspace-id',
+ toolOutput: expect.objectContaining({
+ result: {
+ questions: QUESTIONS,
+ status: 'answered',
+ answers: ANSWERS,
+ },
+ }),
+ });
+ expect(agentChatService.addMessage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ userWorkspaceId: 'user-workspace-id',
+ uiMessage: {
+ role: 'user',
+ parts: [{ type: 'text', text: 'Which plan?\nTeam' }],
+ },
+ }),
+ );
+ expect(
+ agentChatStreamingService.enqueueResumeStream,
+ ).toHaveBeenCalledWith(
+ expect.objectContaining({
+ streamId: result.streamId,
+ messageId: 'answer-message-id',
+ turnId: 'answer-turn',
+ }),
+ );
+ expect(publishedEvents).toContainEqual({
+ type: 'tool-call-resolved',
+ toolCallId: 'tool-call-id',
+ });
+ });
+
+ it('records the answer but leaves the agent paused while another call of the step waits', async () => {
+ const {
+ service,
+ agentChatService,
+ agentChatStreamingService,
+ publishedEvents,
+ } = buildService({ hasOtherPendingAsks: true });
+
+ const result = await service.answer(answerArguments);
+
+ expect(result).toEqual({
+ streamId: null,
+ threadId: 'thread-id',
+ turnId: 'answer-turn',
+ });
+ expect(agentChatService.updateToolPartOutput).toHaveBeenCalled();
+ expect(agentChatService.addMessage).toHaveBeenCalled();
+ expect(
+ agentChatStreamingService.enqueueResumeStream,
+ ).not.toHaveBeenCalled();
+ expect(agentChatStreamingService.releaseStreamClaim).toHaveBeenCalledWith(
+ 'thread-id',
+ 'workspace-id',
+ expect.any(String),
+ );
+ expect(publishedEvents).toContainEqual({
+ type: 'tool-call-resolved',
+ toolCallId: 'tool-call-id',
+ });
+ });
+
+ it.each([
+ { answers: [] },
+ {
+ answers: [
+ { questionIndex: 0, selectedOptionIndices: [], freeText: ' ' },
+ ],
+ },
+ { answers: [{ questionIndex: 3, selectedOptionIndices: [0] }] },
+ { answers: [{ questionIndex: 0, selectedOptionIndices: [0, 1] }] },
+ ])('rejects a response the call cannot accept (%j)', async (response) => {
+ const { service, inputAskWorkspaceService } = buildService();
+
+ await expect(
+ service.answer({ ...answerArguments, response }),
+ ).rejects.toMatchObject({ code: 'INVALID_ASK_RESPONSE' });
+ expect(inputAskWorkspaceService.answer).not.toHaveBeenCalled();
+ });
+
+ it('refuses someone without the AI permission', async () => {
+ const { service, inputAskWorkspaceService } = buildService({
+ hasPermission: false,
+ });
+
+ await expect(service.answer(answerArguments)).rejects.toMatchObject({
+ code: 'ASK_ANSWER_FORBIDDEN',
+ });
+ expect(inputAskWorkspaceService.answer).not.toHaveBeenCalled();
+ });
+
+ it('refuses while another response holds the stream, without answering', async () => {
+ const { service, inputAskWorkspaceService } = buildService({
+ hasClaimedStream: false,
+ });
+
+ await expect(service.answer(answerArguments)).rejects.toMatchObject({
+ code: 'ASK_NOT_PENDING',
+ });
+ expect(inputAskWorkspaceService.answer).not.toHaveBeenCalled();
+ });
+
+ it('releases the stream it claimed when another answer won the Ask', async () => {
+ const { service, agentChatStreamingService, agentChatService } =
+ buildService({ hasAnswered: false });
+
+ await expect(service.answer(answerArguments)).rejects.toMatchObject({
+ code: 'ASK_NOT_PENDING',
+ });
+
+ const [[{ streamId: claimedStreamId }]] =
+ agentChatStreamingService.tryClaimStream.mock.calls;
+
+ expect(agentChatStreamingService.releaseStreamClaim).toHaveBeenCalledWith(
+ 'thread-id',
+ 'workspace-id',
+ claimedStreamId,
+ );
+ expect(agentChatService.updateToolPartOutput).not.toHaveBeenCalled();
+ expect(agentChatService.addMessage).not.toHaveBeenCalled();
+ });
+
+ it('leaves a retryable failed turn when the resume cannot be scheduled', async () => {
+ const { service, agentChatStreamingService, publishedEvents } =
+ buildService();
+
+ agentChatStreamingService.enqueueResumeStream.mockRejectedValue(
+ new Error('redis down'),
+ );
+
+ await expect(service.answer(answerArguments)).rejects.toThrow(
+ 'redis down',
+ );
+ expect(agentChatStreamingService.releaseStreamClaim).toHaveBeenCalledWith(
+ 'thread-id',
+ 'workspace-id',
+ expect.any(String),
+ {
+ lastStreamError: expect.objectContaining({
+ message: 'redis down',
+ failedAt: expect.any(String),
+ }),
+ },
+ );
+ expect(publishedEvents.map((event) => event.type)).toContain(
+ 'stream-error',
+ );
+ expect(publishedEvents.map((event) => event.type)).not.toContain(
+ 'tool-call-resolved',
+ );
+ });
+ });
+
+ describe('an email approval', () => {
+ const emailInputAsk = {
+ ...chatInputAsk,
+ form: { kind: 'emailApproval', email: PROPOSED_EMAIL },
+ };
+ const emailPart = {
+ ...questionPart,
+ toolName: 'propose_email',
+ toolInput: PROPOSED_EMAIL,
+ toolOutput: { result: { status: 'pending', email: PROPOSED_EMAIL } },
+ };
+
+ it('sends the edited email as the person only once the Ask is answered', async () => {
+ const {
+ service,
+ toolRegistryService,
+ inputAskWorkspaceService,
+ agentChatService,
+ } = buildService({ inputAsk: emailInputAsk, toolPart: emailPart });
+ const editedEmail = { ...PROPOSED_EMAIL, subject: 'Your renewal' };
+
+ // The email goes out as whoever answered, from their request.
+ await withWorkspaceAuthContext(
+ {
+ type: 'user',
+ workspace: { id: 'workspace-id' },
+ userWorkspaceId: 'user-workspace-id',
+ } as never,
+ () =>
+ service.answer({
+ ...answerArguments,
+ response: { decision: 'send', email: editedEmail },
+ }),
+ );
+
+ expect(toolRegistryService.resolveAndExecute).toHaveBeenCalledWith(
+ 'send_email',
+ {
+ recipients: PROPOSED_EMAIL.recipients,
+ subject: 'Your renewal',
+ body: '<p>Hi Tim,</p><p>Your plan renews next week.</p>',
+ },
+ expect.objectContaining({
+ userWorkspaceId: 'user-workspace-id',
+ roleId: 'role-id',
+ }),
+ );
+ expect(
+ inputAskWorkspaceService.answer.mock.invocationCallOrder[0],
+ ).toBeLessThan(
+ toolRegistryService.resolveAndExecute.mock.invocationCallOrder[0],
+ );
+ expect(agentChatService.updateToolPartOutput).toHaveBeenCalledWith(
+ expect.objectContaining({
+ toolOutput: expect.objectContaining({
+ success: true,
+ result: expect.objectContaining({
+ status: 'sent',
+ email: editedEmail,
+ }),
+ }),
+ }),
+ );
+ });
+
+ it('sends nothing when the person discards the email', async () => {
+ const { service, toolRegistryService, agentChatService } = buildService({
+ inputAsk: emailInputAsk,
+ toolPart: emailPart,
+ });
+
+ await service.answer({
+ ...answerArguments,
+ response: { decision: 'discard' },
+ });
+
+ expect(toolRegistryService.resolveAndExecute).not.toHaveBeenCalled();
+ expect(agentChatService.updateToolPartOutput).toHaveBeenCalledWith(
+ expect.objectContaining({
+ toolOutput: expect.objectContaining({
+ result: expect.objectContaining({ status: 'discarded' }),
+ }),
+ }),
+ );
+ });
+
+ it('sends nothing when another answer already claimed the Ask', async () => {
+ const { service, toolRegistryService } = buildService({
+ inputAsk: emailInputAsk,
+ toolPart: emailPart,
+ hasAnswered: false,
+ });
+
+ await expect(
+ service.answer({
+ ...answerArguments,
+ response: { decision: 'send', email: PROPOSED_EMAIL },
+ }),
+ ).rejects.toMatchObject({ code: 'ASK_NOT_PENDING' });
+ expect(toolRegistryService.resolveAndExecute).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('a workflow agent step', () => {
+ const runInputAsk = {
+ ...chatInputAsk,
+ workflowRunId: 'workflow-run-id',
+ stepId: 'step-id',
+ };
+
+ it('hands the answer to the run, with no chat stream', async () => {
+ const {
+ service,
+ workflowRunnerWorkspaceService,
+ workflowRunWorkspaceService,
+ agentChatStreamingService,
+ permissionsService,
+ publishedEvents,
+ } = buildService({ inputAsk: runInputAsk });
+
+ expect(await service.answer(answerArguments)).toEqual({
+ streamId: null,
+ threadId: null,
+ turnId: null,
+ });
+ expect(
+ permissionsService.userHasWorkspaceSettingPermission,
+ ).toHaveBeenCalledWith(expect.objectContaining({ setting: 'WORKFLOWS' }));
+ expect(
+ workflowRunWorkspaceService.resolveStepAwaitingToolCall,
+ ).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ workflowRunId: 'workflow-run-id',
+ threadId: 'thread-id',
+ toolCallId: 'tool-call-id',
+ response: { answers: ANSWERS },
+ });
+ expect(
+ workflowRunnerWorkspaceService.resumeAnsweredAgentStep,
+ ).toHaveBeenCalledWith(
+ expect.objectContaining({
+ stepId: 'step-id',
+ toolPart: questionPart,
+ answerText: 'Which plan?\nTeam',
+ senderUserWorkspaceId: 'user-workspace-id',
+ }),
+ );
+ expect(workflowRunWorkspaceService.endWorkflowRun).not.toHaveBeenCalled();
+ expect(agentChatStreamingService.tryClaimStream).not.toHaveBeenCalled();
+ expect(publishedEvents).toContainEqual({
+ type: 'tool-call-resolved',
+ toolCallId: 'tool-call-id',
+ });
+ });
+
+ it('refuses an answer the run no longer waits for', async () => {
+ const {
+ service,
+ workflowRunnerWorkspaceService,
+ workflowRunWorkspaceService,
+ } = buildService({ inputAsk: runInputAsk });
+
+ workflowRunWorkspaceService.resolveStepAwaitingToolCall.mockResolvedValue(
+ { status: 'NOT_AWAITING' },
+ );
+
+ await expect(service.answer(answerArguments)).rejects.toMatchObject({
+ code: 'ASK_NOT_PENDING',
+ });
+ expect(
+ workflowRunnerWorkspaceService.resumeAnsweredAgentStep,
+ ).not.toHaveBeenCalled();
+ });
+
+ it('fails the run when the answered step cannot resume', async () => {
+ const {
+ service,
+ workflowRunnerWorkspaceService,
+ workflowRunWorkspaceService,
+ } = buildService({ inputAsk: runInputAsk });
+
+ workflowRunnerWorkspaceService.resumeAnsweredAgentStep.mockRejectedValue(
+ new Error('Queue unavailable'),
+ );
+
+ await expect(service.answer(answerArguments)).rejects.toThrow(
+ 'Queue unavailable',
+ );
+ expect(workflowRunWorkspaceService.endWorkflowRun).toHaveBeenCalledWith(
+ expect.objectContaining({
+ workflowRunId: 'workflow-run-id',
+ workspaceId: 'workspace-id',
+ status: 'FAILED',
+ }),
+ );
+ });
+
+ it('treats a run the caller cannot read as not found', async () => {
+ const { service, workflowRunRepository, workflowRunWorkspaceService } =
+ buildService({ inputAsk: runInputAsk });
+
+ workflowRunRepository.findOne.mockResolvedValue(null);
+
+ await expect(service.answer(answerArguments)).rejects.toMatchObject({
+ code: 'ASK_NOT_FOUND',
+ });
+ expect(
+ workflowRunWorkspaceService.resolveStepAwaitingToolCall,
+ ).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('a form step', () => {
+ const formInputAsk = {
+ id: 'ask-id',
+ status: InputAskStatus.PENDING,
+ form: {
+ kind: 'formFields',
+ fields: [
+ { id: 'field-id', name: 'discount', label: 'Discount', type: 'TEXT' },
+ ],
+ },
+ threadId: null,
+ toolCallId: null,
+ workflowRunId: 'workflow-run-id',
+ stepId: 'step-id',
+ };
+
+ it('submits the form step with the response', async () => {
+ const { service, workflowRunnerWorkspaceService } = buildService({
+ inputAsk: formInputAsk,
+ });
+
+ expect(
+ await service.answer({
+ ...answerArguments,
+ response: { discount: '20%' },
+ }),
+ ).toEqual({ streamId: null, threadId: null, turnId: null });
+ expect(
+ workflowRunnerWorkspaceService.submitFormStep,
+ ).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ workflowRunId: 'workflow-run-id',
+ stepId: 'step-id',
+ response: { discount: '20%' },
+ });
+ });
+
+ it('rejects a response naming a field the form does not have', async () => {
+ const { service, workflowRunnerWorkspaceService } = buildService({
+ inputAsk: formInputAsk,
+ });
+
+ await expect(
+ service.answer({ ...answerArguments, response: { price: 10 } }),
+ ).rejects.toMatchObject({ code: 'INVALID_ASK_RESPONSE' });
+ expect(
+ workflowRunnerWorkspaceService.submitFormStep,
+ ).not.toHaveBeenCalled();
+ });
+
+ it('refuses a submission the form no longer waits for', async () => {
+ const { service } = buildService({
+ inputAsk: formInputAsk,
+ hasSubmittedForm: false,
+ });
+
+ await expect(
+ service.answer({ ...answerArguments, response: { discount: '20%' } }),
+ ).rejects.toMatchObject({ code: 'ASK_NOT_PENDING' });
+ });
+
+ it('refuses someone without the Workflows permission', async () => {
+ const { service, workflowRunnerWorkspaceService } = buildService({
+ inputAsk: formInputAsk,
+ hasPermission: false,
+ });
+
+ await expect(
+ service.answer({ ...answerArguments, response: { discount: '20%' } }),
+ ).rejects.toMatchObject({ code: 'ASK_ANSWER_FORBIDDEN' });
+ expect(
+ workflowRunnerWorkspaceService.submitFormStep,
+ ).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/packages/twenty-server/src/modules/input-ask/answer-ask/services/answer-ask.service.ts b/packages/twenty-server/src/modules/input-ask/answer-ask/services/answer-ask.service.ts
new file mode 100644
index 00000000000..468556ac2e1
--- /dev/null
+++ b/packages/twenty-server/src/modules/input-ask/answer-ask/services/answer-ask.service.ts
@@ -0,0 +1,679 @@
+import { Injectable } from '@nestjs/common';
+
+import { generateId } from 'ai';
+import { ASK_QUESTIONS_TOOL_NAME } from 'twenty-shared/ai';
+import { PermissionFlagType } from 'twenty-shared/constants';
+import { isDefined } from 'twenty-shared/utils';
+
+import { isUserAuthContext } from 'src/engine/core-modules/auth/guards/is-user-auth-context.guard';
+import { workspaceAuthContextStorage } from 'src/engine/core-modules/auth/storage/workspace-auth-context.storage';
+import { ToolRegistryService } from 'src/engine/core-modules/tool-provider/services/tool-registry.service';
+import { type ToolContext } from 'src/engine/core-modules/tool-provider/types/tool-context.type';
+import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';
+import { type PausingToolCall } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-call.type';
+import { type PausingToolCompletionContext } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-completion-context.type';
+import { parsePausingToolCall } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/parse-pausing-tool-call.util';
+import { AgentActorContextService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-actor-context.service';
+import { AgentChatActorService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-actor.service';
+import { AgentChatEventPublisherService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-event-publisher.service';
+import { AgentChatStreamingService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-streaming.service';
+import { AgentChatTurnPreflightService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-turn-preflight.service';
+import { AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
+import { mapErrorToStreamError } from 'src/engine/metadata-modules/ai/ai-chat/utils/map-error-to-stream-error.util';
+import { PermissionsException } from 'src/engine/metadata-modules/permissions/permissions.exception';
+import { PermissionsService } from 'src/engine/metadata-modules/permissions/permissions.service';
+import { resolveRolePermissionConfig } from 'src/engine/twenty-orm/utils/resolve-role-permission-config.util';
+import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { InputAskStatus } from 'src/modules/input-ask/enums/input-ask-status.enum';
+import {
+ InputAskException,
+ InputAskExceptionCode,
+} from 'src/modules/input-ask/input-ask.exception';
+import { type InputAskWorkspaceEntity } from 'src/modules/input-ask/standard-objects/input-ask.workspace-entity';
+import { InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-service';
+import {
+ WorkflowRunStatus,
+ type WorkflowRunWorkspaceEntity,
+} from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
+import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
+import { WorkflowRunnerWorkspaceService } from 'src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service';
+
+type AnswerAskArgs = {
+ askId: string;
+ response: Record<string, unknown>;
+ modelId?: string;
+ userWorkspaceId: string;
+ workspaceMemberId: string;
+ workspace: WorkspaceEntity;
+};
+
+type AnswerAskOutcome = {
+ streamId: string | null;
+ threadId: string | null;
+ turnId: string | null;
+};
+
+type ToolCallToAnswer = AnswerAskArgs & {
+ threadId: string;
+ toolCallId: string;
+ toolPart: NonNullable<Awaited<ReturnType<AgentChatService['findToolPart']>>>;
+ pausingToolCall: PausingToolCall;
+ output: Record<string, unknown>;
+};
+
+const NO_STREAM: AnswerAskOutcome = {
+ streamId: null,
+ threadId: null,
+ turnId: null,
+};
+
+// Every pause for a person is answered here, by its Ask: the Ask says what it
+// gates, a form step, a chat's tool call or a run agent's tool call, and
+// moving it out of PENDING is the one claim that lets exactly one answer
+// resume what waits on it.
+@Injectable()
+export class AnswerAskService {
+ constructor(
+ private readonly agentChatService: AgentChatService,
+ private readonly agentChatStreamingService: AgentChatStreamingService,
+ private readonly actorService: AgentChatActorService,
+ private readonly eventPublisherService: AgentChatEventPublisherService,
+ private readonly inputAskWorkspaceService: InputAskWorkspaceService,
+ private readonly workflowRunnerWorkspaceService: WorkflowRunnerWorkspaceService,
+ private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,
+ private readonly permissionsService: PermissionsService,
+ private readonly turnPreflightService: AgentChatTurnPreflightService,
+ private readonly workspaceOrmManager: WorkspaceOrmManager,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ private readonly agentActorContextService: AgentActorContextService,
+ private readonly toolRegistryService: ToolRegistryService,
+ ) {}
+
+ async answer(args: AnswerAskArgs): Promise<AnswerAskOutcome> {
+ const workspaceId = args.workspace.id;
+
+ const inputAsk = await this.inputAskWorkspaceService.findReadable({
+ workspaceId,
+ inputAskId: args.askId,
+ });
+
+ if (!isDefined(inputAsk)) {
+ throw new InputAskException(
+ 'Ask not found',
+ InputAskExceptionCode.ASK_NOT_FOUND,
+ );
+ }
+
+ if (inputAsk.status !== InputAskStatus.PENDING) {
+ throw this.notPending();
+ }
+
+ if (isDefined(inputAsk.threadId) && isDefined(inputAsk.toolCallId)) {
+ const { threadId, toolCallId, workflowRunId } = inputAsk;
+ const toolPart = await this.agentChatService.findToolPart({
+ threadId,
+ toolCallId,
+ workspaceId,
+ });
+ const pausingToolCall = parsePausingToolCall(toolPart);
+
+ if (!isDefined(toolPart) || !isDefined(pausingToolCall)) {
+ throw new InputAskException(
+ 'The tool call this Ask waits on could not be found',
+ InputAskExceptionCode.ASK_NOT_FOUND,
+ );
+ }
+
+ const validation = pausingToolCall.validate(args.response);
+
+ if (!validation.isValid) {
+ throw new InputAskException(
+ validation.errorMessage,
+ InputAskExceptionCode.INVALID_ASK_RESPONSE,
+ );
+ }
+
+ const toolCallToAnswer: ToolCallToAnswer = {
+ ...args,
+ threadId,
+ toolCallId,
+ toolPart,
+ pausingToolCall,
+ output: validation.output,
+ };
+
+ if (isDefined(workflowRunId)) {
+ await this.answerWorkflowRunToolCall({
+ ...toolCallToAnswer,
+ workflowRunId,
+ });
+
+ return NO_STREAM;
+ }
+
+ return this.answerChatToolCall(toolCallToAnswer);
+ }
+
+ if (isDefined(inputAsk.workflowRunId) && isDefined(inputAsk.stepId)) {
+ await this.answerFormStep({
+ ...args,
+ form: inputAsk.form,
+ workflowRunId: inputAsk.workflowRunId,
+ stepId: inputAsk.stepId,
+ });
+
+ return NO_STREAM;
+ }
+
+ throw new InputAskException(
+ 'This Ask gates nothing that can be answered',
+ InputAskExceptionCode.ASK_NOT_FOUND,
+ );
+ }
+
+ // Behind submitFormStep, kept for clients built before answerAsk: the
+ // form step's Ask is answered as if it had been named.
+ async answerFormStepByStep({
+ workflowRunId,
+ stepId,
+ ...args
+ }: Omit<AnswerAskArgs, 'askId' | 'modelId'> & {
+ workflowRunId: string;
+ stepId: string;
+ }): Promise<void> {
+ const inputAsk = await this.inputAskWorkspaceService.findPendingForStep({
+ workspaceId: args.workspace.id,
+ workflowRunId,
+ stepId,
+ });
+
+ if (!isDefined(inputAsk)) {
+ throw this.notPending();
+ }
+
+ await this.answer({ ...args, askId: inputAsk.id });
+ }
+
+ // Behind answerAgentChatQuestion, kept for clients built before answerAsk:
+ // a question is named by the message that asked it rather than by its Ask.
+ async answerQuestionsOfMessage({
+ threadId,
+ messageId,
+ ...args
+ }: Omit<AnswerAskArgs, 'askId'> & {
+ threadId: string;
+ messageId: string;
+ }): Promise<AnswerAskOutcome> {
+ const workspaceId = args.workspace.id;
+ const pendingInputAsks =
+ await this.inputAskWorkspaceService.findPendingForThread({
+ workspaceId,
+ threadId,
+ });
+
+ for (const { id, toolCallId } of pendingInputAsks) {
+ if (!isDefined(toolCallId)) {
+ continue;
+ }
+
+ const toolPart = await this.agentChatService.findToolPart({
+ threadId,
+ toolCallId,
+ workspaceId,
+ });
+
+ if (
+ toolPart?.messageId === messageId &&
+ toolPart.toolName === ASK_QUESTIONS_TOOL_NAME
+ ) {
+ return this.answer({ ...args, askId: id });
+ }
+ }
+
+ throw this.notPending();
+ }
+
+ private async answerFormStep({
+ response,
+ userWorkspaceId,
+ workspace,
+ form,
+ workflowRunId,
+ stepId,
+ }: AnswerAskArgs & {
+ form: InputAskWorkspaceEntity['form'];
+ workflowRunId: string;
+ stepId: string;
+ }): Promise<void> {
+ const workspaceId = workspace.id;
+
+ if (form?.kind === 'formFields') {
+ const fieldNames = new Set(form.fields.map((field) => field.name));
+ const unknownFieldName = Object.keys(response).find(
+ (fieldName) => !fieldNames.has(fieldName),
+ );
+
+ if (isDefined(unknownFieldName)) {
+ throw new InputAskException(
+ `The form has no field named ${unknownFieldName}`,
+ InputAskExceptionCode.INVALID_ASK_RESPONSE,
+ );
+ }
+ }
+
+ await this.assertCanAnswerForWorkflowRun({
+ userWorkspaceId,
+ workspaceId,
+ workflowRunId,
+ });
+
+ const hasSubmitted =
+ await this.workflowRunnerWorkspaceService.submitFormStep({
+ workspaceId,
+ workflowRunId,
+ stepId,
+ response,
+ });
+
+ if (!hasSubmitted) {
+ throw this.notPending();
+ }
+ }
+
+ private async answerChatToolCall({
+ threadId,
+ toolCallId,
+ toolPart,
+ pausingToolCall,
+ output,
+ userWorkspaceId,
+ workspace,
+ modelId,
+ workspaceMemberId,
+ }: ToolCallToAnswer): Promise<AnswerAskOutcome> {
+ const workspaceId = workspace.id;
+
+ await this.assertHasSettingPermission({
+ setting: PermissionFlagType.AI,
+ userWorkspaceId,
+ workspaceId,
+ });
+
+ const thread = await this.turnPreflightService.assertCanStartChatTurn({
+ threadId,
+ modelId,
+ userWorkspaceId,
+ workspaceMemberId,
+ workspace,
+ });
+
+ await this.actorService.authorizeToolCallResolution({
+ workspaceId,
+ threadId,
+ messageId: toolPart.messageId,
+ });
+
+ await this.agentChatStreamingService.reapDeadStream({
+ thread,
+ workspaceId,
+ });
+
+ const streamId = generateId();
+
+ const hasClaimedStream =
+ await this.agentChatStreamingService.tryClaimStream({
+ threadId,
+ workspaceId,
+ streamId,
+ });
+
+ if (!hasClaimedStream) {
+ throw new InputAskException(
+ 'The conversation is still busy with another response',
+ InputAskExceptionCode.ASK_NOT_PENDING,
+ );
+ }
+
+ let hasAnswered = false;
+
+ try {
+ hasAnswered = await this.inputAskWorkspaceService.answer({
+ workspaceId,
+ key: { threadId, toolCallId },
+ response: output,
+ });
+ } finally {
+ if (!hasAnswered) {
+ await this.agentChatStreamingService.releaseStreamClaim(
+ threadId,
+ workspaceId,
+ streamId,
+ );
+ }
+ }
+
+ if (!hasAnswered) {
+ throw this.notPending();
+ }
+
+ let turnId: string | null;
+ let hasOtherPendingAsks = false;
+
+ // The answer is already recorded, so a failure from here on leaves a
+ // failed turn to retry rather than an answer that can be given twice.
+ try {
+ const completion = await pausingToolCall.complete({
+ output,
+ context: this.buildCompletionContext({
+ workspaceId,
+ userWorkspaceId,
+ threadId,
+ }),
+ });
+
+ await this.agentChatService.updateToolPartOutput({
+ partId: toolPart.id,
+ toolOutput: completion.toolResult,
+ workspaceId,
+ });
+
+ const answerMessage = await this.agentChatService.addMessage({
+ threadId,
+ userWorkspaceId,
+ uiMessage: {
+ role: AgentMessageRole.USER,
+ parts: [{ type: 'text', text: completion.answerText }],
+ },
+ workspaceId,
+ });
+
+ turnId = answerMessage.turnId;
+
+ // The agent continues once every call it paused on is answered. Each
+ // answer holds the stream claim until here, so exactly one of them,
+ // the last, finds none left.
+ hasOtherPendingAsks =
+ await this.inputAskWorkspaceService.hasPendingForThread({
+ threadId,
+ workspaceId,
+ });
+
+ if (hasOtherPendingAsks) {
+ await this.agentChatStreamingService.releaseStreamClaim(
+ threadId,
+ workspaceId,
+ streamId,
+ );
+ } else {
+ await this.agentChatStreamingService.enqueueResumeStream({
+ threadId,
+ userWorkspaceId,
+ workspaceMemberId,
+ workspace,
+ turnId,
+ streamId,
+ modelId,
+ messageId: answerMessage.id,
+ });
+ }
+ } catch (error) {
+ const streamError = mapErrorToStreamError(error);
+
+ await this.agentChatStreamingService.releaseStreamClaim(
+ threadId,
+ workspaceId,
+ streamId,
+ {
+ lastStreamError: {
+ ...streamError,
+ failedAt: new Date().toISOString(),
+ },
+ },
+ );
+
+ await this.eventPublisherService
+ .publish({
+ threadId,
+ workspaceId,
+ event: {
+ type: 'stream-error',
+ code: streamError.code,
+ message: streamError.message,
+ },
+ })
+ .catch(() => {});
+
+ throw error;
+ }
+
+ await this.publishToolCallResolved({ threadId, toolCallId, workspaceId });
+
+ return {
+ streamId: hasOtherPendingAsks ? null : streamId,
+ threadId,
+ turnId,
+ };
+ }
+
+ private async answerWorkflowRunToolCall({
+ threadId,
+ toolCallId,
+ toolPart,
+ pausingToolCall,
+ output,
+ userWorkspaceId,
+ workspace,
+ workflowRunId,
+ }: ToolCallToAnswer & { workflowRunId: string }): Promise<void> {
+ const workspaceId = workspace.id;
+
+ await this.assertCanAnswerForWorkflowRun({
+ userWorkspaceId,
+ workspaceId,
+ workflowRunId,
+ });
+
+ // The answer resumes the agent step that asked, not the steps after it:
+ // the agent continues its conversation with the answer as the last message.
+ const claim =
+ await this.workflowRunWorkspaceService.resolveStepAwaitingToolCall({
+ threadId,
+ toolCallId,
+ response: output,
+ workflowRunId,
+ workspaceId,
+ });
+
+ if (claim.status !== 'RESOLVED') {
+ throw this.notPending();
+ }
+
+ // The Ask is answered and cannot be answered again, so a completion or a
+ // resume that fails fails the run, which can then be retried, rather than
+ // leaving it waiting on an answer nobody can give anymore.
+ try {
+ const completion = await pausingToolCall.complete({
+ output,
+ context: this.buildCompletionContext({
+ workspaceId,
+ userWorkspaceId,
+ threadId,
+ }),
+ });
+
+ await this.workflowRunnerWorkspaceService.resumeAnsweredAgentStep({
+ workspaceId,
+ workflowRunId,
+ stepId: claim.stepId,
+ threadId,
+ toolPart,
+ toolResult: completion.toolResult,
+ answerText: completion.answerText,
+ senderUserWorkspaceId: userWorkspaceId,
+ });
+ } catch (error) {
+ await this.workflowRunWorkspaceService.endWorkflowRun({
+ workflowRunId,
+ workspaceId,
+ status: WorkflowRunStatus.FAILED,
+ error: 'The run could not resume after its question was answered',
+ });
+
+ throw error;
+ }
+
+ await this.publishToolCallResolved({ threadId, toolCallId, workspaceId });
+ }
+
+ // The same permission that lets someone run a workflow, on a run they can
+ // read.
+ private async assertCanAnswerForWorkflowRun({
+ userWorkspaceId,
+ workspaceId,
+ workflowRunId,
+ }: {
+ userWorkspaceId: string;
+ workspaceId: string;
+ workflowRunId: string;
+ }): Promise<void> {
+ await this.assertHasSettingPermission({
+ setting: PermissionFlagType.WORKFLOWS,
+ userWorkspaceId,
+ workspaceId,
+ });
+
+ let workflowRun: Pick<WorkflowRunWorkspaceEntity, 'id'> | null = null;
+
+ try {
+ workflowRun = await this.workspaceOrmManager.executeInWorkspaceContext(
+ () =>
+ this.workspaceOrmManager
+ .getRepositoryWithContextPermissions<WorkflowRunWorkspaceEntity>(
+ 'workflowRun',
+ )
+ .findOne({ where: { id: workflowRunId }, select: { id: true } }),
+ );
+ } catch (error) {
+ if (!(error instanceof PermissionsException)) {
+ throw error;
+ }
+ }
+
+ if (!isDefined(workflowRun)) {
+ throw new InputAskException(
+ 'Ask not found',
+ InputAskExceptionCode.ASK_NOT_FOUND,
+ );
+ }
+ }
+
+ // Built only when a pausing tool runs another tool, and as the person who
+ // answered: their role and connected accounts decide what it may do.
+ private buildCompletionContext({
+ workspaceId,
+ userWorkspaceId,
+ threadId,
+ }: {
+ workspaceId: string;
+ userWorkspaceId: string;
+ threadId: string;
+ }): PausingToolCompletionContext {
+ return {
+ executeTool: async ({ toolName, args }) => {
+ const authContext = workspaceAuthContextStorage.getStore();
+
+ if (!isDefined(authContext) || !isUserAuthContext(authContext)) {
+ throw new InputAskException(
+ 'Answering requires a signed-in person',
+ InputAskExceptionCode.ASK_ANSWER_FORBIDDEN,
+ );
+ }
+
+ const { userWorkspaceRoleMap } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'userWorkspaceRoleMap',
+ ]);
+ const { actorContext, roleId, userId, userContext } =
+ await this.agentActorContextService.buildUserAndAgentActorContext(
+ userWorkspaceId,
+ workspaceId,
+ );
+
+ return this.toolRegistryService.resolveAndExecute(toolName, args, {
+ workspaceId,
+ roleId,
+ rolePermissionConfig:
+ resolveRolePermissionConfig({
+ authContext,
+ userWorkspaceRoleMap,
+ apiKeyRoleMap: {},
+ }) ?? undefined,
+ authContext,
+ actorContext,
+ userId,
+ userWorkspaceId,
+ threadId,
+ locale: userContext.locale as ToolContext['locale'],
+ });
+ },
+ };
+ }
+
+ private async assertHasSettingPermission({
+ setting,
+ userWorkspaceId,
+ workspaceId,
+ }: {
+ setting: PermissionFlagType;
+ userWorkspaceId: string;
+ workspaceId: string;
+ }): Promise<void> {
+ const requestAuthContext = workspaceAuthContextStorage.getStore();
+ const applicationId =
+ isDefined(requestAuthContext) && isUserAuthContext(requestAuthContext)
+ ? requestAuthContext.application?.id
+ : undefined;
+
+ const hasPermission =
+ await this.permissionsService.userHasWorkspaceSettingPermission({
+ userWorkspaceId,
+ workspaceId,
+ setting,
+ applicationId,
+ });
+
+ if (!hasPermission) {
+ throw new InputAskException(
+ `Answering this Ask requires the ${setting} permission`,
+ InputAskExceptionCode.ASK_ANSWER_FORBIDDEN,
+ );
+ }
+ }
+
+ private notPending(): InputAskException {
+ return new InputAskException(
+ 'This Ask is no longer waiting for an answer',
+ InputAskExceptionCode.ASK_NOT_PENDING,
+ );
+ }
+
+ private async publishToolCallResolved({
+ threadId,
+ toolCallId,
+ workspaceId,
+ }: {
+ threadId: string;
+ toolCallId: string;
+ workspaceId: string;
+ }): Promise<void> {
+ await this.eventPublisherService
+ .publish({
+ threadId,
+ workspaceId,
+ event: { type: 'tool-call-resolved', toolCallId },
+ })
+ .catch(() => {});
+ }
+}
diff --git a/packages/twenty-server/src/modules/input-ask/filters/input-ask-graphql-api-exception.filter.ts b/packages/twenty-server/src/modules/input-ask/filters/input-ask-graphql-api-exception.filter.ts
new file mode 100644
index 00000000000..da7ecdc221d
--- /dev/null
+++ b/packages/twenty-server/src/modules/input-ask/filters/input-ask-graphql-api-exception.filter.ts
@@ -0,0 +1,11 @@
+import { Catch, type ExceptionFilter } from '@nestjs/common';
+
+import { InputAskException } from 'src/modules/input-ask/input-ask.exception';
+import { inputAskGraphqlApiExceptionHandler } from 'src/modules/input-ask/utils/input-ask-graphql-api-exception-handler.util';
+
+@Catch(InputAskException)
+export class InputAskGraphqlApiExceptionFilter implements ExceptionFilter {
+ catch(exception: InputAskException) {
+ return inputAskGraphqlApiExceptionHandler(exception);
+ }
+}
diff --git a/packages/twenty-server/src/modules/input-ask/input-ask.exception.ts b/packages/twenty-server/src/modules/input-ask/input-ask.exception.ts
new file mode 100644
index 00000000000..56777a8ede5
--- /dev/null
+++ b/packages/twenty-server/src/modules/input-ask/input-ask.exception.ts
@@ -0,0 +1,45 @@
+import { type MessageDescriptor } from '@lingui/core';
+import { msg } from '@lingui/core/macro';
+import { assertUnreachable } from 'twenty-shared/utils';
+
+import { CustomException } from 'src/utils/custom-exception';
+
+export enum InputAskExceptionCode {
+ INPUT_ASK_OBJECT_MISSING = 'INPUT_ASK_OBJECT_MISSING',
+ ASK_NOT_FOUND = 'ASK_NOT_FOUND',
+ ASK_NOT_PENDING = 'ASK_NOT_PENDING',
+ INVALID_ASK_RESPONSE = 'INVALID_ASK_RESPONSE',
+ ASK_ANSWER_FORBIDDEN = 'ASK_ANSWER_FORBIDDEN',
+}
+
+const getInputAskExceptionUserFriendlyMessage = (
+ code: InputAskExceptionCode,
+) => {
+ switch (code) {
+ case InputAskExceptionCode.INPUT_ASK_OBJECT_MISSING:
+ return msg`This workspace is still being upgraded and cannot wait for an answer yet. Try again in a moment.`;
+ case InputAskExceptionCode.ASK_NOT_FOUND:
+ return msg`This request for input could not be found.`;
+ case InputAskExceptionCode.ASK_NOT_PENDING:
+ return msg`This request is no longer waiting for an answer.`;
+ case InputAskExceptionCode.INVALID_ASK_RESPONSE:
+ return msg`Invalid answer for this request.`;
+ case InputAskExceptionCode.ASK_ANSWER_FORBIDDEN:
+ return msg`You are not allowed to answer this request.`;
+ default:
+ assertUnreachable(code);
+ }
+};
+
+export class InputAskException extends CustomException<InputAskExceptionCode> {
+ constructor(
+ message: string,
+ code: InputAskExceptionCode,
+ { userFriendlyMessage }: { userFriendlyMessage?: MessageDescriptor } = {},
+ ) {
+ super(message, code, {
+ userFriendlyMessage:
+ userFriendlyMessage ?? getInputAskExceptionUserFriendlyMessage(code),
+ });
+ }
+}
diff --git a/packages/twenty-server/src/modules/input-ask/standard-objects/input-ask.workspace-entity.ts b/packages/twenty-server/src/modules/input-ask/standard-objects/input-ask.workspace-entity.ts
index aa9c67b123e..c3e8f54f019 100644
--- a/packages/twenty-server/src/modules/input-ask/standard-objects/input-ask.workspace-entity.ts
+++ b/packages/twenty-server/src/modules/input-ask/standard-objects/input-ask.workspace-entity.ts
@@ -1,11 +1,10 @@
-import { type AskQuestionItem } from 'twenty-shared/ai';
+import { type InputAskForm } from 'twenty-shared/ai';
import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
import { type InputAskStatus } from 'src/modules/input-ask/enums/input-ask-status.enum';
import { BaseWorkspaceEntity } from 'src/engine/twenty-orm/base.workspace-entity';
import { type EntityRelation } from 'src/engine/workspace-manager/workspace-migration/types/entity-relation.interface';
import { type WorkflowRunWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
-import { type FormFieldMetadata } from 'src/modules/workflow/workflow-executor/workflow-actions/form/types/workflow-form-action-settings.type';
import { type WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-member/standard-objects/workspace-member.workspace-entity';
export class InputAskWorkspaceEntity extends BaseWorkspaceEntity {
@@ -15,10 +14,7 @@ export class InputAskWorkspaceEntity extends BaseWorkspaceEntity {
// The questions are snapshotted rather than read back from the step: a
// workflow version can be edited or discarded after the Ask goes out, and
// what someone was asked has to stay what they were asked.
- form:
- | { fields: FormFieldMetadata[] }
- | { questions: AskQuestionItem[] }
- | null;
+ form: InputAskForm | null;
response: Record<string, unknown> | null;
answeredAt: string | null;
stepId: string | null;
diff --git a/packages/twenty-server/src/modules/input-ask/utils/input-ask-graphql-api-exception-handler.util.ts b/packages/twenty-server/src/modules/input-ask/utils/input-ask-graphql-api-exception-handler.util.ts
new file mode 100644
index 00000000000..06f9bc56a4c
--- /dev/null
+++ b/packages/twenty-server/src/modules/input-ask/utils/input-ask-graphql-api-exception-handler.util.ts
@@ -0,0 +1,30 @@
+import { assertUnreachable } from 'twenty-shared/utils';
+
+import {
+ ForbiddenError,
+ InternalServerError,
+ NotFoundError,
+ UserInputError,
+} from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
+import {
+ type InputAskException,
+ InputAskExceptionCode,
+} from 'src/modules/input-ask/input-ask.exception';
+
+export const inputAskGraphqlApiExceptionHandler = (
+ exception: InputAskException,
+): never => {
+ switch (exception.code) {
+ case InputAskExceptionCode.ASK_NOT_FOUND:
+ throw new NotFoundError(exception);
+ case InputAskExceptionCode.ASK_NOT_PENDING:
+ case InputAskExceptionCode.INVALID_ASK_RESPONSE:
+ throw new UserInputError(exception);
+ case InputAskExceptionCode.ASK_ANSWER_FORBIDDEN:
+ throw new ForbiddenError(exception);
+ case InputAskExceptionCode.INPUT_ASK_OBJECT_MISSING:
+ throw new InternalServerError(exception);
+ default:
+ return assertUnreachable(exception.code);
+ }
+};
diff --git a/packages/twenty-server/src/modules/input-ask/workspace-services/__tests__/input-ask.workspace-service.spec.ts b/packages/twenty-server/src/modules/input-ask/workspace-services/__tests__/input-ask.workspace-service.spec.ts
new file mode 100644
index 00000000000..2664af3507c
--- /dev/null
+++ b/packages/twenty-server/src/modules/input-ask/workspace-services/__tests__/input-ask.workspace-service.spec.ts
@@ -0,0 +1,240 @@
+import { IsNull, Not } from 'typeorm';
+
+import {
+ TwentyOrmException,
+ TwentyOrmExceptionCode,
+} from 'src/engine/twenty-orm/exceptions/twenty-orm.exception';
+import { InputAskStatus } from 'src/modules/input-ask/enums/input-ask-status.enum';
+import { InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-service';
+
+const QUESTIONS_FORM = {
+ kind: 'questions' as const,
+ questions: [
+ {
+ header: 'Plan',
+ question: 'Which plan?',
+ options: [{ label: 'Pro' }, { label: 'Team' }],
+ },
+ ],
+};
+
+describe('InputAskWorkspaceService', () => {
+ const buildService = ({ hasInputAskObject = true } = {}) => {
+ const inputAskRepository = {
+ insert: jest.fn().mockResolvedValue(undefined),
+ update: jest.fn().mockResolvedValue({ affected: 1 }),
+ findOne: jest.fn().mockResolvedValue(null),
+ };
+ const workspaceOrmManager = {
+ executeInWorkspaceContext: jest.fn().mockImplementation((work) => work()),
+ getRepository: jest.fn().mockReturnValue(inputAskRepository),
+ getRepositoryWithContextPermissions: jest
+ .fn()
+ .mockReturnValue(inputAskRepository),
+ };
+ const recordPositionService = {
+ buildRecordPosition: jest.fn().mockResolvedValue(-1),
+ };
+ const workspaceCacheService = {
+ getOrRecompute: jest.fn().mockResolvedValue({
+ flatObjectMetadataMaps: {
+ byUniversalIdentifier: hasInputAskObject
+ ? new Proxy({}, { get: () => ({ id: 'input-ask-object-id' }) })
+ : {},
+ },
+ }),
+ };
+
+ const service = new InputAskWorkspaceService(
+ workspaceOrmManager as never,
+ recordPositionService as never,
+ workspaceCacheService as never,
+ );
+
+ return { service, inputAskRepository, workspaceOrmManager };
+ };
+
+ describe('open', () => {
+ const toolCallAsk = {
+ name: 'Which plan?',
+ form: QUESTIONS_FORM,
+ threadId: 'thread-id',
+ toolCallId: 'tool-call-id',
+ assigneeId: 'member-id',
+ };
+
+ it('inserts a pending Ask', async () => {
+ const { service, inputAskRepository } = buildService();
+
+ await service.open({
+ workspaceId: 'workspace-id',
+ inputAsk: toolCallAsk,
+ });
+
+ expect(inputAskRepository.insert).toHaveBeenCalledWith({
+ ...toolCallAsk,
+ status: InputAskStatus.PENDING,
+ position: -1,
+ });
+ expect(inputAskRepository.update).not.toHaveBeenCalled();
+ });
+
+ it('asks a form step again when the run re-enters it', async () => {
+ const { service, inputAskRepository } = buildService();
+
+ inputAskRepository.insert.mockRejectedValue(
+ new TwentyOrmException(
+ 'duplicate',
+ TwentyOrmExceptionCode.DUPLICATE_ENTRY_DETECTED,
+ ),
+ );
+
+ await service.open({
+ workspaceId: 'workspace-id',
+ inputAsk: {
+ name: 'Approve',
+ form: { kind: 'formFields', fields: [] },
+ workflowRunId: 'workflow-run-id',
+ stepId: 'step-id',
+ assigneeId: null,
+ },
+ });
+
+ expect(inputAskRepository.update).toHaveBeenCalledWith(
+ {
+ workflowRunId: 'workflow-run-id',
+ stepId: 'step-id',
+ toolCallId: IsNull(),
+ status: Not(InputAskStatus.PENDING),
+ },
+ {
+ name: 'Approve',
+ form: { kind: 'formFields', fields: [] },
+ status: InputAskStatus.PENDING,
+ response: null,
+ answeredAt: null,
+ },
+ );
+ });
+
+ it('rethrows any other write failure', async () => {
+ const { service, inputAskRepository } = buildService();
+
+ inputAskRepository.insert.mockRejectedValue(new Error('db down'));
+
+ await expect(
+ service.open({ workspaceId: 'workspace-id', inputAsk: toolCallAsk }),
+ ).rejects.toThrow('db down');
+ });
+
+ it('refuses to pause a tool call in a workspace without Asks yet', async () => {
+ const { service, inputAskRepository } = buildService({
+ hasInputAskObject: false,
+ });
+
+ await expect(
+ service.open({ workspaceId: 'workspace-id', inputAsk: toolCallAsk }),
+ ).rejects.toMatchObject({ code: 'INPUT_ASK_OBJECT_MISSING' });
+ expect(inputAskRepository.insert).not.toHaveBeenCalled();
+ });
+
+ it('lets a form step wait without an Ask in a workspace without Asks yet', async () => {
+ const { service, inputAskRepository } = buildService({
+ hasInputAskObject: false,
+ });
+
+ await service.open({
+ workspaceId: 'workspace-id',
+ inputAsk: {
+ name: 'Approve',
+ form: { kind: 'formFields', fields: [] },
+ workflowRunId: 'workflow-run-id',
+ stepId: 'step-id',
+ assigneeId: null,
+ },
+ });
+
+ expect(inputAskRepository.insert).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('answer', () => {
+ it('answers only a pending Ask, reporting whether it was the one to answer it', async () => {
+ const { service, inputAskRepository } = buildService();
+
+ inputAskRepository.update
+ .mockResolvedValueOnce({ affected: 1 })
+ .mockResolvedValueOnce({ affected: 0 });
+
+ const answer = () =>
+ service.answer({
+ workspaceId: 'workspace-id',
+ key: { threadId: 'thread-id', toolCallId: 'tool-call-id' },
+ response: { answers: [] },
+ });
+
+ expect(await answer()).toBe(true);
+ expect(await answer()).toBe(false);
+ expect(inputAskRepository.update).toHaveBeenCalledWith(
+ {
+ threadId: 'thread-id',
+ toolCallId: 'tool-call-id',
+ status: InputAskStatus.PENDING,
+ },
+ {
+ status: InputAskStatus.ANSWERED,
+ response: { answers: [] },
+ answeredAt: expect.any(String),
+ },
+ );
+ });
+ });
+
+ describe('cancel', () => {
+ it('cancels one pending Ask by its key', async () => {
+ const { service, inputAskRepository } = buildService();
+
+ expect(
+ await service.cancel({
+ workspaceId: 'workspace-id',
+ match: { threadId: 'thread-id', toolCallId: 'tool-call-id' },
+ }),
+ ).toBe(true);
+ expect(inputAskRepository.update).toHaveBeenCalledWith(
+ {
+ threadId: 'thread-id',
+ toolCallId: 'tool-call-id',
+ status: InputAskStatus.PENDING,
+ },
+ { status: InputAskStatus.CANCELED },
+ );
+ });
+
+ it('cancels what an ended run left pending', async () => {
+ const { service, inputAskRepository } = buildService();
+
+ await service.cancel({
+ workspaceId: 'workspace-id',
+ match: { workflowRunId: 'workflow-run-id' },
+ });
+
+ expect(inputAskRepository.update).toHaveBeenCalledWith(
+ { workflowRunId: 'workflow-run-id', status: InputAskStatus.PENDING },
+ { status: InputAskStatus.CANCELED },
+ );
+ });
+
+ it('surfaces a failure to cancel a single Ask', async () => {
+ const { service, inputAskRepository } = buildService();
+
+ inputAskRepository.update.mockRejectedValue(new Error('db down'));
+
+ await expect(
+ service.cancel({
+ workspaceId: 'workspace-id',
+ match: { threadId: 'thread-id', toolCallId: 'tool-call-id' },
+ }),
+ ).rejects.toThrow('db down');
+ });
+ });
+});
diff --git a/packages/twenty-server/src/modules/input-ask/workspace-services/input-ask.workspace-service.ts b/packages/twenty-server/src/modules/input-ask/workspace-services/input-ask.workspace-service.ts
index 479e5c6a123..0b0e50bbea9 100644
--- a/packages/twenty-server/src/modules/input-ask/workspace-services/input-ask.workspace-service.ts
+++ b/packages/twenty-server/src/modules/input-ask/workspace-services/input-ask.workspace-service.ts
@@ -1,27 +1,57 @@
import { Injectable } from '@nestjs/common';
-import { type AskQuestionItem } from 'twenty-shared/ai';
import { STANDARD_OBJECTS } from 'twenty-shared/metadata';
-import { isDefined, isPlainObject } from 'twenty-shared/utils';
-import { StepStatus, type WorkflowRunStepInfo } from 'twenty-shared/workflow';
-import { IsNull, Not } from 'typeorm';
+import { isDefined } from 'twenty-shared/utils';
+import { type FindOptionsWhere, IsNull, Not } from 'typeorm';
import { RecordPositionService } from 'src/engine/core-modules/record-position/services/record-position.service';
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { type WorkspaceRepository } from 'src/engine/twenty-orm/repository/workspace-repository';
-import {
- TwentyOrmException,
- TwentyOrmExceptionCode,
-} from 'src/engine/twenty-orm/exceptions/twenty-orm.exception';
+import { isDuplicateEntryError } from 'src/engine/twenty-orm/utils/is-duplicate-entry-error.util';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
import { InputAskStatus } from 'src/modules/input-ask/enums/input-ask-status.enum';
+import {
+ InputAskException,
+ InputAskExceptionCode,
+} from 'src/modules/input-ask/input-ask.exception';
import { type InputAskWorkspaceEntity } from 'src/modules/input-ask/standard-objects/input-ask.workspace-entity';
-import { type FormFieldMetadata } from 'src/modules/workflow/workflow-executor/workflow-actions/form/types/workflow-form-action-settings.type';
-const isDuplicateEntry = (error: unknown): boolean =>
- error instanceof TwentyOrmException &&
- error.code === TwentyOrmExceptionCode.DUPLICATE_ENTRY_DETECTED;
+export type InputAskToolCallKey = { threadId: string; toolCallId: string };
+
+// A form step's Ask is keyed by its run and step; any Ask a tool call opened,
+// in a chat or in a run, by the conversation and the call.
+export type InputAskKey =
+ | { workflowRunId: string; stepId: string }
+ | InputAskToolCallKey;
+
+export type InputAskToOpen = Pick<
+ InputAskWorkspaceEntity,
+ 'name' | 'form' | 'assigneeId'
+> &
+ (
+ | (InputAskToolCallKey & { workflowRunId?: string; stepId?: string })
+ | {
+ workflowRunId: string;
+ stepId: string;
+ threadId?: undefined;
+ toolCallId?: undefined;
+ }
+ );
+
+const isToolCallKey = (key: InputAskKey): key is InputAskToolCallKey =>
+ 'toolCallId' in key;
+
+const buildKeyWhere = (
+ key: InputAskKey,
+): FindOptionsWhere<InputAskWorkspaceEntity> =>
+ isToolCallKey(key)
+ ? { threadId: key.threadId, toolCallId: key.toolCallId }
+ : {
+ workflowRunId: key.workflowRunId,
+ stepId: key.stepId,
+ toolCallId: IsNull(),
+ };
@Injectable()
export class InputAskWorkspaceService {
@@ -31,251 +61,217 @@ export class InputAskWorkspaceService {
private readonly workspaceCacheService: WorkspaceCacheService,
) {}
- // A run can re-enter a form it already asked about (a retried worker, a
- // retried run, the next item of an iterator): the previous answer belonged
- // to the previous execution, while a question still pending may be one
- // someone is looking at.
- async openForFormStep({
+ // A run can re-enter a step it already asked about (a retried worker, a
+ // retried run, the next item of an iterator): the key's unique index turns
+ // that into a duplicate, and the existing Ask is asked again rather than a
+ // second one opened.
+ async open({
workspaceId,
- workflowRunId,
- stepId,
- stepName,
- fields,
+ inputAsk,
}: {
workspaceId: string;
- workflowRunId: string;
- stepId: string;
- stepName: string;
- fields: FormFieldMetadata[];
+ inputAsk: InputAskToOpen;
}): Promise<void> {
- if (!(await this.hasInputAskObject(workspaceId))) {
- return;
- }
-
- await this.executeAsSystem(workspaceId, async (inputAskRepository) => {
- const reopenResult = await inputAskRepository.update(
- {
- workflowRunId,
- stepId,
- toolCallId: IsNull(),
- status: Not(InputAskStatus.PENDING),
- },
- {
- name: stepName,
- status: InputAskStatus.PENDING,
- form: { fields },
- response: null,
- answeredAt: null,
- },
- );
+ const key: InputAskKey =
+ inputAsk.toolCallId !== undefined
+ ? { threadId: inputAsk.threadId, toolCallId: inputAsk.toolCallId }
+ : { workflowRunId: inputAsk.workflowRunId, stepId: inputAsk.stepId };
- if ((reopenResult.affected ?? 0) > 0) {
- return;
- }
+ await this.execute({
+ workspaceId,
+ // A paused tool call can only be answered through its Ask, so it must
+ // not pause without one. A form step still parks, and the 2.44 upgrade
+ // opens the Ask it waits on.
+ whenObjectMissing: () => {
+ if (isToolCallKey(key)) {
+ throw new InputAskException(
+ 'This workspace cannot record a request for input yet',
+ InputAskExceptionCode.INPUT_ASK_OBJECT_MISSING,
+ );
+ }
+ },
+ run: async (inputAskRepository) => {
+ const position = await this.recordPositionService.buildRecordPosition({
+ value: 'first',
+ objectMetadata: { isCustom: false, nameSingular: 'inputAsk' },
+ workspaceId,
+ });
- const position = await this.recordPositionService.buildRecordPosition({
- value: 'first',
- objectMetadata: { isCustom: false, nameSingular: 'inputAsk' },
- workspaceId,
- });
+ try {
+ await inputAskRepository.insert({
+ ...inputAsk,
+ status: InputAskStatus.PENDING,
+ position,
+ });
- try {
- await inputAskRepository.insert({
- name: stepName,
- status: InputAskStatus.PENDING,
- form: { fields },
- workflowRunId,
- stepId,
- position,
- });
- } catch (error) {
- // The row is already pending, whether from an earlier execution or a
- // concurrent worker
- if (!isDuplicateEntry(error)) {
- throw error;
+ return;
+ } catch (error) {
+ if (!isDuplicateEntryError(error)) {
+ throw error;
+ }
}
- }
+
+ await inputAskRepository.update(
+ { ...buildKeyWhere(key), status: Not(InputAskStatus.PENDING) },
+ {
+ name: inputAsk.name,
+ form: inputAsk.form,
+ status: InputAskStatus.PENDING,
+ response: null,
+ answeredAt: null,
+ },
+ );
+ },
});
}
- // Records the answer the run has already accepted. The run's own step
- // transition is what refuses a second submission, so nothing here gates
- // anything: a row that is missing, canceled or already answered simply has
- // nothing left to record.
- async answerForFormStep({
+ // Moving an Ask out of PENDING is the claim on it: of two concurrent
+ // answers only one sees a row change, so only one resumes what waits on it.
+ async answer({
workspaceId,
- workflowRunId,
- stepId,
+ key,
response,
}: {
workspaceId: string;
- workflowRunId: string;
- stepId: string;
+ key: InputAskKey;
response: Record<string, unknown>;
- }): Promise<void> {
- if (!(await this.hasInputAskObject(workspaceId))) {
- return;
- }
+ }): Promise<boolean> {
+ return this.execute({
+ workspaceId,
+ whenObjectMissing: () => false,
+ run: async (inputAskRepository) => {
+ const result = await inputAskRepository.update(
+ { ...buildKeyWhere(key), status: InputAskStatus.PENDING },
+ {
+ status: InputAskStatus.ANSWERED,
+ response,
+ answeredAt: new Date().toISOString(),
+ },
+ );
- await this.executeAsSystem(workspaceId, async (inputAskRepository) => {
- await inputAskRepository.update(
- {
- workflowRunId,
- stepId,
- toolCallId: IsNull(),
- status: InputAskStatus.PENDING,
- },
- {
- status: InputAskStatus.ANSWERED,
- response,
- answeredAt: new Date().toISOString(),
- },
- );
+ return (result.affected ?? 0) > 0;
+ },
});
}
- // An agent can ask several times in one conversation, each question its own
- // Ask keyed on the tool call that asked it. The conversation's pending
- // marker and the run's step stay what gate the answer; this only records
- // the question where people can find it.
- async openForAgentQuestion({
+ async cancel({
workspaceId,
- workflowRunId,
- stepId,
- threadId,
- toolCallId,
- name,
- questions,
+ match,
}: {
workspaceId: string;
- workflowRunId: string;
- stepId: string;
- threadId: string;
- toolCallId: string;
- name: string;
- questions: AskQuestionItem[];
- }): Promise<void> {
- if (!(await this.hasInputAskObject(workspaceId))) {
- return;
- }
-
- await this.executeAsSystem(workspaceId, async (inputAskRepository) => {
- const position = await this.recordPositionService.buildRecordPosition({
- value: 'first',
- objectMetadata: { isCustom: false, nameSingular: 'inputAsk' },
- workspaceId,
- });
+ match: InputAskToolCallKey | { workflowRunId: string };
+ }): Promise<boolean> {
+ return this.execute({
+ workspaceId,
+ whenObjectMissing: () => false,
+ run: async (inputAskRepository) => {
+ const result = await inputAskRepository.update(
+ { ...match, status: InputAskStatus.PENDING },
+ { status: InputAskStatus.CANCELED },
+ );
- try {
- await inputAskRepository.insert({
- name,
- status: InputAskStatus.PENDING,
- form: { questions },
- workflowRunId,
- stepId,
- threadId,
- toolCallId,
- position,
- });
- } catch (error) {
- // A retried recording of the same question wants the existing row.
- if (!isDuplicateEntry(error)) {
- throw error;
- }
- }
+ return (result.affected ?? 0) > 0;
+ },
});
}
- // An agent can ask several times in one conversation, so the answer is
- // matched to its question by tool call, never to whichever Ask is pending.
- // The run may already have ended and canceled it after taking the answer.
- async answerForToolCall({
+ async findPendingForThread({
workspaceId,
threadId,
- toolCallId,
- response,
}: {
workspaceId: string;
threadId: string;
- toolCallId: string | null;
- response: Record<string, unknown>;
- }): Promise<void> {
- if (
- !isDefined(toolCallId) ||
- !(await this.hasInputAskObject(workspaceId))
- ) {
- return;
- }
+ }): Promise<
+ Pick<InputAskWorkspaceEntity, 'id' | 'toolCallId' | 'workflowRunId'>[]
+ > {
+ return this.execute({
+ workspaceId,
+ whenObjectMissing: () => [],
+ run: (inputAskRepository) =>
+ inputAskRepository.find({
+ where: { threadId, status: InputAskStatus.PENDING },
+ select: { id: true, toolCallId: true, workflowRunId: true },
+ }),
+ });
+ }
- await this.executeAsSystem(workspaceId, async (inputAskRepository) => {
- await inputAskRepository.update(
- { threadId, toolCallId, status: Not(InputAskStatus.ANSWERED) },
- {
- status: InputAskStatus.ANSWERED,
- response,
- answeredAt: new Date().toISOString(),
- },
- );
+ async hasPendingForThread({
+ workspaceId,
+ threadId,
+ }: {
+ workspaceId: string;
+ threadId: string;
+ }): Promise<boolean> {
+ return this.execute({
+ workspaceId,
+ whenObjectMissing: () => false,
+ run: (inputAskRepository) =>
+ inputAskRepository.existsBy({
+ threadId,
+ status: InputAskStatus.PENDING,
+ }),
});
}
- // A run that ends before its answer arrives leaves the question unanswerable,
- // and an unanswerable question left PENDING sits in someone's list forever.
- // A form whose step completed was answered even if recording the answer
- // failed at submission, so it closes as answered from the step's result.
- async cancelPendingForWorkflowRun({
+ async findPendingForStep({
workspaceId,
workflowRunId,
- stepInfos,
+ stepId,
}: {
workspaceId: string;
workflowRunId: string;
- stepInfos: Record<string, WorkflowRunStepInfo>;
- }): Promise<void> {
- if (!(await this.hasInputAskObject(workspaceId))) {
- return;
- }
-
- await this.executeAsSystem(workspaceId, async (inputAskRepository) => {
- const pendingFormInputAsks = await inputAskRepository.find({
- where: {
- workflowRunId,
- status: InputAskStatus.PENDING,
- toolCallId: IsNull(),
- },
- select: { id: true, stepId: true },
- });
-
- for (const pendingFormInputAsk of pendingFormInputAsks) {
- const stepInfo = isDefined(pendingFormInputAsk.stepId)
- ? stepInfos[pendingFormInputAsk.stepId]
- : undefined;
-
- if (stepInfo?.status !== StepStatus.SUCCESS) {
- continue;
- }
-
- await inputAskRepository.update(
- { id: pendingFormInputAsk.id, status: InputAskStatus.PENDING },
- {
- status: InputAskStatus.ANSWERED,
- response: isPlainObject(stepInfo.result) ? stepInfo.result : null,
- answeredAt: new Date().toISOString(),
+ stepId: string;
+ }): Promise<Pick<InputAskWorkspaceEntity, 'id'> | null> {
+ return this.execute({
+ workspaceId,
+ whenObjectMissing: () => null,
+ run: (inputAskRepository) =>
+ inputAskRepository.findOne({
+ where: {
+ ...buildKeyWhere({ workflowRunId, stepId }),
+ status: InputAskStatus.PENDING,
},
- );
- }
+ select: { id: true },
+ }),
+ });
+ }
- await inputAskRepository.update(
- { workflowRunId, status: InputAskStatus.PENDING },
- { status: InputAskStatus.CANCELED },
- );
+ async findReadable({
+ workspaceId,
+ inputAskId,
+ }: {
+ workspaceId: string;
+ inputAskId: string;
+ }): Promise<Pick<
+ InputAskWorkspaceEntity,
+ | 'id'
+ | 'status'
+ | 'form'
+ | 'threadId'
+ | 'toolCallId'
+ | 'workflowRunId'
+ | 'stepId'
+ > | null> {
+ return this.execute({
+ workspaceId,
+ asCaller: true,
+ whenObjectMissing: () => null,
+ run: (inputAskRepository) =>
+ inputAskRepository.findOne({
+ where: { id: inputAskId },
+ select: {
+ id: true,
+ status: true,
+ form: true,
+ threadId: true,
+ toolCallId: true,
+ workflowRunId: true,
+ stepId: true,
+ },
+ }),
});
}
- // The object reaches existing workspaces through a workspace upgrade command,
- // which runs per workspace while this code is already serving — and an
- // interrupted upgrade leaves the rest without it indefinitely. Until a
- // workspace has the object, a form step behaves exactly as it did before.
private async hasInputAskObject(workspaceId: string): Promise<boolean> {
const { flatObjectMetadataMaps } =
await this.workspaceCacheService.getOrRecompute(workspaceId, [
@@ -289,15 +285,41 @@ export class InputAskWorkspaceService {
);
}
- private async executeAsSystem<TResult>(
- workspaceId: string,
- execute: (
+ // The object reaches existing workspaces through a workspace upgrade command,
+ // which runs per workspace while this code is already serving, and an
+ // interrupted upgrade leaves the rest without it indefinitely: every use
+ // says what it means for a workspace that does not have it yet.
+ private async execute<TResult>({
+ workspaceId,
+ asCaller = false,
+ whenObjectMissing,
+ run,
+ }: {
+ workspaceId: string;
+ // Read as the caller: an Ask they cannot read is one they cannot answer.
+ asCaller?: boolean;
+ whenObjectMissing: () => TResult;
+ run: (
inputAskRepository: WorkspaceRepository<InputAskWorkspaceEntity>,
- ) => Promise<TResult>,
- ): Promise<TResult> {
+ ) => Promise<TResult>;
+ }): Promise<TResult> {
+ if (!(await this.hasInputAskObject(workspaceId))) {
+ return whenObjectMissing();
+ }
+
+ if (asCaller) {
+ return this.workspaceOrmManager.executeInWorkspaceContext(async () =>
+ run(
+ this.workspaceOrmManager.getRepositoryWithContextPermissions<InputAskWorkspaceEntity>(
+ 'inputAsk',
+ ),
+ ),
+ );
+ }
+
return this.workspaceOrmManager.executeInWorkspaceContext(
async () =>
- execute(
+ run(
this.workspaceOrmManager.getRepository<InputAskWorkspaceEntity>(
'inputAsk',
{ shouldBypassPermissionChecks: true },
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-action-output.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-action-output.type.ts
index 7ac2b760639..33f0badc293 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-action-output.type.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-action-output.type.ts
@@ -1,8 +1,11 @@
+import { type WorkflowPendingAsk } from 'src/modules/workflow/workflow-executor/types/workflow-pending-ask.type';
+
export type WorkflowActionOutput = {
result?: object;
error?: string;
isUserError?: boolean;
pendingEvent?: boolean;
+ pendingAsks?: WorkflowPendingAsk[];
shouldEndWorkflowRun?: boolean;
shouldRemainRunning?: boolean;
shouldSkipStepExecution?: boolean;
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-pending-ask.type.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-pending-ask.type.ts
new file mode 100644
index 00000000000..951e6a34a1c
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/types/workflow-pending-ask.type.ts
@@ -0,0 +1,7 @@
+import { type PausingToolAsk } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/types/pausing-tool-ask.type';
+import { type InputAskToolCallKey } from 'src/modules/input-ask/workspace-services/input-ask.workspace-service';
+
+// What a step that waits on a person is waiting for. The run opens each as
+// an Ask when it parks the step, under the same lock as that transition.
+export type WorkflowPendingAsk = PausingToolAsk &
+ (InputAskToolCallKey | { threadId?: undefined; toolCallId?: undefined });
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts
index 716794d98ba..30483c0ae15 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts
@@ -1,7 +1,10 @@
import { Injectable, Logger } from '@nestjs/common';
-import { ASK_QUESTIONS_TOOL_NAME } from 'twenty-shared/ai';
-import { isDefined, resolveInput } from 'twenty-shared/utils';
+import {
+ ASK_QUESTIONS_TOOL_NAME,
+ PROPOSE_EMAIL_TOOL_NAME,
+} from 'twenty-shared/ai';
+import { isDefined, isNonEmptyArray, resolveInput } from 'twenty-shared/utils';
import { type WorkflowRunStepLog } from 'twenty-shared/workflow';
import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/interfaces/workflow-action.interface';
@@ -10,6 +13,7 @@ import { UsageOperationType } from 'src/engine/core-modules/usage/enums/usage-op
import { AgentAsyncExecutorService } from 'src/engine/metadata-modules/ai/ai-agent-execution/services/agent-async-executor.service';
import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';
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 { WORKFLOW_BASE_SYSTEM_PROMPT } from 'src/engine/metadata-modules/ai/ai-agent/constants/workflow-base-system-prompt.const';
import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
@@ -102,8 +106,6 @@ export class AiAgentWorkflowAction implements WorkflowAction {
(isDefined(resumedThreadId)
? this.workflowAgentConversationService.recordContinuation({
workspaceId,
- workflowRunId: runInfo.workflowRunId,
- stepId: currentStepId,
threadId: resumedThreadId,
agentId: agent?.id ?? null,
executionResult,
@@ -152,6 +154,7 @@ export class AiAgentWorkflowAction implements WorkflowAction {
[ASK_QUESTIONS_TOOL_NAME]: createAskQuestionsTool({
isWorkspaceSetupThread: false,
}),
+ [PROPOSE_EMAIL_TOOL_NAME]: createProposeEmailTool(),
}
: {},
actorContext: executionContext.isActingOnBehalfOfUser
@@ -191,13 +194,16 @@ export class AiAgentWorkflowAction implements WorkflowAction {
if (executionResult.isPaused === true) {
// The conversation is where the question is answered, so without it the
// run would wait for an answer nobody can give.
- if (recordedConversation?.isAwaitingAnswer !== true) {
+ if (!isNonEmptyArray(recordedConversation?.pendingAsks)) {
return {
error: 'Agent asked a question that could not be recorded.',
};
}
- return { pendingEvent: true };
+ return {
+ pendingEvent: true,
+ pendingAsks: recordedConversation.pendingAsks,
+ };
}
return {
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-ask-questions-prompt.constant.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-ask-questions-prompt.constant.ts
index b96bf6e4d94..31a4682349a 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-ask-questions-prompt.constant.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/constants/workflow-agent-ask-questions-prompt.constant.ts
@@ -1 +1 @@
-export const WORKFLOW_AGENT_ASK_QUESTIONS_PROMPT = `You run inside a workflow, with nobody watching as you work. When you need a decision or a fact that only a person can give, such as an approval or a choice with no safe default, call ask_questions: the workflow pauses until someone answers, then you continue with their answer. Ask everything you need in one call, and do not ask about anything you can find or decide yourself.`;
+export const WORKFLOW_AGENT_ASK_QUESTIONS_PROMPT = `You run inside a workflow, with nobody watching as you work. When you need a decision or a fact that only a person can give, such as an approval or a choice with no safe default, call ask_questions: the workflow pauses until someone answers, then you continue with their answer. Ask everything you need in one call, and do not ask about anything you can find or decide yourself. When the step should send an email that a person must review first, call propose_email instead of send_email: the workflow pauses until someone sends, saves or discards it, and you get the outcome.`;
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 557cb07d092..f968b310c40 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
@@ -20,22 +20,33 @@ import { finalizeDanglingToolParts } from 'src/engine/metadata-modules/ai/ai-age
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 { findPendingQuestionPart } from 'src/engine/metadata-modules/ai/ai-chat/utils/find-pending-question-part.util';
+import { PAUSING_TOOLS } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/constants/pausing-tools.constant';
+import { findAwaitingPausingToolParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/pausing-tools/utils/find-awaiting-pausing-tool-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 { hasWorkflowRunThreadFields } from 'src/engine/metadata-modules/ai/ai-history/utils/has-workflow-run-thread-fields.util';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
-import { InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-service';
+import {
+ WorkflowStepExecutorException,
+ WorkflowStepExecutorExceptionCode,
+} from 'src/modules/workflow/workflow-executor/exceptions/workflow-step-executor.exception';
+import { type WorkflowPendingAsk } from 'src/modules/workflow/workflow-executor/types/workflow-pending-ask.type';
import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
-type RecordedExecutionResult = {
+export type RecordedExecutionResult = {
steps?: Pick<NonNullable<AgentExecutionResult['steps']>[number], 'content'>[];
isPaused?: boolean;
};
+export type AnsweredToolPart = {
+ id: string;
+ messageId: string;
+ turnId: string | null;
+};
+
export type RecordedConversation = {
threadId: string;
- isAwaitingAnswer: boolean;
+ pendingAsks: WorkflowPendingAsk[];
};
// A conversation is recorded only for an execution of an agent step that asks
@@ -56,7 +67,6 @@ export class WorkflowAgentConversationWorkspaceService {
private readonly messagePartRepository: AgentHistoryRepository<AgentMessagePartEntity>,
private readonly workspaceCacheService: WorkspaceCacheService,
private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,
- private readonly inputAskWorkspaceService: InputAskWorkspaceService,
) {}
async recordExecution({
@@ -105,9 +115,6 @@ export class WorkflowAgentConversationWorkspaceService {
parts: [{ type: 'text', text: prompt }],
});
- // Linked to its step before its question is offered: an answer is matched
- // to the step through this link, and one arriving before it would find
- // no step waiting and close the question the step is about to wait on.
await this.workflowRunWorkspaceService.setStepThreadId({
stepId,
threadId,
@@ -115,49 +122,41 @@ export class WorkflowAgentConversationWorkspaceService {
workspaceId,
});
- const isAwaitingAnswer = await this.recordReply({
+ const pendingAsks = await this.recordReply({
workspaceId,
- workflowRunId,
- stepId,
threadId,
turnId,
agentId,
executionResult,
});
- return { threadId, isAwaitingAnswer };
+ return { threadId, pendingAsks };
}
// Continues a conversation whose question has been answered: the answer is
// already recorded as the last message, so only the agent's reply is added.
async recordContinuation({
workspaceId,
- workflowRunId,
- stepId,
threadId,
agentId,
executionResult,
}: {
workspaceId: string;
- workflowRunId: string;
- stepId: string;
threadId: string;
agentId: string | null;
executionResult: RecordedExecutionResult;
}): Promise<RecordedConversation> {
const turnId = await this.insertTurn({ workspaceId, threadId, agentId });
- const isAwaitingAnswer = await this.recordReply({
+ const pendingAsks = await this.recordReply({
workspaceId,
- workflowRunId,
- stepId,
threadId,
turnId,
agentId,
executionResult,
});
- return { threadId, isAwaitingAnswer };
+ return { threadId, pendingAsks };
}
async loadModelMessages({
@@ -187,30 +186,86 @@ export class WorkflowAgentConversationWorkspaceService {
return convertToModelMessages(uiMessages);
}
+ // Records a person's answer where the agent will read it on resuming: the
+ // call's result, then the answer as the person's message in the call's turn.
+ async recordAnswer({
+ workspaceId,
+ threadId,
+ toolPart,
+ toolResult,
+ answerText,
+ senderUserWorkspaceId,
+ }: {
+ workspaceId: string;
+ threadId: string;
+ toolPart: AnsweredToolPart;
+ toolResult: Record<string, unknown>;
+ answerText: string;
+ senderUserWorkspaceId: string;
+ }): Promise<{ hasAwaitingToolCalls: boolean }> {
+ if (!isDefined(toolPart.turnId)) {
+ throw new WorkflowStepExecutorException(
+ `Tool call message ${toolPart.messageId} has no turn in conversation ${threadId}`,
+ WorkflowStepExecutorExceptionCode.INTERNAL_ERROR,
+ );
+ }
+
+ await this.messagePartRepository.update(
+ workspaceId,
+ { id: toolPart.id },
+ { toolOutput: toolResult },
+ );
+
+ await this.insertMessage({
+ workspaceId,
+ threadId,
+ turnId: toolPart.turnId,
+ role: AgentMessageRole.USER,
+ agentId: null,
+ senderUserWorkspaceId,
+ parts: [{ type: 'text', text: answerText }],
+ });
+
+ // Read after this answer is written, so of answers recorded concurrently
+ // the last to write always sees the others.
+ const messageParts = await this.messagePartRepository.find(workspaceId, {
+ where: { messageId: toolPart.messageId },
+ select: ['toolName', 'toolOutput'],
+ });
+
+ return {
+ hasAwaitingToolCalls: messageParts.some(
+ (messagePart) =>
+ isDefined(messagePart.toolName) &&
+ PAUSING_TOOLS.get(messagePart.toolName)?.isAwaitingOutput(
+ messagePart.toolOutput,
+ ) === true,
+ ),
+ };
+ }
+
+ // The run opens the Ask when it parks the step, under the lock that
+ // transition takes; the conversation only says what it would be.
private async recordReply({
workspaceId,
- workflowRunId,
- stepId,
threadId,
turnId,
agentId,
executionResult,
}: {
workspaceId: string;
- workflowRunId: string;
- stepId: string;
threadId: string;
turnId: string;
agentId: string | null;
executionResult: RecordedExecutionResult;
- }): Promise<boolean> {
+ }): Promise<WorkflowPendingAsk[]> {
const replyParts = mapAiStepsToUiMessageParts(executionResult.steps ?? []);
if (replyParts.length === 0) {
- return false;
+ return [];
}
- const messageId = await this.insertMessage({
+ await this.insertMessage({
workspaceId,
threadId,
turnId,
@@ -220,38 +275,25 @@ export class WorkflowAgentConversationWorkspaceService {
parts: replyParts,
});
- const pendingQuestionPart = executionResult.isPaused
- ? findPendingQuestionPart(replyParts)
- : undefined;
-
- if (!isDefined(pendingQuestionPart)) {
- return false;
+ if (executionResult.isPaused !== true) {
+ return [];
}
- const questions = pendingQuestionPart.output?.result?.questions ?? [];
+ const pendingAsks: WorkflowPendingAsk[] = [];
- // Opened before the marker: a question pending without its Ask is one
- // nobody can find, while an Ask whose marker failed ends canceled with the
- // run that step then fails.
- await this.inputAskWorkspaceService.openForAgentQuestion({
- workspaceId,
- workflowRunId,
- stepId,
- threadId,
- toolCallId: pendingQuestionPart.toolCallId,
- name: questions[0]?.question ?? 'Question',
- questions,
- });
+ for (const { toolCallId, ask } of findAwaitingPausingToolParts(
+ replyParts,
+ )) {
+ // One call nobody can answer would keep the step waiting forever on
+ // the others, so the step fails as if none had been recorded.
+ if (!isDefined(ask)) {
+ return [];
+ }
- // The same marker a chat question sets, so the answer flow can claim the
- // question exactly once.
- await this.threadRepository.update(
- workspaceId,
- { id: threadId },
- { pendingQuestionMessageId: messageId },
- );
+ pendingAsks.push({ ...ask, threadId, toolCallId });
+ }
- return true;
+ return pendingAsks;
}
private async insertTurn({
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/workflow-agent-conversation.module.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/workflow-agent-conversation.module.ts
index e7cfc6e18bd..1f69b334fe7 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/workflow-agent-conversation.module.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/workflow-agent-conversation.module.ts
@@ -2,17 +2,11 @@ import { Module } from '@nestjs/common';
import { AgentHistoryModule } from 'src/engine/metadata-modules/ai/ai-history/ai-history.module';
import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';
-import { InputAskModule } from 'src/modules/input-ask/input-ask.module';
import { WorkflowAgentConversationWorkspaceService } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service';
import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.module';
@Module({
- imports: [
- AgentHistoryModule,
- WorkspaceCacheModule,
- WorkflowRunModule,
- InputAskModule,
- ],
+ imports: [AgentHistoryModule, WorkspaceCacheModule, WorkflowRunModule],
providers: [WorkflowAgentConversationWorkspaceService],
exports: [WorkflowAgentConversationWorkspaceService],
})
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/form/form-action.module.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/form/form-action.module.ts
index c538dceb41c..1600d235b9c 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/form/form-action.module.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/form/form-action.module.ts
@@ -1,10 +1,8 @@
import { Module } from '@nestjs/common';
-import { InputAskModule } from 'src/modules/input-ask/input-ask.module';
import { FormWorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/form/form.workflow-action';
@Module({
- imports: [InputAskModule],
providers: [FormWorkflowAction],
exports: [FormWorkflowAction],
})
diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/form/form.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/form/form.workflow-action.ts
index 2a79339874b..ca94c076509 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/form/form.workflow-action.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/form/form.workflow-action.ts
@@ -2,8 +2,6 @@ import { Injectable } from '@nestjs/common';
import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/interfaces/workflow-action.interface';
-import { InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-service';
-
import {
WorkflowStepExecutorException,
WorkflowStepExecutorExceptionCode,
@@ -15,14 +13,9 @@ import { isWorkflowFormAction } from 'src/modules/workflow/workflow-executor/wor
@Injectable()
export class FormWorkflowAction implements WorkflowAction {
- constructor(
- private readonly inputAskWorkspaceService: InputAskWorkspaceService,
- ) {}
-
async execute({
currentStepId,
steps,
- runInfo,
}: WorkflowActionInput): Promise<WorkflowActionOutput> {
const step = findStepOrThrow({
stepId: currentStepId,
@@ -36,19 +29,14 @@ export class FormWorkflowAction implements WorkflowAction {
);
}
- // Written before the step reports itself pending: a run parked without its
- // Ask is a question nobody can find, while an early Ask is only briefly
- // unanswerable and is canceled if the run dies before parking.
- await this.inputAskWorkspaceService.openForFormStep({
- workspaceId: runInfo.workspaceId,
- workflowRunId: runInfo.workflowRunId,
- stepId: step.id,
- stepName: step.name,
- fields: step.settings.input,
- });
-
return {
pendingEvent: true,
+ pendingAsks: [
+ {
+ name: step.name,
+ form: { kind: 'formFields', fields: step.settings.input },
+ },
+ ],
};
}
}
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..88b559af1dd 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
@@ -502,6 +502,7 @@ export class WorkflowExecutorWorkspaceService {
await this.workflowRunWorkspaceService.updateWorkflowRunStepInfo({
stepId,
stepInfo,
+ pendingAsks: isPendingEvent ? actionOutput.pendingAsks : undefined,
workflowRunId,
workspaceId,
});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/utils/__tests__/can-workflow-run-have-asks.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/utils/__tests__/can-workflow-run-have-asks.util.spec.ts
new file mode 100644
index 00000000000..e3da8efb7d7
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/utils/__tests__/can-workflow-run-have-asks.util.spec.ts
@@ -0,0 +1,54 @@
+import { StepStatus, WorkflowActionType } from 'twenty-shared/workflow';
+
+import { type WorkflowRunState } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
+import { canWorkflowRunHaveAsks } from 'src/modules/workflow/workflow-runner/utils/can-workflow-run-have-asks.util';
+
+const buildState = ({
+ stepTypes,
+ stepInfos = {},
+}: {
+ stepTypes: WorkflowActionType[];
+ stepInfos?: WorkflowRunState['stepInfos'];
+}) =>
+ ({
+ flow: {
+ trigger: { type: 'MANUAL' },
+ steps: stepTypes.map((type, index) => ({ id: `step-${index}`, type })),
+ },
+ stepInfos,
+ }) as unknown as WorkflowRunState;
+
+describe('canWorkflowRunHaveAsks', () => {
+ it('knows a run with a form step can', () => {
+ expect(
+ canWorkflowRunHaveAsks(
+ buildState({ stepTypes: [WorkflowActionType.FORM] }),
+ ),
+ ).toBe(true);
+ });
+
+ it('knows a run whose agent step started a conversation can', () => {
+ expect(
+ canWorkflowRunHaveAsks(
+ buildState({
+ stepTypes: [WorkflowActionType.AI_AGENT],
+ stepInfos: {
+ 'step-0': { status: StepStatus.SUCCESS, threadId: 'thread-id' },
+ },
+ }),
+ ),
+ ).toBe(true);
+ });
+
+ it('knows a run with neither cannot', () => {
+ expect(
+ canWorkflowRunHaveAsks(
+ buildState({
+ stepTypes: [WorkflowActionType.CODE, WorkflowActionType.AI_AGENT],
+ stepInfos: { 'step-0': { status: StepStatus.SUCCESS } },
+ }),
+ ),
+ ).toBe(false);
+ expect(canWorkflowRunHaveAsks(null)).toBe(false);
+ });
+});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/utils/can-workflow-run-have-asks.util.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/utils/can-workflow-run-have-asks.util.ts
new file mode 100644
index 00000000000..4aabf961a5e
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/utils/can-workflow-run-have-asks.util.ts
@@ -0,0 +1,17 @@
+import { isDefined } from 'twenty-shared/utils';
+import { WorkflowActionType } from 'twenty-shared/workflow';
+
+import { type WorkflowRunState } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
+
+// Only a form step or an agent step's conversation ever opens an Ask, and the
+// run state already says whether it has either, so most runs end without
+// touching the Asks at all.
+export const canWorkflowRunHaveAsks = (
+ state: WorkflowRunState | null | undefined,
+): boolean =>
+ (state?.flow?.steps ?? []).some(
+ (step) => step.type === WorkflowActionType.FORM,
+ ) ||
+ Object.values(state?.stepInfos ?? {}).some((stepInfo) =>
+ isDefined(stepInfo?.threadId),
+ );
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/utils/get-run-initiator-workspace-member-id.util.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/utils/get-run-initiator-workspace-member-id.util.ts
new file mode 100644
index 00000000000..8e0e2bfdb5e
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/utils/get-run-initiator-workspace-member-id.util.ts
@@ -0,0 +1,12 @@
+import { FieldActorSource } from 'twenty-shared/types';
+
+import { type WorkflowRunWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
+
+// Whoever started a run is who it waits on unless someone reassigns its Ask;
+// a run started by a trigger has nobody to default to.
+export const getRunInitiatorWorkspaceMemberId = (
+ workflowRun: Pick<WorkflowRunWorkspaceEntity, 'createdBy'>,
+): string | null =>
+ workflowRun.createdBy?.source === FieldActorSource.MANUAL
+ ? (workflowRun.createdBy.workspaceMemberId ?? null)
+ : null;
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.input-ask.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.input-ask.spec.ts
new file mode 100644
index 00000000000..23fc019a3aa
--- /dev/null
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.input-ask.spec.ts
@@ -0,0 +1,366 @@
+import { FieldActorSource } from 'twenty-shared/types';
+import { StepStatus } from 'twenty-shared/workflow';
+
+import { WorkflowRunStatus } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
+import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
+
+const QUESTIONS_FORM = {
+ kind: 'questions' as const,
+ questions: [
+ {
+ header: 'Plan',
+ question: 'Which plan?',
+ options: [{ label: 'Pro' }, { label: 'Team' }],
+ },
+ ],
+};
+
+describe('WorkflowRunWorkspaceService Ask lifecycle', () => {
+ const buildService = ({
+ status = WorkflowRunStatus.RUNNING,
+ stepInfo = {
+ status: StepStatus.PENDING,
+ threadId: 'thread-id',
+ } as Record<string, unknown>,
+ hasAnswered = true,
+ } = {}) => {
+ const inputAskWorkspaceService = {
+ open: jest.fn().mockResolvedValue(undefined),
+ answer: jest.fn().mockResolvedValue(hasAnswered),
+ cancel: jest.fn().mockResolvedValue(true),
+ };
+ const service = new WorkflowRunWorkspaceService(
+ {} as never,
+ {} as never,
+ { incrementCounterForEvent: jest.fn() } as never,
+ inputAskWorkspaceService as never,
+ {} as never,
+ );
+
+ // The run lock serializes these methods with every other step write.
+ Object.assign(service, {
+ cacheLockService: {
+ withLock: jest.fn().mockImplementation((work) => work()),
+ },
+ });
+
+ const workflowRun = {
+ id: 'workflow-run-id',
+ status,
+ createdBy: {
+ source: FieldActorSource.MANUAL,
+ workspaceMemberId: 'initiator-member-id',
+ },
+ state: { flow: { steps: [] }, stepInfos: { 'step-id': stepInfo } },
+ };
+
+ jest
+ .spyOn(service, 'getWorkflowRunOrFail')
+ .mockResolvedValue(workflowRun as never);
+
+ const updateWorkflowRun = jest
+ .spyOn(service, 'updateWorkflowRun')
+ .mockResolvedValue(undefined);
+
+ return { service, inputAskWorkspaceService, updateWorkflowRun };
+ };
+
+ describe('resolveStepAwaitingToolCall', () => {
+ const resolveArguments = {
+ threadId: 'thread-id',
+ toolCallId: 'tool-call-id',
+ response: { answers: [] },
+ workflowRunId: 'workflow-run-id',
+ workspaceId: 'workspace-id',
+ };
+
+ it('answers the Ask and leaves the step PENDING for the resume job to claim', async () => {
+ const { service, inputAskWorkspaceService, updateWorkflowRun } =
+ buildService();
+
+ expect(
+ await service.resolveStepAwaitingToolCall(resolveArguments),
+ ).toEqual({ status: 'RESOLVED', stepId: 'step-id' });
+ expect(inputAskWorkspaceService.answer).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ key: { threadId: 'thread-id', toolCallId: 'tool-call-id' },
+ response: { answers: [] },
+ });
+ expect(updateWorkflowRun).not.toHaveBeenCalled();
+ });
+
+ it('moves nothing when another answer already claimed the Ask', async () => {
+ const { service, updateWorkflowRun } = buildService({
+ hasAnswered: false,
+ });
+
+ expect(
+ await service.resolveStepAwaitingToolCall(resolveArguments),
+ ).toEqual({ status: 'NOT_AWAITING' });
+ expect(updateWorkflowRun).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['the run is stopping', { status: WorkflowRunStatus.STOPPING }],
+ [
+ 'the step already moved on',
+ { stepInfo: { status: StepStatus.SUCCESS, threadId: 'thread-id' } },
+ ],
+ [
+ 'a retry replaced the conversation',
+ { stepInfo: { status: StepStatus.PENDING, threadId: 'other-thread' } },
+ ],
+ [
+ 'the step waits on a retry',
+ {
+ stepInfo: {
+ status: StepStatus.PENDING,
+ threadId: 'thread-id',
+ error: 'boom',
+ },
+ },
+ ],
+ ])('answers nothing when %s', async (_description, overrides) => {
+ const { service, inputAskWorkspaceService, updateWorkflowRun } =
+ buildService(overrides);
+
+ expect(
+ await service.resolveStepAwaitingToolCall(resolveArguments),
+ ).toEqual({ status: 'NOT_AWAITING' });
+ expect(inputAskWorkspaceService.answer).not.toHaveBeenCalled();
+ expect(updateWorkflowRun).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('updateWorkflowRunStepInfo', () => {
+ it('opens the Ask of a step it parks, assigned to whoever started the run', async () => {
+ const { service, inputAskWorkspaceService, updateWorkflowRun } =
+ buildService({ stepInfo: { status: StepStatus.RUNNING } });
+
+ await service.updateWorkflowRunStepInfo({
+ stepId: 'step-id',
+ stepInfo: { status: StepStatus.PENDING },
+ pendingAsks: [
+ {
+ name: 'Which plan?',
+ form: QUESTIONS_FORM,
+ threadId: 'thread-id',
+ toolCallId: 'tool-call-id',
+ },
+ ],
+ workflowRunId: 'workflow-run-id',
+ workspaceId: 'workspace-id',
+ });
+
+ expect(inputAskWorkspaceService.open).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ inputAsk: {
+ name: 'Which plan?',
+ form: QUESTIONS_FORM,
+ threadId: 'thread-id',
+ toolCallId: 'tool-call-id',
+ workflowRunId: 'workflow-run-id',
+ stepId: 'step-id',
+ assigneeId: 'initiator-member-id',
+ },
+ });
+ expect(
+ inputAskWorkspaceService.open.mock.invocationCallOrder[0],
+ ).toBeLessThan(updateWorkflowRun.mock.invocationCallOrder[0]);
+ });
+
+ it('does not park the step when its Ask cannot be opened', async () => {
+ const { service, inputAskWorkspaceService, updateWorkflowRun } =
+ buildService({ stepInfo: { status: StepStatus.RUNNING } });
+
+ inputAskWorkspaceService.open.mockRejectedValue(new Error('db down'));
+
+ await expect(
+ service.updateWorkflowRunStepInfo({
+ stepId: 'step-id',
+ stepInfo: { status: StepStatus.PENDING },
+ pendingAsks: [
+ {
+ name: 'Approve',
+ form: { kind: 'formFields', fields: [] },
+ },
+ ],
+ workflowRunId: 'workflow-run-id',
+ workspaceId: 'workspace-id',
+ }),
+ ).rejects.toThrow('db down');
+ expect(updateWorkflowRun).not.toHaveBeenCalled();
+ });
+
+ it('opens no Ask for a step that does not wait on a person', async () => {
+ const { service, inputAskWorkspaceService } = buildService({
+ stepInfo: { status: StepStatus.RUNNING },
+ });
+
+ await service.updateWorkflowRunStepInfo({
+ stepId: 'step-id',
+ stepInfo: { status: StepStatus.SUCCESS, result: {} },
+ workflowRunId: 'workflow-run-id',
+ workspaceId: 'workspace-id',
+ });
+
+ expect(inputAskWorkspaceService.open).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('updateStepInfoIfPending', () => {
+ it('answers the form Ask in the write that accepts the submission', async () => {
+ const { service, inputAskWorkspaceService, updateWorkflowRun } =
+ buildService({ stepInfo: { status: StepStatus.PENDING } });
+
+ expect(
+ await service.updateStepInfoIfPending({
+ stepId: 'step-id',
+ stepInfo: { status: StepStatus.SUCCESS, result: { name: 'Tim' } },
+ inputAskResponse: { name: 'Tim' },
+ workflowRunId: 'workflow-run-id',
+ workspaceId: 'workspace-id',
+ }),
+ ).toBe(true);
+ expect(inputAskWorkspaceService.answer).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ key: { workflowRunId: 'workflow-run-id', stepId: 'step-id' },
+ response: { name: 'Tim' },
+ });
+ expect(updateWorkflowRun).toHaveBeenCalled();
+ });
+
+ it('refuses a submission when another one already answered the Ask', async () => {
+ const { service, updateWorkflowRun } = buildService({
+ stepInfo: { status: StepStatus.PENDING },
+ hasAnswered: false,
+ });
+
+ expect(
+ await service.updateStepInfoIfPending({
+ stepId: 'step-id',
+ stepInfo: { status: StepStatus.SUCCESS, result: { name: 'Tim' } },
+ inputAskResponse: { name: 'Tim' },
+ workflowRunId: 'workflow-run-id',
+ workspaceId: 'workspace-id',
+ }),
+ ).toBe(false);
+ expect(updateWorkflowRun).not.toHaveBeenCalled();
+ });
+
+ it('answers nothing for a refused submission', async () => {
+ const { service, inputAskWorkspaceService } = buildService({
+ stepInfo: { status: StepStatus.SUCCESS },
+ });
+
+ expect(
+ await service.updateStepInfoIfPending({
+ stepId: 'step-id',
+ stepInfo: { status: StepStatus.SUCCESS },
+ inputAskResponse: { name: 'Tim' },
+ workflowRunId: 'workflow-run-id',
+ workspaceId: 'workspace-id',
+ }),
+ ).toBe(false);
+ expect(inputAskWorkspaceService.answer).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('updateStepInfoIfPending in a conversation', () => {
+ const claimInConversation = (service: WorkflowRunWorkspaceService) =>
+ service.updateStepInfoIfPending({
+ stepId: 'step-id',
+ stepInfo: { status: StepStatus.RUNNING },
+ expectedThreadId: 'thread-id',
+ workflowRunId: 'workflow-run-id',
+ workspaceId: 'workspace-id',
+ });
+
+ it('claims a PENDING step still holding the expected conversation', async () => {
+ const { service, updateWorkflowRun } = buildService();
+
+ expect(await claimInConversation(service)).toBe(true);
+ expect(updateWorkflowRun).toHaveBeenCalledWith(
+ expect.objectContaining({
+ partialUpdate: {
+ state: expect.objectContaining({
+ stepInfos: {
+ 'step-id': {
+ status: StepStatus.RUNNING,
+ threadId: 'thread-id',
+ },
+ },
+ }),
+ },
+ }),
+ );
+ });
+
+ it.each([
+ ['the run is no longer running', { status: WorkflowRunStatus.STOPPED }],
+ [
+ 'the step already resumed',
+ { stepInfo: { status: StepStatus.RUNNING, threadId: 'thread-id' } },
+ ],
+ [
+ 'the step waits on something other than a question',
+ { stepInfo: { status: StepStatus.PENDING } },
+ ],
+ [
+ 'the step holds another conversation',
+ { stepInfo: { status: StepStatus.PENDING, threadId: 'other-thread' } },
+ ],
+ ])('claims nothing when %s', async (_description, overrides) => {
+ const { service, updateWorkflowRun } = buildService(overrides);
+
+ expect(await claimInConversation(service)).toBe(false);
+ expect(updateWorkflowRun).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('endWorkflowRun', () => {
+ it('cancels what the run leaves pending', async () => {
+ const { service, inputAskWorkspaceService } = buildService();
+
+ await service.endWorkflowRun({
+ workflowRunId: 'workflow-run-id',
+ workspaceId: 'workspace-id',
+ status: WorkflowRunStatus.STOPPED,
+ });
+
+ expect(inputAskWorkspaceService.cancel).toHaveBeenCalledWith({
+ workspaceId: 'workspace-id',
+ match: { workflowRunId: 'workflow-run-id' },
+ });
+ });
+
+ it('still ends the run when its Asks cannot be canceled', async () => {
+ const { service, inputAskWorkspaceService, updateWorkflowRun } =
+ buildService();
+
+ inputAskWorkspaceService.cancel.mockRejectedValue(new Error('db down'));
+
+ await service.endWorkflowRun({
+ workflowRunId: 'workflow-run-id',
+ workspaceId: 'workspace-id',
+ status: WorkflowRunStatus.STOPPED,
+ });
+
+ expect(updateWorkflowRun).toHaveBeenCalled();
+ });
+
+ it('leaves the Asks alone for a run that could not open any', async () => {
+ const { service, inputAskWorkspaceService } = buildService({
+ stepInfo: { status: StepStatus.SUCCESS },
+ });
+
+ await service.endWorkflowRun({
+ workflowRunId: 'workflow-run-id',
+ workspaceId: 'workspace-id',
+ status: WorkflowRunStatus.COMPLETED,
+ });
+
+ expect(inputAskWorkspaceService.cancel).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.spec.ts
deleted file mode 100644
index 6c17e683b46..00000000000
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/__tests__/workflow-run.workspace-service.spec.ts
+++ /dev/null
@@ -1,266 +0,0 @@
-import { ASK_QUESTIONS_TOOL_NAME } from 'twenty-shared/ai';
-import { StepStatus, type WorkflowRunStepInfos } from 'twenty-shared/workflow';
-
-import { type AgentMessagePartEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message-part.entity';
-import { type AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';
-import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
-import { type MetricsService } from 'src/engine/core-modules/metrics/metrics.service';
-import { type RecordPositionService } from 'src/engine/core-modules/record-position/services/record-position.service';
-import { type WorkflowRunRecordShareService } from 'src/engine/core-modules/workflow/services/workflow-run-record-share.service';
-import { type WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
-import { type InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-service';
-import {
- WorkflowRunStatus,
- type WorkflowRunWorkspaceEntity,
-} from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
-import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
-
-const WORKSPACE_ID = 'workspace-id';
-const WORKFLOW_RUN_ID = 'workflow-run-id';
-const AGENT_STEP_ID = 'agent-step-id';
-const THREAD_ID = 'thread-id';
-
-describe('WorkflowRunWorkspaceService', () => {
- const threadRepository = { find: jest.fn(), update: jest.fn() };
- const messagePartRepository = { find: jest.fn(), update: jest.fn() };
-
- const service = Object.assign(
- new WorkflowRunWorkspaceService(
- {} as WorkspaceOrmManager,
- {} as RecordPositionService,
- {
- incrementCounterForEvent: jest.fn(),
- } as unknown as MetricsService,
- {} as InputAskWorkspaceService,
- {} as WorkflowRunRecordShareService,
- threadRepository as unknown as AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,
- messagePartRepository as unknown as AgentHistoryRepository<AgentMessagePartEntity>,
- ),
- {
- cacheLockService: {
- withLock: (callback: () => Promise<unknown>) => callback(),
- },
- },
- );
-
- const getWorkflowRunOrFail = jest.spyOn(service, 'getWorkflowRunOrFail');
- const updateWorkflowRun = jest.spyOn(service, 'updateWorkflowRun');
-
- const mockWorkflowRun = ({
- status = WorkflowRunStatus.RUNNING,
- stepInfos,
- }: {
- status?: WorkflowRunStatus;
- stepInfos: WorkflowRunStepInfos;
- }) =>
- getWorkflowRunOrFail.mockResolvedValue({
- id: WORKFLOW_RUN_ID,
- status,
- state: { stepInfos },
- } as unknown as WorkflowRunWorkspaceEntity);
-
- const findStepAwaitingAnswer = () =>
- service.findStepAwaitingAnswer({
- threadId: THREAD_ID,
- workflowRunId: WORKFLOW_RUN_ID,
- workspaceId: WORKSPACE_ID,
- });
-
- beforeEach(() => {
- jest.clearAllMocks();
- updateWorkflowRun.mockResolvedValue(undefined);
- });
-
- describe('findStepAwaitingAnswer', () => {
- it('finds the PENDING step holding the conversation and leaves it PENDING', async () => {
- mockWorkflowRun({
- stepInfos: {
- [AGENT_STEP_ID]: { status: StepStatus.PENDING, threadId: THREAD_ID },
- },
- });
-
- expect(await findStepAwaitingAnswer()).toEqual({
- status: 'AWAITING_ANSWER',
- stepId: AGENT_STEP_ID,
- });
- expect(updateWorkflowRun).not.toHaveBeenCalled();
- });
-
- it('asks to wait out a step that has asked but is not parked yet', async () => {
- mockWorkflowRun({
- stepInfos: {
- [AGENT_STEP_ID]: { status: StepStatus.RUNNING, threadId: THREAD_ID },
- },
- });
-
- expect(await findStepAwaitingAnswer()).toEqual({
- status: 'NOT_YET_AWAITING',
- });
- });
-
- it.each([
- [
- 'the run is no longer running',
- WorkflowRunStatus.STOPPED,
- { status: StepStatus.PENDING, threadId: THREAD_ID },
- ],
- [
- 'the step moved on',
- WorkflowRunStatus.RUNNING,
- { status: StepStatus.SUCCESS, threadId: THREAD_ID },
- ],
- [
- 'a retry replaced the conversation',
- WorkflowRunStatus.RUNNING,
- { status: StepStatus.PENDING, error: 'failed' },
- ],
- ])('reports no longer awaiting when %s', async (_, status, stepInfo) => {
- mockWorkflowRun({ status, stepInfos: { [AGENT_STEP_ID]: stepInfo } });
-
- expect(await findStepAwaitingAnswer()).toEqual({
- status: 'NO_LONGER_AWAITING',
- });
- expect(updateWorkflowRun).not.toHaveBeenCalled();
- });
- });
-
- describe('updateStepInfoIfPending', () => {
- const claimInConversation = () =>
- service.updateStepInfoIfPending({
- stepId: AGENT_STEP_ID,
- stepInfo: { status: StepStatus.RUNNING },
- expectedThreadId: THREAD_ID,
- workflowRunId: WORKFLOW_RUN_ID,
- workspaceId: WORKSPACE_ID,
- });
-
- it('claims a PENDING step still holding the expected conversation', async () => {
- mockWorkflowRun({
- stepInfos: {
- [AGENT_STEP_ID]: { status: StepStatus.PENDING, threadId: THREAD_ID },
- },
- });
-
- expect(await claimInConversation()).toBe(true);
- expect(updateWorkflowRun).toHaveBeenCalledWith({
- workflowRunId: WORKFLOW_RUN_ID,
- workspaceId: WORKSPACE_ID,
- partialUpdate: {
- state: {
- stepInfos: {
- [AGENT_STEP_ID]: {
- status: StepStatus.RUNNING,
- threadId: THREAD_ID,
- },
- },
- },
- },
- });
- });
-
- it.each([
- [
- 'the run is no longer running',
- WorkflowRunStatus.STOPPED,
- { status: StepStatus.PENDING, threadId: THREAD_ID },
- ],
- [
- 'the step already resumed',
- WorkflowRunStatus.RUNNING,
- { status: StepStatus.RUNNING, threadId: THREAD_ID },
- ],
- [
- 'the step waits on something other than a question',
- WorkflowRunStatus.RUNNING,
- { status: StepStatus.PENDING },
- ],
- [
- 'the step holds another conversation',
- WorkflowRunStatus.RUNNING,
- { status: StepStatus.PENDING, threadId: 'other-thread-id' },
- ],
- ])('claims nothing when %s', async (_, status, stepInfo) => {
- mockWorkflowRun({ status, stepInfos: { [AGENT_STEP_ID]: stepInfo } });
-
- expect(await claimInConversation()).toBe(false);
- expect(updateWorkflowRun).not.toHaveBeenCalled();
- });
- });
-
- describe('endWorkflowRun', () => {
- it('closes the question a conversation of the run still offers', async () => {
- mockWorkflowRun({
- stepInfos: {
- [AGENT_STEP_ID]: { status: StepStatus.PENDING, threadId: THREAD_ID },
- other: { status: StepStatus.SUCCESS },
- },
- });
- threadRepository.find.mockResolvedValue([
- { id: THREAD_ID, pendingQuestionMessageId: 'question-message-id' },
- ]);
- threadRepository.update.mockResolvedValue({ affected: 1 });
- messagePartRepository.find.mockResolvedValue([
- {
- id: 'part-id',
- toolName: ASK_QUESTIONS_TOOL_NAME,
- toolOutput: { result: { questions: [], status: 'pending' } },
- },
- ]);
-
- await service.endWorkflowRun({
- workflowRunId: WORKFLOW_RUN_ID,
- workspaceId: WORKSPACE_ID,
- status: WorkflowRunStatus.STOPPED,
- });
-
- expect(threadRepository.update).toHaveBeenCalledWith(
- WORKSPACE_ID,
- { id: THREAD_ID, pendingQuestionMessageId: 'question-message-id' },
- { pendingQuestionMessageId: null },
- );
- expect(messagePartRepository.update).toHaveBeenCalledWith(
- WORKSPACE_ID,
- { id: 'part-id' },
- { toolOutput: { result: { questions: [], status: 'skipped' } } },
- );
- });
-
- it('leaves a question an answer has just claimed to that answer', async () => {
- mockWorkflowRun({
- stepInfos: {
- [AGENT_STEP_ID]: { status: StepStatus.PENDING, threadId: THREAD_ID },
- },
- });
- threadRepository.find.mockResolvedValue([
- { id: THREAD_ID, pendingQuestionMessageId: 'question-message-id' },
- ]);
- threadRepository.update.mockResolvedValue({ affected: 0 });
-
- await service.endWorkflowRun({
- workflowRunId: WORKFLOW_RUN_ID,
- workspaceId: WORKSPACE_ID,
- status: WorkflowRunStatus.STOPPED,
- });
-
- expect(messagePartRepository.update).not.toHaveBeenCalled();
- });
-
- it('still ends the run when its questions cannot be closed', async () => {
- mockWorkflowRun({
- stepInfos: {
- [AGENT_STEP_ID]: { status: StepStatus.PENDING, threadId: THREAD_ID },
- },
- });
- threadRepository.find.mockRejectedValue(new Error('storage down'));
-
- await expect(
- service.endWorkflowRun({
- workflowRunId: WORKFLOW_RUN_ID,
- workspaceId: WORKSPACE_ID,
- status: WorkflowRunStatus.STOPPED,
- }),
- ).resolves.toBeUndefined();
- expect(updateWorkflowRun).toHaveBeenCalledTimes(1);
- });
- });
-});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.module.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.module.ts
index 63940b18599..94daa817e8f 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.module.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.module.ts
@@ -1,7 +1,6 @@
import { Module } from '@nestjs/common';
import { WorkspaceIteratorModule } from 'src/database/commands/command-runners/workspace-iterator.module';
-import { AgentHistoryModule } from 'src/engine/metadata-modules/ai/ai-history/ai-history.module';
import { CacheLockModule } from 'src/engine/core-modules/cache-lock/cache-lock.module';
import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';
import { MetricsModule } from 'src/engine/core-modules/metrics/metrics.module';
@@ -15,7 +14,6 @@ import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runne
@Module({
imports: [
- AgentHistoryModule,
WorkflowCommonModule,
RecordPositionModule,
CacheLockModule,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts
index 9b284963bcf..163163a4be7 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts
@@ -1,13 +1,8 @@
import { Injectable, Logger } from '@nestjs/common';
-import {
- ASK_QUESTIONS_TOOL_NAME,
- type AskQuestionsToolResult,
-} from 'twenty-shared/ai';
import { type ActorMetadata } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { StepStatus, type WorkflowRunStepInfo } from 'twenty-shared/workflow';
-import { In, IsNull, Not } from 'typeorm';
import { v4 } from 'uuid';
import { WithLock } from 'src/engine/core-modules/cache-lock/with-lock.decorator';
@@ -15,10 +10,6 @@ import { MetricsService } from 'src/engine/core-modules/metrics/metrics.service'
import { MetricsKeys } from 'src/engine/core-modules/metrics/types/metrics-keys.type';
import { RecordPositionService } from 'src/engine/core-modules/record-position/services/record-position.service';
import { WorkflowRunRecordShareService } from 'src/engine/core-modules/workflow/services/workflow-run-record-share.service';
-import { type AgentMessagePartEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message-part.entity';
-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 { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';
import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
import { InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-service';
@@ -30,16 +21,19 @@ import {
import { setAllIteratorsStepInfosAsStopped } from 'src/modules/workflow/common/utils/set-all-iterators-step-infos-as-stopped.util';
import { type WorkflowVersionWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow-version.workspace-entity';
import { getStepRetryAttempt } from 'src/modules/workflow/workflow-executor/utils/get-step-retry-attempt.util';
+import { type WorkflowPendingAsk } from 'src/modules/workflow/workflow-executor/types/workflow-pending-ask.type';
import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';
import { type WorkflowTrigger } from 'src/modules/workflow/workflow-trigger/types/workflow-trigger.type';
import {
WorkflowRunException,
WorkflowRunExceptionCode,
} from 'src/modules/workflow/workflow-runner/exceptions/workflow-run.exception';
+import { canWorkflowRunHaveAsks } from 'src/modules/workflow/workflow-runner/utils/can-workflow-run-have-asks.util';
+import { getRunInitiatorWorkspaceMemberId } from 'src/modules/workflow/workflow-runner/utils/get-run-initiator-workspace-member-id.util';
-export type StepAwaitingAnswer =
- | { status: 'AWAITING_ANSWER'; stepId: string }
- | { status: 'NOT_YET_AWAITING' | 'NO_LONGER_AWAITING' };
+export type StepInputResolution =
+ | { status: 'RESOLVED'; stepId: string }
+ | { status: 'NOT_AWAITING' };
@Injectable()
export class WorkflowRunWorkspaceService {
@@ -51,10 +45,6 @@ export class WorkflowRunWorkspaceService {
private readonly metricsService: MetricsService,
private readonly inputAskWorkspaceService: InputAskWorkspaceService,
private readonly workflowRunRecordShareService: WorkflowRunRecordShareService,
- @InjectAgentHistoryRepository('agentChatThread')
- private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,
- @InjectAgentHistoryRepository('agentMessagePart')
- private readonly messagePartRepository: AgentHistoryRepository<AgentMessagePartEntity>,
) {}
async createCoreWorkflowRun({
@@ -216,25 +206,18 @@ export class WorkflowRunWorkspaceService {
await this.updateWorkflowRun({ workflowRunId, workspaceId, partialUpdate });
- await this.closeQuestionsOfEndedRun({
- stepInfos: workflowRunToUpdate.state?.stepInfos ?? {},
- workspaceId,
- });
-
// A run that ends can no longer consume an answer, so an Ask still
- // waiting on one stops being actionable here rather than outliving it.
- // The run has ended either way: a failure here only leaves a stale Ask,
- // and must not turn the run's outcome into a failure.
- try {
- await this.inputAskWorkspaceService.cancelPendingForWorkflowRun({
- workspaceId,
- workflowRunId,
- stepInfos: updatedStepInfos,
- });
- } catch (error) {
- this.logger.error(
- `Failed to close the Asks of workflow run ${workflowRunId} in workspace ${workspaceId}: ${error instanceof Error ? error.message : String(error)}`,
- );
+ // waiting on one stops being actionable rather than outliving it. This is
+ // housekeeping: the run is over either way, and a failure here only
+ // leaves a stale Ask behind.
+ if (canWorkflowRunHaveAsks(workflowRunToUpdate.state)) {
+ await this.inputAskWorkspaceService
+ .cancel({ workspaceId, match: { workflowRunId } })
+ .catch((error: unknown) => {
+ this.logger.error(
+ `Failed to cancel the Asks of workflow run ${workflowRunId} in workspace ${workspaceId}: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ });
}
const metricKey =
@@ -258,15 +241,20 @@ export class WorkflowRunWorkspaceService {
}
}
+ // A step that parks on a person opens its Ask in the same locked write, so
+ // an answer can never find the step waiting without it, and a run ending
+ // right after cannot miss it when canceling what is left pending.
@WithLock('workflowRunId')
async updateWorkflowRunStepInfo({
stepId,
stepInfo,
+ pendingAsks,
workflowRunId,
workspaceId,
}: {
stepId: string;
stepInfo: WorkflowRunStepInfo;
+ pendingAsks?: WorkflowPendingAsk[];
workflowRunId: string;
workspaceId: string;
}) {
@@ -275,6 +263,20 @@ export class WorkflowRunWorkspaceService {
workspaceId,
});
+ if (stepInfo.status === StepStatus.PENDING) {
+ for (const pendingAsk of pendingAsks ?? []) {
+ await this.inputAskWorkspaceService.open({
+ workspaceId,
+ inputAsk: {
+ ...pendingAsk,
+ workflowRunId,
+ stepId,
+ assigneeId: getRunInitiatorWorkspaceMemberId(workflowRunToUpdate),
+ },
+ });
+ }
+ }
+
const partialUpdate = {
state: {
...workflowRunToUpdate.state,
@@ -442,12 +444,14 @@ export class WorkflowRunWorkspaceService {
async updateStepInfoIfPending({
stepId,
stepInfo,
+ inputAskResponse,
expectedThreadId,
workflowRunId,
workspaceId,
}: {
stepId: string;
stepInfo: Partial<WorkflowRunStepInfo>;
+ inputAskResponse?: Record<string, unknown>;
expectedThreadId?: string;
workflowRunId: string;
workspaceId: string;
@@ -468,6 +472,19 @@ export class WorkflowRunWorkspaceService {
return false;
}
+ // Answering the Ask under the lock that accepts the submission is the
+ // claim: of two submissions only the one that answers it moves the step.
+ if (
+ isDefined(inputAskResponse) &&
+ !(await this.inputAskWorkspaceService.answer({
+ workspaceId,
+ key: { workflowRunId, stepId },
+ response: inputAskResponse,
+ }))
+ ) {
+ return false;
+ }
+
await this.updateWorkflowRun({
workflowRunId,
workspaceId,
@@ -485,22 +502,26 @@ export class WorkflowRunWorkspaceService {
return true;
}
- // Finds the step whose agent asked a question in this conversation and is
- // still waiting for its answer: a stop, a retry or another loop iteration
- // has moved the step on or replaced its conversation. A step still RUNNING
- // has asked but not yet been parked, which an answer only has to wait out.
- // Nothing is written: the step stays PENDING, which keeps its run alive,
- // until the resume job claims it.
+ // Answers the Ask an agent step is waiting on, once and only for that Ask:
+ // a stop, a retry or another loop iteration has moved the step on or
+ // replaced its conversation. The Ask is answered under the run lock, so a
+ // run ending in between cannot cancel an answer it accepts, and of two
+ // concurrent answers the second finds it answered. The step stays PENDING,
+ // which keeps its run alive, until the resume job claims it.
@WithLock('workflowRunId')
- async findStepAwaitingAnswer({
+ async resolveStepAwaitingToolCall({
threadId,
+ toolCallId,
+ response,
workflowRunId,
workspaceId,
}: {
threadId: string;
+ toolCallId: string;
+ response: Record<string, unknown>;
workflowRunId: string;
workspaceId: string;
- }): Promise<StepAwaitingAnswer> {
+ }): Promise<StepInputResolution> {
const workflowRun = await this.getWorkflowRunOrFail({
workflowRunId,
workspaceId,
@@ -518,20 +539,23 @@ export class WorkflowRunWorkspaceService {
workflowRun.status !== WorkflowRunStatus.RUNNING ||
!isDefined(stepId) ||
!isDefined(currentStepInfo) ||
- isDefined(currentStepInfo.error)
+ isDefined(currentStepInfo.error) ||
+ currentStepInfo.status !== StepStatus.PENDING
) {
- return { status: 'NO_LONGER_AWAITING' };
+ return { status: 'NOT_AWAITING' };
}
- if (currentStepInfo.status === StepStatus.RUNNING) {
- return { status: 'NOT_YET_AWAITING' };
- }
+ const hasAnswered = await this.inputAskWorkspaceService.answer({
+ workspaceId,
+ key: { threadId, toolCallId },
+ response,
+ });
- if (currentStepInfo.status !== StepStatus.PENDING) {
- return { status: 'NO_LONGER_AWAITING' };
+ if (!hasAnswered) {
+ return { status: 'NOT_AWAITING' };
}
- return { status: 'AWAITING_ANSWER', stepId };
+ return { status: 'RESOLVED', stepId };
}
@WithLock('workflowRunId')
@@ -721,91 +745,6 @@ export class WorkflowRunWorkspaceService {
};
}
- // An ended run resumes nothing, so a question still offered in one of its
- // conversations is closed rather than left to refuse every answer. Clearing
- // the marker is the same claim an answer makes, so the two never both win.
- // Closing is cosmetic and must not fail ending the run.
- private async closeQuestionsOfEndedRun({
- stepInfos,
- workspaceId,
- }: {
- stepInfos: Record<string, WorkflowRunStepInfo>;
- workspaceId: string;
- }): Promise<void> {
- const threadIds = Object.values(stepInfos)
- .map((stepInfo) => stepInfo.threadId)
- .filter(isDefined);
-
- if (threadIds.length === 0) {
- return;
- }
-
- try {
- const threadsAwaitingAnswer = await this.threadRepository.find(
- workspaceId,
- {
- where: { id: In(threadIds), pendingQuestionMessageId: Not(IsNull()) },
- },
- );
-
- for (const {
- id: threadId,
- pendingQuestionMessageId,
- } of threadsAwaitingAnswer) {
- if (!isDefined(pendingQuestionMessageId)) {
- continue;
- }
-
- const claim = await this.threadRepository.update(
- workspaceId,
- { id: threadId, pendingQuestionMessageId },
- { pendingQuestionMessageId: null },
- );
-
- if ((claim.affected ?? 0) === 0) {
- continue;
- }
-
- const questionParts = await this.messagePartRepository.find(
- workspaceId,
- {
- where: {
- messageId: pendingQuestionMessageId,
- toolName: ASK_QUESTIONS_TOOL_NAME,
- },
- },
- );
-
- for (const questionPart of questionParts) {
- const toolOutput = questionPart.toolOutput as {
- result?: AskQuestionsToolResult;
- } | null;
-
- if (toolOutput?.result?.status !== 'pending') {
- continue;
- }
-
- await this.messagePartRepository.update(
- workspaceId,
- { id: questionPart.id },
- {
- toolOutput: {
- ...toolOutput,
- result: { ...toolOutput.result, status: 'skipped' },
- },
- },
- );
- }
- }
- } catch (error) {
- this.logger.warn(
- `Failed to close the questions of an ended workflow run in workspace ${workspaceId}: ${
- error instanceof Error ? error.message : String(error)
- }`,
- );
- }
- }
-
private markRunningStepsAsFailed({
stepInfosToUpdate,
}: {
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-runner.module.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-runner.module.ts
index e4ae1139221..c4700ad36d0 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-runner.module.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-runner.module.ts
@@ -2,11 +2,11 @@ import { Module } from '@nestjs/common';
import { BillingModule } from 'src/engine/core-modules/billing/billing.module';
import { MetricsModule } from 'src/engine/core-modules/metrics/metrics.module';
-import { InputAskModule } from 'src/modules/input-ask/input-ask.module';
import { WorkflowCommonModule } from 'src/modules/workflow/common/workflow-common.module';
import { CodeStepBuildModule } from 'src/modules/workflow/workflow-builder/workflow-version-step/code-step/code-step-build.module';
import { WorkflowVersionStepModule } from 'src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step.module';
import { WorkflowExecutorModule } from 'src/modules/workflow/workflow-executor/workflow-executor.module';
+import { WorkflowAgentConversationModule } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/workflow-agent-conversation.module';
import { RunWorkflowJob } from 'src/modules/workflow/workflow-runner/jobs/run-workflow.job';
import { WorkflowRunQueueModule } from 'src/modules/workflow/workflow-runner/workflow-run-queue/workflow-run-queue.module';
import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.module';
@@ -27,7 +27,7 @@ import { WorkflowVersionCoreModule } from 'src/engine/core-modules/workflow/work
CodeStepBuildModule,
WorkflowCoreModule,
WorkflowVersionCoreModule,
- InputAskModule,
+ WorkflowAgentConversationModule,
],
providers: [
WorkflowRunnerWorkspaceService,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/__tests__/workflow-runner.workspace-service.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/__tests__/workflow-runner.workspace-service.spec.ts
index e89b96fc976..ba4e03a4eb1 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/__tests__/workflow-runner.workspace-service.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/__tests__/workflow-runner.workspace-service.spec.ts
@@ -1,7 +1,7 @@
import { type MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
import { type WorkflowVersionCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-version-core-sync.service';
-import { type InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-service';
import { type WorkflowVersionStepOperationsWorkspaceService } from 'src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service';
+import { type WorkflowAgentConversationWorkspaceService } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service';
import { RUN_WORKFLOW_JOB_NAME } from 'src/modules/workflow/workflow-runner/constants/run-workflow-job-name';
import { type CoreWorkflowRunnerService } from 'src/modules/workflow/workflow-runner/services/core-workflow-runner.service';
import { type WorkflowThrottlingWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run-queue/workspace-services/workflow-throttling.workspace-service';
@@ -11,42 +11,57 @@ import { WorkflowRunnerWorkspaceService } from 'src/modules/workflow/workflow-ru
const WORKSPACE_ID = 'workspace-id';
const WORKFLOW_RUN_ID = 'workflow-run-id';
const THREAD_ID = 'thread-id';
+const TOOL_PART = {
+ id: 'part-id',
+ messageId: 'question-message-id',
+ turnId: 'question-turn-id',
+};
describe('WorkflowRunnerWorkspaceService', () => {
- const workflowRunWorkspaceService = { findStepAwaitingAnswer: jest.fn() };
const messageQueueService = { add: jest.fn() };
+ const workflowAgentConversationWorkspaceService = {
+ recordAnswer: jest.fn().mockResolvedValue({ hasAwaitingToolCalls: false }),
+ };
const service = new WorkflowRunnerWorkspaceService(
- workflowRunWorkspaceService as unknown as WorkflowRunWorkspaceService,
+ {} as WorkflowRunWorkspaceService,
messageQueueService as unknown as MessageQueueService,
{} as WorkflowVersionStepOperationsWorkspaceService,
{} as WorkflowThrottlingWorkspaceService,
{} as CoreWorkflowRunnerService,
{} as WorkflowVersionCoreSyncService,
- {} as InputAskWorkspaceService,
+ workflowAgentConversationWorkspaceService as unknown as WorkflowAgentConversationWorkspaceService,
);
- const resumeAgentStepWithAnswer = () =>
- service.resumeAgentStepWithAnswer({
- threadId: THREAD_ID,
- workflowRunId: WORKFLOW_RUN_ID,
+ const resumeAnsweredAgentStep = () =>
+ service.resumeAnsweredAgentStep({
workspaceId: WORKSPACE_ID,
+ workflowRunId: WORKFLOW_RUN_ID,
+ stepId: 'agent-step-id',
+ threadId: THREAD_ID,
+ toolPart: TOOL_PART,
+ toolResult: { success: true },
+ answerText: 'Send it',
+ senderUserWorkspaceId: 'user-workspace-id',
});
beforeEach(() => {
jest.clearAllMocks();
});
- describe('resumeAgentStepWithAnswer', () => {
- it('schedules an explicit resume of the step awaiting the answer', async () => {
- workflowRunWorkspaceService.findStepAwaitingAnswer.mockResolvedValue({
- status: 'AWAITING_ANSWER',
- stepId: 'agent-step-id',
- });
+ describe('resumeAnsweredAgentStep', () => {
+ it('records the answer, then schedules an explicit resume of the step in its conversation', async () => {
+ await resumeAnsweredAgentStep();
- expect(await resumeAgentStepWithAnswer()).toEqual({
- status: 'AWAITING_ANSWER',
- stepId: 'agent-step-id',
+ expect(
+ workflowAgentConversationWorkspaceService.recordAnswer,
+ ).toHaveBeenCalledWith({
+ workspaceId: WORKSPACE_ID,
+ threadId: THREAD_ID,
+ toolPart: TOOL_PART,
+ toolResult: { success: true },
+ answerText: 'Send it',
+ senderUserWorkspaceId: 'user-workspace-id',
});
expect(messageQueueService.add).toHaveBeenCalledWith(
RUN_WORKFLOW_JOB_NAME,
@@ -57,32 +72,31 @@ describe('WorkflowRunnerWorkspaceService', () => {
},
expect.objectContaining({ id: WORKFLOW_RUN_ID }),
);
+ expect(
+ workflowAgentConversationWorkspaceService.recordAnswer.mock
+ .invocationCallOrder[0],
+ ).toBeLessThan(messageQueueService.add.mock.invocationCallOrder[0]);
});
- it.each(['NOT_YET_AWAITING', 'NO_LONGER_AWAITING'])(
- 'schedules nothing when the step is %s',
- async (status) => {
- workflowRunWorkspaceService.findStepAwaitingAnswer.mockResolvedValue({
- status,
- });
+ it('schedules nothing while another call of the step still waits on its answer', async () => {
+ workflowAgentConversationWorkspaceService.recordAnswer.mockResolvedValueOnce(
+ { hasAwaitingToolCalls: true },
+ );
- expect(await resumeAgentStepWithAnswer()).toEqual({ status });
- expect(messageQueueService.add).not.toHaveBeenCalled();
- },
- );
+ await resumeAnsweredAgentStep();
- it('lets a failure to schedule the resume reach the caller', async () => {
- workflowRunWorkspaceService.findStepAwaitingAnswer.mockResolvedValue({
- status: 'AWAITING_ANSWER',
- stepId: 'agent-step-id',
- });
- messageQueueService.add.mockRejectedValueOnce(
- new Error('Queue unavailable'),
+ expect(messageQueueService.add).not.toHaveBeenCalled();
+ });
+
+ it('schedules nothing when the answer cannot be recorded', async () => {
+ workflowAgentConversationWorkspaceService.recordAnswer.mockRejectedValueOnce(
+ new Error('History unavailable'),
);
- await expect(resumeAgentStepWithAnswer()).rejects.toThrow(
- 'Queue unavailable',
+ await expect(resumeAnsweredAgentStep()).rejects.toThrow(
+ 'History unavailable',
);
+ expect(messageQueueService.add).not.toHaveBeenCalled();
});
});
});
diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service.ts
index 57987ef6c66..dd1b0c74c28 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service.ts
@@ -1,4 +1,4 @@
-import { Injectable, Logger } from '@nestjs/common';
+import { Injectable } from '@nestjs/common';
import { msg } from '@lingui/core/macro';
import { type ActorMetadata } from 'twenty-shared/types';
@@ -8,7 +8,6 @@ import { StepStatus } from 'twenty-shared/workflow';
import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
-import { InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-service';
import {
WorkflowVersionStepException,
WorkflowVersionStepExceptionCode,
@@ -16,6 +15,10 @@ import {
import { WorkflowRunStatus } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';
import { workflowHasRunningSteps } from 'src/modules/workflow/common/utils/workflow-has-running-steps.util';
import { WorkflowVersionStepOperationsWorkspaceService } from 'src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service';
+import {
+ type AnsweredToolPart,
+ WorkflowAgentConversationWorkspaceService,
+} from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service';
import { isWorkflowFormAction } from 'src/modules/workflow/workflow-executor/workflow-actions/form/guards/is-workflow-form-action.guard';
import {
WorkflowRunException,
@@ -27,17 +30,12 @@ import { buildRetryStepInfos } from 'src/modules/workflow/workflow-runner/utils/
import { buildRunWorkflowJobOptions } from 'src/modules/workflow/workflow-runner/utils/build-run-workflow-job-options.util';
import { getRunnableStepIds } from 'src/modules/workflow/workflow-runner/utils/get-runnable-step-ids.util';
import { WorkflowThrottlingWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run-queue/workspace-services/workflow-throttling.workspace-service';
-import {
- type StepAwaitingAnswer,
- WorkflowRunWorkspaceService,
-} from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
+import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';
import { CoreWorkflowRunnerService } from 'src/modules/workflow/workflow-runner/services/core-workflow-runner.service';
import { WorkflowVersionCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-version-core-sync.service';
@Injectable()
export class WorkflowRunnerWorkspaceService {
- private readonly logger = new Logger(WorkflowRunnerWorkspaceService.name);
-
constructor(
private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,
@InjectMessageQueue(MessageQueue.workflowQueue)
@@ -46,7 +44,7 @@ export class WorkflowRunnerWorkspaceService {
private readonly workflowThrottlingWorkspaceService: WorkflowThrottlingWorkspaceService,
private readonly coreWorkflowRunnerService: CoreWorkflowRunnerService,
private readonly workflowVersionCoreSyncService: WorkflowVersionCoreSyncService,
- private readonly inputAskWorkspaceService: InputAskWorkspaceService,
+ private readonly workflowAgentConversationWorkspaceService: WorkflowAgentConversationWorkspaceService,
) {}
async run({
@@ -104,6 +102,8 @@ export class WorkflowRunnerWorkspaceService {
);
}
+ // Called with the answer to the form step's Ask, whose claim the step
+ // transition takes: false when the form no longer waits for it.
async submitFormStep({
workspaceId,
stepId,
@@ -113,8 +113,8 @@ export class WorkflowRunnerWorkspaceService {
workspaceId: string;
stepId: string;
workflowRunId: string;
- response: object;
- }) {
+ response: Record<string, unknown>;
+ }): Promise<boolean> {
const workflowRun =
await this.workflowRunWorkspaceService.getWorkflowRunOrFail({
workflowRunId,
@@ -158,36 +158,13 @@ export class WorkflowRunnerWorkspaceService {
status: StepStatus.SUCCESS,
result: enrichedResponse,
},
+ inputAskResponse: enrichedResponse,
workspaceId,
workflowRunId,
});
if (!hasCompletedStep) {
- throw new WorkflowVersionStepException(
- 'Form is no longer awaiting a submission',
- WorkflowVersionStepExceptionCode.INVALID_REQUEST,
- {
- userFriendlyMessage: msg`This form is no longer awaiting a submission`,
- },
- );
- }
-
- // Recorded before the run is resumed: the resumed run can reach its end,
- // and ending a run cancels whatever is still pending, so an Ask answered
- // afterwards would read as canceled on a form somebody did answer. The
- // submission is already accepted, so a failure here must not keep the run
- // from resuming; the run's end records the answer from the step instead.
- try {
- await this.inputAskWorkspaceService.answerForFormStep({
- workspaceId,
- workflowRunId,
- stepId,
- response: enrichedResponse,
- });
- } catch (error) {
- this.logger.warn(
- `Could not record the answer to form step ${stepId} of workflow run ${workflowRunId} in workspace ${workspaceId}: ${error instanceof Error ? error.message : String(error)}`,
- );
+ return false;
}
await this.resume({
@@ -195,39 +172,57 @@ export class WorkflowRunnerWorkspaceService {
workflowRunId,
lastExecutedStepId: stepId,
});
+
+ return true;
}
- // The answer is already recorded in the step's conversation. The step stays
- // PENDING, which keeps its run alive, until the resume job claims it.
- async resumeAgentStepWithAnswer({
- threadId,
- workflowRunId,
+ // The step stays PENDING until the resume job claims it in its
+ // conversation.
+ async resumeAnsweredAgentStep({
workspaceId,
+ workflowRunId,
+ stepId,
+ threadId,
+ toolPart,
+ toolResult,
+ answerText,
+ senderUserWorkspaceId,
}: {
- threadId: string;
- workflowRunId: string;
workspaceId: string;
- }): Promise<StepAwaitingAnswer> {
- const stepAwaitingAnswer =
- await this.workflowRunWorkspaceService.findStepAwaitingAnswer({
- threadId,
- workflowRunId,
+ workflowRunId: string;
+ stepId: string;
+ threadId: string;
+ toolPart: AnsweredToolPart;
+ toolResult: Record<string, unknown>;
+ answerText: string;
+ senderUserWorkspaceId: string;
+ }): Promise<void> {
+ const { hasAwaitingToolCalls } =
+ await this.workflowAgentConversationWorkspaceService.recordAnswer({
workspaceId,
+ threadId,
+ toolPart,
+ toolResult,
+ answerText,
+ senderUserWorkspaceId,
});
- if (stepAwaitingAnswer.status === 'AWAITING_ANSWER') {
- await this.messageQueueService.add<RunWorkflowJobData>(
- RunWorkflowJob.name,
- {
- workspaceId,
- workflowRunId,
- stepToResume: { stepId: stepAwaitingAnswer.stepId, threadId },
- },
- buildRunWorkflowJobOptions(workflowRunId),
- );
+ // The agent paused on several calls and continues once all are
+ // answered. Two answers that both see none left each queue a resume,
+ // and the resume's claim on the step lets only one of them run it.
+ if (hasAwaitingToolCalls) {
+ return;
}
- return stepAwaitingAnswer;
+ await this.messageQueueService.add<RunWorkflowJobData>(
+ RunWorkflowJob.name,
+ {
+ workspaceId,
+ workflowRunId,
+ stepToResume: { stepId, threadId },
+ },
+ buildRunWorkflowJobOptions(workflowRunId),
+ );
}
async stopWorkflowRun(workspaceId: string, workflowRunId: string) {
diff --git a/packages/twenty-server/test/integration/graphql/suites/ai-chat-answer-ask.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/ai-chat-answer-ask.integration-spec.ts
new file mode 100644
index 00000000000..d8500de3b2b
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/ai-chat-answer-ask.integration-spec.ts
@@ -0,0 +1,288 @@
+import { randomUUID } from 'node:crypto';
+
+import { parse } from 'graphql';
+import { answerAsk } from 'test/integration/graphql/suites/workflow/utils/answer-ask.util';
+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+
+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 { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';
+import { type AgentChatService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service';
+import { createAskQuestionsTool } from 'src/engine/metadata-modules/ai/ai-chat/tools/ask-questions.tool';
+import { type AiModelRegistryService } from 'src/engine/metadata-modules/ai/ai-models/services/ai-model-registry.service';
+import { type InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-service';
+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 workspaceId = SEED_APPLE_WORKSPACE_ID;
+const schema = getWorkspaceSchemaName(workspaceId);
+const workspaceMemberId = WORKSPACE_MEMBER_DATA_SEED_IDS.JANE;
+const userWorkspaceId = USER_WORKSPACE_DATA_SEED_IDS.JANE;
+
+const QUESTIONS = [
+ {
+ header: 'Plan',
+ question: 'Which plan should I quote?',
+ options: [{ label: 'Pro' }, { label: 'Team' }],
+ },
+];
+
+// The model is not called here: the turn that asked is written as the stream
+// job persists it, and the resumed stream is only checked for being queued.
+describe('Answering a chat tool call through its Ask', () => {
+ const threadId = randomUUID();
+ let chat: AgentChatService;
+ let inputAsks: InputAskWorkspaceService;
+ let enqueueStream: jest.SpyInstance;
+ const spies: jest.SpyInstance[] = [];
+
+ // One assistant message that calls ask_questions once per id, as a model
+ // asking several things in one step does.
+ const pauseOnQuestions = async (...toolCallIds: string[]) => {
+ const userMessage = await chat.addMessage({
+ workspaceId,
+ threadId,
+ userWorkspaceId,
+ uiMessage: {
+ role: AgentMessageRole.USER,
+ parts: [{ type: 'text', text: 'Draft a quote' }],
+ },
+ });
+
+ const assistantMessageId = randomUUID();
+ const pendingOutput = await createAskQuestionsTool({
+ isWorkspaceSetupThread: false,
+ }).execute({ questions: QUESTIONS });
+
+ await chat.upsertAssistantMessage({
+ id: assistantMessageId,
+ threadId,
+ turnId: userMessage.turnId,
+ workspaceId,
+ parts: toolCallIds.map((toolCallId) => ({
+ type: 'tool-ask_questions',
+ toolCallId,
+ state: 'output-available',
+ input: { questions: QUESTIONS },
+ output: pendingOutput,
+ })) as never,
+ });
+
+ for (const toolCallId of toolCallIds) {
+ await inputAsks.open({
+ workspaceId,
+ inputAsk: {
+ name: QUESTIONS[0].question,
+ form: { kind: 'questions', questions: QUESTIONS },
+ threadId,
+ toolCallId,
+ assigneeId: workspaceMemberId,
+ },
+ });
+ }
+
+ return { assistantMessageId };
+ };
+
+ const answerToolCallAsk = (toolCallId: string) =>
+ answerAsk({
+ ask: { threadId, toolCallId },
+ response: { answers: [{ questionIndex: 0, selectedOptionIndices: [1] }] },
+ });
+
+ const readAsk = async (toolCallId: string) =>
+ (
+ await global.testDataSource.query(
+ `SELECT status, response FROM "${schema}"."inputAsk" WHERE "threadId" = $1 AND "toolCallId" = $2`,
+ [threadId, toolCallId],
+ )
+ )[0];
+
+ const readToolCallStatus = async (toolCallId: string) =>
+ (
+ await global.testDataSource.query(
+ `SELECT "toolOutput" FROM "${schema}"."agentMessagePart" WHERE "toolCallId" = $1`,
+ [toolCallId],
+ )
+ )[0]?.toolOutput?.result?.status;
+
+ const stopStream = () =>
+ makeMetadataApiRequest({
+ query: parse(
+ 'mutation Stop($threadId: UUID!) { stopAgentChatStream(threadId: $threadId) }',
+ ),
+ variables: { threadId },
+ });
+
+ beforeAll(async () => {
+ chat = getAppProviderByClassName<AgentChatService>('AgentChatService');
+ inputAsks = getAppProviderByClassName<InputAskWorkspaceService>(
+ 'InputAskWorkspaceService',
+ );
+
+ 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);
+
+ await chat.createThread({
+ workspaceId,
+ workspaceMemberId,
+ id: threadId,
+ title: 'Tool call resolution',
+ });
+ });
+
+ afterAll(async () => {
+ spies.forEach((spy) => spy.mockRestore());
+ await chat.hardDeleteThread({ workspaceId, workspaceMemberId, threadId });
+ });
+
+ afterEach(async () => {
+ await stopStream();
+ });
+
+ it('answers the Ask once, records the answer and resumes the chat', async () => {
+ await pauseOnQuestions('call-answered');
+
+ expect(await readAsk('call-answered')).toEqual({
+ status: 'PENDING',
+ response: null,
+ });
+
+ const response = await answerToolCallAsk('call-answered');
+
+ expect(response.body.errors).toBeUndefined();
+ expect(response.body.data.answerAsk.streamId).toEqual(expect.any(String));
+ expect(await readAsk('call-answered')).toEqual({
+ status: 'ANSWERED',
+ response: {
+ answers: [{ questionIndex: 0, selectedOptionIndices: [1] }],
+ },
+ });
+ expect(await readToolCallStatus('call-answered')).toBe('answered');
+ expect(enqueueStream).toHaveBeenLastCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ threadId,
+ streamId: response.body.data.answerAsk.streamId,
+ userWorkspaceId,
+ }),
+ );
+
+ await stopStream();
+
+ const second = await answerToolCallAsk('call-answered');
+
+ expect(JSON.stringify(second.body.errors)).toContain('ASK_NOT_PENDING');
+ });
+
+ it('resumes the chat only once every question asked together is answered', async () => {
+ await pauseOnQuestions('call-first', 'call-last');
+ enqueueStream.mockClear();
+
+ const first = await answerToolCallAsk('call-first');
+
+ expect(first.body.errors).toBeUndefined();
+ expect(first.body.data.answerAsk.streamId).toBeNull();
+ expect(await readAsk('call-first')).toMatchObject({ status: 'ANSWERED' });
+ expect(await readToolCallStatus('call-first')).toBe('answered');
+ expect(await readAsk('call-last')).toMatchObject({ status: 'PENDING' });
+ expect(enqueueStream).not.toHaveBeenCalled();
+
+ const last = await answerToolCallAsk('call-last');
+
+ expect(last.body.errors).toBeUndefined();
+ expect(last.body.data.answerAsk.streamId).toEqual(expect.any(String));
+ expect(enqueueStream).toHaveBeenCalledTimes(1);
+ expect(enqueueStream).toHaveBeenLastCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ threadId,
+ streamId: last.body.data.answerAsk.streamId,
+ }),
+ );
+ });
+
+ it('still answers a question through the deprecated answerAgentChatQuestion', async () => {
+ const { assistantMessageId } = await pauseOnQuestions('call-legacy');
+ enqueueStream.mockClear();
+
+ const response = await makeMetadataApiRequest({
+ query: parse(
+ `mutation Answer($threadId: UUID!, $messageId: UUID!, $answers: [AgentChatQuestionAnswerInput!]!) {
+ answerAgentChatQuestion(threadId: $threadId, messageId: $messageId, answers: $answers) { messageId queued streamId }
+ }`,
+ ),
+ variables: {
+ threadId,
+ messageId: assistantMessageId,
+ answers: [{ questionIndex: 0, selectedOptionIndices: [1] }],
+ },
+ });
+
+ expect(response.body.errors).toBeUndefined();
+ expect(response.body.data.answerAgentChatQuestion).toMatchObject({
+ messageId: assistantMessageId,
+ queued: false,
+ streamId: expect.any(String),
+ });
+ expect(await readAsk('call-legacy')).toEqual({
+ status: 'ANSWERED',
+ response: {
+ answers: [{ questionIndex: 0, selectedOptionIndices: [1] }],
+ },
+ });
+ expect(enqueueStream).toHaveBeenCalledTimes(1);
+ });
+
+ it('cancels every pending Ask when a message is sent instead of the answers', async () => {
+ await pauseOnQuestions('call-skipped-first', 'call-skipped-last');
+
+ const response = await makeMetadataApiRequest({
+ query: parse(
+ `mutation Send($threadId: UUID!, $text: String!, $messageId: UUID!) {
+ sendChatMessage(threadId: $threadId, text: $text, messageId: $messageId) { queued streamId }
+ }`,
+ ),
+ variables: { threadId, text: 'Never mind', messageId: randomUUID() },
+ });
+
+ expect(response.body.errors).toBeUndefined();
+ expect(response.body.data.sendChatMessage.queued).toBe(false);
+
+ for (const toolCallId of ['call-skipped-first', 'call-skipped-last']) {
+ expect(await readAsk(toolCallId)).toEqual({
+ status: 'CANCELED',
+ response: null,
+ });
+ expect(await readToolCallStatus(toolCallId)).toBe('skipped');
+ }
+
+ const lateAnswer = await answerToolCallAsk('call-skipped-first');
+
+ expect(JSON.stringify(lateAnswer.body.errors)).toContain('ASK_NOT_PENDING');
+ });
+});
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts
index 58504d87161..4331f8fa480 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-execution.integration-spec.ts
@@ -1,9 +1,15 @@
import { CronTriggerDeduplicationService } from 'src/engine/core-modules/cron/services/cron-trigger-deduplication.service';
import { randomUUID } from 'node:crypto';
import { USER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-users.util';
+import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';
import request from 'supertest';
-import { FeatureFlagKey, FieldMetadataType } from 'twenty-shared/types';
+import { PermissionFlagType } from 'twenty-shared/constants';
+import {
+ FeatureFlagKey,
+ FieldMetadataType,
+ WorkflowVisibility,
+} from 'twenty-shared/types';
import { WorkspaceActivationStatus } from 'twenty-shared/workspace';
import { type UserEntity } from 'src/engine/core-modules/user/user.entity';
import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
@@ -24,6 +30,12 @@ import { type CacheStorageService } from 'src/engine/core-modules/cache-storage/
import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';
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 { createOneRole } from 'test/integration/metadata/suites/role/utils/create-one-role.util';
+import { deleteOneRole } from 'test/integration/metadata/suites/role/utils/delete-one-role.util';
+import { findOneRoleByLabel } from 'test/integration/metadata/suites/role/utils/find-one-role-by-label.util';
+import { updateWorkspaceMemberRole } from 'test/integration/metadata/suites/role/utils/update-workspace-member-role.util';
+import { upsertPermissionFlags } from 'test/integration/metadata/suites/role-permission-flag/utils/upsert-permission-flags.util';
+import { answerAsk } from 'test/integration/graphql/suites/workflow/utils/answer-ask.util';
import { workflowGraphqlRequest } from 'test/integration/graphql/suites/workflow/utils/workflow-graphql-request.util';
import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
import { type InputAskWorkspaceService } from 'src/modules/input-ask/workspace-services/input-ask.workspace-service';
@@ -40,6 +52,7 @@ import { type WorkflowActionFactory } from 'src/modules/workflow/workflow-execut
const workspaceId = SEED_APPLE_WORKSPACE_ID;
const schema = getWorkspaceSchemaName(workspaceId);
+
const settings = {
input: {},
outputSchema: {},
@@ -737,16 +750,10 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
await waitForStep(runId, form.id, 'PENDING');
await migratePendingRun(fixture, runId);
await clearDefinitions(fixture);
- const response = await workflowGraphqlRequest(
- 'mutation Submit($input: SubmitFormStepInput!) { submitFormStep(input: $input) }',
- {
- input: {
- workflowRunId: runId,
- stepId: form.id,
- response: { answer: 'From the stored form' },
- },
- },
- );
+ const response = await answerAsk({
+ ask: { workflowRunId: runId, stepId: form.id },
+ response: { answer: 'From the stored form' },
+ });
expect(response.body.errors).toBeUndefined();
const run = await waitForRun(runId, 'COMPLETED');
@@ -783,12 +790,9 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
stepId: string;
answer: string;
}) =>
- workflowGraphqlRequest(
- 'mutation Submit($input: SubmitFormStepInput!) { submitFormStep(input: $input) }',
- { input: { workflowRunId: runId, stepId, response: { answer } } },
- );
+ answerAsk({ ask: { workflowRunId: runId, stepId }, response: { answer } });
- it('refuses a second submission of the same form and keeps the first answer', async () => {
+ it('still answers a form through the deprecated submitFormStep', async () => {
const finalStep = emptyStep();
const form = formStep([finalStep.id]);
const fixture = await createFixture({
@@ -799,61 +803,38 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
await waitForStep(runId, form.id, 'PENDING');
- const first = await submitForm({
- runId,
- stepId: form.id,
- answer: 'Approved',
- });
-
- expect(first.body.errors).toBeUndefined();
- await waitForRun(runId, 'COMPLETED');
-
- const second = await submitForm({
- runId,
- stepId: form.id,
- answer: 'Approved again',
- });
-
- expect(second.body.errors?.[0]?.message).toContain(
- 'no longer awaiting a submission',
+ const response = await workflowGraphqlRequest(
+ 'mutation Submit($input: SubmitFormStepInput!) { submitFormStep(input: $input) }',
+ {
+ input: {
+ stepId: form.id,
+ workflowRunId: runId,
+ response: { answer: 'Approved' },
+ },
+ },
);
- expect((await getRun(runId)).state.stepInfos[form.id].result).toEqual({
- answer: 'Approved',
- });
- });
- it('refuses a submission once its run has been stopped', async () => {
- const finalStep = emptyStep();
- const form = formStep([finalStep.id]);
- const fixture = await createFixture({
- mirrorless: true,
- steps: [form, finalStep],
- });
- const runId = await runFixture(fixture);
-
- await waitForStep(runId, form.id, 'PENDING');
+ expect(response.body.errors).toBeUndefined();
+ expect(response.body.data.submitFormStep).toBe(true);
- await workflowGraphqlRequest(
- 'mutation Stop($id: UUID!) { stopWorkflowRun(workflowRunId: $id) { id status } }',
- { id: runId },
- );
- await waitForRun(runId, 'STOPPED');
+ const run = await waitForRun(runId, 'COMPLETED');
- const response = await submitForm({
- runId,
- stepId: form.id,
- answer: 'Too late',
+ expect(run.state.stepInfos[form.id].result).toMatchObject({
+ answer: 'Approved',
});
- expect(response.body.errors?.[0]?.message).toContain(
- 'no longer awaiting a submission',
+ const second = await workflowGraphqlRequest(
+ 'mutation Submit($input: SubmitFormStepInput!) { submitFormStep(input: $input) }',
+ {
+ input: {
+ stepId: form.id,
+ workflowRunId: runId,
+ response: { answer: 'Rejected' },
+ },
+ },
);
- const run = await getRun(runId);
-
- expect(run.status).toBe('STOPPED');
- expect(run.state.stepInfos[form.id].status).toBe('FAILED');
- expect(run.state.stepInfos[finalStep.id].status).toBe('NOT_STARTED');
+ expect(JSON.stringify(second.body.errors)).toContain('ASK_NOT_PENDING');
});
describe('the Ask a form step opens', () => {
@@ -888,7 +869,10 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
response: null,
answeredAt: null,
});
- expect(pendingInputAsk.form).toEqual({ fields: form.settings.input });
+ expect(pendingInputAsk.form).toEqual({
+ kind: 'formFields',
+ fields: form.settings.input,
+ });
const response = await submitForm({
runId,
@@ -910,43 +894,196 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
expect(answeredInputAsks[0].answeredAt).not.toBeNull();
});
- it('resumes the run when recording the answer fails and records it once the run ends', async () => {
- const finalStep = emptyStep();
- const form = approvalForm([finalStep.id]);
- const fixture = await createFixture({
- mirrorless: true,
- steps: [form, finalStep],
+ describe('handed on to another member', () => {
+ let originalMemberRoleId: string;
+ let workflowsRoleId: string;
+
+ // Handing an Ask on writes it through its run, and the seeded Member role
+ // cannot reach workflows at all.
+ beforeAll(async () => {
+ originalMemberRoleId = (await findOneRoleByLabel({ label: 'Member' }))
+ .id;
+
+ const { data: createdRole } = await createOneRole({
+ expectToFail: false,
+ input: {
+ label: `Workflows-enabled member ${randomUUID()}`,
+ description: 'Member plus the WORKFLOWS permission flag',
+ icon: 'IconSettingsAutomation',
+ canUpdateAllSettings: false,
+ canAccessAllTools: true,
+ canReadAllObjectRecords: true,
+ canUpdateAllObjectRecords: true,
+ canSoftDeleteAllObjectRecords: true,
+ canDestroyAllObjectRecords: true,
+ canBeAssignedToUsers: true,
+ canBeAssignedToAgents: false,
+ canBeAssignedToApiKeys: false,
+ },
+ });
+
+ workflowsRoleId = createdRole.createOneRole.id;
+
+ await upsertPermissionFlags({
+ expectToFail: false,
+ input: {
+ roleId: workflowsRoleId,
+ permissionFlagKeys: [PermissionFlagType.WORKFLOWS],
+ },
+ });
+ await updateWorkspaceMemberRole({
+ expectToFail: false,
+ input: {
+ roleId: workflowsRoleId,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ },
+ });
});
- const runId = await runFixture(fixture);
- await waitForStep(runId, form.id, 'PENDING');
+ afterAll(async () => {
+ await updateWorkspaceMemberRole({
+ expectToFail: false,
+ input: {
+ roleId: originalMemberRoleId,
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ },
+ });
+ await deleteOneRole({
+ expectToFail: false,
+ input: { idToDelete: workflowsRoleId },
+ });
+ });
- const answerForFormStep = jest
- .spyOn(
- getAppProviderByClassName<InputAskWorkspaceService>(
- 'InputAskWorkspaceService',
- ),
- 'answerForFormStep',
- )
- .mockRejectedValueOnce(new Error('Ask write failed'));
+ // Whoever started the run is who it waits on, until someone hands it on.
+ it('is assigned to the member who started the run and can be handed to another', async () => {
+ const finalStep = emptyStep();
+ const form = approvalForm([finalStep.id]);
+ // Updating the Ask needs to write it, which goes through its run's
+ // workspace workflow, so not a mirrorless fixture.
+ const fixture = await createFixture({ steps: [form, finalStep] });
+ const runId = await runFixture(fixture);
+
+ await waitForStep(runId, form.id, 'PENDING');
+
+ const [{ id: inputAskId, assigneeId }] =
+ await global.testDataSource.query(
+ `SELECT id, "assigneeId" FROM "${schema}"."inputAsk" WHERE "workflowRunId" = $1`,
+ [runId],
+ );
- const response = await submitForm({
- runId,
- stepId: form.id,
- answer: 'Approved',
+ expect(assigneeId).toBe(WORKSPACE_MEMBER_DATA_SEED_IDS.JANE);
+
+ const updateInputAsk = (data: Record<string, unknown>) =>
+ workflowGraphqlRequest(
+ 'mutation UpdateInputAsk($id: UUID!, $data: InputAskUpdateInput!) { updateInputAsk(id: $id, data: $data) { id } }',
+ { id: inputAskId, data },
+ );
+
+ const readInputAsk = async () =>
+ (
+ await global.testDataSource.query(
+ `SELECT "assigneeId", status FROM "${schema}"."inputAsk" WHERE id = $1`,
+ [inputAskId],
+ )
+ )[0];
+
+ expect(
+ (
+ await updateInputAsk({
+ assigneeId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ })
+ ).body.errors,
+ ).toBeUndefined();
+ expect((await readInputAsk()).assigneeId).toBe(
+ WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ );
+
+ // What the Ask gates only changes with the flow that owns the wait.
+ expect(
+ (await updateInputAsk({ status: 'ANSWERED' })).body.errors,
+ ).toBeDefined();
+ expect((await readInputAsk()).status).toBe('PENDING');
+
+ expect(
+ (await updateInputAsk({ assigneeId: null })).body.errors,
+ ).toBeUndefined();
+ expect((await readInputAsk()).assigneeId).toBeNull();
});
- answerForFormStep.mockRestore();
+ it('is handed on only by someone who can write its run', async () => {
+ const finalStep = emptyStep();
+ const form = approvalForm([finalStep.id]);
+ const fixture = await createFixture({ steps: [form, finalStep] });
+ const runId = await runFixture(fixture);
- expect(response.body.errors).toBeUndefined();
- await waitForRun(runId, 'COMPLETED');
+ await waitForStep(runId, form.id, 'PENDING');
- expect(await getInputAsks(runId)).toMatchObject([
- { status: 'ANSWERED', response: { answer: 'Approved' } },
- ]);
+ const [{ id: inputAskId }] = await global.testDataSource.query(
+ `SELECT id FROM "${schema}"."inputAsk" WHERE "workflowRunId" = $1`,
+ [runId],
+ );
+
+ const assignAs = (accessToken: string, workspaceMemberId: string) =>
+ request(`http://localhost:${APP_PORT}`)
+ .post('/graphql')
+ .set('Authorization', `Bearer ${accessToken}`)
+ .send({
+ query:
+ 'mutation UpdateInputAsk($id: UUID!, $data: InputAskUpdateInput!) { updateInputAsk(id: $id, data: $data) { id } }',
+ variables: {
+ id: inputAskId,
+ data: { assigneeId: workspaceMemberId },
+ },
+ });
+
+ const setVisibility = async (visibility: WorkflowVisibility) =>
+ expect(
+ (
+ await workflowGraphqlRequest(
+ 'mutation Visibility($input: UpdateCoreWorkflowVisibilityInput!) { updateCoreWorkflowVisibility(input: $input) { id } }',
+ {
+ input: { coreWorkflowId: fixture.coreWorkflowId, visibility },
+ },
+ )
+ ).body.errors,
+ ).toBeUndefined();
+
+ const readAssignee = async () =>
+ (
+ await global.testDataSource.query(
+ `SELECT "assigneeId" FROM "${schema}"."inputAsk" WHERE id = $1`,
+ [inputAskId],
+ )
+ )[0].assigneeId;
+
+ expect(
+ (
+ await assignAs(
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ )
+ ).body.errors,
+ ).toBeUndefined();
+ expect(await readAssignee()).toBe(WORKSPACE_MEMBER_DATA_SEED_IDS.JONY);
+
+ // A run Jony cannot read hides its Ask from him, assignee or not.
+ await setVisibility(WorkflowVisibility.PRIVATE);
+
+ expect(
+ (
+ await assignAs(
+ APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,
+ )
+ ).body.errors,
+ ).toBeDefined();
+ expect(await readAssignee()).toBe(WORKSPACE_MEMBER_DATA_SEED_IDS.JONY);
+
+ await setVisibility(WorkflowVisibility.WORKSPACE);
+ });
});
- it('completes the run even when its Asks cannot be closed', async () => {
+ it('refuses a submission whose Ask cannot record it, leaving the form waiting', async () => {
const finalStep = emptyStep();
const form = approvalForm([finalStep.id]);
const fixture = await createFixture({
@@ -957,32 +1094,43 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
await waitForStep(runId, form.id, 'PENDING');
- const cancelPending = jest
+ const answer = jest
.spyOn(
getAppProviderByClassName<InputAskWorkspaceService>(
'InputAskWorkspaceService',
),
- 'cancelPendingForWorkflowRun',
+ 'answer',
)
.mockRejectedValueOnce(new Error('Ask write failed'));
- const response = await submitForm({
+ const refused = await submitForm({
runId,
stepId: form.id,
answer: 'Approved',
});
- expect(response.body.errors).toBeUndefined();
+ answer.mockRestore();
- const run = await waitForRun(runId, 'COMPLETED');
+ expect(refused.body.errors).toBeDefined();
+ expect((await getRun(runId)).state.stepInfos[form.id].status).toBe(
+ 'PENDING',
+ );
+ expect(await getInputAsks(runId)).toMatchObject([
+ { status: 'PENDING', response: null },
+ ]);
- cancelPending.mockRestore();
+ expect(
+ (await submitForm({ runId, stepId: form.id, answer: 'Approved' })).body
+ .errors,
+ ).toBeUndefined();
+ await waitForRun(runId, 'COMPLETED');
- expect(run.status).toBe('COMPLETED');
- expect(run.state.stepInfos[finalStep.id].status).toBe('SUCCESS');
+ expect(await getInputAsks(runId)).toMatchObject([
+ { status: 'ANSWERED', response: { answer: 'Approved' } },
+ ]);
});
- it('keeps the first answer when a second submission is refused', async () => {
+ it('refuses a second submission and keeps the first answer', async () => {
const finalStep = emptyStep();
const form = approvalForm([finalStep.id]);
const fixture = await createFixture({
@@ -992,7 +1140,14 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
const runId = await runFixture(fixture);
await waitForStep(runId, form.id, 'PENDING');
- await submitForm({ runId, stepId: form.id, answer: 'Approved' });
+
+ const first = await submitForm({
+ runId,
+ stepId: form.id,
+ answer: 'Approved',
+ });
+
+ expect(first.body.errors).toBeUndefined();
await waitForRun(runId, 'COMPLETED');
const second = await submitForm({
@@ -1001,7 +1156,10 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
answer: 'Approved again',
});
- expect(second.body.errors).toBeDefined();
+ expect(JSON.stringify(second.body.errors)).toContain('ASK_NOT_PENDING');
+ expect((await getRun(runId)).state.stepInfos[form.id].result).toEqual({
+ answer: 'Approved',
+ });
expect(await getInputAsks(runId)).toMatchObject([
{ status: 'ANSWERED', response: { answer: 'Approved' } },
]);
@@ -1096,10 +1254,16 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
answer: 'Too late',
});
- expect(late.body.errors).toBeDefined();
+ expect(JSON.stringify(late.body.errors)).toContain('ASK_NOT_PENDING');
expect(await getInputAsks(runId)).toMatchObject([
{ status: 'CANCELED', response: null },
]);
+
+ const run = await getRun(runId);
+
+ expect(run.status).toBe('STOPPED');
+ expect(run.state.stepInfos[form.id].status).toBe('FAILED');
+ expect(run.state.stepInfos[finalStep.id].status).toBe('NOT_STARTED');
});
});
@@ -1126,9 +1290,7 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
answer: 'While stopping',
});
- expect(response.body.errors?.[0]?.message).toContain(
- 'no longer awaiting a submission',
- );
+ expect(JSON.stringify(response.body.errors)).toContain('ASK_NOT_PENDING');
expect((await getRun(runId)).state.stepInfos[form.id].status).toBe(
'PENDING',
);
@@ -1221,16 +1383,16 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
);
const getConversation = async (threadId: string) => {
- const [thread] = await global.testDataSource.query(
- `SELECT "pendingQuestionMessageId" FROM "${schema}"."agentChatThread" WHERE id = $1`,
- [threadId],
- );
const messages = await global.testDataSource.query(
`SELECT id, role FROM "${schema}"."agentMessage" WHERE "threadId" = $1 ORDER BY "processedAt", "createdAt"`,
[threadId],
);
+ const [questionPart] = await global.testDataSource.query(
+ `SELECT "toolOutput" FROM "${schema}"."agentMessagePart" WHERE "toolCallId" = 'ask-1' AND "messageId" = ANY($1::uuid[])`,
+ [messages.map(({ id }: { id: string }) => id)],
+ );
- return { thread, messages };
+ return { messages, questionPart };
};
const startAskingRun = async () => {
@@ -1242,37 +1404,23 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
const runId = await runFixture(fixture);
const run = await waitForStep(runId, agent.id, 'PENDING');
const threadId: string = run.state.stepInfos[agent.id].threadId;
- const { thread } = await getConversation(threadId);
- return {
- runId,
- agent,
- finalStep,
- threadId,
- questionMessageId: thread.pendingQuestionMessageId as string,
- };
+ return { runId, agent, finalStep, threadId };
};
const answer = ({
threadId,
- messageId,
+ toolCallId = 'ask-1',
}: {
threadId: string;
- messageId: string;
+ toolCallId?: string;
}) =>
- request(`http://localhost:${APP_PORT}`)
- .post('/metadata')
- .set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
- .send({
- query: `mutation Answer($threadId: UUID!, $messageId: UUID!, $answers: [AgentChatQuestionAnswerInput!]!) {
- answerAgentChatQuestion(threadId: $threadId, messageId: $messageId, answers: $answers) { messageId streamId }
- }`,
- variables: {
- threadId,
- messageId,
- answers: [{ questionIndex: 0, selectedOptionIndices: [0] }],
- },
- });
+ answerAsk({
+ ask: { threadId, toolCallId },
+ response: {
+ answers: [{ questionIndex: 0, selectedOptionIndices: [0] }],
+ },
+ });
it('records no conversation for an agent that answers without asking', async () => {
jest
@@ -1306,10 +1454,8 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
it('pauses the run on the question and resumes the same conversation with the answer', async () => {
const executeAgent = mockAgent();
- const { runId, agent, finalStep, threadId, questionMessageId } =
- await startAskingRun();
+ const { runId, agent, finalStep, threadId } = await startAskingRun();
- expect(questionMessageId).toBeDefined();
expect((await getRun(runId)).state.stepInfos[finalStep.id].status).toBe(
'NOT_STARTED',
);
@@ -1320,15 +1466,15 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
toolCallId: 'ask-1',
stepId: agent.id,
workflowRunId: runId,
- form: { questions: QUESTIONS },
+ form: { kind: 'questions', questions: QUESTIONS },
response: null,
},
]);
- const response = await answer({ threadId, messageId: questionMessageId });
+ const response = await answer({ threadId });
expect(response.body.errors).toBeUndefined();
- expect(response.body.data.answerAgentChatQuestion.streamId).toBeNull();
+ expect(response.body.data.answerAsk.streamId).toBeNull();
const run = await waitForRun(runId, 'COMPLETED');
@@ -1346,9 +1492,9 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
'Send it',
);
- const { thread, messages } = await getConversation(threadId);
+ const { messages, questionPart } = await getConversation(threadId);
- expect(thread.pendingQuestionMessageId).toBeNull();
+ expect(questionPart.toolOutput.result.status).toBe('answered');
expect(await getThreadInputAsks(threadId)).toMatchObject([
{
status: 'ANSWERED',
@@ -1367,24 +1513,101 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
it('refuses a second answer to the same question', async () => {
mockAgent();
- const { runId, threadId, questionMessageId } = await startAskingRun();
+ const { runId, threadId } = await startAskingRun();
- expect(
- (await answer({ threadId, messageId: questionMessageId })).body.errors,
- ).toBeUndefined();
+ expect((await answer({ threadId })).body.errors).toBeUndefined();
await waitForRun(runId, 'COMPLETED');
- const second = await answer({ threadId, messageId: questionMessageId });
+ const second = await answer({ threadId });
- expect(JSON.stringify(second.body.errors)).toContain(
- 'QUESTION_NOT_PENDING',
+ expect(JSON.stringify(second.body.errors)).toContain('ASK_NOT_PENDING');
+ expect(await getThreadInputAsks(threadId)).toMatchObject([
+ { status: 'ANSWERED' },
+ ]);
+ });
+
+ it('waits for every question asked at once and resumes once all are answered', async () => {
+ const askCall = (toolCallId: string) => [
+ {
+ type: 'tool-call',
+ toolCallId,
+ toolName: 'ask_questions',
+ input: { questions: QUESTIONS },
+ },
+ {
+ type: 'tool-result',
+ toolCallId,
+ toolName: 'ask_questions',
+ input: { questions: QUESTIONS },
+ output: {
+ success: true,
+ message: 'Questions presented to the user; awaiting their answer.',
+ result: { questions: QUESTIONS, status: 'pending' },
+ },
+ },
+ ];
+ const executeAgent = jest
+ .spyOn(
+ getAppProviderByClassName<AgentAsyncExecutorService>(
+ 'AgentAsyncExecutorService',
+ ),
+ 'executeAgent',
+ )
+ .mockResolvedValueOnce(
+ agentResult({
+ isPaused: true,
+ steps: [
+ { content: [...askCall('ask-1'), ...askCall('ask-2')] },
+ ] as AgentExecutionResult['steps'],
+ }),
+ )
+ .mockResolvedValueOnce(replyingResult);
+ const { runId, agent, threadId } = await startAskingRun();
+
+ expect(
+ (await getThreadInputAsks(threadId)).map(
+ ({ toolCallId, status }: { toolCallId: string; status: string }) => ({
+ toolCallId,
+ status,
+ }),
+ ),
+ ).toEqual(
+ expect.arrayContaining([
+ { toolCallId: 'ask-1', status: 'PENDING' },
+ { toolCallId: 'ask-2', status: 'PENDING' },
+ ]),
);
+
+ const first = await answer({ threadId, toolCallId: 'ask-1' });
+
+ expect(first.body.errors).toBeUndefined();
+
+ const waitingRun = await getRun(runId);
+
+ expect(waitingRun.status).toBe('RUNNING');
+ expect(waitingRun.state.stepInfos[agent.id].status).toBe('PENDING');
+
+ // Had the first answer resumed the step, the second would find it no
+ // longer waiting.
+ const second = await answer({ threadId, toolCallId: 'ask-2' });
+
+ expect(second.body.errors).toBeUndefined();
+
+ const run = await waitForRun(runId, 'COMPLETED');
+
+ expect(run.state.stepInfos[agent.id]).toMatchObject({
+ status: 'SUCCESS',
+ result: { response: 'Quote sent' },
+ });
+ expect(executeAgent).toHaveBeenCalledTimes(2);
+ expect(
+ JSON.stringify(executeAgent.mock.calls[1][0].priorModelMessages),
+ ).not.toContain('"pending"');
});
- it('closes the question when the run is stopped and refuses a later answer', async () => {
+ it('refuses an answer once the run is stopped, whose end canceled the Ask', async () => {
mockAgent();
- const { runId, agent, threadId, questionMessageId } =
- await startAskingRun();
+ const { runId, agent, threadId } = await startAskingRun();
await workflowGraphqlRequest(
'mutation Stop($id: UUID!) { stopWorkflowRun(workflowRunId: $id) { id status } }',
@@ -1392,26 +1615,13 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
);
await waitForRun(runId, 'STOPPED');
- expect(
- (await getConversation(threadId)).thread.pendingQuestionMessageId,
- ).toBeNull();
-
- const response = await answer({ threadId, messageId: questionMessageId });
+ const response = await answer({ threadId });
- expect(JSON.stringify(response.body.errors)).toContain(
- 'QUESTION_NOT_PENDING',
- );
+ expect(JSON.stringify(response.body.errors)).toContain('ASK_NOT_PENDING');
- const { thread, messages } = await getConversation(threadId);
- const [questionPart] = await global.testDataSource.query(
- `SELECT "toolOutput" FROM "${schema}"."agentMessagePart" WHERE "messageId" = $1 AND "toolName" = 'ask_questions'`,
- [questionMessageId],
- );
+ const { messages, questionPart } = await getConversation(threadId);
- // Nothing can resume a stopped run, so the question stops being offered
- // rather than coming back after every refused answer.
- expect(thread.pendingQuestionMessageId).toBeNull();
- expect(questionPart.toolOutput.result.status).toBe('skipped');
+ expect(questionPart.toolOutput.result.status).not.toBe('answered');
expect(messages).toHaveLength(2);
expect(await getThreadInputAsks(threadId)).toMatchObject([
{ status: 'CANCELED', response: null },
@@ -1435,7 +1645,6 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
await waitForStep(runId, parallelBranch.id, 'SUCCESS');
const threadId: string = pausedRun.state.stepInfos[agent.id].threadId;
- const { thread } = await getConversation(threadId);
const queue = global.app.get<MessageQueueService>(
getQueueToken(MessageQueue.workflowQueue),
);
@@ -1444,10 +1653,7 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
// still queued.
const enqueue = jest.spyOn(queue, 'add').mockResolvedValueOnce(undefined);
- const response = await answer({
- threadId,
- messageId: thread.pendingQuestionMessageId,
- });
+ const response = await answer({ threadId });
const [[resumeJobName, resumeJobData, resumeJobOptions]] =
enqueue.mock.calls;
@@ -1489,70 +1695,101 @@ describe('core workflow execution and queue compatibility (e2e)', () => {
expect(executeAgent).toHaveBeenCalledTimes(2);
});
- it('keeps the question open when the resume cannot be scheduled, so it can be answered again', async () => {
+ it('refuses the answer, leaving the question open, when its Ask cannot record it', async () => {
mockAgent();
- const { runId, agent, threadId, questionMessageId } =
- await startAskingRun();
+ const { runId, agent, threadId } = await startAskingRun();
- const enqueue = jest
+ const inputAskAnswer = jest
.spyOn(
- global.app.get<MessageQueueService>(
- getQueueToken(MessageQueue.workflowQueue),
+ getAppProviderByClassName<InputAskWorkspaceService>(
+ 'InputAskWorkspaceService',
),
- 'add',
+ 'answer',
)
- .mockRejectedValueOnce(new Error('Queue unavailable'));
+ .mockRejectedValueOnce(new Error('Ask write failed'));
- const failedAnswer = await answer({
- threadId,
- messageId: questionMessageId,
- });
+ const refused = await answer({ threadId });
- enqueue.mockRestore();
+ inputAskAnswer.mockRestore();
- expect(failedAnswer.body.errors).toBeDefined();
+ expect(refused.body.errors).toBeDefined();
expect((await getRun(runId)).state.stepInfos[agent.id]).toMatchObject({
status: 'PENDING',
threadId,
});
-
- const { thread, messages } = await getConversation(threadId);
-
- expect(thread.pendingQuestionMessageId).toBe(questionMessageId);
- expect(messages).toHaveLength(2);
+ expect((await getConversation(threadId)).messages).toHaveLength(2);
expect(await getThreadInputAsks(threadId)).toMatchObject([
{ status: 'PENDING', response: null },
]);
- expect(
- (await answer({ threadId, messageId: questionMessageId })).body.errors,
- ).toBeUndefined();
+ expect((await answer({ threadId })).body.errors).toBeUndefined();
await waitForRun(runId, 'COMPLETED');
+ });
+
+ it('keeps the answer and fails the run, so it can be retried, when the resume cannot be scheduled', async () => {
+ mockAgent();
+ const { runId, threadId } = await startAskingRun();
+
+ const enqueue = jest
+ .spyOn(
+ global.app.get<MessageQueueService>(
+ getQueueToken(MessageQueue.workflowQueue),
+ ),
+ 'add',
+ )
+ .mockRejectedValueOnce(new Error('Queue unavailable'));
+
+ const failedAnswer = await answer({ threadId });
+
+ enqueue.mockRestore();
+ expect(failedAnswer.body.errors).toBeDefined();
+ await waitForRun(runId, 'FAILED');
expect(await getThreadInputAsks(threadId)).toMatchObject([
{ status: 'ANSWERED' },
]);
+ expect(
+ JSON.stringify((await answer({ threadId })).body.errors),
+ ).toContain('ASK_NOT_PENDING');
});
- it('resumes the run when the Ask cannot record the answer', async () => {
+ it('keeps the Ask answered when the run is stopped while the answer is accepted', async () => {
mockAgent();
- const { runId, threadId, questionMessageId } = await startAskingRun();
+ const { runId, threadId } = await startAskingRun();
- const answerForToolCall = jest
- .spyOn(
- getAppProviderByClassName<InputAskWorkspaceService>(
- 'InputAskWorkspaceService',
- ),
- 'answerForToolCall',
- )
- .mockRejectedValueOnce(new Error('Ask write failed'));
+ const inputAskWorkspaceService =
+ getAppProviderByClassName<InputAskWorkspaceService>(
+ 'InputAskWorkspaceService',
+ );
+ const inputAskAnswer = inputAskWorkspaceService.answer.bind(
+ inputAskWorkspaceService,
+ );
+ let stop: Promise<void> | undefined;
+
+ const spy = jest
+ .spyOn(inputAskWorkspaceService, 'answer')
+ .mockImplementationOnce(async (args) => {
+ // The stop lands while the run lock accepting the answer is held,
+ // which is where a run ending used to cancel the Ask.
+ stop = workflowGraphqlRequest(
+ 'mutation Stop($id: UUID!) { stopWorkflowRun(workflowRunId: $id) { id status } }',
+ { id: runId },
+ ).then(() => undefined);
+ await new Promise((resolve) => setTimeout(resolve, 500));
+
+ return inputAskAnswer(args);
+ });
- const response = await answer({ threadId, messageId: questionMessageId });
+ const response = await answer({ threadId });
- answerForToolCall.mockRestore();
+ await stop;
+ spy.mockRestore();
expect(response.body.errors).toBeUndefined();
- await waitForRun(runId, 'COMPLETED');
+ await waitForRun(runId, 'STOPPED');
+ expect(await getThreadInputAsks(threadId)).toMatchObject([
+ { status: 'ANSWERED' },
+ ]);
});
});
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts
index 2ef66603884..f24eafcee78 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts
@@ -1,3 +1,4 @@
+import { StepStatus } from 'twenty-shared/workflow';
import { randomUUID } from 'node:crypto';
import request from 'supertest';
@@ -903,38 +904,26 @@ describe('core workflow visibility (e2e)', () => {
).not.toContain(threadId);
});
- it('refuses to rename it or add to it, even for the workflow creator', async () => {
- const renameResponse = await metadataRequestAs(
- APPLE_JANE_ADMIN_ACCESS_TOKEN,
- `
- mutation RenameRunConversation($threadId: UUID!) {
- renameChatThread(id: $threadId, title: "Renamed") {
- id
+ it('lets the workflow creator rename it like any conversation they can write', async () => {
+ const rename = (title: string) =>
+ metadataRequestAs(
+ APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ `
+ mutation RenameRunConversation($threadId: UUID!, $title: String!) {
+ renameChatThread(id: $threadId, title: $title) {
+ title
+ }
}
- }
- `,
- { threadId },
- );
+ `,
+ { threadId, title },
+ );
- expect(renameResponse.body.errors?.[0]?.extensions?.code).toBe(
- 'FORBIDDEN',
- );
+ const renameResponse = await rename('Renamed');
- const archiveResponse = await metadataRequestAs(
- APPLE_JANE_ADMIN_ACCESS_TOKEN,
- `
- mutation ArchiveRunConversation($threadId: UUID!) {
- archiveChatThread(id: $threadId) {
- id
- }
- }
- `,
- { threadId },
- );
+ expect(renameResponse.body.errors).toBeUndefined();
+ expect(renameResponse.body.data.renameChatThread.title).toBe('Renamed');
- expect(archiveResponse.body.errors?.[0]?.extensions?.code).toBe(
- 'FORBIDDEN',
- );
+ expect((await rename('Summarize the lead')).body.errors).toBeUndefined();
});
it('follows the workflow visibility for another member', async () => {
@@ -1095,8 +1084,20 @@ describe('core workflow visibility (e2e)', () => {
},
});
- expect(recordedConversation?.isAwaitingAnswer).toBe(true);
+ expect(recordedConversation?.pendingAsks).toHaveLength(1);
threadId = recordedConversation!.threadId;
+
+ // Parked the way the executor parks a step that asked, which is what
+ // opens its Ask.
+ await getAppProviderByClassName<WorkflowRunWorkspaceService>(
+ 'WorkflowRunWorkspaceService',
+ ).updateWorkflowRunStepInfo({
+ stepId: askStepId,
+ stepInfo: { status: StepStatus.PENDING },
+ pendingAsks: recordedConversation!.pendingAsks,
+ workflowRunId: askRunId,
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ });
});
afterAll(async () => {
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/parallel-branch-leaf-resume-workflow.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/parallel-branch-leaf-resume-workflow.integration-spec.ts
index c65789017e8..4bad87bd2f7 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/parallel-branch-leaf-resume-workflow.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/parallel-branch-leaf-resume-workflow.integration-spec.ts
@@ -324,26 +324,32 @@ describe('Parallel branch leaf resume workflow (e2e)', () => {
'NOT_STARTED',
);
+ const [{ id: formAskId }] = await global.testDataSource.query(
+ `SELECT id FROM "${getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID)}"."inputAsk" WHERE "workflowRunId" = $1 AND "stepId" = $2`,
+ [createdWorkflowRunId, formStepId],
+ );
+
const submitFormResponse = await client
.post('/graphql')
.set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
.send({
query: `
- mutation SubmitFormStep($input: SubmitFormStepInput!) {
- submitFormStep(input: $input)
+ mutation AnswerAsk($input: AnswerAskInput!) {
+ answerAsk(input: $input) {
+ streamId
+ }
}
`,
variables: {
input: {
- stepId: formStepId,
- workflowRunId: createdWorkflowRunId,
+ askId: formAskId,
response: { answer: 'Submitted from integration test' },
},
},
});
expect(submitFormResponse.body.errors).toBeUndefined();
- expect(submitFormResponse.body.data.submitFormStep).toBe(true);
+ expect(submitFormResponse.body.data.answerAsk.streamId).toBeNull();
await (
await global.workflowTestServices.runJob()
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/quick-lead-workflow.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/quick-lead-workflow.integration-spec.ts
index 3aeaec70f76..16bf5a2f7f6 100644
--- a/packages/twenty-server/test/integration/graphql/suites/workflow/quick-lead-workflow.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/quick-lead-workflow.integration-spec.ts
@@ -1,4 +1,5 @@
import request from 'supertest';
+import { answerAsk } from 'test/integration/graphql/suites/workflow/utils/answer-ask.util';
import {
destroyWorkflowRun,
getWorkflowRun,
@@ -269,26 +270,16 @@ describe('Quick Lead Workflow (e2e)', () => {
companyDomain: `https://test-${testId}.example.com`,
};
- const submitFormResponse = await client
- .post('/graphql')
- .set('Authorization', `Bearer ${APPLE_JANE_ADMIN_ACCESS_TOKEN}`)
- .send({
- query: `
- mutation SubmitFormStep($input: SubmitFormStepInput!) {
- submitFormStep(input: $input)
- }
- `,
- variables: {
- input: {
- stepId: FORM_STEP_ID,
- workflowRunId: testWorkflowRunId,
- response: testFormData,
- },
- },
- });
+ const submitFormResponse = await answerAsk({
+ ask: {
+ workflowRunId: testWorkflowRunId as string,
+ stepId: FORM_STEP_ID,
+ },
+ response: testFormData,
+ });
expect(submitFormResponse.body.errors).toBeUndefined();
- expect(submitFormResponse.body.data.submitFormStep).toBe(true);
+ expect(submitFormResponse.body.data.answerAsk.streamId).toBeNull();
workflowRun = await waitForWorkflowCompletion(
testWorkflowRunId as string,
diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/utils/answer-ask.util.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/utils/answer-ask.util.ts
new file mode 100644
index 00000000000..f4868d917d8
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/utils/answer-ask.util.ts
@@ -0,0 +1,40 @@
+import { workflowGraphqlRequest } from 'test/integration/graphql/suites/workflow/utils/workflow-graphql-request.util';
+
+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';
+
+type AskLocation =
+ | { workflowRunId: string; stepId: string }
+ | { threadId: string; toolCallId: string };
+
+const findAskId = async (ask: AskLocation): Promise<string | undefined> => {
+ const [condition, parameters] =
+ 'threadId' in ask
+ ? [
+ '"threadId" = $1 AND "toolCallId" = $2',
+ [ask.threadId, ask.toolCallId],
+ ]
+ : [
+ '"workflowRunId" = $1 AND "stepId" = $2 AND "toolCallId" IS NULL',
+ [ask.workflowRunId, ask.stepId],
+ ];
+
+ const [row] = await global.testDataSource.query(
+ `SELECT id FROM "${getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID)}"."inputAsk" WHERE ${condition}`,
+ parameters,
+ );
+
+ return row?.id;
+};
+
+export const answerAsk = async ({
+ ask,
+ response,
+}: {
+ ask: AskLocation;
+ response: Record<string, unknown>;
+}) =>
+ workflowGraphqlRequest(
+ 'mutation Answer($input: AnswerAskInput!) { answerAsk(input: $input) { streamId } }',
+ { input: { askId: await findAskId(ask), response } },
+ );
diff --git a/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790714482317-open-asks-for-pending-input.integration-spec.ts b/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790714482317-open-asks-for-pending-input.integration-spec.ts
new file mode 100644
index 00000000000..cb894ca13a9
--- /dev/null
+++ b/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790714482317-open-asks-for-pending-input.integration-spec.ts
@@ -0,0 +1,236 @@
+import { randomUUID } from 'node:crypto';
+
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+
+import { type OpenAsksForPendingInputCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790714482317-open-asks-for-pending-input.command';
+import { type UpgradeCommandRegistryService } from 'src/engine/core-modules/upgrade/services/upgrade-command-registry.service';
+import { AgentMessageRole } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';
+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 { 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 RUN_ON_WORKSPACE_ARGS = {
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ options: {},
+ index: 0,
+ total: 1,
+};
+
+const QUESTIONS = [
+ {
+ header: 'Quote',
+ question: 'Send the quote to the customer?',
+ options: [{ label: 'Send it' }, { label: 'Hold it' }],
+ },
+];
+
+describe('2-44 workspace command 1790714482317 - OpenAsksForPendingInputCommand (integration)', () => {
+ let command: OpenAsksForPendingInputCommand;
+ let workspaceOrmManager: WorkspaceOrmManager;
+
+ const threadIds: string[] = [];
+
+ const inWorkspace = <TResult>(work: () => Promise<TResult>) =>
+ workspaceOrmManager.executeInWorkspaceContext(
+ work,
+ buildSystemAuthContext(SEED_APPLE_WORKSPACE_ID),
+ );
+
+ const repository = (objectName: string) =>
+ workspaceOrmManager.getRepository(objectName, {
+ shouldBypassPermissionChecks: true,
+ });
+
+ const runCommand = (options: { dryRun?: boolean } = {}) =>
+ inWorkspace(() =>
+ command.runOnWorkspace({ ...RUN_ON_WORKSPACE_ARGS, options }),
+ );
+
+ const findThreadAsks = (threadId: string) =>
+ inWorkspace(() =>
+ repository('inputAsk').find({
+ where: { threadId },
+ select: {
+ name: true,
+ status: true,
+ toolCallId: true,
+ form: true,
+ assigneeId: true,
+ workflowRunId: true,
+ },
+ }),
+ );
+
+ // What a conversation paused on a question looked like before its Ask:
+ // the pending marker pointing at the assistant message that asked.
+ const insertPausedConversation = async ({
+ status,
+ }: {
+ status: 'pending' | 'answered';
+ }) => {
+ const threadId = randomUUID();
+ const turnId = randomUUID();
+ const questionMessageId = randomUUID();
+ const toolCallId = `call-${threadId}`;
+
+ threadIds.push(threadId);
+
+ await inWorkspace(async () => {
+ await repository('agentChatThread').insert({
+ id: threadId,
+ title: 'Quote',
+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.TIM,
+ });
+ await repository('agentTurn').insert({ id: turnId, threadId });
+ await repository('agentMessage').insert({
+ threadId,
+ turnId,
+ role: AgentMessageRole.USER,
+ senderWorkspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ processedAt: new Date().toISOString(),
+ });
+ await repository('agentMessage').insert({
+ id: questionMessageId,
+ threadId,
+ turnId,
+ role: AgentMessageRole.ASSISTANT,
+ processedAt: new Date().toISOString(),
+ });
+ await repository('agentMessagePart').insert({
+ messageId: questionMessageId,
+ orderIndex: 0,
+ type: 'tool-ask_questions',
+ toolName: 'ask_questions',
+ toolCallId,
+ toolInput: { questions: QUESTIONS },
+ toolOutput: {
+ success: true,
+ message: 'Questions presented to the user; awaiting their answer.',
+ result: { questions: QUESTIONS, status },
+ },
+ state: 'output-available',
+ });
+ await repository('agentChatThread').update(
+ { id: threadId },
+ { pendingQuestionMessageId: questionMessageId },
+ );
+ });
+
+ return { threadId, toolCallId };
+ };
+
+ beforeAll(() => {
+ command = getAppProviderByClassName<OpenAsksForPendingInputCommand>(
+ 'OpenAsksForPendingInputCommand',
+ );
+ workspaceOrmManager = getAppProviderByClassName<WorkspaceOrmManager>(
+ 'WorkspaceOrmManager',
+ );
+ });
+
+ afterAll(async () => {
+ await inWorkspace(async () => {
+ for (const threadId of threadIds) {
+ await repository('inputAsk').delete({ threadId });
+ await repository('agentChatThread').delete({ id: threadId });
+ }
+ });
+ });
+
+ it('is registered in the 2.44 bundle', () => {
+ const registry = getAppProviderByClassName<UpgradeCommandRegistryService>(
+ 'UpgradeCommandRegistryService',
+ );
+
+ expect(registry.getBundleForVersion('2.44.0').workspaceCommands).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ command, timestamp: 1790714482317 }),
+ ]),
+ );
+ });
+
+ it('opens nothing on a dry run', async () => {
+ const { threadId } = await insertPausedConversation({ status: 'pending' });
+
+ await runCommand({ dryRun: true });
+
+ expect(await findThreadAsks(threadId)).toEqual([]);
+ });
+
+ it('opens a pending Ask for a question still waiting, assigned to who sent the turn', async () => {
+ const { threadId, toolCallId } = await insertPausedConversation({
+ status: 'pending',
+ });
+
+ await runCommand();
+
+ expect(await findThreadAsks(threadId)).toEqual([
+ {
+ name: 'Send the quote to the customer?',
+ status: 'PENDING',
+ toolCallId,
+ form: { kind: 'questions', questions: QUESTIONS },
+ assigneeId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ workflowRunId: null,
+ },
+ ]);
+ });
+
+ it('opens nothing for a question the marker points at but that was answered', async () => {
+ const { threadId } = await insertPausedConversation({
+ status: 'answered',
+ });
+
+ await runCommand();
+
+ expect(await findThreadAsks(threadId)).toEqual([]);
+ });
+
+ it('reopens the Ask of a form still waiting, assigned to who started the run', async () => {
+ const formAskWhere = {
+ name: 'Approve discount',
+ status: 'PENDING',
+ assigneeId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ };
+ const seededFormAsk = await inWorkspace(() =>
+ repository('inputAsk').findOneOrFail({
+ where: formAskWhere,
+ select: { id: true, workflowRunId: true, stepId: true },
+ }),
+ );
+
+ await inWorkspace(() =>
+ repository('inputAsk').delete({ id: seededFormAsk.id }),
+ );
+
+ await runCommand();
+
+ expect(
+ await inWorkspace(() =>
+ repository('inputAsk').find({
+ where: {
+ workflowRunId: seededFormAsk.workflowRunId,
+ stepId: seededFormAsk.stepId,
+ },
+ select: { status: true, assigneeId: true, form: true },
+ }),
+ ),
+ ).toEqual([
+ {
+ status: 'PENDING',
+ assigneeId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,
+ form: expect.objectContaining({ kind: 'formFields' }),
+ },
+ ]);
+ });
+
+ it('is a no-op when run again', async () => {
+ const { threadId } = await insertPausedConversation({ status: 'pending' });
+
+ await runCommand();
+ await runCommand();
+
+ expect(await findThreadAsks(threadId)).toHaveLength(1);
+ });
+});
diff --git a/packages/twenty-shared/src/ai/constants/propose-email-tool-name.const.ts b/packages/twenty-shared/src/ai/constants/propose-email-tool-name.const.ts
new file mode 100644
index 00000000000..c278fbe4d57
--- /dev/null
+++ b/packages/twenty-shared/src/ai/constants/propose-email-tool-name.const.ts
@@ -0,0 +1 @@
+export const PROPOSE_EMAIL_TOOL_NAME = 'propose_email';
diff --git a/packages/twenty-shared/src/ai/index.ts b/packages/twenty-shared/src/ai/index.ts
index 9953ba80fdf..5e7204afba2 100644
--- a/packages/twenty-shared/src/ai/index.ts
+++ b/packages/twenty-shared/src/ai/index.ts
@@ -30,6 +30,7 @@ export { DATABASE_CRUD_OPERATIONS } from './constants/database-crud-operation.co
export { DEFAULT_AI_AGENT_MODEL_TIER } from './constants/default-ai-agent-model-tier.const';
export { DEFAULT_AI_CHAT_MODEL_TIER } from './constants/default-ai-chat-model-tier.const';
export { JEV_MODEL_ID } from './constants/jev-model-id.const';
+export { PROPOSE_EMAIL_TOOL_NAME } from './constants/propose-email-tool-name.const';
export { ToolCategory } from './constants/tool-category.const';
export type { AgentChatSubscriptionEvent } from './types/AgentChatSubscriptionEvent';
export type {
@@ -56,14 +57,22 @@ export type {
DataMessagePart,
} from './types/DataMessagePart';
export { isExtendedFileUIPart } from './types/DataMessagePart';
+export type { EmailApprovalDecision } from './types/EmailApprovalDecision';
export type {
AiChatUsageMetadata,
AiChatModelMetadata,
ExtendedUIMessage,
} from './types/ExtendedUIMessage';
export type { ExtendedUIMessagePart } from './types/ExtendedUIMessagePart';
+export type { InputAskForm } from './types/InputAskForm';
+export type { InputAskEmailApprovalResponse } from './types/InputAskResponse';
export type { ModelConfiguration } from './types/ModelConfiguration';
export type { NavigateAppToolOutput } from './types/NavigateAppToolOutput';
+export type { ProposedEmail } from './types/ProposedEmail';
+export type {
+ ProposeEmailToolStatus,
+ ProposeEmailToolResult,
+} from './types/ProposeEmailToolResult';
export type { ToolWidgetName, ToolRecordReference } from './types/ToolWidget';
export {
RECORDS_TOOL_WIDGET_NAME,
diff --git a/packages/twenty-shared/src/ai/types/AgentChatSubscriptionEvent.ts b/packages/twenty-shared/src/ai/types/AgentChatSubscriptionEvent.ts
index e4fb203d9af..d3e3abe7943 100644
--- a/packages/twenty-shared/src/ai/types/AgentChatSubscriptionEvent.ts
+++ b/packages/twenty-shared/src/ai/types/AgentChatSubscriptionEvent.ts
@@ -5,7 +5,7 @@ export type AgentChatSubscriptionEvent =
| { type: 'stream-chunk'; chunk: Record<string, unknown>; seq?: number }
| { type: 'message-persisted'; messageId: string }
| { type: 'queue-updated' }
- | { type: 'question-answered' }
+ | { type: 'tool-call-resolved'; toolCallId: string }
| { type: 'stream-error'; code: string; message: string }
| { type: 'credits-exhausted' }
| { type: 'keepalive' };
diff --git a/packages/twenty-shared/src/ai/types/EmailApprovalDecision.ts b/packages/twenty-shared/src/ai/types/EmailApprovalDecision.ts
new file mode 100644
index 00000000000..17b2b8e6a1e
--- /dev/null
+++ b/packages/twenty-shared/src/ai/types/EmailApprovalDecision.ts
@@ -0,0 +1 @@
+export type EmailApprovalDecision = 'send' | 'saveDraft' | 'discard';
diff --git a/packages/twenty-shared/src/ai/types/InputAskForm.ts b/packages/twenty-shared/src/ai/types/InputAskForm.ts
new file mode 100644
index 00000000000..db92c4dc1bf
--- /dev/null
+++ b/packages/twenty-shared/src/ai/types/InputAskForm.ts
@@ -0,0 +1,19 @@
+import type z from 'zod';
+
+import { type AskQuestionItem } from '@/ai/types/AskQuestionItem';
+import { type ProposedEmail } from '@/ai/types/ProposedEmail';
+import { type workflowFormActionSettingsSchema } from '@/workflow/schemas/form-action-settings-schema';
+
+// What an Ask shows the person it waits on. The kind decides how it renders
+// and which response answers it:
+// - questions: the answer to each question
+// - formFields: each field's value, keyed by its name
+// - emailApproval: InputAskEmailApprovalResponse
+export type InputAskForm =
+ | { kind: 'questions'; questions: AskQuestionItem[] }
+ | {
+ kind: 'formFields';
+ // A snapshot of the form step's fields.
+ fields: z.infer<typeof workflowFormActionSettingsSchema>['input'];
+ }
+ | { kind: 'emailApproval'; email: ProposedEmail };
diff --git a/packages/twenty-shared/src/ai/types/InputAskResponse.ts b/packages/twenty-shared/src/ai/types/InputAskResponse.ts
new file mode 100644
index 00000000000..ecc4e024d96
--- /dev/null
+++ b/packages/twenty-shared/src/ai/types/InputAskResponse.ts
@@ -0,0 +1,9 @@
+import { type EmailApprovalDecision } from '@/ai/types/EmailApprovalDecision';
+import { type ProposedEmail } from '@/ai/types/ProposedEmail';
+
+// The email is the one the person approved, edited or not; a discard needs
+// none.
+export type InputAskEmailApprovalResponse = {
+ decision: EmailApprovalDecision;
+ email?: ProposedEmail;
+};
diff --git a/packages/twenty-shared/src/ai/types/ProposeEmailToolResult.ts b/packages/twenty-shared/src/ai/types/ProposeEmailToolResult.ts
new file mode 100644
index 00000000000..1a43ff9a1b1
--- /dev/null
+++ b/packages/twenty-shared/src/ai/types/ProposeEmailToolResult.ts
@@ -0,0 +1,15 @@
+import { type ProposedEmail } from '@/ai/types/ProposedEmail';
+
+export type ProposeEmailToolStatus =
+ | 'pending'
+ | 'sent'
+ | 'drafted'
+ | 'discarded'
+ | 'failed'
+ | 'skipped';
+
+export type ProposeEmailToolResult = {
+ status: ProposeEmailToolStatus;
+ email: ProposedEmail;
+ error?: string;
+};
diff --git a/packages/twenty-shared/src/ai/types/ProposedEmail.ts b/packages/twenty-shared/src/ai/types/ProposedEmail.ts
new file mode 100644
index 00000000000..13691aaacec
--- /dev/null
+++ b/packages/twenty-shared/src/ai/types/ProposedEmail.ts
@@ -0,0 +1,10 @@
+import { type EmailRecipients } from '@/workflow/types/EmailRecipients';
+
+// An email as an agent proposes it and as a person edits it before sending:
+// recipients are comma-separated, the body is plain text.
+export type ProposedEmail = {
+ recipients: Required<EmailRecipients>;
+ subject: string;
+ body: string;
+ connectedAccountId?: string;
+};
diff --git a/packages/twenty-shared/src/types/CoreObjectNameSingular.ts b/packages/twenty-shared/src/types/CoreObjectNameSingular.ts
index 65e656c1ed1..595057a64a4 100644
--- a/packages/twenty-shared/src/types/CoreObjectNameSingular.ts
+++ b/packages/twenty-shared/src/types/CoreObjectNameSingular.ts
@@ -13,6 +13,7 @@ export enum CoreObjectNameSingular {
Comment = 'comment',
Company = 'company',
Dashboard = 'dashboard',
+ InputAsk = 'inputAsk',
TimelineActivity = 'timelineActivity',
Message = 'message',
MessageCampaign = 'messageCampaign',